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 static void print_verifier_state(struct bpf_verifier_env *env, 616 const struct bpf_func_state *state) 617 { 618 const struct bpf_reg_state *reg; 619 enum bpf_reg_type t; 620 int i; 621 622 if (state->frameno) 623 verbose(env, " frame%d:", state->frameno); 624 for (i = 0; i < MAX_BPF_REG; i++) { 625 reg = &state->regs[i]; 626 t = reg->type; 627 if (t == NOT_INIT) 628 continue; 629 verbose(env, " R%d", i); 630 print_liveness(env, reg->live); 631 verbose(env, "=%s", reg_type_str[t]); 632 if (t == SCALAR_VALUE && reg->precise) 633 verbose(env, "P"); 634 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 635 tnum_is_const(reg->var_off)) { 636 /* reg->off should be 0 for SCALAR_VALUE */ 637 verbose(env, "%lld", reg->var_off.value + reg->off); 638 } else { 639 if (t == PTR_TO_BTF_ID || 640 t == PTR_TO_BTF_ID_OR_NULL || 641 t == PTR_TO_PERCPU_BTF_ID) 642 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 643 verbose(env, "(id=%d", reg->id); 644 if (reg_type_may_be_refcounted_or_null(t)) 645 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 646 if (t != SCALAR_VALUE) 647 verbose(env, ",off=%d", reg->off); 648 if (type_is_pkt_pointer(t)) 649 verbose(env, ",r=%d", reg->range); 650 else if (t == CONST_PTR_TO_MAP || 651 t == PTR_TO_MAP_KEY || 652 t == PTR_TO_MAP_VALUE || 653 t == PTR_TO_MAP_VALUE_OR_NULL) 654 verbose(env, ",ks=%d,vs=%d", 655 reg->map_ptr->key_size, 656 reg->map_ptr->value_size); 657 if (tnum_is_const(reg->var_off)) { 658 /* Typically an immediate SCALAR_VALUE, but 659 * could be a pointer whose offset is too big 660 * for reg->off 661 */ 662 verbose(env, ",imm=%llx", reg->var_off.value); 663 } else { 664 if (reg->smin_value != reg->umin_value && 665 reg->smin_value != S64_MIN) 666 verbose(env, ",smin_value=%lld", 667 (long long)reg->smin_value); 668 if (reg->smax_value != reg->umax_value && 669 reg->smax_value != S64_MAX) 670 verbose(env, ",smax_value=%lld", 671 (long long)reg->smax_value); 672 if (reg->umin_value != 0) 673 verbose(env, ",umin_value=%llu", 674 (unsigned long long)reg->umin_value); 675 if (reg->umax_value != U64_MAX) 676 verbose(env, ",umax_value=%llu", 677 (unsigned long long)reg->umax_value); 678 if (!tnum_is_unknown(reg->var_off)) { 679 char tn_buf[48]; 680 681 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 682 verbose(env, ",var_off=%s", tn_buf); 683 } 684 if (reg->s32_min_value != reg->smin_value && 685 reg->s32_min_value != S32_MIN) 686 verbose(env, ",s32_min_value=%d", 687 (int)(reg->s32_min_value)); 688 if (reg->s32_max_value != reg->smax_value && 689 reg->s32_max_value != S32_MAX) 690 verbose(env, ",s32_max_value=%d", 691 (int)(reg->s32_max_value)); 692 if (reg->u32_min_value != reg->umin_value && 693 reg->u32_min_value != U32_MIN) 694 verbose(env, ",u32_min_value=%d", 695 (int)(reg->u32_min_value)); 696 if (reg->u32_max_value != reg->umax_value && 697 reg->u32_max_value != U32_MAX) 698 verbose(env, ",u32_max_value=%d", 699 (int)(reg->u32_max_value)); 700 } 701 verbose(env, ")"); 702 } 703 } 704 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 705 char types_buf[BPF_REG_SIZE + 1]; 706 bool valid = false; 707 int j; 708 709 for (j = 0; j < BPF_REG_SIZE; j++) { 710 if (state->stack[i].slot_type[j] != STACK_INVALID) 711 valid = true; 712 types_buf[j] = slot_type_char[ 713 state->stack[i].slot_type[j]]; 714 } 715 types_buf[BPF_REG_SIZE] = 0; 716 if (!valid) 717 continue; 718 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 719 print_liveness(env, state->stack[i].spilled_ptr.live); 720 if (state->stack[i].slot_type[0] == STACK_SPILL) { 721 reg = &state->stack[i].spilled_ptr; 722 t = reg->type; 723 verbose(env, "=%s", reg_type_str[t]); 724 if (t == SCALAR_VALUE && reg->precise) 725 verbose(env, "P"); 726 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 727 verbose(env, "%lld", reg->var_off.value + reg->off); 728 } else { 729 verbose(env, "=%s", types_buf); 730 } 731 } 732 if (state->acquired_refs && state->refs[0].id) { 733 verbose(env, " refs=%d", state->refs[0].id); 734 for (i = 1; i < state->acquired_refs; i++) 735 if (state->refs[i].id) 736 verbose(env, ",%d", state->refs[i].id); 737 } 738 if (state->in_callback_fn) 739 verbose(env, " cb"); 740 if (state->in_async_callback_fn) 741 verbose(env, " async_cb"); 742 verbose(env, "\n"); 743 } 744 745 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 746 * small to hold src. This is different from krealloc since we don't want to preserve 747 * the contents of dst. 748 * 749 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 750 * not be allocated. 751 */ 752 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 753 { 754 size_t bytes; 755 756 if (ZERO_OR_NULL_PTR(src)) 757 goto out; 758 759 if (unlikely(check_mul_overflow(n, size, &bytes))) 760 return NULL; 761 762 if (ksize(dst) < bytes) { 763 kfree(dst); 764 dst = kmalloc_track_caller(bytes, flags); 765 if (!dst) 766 return NULL; 767 } 768 769 memcpy(dst, src, bytes); 770 out: 771 return dst ? dst : ZERO_SIZE_PTR; 772 } 773 774 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 775 * small to hold new_n items. new items are zeroed out if the array grows. 776 * 777 * Contrary to krealloc_array, does not free arr if new_n is zero. 778 */ 779 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 780 { 781 if (!new_n || old_n == new_n) 782 goto out; 783 784 arr = krealloc_array(arr, new_n, size, GFP_KERNEL); 785 if (!arr) 786 return NULL; 787 788 if (new_n > old_n) 789 memset(arr + old_n * size, 0, (new_n - old_n) * size); 790 791 out: 792 return arr ? arr : ZERO_SIZE_PTR; 793 } 794 795 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 796 { 797 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 798 sizeof(struct bpf_reference_state), GFP_KERNEL); 799 if (!dst->refs) 800 return -ENOMEM; 801 802 dst->acquired_refs = src->acquired_refs; 803 return 0; 804 } 805 806 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 807 { 808 size_t n = src->allocated_stack / BPF_REG_SIZE; 809 810 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 811 GFP_KERNEL); 812 if (!dst->stack) 813 return -ENOMEM; 814 815 dst->allocated_stack = src->allocated_stack; 816 return 0; 817 } 818 819 static int resize_reference_state(struct bpf_func_state *state, size_t n) 820 { 821 state->refs = realloc_array(state->refs, state->acquired_refs, n, 822 sizeof(struct bpf_reference_state)); 823 if (!state->refs) 824 return -ENOMEM; 825 826 state->acquired_refs = n; 827 return 0; 828 } 829 830 static int grow_stack_state(struct bpf_func_state *state, int size) 831 { 832 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 833 834 if (old_n >= n) 835 return 0; 836 837 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 838 if (!state->stack) 839 return -ENOMEM; 840 841 state->allocated_stack = size; 842 return 0; 843 } 844 845 /* Acquire a pointer id from the env and update the state->refs to include 846 * this new pointer reference. 847 * On success, returns a valid pointer id to associate with the register 848 * On failure, returns a negative errno. 849 */ 850 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 851 { 852 struct bpf_func_state *state = cur_func(env); 853 int new_ofs = state->acquired_refs; 854 int id, err; 855 856 err = resize_reference_state(state, state->acquired_refs + 1); 857 if (err) 858 return err; 859 id = ++env->id_gen; 860 state->refs[new_ofs].id = id; 861 state->refs[new_ofs].insn_idx = insn_idx; 862 863 return id; 864 } 865 866 /* release function corresponding to acquire_reference_state(). Idempotent. */ 867 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 868 { 869 int i, last_idx; 870 871 last_idx = state->acquired_refs - 1; 872 for (i = 0; i < state->acquired_refs; i++) { 873 if (state->refs[i].id == ptr_id) { 874 if (last_idx && i != last_idx) 875 memcpy(&state->refs[i], &state->refs[last_idx], 876 sizeof(*state->refs)); 877 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 878 state->acquired_refs--; 879 return 0; 880 } 881 } 882 return -EINVAL; 883 } 884 885 static void free_func_state(struct bpf_func_state *state) 886 { 887 if (!state) 888 return; 889 kfree(state->refs); 890 kfree(state->stack); 891 kfree(state); 892 } 893 894 static void clear_jmp_history(struct bpf_verifier_state *state) 895 { 896 kfree(state->jmp_history); 897 state->jmp_history = NULL; 898 state->jmp_history_cnt = 0; 899 } 900 901 static void free_verifier_state(struct bpf_verifier_state *state, 902 bool free_self) 903 { 904 int i; 905 906 for (i = 0; i <= state->curframe; i++) { 907 free_func_state(state->frame[i]); 908 state->frame[i] = NULL; 909 } 910 clear_jmp_history(state); 911 if (free_self) 912 kfree(state); 913 } 914 915 /* copy verifier state from src to dst growing dst stack space 916 * when necessary to accommodate larger src stack 917 */ 918 static int copy_func_state(struct bpf_func_state *dst, 919 const struct bpf_func_state *src) 920 { 921 int err; 922 923 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 924 err = copy_reference_state(dst, src); 925 if (err) 926 return err; 927 return copy_stack_state(dst, src); 928 } 929 930 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 931 const struct bpf_verifier_state *src) 932 { 933 struct bpf_func_state *dst; 934 int i, err; 935 936 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 937 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 938 GFP_USER); 939 if (!dst_state->jmp_history) 940 return -ENOMEM; 941 dst_state->jmp_history_cnt = src->jmp_history_cnt; 942 943 /* if dst has more stack frames then src frame, free them */ 944 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 945 free_func_state(dst_state->frame[i]); 946 dst_state->frame[i] = NULL; 947 } 948 dst_state->speculative = src->speculative; 949 dst_state->curframe = src->curframe; 950 dst_state->active_spin_lock = src->active_spin_lock; 951 dst_state->branches = src->branches; 952 dst_state->parent = src->parent; 953 dst_state->first_insn_idx = src->first_insn_idx; 954 dst_state->last_insn_idx = src->last_insn_idx; 955 for (i = 0; i <= src->curframe; i++) { 956 dst = dst_state->frame[i]; 957 if (!dst) { 958 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 959 if (!dst) 960 return -ENOMEM; 961 dst_state->frame[i] = dst; 962 } 963 err = copy_func_state(dst, src->frame[i]); 964 if (err) 965 return err; 966 } 967 return 0; 968 } 969 970 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 971 { 972 while (st) { 973 u32 br = --st->branches; 974 975 /* WARN_ON(br > 1) technically makes sense here, 976 * but see comment in push_stack(), hence: 977 */ 978 WARN_ONCE((int)br < 0, 979 "BUG update_branch_counts:branches_to_explore=%d\n", 980 br); 981 if (br) 982 break; 983 st = st->parent; 984 } 985 } 986 987 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 988 int *insn_idx, bool pop_log) 989 { 990 struct bpf_verifier_state *cur = env->cur_state; 991 struct bpf_verifier_stack_elem *elem, *head = env->head; 992 int err; 993 994 if (env->head == NULL) 995 return -ENOENT; 996 997 if (cur) { 998 err = copy_verifier_state(cur, &head->st); 999 if (err) 1000 return err; 1001 } 1002 if (pop_log) 1003 bpf_vlog_reset(&env->log, head->log_pos); 1004 if (insn_idx) 1005 *insn_idx = head->insn_idx; 1006 if (prev_insn_idx) 1007 *prev_insn_idx = head->prev_insn_idx; 1008 elem = head->next; 1009 free_verifier_state(&head->st, false); 1010 kfree(head); 1011 env->head = elem; 1012 env->stack_size--; 1013 return 0; 1014 } 1015 1016 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1017 int insn_idx, int prev_insn_idx, 1018 bool speculative) 1019 { 1020 struct bpf_verifier_state *cur = env->cur_state; 1021 struct bpf_verifier_stack_elem *elem; 1022 int err; 1023 1024 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1025 if (!elem) 1026 goto err; 1027 1028 elem->insn_idx = insn_idx; 1029 elem->prev_insn_idx = prev_insn_idx; 1030 elem->next = env->head; 1031 elem->log_pos = env->log.len_used; 1032 env->head = elem; 1033 env->stack_size++; 1034 err = copy_verifier_state(&elem->st, cur); 1035 if (err) 1036 goto err; 1037 elem->st.speculative |= speculative; 1038 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1039 verbose(env, "The sequence of %d jumps is too complex.\n", 1040 env->stack_size); 1041 goto err; 1042 } 1043 if (elem->st.parent) { 1044 ++elem->st.parent->branches; 1045 /* WARN_ON(branches > 2) technically makes sense here, 1046 * but 1047 * 1. speculative states will bump 'branches' for non-branch 1048 * instructions 1049 * 2. is_state_visited() heuristics may decide not to create 1050 * a new state for a sequence of branches and all such current 1051 * and cloned states will be pointing to a single parent state 1052 * which might have large 'branches' count. 1053 */ 1054 } 1055 return &elem->st; 1056 err: 1057 free_verifier_state(env->cur_state, true); 1058 env->cur_state = NULL; 1059 /* pop all elements and return */ 1060 while (!pop_stack(env, NULL, NULL, false)); 1061 return NULL; 1062 } 1063 1064 #define CALLER_SAVED_REGS 6 1065 static const int caller_saved[CALLER_SAVED_REGS] = { 1066 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1067 }; 1068 1069 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1070 struct bpf_reg_state *reg); 1071 1072 /* This helper doesn't clear reg->id */ 1073 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1074 { 1075 reg->var_off = tnum_const(imm); 1076 reg->smin_value = (s64)imm; 1077 reg->smax_value = (s64)imm; 1078 reg->umin_value = imm; 1079 reg->umax_value = imm; 1080 1081 reg->s32_min_value = (s32)imm; 1082 reg->s32_max_value = (s32)imm; 1083 reg->u32_min_value = (u32)imm; 1084 reg->u32_max_value = (u32)imm; 1085 } 1086 1087 /* Mark the unknown part of a register (variable offset or scalar value) as 1088 * known to have the value @imm. 1089 */ 1090 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1091 { 1092 /* Clear id, off, and union(map_ptr, range) */ 1093 memset(((u8 *)reg) + sizeof(reg->type), 0, 1094 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1095 ___mark_reg_known(reg, imm); 1096 } 1097 1098 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1099 { 1100 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1101 reg->s32_min_value = (s32)imm; 1102 reg->s32_max_value = (s32)imm; 1103 reg->u32_min_value = (u32)imm; 1104 reg->u32_max_value = (u32)imm; 1105 } 1106 1107 /* Mark the 'variable offset' part of a register as zero. This should be 1108 * used only on registers holding a pointer type. 1109 */ 1110 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1111 { 1112 __mark_reg_known(reg, 0); 1113 } 1114 1115 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1116 { 1117 __mark_reg_known(reg, 0); 1118 reg->type = SCALAR_VALUE; 1119 } 1120 1121 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1122 struct bpf_reg_state *regs, u32 regno) 1123 { 1124 if (WARN_ON(regno >= MAX_BPF_REG)) { 1125 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1126 /* Something bad happened, let's kill all regs */ 1127 for (regno = 0; regno < MAX_BPF_REG; regno++) 1128 __mark_reg_not_init(env, regs + regno); 1129 return; 1130 } 1131 __mark_reg_known_zero(regs + regno); 1132 } 1133 1134 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1135 { 1136 switch (reg->type) { 1137 case PTR_TO_MAP_VALUE_OR_NULL: { 1138 const struct bpf_map *map = reg->map_ptr; 1139 1140 if (map->inner_map_meta) { 1141 reg->type = CONST_PTR_TO_MAP; 1142 reg->map_ptr = map->inner_map_meta; 1143 /* transfer reg's id which is unique for every map_lookup_elem 1144 * as UID of the inner map. 1145 */ 1146 reg->map_uid = reg->id; 1147 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1148 reg->type = PTR_TO_XDP_SOCK; 1149 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1150 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1151 reg->type = PTR_TO_SOCKET; 1152 } else { 1153 reg->type = PTR_TO_MAP_VALUE; 1154 } 1155 break; 1156 } 1157 case PTR_TO_SOCKET_OR_NULL: 1158 reg->type = PTR_TO_SOCKET; 1159 break; 1160 case PTR_TO_SOCK_COMMON_OR_NULL: 1161 reg->type = PTR_TO_SOCK_COMMON; 1162 break; 1163 case PTR_TO_TCP_SOCK_OR_NULL: 1164 reg->type = PTR_TO_TCP_SOCK; 1165 break; 1166 case PTR_TO_BTF_ID_OR_NULL: 1167 reg->type = PTR_TO_BTF_ID; 1168 break; 1169 case PTR_TO_MEM_OR_NULL: 1170 reg->type = PTR_TO_MEM; 1171 break; 1172 case PTR_TO_RDONLY_BUF_OR_NULL: 1173 reg->type = PTR_TO_RDONLY_BUF; 1174 break; 1175 case PTR_TO_RDWR_BUF_OR_NULL: 1176 reg->type = PTR_TO_RDWR_BUF; 1177 break; 1178 default: 1179 WARN_ONCE(1, "unknown nullable register type"); 1180 } 1181 } 1182 1183 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1184 { 1185 return type_is_pkt_pointer(reg->type); 1186 } 1187 1188 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1189 { 1190 return reg_is_pkt_pointer(reg) || 1191 reg->type == PTR_TO_PACKET_END; 1192 } 1193 1194 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1195 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1196 enum bpf_reg_type which) 1197 { 1198 /* The register can already have a range from prior markings. 1199 * This is fine as long as it hasn't been advanced from its 1200 * origin. 1201 */ 1202 return reg->type == which && 1203 reg->id == 0 && 1204 reg->off == 0 && 1205 tnum_equals_const(reg->var_off, 0); 1206 } 1207 1208 /* Reset the min/max bounds of a register */ 1209 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1210 { 1211 reg->smin_value = S64_MIN; 1212 reg->smax_value = S64_MAX; 1213 reg->umin_value = 0; 1214 reg->umax_value = U64_MAX; 1215 1216 reg->s32_min_value = S32_MIN; 1217 reg->s32_max_value = S32_MAX; 1218 reg->u32_min_value = 0; 1219 reg->u32_max_value = U32_MAX; 1220 } 1221 1222 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1223 { 1224 reg->smin_value = S64_MIN; 1225 reg->smax_value = S64_MAX; 1226 reg->umin_value = 0; 1227 reg->umax_value = U64_MAX; 1228 } 1229 1230 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1231 { 1232 reg->s32_min_value = S32_MIN; 1233 reg->s32_max_value = S32_MAX; 1234 reg->u32_min_value = 0; 1235 reg->u32_max_value = U32_MAX; 1236 } 1237 1238 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1239 { 1240 struct tnum var32_off = tnum_subreg(reg->var_off); 1241 1242 /* min signed is max(sign bit) | min(other bits) */ 1243 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1244 var32_off.value | (var32_off.mask & S32_MIN)); 1245 /* max signed is min(sign bit) | max(other bits) */ 1246 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1247 var32_off.value | (var32_off.mask & S32_MAX)); 1248 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1249 reg->u32_max_value = min(reg->u32_max_value, 1250 (u32)(var32_off.value | var32_off.mask)); 1251 } 1252 1253 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1254 { 1255 /* min signed is max(sign bit) | min(other bits) */ 1256 reg->smin_value = max_t(s64, reg->smin_value, 1257 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1258 /* max signed is min(sign bit) | max(other bits) */ 1259 reg->smax_value = min_t(s64, reg->smax_value, 1260 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1261 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1262 reg->umax_value = min(reg->umax_value, 1263 reg->var_off.value | reg->var_off.mask); 1264 } 1265 1266 static void __update_reg_bounds(struct bpf_reg_state *reg) 1267 { 1268 __update_reg32_bounds(reg); 1269 __update_reg64_bounds(reg); 1270 } 1271 1272 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1273 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1274 { 1275 /* Learn sign from signed bounds. 1276 * If we cannot cross the sign boundary, then signed and unsigned bounds 1277 * are the same, so combine. This works even in the negative case, e.g. 1278 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1279 */ 1280 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1281 reg->s32_min_value = reg->u32_min_value = 1282 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1283 reg->s32_max_value = reg->u32_max_value = 1284 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1285 return; 1286 } 1287 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1288 * boundary, so we must be careful. 1289 */ 1290 if ((s32)reg->u32_max_value >= 0) { 1291 /* Positive. We can't learn anything from the smin, but smax 1292 * is positive, hence safe. 1293 */ 1294 reg->s32_min_value = reg->u32_min_value; 1295 reg->s32_max_value = reg->u32_max_value = 1296 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1297 } else if ((s32)reg->u32_min_value < 0) { 1298 /* Negative. We can't learn anything from the smax, but smin 1299 * is negative, hence safe. 1300 */ 1301 reg->s32_min_value = reg->u32_min_value = 1302 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1303 reg->s32_max_value = reg->u32_max_value; 1304 } 1305 } 1306 1307 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1308 { 1309 /* Learn sign from signed bounds. 1310 * If we cannot cross the sign boundary, then signed and unsigned bounds 1311 * are the same, so combine. This works even in the negative case, e.g. 1312 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1313 */ 1314 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1315 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1316 reg->umin_value); 1317 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1318 reg->umax_value); 1319 return; 1320 } 1321 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1322 * boundary, so we must be careful. 1323 */ 1324 if ((s64)reg->umax_value >= 0) { 1325 /* Positive. We can't learn anything from the smin, but smax 1326 * is positive, hence safe. 1327 */ 1328 reg->smin_value = reg->umin_value; 1329 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1330 reg->umax_value); 1331 } else if ((s64)reg->umin_value < 0) { 1332 /* Negative. We can't learn anything from the smax, but smin 1333 * is negative, hence safe. 1334 */ 1335 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1336 reg->umin_value); 1337 reg->smax_value = reg->umax_value; 1338 } 1339 } 1340 1341 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1342 { 1343 __reg32_deduce_bounds(reg); 1344 __reg64_deduce_bounds(reg); 1345 } 1346 1347 /* Attempts to improve var_off based on unsigned min/max information */ 1348 static void __reg_bound_offset(struct bpf_reg_state *reg) 1349 { 1350 struct tnum var64_off = tnum_intersect(reg->var_off, 1351 tnum_range(reg->umin_value, 1352 reg->umax_value)); 1353 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1354 tnum_range(reg->u32_min_value, 1355 reg->u32_max_value)); 1356 1357 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1358 } 1359 1360 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1361 { 1362 reg->umin_value = reg->u32_min_value; 1363 reg->umax_value = reg->u32_max_value; 1364 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1365 * but must be positive otherwise set to worse case bounds 1366 * and refine later from tnum. 1367 */ 1368 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0) 1369 reg->smax_value = reg->s32_max_value; 1370 else 1371 reg->smax_value = U32_MAX; 1372 if (reg->s32_min_value >= 0) 1373 reg->smin_value = reg->s32_min_value; 1374 else 1375 reg->smin_value = 0; 1376 } 1377 1378 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1379 { 1380 /* special case when 64-bit register has upper 32-bit register 1381 * zeroed. Typically happens after zext or <<32, >>32 sequence 1382 * allowing us to use 32-bit bounds directly, 1383 */ 1384 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1385 __reg_assign_32_into_64(reg); 1386 } else { 1387 /* Otherwise the best we can do is push lower 32bit known and 1388 * unknown bits into register (var_off set from jmp logic) 1389 * then learn as much as possible from the 64-bit tnum 1390 * known and unknown bits. The previous smin/smax bounds are 1391 * invalid here because of jmp32 compare so mark them unknown 1392 * so they do not impact tnum bounds calculation. 1393 */ 1394 __mark_reg64_unbounded(reg); 1395 __update_reg_bounds(reg); 1396 } 1397 1398 /* Intersecting with the old var_off might have improved our bounds 1399 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1400 * then new var_off is (0; 0x7f...fc) which improves our umax. 1401 */ 1402 __reg_deduce_bounds(reg); 1403 __reg_bound_offset(reg); 1404 __update_reg_bounds(reg); 1405 } 1406 1407 static bool __reg64_bound_s32(s64 a) 1408 { 1409 return a > S32_MIN && a < S32_MAX; 1410 } 1411 1412 static bool __reg64_bound_u32(u64 a) 1413 { 1414 return a > U32_MIN && a < U32_MAX; 1415 } 1416 1417 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1418 { 1419 __mark_reg32_unbounded(reg); 1420 1421 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1422 reg->s32_min_value = (s32)reg->smin_value; 1423 reg->s32_max_value = (s32)reg->smax_value; 1424 } 1425 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1426 reg->u32_min_value = (u32)reg->umin_value; 1427 reg->u32_max_value = (u32)reg->umax_value; 1428 } 1429 1430 /* Intersecting with the old var_off might have improved our bounds 1431 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1432 * then new var_off is (0; 0x7f...fc) which improves our umax. 1433 */ 1434 __reg_deduce_bounds(reg); 1435 __reg_bound_offset(reg); 1436 __update_reg_bounds(reg); 1437 } 1438 1439 /* Mark a register as having a completely unknown (scalar) value. */ 1440 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1441 struct bpf_reg_state *reg) 1442 { 1443 /* 1444 * Clear type, id, off, and union(map_ptr, range) and 1445 * padding between 'type' and union 1446 */ 1447 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1448 reg->type = SCALAR_VALUE; 1449 reg->var_off = tnum_unknown; 1450 reg->frameno = 0; 1451 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1452 __mark_reg_unbounded(reg); 1453 } 1454 1455 static void mark_reg_unknown(struct bpf_verifier_env *env, 1456 struct bpf_reg_state *regs, u32 regno) 1457 { 1458 if (WARN_ON(regno >= MAX_BPF_REG)) { 1459 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1460 /* Something bad happened, let's kill all regs except FP */ 1461 for (regno = 0; regno < BPF_REG_FP; regno++) 1462 __mark_reg_not_init(env, regs + regno); 1463 return; 1464 } 1465 __mark_reg_unknown(env, regs + regno); 1466 } 1467 1468 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1469 struct bpf_reg_state *reg) 1470 { 1471 __mark_reg_unknown(env, reg); 1472 reg->type = NOT_INIT; 1473 } 1474 1475 static void mark_reg_not_init(struct bpf_verifier_env *env, 1476 struct bpf_reg_state *regs, u32 regno) 1477 { 1478 if (WARN_ON(regno >= MAX_BPF_REG)) { 1479 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1480 /* Something bad happened, let's kill all regs except FP */ 1481 for (regno = 0; regno < BPF_REG_FP; regno++) 1482 __mark_reg_not_init(env, regs + regno); 1483 return; 1484 } 1485 __mark_reg_not_init(env, regs + regno); 1486 } 1487 1488 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1489 struct bpf_reg_state *regs, u32 regno, 1490 enum bpf_reg_type reg_type, 1491 struct btf *btf, u32 btf_id) 1492 { 1493 if (reg_type == SCALAR_VALUE) { 1494 mark_reg_unknown(env, regs, regno); 1495 return; 1496 } 1497 mark_reg_known_zero(env, regs, regno); 1498 regs[regno].type = PTR_TO_BTF_ID; 1499 regs[regno].btf = btf; 1500 regs[regno].btf_id = btf_id; 1501 } 1502 1503 #define DEF_NOT_SUBREG (0) 1504 static void init_reg_state(struct bpf_verifier_env *env, 1505 struct bpf_func_state *state) 1506 { 1507 struct bpf_reg_state *regs = state->regs; 1508 int i; 1509 1510 for (i = 0; i < MAX_BPF_REG; i++) { 1511 mark_reg_not_init(env, regs, i); 1512 regs[i].live = REG_LIVE_NONE; 1513 regs[i].parent = NULL; 1514 regs[i].subreg_def = DEF_NOT_SUBREG; 1515 } 1516 1517 /* frame pointer */ 1518 regs[BPF_REG_FP].type = PTR_TO_STACK; 1519 mark_reg_known_zero(env, regs, BPF_REG_FP); 1520 regs[BPF_REG_FP].frameno = state->frameno; 1521 } 1522 1523 #define BPF_MAIN_FUNC (-1) 1524 static void init_func_state(struct bpf_verifier_env *env, 1525 struct bpf_func_state *state, 1526 int callsite, int frameno, int subprogno) 1527 { 1528 state->callsite = callsite; 1529 state->frameno = frameno; 1530 state->subprogno = subprogno; 1531 init_reg_state(env, state); 1532 } 1533 1534 /* Similar to push_stack(), but for async callbacks */ 1535 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 1536 int insn_idx, int prev_insn_idx, 1537 int subprog) 1538 { 1539 struct bpf_verifier_stack_elem *elem; 1540 struct bpf_func_state *frame; 1541 1542 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1543 if (!elem) 1544 goto err; 1545 1546 elem->insn_idx = insn_idx; 1547 elem->prev_insn_idx = prev_insn_idx; 1548 elem->next = env->head; 1549 elem->log_pos = env->log.len_used; 1550 env->head = elem; 1551 env->stack_size++; 1552 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1553 verbose(env, 1554 "The sequence of %d jumps is too complex for async cb.\n", 1555 env->stack_size); 1556 goto err; 1557 } 1558 /* Unlike push_stack() do not copy_verifier_state(). 1559 * The caller state doesn't matter. 1560 * This is async callback. It starts in a fresh stack. 1561 * Initialize it similar to do_check_common(). 1562 */ 1563 elem->st.branches = 1; 1564 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 1565 if (!frame) 1566 goto err; 1567 init_func_state(env, frame, 1568 BPF_MAIN_FUNC /* callsite */, 1569 0 /* frameno within this callchain */, 1570 subprog /* subprog number within this prog */); 1571 elem->st.frame[0] = frame; 1572 return &elem->st; 1573 err: 1574 free_verifier_state(env->cur_state, true); 1575 env->cur_state = NULL; 1576 /* pop all elements and return */ 1577 while (!pop_stack(env, NULL, NULL, false)); 1578 return NULL; 1579 } 1580 1581 1582 enum reg_arg_type { 1583 SRC_OP, /* register is used as source operand */ 1584 DST_OP, /* register is used as destination operand */ 1585 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1586 }; 1587 1588 static int cmp_subprogs(const void *a, const void *b) 1589 { 1590 return ((struct bpf_subprog_info *)a)->start - 1591 ((struct bpf_subprog_info *)b)->start; 1592 } 1593 1594 static int find_subprog(struct bpf_verifier_env *env, int off) 1595 { 1596 struct bpf_subprog_info *p; 1597 1598 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1599 sizeof(env->subprog_info[0]), cmp_subprogs); 1600 if (!p) 1601 return -ENOENT; 1602 return p - env->subprog_info; 1603 1604 } 1605 1606 static int add_subprog(struct bpf_verifier_env *env, int off) 1607 { 1608 int insn_cnt = env->prog->len; 1609 int ret; 1610 1611 if (off >= insn_cnt || off < 0) { 1612 verbose(env, "call to invalid destination\n"); 1613 return -EINVAL; 1614 } 1615 ret = find_subprog(env, off); 1616 if (ret >= 0) 1617 return ret; 1618 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1619 verbose(env, "too many subprograms\n"); 1620 return -E2BIG; 1621 } 1622 /* determine subprog starts. The end is one before the next starts */ 1623 env->subprog_info[env->subprog_cnt++].start = off; 1624 sort(env->subprog_info, env->subprog_cnt, 1625 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1626 return env->subprog_cnt - 1; 1627 } 1628 1629 struct bpf_kfunc_desc { 1630 struct btf_func_model func_model; 1631 u32 func_id; 1632 s32 imm; 1633 }; 1634 1635 #define MAX_KFUNC_DESCS 256 1636 struct bpf_kfunc_desc_tab { 1637 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 1638 u32 nr_descs; 1639 }; 1640 1641 static int kfunc_desc_cmp_by_id(const void *a, const void *b) 1642 { 1643 const struct bpf_kfunc_desc *d0 = a; 1644 const struct bpf_kfunc_desc *d1 = b; 1645 1646 /* func_id is not greater than BTF_MAX_TYPE */ 1647 return d0->func_id - d1->func_id; 1648 } 1649 1650 static const struct bpf_kfunc_desc * 1651 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id) 1652 { 1653 struct bpf_kfunc_desc desc = { 1654 .func_id = func_id, 1655 }; 1656 struct bpf_kfunc_desc_tab *tab; 1657 1658 tab = prog->aux->kfunc_tab; 1659 return bsearch(&desc, tab->descs, tab->nr_descs, 1660 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id); 1661 } 1662 1663 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id) 1664 { 1665 const struct btf_type *func, *func_proto; 1666 struct bpf_kfunc_desc_tab *tab; 1667 struct bpf_prog_aux *prog_aux; 1668 struct bpf_kfunc_desc *desc; 1669 const char *func_name; 1670 unsigned long addr; 1671 int err; 1672 1673 prog_aux = env->prog->aux; 1674 tab = prog_aux->kfunc_tab; 1675 if (!tab) { 1676 if (!btf_vmlinux) { 1677 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 1678 return -ENOTSUPP; 1679 } 1680 1681 if (!env->prog->jit_requested) { 1682 verbose(env, "JIT is required for calling kernel function\n"); 1683 return -ENOTSUPP; 1684 } 1685 1686 if (!bpf_jit_supports_kfunc_call()) { 1687 verbose(env, "JIT does not support calling kernel function\n"); 1688 return -ENOTSUPP; 1689 } 1690 1691 if (!env->prog->gpl_compatible) { 1692 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 1693 return -EINVAL; 1694 } 1695 1696 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 1697 if (!tab) 1698 return -ENOMEM; 1699 prog_aux->kfunc_tab = tab; 1700 } 1701 1702 if (find_kfunc_desc(env->prog, func_id)) 1703 return 0; 1704 1705 if (tab->nr_descs == MAX_KFUNC_DESCS) { 1706 verbose(env, "too many different kernel function calls\n"); 1707 return -E2BIG; 1708 } 1709 1710 func = btf_type_by_id(btf_vmlinux, func_id); 1711 if (!func || !btf_type_is_func(func)) { 1712 verbose(env, "kernel btf_id %u is not a function\n", 1713 func_id); 1714 return -EINVAL; 1715 } 1716 func_proto = btf_type_by_id(btf_vmlinux, func->type); 1717 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 1718 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 1719 func_id); 1720 return -EINVAL; 1721 } 1722 1723 func_name = btf_name_by_offset(btf_vmlinux, func->name_off); 1724 addr = kallsyms_lookup_name(func_name); 1725 if (!addr) { 1726 verbose(env, "cannot find address for kernel function %s\n", 1727 func_name); 1728 return -EINVAL; 1729 } 1730 1731 desc = &tab->descs[tab->nr_descs++]; 1732 desc->func_id = func_id; 1733 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base; 1734 err = btf_distill_func_proto(&env->log, btf_vmlinux, 1735 func_proto, func_name, 1736 &desc->func_model); 1737 if (!err) 1738 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1739 kfunc_desc_cmp_by_id, NULL); 1740 return err; 1741 } 1742 1743 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 1744 { 1745 const struct bpf_kfunc_desc *d0 = a; 1746 const struct bpf_kfunc_desc *d1 = b; 1747 1748 if (d0->imm > d1->imm) 1749 return 1; 1750 else if (d0->imm < d1->imm) 1751 return -1; 1752 return 0; 1753 } 1754 1755 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 1756 { 1757 struct bpf_kfunc_desc_tab *tab; 1758 1759 tab = prog->aux->kfunc_tab; 1760 if (!tab) 1761 return; 1762 1763 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1764 kfunc_desc_cmp_by_imm, NULL); 1765 } 1766 1767 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 1768 { 1769 return !!prog->aux->kfunc_tab; 1770 } 1771 1772 const struct btf_func_model * 1773 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 1774 const struct bpf_insn *insn) 1775 { 1776 const struct bpf_kfunc_desc desc = { 1777 .imm = insn->imm, 1778 }; 1779 const struct bpf_kfunc_desc *res; 1780 struct bpf_kfunc_desc_tab *tab; 1781 1782 tab = prog->aux->kfunc_tab; 1783 res = bsearch(&desc, tab->descs, tab->nr_descs, 1784 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 1785 1786 return res ? &res->func_model : NULL; 1787 } 1788 1789 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 1790 { 1791 struct bpf_subprog_info *subprog = env->subprog_info; 1792 struct bpf_insn *insn = env->prog->insnsi; 1793 int i, ret, insn_cnt = env->prog->len; 1794 1795 /* Add entry function. */ 1796 ret = add_subprog(env, 0); 1797 if (ret) 1798 return ret; 1799 1800 for (i = 0; i < insn_cnt; i++, insn++) { 1801 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 1802 !bpf_pseudo_kfunc_call(insn)) 1803 continue; 1804 1805 if (!env->bpf_capable) { 1806 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1807 return -EPERM; 1808 } 1809 1810 if (bpf_pseudo_func(insn)) { 1811 ret = add_subprog(env, i + insn->imm + 1); 1812 if (ret >= 0) 1813 /* remember subprog */ 1814 insn[1].imm = ret; 1815 } else if (bpf_pseudo_call(insn)) { 1816 ret = add_subprog(env, i + insn->imm + 1); 1817 } else { 1818 ret = add_kfunc_call(env, insn->imm); 1819 } 1820 1821 if (ret < 0) 1822 return ret; 1823 } 1824 1825 /* Add a fake 'exit' subprog which could simplify subprog iteration 1826 * logic. 'subprog_cnt' should not be increased. 1827 */ 1828 subprog[env->subprog_cnt].start = insn_cnt; 1829 1830 if (env->log.level & BPF_LOG_LEVEL2) 1831 for (i = 0; i < env->subprog_cnt; i++) 1832 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1833 1834 return 0; 1835 } 1836 1837 static int check_subprogs(struct bpf_verifier_env *env) 1838 { 1839 int i, subprog_start, subprog_end, off, cur_subprog = 0; 1840 struct bpf_subprog_info *subprog = env->subprog_info; 1841 struct bpf_insn *insn = env->prog->insnsi; 1842 int insn_cnt = env->prog->len; 1843 1844 /* now check that all jumps are within the same subprog */ 1845 subprog_start = subprog[cur_subprog].start; 1846 subprog_end = subprog[cur_subprog + 1].start; 1847 for (i = 0; i < insn_cnt; i++) { 1848 u8 code = insn[i].code; 1849 1850 if (code == (BPF_JMP | BPF_CALL) && 1851 insn[i].imm == BPF_FUNC_tail_call && 1852 insn[i].src_reg != BPF_PSEUDO_CALL) 1853 subprog[cur_subprog].has_tail_call = true; 1854 if (BPF_CLASS(code) == BPF_LD && 1855 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 1856 subprog[cur_subprog].has_ld_abs = true; 1857 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 1858 goto next; 1859 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1860 goto next; 1861 off = i + insn[i].off + 1; 1862 if (off < subprog_start || off >= subprog_end) { 1863 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1864 return -EINVAL; 1865 } 1866 next: 1867 if (i == subprog_end - 1) { 1868 /* to avoid fall-through from one subprog into another 1869 * the last insn of the subprog should be either exit 1870 * or unconditional jump back 1871 */ 1872 if (code != (BPF_JMP | BPF_EXIT) && 1873 code != (BPF_JMP | BPF_JA)) { 1874 verbose(env, "last insn is not an exit or jmp\n"); 1875 return -EINVAL; 1876 } 1877 subprog_start = subprog_end; 1878 cur_subprog++; 1879 if (cur_subprog < env->subprog_cnt) 1880 subprog_end = subprog[cur_subprog + 1].start; 1881 } 1882 } 1883 return 0; 1884 } 1885 1886 /* Parentage chain of this register (or stack slot) should take care of all 1887 * issues like callee-saved registers, stack slot allocation time, etc. 1888 */ 1889 static int mark_reg_read(struct bpf_verifier_env *env, 1890 const struct bpf_reg_state *state, 1891 struct bpf_reg_state *parent, u8 flag) 1892 { 1893 bool writes = parent == state->parent; /* Observe write marks */ 1894 int cnt = 0; 1895 1896 while (parent) { 1897 /* if read wasn't screened by an earlier write ... */ 1898 if (writes && state->live & REG_LIVE_WRITTEN) 1899 break; 1900 if (parent->live & REG_LIVE_DONE) { 1901 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 1902 reg_type_str[parent->type], 1903 parent->var_off.value, parent->off); 1904 return -EFAULT; 1905 } 1906 /* The first condition is more likely to be true than the 1907 * second, checked it first. 1908 */ 1909 if ((parent->live & REG_LIVE_READ) == flag || 1910 parent->live & REG_LIVE_READ64) 1911 /* The parentage chain never changes and 1912 * this parent was already marked as LIVE_READ. 1913 * There is no need to keep walking the chain again and 1914 * keep re-marking all parents as LIVE_READ. 1915 * This case happens when the same register is read 1916 * multiple times without writes into it in-between. 1917 * Also, if parent has the stronger REG_LIVE_READ64 set, 1918 * then no need to set the weak REG_LIVE_READ32. 1919 */ 1920 break; 1921 /* ... then we depend on parent's value */ 1922 parent->live |= flag; 1923 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 1924 if (flag == REG_LIVE_READ64) 1925 parent->live &= ~REG_LIVE_READ32; 1926 state = parent; 1927 parent = state->parent; 1928 writes = true; 1929 cnt++; 1930 } 1931 1932 if (env->longest_mark_read_walk < cnt) 1933 env->longest_mark_read_walk = cnt; 1934 return 0; 1935 } 1936 1937 /* This function is supposed to be used by the following 32-bit optimization 1938 * code only. It returns TRUE if the source or destination register operates 1939 * on 64-bit, otherwise return FALSE. 1940 */ 1941 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 1942 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 1943 { 1944 u8 code, class, op; 1945 1946 code = insn->code; 1947 class = BPF_CLASS(code); 1948 op = BPF_OP(code); 1949 if (class == BPF_JMP) { 1950 /* BPF_EXIT for "main" will reach here. Return TRUE 1951 * conservatively. 1952 */ 1953 if (op == BPF_EXIT) 1954 return true; 1955 if (op == BPF_CALL) { 1956 /* BPF to BPF call will reach here because of marking 1957 * caller saved clobber with DST_OP_NO_MARK for which we 1958 * don't care the register def because they are anyway 1959 * marked as NOT_INIT already. 1960 */ 1961 if (insn->src_reg == BPF_PSEUDO_CALL) 1962 return false; 1963 /* Helper call will reach here because of arg type 1964 * check, conservatively return TRUE. 1965 */ 1966 if (t == SRC_OP) 1967 return true; 1968 1969 return false; 1970 } 1971 } 1972 1973 if (class == BPF_ALU64 || class == BPF_JMP || 1974 /* BPF_END always use BPF_ALU class. */ 1975 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 1976 return true; 1977 1978 if (class == BPF_ALU || class == BPF_JMP32) 1979 return false; 1980 1981 if (class == BPF_LDX) { 1982 if (t != SRC_OP) 1983 return BPF_SIZE(code) == BPF_DW; 1984 /* LDX source must be ptr. */ 1985 return true; 1986 } 1987 1988 if (class == BPF_STX) { 1989 /* BPF_STX (including atomic variants) has multiple source 1990 * operands, one of which is a ptr. Check whether the caller is 1991 * asking about it. 1992 */ 1993 if (t == SRC_OP && reg->type != SCALAR_VALUE) 1994 return true; 1995 return BPF_SIZE(code) == BPF_DW; 1996 } 1997 1998 if (class == BPF_LD) { 1999 u8 mode = BPF_MODE(code); 2000 2001 /* LD_IMM64 */ 2002 if (mode == BPF_IMM) 2003 return true; 2004 2005 /* Both LD_IND and LD_ABS return 32-bit data. */ 2006 if (t != SRC_OP) 2007 return false; 2008 2009 /* Implicit ctx ptr. */ 2010 if (regno == BPF_REG_6) 2011 return true; 2012 2013 /* Explicit source could be any width. */ 2014 return true; 2015 } 2016 2017 if (class == BPF_ST) 2018 /* The only source register for BPF_ST is a ptr. */ 2019 return true; 2020 2021 /* Conservatively return true at default. */ 2022 return true; 2023 } 2024 2025 /* Return the regno defined by the insn, or -1. */ 2026 static int insn_def_regno(const struct bpf_insn *insn) 2027 { 2028 switch (BPF_CLASS(insn->code)) { 2029 case BPF_JMP: 2030 case BPF_JMP32: 2031 case BPF_ST: 2032 return -1; 2033 case BPF_STX: 2034 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2035 (insn->imm & BPF_FETCH)) { 2036 if (insn->imm == BPF_CMPXCHG) 2037 return BPF_REG_0; 2038 else 2039 return insn->src_reg; 2040 } else { 2041 return -1; 2042 } 2043 default: 2044 return insn->dst_reg; 2045 } 2046 } 2047 2048 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2049 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2050 { 2051 int dst_reg = insn_def_regno(insn); 2052 2053 if (dst_reg == -1) 2054 return false; 2055 2056 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2057 } 2058 2059 static void mark_insn_zext(struct bpf_verifier_env *env, 2060 struct bpf_reg_state *reg) 2061 { 2062 s32 def_idx = reg->subreg_def; 2063 2064 if (def_idx == DEF_NOT_SUBREG) 2065 return; 2066 2067 env->insn_aux_data[def_idx - 1].zext_dst = true; 2068 /* The dst will be zero extended, so won't be sub-register anymore. */ 2069 reg->subreg_def = DEF_NOT_SUBREG; 2070 } 2071 2072 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2073 enum reg_arg_type t) 2074 { 2075 struct bpf_verifier_state *vstate = env->cur_state; 2076 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2077 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2078 struct bpf_reg_state *reg, *regs = state->regs; 2079 bool rw64; 2080 2081 if (regno >= MAX_BPF_REG) { 2082 verbose(env, "R%d is invalid\n", regno); 2083 return -EINVAL; 2084 } 2085 2086 reg = ®s[regno]; 2087 rw64 = is_reg64(env, insn, regno, reg, t); 2088 if (t == SRC_OP) { 2089 /* check whether register used as source operand can be read */ 2090 if (reg->type == NOT_INIT) { 2091 verbose(env, "R%d !read_ok\n", regno); 2092 return -EACCES; 2093 } 2094 /* We don't need to worry about FP liveness because it's read-only */ 2095 if (regno == BPF_REG_FP) 2096 return 0; 2097 2098 if (rw64) 2099 mark_insn_zext(env, reg); 2100 2101 return mark_reg_read(env, reg, reg->parent, 2102 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2103 } else { 2104 /* check whether register used as dest operand can be written to */ 2105 if (regno == BPF_REG_FP) { 2106 verbose(env, "frame pointer is read only\n"); 2107 return -EACCES; 2108 } 2109 reg->live |= REG_LIVE_WRITTEN; 2110 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2111 if (t == DST_OP) 2112 mark_reg_unknown(env, regs, regno); 2113 } 2114 return 0; 2115 } 2116 2117 /* for any branch, call, exit record the history of jmps in the given state */ 2118 static int push_jmp_history(struct bpf_verifier_env *env, 2119 struct bpf_verifier_state *cur) 2120 { 2121 u32 cnt = cur->jmp_history_cnt; 2122 struct bpf_idx_pair *p; 2123 2124 cnt++; 2125 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 2126 if (!p) 2127 return -ENOMEM; 2128 p[cnt - 1].idx = env->insn_idx; 2129 p[cnt - 1].prev_idx = env->prev_insn_idx; 2130 cur->jmp_history = p; 2131 cur->jmp_history_cnt = cnt; 2132 return 0; 2133 } 2134 2135 /* Backtrack one insn at a time. If idx is not at the top of recorded 2136 * history then previous instruction came from straight line execution. 2137 */ 2138 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2139 u32 *history) 2140 { 2141 u32 cnt = *history; 2142 2143 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2144 i = st->jmp_history[cnt - 1].prev_idx; 2145 (*history)--; 2146 } else { 2147 i--; 2148 } 2149 return i; 2150 } 2151 2152 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2153 { 2154 const struct btf_type *func; 2155 2156 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2157 return NULL; 2158 2159 func = btf_type_by_id(btf_vmlinux, insn->imm); 2160 return btf_name_by_offset(btf_vmlinux, func->name_off); 2161 } 2162 2163 /* For given verifier state backtrack_insn() is called from the last insn to 2164 * the first insn. Its purpose is to compute a bitmask of registers and 2165 * stack slots that needs precision in the parent verifier state. 2166 */ 2167 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2168 u32 *reg_mask, u64 *stack_mask) 2169 { 2170 const struct bpf_insn_cbs cbs = { 2171 .cb_call = disasm_kfunc_name, 2172 .cb_print = verbose, 2173 .private_data = env, 2174 }; 2175 struct bpf_insn *insn = env->prog->insnsi + idx; 2176 u8 class = BPF_CLASS(insn->code); 2177 u8 opcode = BPF_OP(insn->code); 2178 u8 mode = BPF_MODE(insn->code); 2179 u32 dreg = 1u << insn->dst_reg; 2180 u32 sreg = 1u << insn->src_reg; 2181 u32 spi; 2182 2183 if (insn->code == 0) 2184 return 0; 2185 if (env->log.level & BPF_LOG_LEVEL) { 2186 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2187 verbose(env, "%d: ", idx); 2188 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2189 } 2190 2191 if (class == BPF_ALU || class == BPF_ALU64) { 2192 if (!(*reg_mask & dreg)) 2193 return 0; 2194 if (opcode == BPF_MOV) { 2195 if (BPF_SRC(insn->code) == BPF_X) { 2196 /* dreg = sreg 2197 * dreg needs precision after this insn 2198 * sreg needs precision before this insn 2199 */ 2200 *reg_mask &= ~dreg; 2201 *reg_mask |= sreg; 2202 } else { 2203 /* dreg = K 2204 * dreg needs precision after this insn. 2205 * Corresponding register is already marked 2206 * as precise=true in this verifier state. 2207 * No further markings in parent are necessary 2208 */ 2209 *reg_mask &= ~dreg; 2210 } 2211 } else { 2212 if (BPF_SRC(insn->code) == BPF_X) { 2213 /* dreg += sreg 2214 * both dreg and sreg need precision 2215 * before this insn 2216 */ 2217 *reg_mask |= sreg; 2218 } /* else dreg += K 2219 * dreg still needs precision before this insn 2220 */ 2221 } 2222 } else if (class == BPF_LDX) { 2223 if (!(*reg_mask & dreg)) 2224 return 0; 2225 *reg_mask &= ~dreg; 2226 2227 /* scalars can only be spilled into stack w/o losing precision. 2228 * Load from any other memory can be zero extended. 2229 * The desire to keep that precision is already indicated 2230 * by 'precise' mark in corresponding register of this state. 2231 * No further tracking necessary. 2232 */ 2233 if (insn->src_reg != BPF_REG_FP) 2234 return 0; 2235 if (BPF_SIZE(insn->code) != BPF_DW) 2236 return 0; 2237 2238 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2239 * that [fp - off] slot contains scalar that needs to be 2240 * tracked with precision 2241 */ 2242 spi = (-insn->off - 1) / BPF_REG_SIZE; 2243 if (spi >= 64) { 2244 verbose(env, "BUG spi %d\n", spi); 2245 WARN_ONCE(1, "verifier backtracking bug"); 2246 return -EFAULT; 2247 } 2248 *stack_mask |= 1ull << spi; 2249 } else if (class == BPF_STX || class == BPF_ST) { 2250 if (*reg_mask & dreg) 2251 /* stx & st shouldn't be using _scalar_ dst_reg 2252 * to access memory. It means backtracking 2253 * encountered a case of pointer subtraction. 2254 */ 2255 return -ENOTSUPP; 2256 /* scalars can only be spilled into stack */ 2257 if (insn->dst_reg != BPF_REG_FP) 2258 return 0; 2259 if (BPF_SIZE(insn->code) != BPF_DW) 2260 return 0; 2261 spi = (-insn->off - 1) / BPF_REG_SIZE; 2262 if (spi >= 64) { 2263 verbose(env, "BUG spi %d\n", spi); 2264 WARN_ONCE(1, "verifier backtracking bug"); 2265 return -EFAULT; 2266 } 2267 if (!(*stack_mask & (1ull << spi))) 2268 return 0; 2269 *stack_mask &= ~(1ull << spi); 2270 if (class == BPF_STX) 2271 *reg_mask |= sreg; 2272 } else if (class == BPF_JMP || class == BPF_JMP32) { 2273 if (opcode == BPF_CALL) { 2274 if (insn->src_reg == BPF_PSEUDO_CALL) 2275 return -ENOTSUPP; 2276 /* regular helper call sets R0 */ 2277 *reg_mask &= ~1; 2278 if (*reg_mask & 0x3f) { 2279 /* if backtracing was looking for registers R1-R5 2280 * they should have been found already. 2281 */ 2282 verbose(env, "BUG regs %x\n", *reg_mask); 2283 WARN_ONCE(1, "verifier backtracking bug"); 2284 return -EFAULT; 2285 } 2286 } else if (opcode == BPF_EXIT) { 2287 return -ENOTSUPP; 2288 } 2289 } else if (class == BPF_LD) { 2290 if (!(*reg_mask & dreg)) 2291 return 0; 2292 *reg_mask &= ~dreg; 2293 /* It's ld_imm64 or ld_abs or ld_ind. 2294 * For ld_imm64 no further tracking of precision 2295 * into parent is necessary 2296 */ 2297 if (mode == BPF_IND || mode == BPF_ABS) 2298 /* to be analyzed */ 2299 return -ENOTSUPP; 2300 } 2301 return 0; 2302 } 2303 2304 /* the scalar precision tracking algorithm: 2305 * . at the start all registers have precise=false. 2306 * . scalar ranges are tracked as normal through alu and jmp insns. 2307 * . once precise value of the scalar register is used in: 2308 * . ptr + scalar alu 2309 * . if (scalar cond K|scalar) 2310 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2311 * backtrack through the verifier states and mark all registers and 2312 * stack slots with spilled constants that these scalar regisers 2313 * should be precise. 2314 * . during state pruning two registers (or spilled stack slots) 2315 * are equivalent if both are not precise. 2316 * 2317 * Note the verifier cannot simply walk register parentage chain, 2318 * since many different registers and stack slots could have been 2319 * used to compute single precise scalar. 2320 * 2321 * The approach of starting with precise=true for all registers and then 2322 * backtrack to mark a register as not precise when the verifier detects 2323 * that program doesn't care about specific value (e.g., when helper 2324 * takes register as ARG_ANYTHING parameter) is not safe. 2325 * 2326 * It's ok to walk single parentage chain of the verifier states. 2327 * It's possible that this backtracking will go all the way till 1st insn. 2328 * All other branches will be explored for needing precision later. 2329 * 2330 * The backtracking needs to deal with cases like: 2331 * 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) 2332 * r9 -= r8 2333 * r5 = r9 2334 * if r5 > 0x79f goto pc+7 2335 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2336 * r5 += 1 2337 * ... 2338 * call bpf_perf_event_output#25 2339 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2340 * 2341 * and this case: 2342 * r6 = 1 2343 * call foo // uses callee's r6 inside to compute r0 2344 * r0 += r6 2345 * if r0 == 0 goto 2346 * 2347 * to track above reg_mask/stack_mask needs to be independent for each frame. 2348 * 2349 * Also if parent's curframe > frame where backtracking started, 2350 * the verifier need to mark registers in both frames, otherwise callees 2351 * may incorrectly prune callers. This is similar to 2352 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2353 * 2354 * For now backtracking falls back into conservative marking. 2355 */ 2356 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2357 struct bpf_verifier_state *st) 2358 { 2359 struct bpf_func_state *func; 2360 struct bpf_reg_state *reg; 2361 int i, j; 2362 2363 /* big hammer: mark all scalars precise in this path. 2364 * pop_stack may still get !precise scalars. 2365 */ 2366 for (; st; st = st->parent) 2367 for (i = 0; i <= st->curframe; i++) { 2368 func = st->frame[i]; 2369 for (j = 0; j < BPF_REG_FP; j++) { 2370 reg = &func->regs[j]; 2371 if (reg->type != SCALAR_VALUE) 2372 continue; 2373 reg->precise = true; 2374 } 2375 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2376 if (func->stack[j].slot_type[0] != STACK_SPILL) 2377 continue; 2378 reg = &func->stack[j].spilled_ptr; 2379 if (reg->type != SCALAR_VALUE) 2380 continue; 2381 reg->precise = true; 2382 } 2383 } 2384 } 2385 2386 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 2387 int spi) 2388 { 2389 struct bpf_verifier_state *st = env->cur_state; 2390 int first_idx = st->first_insn_idx; 2391 int last_idx = env->insn_idx; 2392 struct bpf_func_state *func; 2393 struct bpf_reg_state *reg; 2394 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2395 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2396 bool skip_first = true; 2397 bool new_marks = false; 2398 int i, err; 2399 2400 if (!env->bpf_capable) 2401 return 0; 2402 2403 func = st->frame[st->curframe]; 2404 if (regno >= 0) { 2405 reg = &func->regs[regno]; 2406 if (reg->type != SCALAR_VALUE) { 2407 WARN_ONCE(1, "backtracing misuse"); 2408 return -EFAULT; 2409 } 2410 if (!reg->precise) 2411 new_marks = true; 2412 else 2413 reg_mask = 0; 2414 reg->precise = true; 2415 } 2416 2417 while (spi >= 0) { 2418 if (func->stack[spi].slot_type[0] != STACK_SPILL) { 2419 stack_mask = 0; 2420 break; 2421 } 2422 reg = &func->stack[spi].spilled_ptr; 2423 if (reg->type != SCALAR_VALUE) { 2424 stack_mask = 0; 2425 break; 2426 } 2427 if (!reg->precise) 2428 new_marks = true; 2429 else 2430 stack_mask = 0; 2431 reg->precise = true; 2432 break; 2433 } 2434 2435 if (!new_marks) 2436 return 0; 2437 if (!reg_mask && !stack_mask) 2438 return 0; 2439 for (;;) { 2440 DECLARE_BITMAP(mask, 64); 2441 u32 history = st->jmp_history_cnt; 2442 2443 if (env->log.level & BPF_LOG_LEVEL) 2444 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2445 for (i = last_idx;;) { 2446 if (skip_first) { 2447 err = 0; 2448 skip_first = false; 2449 } else { 2450 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2451 } 2452 if (err == -ENOTSUPP) { 2453 mark_all_scalars_precise(env, st); 2454 return 0; 2455 } else if (err) { 2456 return err; 2457 } 2458 if (!reg_mask && !stack_mask) 2459 /* Found assignment(s) into tracked register in this state. 2460 * Since this state is already marked, just return. 2461 * Nothing to be tracked further in the parent state. 2462 */ 2463 return 0; 2464 if (i == first_idx) 2465 break; 2466 i = get_prev_insn_idx(st, i, &history); 2467 if (i >= env->prog->len) { 2468 /* This can happen if backtracking reached insn 0 2469 * and there are still reg_mask or stack_mask 2470 * to backtrack. 2471 * It means the backtracking missed the spot where 2472 * particular register was initialized with a constant. 2473 */ 2474 verbose(env, "BUG backtracking idx %d\n", i); 2475 WARN_ONCE(1, "verifier backtracking bug"); 2476 return -EFAULT; 2477 } 2478 } 2479 st = st->parent; 2480 if (!st) 2481 break; 2482 2483 new_marks = false; 2484 func = st->frame[st->curframe]; 2485 bitmap_from_u64(mask, reg_mask); 2486 for_each_set_bit(i, mask, 32) { 2487 reg = &func->regs[i]; 2488 if (reg->type != SCALAR_VALUE) { 2489 reg_mask &= ~(1u << i); 2490 continue; 2491 } 2492 if (!reg->precise) 2493 new_marks = true; 2494 reg->precise = true; 2495 } 2496 2497 bitmap_from_u64(mask, stack_mask); 2498 for_each_set_bit(i, mask, 64) { 2499 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2500 /* the sequence of instructions: 2501 * 2: (bf) r3 = r10 2502 * 3: (7b) *(u64 *)(r3 -8) = r0 2503 * 4: (79) r4 = *(u64 *)(r10 -8) 2504 * doesn't contain jmps. It's backtracked 2505 * as a single block. 2506 * During backtracking insn 3 is not recognized as 2507 * stack access, so at the end of backtracking 2508 * stack slot fp-8 is still marked in stack_mask. 2509 * However the parent state may not have accessed 2510 * fp-8 and it's "unallocated" stack space. 2511 * In such case fallback to conservative. 2512 */ 2513 mark_all_scalars_precise(env, st); 2514 return 0; 2515 } 2516 2517 if (func->stack[i].slot_type[0] != STACK_SPILL) { 2518 stack_mask &= ~(1ull << i); 2519 continue; 2520 } 2521 reg = &func->stack[i].spilled_ptr; 2522 if (reg->type != SCALAR_VALUE) { 2523 stack_mask &= ~(1ull << i); 2524 continue; 2525 } 2526 if (!reg->precise) 2527 new_marks = true; 2528 reg->precise = true; 2529 } 2530 if (env->log.level & BPF_LOG_LEVEL) { 2531 print_verifier_state(env, func); 2532 verbose(env, "parent %s regs=%x stack=%llx marks\n", 2533 new_marks ? "didn't have" : "already had", 2534 reg_mask, stack_mask); 2535 } 2536 2537 if (!reg_mask && !stack_mask) 2538 break; 2539 if (!new_marks) 2540 break; 2541 2542 last_idx = st->last_insn_idx; 2543 first_idx = st->first_insn_idx; 2544 } 2545 return 0; 2546 } 2547 2548 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2549 { 2550 return __mark_chain_precision(env, regno, -1); 2551 } 2552 2553 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2554 { 2555 return __mark_chain_precision(env, -1, spi); 2556 } 2557 2558 static bool is_spillable_regtype(enum bpf_reg_type type) 2559 { 2560 switch (type) { 2561 case PTR_TO_MAP_VALUE: 2562 case PTR_TO_MAP_VALUE_OR_NULL: 2563 case PTR_TO_STACK: 2564 case PTR_TO_CTX: 2565 case PTR_TO_PACKET: 2566 case PTR_TO_PACKET_META: 2567 case PTR_TO_PACKET_END: 2568 case PTR_TO_FLOW_KEYS: 2569 case CONST_PTR_TO_MAP: 2570 case PTR_TO_SOCKET: 2571 case PTR_TO_SOCKET_OR_NULL: 2572 case PTR_TO_SOCK_COMMON: 2573 case PTR_TO_SOCK_COMMON_OR_NULL: 2574 case PTR_TO_TCP_SOCK: 2575 case PTR_TO_TCP_SOCK_OR_NULL: 2576 case PTR_TO_XDP_SOCK: 2577 case PTR_TO_BTF_ID: 2578 case PTR_TO_BTF_ID_OR_NULL: 2579 case PTR_TO_RDONLY_BUF: 2580 case PTR_TO_RDONLY_BUF_OR_NULL: 2581 case PTR_TO_RDWR_BUF: 2582 case PTR_TO_RDWR_BUF_OR_NULL: 2583 case PTR_TO_PERCPU_BTF_ID: 2584 case PTR_TO_MEM: 2585 case PTR_TO_MEM_OR_NULL: 2586 case PTR_TO_FUNC: 2587 case PTR_TO_MAP_KEY: 2588 return true; 2589 default: 2590 return false; 2591 } 2592 } 2593 2594 /* Does this register contain a constant zero? */ 2595 static bool register_is_null(struct bpf_reg_state *reg) 2596 { 2597 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2598 } 2599 2600 static bool register_is_const(struct bpf_reg_state *reg) 2601 { 2602 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2603 } 2604 2605 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 2606 { 2607 return tnum_is_unknown(reg->var_off) && 2608 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 2609 reg->umin_value == 0 && reg->umax_value == U64_MAX && 2610 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 2611 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 2612 } 2613 2614 static bool register_is_bounded(struct bpf_reg_state *reg) 2615 { 2616 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 2617 } 2618 2619 static bool __is_pointer_value(bool allow_ptr_leaks, 2620 const struct bpf_reg_state *reg) 2621 { 2622 if (allow_ptr_leaks) 2623 return false; 2624 2625 return reg->type != SCALAR_VALUE; 2626 } 2627 2628 static void save_register_state(struct bpf_func_state *state, 2629 int spi, struct bpf_reg_state *reg) 2630 { 2631 int i; 2632 2633 state->stack[spi].spilled_ptr = *reg; 2634 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2635 2636 for (i = 0; i < BPF_REG_SIZE; i++) 2637 state->stack[spi].slot_type[i] = STACK_SPILL; 2638 } 2639 2640 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 2641 * stack boundary and alignment are checked in check_mem_access() 2642 */ 2643 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 2644 /* stack frame we're writing to */ 2645 struct bpf_func_state *state, 2646 int off, int size, int value_regno, 2647 int insn_idx) 2648 { 2649 struct bpf_func_state *cur; /* state of the current function */ 2650 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2651 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2652 struct bpf_reg_state *reg = NULL; 2653 2654 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 2655 if (err) 2656 return err; 2657 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2658 * so it's aligned access and [off, off + size) are within stack limits 2659 */ 2660 if (!env->allow_ptr_leaks && 2661 state->stack[spi].slot_type[0] == STACK_SPILL && 2662 size != BPF_REG_SIZE) { 2663 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2664 return -EACCES; 2665 } 2666 2667 cur = env->cur_state->frame[env->cur_state->curframe]; 2668 if (value_regno >= 0) 2669 reg = &cur->regs[value_regno]; 2670 2671 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) && 2672 !register_is_null(reg) && env->bpf_capable) { 2673 if (dst_reg != BPF_REG_FP) { 2674 /* The backtracking logic can only recognize explicit 2675 * stack slot address like [fp - 8]. Other spill of 2676 * scalar via different register has to be conservative. 2677 * Backtrack from here and mark all registers as precise 2678 * that contributed into 'reg' being a constant. 2679 */ 2680 err = mark_chain_precision(env, value_regno); 2681 if (err) 2682 return err; 2683 } 2684 save_register_state(state, spi, reg); 2685 } else if (reg && is_spillable_regtype(reg->type)) { 2686 /* register containing pointer is being spilled into stack */ 2687 if (size != BPF_REG_SIZE) { 2688 verbose_linfo(env, insn_idx, "; "); 2689 verbose(env, "invalid size of register spill\n"); 2690 return -EACCES; 2691 } 2692 2693 if (state != cur && reg->type == PTR_TO_STACK) { 2694 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2695 return -EINVAL; 2696 } 2697 2698 if (!env->bypass_spec_v4) { 2699 bool sanitize = false; 2700 2701 if (state->stack[spi].slot_type[0] == STACK_SPILL && 2702 register_is_const(&state->stack[spi].spilled_ptr)) 2703 sanitize = true; 2704 for (i = 0; i < BPF_REG_SIZE; i++) 2705 if (state->stack[spi].slot_type[i] == STACK_MISC) { 2706 sanitize = true; 2707 break; 2708 } 2709 if (sanitize) { 2710 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 2711 int soff = (-spi - 1) * BPF_REG_SIZE; 2712 2713 /* detected reuse of integer stack slot with a pointer 2714 * which means either llvm is reusing stack slot or 2715 * an attacker is trying to exploit CVE-2018-3639 2716 * (speculative store bypass) 2717 * Have to sanitize that slot with preemptive 2718 * store of zero. 2719 */ 2720 if (*poff && *poff != soff) { 2721 /* disallow programs where single insn stores 2722 * into two different stack slots, since verifier 2723 * cannot sanitize them 2724 */ 2725 verbose(env, 2726 "insn %d cannot access two stack slots fp%d and fp%d", 2727 insn_idx, *poff, soff); 2728 return -EINVAL; 2729 } 2730 *poff = soff; 2731 } 2732 } 2733 save_register_state(state, spi, reg); 2734 } else { 2735 u8 type = STACK_MISC; 2736 2737 /* regular write of data into stack destroys any spilled ptr */ 2738 state->stack[spi].spilled_ptr.type = NOT_INIT; 2739 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2740 if (state->stack[spi].slot_type[0] == STACK_SPILL) 2741 for (i = 0; i < BPF_REG_SIZE; i++) 2742 state->stack[spi].slot_type[i] = STACK_MISC; 2743 2744 /* only mark the slot as written if all 8 bytes were written 2745 * otherwise read propagation may incorrectly stop too soon 2746 * when stack slots are partially written. 2747 * This heuristic means that read propagation will be 2748 * conservative, since it will add reg_live_read marks 2749 * to stack slots all the way to first state when programs 2750 * writes+reads less than 8 bytes 2751 */ 2752 if (size == BPF_REG_SIZE) 2753 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2754 2755 /* when we zero initialize stack slots mark them as such */ 2756 if (reg && register_is_null(reg)) { 2757 /* backtracking doesn't work for STACK_ZERO yet. */ 2758 err = mark_chain_precision(env, value_regno); 2759 if (err) 2760 return err; 2761 type = STACK_ZERO; 2762 } 2763 2764 /* Mark slots affected by this stack write. */ 2765 for (i = 0; i < size; i++) 2766 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2767 type; 2768 } 2769 return 0; 2770 } 2771 2772 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 2773 * known to contain a variable offset. 2774 * This function checks whether the write is permitted and conservatively 2775 * tracks the effects of the write, considering that each stack slot in the 2776 * dynamic range is potentially written to. 2777 * 2778 * 'off' includes 'regno->off'. 2779 * 'value_regno' can be -1, meaning that an unknown value is being written to 2780 * the stack. 2781 * 2782 * Spilled pointers in range are not marked as written because we don't know 2783 * what's going to be actually written. This means that read propagation for 2784 * future reads cannot be terminated by this write. 2785 * 2786 * For privileged programs, uninitialized stack slots are considered 2787 * initialized by this write (even though we don't know exactly what offsets 2788 * are going to be written to). The idea is that we don't want the verifier to 2789 * reject future reads that access slots written to through variable offsets. 2790 */ 2791 static int check_stack_write_var_off(struct bpf_verifier_env *env, 2792 /* func where register points to */ 2793 struct bpf_func_state *state, 2794 int ptr_regno, int off, int size, 2795 int value_regno, int insn_idx) 2796 { 2797 struct bpf_func_state *cur; /* state of the current function */ 2798 int min_off, max_off; 2799 int i, err; 2800 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 2801 bool writing_zero = false; 2802 /* set if the fact that we're writing a zero is used to let any 2803 * stack slots remain STACK_ZERO 2804 */ 2805 bool zero_used = false; 2806 2807 cur = env->cur_state->frame[env->cur_state->curframe]; 2808 ptr_reg = &cur->regs[ptr_regno]; 2809 min_off = ptr_reg->smin_value + off; 2810 max_off = ptr_reg->smax_value + off + size; 2811 if (value_regno >= 0) 2812 value_reg = &cur->regs[value_regno]; 2813 if (value_reg && register_is_null(value_reg)) 2814 writing_zero = true; 2815 2816 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 2817 if (err) 2818 return err; 2819 2820 2821 /* Variable offset writes destroy any spilled pointers in range. */ 2822 for (i = min_off; i < max_off; i++) { 2823 u8 new_type, *stype; 2824 int slot, spi; 2825 2826 slot = -i - 1; 2827 spi = slot / BPF_REG_SIZE; 2828 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2829 2830 if (!env->allow_ptr_leaks 2831 && *stype != NOT_INIT 2832 && *stype != SCALAR_VALUE) { 2833 /* Reject the write if there's are spilled pointers in 2834 * range. If we didn't reject here, the ptr status 2835 * would be erased below (even though not all slots are 2836 * actually overwritten), possibly opening the door to 2837 * leaks. 2838 */ 2839 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 2840 insn_idx, i); 2841 return -EINVAL; 2842 } 2843 2844 /* Erase all spilled pointers. */ 2845 state->stack[spi].spilled_ptr.type = NOT_INIT; 2846 2847 /* Update the slot type. */ 2848 new_type = STACK_MISC; 2849 if (writing_zero && *stype == STACK_ZERO) { 2850 new_type = STACK_ZERO; 2851 zero_used = true; 2852 } 2853 /* If the slot is STACK_INVALID, we check whether it's OK to 2854 * pretend that it will be initialized by this write. The slot 2855 * might not actually be written to, and so if we mark it as 2856 * initialized future reads might leak uninitialized memory. 2857 * For privileged programs, we will accept such reads to slots 2858 * that may or may not be written because, if we're reject 2859 * them, the error would be too confusing. 2860 */ 2861 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 2862 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 2863 insn_idx, i); 2864 return -EINVAL; 2865 } 2866 *stype = new_type; 2867 } 2868 if (zero_used) { 2869 /* backtracking doesn't work for STACK_ZERO yet. */ 2870 err = mark_chain_precision(env, value_regno); 2871 if (err) 2872 return err; 2873 } 2874 return 0; 2875 } 2876 2877 /* When register 'dst_regno' is assigned some values from stack[min_off, 2878 * max_off), we set the register's type according to the types of the 2879 * respective stack slots. If all the stack values are known to be zeros, then 2880 * so is the destination reg. Otherwise, the register is considered to be 2881 * SCALAR. This function does not deal with register filling; the caller must 2882 * ensure that all spilled registers in the stack range have been marked as 2883 * read. 2884 */ 2885 static void mark_reg_stack_read(struct bpf_verifier_env *env, 2886 /* func where src register points to */ 2887 struct bpf_func_state *ptr_state, 2888 int min_off, int max_off, int dst_regno) 2889 { 2890 struct bpf_verifier_state *vstate = env->cur_state; 2891 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2892 int i, slot, spi; 2893 u8 *stype; 2894 int zeros = 0; 2895 2896 for (i = min_off; i < max_off; i++) { 2897 slot = -i - 1; 2898 spi = slot / BPF_REG_SIZE; 2899 stype = ptr_state->stack[spi].slot_type; 2900 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 2901 break; 2902 zeros++; 2903 } 2904 if (zeros == max_off - min_off) { 2905 /* any access_size read into register is zero extended, 2906 * so the whole register == const_zero 2907 */ 2908 __mark_reg_const_zero(&state->regs[dst_regno]); 2909 /* backtracking doesn't support STACK_ZERO yet, 2910 * so mark it precise here, so that later 2911 * backtracking can stop here. 2912 * Backtracking may not need this if this register 2913 * doesn't participate in pointer adjustment. 2914 * Forward propagation of precise flag is not 2915 * necessary either. This mark is only to stop 2916 * backtracking. Any register that contributed 2917 * to const 0 was marked precise before spill. 2918 */ 2919 state->regs[dst_regno].precise = true; 2920 } else { 2921 /* have read misc data from the stack */ 2922 mark_reg_unknown(env, state->regs, dst_regno); 2923 } 2924 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2925 } 2926 2927 /* Read the stack at 'off' and put the results into the register indicated by 2928 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 2929 * spilled reg. 2930 * 2931 * 'dst_regno' can be -1, meaning that the read value is not going to a 2932 * register. 2933 * 2934 * The access is assumed to be within the current stack bounds. 2935 */ 2936 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 2937 /* func where src register points to */ 2938 struct bpf_func_state *reg_state, 2939 int off, int size, int dst_regno) 2940 { 2941 struct bpf_verifier_state *vstate = env->cur_state; 2942 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2943 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 2944 struct bpf_reg_state *reg; 2945 u8 *stype; 2946 2947 stype = reg_state->stack[spi].slot_type; 2948 reg = ®_state->stack[spi].spilled_ptr; 2949 2950 if (stype[0] == STACK_SPILL) { 2951 if (size != BPF_REG_SIZE) { 2952 if (reg->type != SCALAR_VALUE) { 2953 verbose_linfo(env, env->insn_idx, "; "); 2954 verbose(env, "invalid size of register fill\n"); 2955 return -EACCES; 2956 } 2957 if (dst_regno >= 0) { 2958 mark_reg_unknown(env, state->regs, dst_regno); 2959 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2960 } 2961 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2962 return 0; 2963 } 2964 for (i = 1; i < BPF_REG_SIZE; i++) { 2965 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 2966 verbose(env, "corrupted spill memory\n"); 2967 return -EACCES; 2968 } 2969 } 2970 2971 if (dst_regno >= 0) { 2972 /* restore register state from stack */ 2973 state->regs[dst_regno] = *reg; 2974 /* mark reg as written since spilled pointer state likely 2975 * has its liveness marks cleared by is_state_visited() 2976 * which resets stack/reg liveness for state transitions 2977 */ 2978 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2979 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 2980 /* If dst_regno==-1, the caller is asking us whether 2981 * it is acceptable to use this value as a SCALAR_VALUE 2982 * (e.g. for XADD). 2983 * We must not allow unprivileged callers to do that 2984 * with spilled pointers. 2985 */ 2986 verbose(env, "leaking pointer from stack off %d\n", 2987 off); 2988 return -EACCES; 2989 } 2990 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2991 } else { 2992 u8 type; 2993 2994 for (i = 0; i < size; i++) { 2995 type = stype[(slot - i) % BPF_REG_SIZE]; 2996 if (type == STACK_MISC) 2997 continue; 2998 if (type == STACK_ZERO) 2999 continue; 3000 verbose(env, "invalid read from stack off %d+%d size %d\n", 3001 off, i, size); 3002 return -EACCES; 3003 } 3004 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3005 if (dst_regno >= 0) 3006 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3007 } 3008 return 0; 3009 } 3010 3011 enum stack_access_src { 3012 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3013 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3014 }; 3015 3016 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3017 int regno, int off, int access_size, 3018 bool zero_size_allowed, 3019 enum stack_access_src type, 3020 struct bpf_call_arg_meta *meta); 3021 3022 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3023 { 3024 return cur_regs(env) + regno; 3025 } 3026 3027 /* Read the stack at 'ptr_regno + off' and put the result into the register 3028 * 'dst_regno'. 3029 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3030 * but not its variable offset. 3031 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3032 * 3033 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3034 * filling registers (i.e. reads of spilled register cannot be detected when 3035 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3036 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3037 * offset; for a fixed offset check_stack_read_fixed_off should be used 3038 * instead. 3039 */ 3040 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3041 int ptr_regno, int off, int size, int dst_regno) 3042 { 3043 /* The state of the source register. */ 3044 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3045 struct bpf_func_state *ptr_state = func(env, reg); 3046 int err; 3047 int min_off, max_off; 3048 3049 /* Note that we pass a NULL meta, so raw access will not be permitted. 3050 */ 3051 err = check_stack_range_initialized(env, ptr_regno, off, size, 3052 false, ACCESS_DIRECT, NULL); 3053 if (err) 3054 return err; 3055 3056 min_off = reg->smin_value + off; 3057 max_off = reg->smax_value + off; 3058 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3059 return 0; 3060 } 3061 3062 /* check_stack_read dispatches to check_stack_read_fixed_off or 3063 * check_stack_read_var_off. 3064 * 3065 * The caller must ensure that the offset falls within the allocated stack 3066 * bounds. 3067 * 3068 * 'dst_regno' is a register which will receive the value from the stack. It 3069 * can be -1, meaning that the read value is not going to a register. 3070 */ 3071 static int check_stack_read(struct bpf_verifier_env *env, 3072 int ptr_regno, int off, int size, 3073 int dst_regno) 3074 { 3075 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3076 struct bpf_func_state *state = func(env, reg); 3077 int err; 3078 /* Some accesses are only permitted with a static offset. */ 3079 bool var_off = !tnum_is_const(reg->var_off); 3080 3081 /* The offset is required to be static when reads don't go to a 3082 * register, in order to not leak pointers (see 3083 * check_stack_read_fixed_off). 3084 */ 3085 if (dst_regno < 0 && var_off) { 3086 char tn_buf[48]; 3087 3088 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3089 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3090 tn_buf, off, size); 3091 return -EACCES; 3092 } 3093 /* Variable offset is prohibited for unprivileged mode for simplicity 3094 * since it requires corresponding support in Spectre masking for stack 3095 * ALU. See also retrieve_ptr_limit(). 3096 */ 3097 if (!env->bypass_spec_v1 && var_off) { 3098 char tn_buf[48]; 3099 3100 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3101 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3102 ptr_regno, tn_buf); 3103 return -EACCES; 3104 } 3105 3106 if (!var_off) { 3107 off += reg->var_off.value; 3108 err = check_stack_read_fixed_off(env, state, off, size, 3109 dst_regno); 3110 } else { 3111 /* Variable offset stack reads need more conservative handling 3112 * than fixed offset ones. Note that dst_regno >= 0 on this 3113 * branch. 3114 */ 3115 err = check_stack_read_var_off(env, ptr_regno, off, size, 3116 dst_regno); 3117 } 3118 return err; 3119 } 3120 3121 3122 /* check_stack_write dispatches to check_stack_write_fixed_off or 3123 * check_stack_write_var_off. 3124 * 3125 * 'ptr_regno' is the register used as a pointer into the stack. 3126 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 3127 * 'value_regno' is the register whose value we're writing to the stack. It can 3128 * be -1, meaning that we're not writing from a register. 3129 * 3130 * The caller must ensure that the offset falls within the maximum stack size. 3131 */ 3132 static int check_stack_write(struct bpf_verifier_env *env, 3133 int ptr_regno, int off, int size, 3134 int value_regno, int insn_idx) 3135 { 3136 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3137 struct bpf_func_state *state = func(env, reg); 3138 int err; 3139 3140 if (tnum_is_const(reg->var_off)) { 3141 off += reg->var_off.value; 3142 err = check_stack_write_fixed_off(env, state, off, size, 3143 value_regno, insn_idx); 3144 } else { 3145 /* Variable offset stack reads need more conservative handling 3146 * than fixed offset ones. 3147 */ 3148 err = check_stack_write_var_off(env, state, 3149 ptr_regno, off, size, 3150 value_regno, insn_idx); 3151 } 3152 return err; 3153 } 3154 3155 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 3156 int off, int size, enum bpf_access_type type) 3157 { 3158 struct bpf_reg_state *regs = cur_regs(env); 3159 struct bpf_map *map = regs[regno].map_ptr; 3160 u32 cap = bpf_map_flags_to_cap(map); 3161 3162 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 3163 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 3164 map->value_size, off, size); 3165 return -EACCES; 3166 } 3167 3168 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 3169 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 3170 map->value_size, off, size); 3171 return -EACCES; 3172 } 3173 3174 return 0; 3175 } 3176 3177 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 3178 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 3179 int off, int size, u32 mem_size, 3180 bool zero_size_allowed) 3181 { 3182 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 3183 struct bpf_reg_state *reg; 3184 3185 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 3186 return 0; 3187 3188 reg = &cur_regs(env)[regno]; 3189 switch (reg->type) { 3190 case PTR_TO_MAP_KEY: 3191 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 3192 mem_size, off, size); 3193 break; 3194 case PTR_TO_MAP_VALUE: 3195 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 3196 mem_size, off, size); 3197 break; 3198 case PTR_TO_PACKET: 3199 case PTR_TO_PACKET_META: 3200 case PTR_TO_PACKET_END: 3201 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 3202 off, size, regno, reg->id, off, mem_size); 3203 break; 3204 case PTR_TO_MEM: 3205 default: 3206 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 3207 mem_size, off, size); 3208 } 3209 3210 return -EACCES; 3211 } 3212 3213 /* check read/write into a memory region with possible variable offset */ 3214 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 3215 int off, int size, u32 mem_size, 3216 bool zero_size_allowed) 3217 { 3218 struct bpf_verifier_state *vstate = env->cur_state; 3219 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3220 struct bpf_reg_state *reg = &state->regs[regno]; 3221 int err; 3222 3223 /* We may have adjusted the register pointing to memory region, so we 3224 * need to try adding each of min_value and max_value to off 3225 * to make sure our theoretical access will be safe. 3226 */ 3227 if (env->log.level & BPF_LOG_LEVEL) 3228 print_verifier_state(env, state); 3229 3230 /* The minimum value is only important with signed 3231 * comparisons where we can't assume the floor of a 3232 * value is 0. If we are using signed variables for our 3233 * index'es we need to make sure that whatever we use 3234 * will have a set floor within our range. 3235 */ 3236 if (reg->smin_value < 0 && 3237 (reg->smin_value == S64_MIN || 3238 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 3239 reg->smin_value + off < 0)) { 3240 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3241 regno); 3242 return -EACCES; 3243 } 3244 err = __check_mem_access(env, regno, reg->smin_value + off, size, 3245 mem_size, zero_size_allowed); 3246 if (err) { 3247 verbose(env, "R%d min value is outside of the allowed memory range\n", 3248 regno); 3249 return err; 3250 } 3251 3252 /* If we haven't set a max value then we need to bail since we can't be 3253 * sure we won't do bad things. 3254 * If reg->umax_value + off could overflow, treat that as unbounded too. 3255 */ 3256 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 3257 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 3258 regno); 3259 return -EACCES; 3260 } 3261 err = __check_mem_access(env, regno, reg->umax_value + off, size, 3262 mem_size, zero_size_allowed); 3263 if (err) { 3264 verbose(env, "R%d max value is outside of the allowed memory range\n", 3265 regno); 3266 return err; 3267 } 3268 3269 return 0; 3270 } 3271 3272 /* check read/write into a map element with possible variable offset */ 3273 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 3274 int off, int size, bool zero_size_allowed) 3275 { 3276 struct bpf_verifier_state *vstate = env->cur_state; 3277 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3278 struct bpf_reg_state *reg = &state->regs[regno]; 3279 struct bpf_map *map = reg->map_ptr; 3280 int err; 3281 3282 err = check_mem_region_access(env, regno, off, size, map->value_size, 3283 zero_size_allowed); 3284 if (err) 3285 return err; 3286 3287 if (map_value_has_spin_lock(map)) { 3288 u32 lock = map->spin_lock_off; 3289 3290 /* if any part of struct bpf_spin_lock can be touched by 3291 * load/store reject this program. 3292 * To check that [x1, x2) overlaps with [y1, y2) 3293 * it is sufficient to check x1 < y2 && y1 < x2. 3294 */ 3295 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 3296 lock < reg->umax_value + off + size) { 3297 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 3298 return -EACCES; 3299 } 3300 } 3301 if (map_value_has_timer(map)) { 3302 u32 t = map->timer_off; 3303 3304 if (reg->smin_value + off < t + sizeof(struct bpf_timer) && 3305 t < reg->umax_value + off + size) { 3306 verbose(env, "bpf_timer cannot be accessed directly by load/store\n"); 3307 return -EACCES; 3308 } 3309 } 3310 return err; 3311 } 3312 3313 #define MAX_PACKET_OFF 0xffff 3314 3315 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog) 3316 { 3317 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type; 3318 } 3319 3320 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 3321 const struct bpf_call_arg_meta *meta, 3322 enum bpf_access_type t) 3323 { 3324 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 3325 3326 switch (prog_type) { 3327 /* Program types only with direct read access go here! */ 3328 case BPF_PROG_TYPE_LWT_IN: 3329 case BPF_PROG_TYPE_LWT_OUT: 3330 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 3331 case BPF_PROG_TYPE_SK_REUSEPORT: 3332 case BPF_PROG_TYPE_FLOW_DISSECTOR: 3333 case BPF_PROG_TYPE_CGROUP_SKB: 3334 if (t == BPF_WRITE) 3335 return false; 3336 fallthrough; 3337 3338 /* Program types with direct read + write access go here! */ 3339 case BPF_PROG_TYPE_SCHED_CLS: 3340 case BPF_PROG_TYPE_SCHED_ACT: 3341 case BPF_PROG_TYPE_XDP: 3342 case BPF_PROG_TYPE_LWT_XMIT: 3343 case BPF_PROG_TYPE_SK_SKB: 3344 case BPF_PROG_TYPE_SK_MSG: 3345 if (meta) 3346 return meta->pkt_access; 3347 3348 env->seen_direct_write = true; 3349 return true; 3350 3351 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 3352 if (t == BPF_WRITE) 3353 env->seen_direct_write = true; 3354 3355 return true; 3356 3357 default: 3358 return false; 3359 } 3360 } 3361 3362 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 3363 int size, bool zero_size_allowed) 3364 { 3365 struct bpf_reg_state *regs = cur_regs(env); 3366 struct bpf_reg_state *reg = ®s[regno]; 3367 int err; 3368 3369 /* We may have added a variable offset to the packet pointer; but any 3370 * reg->range we have comes after that. We are only checking the fixed 3371 * offset. 3372 */ 3373 3374 /* We don't allow negative numbers, because we aren't tracking enough 3375 * detail to prove they're safe. 3376 */ 3377 if (reg->smin_value < 0) { 3378 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3379 regno); 3380 return -EACCES; 3381 } 3382 3383 err = reg->range < 0 ? -EINVAL : 3384 __check_mem_access(env, regno, off, size, reg->range, 3385 zero_size_allowed); 3386 if (err) { 3387 verbose(env, "R%d offset is outside of the packet\n", regno); 3388 return err; 3389 } 3390 3391 /* __check_mem_access has made sure "off + size - 1" is within u16. 3392 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 3393 * otherwise find_good_pkt_pointers would have refused to set range info 3394 * that __check_mem_access would have rejected this pkt access. 3395 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 3396 */ 3397 env->prog->aux->max_pkt_offset = 3398 max_t(u32, env->prog->aux->max_pkt_offset, 3399 off + reg->umax_value + size - 1); 3400 3401 return err; 3402 } 3403 3404 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 3405 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 3406 enum bpf_access_type t, enum bpf_reg_type *reg_type, 3407 struct btf **btf, u32 *btf_id) 3408 { 3409 struct bpf_insn_access_aux info = { 3410 .reg_type = *reg_type, 3411 .log = &env->log, 3412 }; 3413 3414 if (env->ops->is_valid_access && 3415 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 3416 /* A non zero info.ctx_field_size indicates that this field is a 3417 * candidate for later verifier transformation to load the whole 3418 * field and then apply a mask when accessed with a narrower 3419 * access than actual ctx access size. A zero info.ctx_field_size 3420 * will only allow for whole field access and rejects any other 3421 * type of narrower access. 3422 */ 3423 *reg_type = info.reg_type; 3424 3425 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) { 3426 *btf = info.btf; 3427 *btf_id = info.btf_id; 3428 } else { 3429 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 3430 } 3431 /* remember the offset of last byte accessed in ctx */ 3432 if (env->prog->aux->max_ctx_offset < off + size) 3433 env->prog->aux->max_ctx_offset = off + size; 3434 return 0; 3435 } 3436 3437 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 3438 return -EACCES; 3439 } 3440 3441 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 3442 int size) 3443 { 3444 if (size < 0 || off < 0 || 3445 (u64)off + size > sizeof(struct bpf_flow_keys)) { 3446 verbose(env, "invalid access to flow keys off=%d size=%d\n", 3447 off, size); 3448 return -EACCES; 3449 } 3450 return 0; 3451 } 3452 3453 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 3454 u32 regno, int off, int size, 3455 enum bpf_access_type t) 3456 { 3457 struct bpf_reg_state *regs = cur_regs(env); 3458 struct bpf_reg_state *reg = ®s[regno]; 3459 struct bpf_insn_access_aux info = {}; 3460 bool valid; 3461 3462 if (reg->smin_value < 0) { 3463 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3464 regno); 3465 return -EACCES; 3466 } 3467 3468 switch (reg->type) { 3469 case PTR_TO_SOCK_COMMON: 3470 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 3471 break; 3472 case PTR_TO_SOCKET: 3473 valid = bpf_sock_is_valid_access(off, size, t, &info); 3474 break; 3475 case PTR_TO_TCP_SOCK: 3476 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 3477 break; 3478 case PTR_TO_XDP_SOCK: 3479 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 3480 break; 3481 default: 3482 valid = false; 3483 } 3484 3485 3486 if (valid) { 3487 env->insn_aux_data[insn_idx].ctx_field_size = 3488 info.ctx_field_size; 3489 return 0; 3490 } 3491 3492 verbose(env, "R%d invalid %s access off=%d size=%d\n", 3493 regno, reg_type_str[reg->type], off, size); 3494 3495 return -EACCES; 3496 } 3497 3498 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 3499 { 3500 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 3501 } 3502 3503 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 3504 { 3505 const struct bpf_reg_state *reg = reg_state(env, regno); 3506 3507 return reg->type == PTR_TO_CTX; 3508 } 3509 3510 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 3511 { 3512 const struct bpf_reg_state *reg = reg_state(env, regno); 3513 3514 return type_is_sk_pointer(reg->type); 3515 } 3516 3517 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 3518 { 3519 const struct bpf_reg_state *reg = reg_state(env, regno); 3520 3521 return type_is_pkt_pointer(reg->type); 3522 } 3523 3524 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 3525 { 3526 const struct bpf_reg_state *reg = reg_state(env, regno); 3527 3528 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 3529 return reg->type == PTR_TO_FLOW_KEYS; 3530 } 3531 3532 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 3533 const struct bpf_reg_state *reg, 3534 int off, int size, bool strict) 3535 { 3536 struct tnum reg_off; 3537 int ip_align; 3538 3539 /* Byte size accesses are always allowed. */ 3540 if (!strict || size == 1) 3541 return 0; 3542 3543 /* For platforms that do not have a Kconfig enabling 3544 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 3545 * NET_IP_ALIGN is universally set to '2'. And on platforms 3546 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 3547 * to this code only in strict mode where we want to emulate 3548 * the NET_IP_ALIGN==2 checking. Therefore use an 3549 * unconditional IP align value of '2'. 3550 */ 3551 ip_align = 2; 3552 3553 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 3554 if (!tnum_is_aligned(reg_off, size)) { 3555 char tn_buf[48]; 3556 3557 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3558 verbose(env, 3559 "misaligned packet access off %d+%s+%d+%d size %d\n", 3560 ip_align, tn_buf, reg->off, off, size); 3561 return -EACCES; 3562 } 3563 3564 return 0; 3565 } 3566 3567 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 3568 const struct bpf_reg_state *reg, 3569 const char *pointer_desc, 3570 int off, int size, bool strict) 3571 { 3572 struct tnum reg_off; 3573 3574 /* Byte size accesses are always allowed. */ 3575 if (!strict || size == 1) 3576 return 0; 3577 3578 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 3579 if (!tnum_is_aligned(reg_off, size)) { 3580 char tn_buf[48]; 3581 3582 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3583 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 3584 pointer_desc, tn_buf, reg->off, off, size); 3585 return -EACCES; 3586 } 3587 3588 return 0; 3589 } 3590 3591 static int check_ptr_alignment(struct bpf_verifier_env *env, 3592 const struct bpf_reg_state *reg, int off, 3593 int size, bool strict_alignment_once) 3594 { 3595 bool strict = env->strict_alignment || strict_alignment_once; 3596 const char *pointer_desc = ""; 3597 3598 switch (reg->type) { 3599 case PTR_TO_PACKET: 3600 case PTR_TO_PACKET_META: 3601 /* Special case, because of NET_IP_ALIGN. Given metadata sits 3602 * right in front, treat it the very same way. 3603 */ 3604 return check_pkt_ptr_alignment(env, reg, off, size, strict); 3605 case PTR_TO_FLOW_KEYS: 3606 pointer_desc = "flow keys "; 3607 break; 3608 case PTR_TO_MAP_KEY: 3609 pointer_desc = "key "; 3610 break; 3611 case PTR_TO_MAP_VALUE: 3612 pointer_desc = "value "; 3613 break; 3614 case PTR_TO_CTX: 3615 pointer_desc = "context "; 3616 break; 3617 case PTR_TO_STACK: 3618 pointer_desc = "stack "; 3619 /* The stack spill tracking logic in check_stack_write_fixed_off() 3620 * and check_stack_read_fixed_off() relies on stack accesses being 3621 * aligned. 3622 */ 3623 strict = true; 3624 break; 3625 case PTR_TO_SOCKET: 3626 pointer_desc = "sock "; 3627 break; 3628 case PTR_TO_SOCK_COMMON: 3629 pointer_desc = "sock_common "; 3630 break; 3631 case PTR_TO_TCP_SOCK: 3632 pointer_desc = "tcp_sock "; 3633 break; 3634 case PTR_TO_XDP_SOCK: 3635 pointer_desc = "xdp_sock "; 3636 break; 3637 default: 3638 break; 3639 } 3640 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 3641 strict); 3642 } 3643 3644 static int update_stack_depth(struct bpf_verifier_env *env, 3645 const struct bpf_func_state *func, 3646 int off) 3647 { 3648 u16 stack = env->subprog_info[func->subprogno].stack_depth; 3649 3650 if (stack >= -off) 3651 return 0; 3652 3653 /* update known max for given subprogram */ 3654 env->subprog_info[func->subprogno].stack_depth = -off; 3655 return 0; 3656 } 3657 3658 /* starting from main bpf function walk all instructions of the function 3659 * and recursively walk all callees that given function can call. 3660 * Ignore jump and exit insns. 3661 * Since recursion is prevented by check_cfg() this algorithm 3662 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 3663 */ 3664 static int check_max_stack_depth(struct bpf_verifier_env *env) 3665 { 3666 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 3667 struct bpf_subprog_info *subprog = env->subprog_info; 3668 struct bpf_insn *insn = env->prog->insnsi; 3669 bool tail_call_reachable = false; 3670 int ret_insn[MAX_CALL_FRAMES]; 3671 int ret_prog[MAX_CALL_FRAMES]; 3672 int j; 3673 3674 process_func: 3675 /* protect against potential stack overflow that might happen when 3676 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 3677 * depth for such case down to 256 so that the worst case scenario 3678 * would result in 8k stack size (32 which is tailcall limit * 256 = 3679 * 8k). 3680 * 3681 * To get the idea what might happen, see an example: 3682 * func1 -> sub rsp, 128 3683 * subfunc1 -> sub rsp, 256 3684 * tailcall1 -> add rsp, 256 3685 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 3686 * subfunc2 -> sub rsp, 64 3687 * subfunc22 -> sub rsp, 128 3688 * tailcall2 -> add rsp, 128 3689 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 3690 * 3691 * tailcall will unwind the current stack frame but it will not get rid 3692 * of caller's stack as shown on the example above. 3693 */ 3694 if (idx && subprog[idx].has_tail_call && depth >= 256) { 3695 verbose(env, 3696 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 3697 depth); 3698 return -EACCES; 3699 } 3700 /* round up to 32-bytes, since this is granularity 3701 * of interpreter stack size 3702 */ 3703 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3704 if (depth > MAX_BPF_STACK) { 3705 verbose(env, "combined stack size of %d calls is %d. Too large\n", 3706 frame + 1, depth); 3707 return -EACCES; 3708 } 3709 continue_func: 3710 subprog_end = subprog[idx + 1].start; 3711 for (; i < subprog_end; i++) { 3712 int next_insn; 3713 3714 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 3715 continue; 3716 /* remember insn and function to return to */ 3717 ret_insn[frame] = i + 1; 3718 ret_prog[frame] = idx; 3719 3720 /* find the callee */ 3721 next_insn = i + insn[i].imm + 1; 3722 idx = find_subprog(env, next_insn); 3723 if (idx < 0) { 3724 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3725 next_insn); 3726 return -EFAULT; 3727 } 3728 if (subprog[idx].is_async_cb) { 3729 if (subprog[idx].has_tail_call) { 3730 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 3731 return -EFAULT; 3732 } 3733 /* async callbacks don't increase bpf prog stack size */ 3734 continue; 3735 } 3736 i = next_insn; 3737 3738 if (subprog[idx].has_tail_call) 3739 tail_call_reachable = true; 3740 3741 frame++; 3742 if (frame >= MAX_CALL_FRAMES) { 3743 verbose(env, "the call stack of %d frames is too deep !\n", 3744 frame); 3745 return -E2BIG; 3746 } 3747 goto process_func; 3748 } 3749 /* if tail call got detected across bpf2bpf calls then mark each of the 3750 * currently present subprog frames as tail call reachable subprogs; 3751 * this info will be utilized by JIT so that we will be preserving the 3752 * tail call counter throughout bpf2bpf calls combined with tailcalls 3753 */ 3754 if (tail_call_reachable) 3755 for (j = 0; j < frame; j++) 3756 subprog[ret_prog[j]].tail_call_reachable = true; 3757 3758 /* end of for() loop means the last insn of the 'subprog' 3759 * was reached. Doesn't matter whether it was JA or EXIT 3760 */ 3761 if (frame == 0) 3762 return 0; 3763 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3764 frame--; 3765 i = ret_insn[frame]; 3766 idx = ret_prog[frame]; 3767 goto continue_func; 3768 } 3769 3770 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 3771 static int get_callee_stack_depth(struct bpf_verifier_env *env, 3772 const struct bpf_insn *insn, int idx) 3773 { 3774 int start = idx + insn->imm + 1, subprog; 3775 3776 subprog = find_subprog(env, start); 3777 if (subprog < 0) { 3778 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3779 start); 3780 return -EFAULT; 3781 } 3782 return env->subprog_info[subprog].stack_depth; 3783 } 3784 #endif 3785 3786 int check_ctx_reg(struct bpf_verifier_env *env, 3787 const struct bpf_reg_state *reg, int regno) 3788 { 3789 /* Access to ctx or passing it to a helper is only allowed in 3790 * its original, unmodified form. 3791 */ 3792 3793 if (reg->off) { 3794 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 3795 regno, reg->off); 3796 return -EACCES; 3797 } 3798 3799 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3800 char tn_buf[48]; 3801 3802 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3803 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3804 return -EACCES; 3805 } 3806 3807 return 0; 3808 } 3809 3810 static int __check_buffer_access(struct bpf_verifier_env *env, 3811 const char *buf_info, 3812 const struct bpf_reg_state *reg, 3813 int regno, int off, int size) 3814 { 3815 if (off < 0) { 3816 verbose(env, 3817 "R%d invalid %s buffer access: off=%d, size=%d\n", 3818 regno, buf_info, off, size); 3819 return -EACCES; 3820 } 3821 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3822 char tn_buf[48]; 3823 3824 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3825 verbose(env, 3826 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 3827 regno, off, tn_buf); 3828 return -EACCES; 3829 } 3830 3831 return 0; 3832 } 3833 3834 static int check_tp_buffer_access(struct bpf_verifier_env *env, 3835 const struct bpf_reg_state *reg, 3836 int regno, int off, int size) 3837 { 3838 int err; 3839 3840 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 3841 if (err) 3842 return err; 3843 3844 if (off + size > env->prog->aux->max_tp_access) 3845 env->prog->aux->max_tp_access = off + size; 3846 3847 return 0; 3848 } 3849 3850 static int check_buffer_access(struct bpf_verifier_env *env, 3851 const struct bpf_reg_state *reg, 3852 int regno, int off, int size, 3853 bool zero_size_allowed, 3854 const char *buf_info, 3855 u32 *max_access) 3856 { 3857 int err; 3858 3859 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 3860 if (err) 3861 return err; 3862 3863 if (off + size > *max_access) 3864 *max_access = off + size; 3865 3866 return 0; 3867 } 3868 3869 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 3870 static void zext_32_to_64(struct bpf_reg_state *reg) 3871 { 3872 reg->var_off = tnum_subreg(reg->var_off); 3873 __reg_assign_32_into_64(reg); 3874 } 3875 3876 /* truncate register to smaller size (in bytes) 3877 * must be called with size < BPF_REG_SIZE 3878 */ 3879 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 3880 { 3881 u64 mask; 3882 3883 /* clear high bits in bit representation */ 3884 reg->var_off = tnum_cast(reg->var_off, size); 3885 3886 /* fix arithmetic bounds */ 3887 mask = ((u64)1 << (size * 8)) - 1; 3888 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 3889 reg->umin_value &= mask; 3890 reg->umax_value &= mask; 3891 } else { 3892 reg->umin_value = 0; 3893 reg->umax_value = mask; 3894 } 3895 reg->smin_value = reg->umin_value; 3896 reg->smax_value = reg->umax_value; 3897 3898 /* If size is smaller than 32bit register the 32bit register 3899 * values are also truncated so we push 64-bit bounds into 3900 * 32-bit bounds. Above were truncated < 32-bits already. 3901 */ 3902 if (size >= 4) 3903 return; 3904 __reg_combine_64_into_32(reg); 3905 } 3906 3907 static bool bpf_map_is_rdonly(const struct bpf_map *map) 3908 { 3909 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; 3910 } 3911 3912 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 3913 { 3914 void *ptr; 3915 u64 addr; 3916 int err; 3917 3918 err = map->ops->map_direct_value_addr(map, &addr, off); 3919 if (err) 3920 return err; 3921 ptr = (void *)(long)addr + off; 3922 3923 switch (size) { 3924 case sizeof(u8): 3925 *val = (u64)*(u8 *)ptr; 3926 break; 3927 case sizeof(u16): 3928 *val = (u64)*(u16 *)ptr; 3929 break; 3930 case sizeof(u32): 3931 *val = (u64)*(u32 *)ptr; 3932 break; 3933 case sizeof(u64): 3934 *val = *(u64 *)ptr; 3935 break; 3936 default: 3937 return -EINVAL; 3938 } 3939 return 0; 3940 } 3941 3942 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 3943 struct bpf_reg_state *regs, 3944 int regno, int off, int size, 3945 enum bpf_access_type atype, 3946 int value_regno) 3947 { 3948 struct bpf_reg_state *reg = regs + regno; 3949 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 3950 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 3951 u32 btf_id; 3952 int ret; 3953 3954 if (off < 0) { 3955 verbose(env, 3956 "R%d is ptr_%s invalid negative access: off=%d\n", 3957 regno, tname, off); 3958 return -EACCES; 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, 3965 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 3966 regno, tname, off, tn_buf); 3967 return -EACCES; 3968 } 3969 3970 if (env->ops->btf_struct_access) { 3971 ret = env->ops->btf_struct_access(&env->log, reg->btf, t, 3972 off, size, atype, &btf_id); 3973 } else { 3974 if (atype != BPF_READ) { 3975 verbose(env, "only read is supported\n"); 3976 return -EACCES; 3977 } 3978 3979 ret = btf_struct_access(&env->log, reg->btf, t, off, size, 3980 atype, &btf_id); 3981 } 3982 3983 if (ret < 0) 3984 return ret; 3985 3986 if (atype == BPF_READ && value_regno >= 0) 3987 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id); 3988 3989 return 0; 3990 } 3991 3992 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 3993 struct bpf_reg_state *regs, 3994 int regno, int off, int size, 3995 enum bpf_access_type atype, 3996 int value_regno) 3997 { 3998 struct bpf_reg_state *reg = regs + regno; 3999 struct bpf_map *map = reg->map_ptr; 4000 const struct btf_type *t; 4001 const char *tname; 4002 u32 btf_id; 4003 int ret; 4004 4005 if (!btf_vmlinux) { 4006 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 4007 return -ENOTSUPP; 4008 } 4009 4010 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 4011 verbose(env, "map_ptr access not supported for map type %d\n", 4012 map->map_type); 4013 return -ENOTSUPP; 4014 } 4015 4016 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 4017 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 4018 4019 if (!env->allow_ptr_to_map_access) { 4020 verbose(env, 4021 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4022 tname); 4023 return -EPERM; 4024 } 4025 4026 if (off < 0) { 4027 verbose(env, "R%d is %s invalid negative access: off=%d\n", 4028 regno, tname, off); 4029 return -EACCES; 4030 } 4031 4032 if (atype != BPF_READ) { 4033 verbose(env, "only read from %s is supported\n", tname); 4034 return -EACCES; 4035 } 4036 4037 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id); 4038 if (ret < 0) 4039 return ret; 4040 4041 if (value_regno >= 0) 4042 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id); 4043 4044 return 0; 4045 } 4046 4047 /* Check that the stack access at the given offset is within bounds. The 4048 * maximum valid offset is -1. 4049 * 4050 * The minimum valid offset is -MAX_BPF_STACK for writes, and 4051 * -state->allocated_stack for reads. 4052 */ 4053 static int check_stack_slot_within_bounds(int off, 4054 struct bpf_func_state *state, 4055 enum bpf_access_type t) 4056 { 4057 int min_valid_off; 4058 4059 if (t == BPF_WRITE) 4060 min_valid_off = -MAX_BPF_STACK; 4061 else 4062 min_valid_off = -state->allocated_stack; 4063 4064 if (off < min_valid_off || off > -1) 4065 return -EACCES; 4066 return 0; 4067 } 4068 4069 /* Check that the stack access at 'regno + off' falls within the maximum stack 4070 * bounds. 4071 * 4072 * 'off' includes `regno->offset`, but not its dynamic part (if any). 4073 */ 4074 static int check_stack_access_within_bounds( 4075 struct bpf_verifier_env *env, 4076 int regno, int off, int access_size, 4077 enum stack_access_src src, enum bpf_access_type type) 4078 { 4079 struct bpf_reg_state *regs = cur_regs(env); 4080 struct bpf_reg_state *reg = regs + regno; 4081 struct bpf_func_state *state = func(env, reg); 4082 int min_off, max_off; 4083 int err; 4084 char *err_extra; 4085 4086 if (src == ACCESS_HELPER) 4087 /* We don't know if helpers are reading or writing (or both). */ 4088 err_extra = " indirect access to"; 4089 else if (type == BPF_READ) 4090 err_extra = " read from"; 4091 else 4092 err_extra = " write to"; 4093 4094 if (tnum_is_const(reg->var_off)) { 4095 min_off = reg->var_off.value + off; 4096 if (access_size > 0) 4097 max_off = min_off + access_size - 1; 4098 else 4099 max_off = min_off; 4100 } else { 4101 if (reg->smax_value >= BPF_MAX_VAR_OFF || 4102 reg->smin_value <= -BPF_MAX_VAR_OFF) { 4103 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 4104 err_extra, regno); 4105 return -EACCES; 4106 } 4107 min_off = reg->smin_value + off; 4108 if (access_size > 0) 4109 max_off = reg->smax_value + off + access_size - 1; 4110 else 4111 max_off = min_off; 4112 } 4113 4114 err = check_stack_slot_within_bounds(min_off, state, type); 4115 if (!err) 4116 err = check_stack_slot_within_bounds(max_off, state, type); 4117 4118 if (err) { 4119 if (tnum_is_const(reg->var_off)) { 4120 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 4121 err_extra, regno, off, access_size); 4122 } else { 4123 char tn_buf[48]; 4124 4125 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4126 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 4127 err_extra, regno, tn_buf, access_size); 4128 } 4129 } 4130 return err; 4131 } 4132 4133 /* check whether memory at (regno + off) is accessible for t = (read | write) 4134 * if t==write, value_regno is a register which value is stored into memory 4135 * if t==read, value_regno is a register which will receive the value from memory 4136 * if t==write && value_regno==-1, some unknown value is stored into memory 4137 * if t==read && value_regno==-1, don't care what we read from memory 4138 */ 4139 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 4140 int off, int bpf_size, enum bpf_access_type t, 4141 int value_regno, bool strict_alignment_once) 4142 { 4143 struct bpf_reg_state *regs = cur_regs(env); 4144 struct bpf_reg_state *reg = regs + regno; 4145 struct bpf_func_state *state; 4146 int size, err = 0; 4147 4148 size = bpf_size_to_bytes(bpf_size); 4149 if (size < 0) 4150 return size; 4151 4152 /* alignment checks will add in reg->off themselves */ 4153 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 4154 if (err) 4155 return err; 4156 4157 /* for access checks, reg->off is just part of off */ 4158 off += reg->off; 4159 4160 if (reg->type == PTR_TO_MAP_KEY) { 4161 if (t == BPF_WRITE) { 4162 verbose(env, "write to change key R%d not allowed\n", regno); 4163 return -EACCES; 4164 } 4165 4166 err = check_mem_region_access(env, regno, off, size, 4167 reg->map_ptr->key_size, false); 4168 if (err) 4169 return err; 4170 if (value_regno >= 0) 4171 mark_reg_unknown(env, regs, value_regno); 4172 } else if (reg->type == PTR_TO_MAP_VALUE) { 4173 if (t == BPF_WRITE && value_regno >= 0 && 4174 is_pointer_value(env, value_regno)) { 4175 verbose(env, "R%d leaks addr into map\n", value_regno); 4176 return -EACCES; 4177 } 4178 err = check_map_access_type(env, regno, off, size, t); 4179 if (err) 4180 return err; 4181 err = check_map_access(env, regno, off, size, false); 4182 if (!err && t == BPF_READ && value_regno >= 0) { 4183 struct bpf_map *map = reg->map_ptr; 4184 4185 /* if map is read-only, track its contents as scalars */ 4186 if (tnum_is_const(reg->var_off) && 4187 bpf_map_is_rdonly(map) && 4188 map->ops->map_direct_value_addr) { 4189 int map_off = off + reg->var_off.value; 4190 u64 val = 0; 4191 4192 err = bpf_map_direct_read(map, map_off, size, 4193 &val); 4194 if (err) 4195 return err; 4196 4197 regs[value_regno].type = SCALAR_VALUE; 4198 __mark_reg_known(®s[value_regno], val); 4199 } else { 4200 mark_reg_unknown(env, regs, value_regno); 4201 } 4202 } 4203 } else if (reg->type == PTR_TO_MEM) { 4204 if (t == BPF_WRITE && value_regno >= 0 && 4205 is_pointer_value(env, value_regno)) { 4206 verbose(env, "R%d leaks addr into mem\n", value_regno); 4207 return -EACCES; 4208 } 4209 err = check_mem_region_access(env, regno, off, size, 4210 reg->mem_size, false); 4211 if (!err && t == BPF_READ && value_regno >= 0) 4212 mark_reg_unknown(env, regs, value_regno); 4213 } else if (reg->type == PTR_TO_CTX) { 4214 enum bpf_reg_type reg_type = SCALAR_VALUE; 4215 struct btf *btf = NULL; 4216 u32 btf_id = 0; 4217 4218 if (t == BPF_WRITE && value_regno >= 0 && 4219 is_pointer_value(env, value_regno)) { 4220 verbose(env, "R%d leaks addr into ctx\n", value_regno); 4221 return -EACCES; 4222 } 4223 4224 err = check_ctx_reg(env, reg, regno); 4225 if (err < 0) 4226 return err; 4227 4228 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id); 4229 if (err) 4230 verbose_linfo(env, insn_idx, "; "); 4231 if (!err && t == BPF_READ && value_regno >= 0) { 4232 /* ctx access returns either a scalar, or a 4233 * PTR_TO_PACKET[_META,_END]. In the latter 4234 * case, we know the offset is zero. 4235 */ 4236 if (reg_type == SCALAR_VALUE) { 4237 mark_reg_unknown(env, regs, value_regno); 4238 } else { 4239 mark_reg_known_zero(env, regs, 4240 value_regno); 4241 if (reg_type_may_be_null(reg_type)) 4242 regs[value_regno].id = ++env->id_gen; 4243 /* A load of ctx field could have different 4244 * actual load size with the one encoded in the 4245 * insn. When the dst is PTR, it is for sure not 4246 * a sub-register. 4247 */ 4248 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 4249 if (reg_type == PTR_TO_BTF_ID || 4250 reg_type == PTR_TO_BTF_ID_OR_NULL) { 4251 regs[value_regno].btf = btf; 4252 regs[value_regno].btf_id = btf_id; 4253 } 4254 } 4255 regs[value_regno].type = reg_type; 4256 } 4257 4258 } else if (reg->type == PTR_TO_STACK) { 4259 /* Basic bounds checks. */ 4260 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 4261 if (err) 4262 return err; 4263 4264 state = func(env, reg); 4265 err = update_stack_depth(env, state, off); 4266 if (err) 4267 return err; 4268 4269 if (t == BPF_READ) 4270 err = check_stack_read(env, regno, off, size, 4271 value_regno); 4272 else 4273 err = check_stack_write(env, regno, off, size, 4274 value_regno, insn_idx); 4275 } else if (reg_is_pkt_pointer(reg)) { 4276 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 4277 verbose(env, "cannot write into packet\n"); 4278 return -EACCES; 4279 } 4280 if (t == BPF_WRITE && value_regno >= 0 && 4281 is_pointer_value(env, value_regno)) { 4282 verbose(env, "R%d leaks addr into packet\n", 4283 value_regno); 4284 return -EACCES; 4285 } 4286 err = check_packet_access(env, regno, off, size, false); 4287 if (!err && t == BPF_READ && value_regno >= 0) 4288 mark_reg_unknown(env, regs, value_regno); 4289 } else if (reg->type == PTR_TO_FLOW_KEYS) { 4290 if (t == BPF_WRITE && value_regno >= 0 && 4291 is_pointer_value(env, value_regno)) { 4292 verbose(env, "R%d leaks addr into flow keys\n", 4293 value_regno); 4294 return -EACCES; 4295 } 4296 4297 err = check_flow_keys_access(env, off, size); 4298 if (!err && t == BPF_READ && value_regno >= 0) 4299 mark_reg_unknown(env, regs, value_regno); 4300 } else if (type_is_sk_pointer(reg->type)) { 4301 if (t == BPF_WRITE) { 4302 verbose(env, "R%d cannot write into %s\n", 4303 regno, reg_type_str[reg->type]); 4304 return -EACCES; 4305 } 4306 err = check_sock_access(env, insn_idx, regno, off, size, t); 4307 if (!err && value_regno >= 0) 4308 mark_reg_unknown(env, regs, value_regno); 4309 } else if (reg->type == PTR_TO_TP_BUFFER) { 4310 err = check_tp_buffer_access(env, reg, regno, off, size); 4311 if (!err && t == BPF_READ && value_regno >= 0) 4312 mark_reg_unknown(env, regs, value_regno); 4313 } else if (reg->type == PTR_TO_BTF_ID) { 4314 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 4315 value_regno); 4316 } else if (reg->type == CONST_PTR_TO_MAP) { 4317 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 4318 value_regno); 4319 } else if (reg->type == PTR_TO_RDONLY_BUF) { 4320 if (t == BPF_WRITE) { 4321 verbose(env, "R%d cannot write into %s\n", 4322 regno, reg_type_str[reg->type]); 4323 return -EACCES; 4324 } 4325 err = check_buffer_access(env, reg, regno, off, size, false, 4326 "rdonly", 4327 &env->prog->aux->max_rdonly_access); 4328 if (!err && value_regno >= 0) 4329 mark_reg_unknown(env, regs, value_regno); 4330 } else if (reg->type == PTR_TO_RDWR_BUF) { 4331 err = check_buffer_access(env, reg, regno, off, size, false, 4332 "rdwr", 4333 &env->prog->aux->max_rdwr_access); 4334 if (!err && t == BPF_READ && value_regno >= 0) 4335 mark_reg_unknown(env, regs, value_regno); 4336 } else { 4337 verbose(env, "R%d invalid mem access '%s'\n", regno, 4338 reg_type_str[reg->type]); 4339 return -EACCES; 4340 } 4341 4342 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 4343 regs[value_regno].type == SCALAR_VALUE) { 4344 /* b/h/w load zero-extends, mark upper bits as known 0 */ 4345 coerce_reg_to_size(®s[value_regno], size); 4346 } 4347 return err; 4348 } 4349 4350 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 4351 { 4352 int load_reg; 4353 int err; 4354 4355 switch (insn->imm) { 4356 case BPF_ADD: 4357 case BPF_ADD | BPF_FETCH: 4358 case BPF_AND: 4359 case BPF_AND | BPF_FETCH: 4360 case BPF_OR: 4361 case BPF_OR | BPF_FETCH: 4362 case BPF_XOR: 4363 case BPF_XOR | BPF_FETCH: 4364 case BPF_XCHG: 4365 case BPF_CMPXCHG: 4366 break; 4367 default: 4368 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 4369 return -EINVAL; 4370 } 4371 4372 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 4373 verbose(env, "invalid atomic operand size\n"); 4374 return -EINVAL; 4375 } 4376 4377 /* check src1 operand */ 4378 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4379 if (err) 4380 return err; 4381 4382 /* check src2 operand */ 4383 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4384 if (err) 4385 return err; 4386 4387 if (insn->imm == BPF_CMPXCHG) { 4388 /* Check comparison of R0 with memory location */ 4389 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 4390 if (err) 4391 return err; 4392 } 4393 4394 if (is_pointer_value(env, insn->src_reg)) { 4395 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 4396 return -EACCES; 4397 } 4398 4399 if (is_ctx_reg(env, insn->dst_reg) || 4400 is_pkt_reg(env, insn->dst_reg) || 4401 is_flow_key_reg(env, insn->dst_reg) || 4402 is_sk_reg(env, insn->dst_reg)) { 4403 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 4404 insn->dst_reg, 4405 reg_type_str[reg_state(env, insn->dst_reg)->type]); 4406 return -EACCES; 4407 } 4408 4409 if (insn->imm & BPF_FETCH) { 4410 if (insn->imm == BPF_CMPXCHG) 4411 load_reg = BPF_REG_0; 4412 else 4413 load_reg = insn->src_reg; 4414 4415 /* check and record load of old value */ 4416 err = check_reg_arg(env, load_reg, DST_OP); 4417 if (err) 4418 return err; 4419 } else { 4420 /* This instruction accesses a memory location but doesn't 4421 * actually load it into a register. 4422 */ 4423 load_reg = -1; 4424 } 4425 4426 /* check whether we can read the memory */ 4427 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4428 BPF_SIZE(insn->code), BPF_READ, load_reg, true); 4429 if (err) 4430 return err; 4431 4432 /* check whether we can write into the same memory */ 4433 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4434 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 4435 if (err) 4436 return err; 4437 4438 return 0; 4439 } 4440 4441 /* When register 'regno' is used to read the stack (either directly or through 4442 * a helper function) make sure that it's within stack boundary and, depending 4443 * on the access type, that all elements of the stack are initialized. 4444 * 4445 * 'off' includes 'regno->off', but not its dynamic part (if any). 4446 * 4447 * All registers that have been spilled on the stack in the slots within the 4448 * read offsets are marked as read. 4449 */ 4450 static int check_stack_range_initialized( 4451 struct bpf_verifier_env *env, int regno, int off, 4452 int access_size, bool zero_size_allowed, 4453 enum stack_access_src type, struct bpf_call_arg_meta *meta) 4454 { 4455 struct bpf_reg_state *reg = reg_state(env, regno); 4456 struct bpf_func_state *state = func(env, reg); 4457 int err, min_off, max_off, i, j, slot, spi; 4458 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 4459 enum bpf_access_type bounds_check_type; 4460 /* Some accesses can write anything into the stack, others are 4461 * read-only. 4462 */ 4463 bool clobber = false; 4464 4465 if (access_size == 0 && !zero_size_allowed) { 4466 verbose(env, "invalid zero-sized read\n"); 4467 return -EACCES; 4468 } 4469 4470 if (type == ACCESS_HELPER) { 4471 /* The bounds checks for writes are more permissive than for 4472 * reads. However, if raw_mode is not set, we'll do extra 4473 * checks below. 4474 */ 4475 bounds_check_type = BPF_WRITE; 4476 clobber = true; 4477 } else { 4478 bounds_check_type = BPF_READ; 4479 } 4480 err = check_stack_access_within_bounds(env, regno, off, access_size, 4481 type, bounds_check_type); 4482 if (err) 4483 return err; 4484 4485 4486 if (tnum_is_const(reg->var_off)) { 4487 min_off = max_off = reg->var_off.value + off; 4488 } else { 4489 /* Variable offset is prohibited for unprivileged mode for 4490 * simplicity since it requires corresponding support in 4491 * Spectre masking for stack ALU. 4492 * See also retrieve_ptr_limit(). 4493 */ 4494 if (!env->bypass_spec_v1) { 4495 char tn_buf[48]; 4496 4497 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4498 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 4499 regno, err_extra, tn_buf); 4500 return -EACCES; 4501 } 4502 /* Only initialized buffer on stack is allowed to be accessed 4503 * with variable offset. With uninitialized buffer it's hard to 4504 * guarantee that whole memory is marked as initialized on 4505 * helper return since specific bounds are unknown what may 4506 * cause uninitialized stack leaking. 4507 */ 4508 if (meta && meta->raw_mode) 4509 meta = NULL; 4510 4511 min_off = reg->smin_value + off; 4512 max_off = reg->smax_value + off; 4513 } 4514 4515 if (meta && meta->raw_mode) { 4516 meta->access_size = access_size; 4517 meta->regno = regno; 4518 return 0; 4519 } 4520 4521 for (i = min_off; i < max_off + access_size; i++) { 4522 u8 *stype; 4523 4524 slot = -i - 1; 4525 spi = slot / BPF_REG_SIZE; 4526 if (state->allocated_stack <= slot) 4527 goto err; 4528 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4529 if (*stype == STACK_MISC) 4530 goto mark; 4531 if (*stype == STACK_ZERO) { 4532 if (clobber) { 4533 /* helper can write anything into the stack */ 4534 *stype = STACK_MISC; 4535 } 4536 goto mark; 4537 } 4538 4539 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4540 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 4541 goto mark; 4542 4543 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4544 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 4545 env->allow_ptr_leaks)) { 4546 if (clobber) { 4547 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 4548 for (j = 0; j < BPF_REG_SIZE; j++) 4549 state->stack[spi].slot_type[j] = STACK_MISC; 4550 } 4551 goto mark; 4552 } 4553 4554 err: 4555 if (tnum_is_const(reg->var_off)) { 4556 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 4557 err_extra, regno, min_off, i - min_off, access_size); 4558 } else { 4559 char tn_buf[48]; 4560 4561 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4562 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 4563 err_extra, regno, tn_buf, i - min_off, access_size); 4564 } 4565 return -EACCES; 4566 mark: 4567 /* reading any byte out of 8-byte 'spill_slot' will cause 4568 * the whole slot to be marked as 'read' 4569 */ 4570 mark_reg_read(env, &state->stack[spi].spilled_ptr, 4571 state->stack[spi].spilled_ptr.parent, 4572 REG_LIVE_READ64); 4573 } 4574 return update_stack_depth(env, state, min_off); 4575 } 4576 4577 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 4578 int access_size, bool zero_size_allowed, 4579 struct bpf_call_arg_meta *meta) 4580 { 4581 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4582 4583 switch (reg->type) { 4584 case PTR_TO_PACKET: 4585 case PTR_TO_PACKET_META: 4586 return check_packet_access(env, regno, reg->off, access_size, 4587 zero_size_allowed); 4588 case PTR_TO_MAP_KEY: 4589 return check_mem_region_access(env, regno, reg->off, access_size, 4590 reg->map_ptr->key_size, false); 4591 case PTR_TO_MAP_VALUE: 4592 if (check_map_access_type(env, regno, reg->off, access_size, 4593 meta && meta->raw_mode ? BPF_WRITE : 4594 BPF_READ)) 4595 return -EACCES; 4596 return check_map_access(env, regno, reg->off, access_size, 4597 zero_size_allowed); 4598 case PTR_TO_MEM: 4599 return check_mem_region_access(env, regno, reg->off, 4600 access_size, reg->mem_size, 4601 zero_size_allowed); 4602 case PTR_TO_RDONLY_BUF: 4603 if (meta && meta->raw_mode) 4604 return -EACCES; 4605 return check_buffer_access(env, reg, regno, reg->off, 4606 access_size, zero_size_allowed, 4607 "rdonly", 4608 &env->prog->aux->max_rdonly_access); 4609 case PTR_TO_RDWR_BUF: 4610 return check_buffer_access(env, reg, regno, reg->off, 4611 access_size, zero_size_allowed, 4612 "rdwr", 4613 &env->prog->aux->max_rdwr_access); 4614 case PTR_TO_STACK: 4615 return check_stack_range_initialized( 4616 env, 4617 regno, reg->off, access_size, 4618 zero_size_allowed, ACCESS_HELPER, meta); 4619 default: /* scalar_value or invalid ptr */ 4620 /* Allow zero-byte read from NULL, regardless of pointer type */ 4621 if (zero_size_allowed && access_size == 0 && 4622 register_is_null(reg)) 4623 return 0; 4624 4625 verbose(env, "R%d type=%s expected=%s\n", regno, 4626 reg_type_str[reg->type], 4627 reg_type_str[PTR_TO_STACK]); 4628 return -EACCES; 4629 } 4630 } 4631 4632 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4633 u32 regno, u32 mem_size) 4634 { 4635 if (register_is_null(reg)) 4636 return 0; 4637 4638 if (reg_type_may_be_null(reg->type)) { 4639 /* Assuming that the register contains a value check if the memory 4640 * access is safe. Temporarily save and restore the register's state as 4641 * the conversion shouldn't be visible to a caller. 4642 */ 4643 const struct bpf_reg_state saved_reg = *reg; 4644 int rv; 4645 4646 mark_ptr_not_null_reg(reg); 4647 rv = check_helper_mem_access(env, regno, mem_size, true, NULL); 4648 *reg = saved_reg; 4649 return rv; 4650 } 4651 4652 return check_helper_mem_access(env, regno, mem_size, true, NULL); 4653 } 4654 4655 /* Implementation details: 4656 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 4657 * Two bpf_map_lookups (even with the same key) will have different reg->id. 4658 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 4659 * value_or_null->value transition, since the verifier only cares about 4660 * the range of access to valid map value pointer and doesn't care about actual 4661 * address of the map element. 4662 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 4663 * reg->id > 0 after value_or_null->value transition. By doing so 4664 * two bpf_map_lookups will be considered two different pointers that 4665 * point to different bpf_spin_locks. 4666 * The verifier allows taking only one bpf_spin_lock at a time to avoid 4667 * dead-locks. 4668 * Since only one bpf_spin_lock is allowed the checks are simpler than 4669 * reg_is_refcounted() logic. The verifier needs to remember only 4670 * one spin_lock instead of array of acquired_refs. 4671 * cur_state->active_spin_lock remembers which map value element got locked 4672 * and clears it after bpf_spin_unlock. 4673 */ 4674 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 4675 bool is_lock) 4676 { 4677 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4678 struct bpf_verifier_state *cur = env->cur_state; 4679 bool is_const = tnum_is_const(reg->var_off); 4680 struct bpf_map *map = reg->map_ptr; 4681 u64 val = reg->var_off.value; 4682 4683 if (!is_const) { 4684 verbose(env, 4685 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 4686 regno); 4687 return -EINVAL; 4688 } 4689 if (!map->btf) { 4690 verbose(env, 4691 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 4692 map->name); 4693 return -EINVAL; 4694 } 4695 if (!map_value_has_spin_lock(map)) { 4696 if (map->spin_lock_off == -E2BIG) 4697 verbose(env, 4698 "map '%s' has more than one 'struct bpf_spin_lock'\n", 4699 map->name); 4700 else if (map->spin_lock_off == -ENOENT) 4701 verbose(env, 4702 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 4703 map->name); 4704 else 4705 verbose(env, 4706 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 4707 map->name); 4708 return -EINVAL; 4709 } 4710 if (map->spin_lock_off != val + reg->off) { 4711 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 4712 val + reg->off); 4713 return -EINVAL; 4714 } 4715 if (is_lock) { 4716 if (cur->active_spin_lock) { 4717 verbose(env, 4718 "Locking two bpf_spin_locks are not allowed\n"); 4719 return -EINVAL; 4720 } 4721 cur->active_spin_lock = reg->id; 4722 } else { 4723 if (!cur->active_spin_lock) { 4724 verbose(env, "bpf_spin_unlock without taking a lock\n"); 4725 return -EINVAL; 4726 } 4727 if (cur->active_spin_lock != reg->id) { 4728 verbose(env, "bpf_spin_unlock of different lock\n"); 4729 return -EINVAL; 4730 } 4731 cur->active_spin_lock = 0; 4732 } 4733 return 0; 4734 } 4735 4736 static int process_timer_func(struct bpf_verifier_env *env, int regno, 4737 struct bpf_call_arg_meta *meta) 4738 { 4739 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4740 bool is_const = tnum_is_const(reg->var_off); 4741 struct bpf_map *map = reg->map_ptr; 4742 u64 val = reg->var_off.value; 4743 4744 if (!is_const) { 4745 verbose(env, 4746 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 4747 regno); 4748 return -EINVAL; 4749 } 4750 if (!map->btf) { 4751 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 4752 map->name); 4753 return -EINVAL; 4754 } 4755 if (!map_value_has_timer(map)) { 4756 if (map->timer_off == -E2BIG) 4757 verbose(env, 4758 "map '%s' has more than one 'struct bpf_timer'\n", 4759 map->name); 4760 else if (map->timer_off == -ENOENT) 4761 verbose(env, 4762 "map '%s' doesn't have 'struct bpf_timer'\n", 4763 map->name); 4764 else 4765 verbose(env, 4766 "map '%s' is not a struct type or bpf_timer is mangled\n", 4767 map->name); 4768 return -EINVAL; 4769 } 4770 if (map->timer_off != val + reg->off) { 4771 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 4772 val + reg->off, map->timer_off); 4773 return -EINVAL; 4774 } 4775 if (meta->map_ptr) { 4776 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 4777 return -EFAULT; 4778 } 4779 meta->map_uid = reg->map_uid; 4780 meta->map_ptr = map; 4781 return 0; 4782 } 4783 4784 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 4785 { 4786 return type == ARG_PTR_TO_MEM || 4787 type == ARG_PTR_TO_MEM_OR_NULL || 4788 type == ARG_PTR_TO_UNINIT_MEM; 4789 } 4790 4791 static bool arg_type_is_mem_size(enum bpf_arg_type type) 4792 { 4793 return type == ARG_CONST_SIZE || 4794 type == ARG_CONST_SIZE_OR_ZERO; 4795 } 4796 4797 static bool arg_type_is_alloc_size(enum bpf_arg_type type) 4798 { 4799 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO; 4800 } 4801 4802 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 4803 { 4804 return type == ARG_PTR_TO_INT || 4805 type == ARG_PTR_TO_LONG; 4806 } 4807 4808 static int int_ptr_type_to_size(enum bpf_arg_type type) 4809 { 4810 if (type == ARG_PTR_TO_INT) 4811 return sizeof(u32); 4812 else if (type == ARG_PTR_TO_LONG) 4813 return sizeof(u64); 4814 4815 return -EINVAL; 4816 } 4817 4818 static int resolve_map_arg_type(struct bpf_verifier_env *env, 4819 const struct bpf_call_arg_meta *meta, 4820 enum bpf_arg_type *arg_type) 4821 { 4822 if (!meta->map_ptr) { 4823 /* kernel subsystem misconfigured verifier */ 4824 verbose(env, "invalid map_ptr to access map->type\n"); 4825 return -EACCES; 4826 } 4827 4828 switch (meta->map_ptr->map_type) { 4829 case BPF_MAP_TYPE_SOCKMAP: 4830 case BPF_MAP_TYPE_SOCKHASH: 4831 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 4832 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 4833 } else { 4834 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 4835 return -EINVAL; 4836 } 4837 break; 4838 4839 default: 4840 break; 4841 } 4842 return 0; 4843 } 4844 4845 struct bpf_reg_types { 4846 const enum bpf_reg_type types[10]; 4847 u32 *btf_id; 4848 }; 4849 4850 static const struct bpf_reg_types map_key_value_types = { 4851 .types = { 4852 PTR_TO_STACK, 4853 PTR_TO_PACKET, 4854 PTR_TO_PACKET_META, 4855 PTR_TO_MAP_KEY, 4856 PTR_TO_MAP_VALUE, 4857 }, 4858 }; 4859 4860 static const struct bpf_reg_types sock_types = { 4861 .types = { 4862 PTR_TO_SOCK_COMMON, 4863 PTR_TO_SOCKET, 4864 PTR_TO_TCP_SOCK, 4865 PTR_TO_XDP_SOCK, 4866 }, 4867 }; 4868 4869 #ifdef CONFIG_NET 4870 static const struct bpf_reg_types btf_id_sock_common_types = { 4871 .types = { 4872 PTR_TO_SOCK_COMMON, 4873 PTR_TO_SOCKET, 4874 PTR_TO_TCP_SOCK, 4875 PTR_TO_XDP_SOCK, 4876 PTR_TO_BTF_ID, 4877 }, 4878 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4879 }; 4880 #endif 4881 4882 static const struct bpf_reg_types mem_types = { 4883 .types = { 4884 PTR_TO_STACK, 4885 PTR_TO_PACKET, 4886 PTR_TO_PACKET_META, 4887 PTR_TO_MAP_KEY, 4888 PTR_TO_MAP_VALUE, 4889 PTR_TO_MEM, 4890 PTR_TO_RDONLY_BUF, 4891 PTR_TO_RDWR_BUF, 4892 }, 4893 }; 4894 4895 static const struct bpf_reg_types int_ptr_types = { 4896 .types = { 4897 PTR_TO_STACK, 4898 PTR_TO_PACKET, 4899 PTR_TO_PACKET_META, 4900 PTR_TO_MAP_KEY, 4901 PTR_TO_MAP_VALUE, 4902 }, 4903 }; 4904 4905 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 4906 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 4907 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 4908 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } }; 4909 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 4910 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } }; 4911 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } }; 4912 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } }; 4913 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 4914 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 4915 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 4916 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 4917 4918 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 4919 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types, 4920 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types, 4921 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types, 4922 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types, 4923 [ARG_CONST_SIZE] = &scalar_types, 4924 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 4925 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 4926 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 4927 [ARG_PTR_TO_CTX] = &context_types, 4928 [ARG_PTR_TO_CTX_OR_NULL] = &context_types, 4929 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 4930 #ifdef CONFIG_NET 4931 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 4932 #endif 4933 [ARG_PTR_TO_SOCKET] = &fullsock_types, 4934 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types, 4935 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 4936 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 4937 [ARG_PTR_TO_MEM] = &mem_types, 4938 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types, 4939 [ARG_PTR_TO_UNINIT_MEM] = &mem_types, 4940 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types, 4941 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types, 4942 [ARG_PTR_TO_INT] = &int_ptr_types, 4943 [ARG_PTR_TO_LONG] = &int_ptr_types, 4944 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 4945 [ARG_PTR_TO_FUNC] = &func_ptr_types, 4946 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types, 4947 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 4948 [ARG_PTR_TO_TIMER] = &timer_types, 4949 }; 4950 4951 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 4952 enum bpf_arg_type arg_type, 4953 const u32 *arg_btf_id) 4954 { 4955 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4956 enum bpf_reg_type expected, type = reg->type; 4957 const struct bpf_reg_types *compatible; 4958 int i, j; 4959 4960 compatible = compatible_reg_types[arg_type]; 4961 if (!compatible) { 4962 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 4963 return -EFAULT; 4964 } 4965 4966 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 4967 expected = compatible->types[i]; 4968 if (expected == NOT_INIT) 4969 break; 4970 4971 if (type == expected) 4972 goto found; 4973 } 4974 4975 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]); 4976 for (j = 0; j + 1 < i; j++) 4977 verbose(env, "%s, ", reg_type_str[compatible->types[j]]); 4978 verbose(env, "%s\n", reg_type_str[compatible->types[j]]); 4979 return -EACCES; 4980 4981 found: 4982 if (type == PTR_TO_BTF_ID) { 4983 if (!arg_btf_id) { 4984 if (!compatible->btf_id) { 4985 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 4986 return -EFAULT; 4987 } 4988 arg_btf_id = compatible->btf_id; 4989 } 4990 4991 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4992 btf_vmlinux, *arg_btf_id)) { 4993 verbose(env, "R%d is of type %s but %s is expected\n", 4994 regno, kernel_type_name(reg->btf, reg->btf_id), 4995 kernel_type_name(btf_vmlinux, *arg_btf_id)); 4996 return -EACCES; 4997 } 4998 4999 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5000 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 5001 regno); 5002 return -EACCES; 5003 } 5004 } 5005 5006 return 0; 5007 } 5008 5009 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 5010 struct bpf_call_arg_meta *meta, 5011 const struct bpf_func_proto *fn) 5012 { 5013 u32 regno = BPF_REG_1 + arg; 5014 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5015 enum bpf_arg_type arg_type = fn->arg_type[arg]; 5016 enum bpf_reg_type type = reg->type; 5017 int err = 0; 5018 5019 if (arg_type == ARG_DONTCARE) 5020 return 0; 5021 5022 err = check_reg_arg(env, regno, SRC_OP); 5023 if (err) 5024 return err; 5025 5026 if (arg_type == ARG_ANYTHING) { 5027 if (is_pointer_value(env, regno)) { 5028 verbose(env, "R%d leaks addr into helper function\n", 5029 regno); 5030 return -EACCES; 5031 } 5032 return 0; 5033 } 5034 5035 if (type_is_pkt_pointer(type) && 5036 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 5037 verbose(env, "helper access to the packet is not allowed\n"); 5038 return -EACCES; 5039 } 5040 5041 if (arg_type == ARG_PTR_TO_MAP_VALUE || 5042 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE || 5043 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) { 5044 err = resolve_map_arg_type(env, meta, &arg_type); 5045 if (err) 5046 return err; 5047 } 5048 5049 if (register_is_null(reg) && arg_type_may_be_null(arg_type)) 5050 /* A NULL register has a SCALAR_VALUE type, so skip 5051 * type checking. 5052 */ 5053 goto skip_type_check; 5054 5055 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]); 5056 if (err) 5057 return err; 5058 5059 if (type == PTR_TO_CTX) { 5060 err = check_ctx_reg(env, reg, regno); 5061 if (err < 0) 5062 return err; 5063 } 5064 5065 skip_type_check: 5066 if (reg->ref_obj_id) { 5067 if (meta->ref_obj_id) { 5068 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 5069 regno, reg->ref_obj_id, 5070 meta->ref_obj_id); 5071 return -EFAULT; 5072 } 5073 meta->ref_obj_id = reg->ref_obj_id; 5074 } 5075 5076 if (arg_type == ARG_CONST_MAP_PTR) { 5077 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 5078 if (meta->map_ptr) { 5079 /* Use map_uid (which is unique id of inner map) to reject: 5080 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 5081 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 5082 * if (inner_map1 && inner_map2) { 5083 * timer = bpf_map_lookup_elem(inner_map1); 5084 * if (timer) 5085 * // mismatch would have been allowed 5086 * bpf_timer_init(timer, inner_map2); 5087 * } 5088 * 5089 * Comparing map_ptr is enough to distinguish normal and outer maps. 5090 */ 5091 if (meta->map_ptr != reg->map_ptr || 5092 meta->map_uid != reg->map_uid) { 5093 verbose(env, 5094 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 5095 meta->map_uid, reg->map_uid); 5096 return -EINVAL; 5097 } 5098 } 5099 meta->map_ptr = reg->map_ptr; 5100 meta->map_uid = reg->map_uid; 5101 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 5102 /* bpf_map_xxx(..., map_ptr, ..., key) call: 5103 * check that [key, key + map->key_size) are within 5104 * stack limits and initialized 5105 */ 5106 if (!meta->map_ptr) { 5107 /* in function declaration map_ptr must come before 5108 * map_key, so that it's verified and known before 5109 * we have to check map_key here. Otherwise it means 5110 * that kernel subsystem misconfigured verifier 5111 */ 5112 verbose(env, "invalid map_ptr to access map->key\n"); 5113 return -EACCES; 5114 } 5115 err = check_helper_mem_access(env, regno, 5116 meta->map_ptr->key_size, false, 5117 NULL); 5118 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 5119 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL && 5120 !register_is_null(reg)) || 5121 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 5122 /* bpf_map_xxx(..., map_ptr, ..., value) call: 5123 * check [value, value + map->value_size) validity 5124 */ 5125 if (!meta->map_ptr) { 5126 /* kernel subsystem misconfigured verifier */ 5127 verbose(env, "invalid map_ptr to access map->value\n"); 5128 return -EACCES; 5129 } 5130 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 5131 err = check_helper_mem_access(env, regno, 5132 meta->map_ptr->value_size, false, 5133 meta); 5134 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) { 5135 if (!reg->btf_id) { 5136 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 5137 return -EACCES; 5138 } 5139 meta->ret_btf = reg->btf; 5140 meta->ret_btf_id = reg->btf_id; 5141 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 5142 if (meta->func_id == BPF_FUNC_spin_lock) { 5143 if (process_spin_lock(env, regno, true)) 5144 return -EACCES; 5145 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 5146 if (process_spin_lock(env, regno, false)) 5147 return -EACCES; 5148 } else { 5149 verbose(env, "verifier internal error\n"); 5150 return -EFAULT; 5151 } 5152 } else if (arg_type == ARG_PTR_TO_TIMER) { 5153 if (process_timer_func(env, regno, meta)) 5154 return -EACCES; 5155 } else if (arg_type == ARG_PTR_TO_FUNC) { 5156 meta->subprogno = reg->subprogno; 5157 } else if (arg_type_is_mem_ptr(arg_type)) { 5158 /* The access to this pointer is only checked when we hit the 5159 * next is_mem_size argument below. 5160 */ 5161 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM); 5162 } else if (arg_type_is_mem_size(arg_type)) { 5163 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 5164 5165 /* This is used to refine r0 return value bounds for helpers 5166 * that enforce this value as an upper bound on return values. 5167 * See do_refine_retval_range() for helpers that can refine 5168 * the return value. C type of helper is u32 so we pull register 5169 * bound from umax_value however, if negative verifier errors 5170 * out. Only upper bounds can be learned because retval is an 5171 * int type and negative retvals are allowed. 5172 */ 5173 meta->msize_max_value = reg->umax_value; 5174 5175 /* The register is SCALAR_VALUE; the access check 5176 * happens using its boundaries. 5177 */ 5178 if (!tnum_is_const(reg->var_off)) 5179 /* For unprivileged variable accesses, disable raw 5180 * mode so that the program is required to 5181 * initialize all the memory that the helper could 5182 * just partially fill up. 5183 */ 5184 meta = NULL; 5185 5186 if (reg->smin_value < 0) { 5187 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5188 regno); 5189 return -EACCES; 5190 } 5191 5192 if (reg->umin_value == 0) { 5193 err = check_helper_mem_access(env, regno - 1, 0, 5194 zero_size_allowed, 5195 meta); 5196 if (err) 5197 return err; 5198 } 5199 5200 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5201 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5202 regno); 5203 return -EACCES; 5204 } 5205 err = check_helper_mem_access(env, regno - 1, 5206 reg->umax_value, 5207 zero_size_allowed, meta); 5208 if (!err) 5209 err = mark_chain_precision(env, regno); 5210 } else if (arg_type_is_alloc_size(arg_type)) { 5211 if (!tnum_is_const(reg->var_off)) { 5212 verbose(env, "R%d is not a known constant'\n", 5213 regno); 5214 return -EACCES; 5215 } 5216 meta->mem_size = reg->var_off.value; 5217 } else if (arg_type_is_int_ptr(arg_type)) { 5218 int size = int_ptr_type_to_size(arg_type); 5219 5220 err = check_helper_mem_access(env, regno, size, false, meta); 5221 if (err) 5222 return err; 5223 err = check_ptr_alignment(env, reg, 0, size, true); 5224 } else if (arg_type == ARG_PTR_TO_CONST_STR) { 5225 struct bpf_map *map = reg->map_ptr; 5226 int map_off; 5227 u64 map_addr; 5228 char *str_ptr; 5229 5230 if (!bpf_map_is_rdonly(map)) { 5231 verbose(env, "R%d does not point to a readonly map'\n", regno); 5232 return -EACCES; 5233 } 5234 5235 if (!tnum_is_const(reg->var_off)) { 5236 verbose(env, "R%d is not a constant address'\n", regno); 5237 return -EACCES; 5238 } 5239 5240 if (!map->ops->map_direct_value_addr) { 5241 verbose(env, "no direct value access support for this map type\n"); 5242 return -EACCES; 5243 } 5244 5245 err = check_map_access(env, regno, reg->off, 5246 map->value_size - reg->off, false); 5247 if (err) 5248 return err; 5249 5250 map_off = reg->off + reg->var_off.value; 5251 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 5252 if (err) { 5253 verbose(env, "direct value access on string failed\n"); 5254 return err; 5255 } 5256 5257 str_ptr = (char *)(long)(map_addr); 5258 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 5259 verbose(env, "string is not zero-terminated\n"); 5260 return -EINVAL; 5261 } 5262 } 5263 5264 return err; 5265 } 5266 5267 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 5268 { 5269 enum bpf_attach_type eatype = env->prog->expected_attach_type; 5270 enum bpf_prog_type type = resolve_prog_type(env->prog); 5271 5272 if (func_id != BPF_FUNC_map_update_elem) 5273 return false; 5274 5275 /* It's not possible to get access to a locked struct sock in these 5276 * contexts, so updating is safe. 5277 */ 5278 switch (type) { 5279 case BPF_PROG_TYPE_TRACING: 5280 if (eatype == BPF_TRACE_ITER) 5281 return true; 5282 break; 5283 case BPF_PROG_TYPE_SOCKET_FILTER: 5284 case BPF_PROG_TYPE_SCHED_CLS: 5285 case BPF_PROG_TYPE_SCHED_ACT: 5286 case BPF_PROG_TYPE_XDP: 5287 case BPF_PROG_TYPE_SK_REUSEPORT: 5288 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5289 case BPF_PROG_TYPE_SK_LOOKUP: 5290 return true; 5291 default: 5292 break; 5293 } 5294 5295 verbose(env, "cannot update sockmap in this context\n"); 5296 return false; 5297 } 5298 5299 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 5300 { 5301 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64); 5302 } 5303 5304 static int check_map_func_compatibility(struct bpf_verifier_env *env, 5305 struct bpf_map *map, int func_id) 5306 { 5307 if (!map) 5308 return 0; 5309 5310 /* We need a two way check, first is from map perspective ... */ 5311 switch (map->map_type) { 5312 case BPF_MAP_TYPE_PROG_ARRAY: 5313 if (func_id != BPF_FUNC_tail_call) 5314 goto error; 5315 break; 5316 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 5317 if (func_id != BPF_FUNC_perf_event_read && 5318 func_id != BPF_FUNC_perf_event_output && 5319 func_id != BPF_FUNC_skb_output && 5320 func_id != BPF_FUNC_perf_event_read_value && 5321 func_id != BPF_FUNC_xdp_output) 5322 goto error; 5323 break; 5324 case BPF_MAP_TYPE_RINGBUF: 5325 if (func_id != BPF_FUNC_ringbuf_output && 5326 func_id != BPF_FUNC_ringbuf_reserve && 5327 func_id != BPF_FUNC_ringbuf_submit && 5328 func_id != BPF_FUNC_ringbuf_discard && 5329 func_id != BPF_FUNC_ringbuf_query) 5330 goto error; 5331 break; 5332 case BPF_MAP_TYPE_STACK_TRACE: 5333 if (func_id != BPF_FUNC_get_stackid) 5334 goto error; 5335 break; 5336 case BPF_MAP_TYPE_CGROUP_ARRAY: 5337 if (func_id != BPF_FUNC_skb_under_cgroup && 5338 func_id != BPF_FUNC_current_task_under_cgroup) 5339 goto error; 5340 break; 5341 case BPF_MAP_TYPE_CGROUP_STORAGE: 5342 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 5343 if (func_id != BPF_FUNC_get_local_storage) 5344 goto error; 5345 break; 5346 case BPF_MAP_TYPE_DEVMAP: 5347 case BPF_MAP_TYPE_DEVMAP_HASH: 5348 if (func_id != BPF_FUNC_redirect_map && 5349 func_id != BPF_FUNC_map_lookup_elem) 5350 goto error; 5351 break; 5352 /* Restrict bpf side of cpumap and xskmap, open when use-cases 5353 * appear. 5354 */ 5355 case BPF_MAP_TYPE_CPUMAP: 5356 if (func_id != BPF_FUNC_redirect_map) 5357 goto error; 5358 break; 5359 case BPF_MAP_TYPE_XSKMAP: 5360 if (func_id != BPF_FUNC_redirect_map && 5361 func_id != BPF_FUNC_map_lookup_elem) 5362 goto error; 5363 break; 5364 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 5365 case BPF_MAP_TYPE_HASH_OF_MAPS: 5366 if (func_id != BPF_FUNC_map_lookup_elem) 5367 goto error; 5368 break; 5369 case BPF_MAP_TYPE_SOCKMAP: 5370 if (func_id != BPF_FUNC_sk_redirect_map && 5371 func_id != BPF_FUNC_sock_map_update && 5372 func_id != BPF_FUNC_map_delete_elem && 5373 func_id != BPF_FUNC_msg_redirect_map && 5374 func_id != BPF_FUNC_sk_select_reuseport && 5375 func_id != BPF_FUNC_map_lookup_elem && 5376 !may_update_sockmap(env, func_id)) 5377 goto error; 5378 break; 5379 case BPF_MAP_TYPE_SOCKHASH: 5380 if (func_id != BPF_FUNC_sk_redirect_hash && 5381 func_id != BPF_FUNC_sock_hash_update && 5382 func_id != BPF_FUNC_map_delete_elem && 5383 func_id != BPF_FUNC_msg_redirect_hash && 5384 func_id != BPF_FUNC_sk_select_reuseport && 5385 func_id != BPF_FUNC_map_lookup_elem && 5386 !may_update_sockmap(env, func_id)) 5387 goto error; 5388 break; 5389 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 5390 if (func_id != BPF_FUNC_sk_select_reuseport) 5391 goto error; 5392 break; 5393 case BPF_MAP_TYPE_QUEUE: 5394 case BPF_MAP_TYPE_STACK: 5395 if (func_id != BPF_FUNC_map_peek_elem && 5396 func_id != BPF_FUNC_map_pop_elem && 5397 func_id != BPF_FUNC_map_push_elem) 5398 goto error; 5399 break; 5400 case BPF_MAP_TYPE_SK_STORAGE: 5401 if (func_id != BPF_FUNC_sk_storage_get && 5402 func_id != BPF_FUNC_sk_storage_delete) 5403 goto error; 5404 break; 5405 case BPF_MAP_TYPE_INODE_STORAGE: 5406 if (func_id != BPF_FUNC_inode_storage_get && 5407 func_id != BPF_FUNC_inode_storage_delete) 5408 goto error; 5409 break; 5410 case BPF_MAP_TYPE_TASK_STORAGE: 5411 if (func_id != BPF_FUNC_task_storage_get && 5412 func_id != BPF_FUNC_task_storage_delete) 5413 goto error; 5414 break; 5415 default: 5416 break; 5417 } 5418 5419 /* ... and second from the function itself. */ 5420 switch (func_id) { 5421 case BPF_FUNC_tail_call: 5422 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 5423 goto error; 5424 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 5425 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 5426 return -EINVAL; 5427 } 5428 break; 5429 case BPF_FUNC_perf_event_read: 5430 case BPF_FUNC_perf_event_output: 5431 case BPF_FUNC_perf_event_read_value: 5432 case BPF_FUNC_skb_output: 5433 case BPF_FUNC_xdp_output: 5434 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 5435 goto error; 5436 break; 5437 case BPF_FUNC_get_stackid: 5438 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 5439 goto error; 5440 break; 5441 case BPF_FUNC_current_task_under_cgroup: 5442 case BPF_FUNC_skb_under_cgroup: 5443 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 5444 goto error; 5445 break; 5446 case BPF_FUNC_redirect_map: 5447 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 5448 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 5449 map->map_type != BPF_MAP_TYPE_CPUMAP && 5450 map->map_type != BPF_MAP_TYPE_XSKMAP) 5451 goto error; 5452 break; 5453 case BPF_FUNC_sk_redirect_map: 5454 case BPF_FUNC_msg_redirect_map: 5455 case BPF_FUNC_sock_map_update: 5456 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 5457 goto error; 5458 break; 5459 case BPF_FUNC_sk_redirect_hash: 5460 case BPF_FUNC_msg_redirect_hash: 5461 case BPF_FUNC_sock_hash_update: 5462 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 5463 goto error; 5464 break; 5465 case BPF_FUNC_get_local_storage: 5466 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 5467 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 5468 goto error; 5469 break; 5470 case BPF_FUNC_sk_select_reuseport: 5471 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 5472 map->map_type != BPF_MAP_TYPE_SOCKMAP && 5473 map->map_type != BPF_MAP_TYPE_SOCKHASH) 5474 goto error; 5475 break; 5476 case BPF_FUNC_map_peek_elem: 5477 case BPF_FUNC_map_pop_elem: 5478 case BPF_FUNC_map_push_elem: 5479 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5480 map->map_type != BPF_MAP_TYPE_STACK) 5481 goto error; 5482 break; 5483 case BPF_FUNC_sk_storage_get: 5484 case BPF_FUNC_sk_storage_delete: 5485 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 5486 goto error; 5487 break; 5488 case BPF_FUNC_inode_storage_get: 5489 case BPF_FUNC_inode_storage_delete: 5490 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 5491 goto error; 5492 break; 5493 case BPF_FUNC_task_storage_get: 5494 case BPF_FUNC_task_storage_delete: 5495 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 5496 goto error; 5497 break; 5498 default: 5499 break; 5500 } 5501 5502 return 0; 5503 error: 5504 verbose(env, "cannot pass map_type %d into func %s#%d\n", 5505 map->map_type, func_id_name(func_id), func_id); 5506 return -EINVAL; 5507 } 5508 5509 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 5510 { 5511 int count = 0; 5512 5513 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 5514 count++; 5515 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 5516 count++; 5517 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 5518 count++; 5519 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 5520 count++; 5521 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 5522 count++; 5523 5524 /* We only support one arg being in raw mode at the moment, 5525 * which is sufficient for the helper functions we have 5526 * right now. 5527 */ 5528 return count <= 1; 5529 } 5530 5531 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 5532 enum bpf_arg_type arg_next) 5533 { 5534 return (arg_type_is_mem_ptr(arg_curr) && 5535 !arg_type_is_mem_size(arg_next)) || 5536 (!arg_type_is_mem_ptr(arg_curr) && 5537 arg_type_is_mem_size(arg_next)); 5538 } 5539 5540 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 5541 { 5542 /* bpf_xxx(..., buf, len) call will access 'len' 5543 * bytes from memory 'buf'. Both arg types need 5544 * to be paired, so make sure there's no buggy 5545 * helper function specification. 5546 */ 5547 if (arg_type_is_mem_size(fn->arg1_type) || 5548 arg_type_is_mem_ptr(fn->arg5_type) || 5549 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 5550 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 5551 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 5552 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 5553 return false; 5554 5555 return true; 5556 } 5557 5558 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 5559 { 5560 int count = 0; 5561 5562 if (arg_type_may_be_refcounted(fn->arg1_type)) 5563 count++; 5564 if (arg_type_may_be_refcounted(fn->arg2_type)) 5565 count++; 5566 if (arg_type_may_be_refcounted(fn->arg3_type)) 5567 count++; 5568 if (arg_type_may_be_refcounted(fn->arg4_type)) 5569 count++; 5570 if (arg_type_may_be_refcounted(fn->arg5_type)) 5571 count++; 5572 5573 /* A reference acquiring function cannot acquire 5574 * another refcounted ptr. 5575 */ 5576 if (may_be_acquire_function(func_id) && count) 5577 return false; 5578 5579 /* We only support one arg being unreferenced at the moment, 5580 * which is sufficient for the helper functions we have right now. 5581 */ 5582 return count <= 1; 5583 } 5584 5585 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 5586 { 5587 int i; 5588 5589 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 5590 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i]) 5591 return false; 5592 5593 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i]) 5594 return false; 5595 } 5596 5597 return true; 5598 } 5599 5600 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 5601 { 5602 return check_raw_mode_ok(fn) && 5603 check_arg_pair_ok(fn) && 5604 check_btf_id_ok(fn) && 5605 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 5606 } 5607 5608 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 5609 * are now invalid, so turn them into unknown SCALAR_VALUE. 5610 */ 5611 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 5612 struct bpf_func_state *state) 5613 { 5614 struct bpf_reg_state *regs = state->regs, *reg; 5615 int i; 5616 5617 for (i = 0; i < MAX_BPF_REG; i++) 5618 if (reg_is_pkt_pointer_any(®s[i])) 5619 mark_reg_unknown(env, regs, i); 5620 5621 bpf_for_each_spilled_reg(i, state, reg) { 5622 if (!reg) 5623 continue; 5624 if (reg_is_pkt_pointer_any(reg)) 5625 __mark_reg_unknown(env, reg); 5626 } 5627 } 5628 5629 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 5630 { 5631 struct bpf_verifier_state *vstate = env->cur_state; 5632 int i; 5633 5634 for (i = 0; i <= vstate->curframe; i++) 5635 __clear_all_pkt_pointers(env, vstate->frame[i]); 5636 } 5637 5638 enum { 5639 AT_PKT_END = -1, 5640 BEYOND_PKT_END = -2, 5641 }; 5642 5643 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 5644 { 5645 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5646 struct bpf_reg_state *reg = &state->regs[regn]; 5647 5648 if (reg->type != PTR_TO_PACKET) 5649 /* PTR_TO_PACKET_META is not supported yet */ 5650 return; 5651 5652 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 5653 * How far beyond pkt_end it goes is unknown. 5654 * if (!range_open) it's the case of pkt >= pkt_end 5655 * if (range_open) it's the case of pkt > pkt_end 5656 * hence this pointer is at least 1 byte bigger than pkt_end 5657 */ 5658 if (range_open) 5659 reg->range = BEYOND_PKT_END; 5660 else 5661 reg->range = AT_PKT_END; 5662 } 5663 5664 static void release_reg_references(struct bpf_verifier_env *env, 5665 struct bpf_func_state *state, 5666 int ref_obj_id) 5667 { 5668 struct bpf_reg_state *regs = state->regs, *reg; 5669 int i; 5670 5671 for (i = 0; i < MAX_BPF_REG; i++) 5672 if (regs[i].ref_obj_id == ref_obj_id) 5673 mark_reg_unknown(env, regs, i); 5674 5675 bpf_for_each_spilled_reg(i, state, reg) { 5676 if (!reg) 5677 continue; 5678 if (reg->ref_obj_id == ref_obj_id) 5679 __mark_reg_unknown(env, reg); 5680 } 5681 } 5682 5683 /* The pointer with the specified id has released its reference to kernel 5684 * resources. Identify all copies of the same pointer and clear the reference. 5685 */ 5686 static int release_reference(struct bpf_verifier_env *env, 5687 int ref_obj_id) 5688 { 5689 struct bpf_verifier_state *vstate = env->cur_state; 5690 int err; 5691 int i; 5692 5693 err = release_reference_state(cur_func(env), ref_obj_id); 5694 if (err) 5695 return err; 5696 5697 for (i = 0; i <= vstate->curframe; i++) 5698 release_reg_references(env, vstate->frame[i], ref_obj_id); 5699 5700 return 0; 5701 } 5702 5703 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 5704 struct bpf_reg_state *regs) 5705 { 5706 int i; 5707 5708 /* after the call registers r0 - r5 were scratched */ 5709 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5710 mark_reg_not_init(env, regs, caller_saved[i]); 5711 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5712 } 5713 } 5714 5715 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 5716 struct bpf_func_state *caller, 5717 struct bpf_func_state *callee, 5718 int insn_idx); 5719 5720 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5721 int *insn_idx, int subprog, 5722 set_callee_state_fn set_callee_state_cb) 5723 { 5724 struct bpf_verifier_state *state = env->cur_state; 5725 struct bpf_func_info_aux *func_info_aux; 5726 struct bpf_func_state *caller, *callee; 5727 int err; 5728 bool is_global = false; 5729 5730 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 5731 verbose(env, "the call stack of %d frames is too deep\n", 5732 state->curframe + 2); 5733 return -E2BIG; 5734 } 5735 5736 caller = state->frame[state->curframe]; 5737 if (state->frame[state->curframe + 1]) { 5738 verbose(env, "verifier bug. Frame %d already allocated\n", 5739 state->curframe + 1); 5740 return -EFAULT; 5741 } 5742 5743 func_info_aux = env->prog->aux->func_info_aux; 5744 if (func_info_aux) 5745 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 5746 err = btf_check_subprog_arg_match(env, subprog, caller->regs); 5747 if (err == -EFAULT) 5748 return err; 5749 if (is_global) { 5750 if (err) { 5751 verbose(env, "Caller passes invalid args into func#%d\n", 5752 subprog); 5753 return err; 5754 } else { 5755 if (env->log.level & BPF_LOG_LEVEL) 5756 verbose(env, 5757 "Func#%d is global and valid. Skipping.\n", 5758 subprog); 5759 clear_caller_saved_regs(env, caller->regs); 5760 5761 /* All global functions return a 64-bit SCALAR_VALUE */ 5762 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5763 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5764 5765 /* continue with next insn after call */ 5766 return 0; 5767 } 5768 } 5769 5770 if (insn->code == (BPF_JMP | BPF_CALL) && 5771 insn->imm == BPF_FUNC_timer_set_callback) { 5772 struct bpf_verifier_state *async_cb; 5773 5774 /* there is no real recursion here. timer callbacks are async */ 5775 env->subprog_info[subprog].is_async_cb = true; 5776 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 5777 *insn_idx, subprog); 5778 if (!async_cb) 5779 return -EFAULT; 5780 callee = async_cb->frame[0]; 5781 callee->async_entry_cnt = caller->async_entry_cnt + 1; 5782 5783 /* Convert bpf_timer_set_callback() args into timer callback args */ 5784 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5785 if (err) 5786 return err; 5787 5788 clear_caller_saved_regs(env, caller->regs); 5789 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5790 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5791 /* continue with next insn after call */ 5792 return 0; 5793 } 5794 5795 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 5796 if (!callee) 5797 return -ENOMEM; 5798 state->frame[state->curframe + 1] = callee; 5799 5800 /* callee cannot access r0, r6 - r9 for reading and has to write 5801 * into its own stack before reading from it. 5802 * callee can read/write into caller's stack 5803 */ 5804 init_func_state(env, callee, 5805 /* remember the callsite, it will be used by bpf_exit */ 5806 *insn_idx /* callsite */, 5807 state->curframe + 1 /* frameno within this callchain */, 5808 subprog /* subprog number within this prog */); 5809 5810 /* Transfer references to the callee */ 5811 err = copy_reference_state(callee, caller); 5812 if (err) 5813 return err; 5814 5815 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5816 if (err) 5817 return err; 5818 5819 clear_caller_saved_regs(env, caller->regs); 5820 5821 /* only increment it after check_reg_arg() finished */ 5822 state->curframe++; 5823 5824 /* and go analyze first insn of the callee */ 5825 *insn_idx = env->subprog_info[subprog].start - 1; 5826 5827 if (env->log.level & BPF_LOG_LEVEL) { 5828 verbose(env, "caller:\n"); 5829 print_verifier_state(env, caller); 5830 verbose(env, "callee:\n"); 5831 print_verifier_state(env, callee); 5832 } 5833 return 0; 5834 } 5835 5836 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 5837 struct bpf_func_state *caller, 5838 struct bpf_func_state *callee) 5839 { 5840 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 5841 * void *callback_ctx, u64 flags); 5842 * callback_fn(struct bpf_map *map, void *key, void *value, 5843 * void *callback_ctx); 5844 */ 5845 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 5846 5847 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 5848 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 5849 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5850 5851 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 5852 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 5853 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5854 5855 /* pointer to stack or null */ 5856 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 5857 5858 /* unused */ 5859 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 5860 return 0; 5861 } 5862 5863 static int set_callee_state(struct bpf_verifier_env *env, 5864 struct bpf_func_state *caller, 5865 struct bpf_func_state *callee, int insn_idx) 5866 { 5867 int i; 5868 5869 /* copy r1 - r5 args that callee can access. The copy includes parent 5870 * pointers, which connects us up to the liveness chain 5871 */ 5872 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 5873 callee->regs[i] = caller->regs[i]; 5874 return 0; 5875 } 5876 5877 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5878 int *insn_idx) 5879 { 5880 int subprog, target_insn; 5881 5882 target_insn = *insn_idx + insn->imm + 1; 5883 subprog = find_subprog(env, target_insn); 5884 if (subprog < 0) { 5885 verbose(env, "verifier bug. No program starts at insn %d\n", 5886 target_insn); 5887 return -EFAULT; 5888 } 5889 5890 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 5891 } 5892 5893 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 5894 struct bpf_func_state *caller, 5895 struct bpf_func_state *callee, 5896 int insn_idx) 5897 { 5898 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 5899 struct bpf_map *map; 5900 int err; 5901 5902 if (bpf_map_ptr_poisoned(insn_aux)) { 5903 verbose(env, "tail_call abusing map_ptr\n"); 5904 return -EINVAL; 5905 } 5906 5907 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 5908 if (!map->ops->map_set_for_each_callback_args || 5909 !map->ops->map_for_each_callback) { 5910 verbose(env, "callback function not allowed for map\n"); 5911 return -ENOTSUPP; 5912 } 5913 5914 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 5915 if (err) 5916 return err; 5917 5918 callee->in_callback_fn = true; 5919 return 0; 5920 } 5921 5922 static int set_timer_callback_state(struct bpf_verifier_env *env, 5923 struct bpf_func_state *caller, 5924 struct bpf_func_state *callee, 5925 int insn_idx) 5926 { 5927 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 5928 5929 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 5930 * callback_fn(struct bpf_map *map, void *key, void *value); 5931 */ 5932 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 5933 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 5934 callee->regs[BPF_REG_1].map_ptr = map_ptr; 5935 5936 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 5937 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 5938 callee->regs[BPF_REG_2].map_ptr = map_ptr; 5939 5940 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 5941 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 5942 callee->regs[BPF_REG_3].map_ptr = map_ptr; 5943 5944 /* unused */ 5945 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 5946 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 5947 callee->in_async_callback_fn = true; 5948 return 0; 5949 } 5950 5951 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 5952 { 5953 struct bpf_verifier_state *state = env->cur_state; 5954 struct bpf_func_state *caller, *callee; 5955 struct bpf_reg_state *r0; 5956 int err; 5957 5958 callee = state->frame[state->curframe]; 5959 r0 = &callee->regs[BPF_REG_0]; 5960 if (r0->type == PTR_TO_STACK) { 5961 /* technically it's ok to return caller's stack pointer 5962 * (or caller's caller's pointer) back to the caller, 5963 * since these pointers are valid. Only current stack 5964 * pointer will be invalid as soon as function exits, 5965 * but let's be conservative 5966 */ 5967 verbose(env, "cannot return stack pointer to the caller\n"); 5968 return -EINVAL; 5969 } 5970 5971 state->curframe--; 5972 caller = state->frame[state->curframe]; 5973 if (callee->in_callback_fn) { 5974 /* enforce R0 return value range [0, 1]. */ 5975 struct tnum range = tnum_range(0, 1); 5976 5977 if (r0->type != SCALAR_VALUE) { 5978 verbose(env, "R0 not a scalar value\n"); 5979 return -EACCES; 5980 } 5981 if (!tnum_in(range, r0->var_off)) { 5982 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 5983 return -EINVAL; 5984 } 5985 } else { 5986 /* return to the caller whatever r0 had in the callee */ 5987 caller->regs[BPF_REG_0] = *r0; 5988 } 5989 5990 /* Transfer references to the caller */ 5991 err = copy_reference_state(caller, callee); 5992 if (err) 5993 return err; 5994 5995 *insn_idx = callee->callsite + 1; 5996 if (env->log.level & BPF_LOG_LEVEL) { 5997 verbose(env, "returning from callee:\n"); 5998 print_verifier_state(env, callee); 5999 verbose(env, "to caller at %d:\n", *insn_idx); 6000 print_verifier_state(env, caller); 6001 } 6002 /* clear everything in the callee */ 6003 free_func_state(callee); 6004 state->frame[state->curframe + 1] = NULL; 6005 return 0; 6006 } 6007 6008 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 6009 int func_id, 6010 struct bpf_call_arg_meta *meta) 6011 { 6012 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 6013 6014 if (ret_type != RET_INTEGER || 6015 (func_id != BPF_FUNC_get_stack && 6016 func_id != BPF_FUNC_get_task_stack && 6017 func_id != BPF_FUNC_probe_read_str && 6018 func_id != BPF_FUNC_probe_read_kernel_str && 6019 func_id != BPF_FUNC_probe_read_user_str)) 6020 return; 6021 6022 ret_reg->smax_value = meta->msize_max_value; 6023 ret_reg->s32_max_value = meta->msize_max_value; 6024 ret_reg->smin_value = -MAX_ERRNO; 6025 ret_reg->s32_min_value = -MAX_ERRNO; 6026 __reg_deduce_bounds(ret_reg); 6027 __reg_bound_offset(ret_reg); 6028 __update_reg_bounds(ret_reg); 6029 } 6030 6031 static int 6032 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6033 int func_id, int insn_idx) 6034 { 6035 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6036 struct bpf_map *map = meta->map_ptr; 6037 6038 if (func_id != BPF_FUNC_tail_call && 6039 func_id != BPF_FUNC_map_lookup_elem && 6040 func_id != BPF_FUNC_map_update_elem && 6041 func_id != BPF_FUNC_map_delete_elem && 6042 func_id != BPF_FUNC_map_push_elem && 6043 func_id != BPF_FUNC_map_pop_elem && 6044 func_id != BPF_FUNC_map_peek_elem && 6045 func_id != BPF_FUNC_for_each_map_elem && 6046 func_id != BPF_FUNC_redirect_map) 6047 return 0; 6048 6049 if (map == NULL) { 6050 verbose(env, "kernel subsystem misconfigured verifier\n"); 6051 return -EINVAL; 6052 } 6053 6054 /* In case of read-only, some additional restrictions 6055 * need to be applied in order to prevent altering the 6056 * state of the map from program side. 6057 */ 6058 if ((map->map_flags & BPF_F_RDONLY_PROG) && 6059 (func_id == BPF_FUNC_map_delete_elem || 6060 func_id == BPF_FUNC_map_update_elem || 6061 func_id == BPF_FUNC_map_push_elem || 6062 func_id == BPF_FUNC_map_pop_elem)) { 6063 verbose(env, "write into map forbidden\n"); 6064 return -EACCES; 6065 } 6066 6067 if (!BPF_MAP_PTR(aux->map_ptr_state)) 6068 bpf_map_ptr_store(aux, meta->map_ptr, 6069 !meta->map_ptr->bypass_spec_v1); 6070 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 6071 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 6072 !meta->map_ptr->bypass_spec_v1); 6073 return 0; 6074 } 6075 6076 static int 6077 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6078 int func_id, int insn_idx) 6079 { 6080 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6081 struct bpf_reg_state *regs = cur_regs(env), *reg; 6082 struct bpf_map *map = meta->map_ptr; 6083 struct tnum range; 6084 u64 val; 6085 int err; 6086 6087 if (func_id != BPF_FUNC_tail_call) 6088 return 0; 6089 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 6090 verbose(env, "kernel subsystem misconfigured verifier\n"); 6091 return -EINVAL; 6092 } 6093 6094 range = tnum_range(0, map->max_entries - 1); 6095 reg = ®s[BPF_REG_3]; 6096 6097 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 6098 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6099 return 0; 6100 } 6101 6102 err = mark_chain_precision(env, BPF_REG_3); 6103 if (err) 6104 return err; 6105 6106 val = reg->var_off.value; 6107 if (bpf_map_key_unseen(aux)) 6108 bpf_map_key_store(aux, val); 6109 else if (!bpf_map_key_poisoned(aux) && 6110 bpf_map_key_immediate(aux) != val) 6111 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6112 return 0; 6113 } 6114 6115 static int check_reference_leak(struct bpf_verifier_env *env) 6116 { 6117 struct bpf_func_state *state = cur_func(env); 6118 int i; 6119 6120 for (i = 0; i < state->acquired_refs; i++) { 6121 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 6122 state->refs[i].id, state->refs[i].insn_idx); 6123 } 6124 return state->acquired_refs ? -EINVAL : 0; 6125 } 6126 6127 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 6128 struct bpf_reg_state *regs) 6129 { 6130 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 6131 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 6132 struct bpf_map *fmt_map = fmt_reg->map_ptr; 6133 int err, fmt_map_off, num_args; 6134 u64 fmt_addr; 6135 char *fmt; 6136 6137 /* data must be an array of u64 */ 6138 if (data_len_reg->var_off.value % 8) 6139 return -EINVAL; 6140 num_args = data_len_reg->var_off.value / 8; 6141 6142 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 6143 * and map_direct_value_addr is set. 6144 */ 6145 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 6146 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 6147 fmt_map_off); 6148 if (err) { 6149 verbose(env, "verifier bug\n"); 6150 return -EFAULT; 6151 } 6152 fmt = (char *)(long)fmt_addr + fmt_map_off; 6153 6154 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 6155 * can focus on validating the format specifiers. 6156 */ 6157 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args); 6158 if (err < 0) 6159 verbose(env, "Invalid format string\n"); 6160 6161 return err; 6162 } 6163 6164 static int check_get_func_ip(struct bpf_verifier_env *env) 6165 { 6166 enum bpf_attach_type eatype = env->prog->expected_attach_type; 6167 enum bpf_prog_type type = resolve_prog_type(env->prog); 6168 int func_id = BPF_FUNC_get_func_ip; 6169 6170 if (type == BPF_PROG_TYPE_TRACING) { 6171 if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT && 6172 eatype != BPF_MODIFY_RETURN) { 6173 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 6174 func_id_name(func_id), func_id); 6175 return -ENOTSUPP; 6176 } 6177 return 0; 6178 } else if (type == BPF_PROG_TYPE_KPROBE) { 6179 return 0; 6180 } 6181 6182 verbose(env, "func %s#%d not supported for program type %d\n", 6183 func_id_name(func_id), func_id, type); 6184 return -ENOTSUPP; 6185 } 6186 6187 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 6188 int *insn_idx_p) 6189 { 6190 const struct bpf_func_proto *fn = NULL; 6191 struct bpf_reg_state *regs; 6192 struct bpf_call_arg_meta meta; 6193 int insn_idx = *insn_idx_p; 6194 bool changes_data; 6195 int i, err, func_id; 6196 6197 /* find function prototype */ 6198 func_id = insn->imm; 6199 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 6200 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 6201 func_id); 6202 return -EINVAL; 6203 } 6204 6205 if (env->ops->get_func_proto) 6206 fn = env->ops->get_func_proto(func_id, env->prog); 6207 if (!fn) { 6208 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 6209 func_id); 6210 return -EINVAL; 6211 } 6212 6213 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 6214 if (!env->prog->gpl_compatible && fn->gpl_only) { 6215 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 6216 return -EINVAL; 6217 } 6218 6219 if (fn->allowed && !fn->allowed(env->prog)) { 6220 verbose(env, "helper call is not allowed in probe\n"); 6221 return -EINVAL; 6222 } 6223 6224 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 6225 changes_data = bpf_helper_changes_pkt_data(fn->func); 6226 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 6227 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 6228 func_id_name(func_id), func_id); 6229 return -EINVAL; 6230 } 6231 6232 memset(&meta, 0, sizeof(meta)); 6233 meta.pkt_access = fn->pkt_access; 6234 6235 err = check_func_proto(fn, func_id); 6236 if (err) { 6237 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 6238 func_id_name(func_id), func_id); 6239 return err; 6240 } 6241 6242 meta.func_id = func_id; 6243 /* check args */ 6244 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 6245 err = check_func_arg(env, i, &meta, fn); 6246 if (err) 6247 return err; 6248 } 6249 6250 err = record_func_map(env, &meta, func_id, insn_idx); 6251 if (err) 6252 return err; 6253 6254 err = record_func_key(env, &meta, func_id, insn_idx); 6255 if (err) 6256 return err; 6257 6258 /* Mark slots with STACK_MISC in case of raw mode, stack offset 6259 * is inferred from register state. 6260 */ 6261 for (i = 0; i < meta.access_size; i++) { 6262 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 6263 BPF_WRITE, -1, false); 6264 if (err) 6265 return err; 6266 } 6267 6268 if (func_id == BPF_FUNC_tail_call) { 6269 err = check_reference_leak(env); 6270 if (err) { 6271 verbose(env, "tail_call would lead to reference leak\n"); 6272 return err; 6273 } 6274 } else if (is_release_function(func_id)) { 6275 err = release_reference(env, meta.ref_obj_id); 6276 if (err) { 6277 verbose(env, "func %s#%d reference has not been acquired before\n", 6278 func_id_name(func_id), func_id); 6279 return err; 6280 } 6281 } 6282 6283 regs = cur_regs(env); 6284 6285 /* check that flags argument in get_local_storage(map, flags) is 0, 6286 * this is required because get_local_storage() can't return an error. 6287 */ 6288 if (func_id == BPF_FUNC_get_local_storage && 6289 !register_is_null(®s[BPF_REG_2])) { 6290 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 6291 return -EINVAL; 6292 } 6293 6294 if (func_id == BPF_FUNC_for_each_map_elem) { 6295 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6296 set_map_elem_callback_state); 6297 if (err < 0) 6298 return -EINVAL; 6299 } 6300 6301 if (func_id == BPF_FUNC_timer_set_callback) { 6302 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6303 set_timer_callback_state); 6304 if (err < 0) 6305 return -EINVAL; 6306 } 6307 6308 if (func_id == BPF_FUNC_snprintf) { 6309 err = check_bpf_snprintf_call(env, regs); 6310 if (err < 0) 6311 return err; 6312 } 6313 6314 /* reset caller saved regs */ 6315 for (i = 0; i < CALLER_SAVED_REGS; i++) { 6316 mark_reg_not_init(env, regs, caller_saved[i]); 6317 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 6318 } 6319 6320 /* helper call returns 64-bit value. */ 6321 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 6322 6323 /* update return register (already marked as written above) */ 6324 if (fn->ret_type == RET_INTEGER) { 6325 /* sets type to SCALAR_VALUE */ 6326 mark_reg_unknown(env, regs, BPF_REG_0); 6327 } else if (fn->ret_type == RET_VOID) { 6328 regs[BPF_REG_0].type = NOT_INIT; 6329 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 6330 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 6331 /* There is no offset yet applied, variable or fixed */ 6332 mark_reg_known_zero(env, regs, BPF_REG_0); 6333 /* remember map_ptr, so that check_map_access() 6334 * can check 'value_size' boundary of memory access 6335 * to map element returned from bpf_map_lookup_elem() 6336 */ 6337 if (meta.map_ptr == NULL) { 6338 verbose(env, 6339 "kernel subsystem misconfigured verifier\n"); 6340 return -EINVAL; 6341 } 6342 regs[BPF_REG_0].map_ptr = meta.map_ptr; 6343 regs[BPF_REG_0].map_uid = meta.map_uid; 6344 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 6345 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 6346 if (map_value_has_spin_lock(meta.map_ptr)) 6347 regs[BPF_REG_0].id = ++env->id_gen; 6348 } else { 6349 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 6350 } 6351 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 6352 mark_reg_known_zero(env, regs, BPF_REG_0); 6353 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 6354 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 6355 mark_reg_known_zero(env, regs, BPF_REG_0); 6356 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 6357 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 6358 mark_reg_known_zero(env, regs, BPF_REG_0); 6359 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 6360 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) { 6361 mark_reg_known_zero(env, regs, BPF_REG_0); 6362 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL; 6363 regs[BPF_REG_0].mem_size = meta.mem_size; 6364 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL || 6365 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) { 6366 const struct btf_type *t; 6367 6368 mark_reg_known_zero(env, regs, BPF_REG_0); 6369 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 6370 if (!btf_type_is_struct(t)) { 6371 u32 tsize; 6372 const struct btf_type *ret; 6373 const char *tname; 6374 6375 /* resolve the type size of ksym. */ 6376 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 6377 if (IS_ERR(ret)) { 6378 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 6379 verbose(env, "unable to resolve the size of type '%s': %ld\n", 6380 tname, PTR_ERR(ret)); 6381 return -EINVAL; 6382 } 6383 regs[BPF_REG_0].type = 6384 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 6385 PTR_TO_MEM : PTR_TO_MEM_OR_NULL; 6386 regs[BPF_REG_0].mem_size = tsize; 6387 } else { 6388 regs[BPF_REG_0].type = 6389 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 6390 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL; 6391 regs[BPF_REG_0].btf = meta.ret_btf; 6392 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 6393 } 6394 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL || 6395 fn->ret_type == RET_PTR_TO_BTF_ID) { 6396 int ret_btf_id; 6397 6398 mark_reg_known_zero(env, regs, BPF_REG_0); 6399 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ? 6400 PTR_TO_BTF_ID : 6401 PTR_TO_BTF_ID_OR_NULL; 6402 ret_btf_id = *fn->ret_btf_id; 6403 if (ret_btf_id == 0) { 6404 verbose(env, "invalid return type %d of func %s#%d\n", 6405 fn->ret_type, func_id_name(func_id), func_id); 6406 return -EINVAL; 6407 } 6408 /* current BPF helper definitions are only coming from 6409 * built-in code with type IDs from vmlinux BTF 6410 */ 6411 regs[BPF_REG_0].btf = btf_vmlinux; 6412 regs[BPF_REG_0].btf_id = ret_btf_id; 6413 } else { 6414 verbose(env, "unknown return type %d of func %s#%d\n", 6415 fn->ret_type, func_id_name(func_id), func_id); 6416 return -EINVAL; 6417 } 6418 6419 if (reg_type_may_be_null(regs[BPF_REG_0].type)) 6420 regs[BPF_REG_0].id = ++env->id_gen; 6421 6422 if (is_ptr_cast_function(func_id)) { 6423 /* For release_reference() */ 6424 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 6425 } else if (is_acquire_function(func_id, meta.map_ptr)) { 6426 int id = acquire_reference_state(env, insn_idx); 6427 6428 if (id < 0) 6429 return id; 6430 /* For mark_ptr_or_null_reg() */ 6431 regs[BPF_REG_0].id = id; 6432 /* For release_reference() */ 6433 regs[BPF_REG_0].ref_obj_id = id; 6434 } 6435 6436 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 6437 6438 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 6439 if (err) 6440 return err; 6441 6442 if ((func_id == BPF_FUNC_get_stack || 6443 func_id == BPF_FUNC_get_task_stack) && 6444 !env->prog->has_callchain_buf) { 6445 const char *err_str; 6446 6447 #ifdef CONFIG_PERF_EVENTS 6448 err = get_callchain_buffers(sysctl_perf_event_max_stack); 6449 err_str = "cannot get callchain buffer for func %s#%d\n"; 6450 #else 6451 err = -ENOTSUPP; 6452 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 6453 #endif 6454 if (err) { 6455 verbose(env, err_str, func_id_name(func_id), func_id); 6456 return err; 6457 } 6458 6459 env->prog->has_callchain_buf = true; 6460 } 6461 6462 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 6463 env->prog->call_get_stack = true; 6464 6465 if (func_id == BPF_FUNC_get_func_ip) { 6466 if (check_get_func_ip(env)) 6467 return -ENOTSUPP; 6468 env->prog->call_get_func_ip = true; 6469 } 6470 6471 if (changes_data) 6472 clear_all_pkt_pointers(env); 6473 return 0; 6474 } 6475 6476 /* mark_btf_func_reg_size() is used when the reg size is determined by 6477 * the BTF func_proto's return value size and argument. 6478 */ 6479 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 6480 size_t reg_size) 6481 { 6482 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 6483 6484 if (regno == BPF_REG_0) { 6485 /* Function return value */ 6486 reg->live |= REG_LIVE_WRITTEN; 6487 reg->subreg_def = reg_size == sizeof(u64) ? 6488 DEF_NOT_SUBREG : env->insn_idx + 1; 6489 } else { 6490 /* Function argument */ 6491 if (reg_size == sizeof(u64)) { 6492 mark_insn_zext(env, reg); 6493 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 6494 } else { 6495 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 6496 } 6497 } 6498 } 6499 6500 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn) 6501 { 6502 const struct btf_type *t, *func, *func_proto, *ptr_type; 6503 struct bpf_reg_state *regs = cur_regs(env); 6504 const char *func_name, *ptr_type_name; 6505 u32 i, nargs, func_id, ptr_type_id; 6506 const struct btf_param *args; 6507 int err; 6508 6509 func_id = insn->imm; 6510 func = btf_type_by_id(btf_vmlinux, func_id); 6511 func_name = btf_name_by_offset(btf_vmlinux, func->name_off); 6512 func_proto = btf_type_by_id(btf_vmlinux, func->type); 6513 6514 if (!env->ops->check_kfunc_call || 6515 !env->ops->check_kfunc_call(func_id)) { 6516 verbose(env, "calling kernel function %s is not allowed\n", 6517 func_name); 6518 return -EACCES; 6519 } 6520 6521 /* Check the arguments */ 6522 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs); 6523 if (err) 6524 return err; 6525 6526 for (i = 0; i < CALLER_SAVED_REGS; i++) 6527 mark_reg_not_init(env, regs, caller_saved[i]); 6528 6529 /* Check return type */ 6530 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL); 6531 if (btf_type_is_scalar(t)) { 6532 mark_reg_unknown(env, regs, BPF_REG_0); 6533 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 6534 } else if (btf_type_is_ptr(t)) { 6535 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type, 6536 &ptr_type_id); 6537 if (!btf_type_is_struct(ptr_type)) { 6538 ptr_type_name = btf_name_by_offset(btf_vmlinux, 6539 ptr_type->name_off); 6540 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n", 6541 func_name, btf_type_str(ptr_type), 6542 ptr_type_name); 6543 return -EINVAL; 6544 } 6545 mark_reg_known_zero(env, regs, BPF_REG_0); 6546 regs[BPF_REG_0].btf = btf_vmlinux; 6547 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 6548 regs[BPF_REG_0].btf_id = ptr_type_id; 6549 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 6550 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 6551 6552 nargs = btf_type_vlen(func_proto); 6553 args = (const struct btf_param *)(func_proto + 1); 6554 for (i = 0; i < nargs; i++) { 6555 u32 regno = i + 1; 6556 6557 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL); 6558 if (btf_type_is_ptr(t)) 6559 mark_btf_func_reg_size(env, regno, sizeof(void *)); 6560 else 6561 /* scalar. ensured by btf_check_kfunc_arg_match() */ 6562 mark_btf_func_reg_size(env, regno, t->size); 6563 } 6564 6565 return 0; 6566 } 6567 6568 static bool signed_add_overflows(s64 a, s64 b) 6569 { 6570 /* Do the add in u64, where overflow is well-defined */ 6571 s64 res = (s64)((u64)a + (u64)b); 6572 6573 if (b < 0) 6574 return res > a; 6575 return res < a; 6576 } 6577 6578 static bool signed_add32_overflows(s32 a, s32 b) 6579 { 6580 /* Do the add in u32, where overflow is well-defined */ 6581 s32 res = (s32)((u32)a + (u32)b); 6582 6583 if (b < 0) 6584 return res > a; 6585 return res < a; 6586 } 6587 6588 static bool signed_sub_overflows(s64 a, s64 b) 6589 { 6590 /* Do the sub in u64, where overflow is well-defined */ 6591 s64 res = (s64)((u64)a - (u64)b); 6592 6593 if (b < 0) 6594 return res < a; 6595 return res > a; 6596 } 6597 6598 static bool signed_sub32_overflows(s32 a, s32 b) 6599 { 6600 /* Do the sub in u32, where overflow is well-defined */ 6601 s32 res = (s32)((u32)a - (u32)b); 6602 6603 if (b < 0) 6604 return res < a; 6605 return res > a; 6606 } 6607 6608 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 6609 const struct bpf_reg_state *reg, 6610 enum bpf_reg_type type) 6611 { 6612 bool known = tnum_is_const(reg->var_off); 6613 s64 val = reg->var_off.value; 6614 s64 smin = reg->smin_value; 6615 6616 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 6617 verbose(env, "math between %s pointer and %lld is not allowed\n", 6618 reg_type_str[type], val); 6619 return false; 6620 } 6621 6622 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 6623 verbose(env, "%s pointer offset %d is not allowed\n", 6624 reg_type_str[type], reg->off); 6625 return false; 6626 } 6627 6628 if (smin == S64_MIN) { 6629 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 6630 reg_type_str[type]); 6631 return false; 6632 } 6633 6634 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 6635 verbose(env, "value %lld makes %s pointer be out of bounds\n", 6636 smin, reg_type_str[type]); 6637 return false; 6638 } 6639 6640 return true; 6641 } 6642 6643 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 6644 { 6645 return &env->insn_aux_data[env->insn_idx]; 6646 } 6647 6648 enum { 6649 REASON_BOUNDS = -1, 6650 REASON_TYPE = -2, 6651 REASON_PATHS = -3, 6652 REASON_LIMIT = -4, 6653 REASON_STACK = -5, 6654 }; 6655 6656 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 6657 u32 *alu_limit, bool mask_to_left) 6658 { 6659 u32 max = 0, ptr_limit = 0; 6660 6661 switch (ptr_reg->type) { 6662 case PTR_TO_STACK: 6663 /* Offset 0 is out-of-bounds, but acceptable start for the 6664 * left direction, see BPF_REG_FP. Also, unknown scalar 6665 * offset where we would need to deal with min/max bounds is 6666 * currently prohibited for unprivileged. 6667 */ 6668 max = MAX_BPF_STACK + mask_to_left; 6669 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 6670 break; 6671 case PTR_TO_MAP_VALUE: 6672 max = ptr_reg->map_ptr->value_size; 6673 ptr_limit = (mask_to_left ? 6674 ptr_reg->smin_value : 6675 ptr_reg->umax_value) + ptr_reg->off; 6676 break; 6677 default: 6678 return REASON_TYPE; 6679 } 6680 6681 if (ptr_limit >= max) 6682 return REASON_LIMIT; 6683 *alu_limit = ptr_limit; 6684 return 0; 6685 } 6686 6687 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 6688 const struct bpf_insn *insn) 6689 { 6690 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 6691 } 6692 6693 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 6694 u32 alu_state, u32 alu_limit) 6695 { 6696 /* If we arrived here from different branches with different 6697 * state or limits to sanitize, then this won't work. 6698 */ 6699 if (aux->alu_state && 6700 (aux->alu_state != alu_state || 6701 aux->alu_limit != alu_limit)) 6702 return REASON_PATHS; 6703 6704 /* Corresponding fixup done in do_misc_fixups(). */ 6705 aux->alu_state = alu_state; 6706 aux->alu_limit = alu_limit; 6707 return 0; 6708 } 6709 6710 static int sanitize_val_alu(struct bpf_verifier_env *env, 6711 struct bpf_insn *insn) 6712 { 6713 struct bpf_insn_aux_data *aux = cur_aux(env); 6714 6715 if (can_skip_alu_sanitation(env, insn)) 6716 return 0; 6717 6718 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 6719 } 6720 6721 static bool sanitize_needed(u8 opcode) 6722 { 6723 return opcode == BPF_ADD || opcode == BPF_SUB; 6724 } 6725 6726 struct bpf_sanitize_info { 6727 struct bpf_insn_aux_data aux; 6728 bool mask_to_left; 6729 }; 6730 6731 static struct bpf_verifier_state * 6732 sanitize_speculative_path(struct bpf_verifier_env *env, 6733 const struct bpf_insn *insn, 6734 u32 next_idx, u32 curr_idx) 6735 { 6736 struct bpf_verifier_state *branch; 6737 struct bpf_reg_state *regs; 6738 6739 branch = push_stack(env, next_idx, curr_idx, true); 6740 if (branch && insn) { 6741 regs = branch->frame[branch->curframe]->regs; 6742 if (BPF_SRC(insn->code) == BPF_K) { 6743 mark_reg_unknown(env, regs, insn->dst_reg); 6744 } else if (BPF_SRC(insn->code) == BPF_X) { 6745 mark_reg_unknown(env, regs, insn->dst_reg); 6746 mark_reg_unknown(env, regs, insn->src_reg); 6747 } 6748 } 6749 return branch; 6750 } 6751 6752 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 6753 struct bpf_insn *insn, 6754 const struct bpf_reg_state *ptr_reg, 6755 const struct bpf_reg_state *off_reg, 6756 struct bpf_reg_state *dst_reg, 6757 struct bpf_sanitize_info *info, 6758 const bool commit_window) 6759 { 6760 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 6761 struct bpf_verifier_state *vstate = env->cur_state; 6762 bool off_is_imm = tnum_is_const(off_reg->var_off); 6763 bool off_is_neg = off_reg->smin_value < 0; 6764 bool ptr_is_dst_reg = ptr_reg == dst_reg; 6765 u8 opcode = BPF_OP(insn->code); 6766 u32 alu_state, alu_limit; 6767 struct bpf_reg_state tmp; 6768 bool ret; 6769 int err; 6770 6771 if (can_skip_alu_sanitation(env, insn)) 6772 return 0; 6773 6774 /* We already marked aux for masking from non-speculative 6775 * paths, thus we got here in the first place. We only care 6776 * to explore bad access from here. 6777 */ 6778 if (vstate->speculative) 6779 goto do_sim; 6780 6781 if (!commit_window) { 6782 if (!tnum_is_const(off_reg->var_off) && 6783 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 6784 return REASON_BOUNDS; 6785 6786 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 6787 (opcode == BPF_SUB && !off_is_neg); 6788 } 6789 6790 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 6791 if (err < 0) 6792 return err; 6793 6794 if (commit_window) { 6795 /* In commit phase we narrow the masking window based on 6796 * the observed pointer move after the simulated operation. 6797 */ 6798 alu_state = info->aux.alu_state; 6799 alu_limit = abs(info->aux.alu_limit - alu_limit); 6800 } else { 6801 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 6802 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 6803 alu_state |= ptr_is_dst_reg ? 6804 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 6805 } 6806 6807 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 6808 if (err < 0) 6809 return err; 6810 do_sim: 6811 /* If we're in commit phase, we're done here given we already 6812 * pushed the truncated dst_reg into the speculative verification 6813 * stack. 6814 * 6815 * Also, when register is a known constant, we rewrite register-based 6816 * operation to immediate-based, and thus do not need masking (and as 6817 * a consequence, do not need to simulate the zero-truncation either). 6818 */ 6819 if (commit_window || off_is_imm) 6820 return 0; 6821 6822 /* Simulate and find potential out-of-bounds access under 6823 * speculative execution from truncation as a result of 6824 * masking when off was not within expected range. If off 6825 * sits in dst, then we temporarily need to move ptr there 6826 * to simulate dst (== 0) +/-= ptr. Needed, for example, 6827 * for cases where we use K-based arithmetic in one direction 6828 * and truncated reg-based in the other in order to explore 6829 * bad access. 6830 */ 6831 if (!ptr_is_dst_reg) { 6832 tmp = *dst_reg; 6833 *dst_reg = *ptr_reg; 6834 } 6835 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 6836 env->insn_idx); 6837 if (!ptr_is_dst_reg && ret) 6838 *dst_reg = tmp; 6839 return !ret ? REASON_STACK : 0; 6840 } 6841 6842 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 6843 { 6844 struct bpf_verifier_state *vstate = env->cur_state; 6845 6846 /* If we simulate paths under speculation, we don't update the 6847 * insn as 'seen' such that when we verify unreachable paths in 6848 * the non-speculative domain, sanitize_dead_code() can still 6849 * rewrite/sanitize them. 6850 */ 6851 if (!vstate->speculative) 6852 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 6853 } 6854 6855 static int sanitize_err(struct bpf_verifier_env *env, 6856 const struct bpf_insn *insn, int reason, 6857 const struct bpf_reg_state *off_reg, 6858 const struct bpf_reg_state *dst_reg) 6859 { 6860 static const char *err = "pointer arithmetic with it prohibited for !root"; 6861 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 6862 u32 dst = insn->dst_reg, src = insn->src_reg; 6863 6864 switch (reason) { 6865 case REASON_BOUNDS: 6866 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 6867 off_reg == dst_reg ? dst : src, err); 6868 break; 6869 case REASON_TYPE: 6870 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 6871 off_reg == dst_reg ? src : dst, err); 6872 break; 6873 case REASON_PATHS: 6874 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 6875 dst, op, err); 6876 break; 6877 case REASON_LIMIT: 6878 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 6879 dst, op, err); 6880 break; 6881 case REASON_STACK: 6882 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 6883 dst, err); 6884 break; 6885 default: 6886 verbose(env, "verifier internal error: unknown reason (%d)\n", 6887 reason); 6888 break; 6889 } 6890 6891 return -EACCES; 6892 } 6893 6894 /* check that stack access falls within stack limits and that 'reg' doesn't 6895 * have a variable offset. 6896 * 6897 * Variable offset is prohibited for unprivileged mode for simplicity since it 6898 * requires corresponding support in Spectre masking for stack ALU. See also 6899 * retrieve_ptr_limit(). 6900 * 6901 * 6902 * 'off' includes 'reg->off'. 6903 */ 6904 static int check_stack_access_for_ptr_arithmetic( 6905 struct bpf_verifier_env *env, 6906 int regno, 6907 const struct bpf_reg_state *reg, 6908 int off) 6909 { 6910 if (!tnum_is_const(reg->var_off)) { 6911 char tn_buf[48]; 6912 6913 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6914 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 6915 regno, tn_buf, off); 6916 return -EACCES; 6917 } 6918 6919 if (off >= 0 || off < -MAX_BPF_STACK) { 6920 verbose(env, "R%d stack pointer arithmetic goes out of range, " 6921 "prohibited for !root; off=%d\n", regno, off); 6922 return -EACCES; 6923 } 6924 6925 return 0; 6926 } 6927 6928 static int sanitize_check_bounds(struct bpf_verifier_env *env, 6929 const struct bpf_insn *insn, 6930 const struct bpf_reg_state *dst_reg) 6931 { 6932 u32 dst = insn->dst_reg; 6933 6934 /* For unprivileged we require that resulting offset must be in bounds 6935 * in order to be able to sanitize access later on. 6936 */ 6937 if (env->bypass_spec_v1) 6938 return 0; 6939 6940 switch (dst_reg->type) { 6941 case PTR_TO_STACK: 6942 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 6943 dst_reg->off + dst_reg->var_off.value)) 6944 return -EACCES; 6945 break; 6946 case PTR_TO_MAP_VALUE: 6947 if (check_map_access(env, dst, dst_reg->off, 1, false)) { 6948 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 6949 "prohibited for !root\n", dst); 6950 return -EACCES; 6951 } 6952 break; 6953 default: 6954 break; 6955 } 6956 6957 return 0; 6958 } 6959 6960 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 6961 * Caller should also handle BPF_MOV case separately. 6962 * If we return -EACCES, caller may want to try again treating pointer as a 6963 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 6964 */ 6965 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 6966 struct bpf_insn *insn, 6967 const struct bpf_reg_state *ptr_reg, 6968 const struct bpf_reg_state *off_reg) 6969 { 6970 struct bpf_verifier_state *vstate = env->cur_state; 6971 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6972 struct bpf_reg_state *regs = state->regs, *dst_reg; 6973 bool known = tnum_is_const(off_reg->var_off); 6974 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 6975 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 6976 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 6977 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 6978 struct bpf_sanitize_info info = {}; 6979 u8 opcode = BPF_OP(insn->code); 6980 u32 dst = insn->dst_reg; 6981 int ret; 6982 6983 dst_reg = ®s[dst]; 6984 6985 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 6986 smin_val > smax_val || umin_val > umax_val) { 6987 /* Taint dst register if offset had invalid bounds derived from 6988 * e.g. dead branches. 6989 */ 6990 __mark_reg_unknown(env, dst_reg); 6991 return 0; 6992 } 6993 6994 if (BPF_CLASS(insn->code) != BPF_ALU64) { 6995 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 6996 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 6997 __mark_reg_unknown(env, dst_reg); 6998 return 0; 6999 } 7000 7001 verbose(env, 7002 "R%d 32-bit pointer arithmetic prohibited\n", 7003 dst); 7004 return -EACCES; 7005 } 7006 7007 switch (ptr_reg->type) { 7008 case PTR_TO_MAP_VALUE_OR_NULL: 7009 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 7010 dst, reg_type_str[ptr_reg->type]); 7011 return -EACCES; 7012 case CONST_PTR_TO_MAP: 7013 /* smin_val represents the known value */ 7014 if (known && smin_val == 0 && opcode == BPF_ADD) 7015 break; 7016 fallthrough; 7017 case PTR_TO_PACKET_END: 7018 case PTR_TO_SOCKET: 7019 case PTR_TO_SOCKET_OR_NULL: 7020 case PTR_TO_SOCK_COMMON: 7021 case PTR_TO_SOCK_COMMON_OR_NULL: 7022 case PTR_TO_TCP_SOCK: 7023 case PTR_TO_TCP_SOCK_OR_NULL: 7024 case PTR_TO_XDP_SOCK: 7025 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 7026 dst, reg_type_str[ptr_reg->type]); 7027 return -EACCES; 7028 default: 7029 break; 7030 } 7031 7032 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 7033 * The id may be overwritten later if we create a new variable offset. 7034 */ 7035 dst_reg->type = ptr_reg->type; 7036 dst_reg->id = ptr_reg->id; 7037 7038 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 7039 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 7040 return -EINVAL; 7041 7042 /* pointer types do not carry 32-bit bounds at the moment. */ 7043 __mark_reg32_unbounded(dst_reg); 7044 7045 if (sanitize_needed(opcode)) { 7046 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 7047 &info, false); 7048 if (ret < 0) 7049 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7050 } 7051 7052 switch (opcode) { 7053 case BPF_ADD: 7054 /* We can take a fixed offset as long as it doesn't overflow 7055 * the s32 'off' field 7056 */ 7057 if (known && (ptr_reg->off + smin_val == 7058 (s64)(s32)(ptr_reg->off + smin_val))) { 7059 /* pointer += K. Accumulate it into fixed offset */ 7060 dst_reg->smin_value = smin_ptr; 7061 dst_reg->smax_value = smax_ptr; 7062 dst_reg->umin_value = umin_ptr; 7063 dst_reg->umax_value = umax_ptr; 7064 dst_reg->var_off = ptr_reg->var_off; 7065 dst_reg->off = ptr_reg->off + smin_val; 7066 dst_reg->raw = ptr_reg->raw; 7067 break; 7068 } 7069 /* A new variable offset is created. Note that off_reg->off 7070 * == 0, since it's a scalar. 7071 * dst_reg gets the pointer type and since some positive 7072 * integer value was added to the pointer, give it a new 'id' 7073 * if it's a PTR_TO_PACKET. 7074 * this creates a new 'base' pointer, off_reg (variable) gets 7075 * added into the variable offset, and we copy the fixed offset 7076 * from ptr_reg. 7077 */ 7078 if (signed_add_overflows(smin_ptr, smin_val) || 7079 signed_add_overflows(smax_ptr, smax_val)) { 7080 dst_reg->smin_value = S64_MIN; 7081 dst_reg->smax_value = S64_MAX; 7082 } else { 7083 dst_reg->smin_value = smin_ptr + smin_val; 7084 dst_reg->smax_value = smax_ptr + smax_val; 7085 } 7086 if (umin_ptr + umin_val < umin_ptr || 7087 umax_ptr + umax_val < umax_ptr) { 7088 dst_reg->umin_value = 0; 7089 dst_reg->umax_value = U64_MAX; 7090 } else { 7091 dst_reg->umin_value = umin_ptr + umin_val; 7092 dst_reg->umax_value = umax_ptr + umax_val; 7093 } 7094 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 7095 dst_reg->off = ptr_reg->off; 7096 dst_reg->raw = ptr_reg->raw; 7097 if (reg_is_pkt_pointer(ptr_reg)) { 7098 dst_reg->id = ++env->id_gen; 7099 /* something was added to pkt_ptr, set range to zero */ 7100 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7101 } 7102 break; 7103 case BPF_SUB: 7104 if (dst_reg == off_reg) { 7105 /* scalar -= pointer. Creates an unknown scalar */ 7106 verbose(env, "R%d tried to subtract pointer from scalar\n", 7107 dst); 7108 return -EACCES; 7109 } 7110 /* We don't allow subtraction from FP, because (according to 7111 * test_verifier.c test "invalid fp arithmetic", JITs might not 7112 * be able to deal with it. 7113 */ 7114 if (ptr_reg->type == PTR_TO_STACK) { 7115 verbose(env, "R%d subtraction from stack pointer prohibited\n", 7116 dst); 7117 return -EACCES; 7118 } 7119 if (known && (ptr_reg->off - smin_val == 7120 (s64)(s32)(ptr_reg->off - smin_val))) { 7121 /* pointer -= K. Subtract it from fixed offset */ 7122 dst_reg->smin_value = smin_ptr; 7123 dst_reg->smax_value = smax_ptr; 7124 dst_reg->umin_value = umin_ptr; 7125 dst_reg->umax_value = umax_ptr; 7126 dst_reg->var_off = ptr_reg->var_off; 7127 dst_reg->id = ptr_reg->id; 7128 dst_reg->off = ptr_reg->off - smin_val; 7129 dst_reg->raw = ptr_reg->raw; 7130 break; 7131 } 7132 /* A new variable offset is created. If the subtrahend is known 7133 * nonnegative, then any reg->range we had before is still good. 7134 */ 7135 if (signed_sub_overflows(smin_ptr, smax_val) || 7136 signed_sub_overflows(smax_ptr, smin_val)) { 7137 /* Overflow possible, we know nothing */ 7138 dst_reg->smin_value = S64_MIN; 7139 dst_reg->smax_value = S64_MAX; 7140 } else { 7141 dst_reg->smin_value = smin_ptr - smax_val; 7142 dst_reg->smax_value = smax_ptr - smin_val; 7143 } 7144 if (umin_ptr < umax_val) { 7145 /* Overflow possible, we know nothing */ 7146 dst_reg->umin_value = 0; 7147 dst_reg->umax_value = U64_MAX; 7148 } else { 7149 /* Cannot overflow (as long as bounds are consistent) */ 7150 dst_reg->umin_value = umin_ptr - umax_val; 7151 dst_reg->umax_value = umax_ptr - umin_val; 7152 } 7153 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 7154 dst_reg->off = ptr_reg->off; 7155 dst_reg->raw = ptr_reg->raw; 7156 if (reg_is_pkt_pointer(ptr_reg)) { 7157 dst_reg->id = ++env->id_gen; 7158 /* something was added to pkt_ptr, set range to zero */ 7159 if (smin_val < 0) 7160 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7161 } 7162 break; 7163 case BPF_AND: 7164 case BPF_OR: 7165 case BPF_XOR: 7166 /* bitwise ops on pointers are troublesome, prohibit. */ 7167 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 7168 dst, bpf_alu_string[opcode >> 4]); 7169 return -EACCES; 7170 default: 7171 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 7172 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 7173 dst, bpf_alu_string[opcode >> 4]); 7174 return -EACCES; 7175 } 7176 7177 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 7178 return -EINVAL; 7179 7180 __update_reg_bounds(dst_reg); 7181 __reg_deduce_bounds(dst_reg); 7182 __reg_bound_offset(dst_reg); 7183 7184 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 7185 return -EACCES; 7186 if (sanitize_needed(opcode)) { 7187 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 7188 &info, true); 7189 if (ret < 0) 7190 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7191 } 7192 7193 return 0; 7194 } 7195 7196 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 7197 struct bpf_reg_state *src_reg) 7198 { 7199 s32 smin_val = src_reg->s32_min_value; 7200 s32 smax_val = src_reg->s32_max_value; 7201 u32 umin_val = src_reg->u32_min_value; 7202 u32 umax_val = src_reg->u32_max_value; 7203 7204 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 7205 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 7206 dst_reg->s32_min_value = S32_MIN; 7207 dst_reg->s32_max_value = S32_MAX; 7208 } else { 7209 dst_reg->s32_min_value += smin_val; 7210 dst_reg->s32_max_value += smax_val; 7211 } 7212 if (dst_reg->u32_min_value + umin_val < umin_val || 7213 dst_reg->u32_max_value + umax_val < umax_val) { 7214 dst_reg->u32_min_value = 0; 7215 dst_reg->u32_max_value = U32_MAX; 7216 } else { 7217 dst_reg->u32_min_value += umin_val; 7218 dst_reg->u32_max_value += umax_val; 7219 } 7220 } 7221 7222 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 7223 struct bpf_reg_state *src_reg) 7224 { 7225 s64 smin_val = src_reg->smin_value; 7226 s64 smax_val = src_reg->smax_value; 7227 u64 umin_val = src_reg->umin_value; 7228 u64 umax_val = src_reg->umax_value; 7229 7230 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 7231 signed_add_overflows(dst_reg->smax_value, smax_val)) { 7232 dst_reg->smin_value = S64_MIN; 7233 dst_reg->smax_value = S64_MAX; 7234 } else { 7235 dst_reg->smin_value += smin_val; 7236 dst_reg->smax_value += smax_val; 7237 } 7238 if (dst_reg->umin_value + umin_val < umin_val || 7239 dst_reg->umax_value + umax_val < umax_val) { 7240 dst_reg->umin_value = 0; 7241 dst_reg->umax_value = U64_MAX; 7242 } else { 7243 dst_reg->umin_value += umin_val; 7244 dst_reg->umax_value += umax_val; 7245 } 7246 } 7247 7248 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 7249 struct bpf_reg_state *src_reg) 7250 { 7251 s32 smin_val = src_reg->s32_min_value; 7252 s32 smax_val = src_reg->s32_max_value; 7253 u32 umin_val = src_reg->u32_min_value; 7254 u32 umax_val = src_reg->u32_max_value; 7255 7256 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 7257 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 7258 /* Overflow possible, we know nothing */ 7259 dst_reg->s32_min_value = S32_MIN; 7260 dst_reg->s32_max_value = S32_MAX; 7261 } else { 7262 dst_reg->s32_min_value -= smax_val; 7263 dst_reg->s32_max_value -= smin_val; 7264 } 7265 if (dst_reg->u32_min_value < umax_val) { 7266 /* Overflow possible, we know nothing */ 7267 dst_reg->u32_min_value = 0; 7268 dst_reg->u32_max_value = U32_MAX; 7269 } else { 7270 /* Cannot overflow (as long as bounds are consistent) */ 7271 dst_reg->u32_min_value -= umax_val; 7272 dst_reg->u32_max_value -= umin_val; 7273 } 7274 } 7275 7276 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 7277 struct bpf_reg_state *src_reg) 7278 { 7279 s64 smin_val = src_reg->smin_value; 7280 s64 smax_val = src_reg->smax_value; 7281 u64 umin_val = src_reg->umin_value; 7282 u64 umax_val = src_reg->umax_value; 7283 7284 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 7285 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 7286 /* Overflow possible, we know nothing */ 7287 dst_reg->smin_value = S64_MIN; 7288 dst_reg->smax_value = S64_MAX; 7289 } else { 7290 dst_reg->smin_value -= smax_val; 7291 dst_reg->smax_value -= smin_val; 7292 } 7293 if (dst_reg->umin_value < umax_val) { 7294 /* Overflow possible, we know nothing */ 7295 dst_reg->umin_value = 0; 7296 dst_reg->umax_value = U64_MAX; 7297 } else { 7298 /* Cannot overflow (as long as bounds are consistent) */ 7299 dst_reg->umin_value -= umax_val; 7300 dst_reg->umax_value -= umin_val; 7301 } 7302 } 7303 7304 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 7305 struct bpf_reg_state *src_reg) 7306 { 7307 s32 smin_val = src_reg->s32_min_value; 7308 u32 umin_val = src_reg->u32_min_value; 7309 u32 umax_val = src_reg->u32_max_value; 7310 7311 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 7312 /* Ain't nobody got time to multiply that sign */ 7313 __mark_reg32_unbounded(dst_reg); 7314 return; 7315 } 7316 /* Both values are positive, so we can work with unsigned and 7317 * copy the result to signed (unless it exceeds S32_MAX). 7318 */ 7319 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 7320 /* Potential overflow, we know nothing */ 7321 __mark_reg32_unbounded(dst_reg); 7322 return; 7323 } 7324 dst_reg->u32_min_value *= umin_val; 7325 dst_reg->u32_max_value *= umax_val; 7326 if (dst_reg->u32_max_value > S32_MAX) { 7327 /* Overflow possible, we know nothing */ 7328 dst_reg->s32_min_value = S32_MIN; 7329 dst_reg->s32_max_value = S32_MAX; 7330 } else { 7331 dst_reg->s32_min_value = dst_reg->u32_min_value; 7332 dst_reg->s32_max_value = dst_reg->u32_max_value; 7333 } 7334 } 7335 7336 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 7337 struct bpf_reg_state *src_reg) 7338 { 7339 s64 smin_val = src_reg->smin_value; 7340 u64 umin_val = src_reg->umin_value; 7341 u64 umax_val = src_reg->umax_value; 7342 7343 if (smin_val < 0 || dst_reg->smin_value < 0) { 7344 /* Ain't nobody got time to multiply that sign */ 7345 __mark_reg64_unbounded(dst_reg); 7346 return; 7347 } 7348 /* Both values are positive, so we can work with unsigned and 7349 * copy the result to signed (unless it exceeds S64_MAX). 7350 */ 7351 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 7352 /* Potential overflow, we know nothing */ 7353 __mark_reg64_unbounded(dst_reg); 7354 return; 7355 } 7356 dst_reg->umin_value *= umin_val; 7357 dst_reg->umax_value *= umax_val; 7358 if (dst_reg->umax_value > S64_MAX) { 7359 /* Overflow possible, we know nothing */ 7360 dst_reg->smin_value = S64_MIN; 7361 dst_reg->smax_value = S64_MAX; 7362 } else { 7363 dst_reg->smin_value = dst_reg->umin_value; 7364 dst_reg->smax_value = dst_reg->umax_value; 7365 } 7366 } 7367 7368 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 7369 struct bpf_reg_state *src_reg) 7370 { 7371 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7372 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7373 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7374 s32 smin_val = src_reg->s32_min_value; 7375 u32 umax_val = src_reg->u32_max_value; 7376 7377 if (src_known && dst_known) { 7378 __mark_reg32_known(dst_reg, var32_off.value); 7379 return; 7380 } 7381 7382 /* We get our minimum from the var_off, since that's inherently 7383 * bitwise. Our maximum is the minimum of the operands' maxima. 7384 */ 7385 dst_reg->u32_min_value = var32_off.value; 7386 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 7387 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7388 /* Lose signed bounds when ANDing negative numbers, 7389 * ain't nobody got time for that. 7390 */ 7391 dst_reg->s32_min_value = S32_MIN; 7392 dst_reg->s32_max_value = S32_MAX; 7393 } else { 7394 /* ANDing two positives gives a positive, so safe to 7395 * cast result into s64. 7396 */ 7397 dst_reg->s32_min_value = dst_reg->u32_min_value; 7398 dst_reg->s32_max_value = dst_reg->u32_max_value; 7399 } 7400 } 7401 7402 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 7403 struct bpf_reg_state *src_reg) 7404 { 7405 bool src_known = tnum_is_const(src_reg->var_off); 7406 bool dst_known = tnum_is_const(dst_reg->var_off); 7407 s64 smin_val = src_reg->smin_value; 7408 u64 umax_val = src_reg->umax_value; 7409 7410 if (src_known && dst_known) { 7411 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7412 return; 7413 } 7414 7415 /* We get our minimum from the var_off, since that's inherently 7416 * bitwise. Our maximum is the minimum of the operands' maxima. 7417 */ 7418 dst_reg->umin_value = dst_reg->var_off.value; 7419 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 7420 if (dst_reg->smin_value < 0 || smin_val < 0) { 7421 /* Lose signed bounds when ANDing negative numbers, 7422 * ain't nobody got time for that. 7423 */ 7424 dst_reg->smin_value = S64_MIN; 7425 dst_reg->smax_value = S64_MAX; 7426 } else { 7427 /* ANDing two positives gives a positive, so safe to 7428 * cast result into s64. 7429 */ 7430 dst_reg->smin_value = dst_reg->umin_value; 7431 dst_reg->smax_value = dst_reg->umax_value; 7432 } 7433 /* We may learn something more from the var_off */ 7434 __update_reg_bounds(dst_reg); 7435 } 7436 7437 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 7438 struct bpf_reg_state *src_reg) 7439 { 7440 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7441 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7442 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7443 s32 smin_val = src_reg->s32_min_value; 7444 u32 umin_val = src_reg->u32_min_value; 7445 7446 if (src_known && dst_known) { 7447 __mark_reg32_known(dst_reg, var32_off.value); 7448 return; 7449 } 7450 7451 /* We get our maximum from the var_off, and our minimum is the 7452 * maximum of the operands' minima 7453 */ 7454 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 7455 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7456 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7457 /* Lose signed bounds when ORing negative numbers, 7458 * ain't nobody got time for that. 7459 */ 7460 dst_reg->s32_min_value = S32_MIN; 7461 dst_reg->s32_max_value = S32_MAX; 7462 } else { 7463 /* ORing two positives gives a positive, so safe to 7464 * cast result into s64. 7465 */ 7466 dst_reg->s32_min_value = dst_reg->u32_min_value; 7467 dst_reg->s32_max_value = dst_reg->u32_max_value; 7468 } 7469 } 7470 7471 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 7472 struct bpf_reg_state *src_reg) 7473 { 7474 bool src_known = tnum_is_const(src_reg->var_off); 7475 bool dst_known = tnum_is_const(dst_reg->var_off); 7476 s64 smin_val = src_reg->smin_value; 7477 u64 umin_val = src_reg->umin_value; 7478 7479 if (src_known && dst_known) { 7480 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7481 return; 7482 } 7483 7484 /* We get our maximum from the var_off, and our minimum is the 7485 * maximum of the operands' minima 7486 */ 7487 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 7488 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7489 if (dst_reg->smin_value < 0 || smin_val < 0) { 7490 /* Lose signed bounds when ORing negative numbers, 7491 * ain't nobody got time for that. 7492 */ 7493 dst_reg->smin_value = S64_MIN; 7494 dst_reg->smax_value = S64_MAX; 7495 } else { 7496 /* ORing two positives gives a positive, so safe to 7497 * cast result into s64. 7498 */ 7499 dst_reg->smin_value = dst_reg->umin_value; 7500 dst_reg->smax_value = dst_reg->umax_value; 7501 } 7502 /* We may learn something more from the var_off */ 7503 __update_reg_bounds(dst_reg); 7504 } 7505 7506 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 7507 struct bpf_reg_state *src_reg) 7508 { 7509 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7510 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7511 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7512 s32 smin_val = src_reg->s32_min_value; 7513 7514 if (src_known && dst_known) { 7515 __mark_reg32_known(dst_reg, var32_off.value); 7516 return; 7517 } 7518 7519 /* We get both minimum and maximum from the var32_off. */ 7520 dst_reg->u32_min_value = var32_off.value; 7521 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7522 7523 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 7524 /* XORing two positive sign numbers gives a positive, 7525 * so safe to cast u32 result into s32. 7526 */ 7527 dst_reg->s32_min_value = dst_reg->u32_min_value; 7528 dst_reg->s32_max_value = dst_reg->u32_max_value; 7529 } else { 7530 dst_reg->s32_min_value = S32_MIN; 7531 dst_reg->s32_max_value = S32_MAX; 7532 } 7533 } 7534 7535 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 7536 struct bpf_reg_state *src_reg) 7537 { 7538 bool src_known = tnum_is_const(src_reg->var_off); 7539 bool dst_known = tnum_is_const(dst_reg->var_off); 7540 s64 smin_val = src_reg->smin_value; 7541 7542 if (src_known && dst_known) { 7543 /* dst_reg->var_off.value has been updated earlier */ 7544 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7545 return; 7546 } 7547 7548 /* We get both minimum and maximum from the var_off. */ 7549 dst_reg->umin_value = dst_reg->var_off.value; 7550 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7551 7552 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 7553 /* XORing two positive sign numbers gives a positive, 7554 * so safe to cast u64 result into s64. 7555 */ 7556 dst_reg->smin_value = dst_reg->umin_value; 7557 dst_reg->smax_value = dst_reg->umax_value; 7558 } else { 7559 dst_reg->smin_value = S64_MIN; 7560 dst_reg->smax_value = S64_MAX; 7561 } 7562 7563 __update_reg_bounds(dst_reg); 7564 } 7565 7566 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7567 u64 umin_val, u64 umax_val) 7568 { 7569 /* We lose all sign bit information (except what we can pick 7570 * up from var_off) 7571 */ 7572 dst_reg->s32_min_value = S32_MIN; 7573 dst_reg->s32_max_value = S32_MAX; 7574 /* If we might shift our top bit out, then we know nothing */ 7575 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 7576 dst_reg->u32_min_value = 0; 7577 dst_reg->u32_max_value = U32_MAX; 7578 } else { 7579 dst_reg->u32_min_value <<= umin_val; 7580 dst_reg->u32_max_value <<= umax_val; 7581 } 7582 } 7583 7584 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7585 struct bpf_reg_state *src_reg) 7586 { 7587 u32 umax_val = src_reg->u32_max_value; 7588 u32 umin_val = src_reg->u32_min_value; 7589 /* u32 alu operation will zext upper bits */ 7590 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7591 7592 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7593 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 7594 /* Not required but being careful mark reg64 bounds as unknown so 7595 * that we are forced to pick them up from tnum and zext later and 7596 * if some path skips this step we are still safe. 7597 */ 7598 __mark_reg64_unbounded(dst_reg); 7599 __update_reg32_bounds(dst_reg); 7600 } 7601 7602 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 7603 u64 umin_val, u64 umax_val) 7604 { 7605 /* Special case <<32 because it is a common compiler pattern to sign 7606 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 7607 * positive we know this shift will also be positive so we can track 7608 * bounds correctly. Otherwise we lose all sign bit information except 7609 * what we can pick up from var_off. Perhaps we can generalize this 7610 * later to shifts of any length. 7611 */ 7612 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 7613 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 7614 else 7615 dst_reg->smax_value = S64_MAX; 7616 7617 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 7618 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 7619 else 7620 dst_reg->smin_value = S64_MIN; 7621 7622 /* If we might shift our top bit out, then we know nothing */ 7623 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 7624 dst_reg->umin_value = 0; 7625 dst_reg->umax_value = U64_MAX; 7626 } else { 7627 dst_reg->umin_value <<= umin_val; 7628 dst_reg->umax_value <<= umax_val; 7629 } 7630 } 7631 7632 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 7633 struct bpf_reg_state *src_reg) 7634 { 7635 u64 umax_val = src_reg->umax_value; 7636 u64 umin_val = src_reg->umin_value; 7637 7638 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 7639 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 7640 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7641 7642 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 7643 /* We may learn something more from the var_off */ 7644 __update_reg_bounds(dst_reg); 7645 } 7646 7647 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 7648 struct bpf_reg_state *src_reg) 7649 { 7650 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7651 u32 umax_val = src_reg->u32_max_value; 7652 u32 umin_val = src_reg->u32_min_value; 7653 7654 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 7655 * be negative, then either: 7656 * 1) src_reg might be zero, so the sign bit of the result is 7657 * unknown, so we lose our signed bounds 7658 * 2) it's known negative, thus the unsigned bounds capture the 7659 * signed bounds 7660 * 3) the signed bounds cross zero, so they tell us nothing 7661 * about the result 7662 * If the value in dst_reg is known nonnegative, then again the 7663 * unsigned bounds capture the signed bounds. 7664 * Thus, in all cases it suffices to blow away our signed bounds 7665 * and rely on inferring new ones from the unsigned bounds and 7666 * var_off of the result. 7667 */ 7668 dst_reg->s32_min_value = S32_MIN; 7669 dst_reg->s32_max_value = S32_MAX; 7670 7671 dst_reg->var_off = tnum_rshift(subreg, umin_val); 7672 dst_reg->u32_min_value >>= umax_val; 7673 dst_reg->u32_max_value >>= umin_val; 7674 7675 __mark_reg64_unbounded(dst_reg); 7676 __update_reg32_bounds(dst_reg); 7677 } 7678 7679 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 7680 struct bpf_reg_state *src_reg) 7681 { 7682 u64 umax_val = src_reg->umax_value; 7683 u64 umin_val = src_reg->umin_value; 7684 7685 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 7686 * be negative, then either: 7687 * 1) src_reg might be zero, so the sign bit of the result is 7688 * unknown, so we lose our signed bounds 7689 * 2) it's known negative, thus the unsigned bounds capture the 7690 * signed bounds 7691 * 3) the signed bounds cross zero, so they tell us nothing 7692 * about the result 7693 * If the value in dst_reg is known nonnegative, then again the 7694 * unsigned bounds capture the signed bounds. 7695 * Thus, in all cases it suffices to blow away our signed bounds 7696 * and rely on inferring new ones from the unsigned bounds and 7697 * var_off of the result. 7698 */ 7699 dst_reg->smin_value = S64_MIN; 7700 dst_reg->smax_value = S64_MAX; 7701 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 7702 dst_reg->umin_value >>= umax_val; 7703 dst_reg->umax_value >>= umin_val; 7704 7705 /* Its not easy to operate on alu32 bounds here because it depends 7706 * on bits being shifted in. Take easy way out and mark unbounded 7707 * so we can recalculate later from tnum. 7708 */ 7709 __mark_reg32_unbounded(dst_reg); 7710 __update_reg_bounds(dst_reg); 7711 } 7712 7713 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 7714 struct bpf_reg_state *src_reg) 7715 { 7716 u64 umin_val = src_reg->u32_min_value; 7717 7718 /* Upon reaching here, src_known is true and 7719 * umax_val is equal to umin_val. 7720 */ 7721 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 7722 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 7723 7724 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 7725 7726 /* blow away the dst_reg umin_value/umax_value and rely on 7727 * dst_reg var_off to refine the result. 7728 */ 7729 dst_reg->u32_min_value = 0; 7730 dst_reg->u32_max_value = U32_MAX; 7731 7732 __mark_reg64_unbounded(dst_reg); 7733 __update_reg32_bounds(dst_reg); 7734 } 7735 7736 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 7737 struct bpf_reg_state *src_reg) 7738 { 7739 u64 umin_val = src_reg->umin_value; 7740 7741 /* Upon reaching here, src_known is true and umax_val is equal 7742 * to umin_val. 7743 */ 7744 dst_reg->smin_value >>= umin_val; 7745 dst_reg->smax_value >>= umin_val; 7746 7747 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 7748 7749 /* blow away the dst_reg umin_value/umax_value and rely on 7750 * dst_reg var_off to refine the result. 7751 */ 7752 dst_reg->umin_value = 0; 7753 dst_reg->umax_value = U64_MAX; 7754 7755 /* Its not easy to operate on alu32 bounds here because it depends 7756 * on bits being shifted in from upper 32-bits. Take easy way out 7757 * and mark unbounded so we can recalculate later from tnum. 7758 */ 7759 __mark_reg32_unbounded(dst_reg); 7760 __update_reg_bounds(dst_reg); 7761 } 7762 7763 /* WARNING: This function does calculations on 64-bit values, but the actual 7764 * execution may occur on 32-bit values. Therefore, things like bitshifts 7765 * need extra checks in the 32-bit case. 7766 */ 7767 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 7768 struct bpf_insn *insn, 7769 struct bpf_reg_state *dst_reg, 7770 struct bpf_reg_state src_reg) 7771 { 7772 struct bpf_reg_state *regs = cur_regs(env); 7773 u8 opcode = BPF_OP(insn->code); 7774 bool src_known; 7775 s64 smin_val, smax_val; 7776 u64 umin_val, umax_val; 7777 s32 s32_min_val, s32_max_val; 7778 u32 u32_min_val, u32_max_val; 7779 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 7780 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 7781 int ret; 7782 7783 smin_val = src_reg.smin_value; 7784 smax_val = src_reg.smax_value; 7785 umin_val = src_reg.umin_value; 7786 umax_val = src_reg.umax_value; 7787 7788 s32_min_val = src_reg.s32_min_value; 7789 s32_max_val = src_reg.s32_max_value; 7790 u32_min_val = src_reg.u32_min_value; 7791 u32_max_val = src_reg.u32_max_value; 7792 7793 if (alu32) { 7794 src_known = tnum_subreg_is_const(src_reg.var_off); 7795 if ((src_known && 7796 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 7797 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 7798 /* Taint dst register if offset had invalid bounds 7799 * derived from e.g. dead branches. 7800 */ 7801 __mark_reg_unknown(env, dst_reg); 7802 return 0; 7803 } 7804 } else { 7805 src_known = tnum_is_const(src_reg.var_off); 7806 if ((src_known && 7807 (smin_val != smax_val || umin_val != umax_val)) || 7808 smin_val > smax_val || umin_val > umax_val) { 7809 /* Taint dst register if offset had invalid bounds 7810 * derived from e.g. dead branches. 7811 */ 7812 __mark_reg_unknown(env, dst_reg); 7813 return 0; 7814 } 7815 } 7816 7817 if (!src_known && 7818 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 7819 __mark_reg_unknown(env, dst_reg); 7820 return 0; 7821 } 7822 7823 if (sanitize_needed(opcode)) { 7824 ret = sanitize_val_alu(env, insn); 7825 if (ret < 0) 7826 return sanitize_err(env, insn, ret, NULL, NULL); 7827 } 7828 7829 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 7830 * There are two classes of instructions: The first class we track both 7831 * alu32 and alu64 sign/unsigned bounds independently this provides the 7832 * greatest amount of precision when alu operations are mixed with jmp32 7833 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 7834 * and BPF_OR. This is possible because these ops have fairly easy to 7835 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 7836 * See alu32 verifier tests for examples. The second class of 7837 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 7838 * with regards to tracking sign/unsigned bounds because the bits may 7839 * cross subreg boundaries in the alu64 case. When this happens we mark 7840 * the reg unbounded in the subreg bound space and use the resulting 7841 * tnum to calculate an approximation of the sign/unsigned bounds. 7842 */ 7843 switch (opcode) { 7844 case BPF_ADD: 7845 scalar32_min_max_add(dst_reg, &src_reg); 7846 scalar_min_max_add(dst_reg, &src_reg); 7847 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 7848 break; 7849 case BPF_SUB: 7850 scalar32_min_max_sub(dst_reg, &src_reg); 7851 scalar_min_max_sub(dst_reg, &src_reg); 7852 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 7853 break; 7854 case BPF_MUL: 7855 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 7856 scalar32_min_max_mul(dst_reg, &src_reg); 7857 scalar_min_max_mul(dst_reg, &src_reg); 7858 break; 7859 case BPF_AND: 7860 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 7861 scalar32_min_max_and(dst_reg, &src_reg); 7862 scalar_min_max_and(dst_reg, &src_reg); 7863 break; 7864 case BPF_OR: 7865 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 7866 scalar32_min_max_or(dst_reg, &src_reg); 7867 scalar_min_max_or(dst_reg, &src_reg); 7868 break; 7869 case BPF_XOR: 7870 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 7871 scalar32_min_max_xor(dst_reg, &src_reg); 7872 scalar_min_max_xor(dst_reg, &src_reg); 7873 break; 7874 case BPF_LSH: 7875 if (umax_val >= insn_bitness) { 7876 /* Shifts greater than 31 or 63 are undefined. 7877 * This includes shifts by a negative number. 7878 */ 7879 mark_reg_unknown(env, regs, insn->dst_reg); 7880 break; 7881 } 7882 if (alu32) 7883 scalar32_min_max_lsh(dst_reg, &src_reg); 7884 else 7885 scalar_min_max_lsh(dst_reg, &src_reg); 7886 break; 7887 case BPF_RSH: 7888 if (umax_val >= insn_bitness) { 7889 /* Shifts greater than 31 or 63 are undefined. 7890 * This includes shifts by a negative number. 7891 */ 7892 mark_reg_unknown(env, regs, insn->dst_reg); 7893 break; 7894 } 7895 if (alu32) 7896 scalar32_min_max_rsh(dst_reg, &src_reg); 7897 else 7898 scalar_min_max_rsh(dst_reg, &src_reg); 7899 break; 7900 case BPF_ARSH: 7901 if (umax_val >= insn_bitness) { 7902 /* Shifts greater than 31 or 63 are undefined. 7903 * This includes shifts by a negative number. 7904 */ 7905 mark_reg_unknown(env, regs, insn->dst_reg); 7906 break; 7907 } 7908 if (alu32) 7909 scalar32_min_max_arsh(dst_reg, &src_reg); 7910 else 7911 scalar_min_max_arsh(dst_reg, &src_reg); 7912 break; 7913 default: 7914 mark_reg_unknown(env, regs, insn->dst_reg); 7915 break; 7916 } 7917 7918 /* ALU32 ops are zero extended into 64bit register */ 7919 if (alu32) 7920 zext_32_to_64(dst_reg); 7921 7922 __update_reg_bounds(dst_reg); 7923 __reg_deduce_bounds(dst_reg); 7924 __reg_bound_offset(dst_reg); 7925 return 0; 7926 } 7927 7928 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 7929 * and var_off. 7930 */ 7931 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 7932 struct bpf_insn *insn) 7933 { 7934 struct bpf_verifier_state *vstate = env->cur_state; 7935 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7936 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 7937 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 7938 u8 opcode = BPF_OP(insn->code); 7939 int err; 7940 7941 dst_reg = ®s[insn->dst_reg]; 7942 src_reg = NULL; 7943 if (dst_reg->type != SCALAR_VALUE) 7944 ptr_reg = dst_reg; 7945 else 7946 /* Make sure ID is cleared otherwise dst_reg min/max could be 7947 * incorrectly propagated into other registers by find_equal_scalars() 7948 */ 7949 dst_reg->id = 0; 7950 if (BPF_SRC(insn->code) == BPF_X) { 7951 src_reg = ®s[insn->src_reg]; 7952 if (src_reg->type != SCALAR_VALUE) { 7953 if (dst_reg->type != SCALAR_VALUE) { 7954 /* Combining two pointers by any ALU op yields 7955 * an arbitrary scalar. Disallow all math except 7956 * pointer subtraction 7957 */ 7958 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 7959 mark_reg_unknown(env, regs, insn->dst_reg); 7960 return 0; 7961 } 7962 verbose(env, "R%d pointer %s pointer prohibited\n", 7963 insn->dst_reg, 7964 bpf_alu_string[opcode >> 4]); 7965 return -EACCES; 7966 } else { 7967 /* scalar += pointer 7968 * This is legal, but we have to reverse our 7969 * src/dest handling in computing the range 7970 */ 7971 err = mark_chain_precision(env, insn->dst_reg); 7972 if (err) 7973 return err; 7974 return adjust_ptr_min_max_vals(env, insn, 7975 src_reg, dst_reg); 7976 } 7977 } else if (ptr_reg) { 7978 /* pointer += scalar */ 7979 err = mark_chain_precision(env, insn->src_reg); 7980 if (err) 7981 return err; 7982 return adjust_ptr_min_max_vals(env, insn, 7983 dst_reg, src_reg); 7984 } 7985 } else { 7986 /* Pretend the src is a reg with a known value, since we only 7987 * need to be able to read from this state. 7988 */ 7989 off_reg.type = SCALAR_VALUE; 7990 __mark_reg_known(&off_reg, insn->imm); 7991 src_reg = &off_reg; 7992 if (ptr_reg) /* pointer += K */ 7993 return adjust_ptr_min_max_vals(env, insn, 7994 ptr_reg, src_reg); 7995 } 7996 7997 /* Got here implies adding two SCALAR_VALUEs */ 7998 if (WARN_ON_ONCE(ptr_reg)) { 7999 print_verifier_state(env, state); 8000 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 8001 return -EINVAL; 8002 } 8003 if (WARN_ON(!src_reg)) { 8004 print_verifier_state(env, state); 8005 verbose(env, "verifier internal error: no src_reg\n"); 8006 return -EINVAL; 8007 } 8008 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 8009 } 8010 8011 /* check validity of 32-bit and 64-bit arithmetic operations */ 8012 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 8013 { 8014 struct bpf_reg_state *regs = cur_regs(env); 8015 u8 opcode = BPF_OP(insn->code); 8016 int err; 8017 8018 if (opcode == BPF_END || opcode == BPF_NEG) { 8019 if (opcode == BPF_NEG) { 8020 if (BPF_SRC(insn->code) != 0 || 8021 insn->src_reg != BPF_REG_0 || 8022 insn->off != 0 || insn->imm != 0) { 8023 verbose(env, "BPF_NEG uses reserved fields\n"); 8024 return -EINVAL; 8025 } 8026 } else { 8027 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 8028 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 8029 BPF_CLASS(insn->code) == BPF_ALU64) { 8030 verbose(env, "BPF_END uses reserved fields\n"); 8031 return -EINVAL; 8032 } 8033 } 8034 8035 /* check src operand */ 8036 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8037 if (err) 8038 return err; 8039 8040 if (is_pointer_value(env, insn->dst_reg)) { 8041 verbose(env, "R%d pointer arithmetic prohibited\n", 8042 insn->dst_reg); 8043 return -EACCES; 8044 } 8045 8046 /* check dest operand */ 8047 err = check_reg_arg(env, insn->dst_reg, DST_OP); 8048 if (err) 8049 return err; 8050 8051 } else if (opcode == BPF_MOV) { 8052 8053 if (BPF_SRC(insn->code) == BPF_X) { 8054 if (insn->imm != 0 || insn->off != 0) { 8055 verbose(env, "BPF_MOV uses reserved fields\n"); 8056 return -EINVAL; 8057 } 8058 8059 /* check src operand */ 8060 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8061 if (err) 8062 return err; 8063 } else { 8064 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8065 verbose(env, "BPF_MOV uses reserved fields\n"); 8066 return -EINVAL; 8067 } 8068 } 8069 8070 /* check dest operand, mark as required later */ 8071 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8072 if (err) 8073 return err; 8074 8075 if (BPF_SRC(insn->code) == BPF_X) { 8076 struct bpf_reg_state *src_reg = regs + insn->src_reg; 8077 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 8078 8079 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8080 /* case: R1 = R2 8081 * copy register state to dest reg 8082 */ 8083 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 8084 /* Assign src and dst registers the same ID 8085 * that will be used by find_equal_scalars() 8086 * to propagate min/max range. 8087 */ 8088 src_reg->id = ++env->id_gen; 8089 *dst_reg = *src_reg; 8090 dst_reg->live |= REG_LIVE_WRITTEN; 8091 dst_reg->subreg_def = DEF_NOT_SUBREG; 8092 } else { 8093 /* R1 = (u32) R2 */ 8094 if (is_pointer_value(env, insn->src_reg)) { 8095 verbose(env, 8096 "R%d partial copy of pointer\n", 8097 insn->src_reg); 8098 return -EACCES; 8099 } else if (src_reg->type == SCALAR_VALUE) { 8100 *dst_reg = *src_reg; 8101 /* Make sure ID is cleared otherwise 8102 * dst_reg min/max could be incorrectly 8103 * propagated into src_reg by find_equal_scalars() 8104 */ 8105 dst_reg->id = 0; 8106 dst_reg->live |= REG_LIVE_WRITTEN; 8107 dst_reg->subreg_def = env->insn_idx + 1; 8108 } else { 8109 mark_reg_unknown(env, regs, 8110 insn->dst_reg); 8111 } 8112 zext_32_to_64(dst_reg); 8113 } 8114 } else { 8115 /* case: R = imm 8116 * remember the value we stored into this reg 8117 */ 8118 /* clear any state __mark_reg_known doesn't set */ 8119 mark_reg_unknown(env, regs, insn->dst_reg); 8120 regs[insn->dst_reg].type = SCALAR_VALUE; 8121 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8122 __mark_reg_known(regs + insn->dst_reg, 8123 insn->imm); 8124 } else { 8125 __mark_reg_known(regs + insn->dst_reg, 8126 (u32)insn->imm); 8127 } 8128 } 8129 8130 } else if (opcode > BPF_END) { 8131 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 8132 return -EINVAL; 8133 8134 } else { /* all other ALU ops: and, sub, xor, add, ... */ 8135 8136 if (BPF_SRC(insn->code) == BPF_X) { 8137 if (insn->imm != 0 || insn->off != 0) { 8138 verbose(env, "BPF_ALU uses reserved fields\n"); 8139 return -EINVAL; 8140 } 8141 /* check src1 operand */ 8142 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8143 if (err) 8144 return err; 8145 } else { 8146 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8147 verbose(env, "BPF_ALU uses reserved fields\n"); 8148 return -EINVAL; 8149 } 8150 } 8151 8152 /* check src2 operand */ 8153 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8154 if (err) 8155 return err; 8156 8157 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 8158 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 8159 verbose(env, "div by zero\n"); 8160 return -EINVAL; 8161 } 8162 8163 if ((opcode == BPF_LSH || opcode == BPF_RSH || 8164 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 8165 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 8166 8167 if (insn->imm < 0 || insn->imm >= size) { 8168 verbose(env, "invalid shift %d\n", insn->imm); 8169 return -EINVAL; 8170 } 8171 } 8172 8173 /* check dest operand */ 8174 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8175 if (err) 8176 return err; 8177 8178 return adjust_reg_min_max_vals(env, insn); 8179 } 8180 8181 return 0; 8182 } 8183 8184 static void __find_good_pkt_pointers(struct bpf_func_state *state, 8185 struct bpf_reg_state *dst_reg, 8186 enum bpf_reg_type type, int new_range) 8187 { 8188 struct bpf_reg_state *reg; 8189 int i; 8190 8191 for (i = 0; i < MAX_BPF_REG; i++) { 8192 reg = &state->regs[i]; 8193 if (reg->type == type && reg->id == dst_reg->id) 8194 /* keep the maximum range already checked */ 8195 reg->range = max(reg->range, new_range); 8196 } 8197 8198 bpf_for_each_spilled_reg(i, state, reg) { 8199 if (!reg) 8200 continue; 8201 if (reg->type == type && reg->id == dst_reg->id) 8202 reg->range = max(reg->range, new_range); 8203 } 8204 } 8205 8206 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 8207 struct bpf_reg_state *dst_reg, 8208 enum bpf_reg_type type, 8209 bool range_right_open) 8210 { 8211 int new_range, i; 8212 8213 if (dst_reg->off < 0 || 8214 (dst_reg->off == 0 && range_right_open)) 8215 /* This doesn't give us any range */ 8216 return; 8217 8218 if (dst_reg->umax_value > MAX_PACKET_OFF || 8219 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 8220 /* Risk of overflow. For instance, ptr + (1<<63) may be less 8221 * than pkt_end, but that's because it's also less than pkt. 8222 */ 8223 return; 8224 8225 new_range = dst_reg->off; 8226 if (range_right_open) 8227 new_range--; 8228 8229 /* Examples for register markings: 8230 * 8231 * pkt_data in dst register: 8232 * 8233 * r2 = r3; 8234 * r2 += 8; 8235 * if (r2 > pkt_end) goto <handle exception> 8236 * <access okay> 8237 * 8238 * r2 = r3; 8239 * r2 += 8; 8240 * if (r2 < pkt_end) goto <access okay> 8241 * <handle exception> 8242 * 8243 * Where: 8244 * r2 == dst_reg, pkt_end == src_reg 8245 * r2=pkt(id=n,off=8,r=0) 8246 * r3=pkt(id=n,off=0,r=0) 8247 * 8248 * pkt_data in src register: 8249 * 8250 * r2 = r3; 8251 * r2 += 8; 8252 * if (pkt_end >= r2) goto <access okay> 8253 * <handle exception> 8254 * 8255 * r2 = r3; 8256 * r2 += 8; 8257 * if (pkt_end <= r2) goto <handle exception> 8258 * <access okay> 8259 * 8260 * Where: 8261 * pkt_end == dst_reg, r2 == src_reg 8262 * r2=pkt(id=n,off=8,r=0) 8263 * r3=pkt(id=n,off=0,r=0) 8264 * 8265 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 8266 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 8267 * and [r3, r3 + 8-1) respectively is safe to access depending on 8268 * the check. 8269 */ 8270 8271 /* If our ids match, then we must have the same max_value. And we 8272 * don't care about the other reg's fixed offset, since if it's too big 8273 * the range won't allow anything. 8274 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 8275 */ 8276 for (i = 0; i <= vstate->curframe; i++) 8277 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 8278 new_range); 8279 } 8280 8281 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 8282 { 8283 struct tnum subreg = tnum_subreg(reg->var_off); 8284 s32 sval = (s32)val; 8285 8286 switch (opcode) { 8287 case BPF_JEQ: 8288 if (tnum_is_const(subreg)) 8289 return !!tnum_equals_const(subreg, val); 8290 break; 8291 case BPF_JNE: 8292 if (tnum_is_const(subreg)) 8293 return !tnum_equals_const(subreg, val); 8294 break; 8295 case BPF_JSET: 8296 if ((~subreg.mask & subreg.value) & val) 8297 return 1; 8298 if (!((subreg.mask | subreg.value) & val)) 8299 return 0; 8300 break; 8301 case BPF_JGT: 8302 if (reg->u32_min_value > val) 8303 return 1; 8304 else if (reg->u32_max_value <= val) 8305 return 0; 8306 break; 8307 case BPF_JSGT: 8308 if (reg->s32_min_value > sval) 8309 return 1; 8310 else if (reg->s32_max_value <= sval) 8311 return 0; 8312 break; 8313 case BPF_JLT: 8314 if (reg->u32_max_value < val) 8315 return 1; 8316 else if (reg->u32_min_value >= val) 8317 return 0; 8318 break; 8319 case BPF_JSLT: 8320 if (reg->s32_max_value < sval) 8321 return 1; 8322 else if (reg->s32_min_value >= sval) 8323 return 0; 8324 break; 8325 case BPF_JGE: 8326 if (reg->u32_min_value >= val) 8327 return 1; 8328 else if (reg->u32_max_value < val) 8329 return 0; 8330 break; 8331 case BPF_JSGE: 8332 if (reg->s32_min_value >= sval) 8333 return 1; 8334 else if (reg->s32_max_value < sval) 8335 return 0; 8336 break; 8337 case BPF_JLE: 8338 if (reg->u32_max_value <= val) 8339 return 1; 8340 else if (reg->u32_min_value > val) 8341 return 0; 8342 break; 8343 case BPF_JSLE: 8344 if (reg->s32_max_value <= sval) 8345 return 1; 8346 else if (reg->s32_min_value > sval) 8347 return 0; 8348 break; 8349 } 8350 8351 return -1; 8352 } 8353 8354 8355 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 8356 { 8357 s64 sval = (s64)val; 8358 8359 switch (opcode) { 8360 case BPF_JEQ: 8361 if (tnum_is_const(reg->var_off)) 8362 return !!tnum_equals_const(reg->var_off, val); 8363 break; 8364 case BPF_JNE: 8365 if (tnum_is_const(reg->var_off)) 8366 return !tnum_equals_const(reg->var_off, val); 8367 break; 8368 case BPF_JSET: 8369 if ((~reg->var_off.mask & reg->var_off.value) & val) 8370 return 1; 8371 if (!((reg->var_off.mask | reg->var_off.value) & val)) 8372 return 0; 8373 break; 8374 case BPF_JGT: 8375 if (reg->umin_value > val) 8376 return 1; 8377 else if (reg->umax_value <= val) 8378 return 0; 8379 break; 8380 case BPF_JSGT: 8381 if (reg->smin_value > sval) 8382 return 1; 8383 else if (reg->smax_value <= sval) 8384 return 0; 8385 break; 8386 case BPF_JLT: 8387 if (reg->umax_value < val) 8388 return 1; 8389 else if (reg->umin_value >= val) 8390 return 0; 8391 break; 8392 case BPF_JSLT: 8393 if (reg->smax_value < sval) 8394 return 1; 8395 else if (reg->smin_value >= sval) 8396 return 0; 8397 break; 8398 case BPF_JGE: 8399 if (reg->umin_value >= val) 8400 return 1; 8401 else if (reg->umax_value < val) 8402 return 0; 8403 break; 8404 case BPF_JSGE: 8405 if (reg->smin_value >= sval) 8406 return 1; 8407 else if (reg->smax_value < sval) 8408 return 0; 8409 break; 8410 case BPF_JLE: 8411 if (reg->umax_value <= val) 8412 return 1; 8413 else if (reg->umin_value > val) 8414 return 0; 8415 break; 8416 case BPF_JSLE: 8417 if (reg->smax_value <= sval) 8418 return 1; 8419 else if (reg->smin_value > sval) 8420 return 0; 8421 break; 8422 } 8423 8424 return -1; 8425 } 8426 8427 /* compute branch direction of the expression "if (reg opcode val) goto target;" 8428 * and return: 8429 * 1 - branch will be taken and "goto target" will be executed 8430 * 0 - branch will not be taken and fall-through to next insn 8431 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 8432 * range [0,10] 8433 */ 8434 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 8435 bool is_jmp32) 8436 { 8437 if (__is_pointer_value(false, reg)) { 8438 if (!reg_type_not_null(reg->type)) 8439 return -1; 8440 8441 /* If pointer is valid tests against zero will fail so we can 8442 * use this to direct branch taken. 8443 */ 8444 if (val != 0) 8445 return -1; 8446 8447 switch (opcode) { 8448 case BPF_JEQ: 8449 return 0; 8450 case BPF_JNE: 8451 return 1; 8452 default: 8453 return -1; 8454 } 8455 } 8456 8457 if (is_jmp32) 8458 return is_branch32_taken(reg, val, opcode); 8459 return is_branch64_taken(reg, val, opcode); 8460 } 8461 8462 static int flip_opcode(u32 opcode) 8463 { 8464 /* How can we transform "a <op> b" into "b <op> a"? */ 8465 static const u8 opcode_flip[16] = { 8466 /* these stay the same */ 8467 [BPF_JEQ >> 4] = BPF_JEQ, 8468 [BPF_JNE >> 4] = BPF_JNE, 8469 [BPF_JSET >> 4] = BPF_JSET, 8470 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 8471 [BPF_JGE >> 4] = BPF_JLE, 8472 [BPF_JGT >> 4] = BPF_JLT, 8473 [BPF_JLE >> 4] = BPF_JGE, 8474 [BPF_JLT >> 4] = BPF_JGT, 8475 [BPF_JSGE >> 4] = BPF_JSLE, 8476 [BPF_JSGT >> 4] = BPF_JSLT, 8477 [BPF_JSLE >> 4] = BPF_JSGE, 8478 [BPF_JSLT >> 4] = BPF_JSGT 8479 }; 8480 return opcode_flip[opcode >> 4]; 8481 } 8482 8483 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 8484 struct bpf_reg_state *src_reg, 8485 u8 opcode) 8486 { 8487 struct bpf_reg_state *pkt; 8488 8489 if (src_reg->type == PTR_TO_PACKET_END) { 8490 pkt = dst_reg; 8491 } else if (dst_reg->type == PTR_TO_PACKET_END) { 8492 pkt = src_reg; 8493 opcode = flip_opcode(opcode); 8494 } else { 8495 return -1; 8496 } 8497 8498 if (pkt->range >= 0) 8499 return -1; 8500 8501 switch (opcode) { 8502 case BPF_JLE: 8503 /* pkt <= pkt_end */ 8504 fallthrough; 8505 case BPF_JGT: 8506 /* pkt > pkt_end */ 8507 if (pkt->range == BEYOND_PKT_END) 8508 /* pkt has at last one extra byte beyond pkt_end */ 8509 return opcode == BPF_JGT; 8510 break; 8511 case BPF_JLT: 8512 /* pkt < pkt_end */ 8513 fallthrough; 8514 case BPF_JGE: 8515 /* pkt >= pkt_end */ 8516 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 8517 return opcode == BPF_JGE; 8518 break; 8519 } 8520 return -1; 8521 } 8522 8523 /* Adjusts the register min/max values in the case that the dst_reg is the 8524 * variable register that we are working on, and src_reg is a constant or we're 8525 * simply doing a BPF_K check. 8526 * In JEQ/JNE cases we also adjust the var_off values. 8527 */ 8528 static void reg_set_min_max(struct bpf_reg_state *true_reg, 8529 struct bpf_reg_state *false_reg, 8530 u64 val, u32 val32, 8531 u8 opcode, bool is_jmp32) 8532 { 8533 struct tnum false_32off = tnum_subreg(false_reg->var_off); 8534 struct tnum false_64off = false_reg->var_off; 8535 struct tnum true_32off = tnum_subreg(true_reg->var_off); 8536 struct tnum true_64off = true_reg->var_off; 8537 s64 sval = (s64)val; 8538 s32 sval32 = (s32)val32; 8539 8540 /* If the dst_reg is a pointer, we can't learn anything about its 8541 * variable offset from the compare (unless src_reg were a pointer into 8542 * the same object, but we don't bother with that. 8543 * Since false_reg and true_reg have the same type by construction, we 8544 * only need to check one of them for pointerness. 8545 */ 8546 if (__is_pointer_value(false, false_reg)) 8547 return; 8548 8549 switch (opcode) { 8550 case BPF_JEQ: 8551 case BPF_JNE: 8552 { 8553 struct bpf_reg_state *reg = 8554 opcode == BPF_JEQ ? true_reg : false_reg; 8555 8556 /* JEQ/JNE comparison doesn't change the register equivalence. 8557 * r1 = r2; 8558 * if (r1 == 42) goto label; 8559 * ... 8560 * label: // here both r1 and r2 are known to be 42. 8561 * 8562 * Hence when marking register as known preserve it's ID. 8563 */ 8564 if (is_jmp32) 8565 __mark_reg32_known(reg, val32); 8566 else 8567 ___mark_reg_known(reg, val); 8568 break; 8569 } 8570 case BPF_JSET: 8571 if (is_jmp32) { 8572 false_32off = tnum_and(false_32off, tnum_const(~val32)); 8573 if (is_power_of_2(val32)) 8574 true_32off = tnum_or(true_32off, 8575 tnum_const(val32)); 8576 } else { 8577 false_64off = tnum_and(false_64off, tnum_const(~val)); 8578 if (is_power_of_2(val)) 8579 true_64off = tnum_or(true_64off, 8580 tnum_const(val)); 8581 } 8582 break; 8583 case BPF_JGE: 8584 case BPF_JGT: 8585 { 8586 if (is_jmp32) { 8587 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 8588 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 8589 8590 false_reg->u32_max_value = min(false_reg->u32_max_value, 8591 false_umax); 8592 true_reg->u32_min_value = max(true_reg->u32_min_value, 8593 true_umin); 8594 } else { 8595 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 8596 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 8597 8598 false_reg->umax_value = min(false_reg->umax_value, false_umax); 8599 true_reg->umin_value = max(true_reg->umin_value, true_umin); 8600 } 8601 break; 8602 } 8603 case BPF_JSGE: 8604 case BPF_JSGT: 8605 { 8606 if (is_jmp32) { 8607 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 8608 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 8609 8610 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 8611 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 8612 } else { 8613 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 8614 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 8615 8616 false_reg->smax_value = min(false_reg->smax_value, false_smax); 8617 true_reg->smin_value = max(true_reg->smin_value, true_smin); 8618 } 8619 break; 8620 } 8621 case BPF_JLE: 8622 case BPF_JLT: 8623 { 8624 if (is_jmp32) { 8625 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 8626 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 8627 8628 false_reg->u32_min_value = max(false_reg->u32_min_value, 8629 false_umin); 8630 true_reg->u32_max_value = min(true_reg->u32_max_value, 8631 true_umax); 8632 } else { 8633 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 8634 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 8635 8636 false_reg->umin_value = max(false_reg->umin_value, false_umin); 8637 true_reg->umax_value = min(true_reg->umax_value, true_umax); 8638 } 8639 break; 8640 } 8641 case BPF_JSLE: 8642 case BPF_JSLT: 8643 { 8644 if (is_jmp32) { 8645 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 8646 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 8647 8648 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 8649 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 8650 } else { 8651 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 8652 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 8653 8654 false_reg->smin_value = max(false_reg->smin_value, false_smin); 8655 true_reg->smax_value = min(true_reg->smax_value, true_smax); 8656 } 8657 break; 8658 } 8659 default: 8660 return; 8661 } 8662 8663 if (is_jmp32) { 8664 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 8665 tnum_subreg(false_32off)); 8666 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 8667 tnum_subreg(true_32off)); 8668 __reg_combine_32_into_64(false_reg); 8669 __reg_combine_32_into_64(true_reg); 8670 } else { 8671 false_reg->var_off = false_64off; 8672 true_reg->var_off = true_64off; 8673 __reg_combine_64_into_32(false_reg); 8674 __reg_combine_64_into_32(true_reg); 8675 } 8676 } 8677 8678 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 8679 * the variable reg. 8680 */ 8681 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 8682 struct bpf_reg_state *false_reg, 8683 u64 val, u32 val32, 8684 u8 opcode, bool is_jmp32) 8685 { 8686 opcode = flip_opcode(opcode); 8687 /* This uses zero as "not present in table"; luckily the zero opcode, 8688 * BPF_JA, can't get here. 8689 */ 8690 if (opcode) 8691 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 8692 } 8693 8694 /* Regs are known to be equal, so intersect their min/max/var_off */ 8695 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 8696 struct bpf_reg_state *dst_reg) 8697 { 8698 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 8699 dst_reg->umin_value); 8700 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 8701 dst_reg->umax_value); 8702 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 8703 dst_reg->smin_value); 8704 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 8705 dst_reg->smax_value); 8706 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 8707 dst_reg->var_off); 8708 /* We might have learned new bounds from the var_off. */ 8709 __update_reg_bounds(src_reg); 8710 __update_reg_bounds(dst_reg); 8711 /* We might have learned something about the sign bit. */ 8712 __reg_deduce_bounds(src_reg); 8713 __reg_deduce_bounds(dst_reg); 8714 /* We might have learned some bits from the bounds. */ 8715 __reg_bound_offset(src_reg); 8716 __reg_bound_offset(dst_reg); 8717 /* Intersecting with the old var_off might have improved our bounds 8718 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 8719 * then new var_off is (0; 0x7f...fc) which improves our umax. 8720 */ 8721 __update_reg_bounds(src_reg); 8722 __update_reg_bounds(dst_reg); 8723 } 8724 8725 static void reg_combine_min_max(struct bpf_reg_state *true_src, 8726 struct bpf_reg_state *true_dst, 8727 struct bpf_reg_state *false_src, 8728 struct bpf_reg_state *false_dst, 8729 u8 opcode) 8730 { 8731 switch (opcode) { 8732 case BPF_JEQ: 8733 __reg_combine_min_max(true_src, true_dst); 8734 break; 8735 case BPF_JNE: 8736 __reg_combine_min_max(false_src, false_dst); 8737 break; 8738 } 8739 } 8740 8741 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 8742 struct bpf_reg_state *reg, u32 id, 8743 bool is_null) 8744 { 8745 if (reg_type_may_be_null(reg->type) && reg->id == id && 8746 !WARN_ON_ONCE(!reg->id)) { 8747 /* Old offset (both fixed and variable parts) should 8748 * have been known-zero, because we don't allow pointer 8749 * arithmetic on pointers that might be NULL. 8750 */ 8751 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 8752 !tnum_equals_const(reg->var_off, 0) || 8753 reg->off)) { 8754 __mark_reg_known_zero(reg); 8755 reg->off = 0; 8756 } 8757 if (is_null) { 8758 reg->type = SCALAR_VALUE; 8759 /* We don't need id and ref_obj_id from this point 8760 * onwards anymore, thus we should better reset it, 8761 * so that state pruning has chances to take effect. 8762 */ 8763 reg->id = 0; 8764 reg->ref_obj_id = 0; 8765 8766 return; 8767 } 8768 8769 mark_ptr_not_null_reg(reg); 8770 8771 if (!reg_may_point_to_spin_lock(reg)) { 8772 /* For not-NULL ptr, reg->ref_obj_id will be reset 8773 * in release_reg_references(). 8774 * 8775 * reg->id is still used by spin_lock ptr. Other 8776 * than spin_lock ptr type, reg->id can be reset. 8777 */ 8778 reg->id = 0; 8779 } 8780 } 8781 } 8782 8783 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 8784 bool is_null) 8785 { 8786 struct bpf_reg_state *reg; 8787 int i; 8788 8789 for (i = 0; i < MAX_BPF_REG; i++) 8790 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 8791 8792 bpf_for_each_spilled_reg(i, state, reg) { 8793 if (!reg) 8794 continue; 8795 mark_ptr_or_null_reg(state, reg, id, is_null); 8796 } 8797 } 8798 8799 /* The logic is similar to find_good_pkt_pointers(), both could eventually 8800 * be folded together at some point. 8801 */ 8802 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 8803 bool is_null) 8804 { 8805 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8806 struct bpf_reg_state *regs = state->regs; 8807 u32 ref_obj_id = regs[regno].ref_obj_id; 8808 u32 id = regs[regno].id; 8809 int i; 8810 8811 if (ref_obj_id && ref_obj_id == id && is_null) 8812 /* regs[regno] is in the " == NULL" branch. 8813 * No one could have freed the reference state before 8814 * doing the NULL check. 8815 */ 8816 WARN_ON_ONCE(release_reference_state(state, id)); 8817 8818 for (i = 0; i <= vstate->curframe; i++) 8819 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 8820 } 8821 8822 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 8823 struct bpf_reg_state *dst_reg, 8824 struct bpf_reg_state *src_reg, 8825 struct bpf_verifier_state *this_branch, 8826 struct bpf_verifier_state *other_branch) 8827 { 8828 if (BPF_SRC(insn->code) != BPF_X) 8829 return false; 8830 8831 /* Pointers are always 64-bit. */ 8832 if (BPF_CLASS(insn->code) == BPF_JMP32) 8833 return false; 8834 8835 switch (BPF_OP(insn->code)) { 8836 case BPF_JGT: 8837 if ((dst_reg->type == PTR_TO_PACKET && 8838 src_reg->type == PTR_TO_PACKET_END) || 8839 (dst_reg->type == PTR_TO_PACKET_META && 8840 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8841 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 8842 find_good_pkt_pointers(this_branch, dst_reg, 8843 dst_reg->type, false); 8844 mark_pkt_end(other_branch, insn->dst_reg, true); 8845 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8846 src_reg->type == PTR_TO_PACKET) || 8847 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8848 src_reg->type == PTR_TO_PACKET_META)) { 8849 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 8850 find_good_pkt_pointers(other_branch, src_reg, 8851 src_reg->type, true); 8852 mark_pkt_end(this_branch, insn->src_reg, false); 8853 } else { 8854 return false; 8855 } 8856 break; 8857 case BPF_JLT: 8858 if ((dst_reg->type == PTR_TO_PACKET && 8859 src_reg->type == PTR_TO_PACKET_END) || 8860 (dst_reg->type == PTR_TO_PACKET_META && 8861 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8862 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 8863 find_good_pkt_pointers(other_branch, dst_reg, 8864 dst_reg->type, true); 8865 mark_pkt_end(this_branch, insn->dst_reg, false); 8866 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8867 src_reg->type == PTR_TO_PACKET) || 8868 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8869 src_reg->type == PTR_TO_PACKET_META)) { 8870 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 8871 find_good_pkt_pointers(this_branch, src_reg, 8872 src_reg->type, false); 8873 mark_pkt_end(other_branch, insn->src_reg, true); 8874 } else { 8875 return false; 8876 } 8877 break; 8878 case BPF_JGE: 8879 if ((dst_reg->type == PTR_TO_PACKET && 8880 src_reg->type == PTR_TO_PACKET_END) || 8881 (dst_reg->type == PTR_TO_PACKET_META && 8882 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8883 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 8884 find_good_pkt_pointers(this_branch, dst_reg, 8885 dst_reg->type, true); 8886 mark_pkt_end(other_branch, insn->dst_reg, false); 8887 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8888 src_reg->type == PTR_TO_PACKET) || 8889 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8890 src_reg->type == PTR_TO_PACKET_META)) { 8891 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 8892 find_good_pkt_pointers(other_branch, src_reg, 8893 src_reg->type, false); 8894 mark_pkt_end(this_branch, insn->src_reg, true); 8895 } else { 8896 return false; 8897 } 8898 break; 8899 case BPF_JLE: 8900 if ((dst_reg->type == PTR_TO_PACKET && 8901 src_reg->type == PTR_TO_PACKET_END) || 8902 (dst_reg->type == PTR_TO_PACKET_META && 8903 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8904 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 8905 find_good_pkt_pointers(other_branch, dst_reg, 8906 dst_reg->type, false); 8907 mark_pkt_end(this_branch, insn->dst_reg, true); 8908 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8909 src_reg->type == PTR_TO_PACKET) || 8910 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8911 src_reg->type == PTR_TO_PACKET_META)) { 8912 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 8913 find_good_pkt_pointers(this_branch, src_reg, 8914 src_reg->type, true); 8915 mark_pkt_end(other_branch, insn->src_reg, false); 8916 } else { 8917 return false; 8918 } 8919 break; 8920 default: 8921 return false; 8922 } 8923 8924 return true; 8925 } 8926 8927 static void find_equal_scalars(struct bpf_verifier_state *vstate, 8928 struct bpf_reg_state *known_reg) 8929 { 8930 struct bpf_func_state *state; 8931 struct bpf_reg_state *reg; 8932 int i, j; 8933 8934 for (i = 0; i <= vstate->curframe; i++) { 8935 state = vstate->frame[i]; 8936 for (j = 0; j < MAX_BPF_REG; j++) { 8937 reg = &state->regs[j]; 8938 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8939 *reg = *known_reg; 8940 } 8941 8942 bpf_for_each_spilled_reg(j, state, reg) { 8943 if (!reg) 8944 continue; 8945 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8946 *reg = *known_reg; 8947 } 8948 } 8949 } 8950 8951 static int check_cond_jmp_op(struct bpf_verifier_env *env, 8952 struct bpf_insn *insn, int *insn_idx) 8953 { 8954 struct bpf_verifier_state *this_branch = env->cur_state; 8955 struct bpf_verifier_state *other_branch; 8956 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 8957 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 8958 u8 opcode = BPF_OP(insn->code); 8959 bool is_jmp32; 8960 int pred = -1; 8961 int err; 8962 8963 /* Only conditional jumps are expected to reach here. */ 8964 if (opcode == BPF_JA || opcode > BPF_JSLE) { 8965 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 8966 return -EINVAL; 8967 } 8968 8969 if (BPF_SRC(insn->code) == BPF_X) { 8970 if (insn->imm != 0) { 8971 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8972 return -EINVAL; 8973 } 8974 8975 /* check src1 operand */ 8976 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8977 if (err) 8978 return err; 8979 8980 if (is_pointer_value(env, insn->src_reg)) { 8981 verbose(env, "R%d pointer comparison prohibited\n", 8982 insn->src_reg); 8983 return -EACCES; 8984 } 8985 src_reg = ®s[insn->src_reg]; 8986 } else { 8987 if (insn->src_reg != BPF_REG_0) { 8988 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8989 return -EINVAL; 8990 } 8991 } 8992 8993 /* check src2 operand */ 8994 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8995 if (err) 8996 return err; 8997 8998 dst_reg = ®s[insn->dst_reg]; 8999 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 9000 9001 if (BPF_SRC(insn->code) == BPF_K) { 9002 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 9003 } else if (src_reg->type == SCALAR_VALUE && 9004 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 9005 pred = is_branch_taken(dst_reg, 9006 tnum_subreg(src_reg->var_off).value, 9007 opcode, 9008 is_jmp32); 9009 } else if (src_reg->type == SCALAR_VALUE && 9010 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 9011 pred = is_branch_taken(dst_reg, 9012 src_reg->var_off.value, 9013 opcode, 9014 is_jmp32); 9015 } else if (reg_is_pkt_pointer_any(dst_reg) && 9016 reg_is_pkt_pointer_any(src_reg) && 9017 !is_jmp32) { 9018 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 9019 } 9020 9021 if (pred >= 0) { 9022 /* If we get here with a dst_reg pointer type it is because 9023 * above is_branch_taken() special cased the 0 comparison. 9024 */ 9025 if (!__is_pointer_value(false, dst_reg)) 9026 err = mark_chain_precision(env, insn->dst_reg); 9027 if (BPF_SRC(insn->code) == BPF_X && !err && 9028 !__is_pointer_value(false, src_reg)) 9029 err = mark_chain_precision(env, insn->src_reg); 9030 if (err) 9031 return err; 9032 } 9033 9034 if (pred == 1) { 9035 /* Only follow the goto, ignore fall-through. If needed, push 9036 * the fall-through branch for simulation under speculative 9037 * execution. 9038 */ 9039 if (!env->bypass_spec_v1 && 9040 !sanitize_speculative_path(env, insn, *insn_idx + 1, 9041 *insn_idx)) 9042 return -EFAULT; 9043 *insn_idx += insn->off; 9044 return 0; 9045 } else if (pred == 0) { 9046 /* Only follow the fall-through branch, since that's where the 9047 * program will go. If needed, push the goto branch for 9048 * simulation under speculative execution. 9049 */ 9050 if (!env->bypass_spec_v1 && 9051 !sanitize_speculative_path(env, insn, 9052 *insn_idx + insn->off + 1, 9053 *insn_idx)) 9054 return -EFAULT; 9055 return 0; 9056 } 9057 9058 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 9059 false); 9060 if (!other_branch) 9061 return -EFAULT; 9062 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 9063 9064 /* detect if we are comparing against a constant value so we can adjust 9065 * our min/max values for our dst register. 9066 * this is only legit if both are scalars (or pointers to the same 9067 * object, I suppose, but we don't support that right now), because 9068 * otherwise the different base pointers mean the offsets aren't 9069 * comparable. 9070 */ 9071 if (BPF_SRC(insn->code) == BPF_X) { 9072 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 9073 9074 if (dst_reg->type == SCALAR_VALUE && 9075 src_reg->type == SCALAR_VALUE) { 9076 if (tnum_is_const(src_reg->var_off) || 9077 (is_jmp32 && 9078 tnum_is_const(tnum_subreg(src_reg->var_off)))) 9079 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9080 dst_reg, 9081 src_reg->var_off.value, 9082 tnum_subreg(src_reg->var_off).value, 9083 opcode, is_jmp32); 9084 else if (tnum_is_const(dst_reg->var_off) || 9085 (is_jmp32 && 9086 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 9087 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 9088 src_reg, 9089 dst_reg->var_off.value, 9090 tnum_subreg(dst_reg->var_off).value, 9091 opcode, is_jmp32); 9092 else if (!is_jmp32 && 9093 (opcode == BPF_JEQ || opcode == BPF_JNE)) 9094 /* Comparing for equality, we can combine knowledge */ 9095 reg_combine_min_max(&other_branch_regs[insn->src_reg], 9096 &other_branch_regs[insn->dst_reg], 9097 src_reg, dst_reg, opcode); 9098 if (src_reg->id && 9099 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 9100 find_equal_scalars(this_branch, src_reg); 9101 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 9102 } 9103 9104 } 9105 } else if (dst_reg->type == SCALAR_VALUE) { 9106 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9107 dst_reg, insn->imm, (u32)insn->imm, 9108 opcode, is_jmp32); 9109 } 9110 9111 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 9112 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 9113 find_equal_scalars(this_branch, dst_reg); 9114 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 9115 } 9116 9117 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 9118 * NOTE: these optimizations below are related with pointer comparison 9119 * which will never be JMP32. 9120 */ 9121 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 9122 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 9123 reg_type_may_be_null(dst_reg->type)) { 9124 /* Mark all identical registers in each branch as either 9125 * safe or unknown depending R == 0 or R != 0 conditional. 9126 */ 9127 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 9128 opcode == BPF_JNE); 9129 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 9130 opcode == BPF_JEQ); 9131 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 9132 this_branch, other_branch) && 9133 is_pointer_value(env, insn->dst_reg)) { 9134 verbose(env, "R%d pointer comparison prohibited\n", 9135 insn->dst_reg); 9136 return -EACCES; 9137 } 9138 if (env->log.level & BPF_LOG_LEVEL) 9139 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 9140 return 0; 9141 } 9142 9143 /* verify BPF_LD_IMM64 instruction */ 9144 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 9145 { 9146 struct bpf_insn_aux_data *aux = cur_aux(env); 9147 struct bpf_reg_state *regs = cur_regs(env); 9148 struct bpf_reg_state *dst_reg; 9149 struct bpf_map *map; 9150 int err; 9151 9152 if (BPF_SIZE(insn->code) != BPF_DW) { 9153 verbose(env, "invalid BPF_LD_IMM insn\n"); 9154 return -EINVAL; 9155 } 9156 if (insn->off != 0) { 9157 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 9158 return -EINVAL; 9159 } 9160 9161 err = check_reg_arg(env, insn->dst_reg, DST_OP); 9162 if (err) 9163 return err; 9164 9165 dst_reg = ®s[insn->dst_reg]; 9166 if (insn->src_reg == 0) { 9167 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 9168 9169 dst_reg->type = SCALAR_VALUE; 9170 __mark_reg_known(®s[insn->dst_reg], imm); 9171 return 0; 9172 } 9173 9174 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 9175 mark_reg_known_zero(env, regs, insn->dst_reg); 9176 9177 dst_reg->type = aux->btf_var.reg_type; 9178 switch (dst_reg->type) { 9179 case PTR_TO_MEM: 9180 dst_reg->mem_size = aux->btf_var.mem_size; 9181 break; 9182 case PTR_TO_BTF_ID: 9183 case PTR_TO_PERCPU_BTF_ID: 9184 dst_reg->btf = aux->btf_var.btf; 9185 dst_reg->btf_id = aux->btf_var.btf_id; 9186 break; 9187 default: 9188 verbose(env, "bpf verifier is misconfigured\n"); 9189 return -EFAULT; 9190 } 9191 return 0; 9192 } 9193 9194 if (insn->src_reg == BPF_PSEUDO_FUNC) { 9195 struct bpf_prog_aux *aux = env->prog->aux; 9196 u32 subprogno = insn[1].imm; 9197 9198 if (!aux->func_info) { 9199 verbose(env, "missing btf func_info\n"); 9200 return -EINVAL; 9201 } 9202 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 9203 verbose(env, "callback function not static\n"); 9204 return -EINVAL; 9205 } 9206 9207 dst_reg->type = PTR_TO_FUNC; 9208 dst_reg->subprogno = subprogno; 9209 return 0; 9210 } 9211 9212 map = env->used_maps[aux->map_index]; 9213 mark_reg_known_zero(env, regs, insn->dst_reg); 9214 dst_reg->map_ptr = map; 9215 9216 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 9217 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 9218 dst_reg->type = PTR_TO_MAP_VALUE; 9219 dst_reg->off = aux->map_off; 9220 if (map_value_has_spin_lock(map)) 9221 dst_reg->id = ++env->id_gen; 9222 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 9223 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 9224 dst_reg->type = CONST_PTR_TO_MAP; 9225 } else { 9226 verbose(env, "bpf verifier is misconfigured\n"); 9227 return -EINVAL; 9228 } 9229 9230 return 0; 9231 } 9232 9233 static bool may_access_skb(enum bpf_prog_type type) 9234 { 9235 switch (type) { 9236 case BPF_PROG_TYPE_SOCKET_FILTER: 9237 case BPF_PROG_TYPE_SCHED_CLS: 9238 case BPF_PROG_TYPE_SCHED_ACT: 9239 return true; 9240 default: 9241 return false; 9242 } 9243 } 9244 9245 /* verify safety of LD_ABS|LD_IND instructions: 9246 * - they can only appear in the programs where ctx == skb 9247 * - since they are wrappers of function calls, they scratch R1-R5 registers, 9248 * preserve R6-R9, and store return value into R0 9249 * 9250 * Implicit input: 9251 * ctx == skb == R6 == CTX 9252 * 9253 * Explicit input: 9254 * SRC == any register 9255 * IMM == 32-bit immediate 9256 * 9257 * Output: 9258 * R0 - 8/16/32-bit skb data converted to cpu endianness 9259 */ 9260 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 9261 { 9262 struct bpf_reg_state *regs = cur_regs(env); 9263 static const int ctx_reg = BPF_REG_6; 9264 u8 mode = BPF_MODE(insn->code); 9265 int i, err; 9266 9267 if (!may_access_skb(resolve_prog_type(env->prog))) { 9268 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 9269 return -EINVAL; 9270 } 9271 9272 if (!env->ops->gen_ld_abs) { 9273 verbose(env, "bpf verifier is misconfigured\n"); 9274 return -EINVAL; 9275 } 9276 9277 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 9278 BPF_SIZE(insn->code) == BPF_DW || 9279 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 9280 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 9281 return -EINVAL; 9282 } 9283 9284 /* check whether implicit source operand (register R6) is readable */ 9285 err = check_reg_arg(env, ctx_reg, SRC_OP); 9286 if (err) 9287 return err; 9288 9289 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 9290 * gen_ld_abs() may terminate the program at runtime, leading to 9291 * reference leak. 9292 */ 9293 err = check_reference_leak(env); 9294 if (err) { 9295 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 9296 return err; 9297 } 9298 9299 if (env->cur_state->active_spin_lock) { 9300 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 9301 return -EINVAL; 9302 } 9303 9304 if (regs[ctx_reg].type != PTR_TO_CTX) { 9305 verbose(env, 9306 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 9307 return -EINVAL; 9308 } 9309 9310 if (mode == BPF_IND) { 9311 /* check explicit source operand */ 9312 err = check_reg_arg(env, insn->src_reg, SRC_OP); 9313 if (err) 9314 return err; 9315 } 9316 9317 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 9318 if (err < 0) 9319 return err; 9320 9321 /* reset caller saved regs to unreadable */ 9322 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9323 mark_reg_not_init(env, regs, caller_saved[i]); 9324 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9325 } 9326 9327 /* mark destination R0 register as readable, since it contains 9328 * the value fetched from the packet. 9329 * Already marked as written above. 9330 */ 9331 mark_reg_unknown(env, regs, BPF_REG_0); 9332 /* ld_abs load up to 32-bit skb data. */ 9333 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 9334 return 0; 9335 } 9336 9337 static int check_return_code(struct bpf_verifier_env *env) 9338 { 9339 struct tnum enforce_attach_type_range = tnum_unknown; 9340 const struct bpf_prog *prog = env->prog; 9341 struct bpf_reg_state *reg; 9342 struct tnum range = tnum_range(0, 1); 9343 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9344 int err; 9345 struct bpf_func_state *frame = env->cur_state->frame[0]; 9346 const bool is_subprog = frame->subprogno; 9347 9348 /* LSM and struct_ops func-ptr's return type could be "void" */ 9349 if (!is_subprog && 9350 (prog_type == BPF_PROG_TYPE_STRUCT_OPS || 9351 prog_type == BPF_PROG_TYPE_LSM) && 9352 !prog->aux->attach_func_proto->type) 9353 return 0; 9354 9355 /* eBPF calling convention is such that R0 is used 9356 * to return the value from eBPF program. 9357 * Make sure that it's readable at this time 9358 * of bpf_exit, which means that program wrote 9359 * something into it earlier 9360 */ 9361 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 9362 if (err) 9363 return err; 9364 9365 if (is_pointer_value(env, BPF_REG_0)) { 9366 verbose(env, "R0 leaks addr as return value\n"); 9367 return -EACCES; 9368 } 9369 9370 reg = cur_regs(env) + BPF_REG_0; 9371 9372 if (frame->in_async_callback_fn) { 9373 /* enforce return zero from async callbacks like timer */ 9374 if (reg->type != SCALAR_VALUE) { 9375 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 9376 reg_type_str[reg->type]); 9377 return -EINVAL; 9378 } 9379 9380 if (!tnum_in(tnum_const(0), reg->var_off)) { 9381 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 9382 return -EINVAL; 9383 } 9384 return 0; 9385 } 9386 9387 if (is_subprog) { 9388 if (reg->type != SCALAR_VALUE) { 9389 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 9390 reg_type_str[reg->type]); 9391 return -EINVAL; 9392 } 9393 return 0; 9394 } 9395 9396 switch (prog_type) { 9397 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 9398 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 9399 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 9400 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 9401 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 9402 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 9403 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 9404 range = tnum_range(1, 1); 9405 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 9406 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 9407 range = tnum_range(0, 3); 9408 break; 9409 case BPF_PROG_TYPE_CGROUP_SKB: 9410 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 9411 range = tnum_range(0, 3); 9412 enforce_attach_type_range = tnum_range(2, 3); 9413 } 9414 break; 9415 case BPF_PROG_TYPE_CGROUP_SOCK: 9416 case BPF_PROG_TYPE_SOCK_OPS: 9417 case BPF_PROG_TYPE_CGROUP_DEVICE: 9418 case BPF_PROG_TYPE_CGROUP_SYSCTL: 9419 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 9420 break; 9421 case BPF_PROG_TYPE_RAW_TRACEPOINT: 9422 if (!env->prog->aux->attach_btf_id) 9423 return 0; 9424 range = tnum_const(0); 9425 break; 9426 case BPF_PROG_TYPE_TRACING: 9427 switch (env->prog->expected_attach_type) { 9428 case BPF_TRACE_FENTRY: 9429 case BPF_TRACE_FEXIT: 9430 range = tnum_const(0); 9431 break; 9432 case BPF_TRACE_RAW_TP: 9433 case BPF_MODIFY_RETURN: 9434 return 0; 9435 case BPF_TRACE_ITER: 9436 break; 9437 default: 9438 return -ENOTSUPP; 9439 } 9440 break; 9441 case BPF_PROG_TYPE_SK_LOOKUP: 9442 range = tnum_range(SK_DROP, SK_PASS); 9443 break; 9444 case BPF_PROG_TYPE_EXT: 9445 /* freplace program can return anything as its return value 9446 * depends on the to-be-replaced kernel func or bpf program. 9447 */ 9448 default: 9449 return 0; 9450 } 9451 9452 if (reg->type != SCALAR_VALUE) { 9453 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 9454 reg_type_str[reg->type]); 9455 return -EINVAL; 9456 } 9457 9458 if (!tnum_in(range, reg->var_off)) { 9459 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 9460 return -EINVAL; 9461 } 9462 9463 if (!tnum_is_unknown(enforce_attach_type_range) && 9464 tnum_in(enforce_attach_type_range, reg->var_off)) 9465 env->prog->enforce_expected_attach_type = 1; 9466 return 0; 9467 } 9468 9469 /* non-recursive DFS pseudo code 9470 * 1 procedure DFS-iterative(G,v): 9471 * 2 label v as discovered 9472 * 3 let S be a stack 9473 * 4 S.push(v) 9474 * 5 while S is not empty 9475 * 6 t <- S.pop() 9476 * 7 if t is what we're looking for: 9477 * 8 return t 9478 * 9 for all edges e in G.adjacentEdges(t) do 9479 * 10 if edge e is already labelled 9480 * 11 continue with the next edge 9481 * 12 w <- G.adjacentVertex(t,e) 9482 * 13 if vertex w is not discovered and not explored 9483 * 14 label e as tree-edge 9484 * 15 label w as discovered 9485 * 16 S.push(w) 9486 * 17 continue at 5 9487 * 18 else if vertex w is discovered 9488 * 19 label e as back-edge 9489 * 20 else 9490 * 21 // vertex w is explored 9491 * 22 label e as forward- or cross-edge 9492 * 23 label t as explored 9493 * 24 S.pop() 9494 * 9495 * convention: 9496 * 0x10 - discovered 9497 * 0x11 - discovered and fall-through edge labelled 9498 * 0x12 - discovered and fall-through and branch edges labelled 9499 * 0x20 - explored 9500 */ 9501 9502 enum { 9503 DISCOVERED = 0x10, 9504 EXPLORED = 0x20, 9505 FALLTHROUGH = 1, 9506 BRANCH = 2, 9507 }; 9508 9509 static u32 state_htab_size(struct bpf_verifier_env *env) 9510 { 9511 return env->prog->len; 9512 } 9513 9514 static struct bpf_verifier_state_list **explored_state( 9515 struct bpf_verifier_env *env, 9516 int idx) 9517 { 9518 struct bpf_verifier_state *cur = env->cur_state; 9519 struct bpf_func_state *state = cur->frame[cur->curframe]; 9520 9521 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 9522 } 9523 9524 static void init_explored_state(struct bpf_verifier_env *env, int idx) 9525 { 9526 env->insn_aux_data[idx].prune_point = true; 9527 } 9528 9529 enum { 9530 DONE_EXPLORING = 0, 9531 KEEP_EXPLORING = 1, 9532 }; 9533 9534 /* t, w, e - match pseudo-code above: 9535 * t - index of current instruction 9536 * w - next instruction 9537 * e - edge 9538 */ 9539 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 9540 bool loop_ok) 9541 { 9542 int *insn_stack = env->cfg.insn_stack; 9543 int *insn_state = env->cfg.insn_state; 9544 9545 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 9546 return DONE_EXPLORING; 9547 9548 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 9549 return DONE_EXPLORING; 9550 9551 if (w < 0 || w >= env->prog->len) { 9552 verbose_linfo(env, t, "%d: ", t); 9553 verbose(env, "jump out of range from insn %d to %d\n", t, w); 9554 return -EINVAL; 9555 } 9556 9557 if (e == BRANCH) 9558 /* mark branch target for state pruning */ 9559 init_explored_state(env, w); 9560 9561 if (insn_state[w] == 0) { 9562 /* tree-edge */ 9563 insn_state[t] = DISCOVERED | e; 9564 insn_state[w] = DISCOVERED; 9565 if (env->cfg.cur_stack >= env->prog->len) 9566 return -E2BIG; 9567 insn_stack[env->cfg.cur_stack++] = w; 9568 return KEEP_EXPLORING; 9569 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 9570 if (loop_ok && env->bpf_capable) 9571 return DONE_EXPLORING; 9572 verbose_linfo(env, t, "%d: ", t); 9573 verbose_linfo(env, w, "%d: ", w); 9574 verbose(env, "back-edge from insn %d to %d\n", t, w); 9575 return -EINVAL; 9576 } else if (insn_state[w] == EXPLORED) { 9577 /* forward- or cross-edge */ 9578 insn_state[t] = DISCOVERED | e; 9579 } else { 9580 verbose(env, "insn state internal bug\n"); 9581 return -EFAULT; 9582 } 9583 return DONE_EXPLORING; 9584 } 9585 9586 static int visit_func_call_insn(int t, int insn_cnt, 9587 struct bpf_insn *insns, 9588 struct bpf_verifier_env *env, 9589 bool visit_callee) 9590 { 9591 int ret; 9592 9593 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 9594 if (ret) 9595 return ret; 9596 9597 if (t + 1 < insn_cnt) 9598 init_explored_state(env, t + 1); 9599 if (visit_callee) { 9600 init_explored_state(env, t); 9601 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 9602 /* It's ok to allow recursion from CFG point of 9603 * view. __check_func_call() will do the actual 9604 * check. 9605 */ 9606 bpf_pseudo_func(insns + t)); 9607 } 9608 return ret; 9609 } 9610 9611 /* Visits the instruction at index t and returns one of the following: 9612 * < 0 - an error occurred 9613 * DONE_EXPLORING - the instruction was fully explored 9614 * KEEP_EXPLORING - there is still work to be done before it is fully explored 9615 */ 9616 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env) 9617 { 9618 struct bpf_insn *insns = env->prog->insnsi; 9619 int ret; 9620 9621 if (bpf_pseudo_func(insns + t)) 9622 return visit_func_call_insn(t, insn_cnt, insns, env, true); 9623 9624 /* All non-branch instructions have a single fall-through edge. */ 9625 if (BPF_CLASS(insns[t].code) != BPF_JMP && 9626 BPF_CLASS(insns[t].code) != BPF_JMP32) 9627 return push_insn(t, t + 1, FALLTHROUGH, env, false); 9628 9629 switch (BPF_OP(insns[t].code)) { 9630 case BPF_EXIT: 9631 return DONE_EXPLORING; 9632 9633 case BPF_CALL: 9634 if (insns[t].imm == BPF_FUNC_timer_set_callback) 9635 /* Mark this call insn to trigger is_state_visited() check 9636 * before call itself is processed by __check_func_call(). 9637 * Otherwise new async state will be pushed for further 9638 * exploration. 9639 */ 9640 init_explored_state(env, t); 9641 return visit_func_call_insn(t, insn_cnt, insns, env, 9642 insns[t].src_reg == BPF_PSEUDO_CALL); 9643 9644 case BPF_JA: 9645 if (BPF_SRC(insns[t].code) != BPF_K) 9646 return -EINVAL; 9647 9648 /* unconditional jump with single edge */ 9649 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 9650 true); 9651 if (ret) 9652 return ret; 9653 9654 /* unconditional jmp is not a good pruning point, 9655 * but it's marked, since backtracking needs 9656 * to record jmp history in is_state_visited(). 9657 */ 9658 init_explored_state(env, t + insns[t].off + 1); 9659 /* tell verifier to check for equivalent states 9660 * after every call and jump 9661 */ 9662 if (t + 1 < insn_cnt) 9663 init_explored_state(env, t + 1); 9664 9665 return ret; 9666 9667 default: 9668 /* conditional jump with two edges */ 9669 init_explored_state(env, t); 9670 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 9671 if (ret) 9672 return ret; 9673 9674 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 9675 } 9676 } 9677 9678 /* non-recursive depth-first-search to detect loops in BPF program 9679 * loop == back-edge in directed graph 9680 */ 9681 static int check_cfg(struct bpf_verifier_env *env) 9682 { 9683 int insn_cnt = env->prog->len; 9684 int *insn_stack, *insn_state; 9685 int ret = 0; 9686 int i; 9687 9688 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 9689 if (!insn_state) 9690 return -ENOMEM; 9691 9692 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 9693 if (!insn_stack) { 9694 kvfree(insn_state); 9695 return -ENOMEM; 9696 } 9697 9698 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 9699 insn_stack[0] = 0; /* 0 is the first instruction */ 9700 env->cfg.cur_stack = 1; 9701 9702 while (env->cfg.cur_stack > 0) { 9703 int t = insn_stack[env->cfg.cur_stack - 1]; 9704 9705 ret = visit_insn(t, insn_cnt, env); 9706 switch (ret) { 9707 case DONE_EXPLORING: 9708 insn_state[t] = EXPLORED; 9709 env->cfg.cur_stack--; 9710 break; 9711 case KEEP_EXPLORING: 9712 break; 9713 default: 9714 if (ret > 0) { 9715 verbose(env, "visit_insn internal bug\n"); 9716 ret = -EFAULT; 9717 } 9718 goto err_free; 9719 } 9720 } 9721 9722 if (env->cfg.cur_stack < 0) { 9723 verbose(env, "pop stack internal bug\n"); 9724 ret = -EFAULT; 9725 goto err_free; 9726 } 9727 9728 for (i = 0; i < insn_cnt; i++) { 9729 if (insn_state[i] != EXPLORED) { 9730 verbose(env, "unreachable insn %d\n", i); 9731 ret = -EINVAL; 9732 goto err_free; 9733 } 9734 } 9735 ret = 0; /* cfg looks good */ 9736 9737 err_free: 9738 kvfree(insn_state); 9739 kvfree(insn_stack); 9740 env->cfg.insn_state = env->cfg.insn_stack = NULL; 9741 return ret; 9742 } 9743 9744 static int check_abnormal_return(struct bpf_verifier_env *env) 9745 { 9746 int i; 9747 9748 for (i = 1; i < env->subprog_cnt; i++) { 9749 if (env->subprog_info[i].has_ld_abs) { 9750 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 9751 return -EINVAL; 9752 } 9753 if (env->subprog_info[i].has_tail_call) { 9754 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 9755 return -EINVAL; 9756 } 9757 } 9758 return 0; 9759 } 9760 9761 /* The minimum supported BTF func info size */ 9762 #define MIN_BPF_FUNCINFO_SIZE 8 9763 #define MAX_FUNCINFO_REC_SIZE 252 9764 9765 static int check_btf_func(struct bpf_verifier_env *env, 9766 const union bpf_attr *attr, 9767 bpfptr_t uattr) 9768 { 9769 const struct btf_type *type, *func_proto, *ret_type; 9770 u32 i, nfuncs, urec_size, min_size; 9771 u32 krec_size = sizeof(struct bpf_func_info); 9772 struct bpf_func_info *krecord; 9773 struct bpf_func_info_aux *info_aux = NULL; 9774 struct bpf_prog *prog; 9775 const struct btf *btf; 9776 bpfptr_t urecord; 9777 u32 prev_offset = 0; 9778 bool scalar_return; 9779 int ret = -ENOMEM; 9780 9781 nfuncs = attr->func_info_cnt; 9782 if (!nfuncs) { 9783 if (check_abnormal_return(env)) 9784 return -EINVAL; 9785 return 0; 9786 } 9787 9788 if (nfuncs != env->subprog_cnt) { 9789 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 9790 return -EINVAL; 9791 } 9792 9793 urec_size = attr->func_info_rec_size; 9794 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 9795 urec_size > MAX_FUNCINFO_REC_SIZE || 9796 urec_size % sizeof(u32)) { 9797 verbose(env, "invalid func info rec size %u\n", urec_size); 9798 return -EINVAL; 9799 } 9800 9801 prog = env->prog; 9802 btf = prog->aux->btf; 9803 9804 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 9805 min_size = min_t(u32, krec_size, urec_size); 9806 9807 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 9808 if (!krecord) 9809 return -ENOMEM; 9810 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 9811 if (!info_aux) 9812 goto err_free; 9813 9814 for (i = 0; i < nfuncs; i++) { 9815 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 9816 if (ret) { 9817 if (ret == -E2BIG) { 9818 verbose(env, "nonzero tailing record in func info"); 9819 /* set the size kernel expects so loader can zero 9820 * out the rest of the record. 9821 */ 9822 if (copy_to_bpfptr_offset(uattr, 9823 offsetof(union bpf_attr, func_info_rec_size), 9824 &min_size, sizeof(min_size))) 9825 ret = -EFAULT; 9826 } 9827 goto err_free; 9828 } 9829 9830 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 9831 ret = -EFAULT; 9832 goto err_free; 9833 } 9834 9835 /* check insn_off */ 9836 ret = -EINVAL; 9837 if (i == 0) { 9838 if (krecord[i].insn_off) { 9839 verbose(env, 9840 "nonzero insn_off %u for the first func info record", 9841 krecord[i].insn_off); 9842 goto err_free; 9843 } 9844 } else if (krecord[i].insn_off <= prev_offset) { 9845 verbose(env, 9846 "same or smaller insn offset (%u) than previous func info record (%u)", 9847 krecord[i].insn_off, prev_offset); 9848 goto err_free; 9849 } 9850 9851 if (env->subprog_info[i].start != krecord[i].insn_off) { 9852 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 9853 goto err_free; 9854 } 9855 9856 /* check type_id */ 9857 type = btf_type_by_id(btf, krecord[i].type_id); 9858 if (!type || !btf_type_is_func(type)) { 9859 verbose(env, "invalid type id %d in func info", 9860 krecord[i].type_id); 9861 goto err_free; 9862 } 9863 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 9864 9865 func_proto = btf_type_by_id(btf, type->type); 9866 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 9867 /* btf_func_check() already verified it during BTF load */ 9868 goto err_free; 9869 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 9870 scalar_return = 9871 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type); 9872 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 9873 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 9874 goto err_free; 9875 } 9876 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 9877 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 9878 goto err_free; 9879 } 9880 9881 prev_offset = krecord[i].insn_off; 9882 bpfptr_add(&urecord, urec_size); 9883 } 9884 9885 prog->aux->func_info = krecord; 9886 prog->aux->func_info_cnt = nfuncs; 9887 prog->aux->func_info_aux = info_aux; 9888 return 0; 9889 9890 err_free: 9891 kvfree(krecord); 9892 kfree(info_aux); 9893 return ret; 9894 } 9895 9896 static void adjust_btf_func(struct bpf_verifier_env *env) 9897 { 9898 struct bpf_prog_aux *aux = env->prog->aux; 9899 int i; 9900 9901 if (!aux->func_info) 9902 return; 9903 9904 for (i = 0; i < env->subprog_cnt; i++) 9905 aux->func_info[i].insn_off = env->subprog_info[i].start; 9906 } 9907 9908 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 9909 sizeof(((struct bpf_line_info *)(0))->line_col)) 9910 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 9911 9912 static int check_btf_line(struct bpf_verifier_env *env, 9913 const union bpf_attr *attr, 9914 bpfptr_t uattr) 9915 { 9916 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 9917 struct bpf_subprog_info *sub; 9918 struct bpf_line_info *linfo; 9919 struct bpf_prog *prog; 9920 const struct btf *btf; 9921 bpfptr_t ulinfo; 9922 int err; 9923 9924 nr_linfo = attr->line_info_cnt; 9925 if (!nr_linfo) 9926 return 0; 9927 9928 rec_size = attr->line_info_rec_size; 9929 if (rec_size < MIN_BPF_LINEINFO_SIZE || 9930 rec_size > MAX_LINEINFO_REC_SIZE || 9931 rec_size & (sizeof(u32) - 1)) 9932 return -EINVAL; 9933 9934 /* Need to zero it in case the userspace may 9935 * pass in a smaller bpf_line_info object. 9936 */ 9937 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 9938 GFP_KERNEL | __GFP_NOWARN); 9939 if (!linfo) 9940 return -ENOMEM; 9941 9942 prog = env->prog; 9943 btf = prog->aux->btf; 9944 9945 s = 0; 9946 sub = env->subprog_info; 9947 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 9948 expected_size = sizeof(struct bpf_line_info); 9949 ncopy = min_t(u32, expected_size, rec_size); 9950 for (i = 0; i < nr_linfo; i++) { 9951 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 9952 if (err) { 9953 if (err == -E2BIG) { 9954 verbose(env, "nonzero tailing record in line_info"); 9955 if (copy_to_bpfptr_offset(uattr, 9956 offsetof(union bpf_attr, line_info_rec_size), 9957 &expected_size, sizeof(expected_size))) 9958 err = -EFAULT; 9959 } 9960 goto err_free; 9961 } 9962 9963 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 9964 err = -EFAULT; 9965 goto err_free; 9966 } 9967 9968 /* 9969 * Check insn_off to ensure 9970 * 1) strictly increasing AND 9971 * 2) bounded by prog->len 9972 * 9973 * The linfo[0].insn_off == 0 check logically falls into 9974 * the later "missing bpf_line_info for func..." case 9975 * because the first linfo[0].insn_off must be the 9976 * first sub also and the first sub must have 9977 * subprog_info[0].start == 0. 9978 */ 9979 if ((i && linfo[i].insn_off <= prev_offset) || 9980 linfo[i].insn_off >= prog->len) { 9981 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 9982 i, linfo[i].insn_off, prev_offset, 9983 prog->len); 9984 err = -EINVAL; 9985 goto err_free; 9986 } 9987 9988 if (!prog->insnsi[linfo[i].insn_off].code) { 9989 verbose(env, 9990 "Invalid insn code at line_info[%u].insn_off\n", 9991 i); 9992 err = -EINVAL; 9993 goto err_free; 9994 } 9995 9996 if (!btf_name_by_offset(btf, linfo[i].line_off) || 9997 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 9998 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 9999 err = -EINVAL; 10000 goto err_free; 10001 } 10002 10003 if (s != env->subprog_cnt) { 10004 if (linfo[i].insn_off == sub[s].start) { 10005 sub[s].linfo_idx = i; 10006 s++; 10007 } else if (sub[s].start < linfo[i].insn_off) { 10008 verbose(env, "missing bpf_line_info for func#%u\n", s); 10009 err = -EINVAL; 10010 goto err_free; 10011 } 10012 } 10013 10014 prev_offset = linfo[i].insn_off; 10015 bpfptr_add(&ulinfo, rec_size); 10016 } 10017 10018 if (s != env->subprog_cnt) { 10019 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 10020 env->subprog_cnt - s, s); 10021 err = -EINVAL; 10022 goto err_free; 10023 } 10024 10025 prog->aux->linfo = linfo; 10026 prog->aux->nr_linfo = nr_linfo; 10027 10028 return 0; 10029 10030 err_free: 10031 kvfree(linfo); 10032 return err; 10033 } 10034 10035 static int check_btf_info(struct bpf_verifier_env *env, 10036 const union bpf_attr *attr, 10037 bpfptr_t uattr) 10038 { 10039 struct btf *btf; 10040 int err; 10041 10042 if (!attr->func_info_cnt && !attr->line_info_cnt) { 10043 if (check_abnormal_return(env)) 10044 return -EINVAL; 10045 return 0; 10046 } 10047 10048 btf = btf_get_by_fd(attr->prog_btf_fd); 10049 if (IS_ERR(btf)) 10050 return PTR_ERR(btf); 10051 if (btf_is_kernel(btf)) { 10052 btf_put(btf); 10053 return -EACCES; 10054 } 10055 env->prog->aux->btf = btf; 10056 10057 err = check_btf_func(env, attr, uattr); 10058 if (err) 10059 return err; 10060 10061 err = check_btf_line(env, attr, uattr); 10062 if (err) 10063 return err; 10064 10065 return 0; 10066 } 10067 10068 /* check %cur's range satisfies %old's */ 10069 static bool range_within(struct bpf_reg_state *old, 10070 struct bpf_reg_state *cur) 10071 { 10072 return old->umin_value <= cur->umin_value && 10073 old->umax_value >= cur->umax_value && 10074 old->smin_value <= cur->smin_value && 10075 old->smax_value >= cur->smax_value && 10076 old->u32_min_value <= cur->u32_min_value && 10077 old->u32_max_value >= cur->u32_max_value && 10078 old->s32_min_value <= cur->s32_min_value && 10079 old->s32_max_value >= cur->s32_max_value; 10080 } 10081 10082 /* If in the old state two registers had the same id, then they need to have 10083 * the same id in the new state as well. But that id could be different from 10084 * the old state, so we need to track the mapping from old to new ids. 10085 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 10086 * regs with old id 5 must also have new id 9 for the new state to be safe. But 10087 * regs with a different old id could still have new id 9, we don't care about 10088 * that. 10089 * So we look through our idmap to see if this old id has been seen before. If 10090 * so, we require the new id to match; otherwise, we add the id pair to the map. 10091 */ 10092 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 10093 { 10094 unsigned int i; 10095 10096 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 10097 if (!idmap[i].old) { 10098 /* Reached an empty slot; haven't seen this id before */ 10099 idmap[i].old = old_id; 10100 idmap[i].cur = cur_id; 10101 return true; 10102 } 10103 if (idmap[i].old == old_id) 10104 return idmap[i].cur == cur_id; 10105 } 10106 /* We ran out of idmap slots, which should be impossible */ 10107 WARN_ON_ONCE(1); 10108 return false; 10109 } 10110 10111 static void clean_func_state(struct bpf_verifier_env *env, 10112 struct bpf_func_state *st) 10113 { 10114 enum bpf_reg_liveness live; 10115 int i, j; 10116 10117 for (i = 0; i < BPF_REG_FP; i++) { 10118 live = st->regs[i].live; 10119 /* liveness must not touch this register anymore */ 10120 st->regs[i].live |= REG_LIVE_DONE; 10121 if (!(live & REG_LIVE_READ)) 10122 /* since the register is unused, clear its state 10123 * to make further comparison simpler 10124 */ 10125 __mark_reg_not_init(env, &st->regs[i]); 10126 } 10127 10128 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 10129 live = st->stack[i].spilled_ptr.live; 10130 /* liveness must not touch this stack slot anymore */ 10131 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 10132 if (!(live & REG_LIVE_READ)) { 10133 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 10134 for (j = 0; j < BPF_REG_SIZE; j++) 10135 st->stack[i].slot_type[j] = STACK_INVALID; 10136 } 10137 } 10138 } 10139 10140 static void clean_verifier_state(struct bpf_verifier_env *env, 10141 struct bpf_verifier_state *st) 10142 { 10143 int i; 10144 10145 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 10146 /* all regs in this state in all frames were already marked */ 10147 return; 10148 10149 for (i = 0; i <= st->curframe; i++) 10150 clean_func_state(env, st->frame[i]); 10151 } 10152 10153 /* the parentage chains form a tree. 10154 * the verifier states are added to state lists at given insn and 10155 * pushed into state stack for future exploration. 10156 * when the verifier reaches bpf_exit insn some of the verifer states 10157 * stored in the state lists have their final liveness state already, 10158 * but a lot of states will get revised from liveness point of view when 10159 * the verifier explores other branches. 10160 * Example: 10161 * 1: r0 = 1 10162 * 2: if r1 == 100 goto pc+1 10163 * 3: r0 = 2 10164 * 4: exit 10165 * when the verifier reaches exit insn the register r0 in the state list of 10166 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 10167 * of insn 2 and goes exploring further. At the insn 4 it will walk the 10168 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 10169 * 10170 * Since the verifier pushes the branch states as it sees them while exploring 10171 * the program the condition of walking the branch instruction for the second 10172 * time means that all states below this branch were already explored and 10173 * their final liveness marks are already propagated. 10174 * Hence when the verifier completes the search of state list in is_state_visited() 10175 * we can call this clean_live_states() function to mark all liveness states 10176 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 10177 * will not be used. 10178 * This function also clears the registers and stack for states that !READ 10179 * to simplify state merging. 10180 * 10181 * Important note here that walking the same branch instruction in the callee 10182 * doesn't meant that the states are DONE. The verifier has to compare 10183 * the callsites 10184 */ 10185 static void clean_live_states(struct bpf_verifier_env *env, int insn, 10186 struct bpf_verifier_state *cur) 10187 { 10188 struct bpf_verifier_state_list *sl; 10189 int i; 10190 10191 sl = *explored_state(env, insn); 10192 while (sl) { 10193 if (sl->state.branches) 10194 goto next; 10195 if (sl->state.insn_idx != insn || 10196 sl->state.curframe != cur->curframe) 10197 goto next; 10198 for (i = 0; i <= cur->curframe; i++) 10199 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 10200 goto next; 10201 clean_verifier_state(env, &sl->state); 10202 next: 10203 sl = sl->next; 10204 } 10205 } 10206 10207 /* Returns true if (rold safe implies rcur safe) */ 10208 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 10209 struct bpf_id_pair *idmap) 10210 { 10211 bool equal; 10212 10213 if (!(rold->live & REG_LIVE_READ)) 10214 /* explored state didn't use this */ 10215 return true; 10216 10217 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 10218 10219 if (rold->type == PTR_TO_STACK) 10220 /* two stack pointers are equal only if they're pointing to 10221 * the same stack frame, since fp-8 in foo != fp-8 in bar 10222 */ 10223 return equal && rold->frameno == rcur->frameno; 10224 10225 if (equal) 10226 return true; 10227 10228 if (rold->type == NOT_INIT) 10229 /* explored state can't have used this */ 10230 return true; 10231 if (rcur->type == NOT_INIT) 10232 return false; 10233 switch (rold->type) { 10234 case SCALAR_VALUE: 10235 if (rcur->type == SCALAR_VALUE) { 10236 if (!rold->precise && !rcur->precise) 10237 return true; 10238 /* new val must satisfy old val knowledge */ 10239 return range_within(rold, rcur) && 10240 tnum_in(rold->var_off, rcur->var_off); 10241 } else { 10242 /* We're trying to use a pointer in place of a scalar. 10243 * Even if the scalar was unbounded, this could lead to 10244 * pointer leaks because scalars are allowed to leak 10245 * while pointers are not. We could make this safe in 10246 * special cases if root is calling us, but it's 10247 * probably not worth the hassle. 10248 */ 10249 return false; 10250 } 10251 case PTR_TO_MAP_KEY: 10252 case PTR_TO_MAP_VALUE: 10253 /* If the new min/max/var_off satisfy the old ones and 10254 * everything else matches, we are OK. 10255 * 'id' is not compared, since it's only used for maps with 10256 * bpf_spin_lock inside map element and in such cases if 10257 * the rest of the prog is valid for one map element then 10258 * it's valid for all map elements regardless of the key 10259 * used in bpf_map_lookup() 10260 */ 10261 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 10262 range_within(rold, rcur) && 10263 tnum_in(rold->var_off, rcur->var_off); 10264 case PTR_TO_MAP_VALUE_OR_NULL: 10265 /* a PTR_TO_MAP_VALUE could be safe to use as a 10266 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 10267 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 10268 * checked, doing so could have affected others with the same 10269 * id, and we can't check for that because we lost the id when 10270 * we converted to a PTR_TO_MAP_VALUE. 10271 */ 10272 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 10273 return false; 10274 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 10275 return false; 10276 /* Check our ids match any regs they're supposed to */ 10277 return check_ids(rold->id, rcur->id, idmap); 10278 case PTR_TO_PACKET_META: 10279 case PTR_TO_PACKET: 10280 if (rcur->type != rold->type) 10281 return false; 10282 /* We must have at least as much range as the old ptr 10283 * did, so that any accesses which were safe before are 10284 * still safe. This is true even if old range < old off, 10285 * since someone could have accessed through (ptr - k), or 10286 * even done ptr -= k in a register, to get a safe access. 10287 */ 10288 if (rold->range > rcur->range) 10289 return false; 10290 /* If the offsets don't match, we can't trust our alignment; 10291 * nor can we be sure that we won't fall out of range. 10292 */ 10293 if (rold->off != rcur->off) 10294 return false; 10295 /* id relations must be preserved */ 10296 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 10297 return false; 10298 /* new val must satisfy old val knowledge */ 10299 return range_within(rold, rcur) && 10300 tnum_in(rold->var_off, rcur->var_off); 10301 case PTR_TO_CTX: 10302 case CONST_PTR_TO_MAP: 10303 case PTR_TO_PACKET_END: 10304 case PTR_TO_FLOW_KEYS: 10305 case PTR_TO_SOCKET: 10306 case PTR_TO_SOCKET_OR_NULL: 10307 case PTR_TO_SOCK_COMMON: 10308 case PTR_TO_SOCK_COMMON_OR_NULL: 10309 case PTR_TO_TCP_SOCK: 10310 case PTR_TO_TCP_SOCK_OR_NULL: 10311 case PTR_TO_XDP_SOCK: 10312 /* Only valid matches are exact, which memcmp() above 10313 * would have accepted 10314 */ 10315 default: 10316 /* Don't know what's going on, just say it's not safe */ 10317 return false; 10318 } 10319 10320 /* Shouldn't get here; if we do, say it's not safe */ 10321 WARN_ON_ONCE(1); 10322 return false; 10323 } 10324 10325 static bool stacksafe(struct bpf_func_state *old, 10326 struct bpf_func_state *cur, 10327 struct bpf_id_pair *idmap) 10328 { 10329 int i, spi; 10330 10331 /* walk slots of the explored stack and ignore any additional 10332 * slots in the current stack, since explored(safe) state 10333 * didn't use them 10334 */ 10335 for (i = 0; i < old->allocated_stack; i++) { 10336 spi = i / BPF_REG_SIZE; 10337 10338 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 10339 i += BPF_REG_SIZE - 1; 10340 /* explored state didn't use this */ 10341 continue; 10342 } 10343 10344 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 10345 continue; 10346 10347 /* explored stack has more populated slots than current stack 10348 * and these slots were used 10349 */ 10350 if (i >= cur->allocated_stack) 10351 return false; 10352 10353 /* if old state was safe with misc data in the stack 10354 * it will be safe with zero-initialized stack. 10355 * The opposite is not true 10356 */ 10357 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 10358 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 10359 continue; 10360 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 10361 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 10362 /* Ex: old explored (safe) state has STACK_SPILL in 10363 * this stack slot, but current has STACK_MISC -> 10364 * this verifier states are not equivalent, 10365 * return false to continue verification of this path 10366 */ 10367 return false; 10368 if (i % BPF_REG_SIZE) 10369 continue; 10370 if (old->stack[spi].slot_type[0] != STACK_SPILL) 10371 continue; 10372 if (!regsafe(&old->stack[spi].spilled_ptr, 10373 &cur->stack[spi].spilled_ptr, 10374 idmap)) 10375 /* when explored and current stack slot are both storing 10376 * spilled registers, check that stored pointers types 10377 * are the same as well. 10378 * Ex: explored safe path could have stored 10379 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 10380 * but current path has stored: 10381 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 10382 * such verifier states are not equivalent. 10383 * return false to continue verification of this path 10384 */ 10385 return false; 10386 } 10387 return true; 10388 } 10389 10390 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 10391 { 10392 if (old->acquired_refs != cur->acquired_refs) 10393 return false; 10394 return !memcmp(old->refs, cur->refs, 10395 sizeof(*old->refs) * old->acquired_refs); 10396 } 10397 10398 /* compare two verifier states 10399 * 10400 * all states stored in state_list are known to be valid, since 10401 * verifier reached 'bpf_exit' instruction through them 10402 * 10403 * this function is called when verifier exploring different branches of 10404 * execution popped from the state stack. If it sees an old state that has 10405 * more strict register state and more strict stack state then this execution 10406 * branch doesn't need to be explored further, since verifier already 10407 * concluded that more strict state leads to valid finish. 10408 * 10409 * Therefore two states are equivalent if register state is more conservative 10410 * and explored stack state is more conservative than the current one. 10411 * Example: 10412 * explored current 10413 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 10414 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 10415 * 10416 * In other words if current stack state (one being explored) has more 10417 * valid slots than old one that already passed validation, it means 10418 * the verifier can stop exploring and conclude that current state is valid too 10419 * 10420 * Similarly with registers. If explored state has register type as invalid 10421 * whereas register type in current state is meaningful, it means that 10422 * the current state will reach 'bpf_exit' instruction safely 10423 */ 10424 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 10425 struct bpf_func_state *cur) 10426 { 10427 int i; 10428 10429 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 10430 for (i = 0; i < MAX_BPF_REG; i++) 10431 if (!regsafe(&old->regs[i], &cur->regs[i], env->idmap_scratch)) 10432 return false; 10433 10434 if (!stacksafe(old, cur, env->idmap_scratch)) 10435 return false; 10436 10437 if (!refsafe(old, cur)) 10438 return false; 10439 10440 return true; 10441 } 10442 10443 static bool states_equal(struct bpf_verifier_env *env, 10444 struct bpf_verifier_state *old, 10445 struct bpf_verifier_state *cur) 10446 { 10447 int i; 10448 10449 if (old->curframe != cur->curframe) 10450 return false; 10451 10452 /* Verification state from speculative execution simulation 10453 * must never prune a non-speculative execution one. 10454 */ 10455 if (old->speculative && !cur->speculative) 10456 return false; 10457 10458 if (old->active_spin_lock != cur->active_spin_lock) 10459 return false; 10460 10461 /* for states to be equal callsites have to be the same 10462 * and all frame states need to be equivalent 10463 */ 10464 for (i = 0; i <= old->curframe; i++) { 10465 if (old->frame[i]->callsite != cur->frame[i]->callsite) 10466 return false; 10467 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 10468 return false; 10469 } 10470 return true; 10471 } 10472 10473 /* Return 0 if no propagation happened. Return negative error code if error 10474 * happened. Otherwise, return the propagated bit. 10475 */ 10476 static int propagate_liveness_reg(struct bpf_verifier_env *env, 10477 struct bpf_reg_state *reg, 10478 struct bpf_reg_state *parent_reg) 10479 { 10480 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 10481 u8 flag = reg->live & REG_LIVE_READ; 10482 int err; 10483 10484 /* When comes here, read flags of PARENT_REG or REG could be any of 10485 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 10486 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 10487 */ 10488 if (parent_flag == REG_LIVE_READ64 || 10489 /* Or if there is no read flag from REG. */ 10490 !flag || 10491 /* Or if the read flag from REG is the same as PARENT_REG. */ 10492 parent_flag == flag) 10493 return 0; 10494 10495 err = mark_reg_read(env, reg, parent_reg, flag); 10496 if (err) 10497 return err; 10498 10499 return flag; 10500 } 10501 10502 /* A write screens off any subsequent reads; but write marks come from the 10503 * straight-line code between a state and its parent. When we arrive at an 10504 * equivalent state (jump target or such) we didn't arrive by the straight-line 10505 * code, so read marks in the state must propagate to the parent regardless 10506 * of the state's write marks. That's what 'parent == state->parent' comparison 10507 * in mark_reg_read() is for. 10508 */ 10509 static int propagate_liveness(struct bpf_verifier_env *env, 10510 const struct bpf_verifier_state *vstate, 10511 struct bpf_verifier_state *vparent) 10512 { 10513 struct bpf_reg_state *state_reg, *parent_reg; 10514 struct bpf_func_state *state, *parent; 10515 int i, frame, err = 0; 10516 10517 if (vparent->curframe != vstate->curframe) { 10518 WARN(1, "propagate_live: parent frame %d current frame %d\n", 10519 vparent->curframe, vstate->curframe); 10520 return -EFAULT; 10521 } 10522 /* Propagate read liveness of registers... */ 10523 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 10524 for (frame = 0; frame <= vstate->curframe; frame++) { 10525 parent = vparent->frame[frame]; 10526 state = vstate->frame[frame]; 10527 parent_reg = parent->regs; 10528 state_reg = state->regs; 10529 /* We don't need to worry about FP liveness, it's read-only */ 10530 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 10531 err = propagate_liveness_reg(env, &state_reg[i], 10532 &parent_reg[i]); 10533 if (err < 0) 10534 return err; 10535 if (err == REG_LIVE_READ64) 10536 mark_insn_zext(env, &parent_reg[i]); 10537 } 10538 10539 /* Propagate stack slots. */ 10540 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 10541 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 10542 parent_reg = &parent->stack[i].spilled_ptr; 10543 state_reg = &state->stack[i].spilled_ptr; 10544 err = propagate_liveness_reg(env, state_reg, 10545 parent_reg); 10546 if (err < 0) 10547 return err; 10548 } 10549 } 10550 return 0; 10551 } 10552 10553 /* find precise scalars in the previous equivalent state and 10554 * propagate them into the current state 10555 */ 10556 static int propagate_precision(struct bpf_verifier_env *env, 10557 const struct bpf_verifier_state *old) 10558 { 10559 struct bpf_reg_state *state_reg; 10560 struct bpf_func_state *state; 10561 int i, err = 0; 10562 10563 state = old->frame[old->curframe]; 10564 state_reg = state->regs; 10565 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 10566 if (state_reg->type != SCALAR_VALUE || 10567 !state_reg->precise) 10568 continue; 10569 if (env->log.level & BPF_LOG_LEVEL2) 10570 verbose(env, "propagating r%d\n", i); 10571 err = mark_chain_precision(env, i); 10572 if (err < 0) 10573 return err; 10574 } 10575 10576 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 10577 if (state->stack[i].slot_type[0] != STACK_SPILL) 10578 continue; 10579 state_reg = &state->stack[i].spilled_ptr; 10580 if (state_reg->type != SCALAR_VALUE || 10581 !state_reg->precise) 10582 continue; 10583 if (env->log.level & BPF_LOG_LEVEL2) 10584 verbose(env, "propagating fp%d\n", 10585 (-i - 1) * BPF_REG_SIZE); 10586 err = mark_chain_precision_stack(env, i); 10587 if (err < 0) 10588 return err; 10589 } 10590 return 0; 10591 } 10592 10593 static bool states_maybe_looping(struct bpf_verifier_state *old, 10594 struct bpf_verifier_state *cur) 10595 { 10596 struct bpf_func_state *fold, *fcur; 10597 int i, fr = cur->curframe; 10598 10599 if (old->curframe != fr) 10600 return false; 10601 10602 fold = old->frame[fr]; 10603 fcur = cur->frame[fr]; 10604 for (i = 0; i < MAX_BPF_REG; i++) 10605 if (memcmp(&fold->regs[i], &fcur->regs[i], 10606 offsetof(struct bpf_reg_state, parent))) 10607 return false; 10608 return true; 10609 } 10610 10611 10612 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 10613 { 10614 struct bpf_verifier_state_list *new_sl; 10615 struct bpf_verifier_state_list *sl, **pprev; 10616 struct bpf_verifier_state *cur = env->cur_state, *new; 10617 int i, j, err, states_cnt = 0; 10618 bool add_new_state = env->test_state_freq ? true : false; 10619 10620 cur->last_insn_idx = env->prev_insn_idx; 10621 if (!env->insn_aux_data[insn_idx].prune_point) 10622 /* this 'insn_idx' instruction wasn't marked, so we will not 10623 * be doing state search here 10624 */ 10625 return 0; 10626 10627 /* bpf progs typically have pruning point every 4 instructions 10628 * http://vger.kernel.org/bpfconf2019.html#session-1 10629 * Do not add new state for future pruning if the verifier hasn't seen 10630 * at least 2 jumps and at least 8 instructions. 10631 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 10632 * In tests that amounts to up to 50% reduction into total verifier 10633 * memory consumption and 20% verifier time speedup. 10634 */ 10635 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 10636 env->insn_processed - env->prev_insn_processed >= 8) 10637 add_new_state = true; 10638 10639 pprev = explored_state(env, insn_idx); 10640 sl = *pprev; 10641 10642 clean_live_states(env, insn_idx, cur); 10643 10644 while (sl) { 10645 states_cnt++; 10646 if (sl->state.insn_idx != insn_idx) 10647 goto next; 10648 10649 if (sl->state.branches) { 10650 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 10651 10652 if (frame->in_async_callback_fn && 10653 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 10654 /* Different async_entry_cnt means that the verifier is 10655 * processing another entry into async callback. 10656 * Seeing the same state is not an indication of infinite 10657 * loop or infinite recursion. 10658 * But finding the same state doesn't mean that it's safe 10659 * to stop processing the current state. The previous state 10660 * hasn't yet reached bpf_exit, since state.branches > 0. 10661 * Checking in_async_callback_fn alone is not enough either. 10662 * Since the verifier still needs to catch infinite loops 10663 * inside async callbacks. 10664 */ 10665 } else if (states_maybe_looping(&sl->state, cur) && 10666 states_equal(env, &sl->state, cur)) { 10667 verbose_linfo(env, insn_idx, "; "); 10668 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 10669 return -EINVAL; 10670 } 10671 /* if the verifier is processing a loop, avoid adding new state 10672 * too often, since different loop iterations have distinct 10673 * states and may not help future pruning. 10674 * This threshold shouldn't be too low to make sure that 10675 * a loop with large bound will be rejected quickly. 10676 * The most abusive loop will be: 10677 * r1 += 1 10678 * if r1 < 1000000 goto pc-2 10679 * 1M insn_procssed limit / 100 == 10k peak states. 10680 * This threshold shouldn't be too high either, since states 10681 * at the end of the loop are likely to be useful in pruning. 10682 */ 10683 if (env->jmps_processed - env->prev_jmps_processed < 20 && 10684 env->insn_processed - env->prev_insn_processed < 100) 10685 add_new_state = false; 10686 goto miss; 10687 } 10688 if (states_equal(env, &sl->state, cur)) { 10689 sl->hit_cnt++; 10690 /* reached equivalent register/stack state, 10691 * prune the search. 10692 * Registers read by the continuation are read by us. 10693 * If we have any write marks in env->cur_state, they 10694 * will prevent corresponding reads in the continuation 10695 * from reaching our parent (an explored_state). Our 10696 * own state will get the read marks recorded, but 10697 * they'll be immediately forgotten as we're pruning 10698 * this state and will pop a new one. 10699 */ 10700 err = propagate_liveness(env, &sl->state, cur); 10701 10702 /* if previous state reached the exit with precision and 10703 * current state is equivalent to it (except precsion marks) 10704 * the precision needs to be propagated back in 10705 * the current state. 10706 */ 10707 err = err ? : push_jmp_history(env, cur); 10708 err = err ? : propagate_precision(env, &sl->state); 10709 if (err) 10710 return err; 10711 return 1; 10712 } 10713 miss: 10714 /* when new state is not going to be added do not increase miss count. 10715 * Otherwise several loop iterations will remove the state 10716 * recorded earlier. The goal of these heuristics is to have 10717 * states from some iterations of the loop (some in the beginning 10718 * and some at the end) to help pruning. 10719 */ 10720 if (add_new_state) 10721 sl->miss_cnt++; 10722 /* heuristic to determine whether this state is beneficial 10723 * to keep checking from state equivalence point of view. 10724 * Higher numbers increase max_states_per_insn and verification time, 10725 * but do not meaningfully decrease insn_processed. 10726 */ 10727 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 10728 /* the state is unlikely to be useful. Remove it to 10729 * speed up verification 10730 */ 10731 *pprev = sl->next; 10732 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 10733 u32 br = sl->state.branches; 10734 10735 WARN_ONCE(br, 10736 "BUG live_done but branches_to_explore %d\n", 10737 br); 10738 free_verifier_state(&sl->state, false); 10739 kfree(sl); 10740 env->peak_states--; 10741 } else { 10742 /* cannot free this state, since parentage chain may 10743 * walk it later. Add it for free_list instead to 10744 * be freed at the end of verification 10745 */ 10746 sl->next = env->free_list; 10747 env->free_list = sl; 10748 } 10749 sl = *pprev; 10750 continue; 10751 } 10752 next: 10753 pprev = &sl->next; 10754 sl = *pprev; 10755 } 10756 10757 if (env->max_states_per_insn < states_cnt) 10758 env->max_states_per_insn = states_cnt; 10759 10760 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 10761 return push_jmp_history(env, cur); 10762 10763 if (!add_new_state) 10764 return push_jmp_history(env, cur); 10765 10766 /* There were no equivalent states, remember the current one. 10767 * Technically the current state is not proven to be safe yet, 10768 * but it will either reach outer most bpf_exit (which means it's safe) 10769 * or it will be rejected. When there are no loops the verifier won't be 10770 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 10771 * again on the way to bpf_exit. 10772 * When looping the sl->state.branches will be > 0 and this state 10773 * will not be considered for equivalence until branches == 0. 10774 */ 10775 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 10776 if (!new_sl) 10777 return -ENOMEM; 10778 env->total_states++; 10779 env->peak_states++; 10780 env->prev_jmps_processed = env->jmps_processed; 10781 env->prev_insn_processed = env->insn_processed; 10782 10783 /* add new state to the head of linked list */ 10784 new = &new_sl->state; 10785 err = copy_verifier_state(new, cur); 10786 if (err) { 10787 free_verifier_state(new, false); 10788 kfree(new_sl); 10789 return err; 10790 } 10791 new->insn_idx = insn_idx; 10792 WARN_ONCE(new->branches != 1, 10793 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 10794 10795 cur->parent = new; 10796 cur->first_insn_idx = insn_idx; 10797 clear_jmp_history(cur); 10798 new_sl->next = *explored_state(env, insn_idx); 10799 *explored_state(env, insn_idx) = new_sl; 10800 /* connect new state to parentage chain. Current frame needs all 10801 * registers connected. Only r6 - r9 of the callers are alive (pushed 10802 * to the stack implicitly by JITs) so in callers' frames connect just 10803 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 10804 * the state of the call instruction (with WRITTEN set), and r0 comes 10805 * from callee with its full parentage chain, anyway. 10806 */ 10807 /* clear write marks in current state: the writes we did are not writes 10808 * our child did, so they don't screen off its reads from us. 10809 * (There are no read marks in current state, because reads always mark 10810 * their parent and current state never has children yet. Only 10811 * explored_states can get read marks.) 10812 */ 10813 for (j = 0; j <= cur->curframe; j++) { 10814 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 10815 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 10816 for (i = 0; i < BPF_REG_FP; i++) 10817 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 10818 } 10819 10820 /* all stack frames are accessible from callee, clear them all */ 10821 for (j = 0; j <= cur->curframe; j++) { 10822 struct bpf_func_state *frame = cur->frame[j]; 10823 struct bpf_func_state *newframe = new->frame[j]; 10824 10825 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 10826 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 10827 frame->stack[i].spilled_ptr.parent = 10828 &newframe->stack[i].spilled_ptr; 10829 } 10830 } 10831 return 0; 10832 } 10833 10834 /* Return true if it's OK to have the same insn return a different type. */ 10835 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 10836 { 10837 switch (type) { 10838 case PTR_TO_CTX: 10839 case PTR_TO_SOCKET: 10840 case PTR_TO_SOCKET_OR_NULL: 10841 case PTR_TO_SOCK_COMMON: 10842 case PTR_TO_SOCK_COMMON_OR_NULL: 10843 case PTR_TO_TCP_SOCK: 10844 case PTR_TO_TCP_SOCK_OR_NULL: 10845 case PTR_TO_XDP_SOCK: 10846 case PTR_TO_BTF_ID: 10847 case PTR_TO_BTF_ID_OR_NULL: 10848 return false; 10849 default: 10850 return true; 10851 } 10852 } 10853 10854 /* If an instruction was previously used with particular pointer types, then we 10855 * need to be careful to avoid cases such as the below, where it may be ok 10856 * for one branch accessing the pointer, but not ok for the other branch: 10857 * 10858 * R1 = sock_ptr 10859 * goto X; 10860 * ... 10861 * R1 = some_other_valid_ptr; 10862 * goto X; 10863 * ... 10864 * R2 = *(u32 *)(R1 + 0); 10865 */ 10866 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 10867 { 10868 return src != prev && (!reg_type_mismatch_ok(src) || 10869 !reg_type_mismatch_ok(prev)); 10870 } 10871 10872 static int do_check(struct bpf_verifier_env *env) 10873 { 10874 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 10875 struct bpf_verifier_state *state = env->cur_state; 10876 struct bpf_insn *insns = env->prog->insnsi; 10877 struct bpf_reg_state *regs; 10878 int insn_cnt = env->prog->len; 10879 bool do_print_state = false; 10880 int prev_insn_idx = -1; 10881 10882 for (;;) { 10883 struct bpf_insn *insn; 10884 u8 class; 10885 int err; 10886 10887 env->prev_insn_idx = prev_insn_idx; 10888 if (env->insn_idx >= insn_cnt) { 10889 verbose(env, "invalid insn idx %d insn_cnt %d\n", 10890 env->insn_idx, insn_cnt); 10891 return -EFAULT; 10892 } 10893 10894 insn = &insns[env->insn_idx]; 10895 class = BPF_CLASS(insn->code); 10896 10897 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 10898 verbose(env, 10899 "BPF program is too large. Processed %d insn\n", 10900 env->insn_processed); 10901 return -E2BIG; 10902 } 10903 10904 err = is_state_visited(env, env->insn_idx); 10905 if (err < 0) 10906 return err; 10907 if (err == 1) { 10908 /* found equivalent state, can prune the search */ 10909 if (env->log.level & BPF_LOG_LEVEL) { 10910 if (do_print_state) 10911 verbose(env, "\nfrom %d to %d%s: safe\n", 10912 env->prev_insn_idx, env->insn_idx, 10913 env->cur_state->speculative ? 10914 " (speculative execution)" : ""); 10915 else 10916 verbose(env, "%d: safe\n", env->insn_idx); 10917 } 10918 goto process_bpf_exit; 10919 } 10920 10921 if (signal_pending(current)) 10922 return -EAGAIN; 10923 10924 if (need_resched()) 10925 cond_resched(); 10926 10927 if (env->log.level & BPF_LOG_LEVEL2 || 10928 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 10929 if (env->log.level & BPF_LOG_LEVEL2) 10930 verbose(env, "%d:", env->insn_idx); 10931 else 10932 verbose(env, "\nfrom %d to %d%s:", 10933 env->prev_insn_idx, env->insn_idx, 10934 env->cur_state->speculative ? 10935 " (speculative execution)" : ""); 10936 print_verifier_state(env, state->frame[state->curframe]); 10937 do_print_state = false; 10938 } 10939 10940 if (env->log.level & BPF_LOG_LEVEL) { 10941 const struct bpf_insn_cbs cbs = { 10942 .cb_call = disasm_kfunc_name, 10943 .cb_print = verbose, 10944 .private_data = env, 10945 }; 10946 10947 verbose_linfo(env, env->insn_idx, "; "); 10948 verbose(env, "%d: ", env->insn_idx); 10949 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 10950 } 10951 10952 if (bpf_prog_is_dev_bound(env->prog->aux)) { 10953 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 10954 env->prev_insn_idx); 10955 if (err) 10956 return err; 10957 } 10958 10959 regs = cur_regs(env); 10960 sanitize_mark_insn_seen(env); 10961 prev_insn_idx = env->insn_idx; 10962 10963 if (class == BPF_ALU || class == BPF_ALU64) { 10964 err = check_alu_op(env, insn); 10965 if (err) 10966 return err; 10967 10968 } else if (class == BPF_LDX) { 10969 enum bpf_reg_type *prev_src_type, src_reg_type; 10970 10971 /* check for reserved fields is already done */ 10972 10973 /* check src operand */ 10974 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10975 if (err) 10976 return err; 10977 10978 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 10979 if (err) 10980 return err; 10981 10982 src_reg_type = regs[insn->src_reg].type; 10983 10984 /* check that memory (src_reg + off) is readable, 10985 * the state of dst_reg will be updated by this func 10986 */ 10987 err = check_mem_access(env, env->insn_idx, insn->src_reg, 10988 insn->off, BPF_SIZE(insn->code), 10989 BPF_READ, insn->dst_reg, false); 10990 if (err) 10991 return err; 10992 10993 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 10994 10995 if (*prev_src_type == NOT_INIT) { 10996 /* saw a valid insn 10997 * dst_reg = *(u32 *)(src_reg + off) 10998 * save type to validate intersecting paths 10999 */ 11000 *prev_src_type = src_reg_type; 11001 11002 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 11003 /* ABuser program is trying to use the same insn 11004 * dst_reg = *(u32*) (src_reg + off) 11005 * with different pointer types: 11006 * src_reg == ctx in one branch and 11007 * src_reg == stack|map in some other branch. 11008 * Reject it. 11009 */ 11010 verbose(env, "same insn cannot be used with different pointers\n"); 11011 return -EINVAL; 11012 } 11013 11014 } else if (class == BPF_STX) { 11015 enum bpf_reg_type *prev_dst_type, dst_reg_type; 11016 11017 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 11018 err = check_atomic(env, env->insn_idx, insn); 11019 if (err) 11020 return err; 11021 env->insn_idx++; 11022 continue; 11023 } 11024 11025 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 11026 verbose(env, "BPF_STX uses reserved fields\n"); 11027 return -EINVAL; 11028 } 11029 11030 /* check src1 operand */ 11031 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11032 if (err) 11033 return err; 11034 /* check src2 operand */ 11035 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11036 if (err) 11037 return err; 11038 11039 dst_reg_type = regs[insn->dst_reg].type; 11040 11041 /* check that memory (dst_reg + off) is writeable */ 11042 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11043 insn->off, BPF_SIZE(insn->code), 11044 BPF_WRITE, insn->src_reg, false); 11045 if (err) 11046 return err; 11047 11048 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 11049 11050 if (*prev_dst_type == NOT_INIT) { 11051 *prev_dst_type = dst_reg_type; 11052 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 11053 verbose(env, "same insn cannot be used with different pointers\n"); 11054 return -EINVAL; 11055 } 11056 11057 } else if (class == BPF_ST) { 11058 if (BPF_MODE(insn->code) != BPF_MEM || 11059 insn->src_reg != BPF_REG_0) { 11060 verbose(env, "BPF_ST uses reserved fields\n"); 11061 return -EINVAL; 11062 } 11063 /* check src operand */ 11064 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11065 if (err) 11066 return err; 11067 11068 if (is_ctx_reg(env, insn->dst_reg)) { 11069 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 11070 insn->dst_reg, 11071 reg_type_str[reg_state(env, insn->dst_reg)->type]); 11072 return -EACCES; 11073 } 11074 11075 /* check that memory (dst_reg + off) is writeable */ 11076 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11077 insn->off, BPF_SIZE(insn->code), 11078 BPF_WRITE, -1, false); 11079 if (err) 11080 return err; 11081 11082 } else if (class == BPF_JMP || class == BPF_JMP32) { 11083 u8 opcode = BPF_OP(insn->code); 11084 11085 env->jmps_processed++; 11086 if (opcode == BPF_CALL) { 11087 if (BPF_SRC(insn->code) != BPF_K || 11088 insn->off != 0 || 11089 (insn->src_reg != BPF_REG_0 && 11090 insn->src_reg != BPF_PSEUDO_CALL && 11091 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 11092 insn->dst_reg != BPF_REG_0 || 11093 class == BPF_JMP32) { 11094 verbose(env, "BPF_CALL uses reserved fields\n"); 11095 return -EINVAL; 11096 } 11097 11098 if (env->cur_state->active_spin_lock && 11099 (insn->src_reg == BPF_PSEUDO_CALL || 11100 insn->imm != BPF_FUNC_spin_unlock)) { 11101 verbose(env, "function calls are not allowed while holding a lock\n"); 11102 return -EINVAL; 11103 } 11104 if (insn->src_reg == BPF_PSEUDO_CALL) 11105 err = check_func_call(env, insn, &env->insn_idx); 11106 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 11107 err = check_kfunc_call(env, insn); 11108 else 11109 err = check_helper_call(env, insn, &env->insn_idx); 11110 if (err) 11111 return err; 11112 } else if (opcode == BPF_JA) { 11113 if (BPF_SRC(insn->code) != BPF_K || 11114 insn->imm != 0 || 11115 insn->src_reg != BPF_REG_0 || 11116 insn->dst_reg != BPF_REG_0 || 11117 class == BPF_JMP32) { 11118 verbose(env, "BPF_JA uses reserved fields\n"); 11119 return -EINVAL; 11120 } 11121 11122 env->insn_idx += insn->off + 1; 11123 continue; 11124 11125 } else if (opcode == BPF_EXIT) { 11126 if (BPF_SRC(insn->code) != BPF_K || 11127 insn->imm != 0 || 11128 insn->src_reg != BPF_REG_0 || 11129 insn->dst_reg != BPF_REG_0 || 11130 class == BPF_JMP32) { 11131 verbose(env, "BPF_EXIT uses reserved fields\n"); 11132 return -EINVAL; 11133 } 11134 11135 if (env->cur_state->active_spin_lock) { 11136 verbose(env, "bpf_spin_unlock is missing\n"); 11137 return -EINVAL; 11138 } 11139 11140 if (state->curframe) { 11141 /* exit from nested function */ 11142 err = prepare_func_exit(env, &env->insn_idx); 11143 if (err) 11144 return err; 11145 do_print_state = true; 11146 continue; 11147 } 11148 11149 err = check_reference_leak(env); 11150 if (err) 11151 return err; 11152 11153 err = check_return_code(env); 11154 if (err) 11155 return err; 11156 process_bpf_exit: 11157 update_branch_counts(env, env->cur_state); 11158 err = pop_stack(env, &prev_insn_idx, 11159 &env->insn_idx, pop_log); 11160 if (err < 0) { 11161 if (err != -ENOENT) 11162 return err; 11163 break; 11164 } else { 11165 do_print_state = true; 11166 continue; 11167 } 11168 } else { 11169 err = check_cond_jmp_op(env, insn, &env->insn_idx); 11170 if (err) 11171 return err; 11172 } 11173 } else if (class == BPF_LD) { 11174 u8 mode = BPF_MODE(insn->code); 11175 11176 if (mode == BPF_ABS || mode == BPF_IND) { 11177 err = check_ld_abs(env, insn); 11178 if (err) 11179 return err; 11180 11181 } else if (mode == BPF_IMM) { 11182 err = check_ld_imm(env, insn); 11183 if (err) 11184 return err; 11185 11186 env->insn_idx++; 11187 sanitize_mark_insn_seen(env); 11188 } else { 11189 verbose(env, "invalid BPF_LD mode\n"); 11190 return -EINVAL; 11191 } 11192 } else { 11193 verbose(env, "unknown insn class %d\n", class); 11194 return -EINVAL; 11195 } 11196 11197 env->insn_idx++; 11198 } 11199 11200 return 0; 11201 } 11202 11203 static int find_btf_percpu_datasec(struct btf *btf) 11204 { 11205 const struct btf_type *t; 11206 const char *tname; 11207 int i, n; 11208 11209 /* 11210 * Both vmlinux and module each have their own ".data..percpu" 11211 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 11212 * types to look at only module's own BTF types. 11213 */ 11214 n = btf_nr_types(btf); 11215 if (btf_is_module(btf)) 11216 i = btf_nr_types(btf_vmlinux); 11217 else 11218 i = 1; 11219 11220 for(; i < n; i++) { 11221 t = btf_type_by_id(btf, i); 11222 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 11223 continue; 11224 11225 tname = btf_name_by_offset(btf, t->name_off); 11226 if (!strcmp(tname, ".data..percpu")) 11227 return i; 11228 } 11229 11230 return -ENOENT; 11231 } 11232 11233 /* replace pseudo btf_id with kernel symbol address */ 11234 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 11235 struct bpf_insn *insn, 11236 struct bpf_insn_aux_data *aux) 11237 { 11238 const struct btf_var_secinfo *vsi; 11239 const struct btf_type *datasec; 11240 struct btf_mod_pair *btf_mod; 11241 const struct btf_type *t; 11242 const char *sym_name; 11243 bool percpu = false; 11244 u32 type, id = insn->imm; 11245 struct btf *btf; 11246 s32 datasec_id; 11247 u64 addr; 11248 int i, btf_fd, err; 11249 11250 btf_fd = insn[1].imm; 11251 if (btf_fd) { 11252 btf = btf_get_by_fd(btf_fd); 11253 if (IS_ERR(btf)) { 11254 verbose(env, "invalid module BTF object FD specified.\n"); 11255 return -EINVAL; 11256 } 11257 } else { 11258 if (!btf_vmlinux) { 11259 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 11260 return -EINVAL; 11261 } 11262 btf = btf_vmlinux; 11263 btf_get(btf); 11264 } 11265 11266 t = btf_type_by_id(btf, id); 11267 if (!t) { 11268 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 11269 err = -ENOENT; 11270 goto err_put; 11271 } 11272 11273 if (!btf_type_is_var(t)) { 11274 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 11275 err = -EINVAL; 11276 goto err_put; 11277 } 11278 11279 sym_name = btf_name_by_offset(btf, t->name_off); 11280 addr = kallsyms_lookup_name(sym_name); 11281 if (!addr) { 11282 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 11283 sym_name); 11284 err = -ENOENT; 11285 goto err_put; 11286 } 11287 11288 datasec_id = find_btf_percpu_datasec(btf); 11289 if (datasec_id > 0) { 11290 datasec = btf_type_by_id(btf, datasec_id); 11291 for_each_vsi(i, datasec, vsi) { 11292 if (vsi->type == id) { 11293 percpu = true; 11294 break; 11295 } 11296 } 11297 } 11298 11299 insn[0].imm = (u32)addr; 11300 insn[1].imm = addr >> 32; 11301 11302 type = t->type; 11303 t = btf_type_skip_modifiers(btf, type, NULL); 11304 if (percpu) { 11305 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID; 11306 aux->btf_var.btf = btf; 11307 aux->btf_var.btf_id = type; 11308 } else if (!btf_type_is_struct(t)) { 11309 const struct btf_type *ret; 11310 const char *tname; 11311 u32 tsize; 11312 11313 /* resolve the type size of ksym. */ 11314 ret = btf_resolve_size(btf, t, &tsize); 11315 if (IS_ERR(ret)) { 11316 tname = btf_name_by_offset(btf, t->name_off); 11317 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 11318 tname, PTR_ERR(ret)); 11319 err = -EINVAL; 11320 goto err_put; 11321 } 11322 aux->btf_var.reg_type = PTR_TO_MEM; 11323 aux->btf_var.mem_size = tsize; 11324 } else { 11325 aux->btf_var.reg_type = PTR_TO_BTF_ID; 11326 aux->btf_var.btf = btf; 11327 aux->btf_var.btf_id = type; 11328 } 11329 11330 /* check whether we recorded this BTF (and maybe module) already */ 11331 for (i = 0; i < env->used_btf_cnt; i++) { 11332 if (env->used_btfs[i].btf == btf) { 11333 btf_put(btf); 11334 return 0; 11335 } 11336 } 11337 11338 if (env->used_btf_cnt >= MAX_USED_BTFS) { 11339 err = -E2BIG; 11340 goto err_put; 11341 } 11342 11343 btf_mod = &env->used_btfs[env->used_btf_cnt]; 11344 btf_mod->btf = btf; 11345 btf_mod->module = NULL; 11346 11347 /* if we reference variables from kernel module, bump its refcount */ 11348 if (btf_is_module(btf)) { 11349 btf_mod->module = btf_try_get_module(btf); 11350 if (!btf_mod->module) { 11351 err = -ENXIO; 11352 goto err_put; 11353 } 11354 } 11355 11356 env->used_btf_cnt++; 11357 11358 return 0; 11359 err_put: 11360 btf_put(btf); 11361 return err; 11362 } 11363 11364 static int check_map_prealloc(struct bpf_map *map) 11365 { 11366 return (map->map_type != BPF_MAP_TYPE_HASH && 11367 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 11368 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 11369 !(map->map_flags & BPF_F_NO_PREALLOC); 11370 } 11371 11372 static bool is_tracing_prog_type(enum bpf_prog_type type) 11373 { 11374 switch (type) { 11375 case BPF_PROG_TYPE_KPROBE: 11376 case BPF_PROG_TYPE_TRACEPOINT: 11377 case BPF_PROG_TYPE_PERF_EVENT: 11378 case BPF_PROG_TYPE_RAW_TRACEPOINT: 11379 return true; 11380 default: 11381 return false; 11382 } 11383 } 11384 11385 static bool is_preallocated_map(struct bpf_map *map) 11386 { 11387 if (!check_map_prealloc(map)) 11388 return false; 11389 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 11390 return false; 11391 return true; 11392 } 11393 11394 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 11395 struct bpf_map *map, 11396 struct bpf_prog *prog) 11397 11398 { 11399 enum bpf_prog_type prog_type = resolve_prog_type(prog); 11400 /* 11401 * Validate that trace type programs use preallocated hash maps. 11402 * 11403 * For programs attached to PERF events this is mandatory as the 11404 * perf NMI can hit any arbitrary code sequence. 11405 * 11406 * All other trace types using preallocated hash maps are unsafe as 11407 * well because tracepoint or kprobes can be inside locked regions 11408 * of the memory allocator or at a place where a recursion into the 11409 * memory allocator would see inconsistent state. 11410 * 11411 * On RT enabled kernels run-time allocation of all trace type 11412 * programs is strictly prohibited due to lock type constraints. On 11413 * !RT kernels it is allowed for backwards compatibility reasons for 11414 * now, but warnings are emitted so developers are made aware of 11415 * the unsafety and can fix their programs before this is enforced. 11416 */ 11417 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) { 11418 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) { 11419 verbose(env, "perf_event programs can only use preallocated hash map\n"); 11420 return -EINVAL; 11421 } 11422 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 11423 verbose(env, "trace type programs can only use preallocated hash map\n"); 11424 return -EINVAL; 11425 } 11426 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 11427 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 11428 } 11429 11430 if (map_value_has_spin_lock(map)) { 11431 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 11432 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 11433 return -EINVAL; 11434 } 11435 11436 if (is_tracing_prog_type(prog_type)) { 11437 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 11438 return -EINVAL; 11439 } 11440 11441 if (prog->aux->sleepable) { 11442 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 11443 return -EINVAL; 11444 } 11445 } 11446 11447 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 11448 !bpf_offload_prog_map_match(prog, map)) { 11449 verbose(env, "offload device mismatch between prog and map\n"); 11450 return -EINVAL; 11451 } 11452 11453 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 11454 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 11455 return -EINVAL; 11456 } 11457 11458 if (prog->aux->sleepable) 11459 switch (map->map_type) { 11460 case BPF_MAP_TYPE_HASH: 11461 case BPF_MAP_TYPE_LRU_HASH: 11462 case BPF_MAP_TYPE_ARRAY: 11463 case BPF_MAP_TYPE_PERCPU_HASH: 11464 case BPF_MAP_TYPE_PERCPU_ARRAY: 11465 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 11466 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 11467 case BPF_MAP_TYPE_HASH_OF_MAPS: 11468 if (!is_preallocated_map(map)) { 11469 verbose(env, 11470 "Sleepable programs can only use preallocated maps\n"); 11471 return -EINVAL; 11472 } 11473 break; 11474 case BPF_MAP_TYPE_RINGBUF: 11475 break; 11476 default: 11477 verbose(env, 11478 "Sleepable programs can only use array, hash, and ringbuf maps\n"); 11479 return -EINVAL; 11480 } 11481 11482 return 0; 11483 } 11484 11485 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 11486 { 11487 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 11488 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 11489 } 11490 11491 /* find and rewrite pseudo imm in ld_imm64 instructions: 11492 * 11493 * 1. if it accesses map FD, replace it with actual map pointer. 11494 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 11495 * 11496 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 11497 */ 11498 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 11499 { 11500 struct bpf_insn *insn = env->prog->insnsi; 11501 int insn_cnt = env->prog->len; 11502 int i, j, err; 11503 11504 err = bpf_prog_calc_tag(env->prog); 11505 if (err) 11506 return err; 11507 11508 for (i = 0; i < insn_cnt; i++, insn++) { 11509 if (BPF_CLASS(insn->code) == BPF_LDX && 11510 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 11511 verbose(env, "BPF_LDX uses reserved fields\n"); 11512 return -EINVAL; 11513 } 11514 11515 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 11516 struct bpf_insn_aux_data *aux; 11517 struct bpf_map *map; 11518 struct fd f; 11519 u64 addr; 11520 u32 fd; 11521 11522 if (i == insn_cnt - 1 || insn[1].code != 0 || 11523 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 11524 insn[1].off != 0) { 11525 verbose(env, "invalid bpf_ld_imm64 insn\n"); 11526 return -EINVAL; 11527 } 11528 11529 if (insn[0].src_reg == 0) 11530 /* valid generic load 64-bit imm */ 11531 goto next_insn; 11532 11533 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 11534 aux = &env->insn_aux_data[i]; 11535 err = check_pseudo_btf_id(env, insn, aux); 11536 if (err) 11537 return err; 11538 goto next_insn; 11539 } 11540 11541 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 11542 aux = &env->insn_aux_data[i]; 11543 aux->ptr_type = PTR_TO_FUNC; 11544 goto next_insn; 11545 } 11546 11547 /* In final convert_pseudo_ld_imm64() step, this is 11548 * converted into regular 64-bit imm load insn. 11549 */ 11550 switch (insn[0].src_reg) { 11551 case BPF_PSEUDO_MAP_VALUE: 11552 case BPF_PSEUDO_MAP_IDX_VALUE: 11553 break; 11554 case BPF_PSEUDO_MAP_FD: 11555 case BPF_PSEUDO_MAP_IDX: 11556 if (insn[1].imm == 0) 11557 break; 11558 fallthrough; 11559 default: 11560 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 11561 return -EINVAL; 11562 } 11563 11564 switch (insn[0].src_reg) { 11565 case BPF_PSEUDO_MAP_IDX_VALUE: 11566 case BPF_PSEUDO_MAP_IDX: 11567 if (bpfptr_is_null(env->fd_array)) { 11568 verbose(env, "fd_idx without fd_array is invalid\n"); 11569 return -EPROTO; 11570 } 11571 if (copy_from_bpfptr_offset(&fd, env->fd_array, 11572 insn[0].imm * sizeof(fd), 11573 sizeof(fd))) 11574 return -EFAULT; 11575 break; 11576 default: 11577 fd = insn[0].imm; 11578 break; 11579 } 11580 11581 f = fdget(fd); 11582 map = __bpf_map_get(f); 11583 if (IS_ERR(map)) { 11584 verbose(env, "fd %d is not pointing to valid bpf_map\n", 11585 insn[0].imm); 11586 return PTR_ERR(map); 11587 } 11588 11589 err = check_map_prog_compatibility(env, map, env->prog); 11590 if (err) { 11591 fdput(f); 11592 return err; 11593 } 11594 11595 aux = &env->insn_aux_data[i]; 11596 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 11597 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 11598 addr = (unsigned long)map; 11599 } else { 11600 u32 off = insn[1].imm; 11601 11602 if (off >= BPF_MAX_VAR_OFF) { 11603 verbose(env, "direct value offset of %u is not allowed\n", off); 11604 fdput(f); 11605 return -EINVAL; 11606 } 11607 11608 if (!map->ops->map_direct_value_addr) { 11609 verbose(env, "no direct value access support for this map type\n"); 11610 fdput(f); 11611 return -EINVAL; 11612 } 11613 11614 err = map->ops->map_direct_value_addr(map, &addr, off); 11615 if (err) { 11616 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 11617 map->value_size, off); 11618 fdput(f); 11619 return err; 11620 } 11621 11622 aux->map_off = off; 11623 addr += off; 11624 } 11625 11626 insn[0].imm = (u32)addr; 11627 insn[1].imm = addr >> 32; 11628 11629 /* check whether we recorded this map already */ 11630 for (j = 0; j < env->used_map_cnt; j++) { 11631 if (env->used_maps[j] == map) { 11632 aux->map_index = j; 11633 fdput(f); 11634 goto next_insn; 11635 } 11636 } 11637 11638 if (env->used_map_cnt >= MAX_USED_MAPS) { 11639 fdput(f); 11640 return -E2BIG; 11641 } 11642 11643 /* hold the map. If the program is rejected by verifier, 11644 * the map will be released by release_maps() or it 11645 * will be used by the valid program until it's unloaded 11646 * and all maps are released in free_used_maps() 11647 */ 11648 bpf_map_inc(map); 11649 11650 aux->map_index = env->used_map_cnt; 11651 env->used_maps[env->used_map_cnt++] = map; 11652 11653 if (bpf_map_is_cgroup_storage(map) && 11654 bpf_cgroup_storage_assign(env->prog->aux, map)) { 11655 verbose(env, "only one cgroup storage of each type is allowed\n"); 11656 fdput(f); 11657 return -EBUSY; 11658 } 11659 11660 fdput(f); 11661 next_insn: 11662 insn++; 11663 i++; 11664 continue; 11665 } 11666 11667 /* Basic sanity check before we invest more work here. */ 11668 if (!bpf_opcode_in_insntable(insn->code)) { 11669 verbose(env, "unknown opcode %02x\n", insn->code); 11670 return -EINVAL; 11671 } 11672 } 11673 11674 /* now all pseudo BPF_LD_IMM64 instructions load valid 11675 * 'struct bpf_map *' into a register instead of user map_fd. 11676 * These pointers will be used later by verifier to validate map access. 11677 */ 11678 return 0; 11679 } 11680 11681 /* drop refcnt of maps used by the rejected program */ 11682 static void release_maps(struct bpf_verifier_env *env) 11683 { 11684 __bpf_free_used_maps(env->prog->aux, env->used_maps, 11685 env->used_map_cnt); 11686 } 11687 11688 /* drop refcnt of maps used by the rejected program */ 11689 static void release_btfs(struct bpf_verifier_env *env) 11690 { 11691 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 11692 env->used_btf_cnt); 11693 } 11694 11695 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 11696 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 11697 { 11698 struct bpf_insn *insn = env->prog->insnsi; 11699 int insn_cnt = env->prog->len; 11700 int i; 11701 11702 for (i = 0; i < insn_cnt; i++, insn++) { 11703 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 11704 continue; 11705 if (insn->src_reg == BPF_PSEUDO_FUNC) 11706 continue; 11707 insn->src_reg = 0; 11708 } 11709 } 11710 11711 /* single env->prog->insni[off] instruction was replaced with the range 11712 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 11713 * [0, off) and [off, end) to new locations, so the patched range stays zero 11714 */ 11715 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 11716 struct bpf_insn_aux_data *new_data, 11717 struct bpf_prog *new_prog, u32 off, u32 cnt) 11718 { 11719 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 11720 struct bpf_insn *insn = new_prog->insnsi; 11721 u32 old_seen = old_data[off].seen; 11722 u32 prog_len; 11723 int i; 11724 11725 /* aux info at OFF always needs adjustment, no matter fast path 11726 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 11727 * original insn at old prog. 11728 */ 11729 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 11730 11731 if (cnt == 1) 11732 return; 11733 prog_len = new_prog->len; 11734 11735 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 11736 memcpy(new_data + off + cnt - 1, old_data + off, 11737 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 11738 for (i = off; i < off + cnt - 1; i++) { 11739 /* Expand insni[off]'s seen count to the patched range. */ 11740 new_data[i].seen = old_seen; 11741 new_data[i].zext_dst = insn_has_def32(env, insn + i); 11742 } 11743 env->insn_aux_data = new_data; 11744 vfree(old_data); 11745 } 11746 11747 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 11748 { 11749 int i; 11750 11751 if (len == 1) 11752 return; 11753 /* NOTE: fake 'exit' subprog should be updated as well. */ 11754 for (i = 0; i <= env->subprog_cnt; i++) { 11755 if (env->subprog_info[i].start <= off) 11756 continue; 11757 env->subprog_info[i].start += len - 1; 11758 } 11759 } 11760 11761 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 11762 { 11763 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 11764 int i, sz = prog->aux->size_poke_tab; 11765 struct bpf_jit_poke_descriptor *desc; 11766 11767 for (i = 0; i < sz; i++) { 11768 desc = &tab[i]; 11769 if (desc->insn_idx <= off) 11770 continue; 11771 desc->insn_idx += len - 1; 11772 } 11773 } 11774 11775 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 11776 const struct bpf_insn *patch, u32 len) 11777 { 11778 struct bpf_prog *new_prog; 11779 struct bpf_insn_aux_data *new_data = NULL; 11780 11781 if (len > 1) { 11782 new_data = vzalloc(array_size(env->prog->len + len - 1, 11783 sizeof(struct bpf_insn_aux_data))); 11784 if (!new_data) 11785 return NULL; 11786 } 11787 11788 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 11789 if (IS_ERR(new_prog)) { 11790 if (PTR_ERR(new_prog) == -ERANGE) 11791 verbose(env, 11792 "insn %d cannot be patched due to 16-bit range\n", 11793 env->insn_aux_data[off].orig_idx); 11794 vfree(new_data); 11795 return NULL; 11796 } 11797 adjust_insn_aux_data(env, new_data, new_prog, off, len); 11798 adjust_subprog_starts(env, off, len); 11799 adjust_poke_descs(new_prog, off, len); 11800 return new_prog; 11801 } 11802 11803 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 11804 u32 off, u32 cnt) 11805 { 11806 int i, j; 11807 11808 /* find first prog starting at or after off (first to remove) */ 11809 for (i = 0; i < env->subprog_cnt; i++) 11810 if (env->subprog_info[i].start >= off) 11811 break; 11812 /* find first prog starting at or after off + cnt (first to stay) */ 11813 for (j = i; j < env->subprog_cnt; j++) 11814 if (env->subprog_info[j].start >= off + cnt) 11815 break; 11816 /* if j doesn't start exactly at off + cnt, we are just removing 11817 * the front of previous prog 11818 */ 11819 if (env->subprog_info[j].start != off + cnt) 11820 j--; 11821 11822 if (j > i) { 11823 struct bpf_prog_aux *aux = env->prog->aux; 11824 int move; 11825 11826 /* move fake 'exit' subprog as well */ 11827 move = env->subprog_cnt + 1 - j; 11828 11829 memmove(env->subprog_info + i, 11830 env->subprog_info + j, 11831 sizeof(*env->subprog_info) * move); 11832 env->subprog_cnt -= j - i; 11833 11834 /* remove func_info */ 11835 if (aux->func_info) { 11836 move = aux->func_info_cnt - j; 11837 11838 memmove(aux->func_info + i, 11839 aux->func_info + j, 11840 sizeof(*aux->func_info) * move); 11841 aux->func_info_cnt -= j - i; 11842 /* func_info->insn_off is set after all code rewrites, 11843 * in adjust_btf_func() - no need to adjust 11844 */ 11845 } 11846 } else { 11847 /* convert i from "first prog to remove" to "first to adjust" */ 11848 if (env->subprog_info[i].start == off) 11849 i++; 11850 } 11851 11852 /* update fake 'exit' subprog as well */ 11853 for (; i <= env->subprog_cnt; i++) 11854 env->subprog_info[i].start -= cnt; 11855 11856 return 0; 11857 } 11858 11859 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 11860 u32 cnt) 11861 { 11862 struct bpf_prog *prog = env->prog; 11863 u32 i, l_off, l_cnt, nr_linfo; 11864 struct bpf_line_info *linfo; 11865 11866 nr_linfo = prog->aux->nr_linfo; 11867 if (!nr_linfo) 11868 return 0; 11869 11870 linfo = prog->aux->linfo; 11871 11872 /* find first line info to remove, count lines to be removed */ 11873 for (i = 0; i < nr_linfo; i++) 11874 if (linfo[i].insn_off >= off) 11875 break; 11876 11877 l_off = i; 11878 l_cnt = 0; 11879 for (; i < nr_linfo; i++) 11880 if (linfo[i].insn_off < off + cnt) 11881 l_cnt++; 11882 else 11883 break; 11884 11885 /* First live insn doesn't match first live linfo, it needs to "inherit" 11886 * last removed linfo. prog is already modified, so prog->len == off 11887 * means no live instructions after (tail of the program was removed). 11888 */ 11889 if (prog->len != off && l_cnt && 11890 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 11891 l_cnt--; 11892 linfo[--i].insn_off = off + cnt; 11893 } 11894 11895 /* remove the line info which refer to the removed instructions */ 11896 if (l_cnt) { 11897 memmove(linfo + l_off, linfo + i, 11898 sizeof(*linfo) * (nr_linfo - i)); 11899 11900 prog->aux->nr_linfo -= l_cnt; 11901 nr_linfo = prog->aux->nr_linfo; 11902 } 11903 11904 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 11905 for (i = l_off; i < nr_linfo; i++) 11906 linfo[i].insn_off -= cnt; 11907 11908 /* fix up all subprogs (incl. 'exit') which start >= off */ 11909 for (i = 0; i <= env->subprog_cnt; i++) 11910 if (env->subprog_info[i].linfo_idx > l_off) { 11911 /* program may have started in the removed region but 11912 * may not be fully removed 11913 */ 11914 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 11915 env->subprog_info[i].linfo_idx -= l_cnt; 11916 else 11917 env->subprog_info[i].linfo_idx = l_off; 11918 } 11919 11920 return 0; 11921 } 11922 11923 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 11924 { 11925 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11926 unsigned int orig_prog_len = env->prog->len; 11927 int err; 11928 11929 if (bpf_prog_is_dev_bound(env->prog->aux)) 11930 bpf_prog_offload_remove_insns(env, off, cnt); 11931 11932 err = bpf_remove_insns(env->prog, off, cnt); 11933 if (err) 11934 return err; 11935 11936 err = adjust_subprog_starts_after_remove(env, off, cnt); 11937 if (err) 11938 return err; 11939 11940 err = bpf_adj_linfo_after_remove(env, off, cnt); 11941 if (err) 11942 return err; 11943 11944 memmove(aux_data + off, aux_data + off + cnt, 11945 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 11946 11947 return 0; 11948 } 11949 11950 /* The verifier does more data flow analysis than llvm and will not 11951 * explore branches that are dead at run time. Malicious programs can 11952 * have dead code too. Therefore replace all dead at-run-time code 11953 * with 'ja -1'. 11954 * 11955 * Just nops are not optimal, e.g. if they would sit at the end of the 11956 * program and through another bug we would manage to jump there, then 11957 * we'd execute beyond program memory otherwise. Returning exception 11958 * code also wouldn't work since we can have subprogs where the dead 11959 * code could be located. 11960 */ 11961 static void sanitize_dead_code(struct bpf_verifier_env *env) 11962 { 11963 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11964 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 11965 struct bpf_insn *insn = env->prog->insnsi; 11966 const int insn_cnt = env->prog->len; 11967 int i; 11968 11969 for (i = 0; i < insn_cnt; i++) { 11970 if (aux_data[i].seen) 11971 continue; 11972 memcpy(insn + i, &trap, sizeof(trap)); 11973 } 11974 } 11975 11976 static bool insn_is_cond_jump(u8 code) 11977 { 11978 u8 op; 11979 11980 if (BPF_CLASS(code) == BPF_JMP32) 11981 return true; 11982 11983 if (BPF_CLASS(code) != BPF_JMP) 11984 return false; 11985 11986 op = BPF_OP(code); 11987 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 11988 } 11989 11990 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 11991 { 11992 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11993 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 11994 struct bpf_insn *insn = env->prog->insnsi; 11995 const int insn_cnt = env->prog->len; 11996 int i; 11997 11998 for (i = 0; i < insn_cnt; i++, insn++) { 11999 if (!insn_is_cond_jump(insn->code)) 12000 continue; 12001 12002 if (!aux_data[i + 1].seen) 12003 ja.off = insn->off; 12004 else if (!aux_data[i + 1 + insn->off].seen) 12005 ja.off = 0; 12006 else 12007 continue; 12008 12009 if (bpf_prog_is_dev_bound(env->prog->aux)) 12010 bpf_prog_offload_replace_insn(env, i, &ja); 12011 12012 memcpy(insn, &ja, sizeof(ja)); 12013 } 12014 } 12015 12016 static int opt_remove_dead_code(struct bpf_verifier_env *env) 12017 { 12018 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12019 int insn_cnt = env->prog->len; 12020 int i, err; 12021 12022 for (i = 0; i < insn_cnt; i++) { 12023 int j; 12024 12025 j = 0; 12026 while (i + j < insn_cnt && !aux_data[i + j].seen) 12027 j++; 12028 if (!j) 12029 continue; 12030 12031 err = verifier_remove_insns(env, i, j); 12032 if (err) 12033 return err; 12034 insn_cnt = env->prog->len; 12035 } 12036 12037 return 0; 12038 } 12039 12040 static int opt_remove_nops(struct bpf_verifier_env *env) 12041 { 12042 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 12043 struct bpf_insn *insn = env->prog->insnsi; 12044 int insn_cnt = env->prog->len; 12045 int i, err; 12046 12047 for (i = 0; i < insn_cnt; i++) { 12048 if (memcmp(&insn[i], &ja, sizeof(ja))) 12049 continue; 12050 12051 err = verifier_remove_insns(env, i, 1); 12052 if (err) 12053 return err; 12054 insn_cnt--; 12055 i--; 12056 } 12057 12058 return 0; 12059 } 12060 12061 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 12062 const union bpf_attr *attr) 12063 { 12064 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 12065 struct bpf_insn_aux_data *aux = env->insn_aux_data; 12066 int i, patch_len, delta = 0, len = env->prog->len; 12067 struct bpf_insn *insns = env->prog->insnsi; 12068 struct bpf_prog *new_prog; 12069 bool rnd_hi32; 12070 12071 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 12072 zext_patch[1] = BPF_ZEXT_REG(0); 12073 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 12074 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 12075 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 12076 for (i = 0; i < len; i++) { 12077 int adj_idx = i + delta; 12078 struct bpf_insn insn; 12079 int load_reg; 12080 12081 insn = insns[adj_idx]; 12082 load_reg = insn_def_regno(&insn); 12083 if (!aux[adj_idx].zext_dst) { 12084 u8 code, class; 12085 u32 imm_rnd; 12086 12087 if (!rnd_hi32) 12088 continue; 12089 12090 code = insn.code; 12091 class = BPF_CLASS(code); 12092 if (load_reg == -1) 12093 continue; 12094 12095 /* NOTE: arg "reg" (the fourth one) is only used for 12096 * BPF_STX + SRC_OP, so it is safe to pass NULL 12097 * here. 12098 */ 12099 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 12100 if (class == BPF_LD && 12101 BPF_MODE(code) == BPF_IMM) 12102 i++; 12103 continue; 12104 } 12105 12106 /* ctx load could be transformed into wider load. */ 12107 if (class == BPF_LDX && 12108 aux[adj_idx].ptr_type == PTR_TO_CTX) 12109 continue; 12110 12111 imm_rnd = get_random_int(); 12112 rnd_hi32_patch[0] = insn; 12113 rnd_hi32_patch[1].imm = imm_rnd; 12114 rnd_hi32_patch[3].dst_reg = load_reg; 12115 patch = rnd_hi32_patch; 12116 patch_len = 4; 12117 goto apply_patch_buffer; 12118 } 12119 12120 /* Add in an zero-extend instruction if a) the JIT has requested 12121 * it or b) it's a CMPXCHG. 12122 * 12123 * The latter is because: BPF_CMPXCHG always loads a value into 12124 * R0, therefore always zero-extends. However some archs' 12125 * equivalent instruction only does this load when the 12126 * comparison is successful. This detail of CMPXCHG is 12127 * orthogonal to the general zero-extension behaviour of the 12128 * CPU, so it's treated independently of bpf_jit_needs_zext. 12129 */ 12130 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 12131 continue; 12132 12133 if (WARN_ON(load_reg == -1)) { 12134 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 12135 return -EFAULT; 12136 } 12137 12138 zext_patch[0] = insn; 12139 zext_patch[1].dst_reg = load_reg; 12140 zext_patch[1].src_reg = load_reg; 12141 patch = zext_patch; 12142 patch_len = 2; 12143 apply_patch_buffer: 12144 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 12145 if (!new_prog) 12146 return -ENOMEM; 12147 env->prog = new_prog; 12148 insns = new_prog->insnsi; 12149 aux = env->insn_aux_data; 12150 delta += patch_len - 1; 12151 } 12152 12153 return 0; 12154 } 12155 12156 /* convert load instructions that access fields of a context type into a 12157 * sequence of instructions that access fields of the underlying structure: 12158 * struct __sk_buff -> struct sk_buff 12159 * struct bpf_sock_ops -> struct sock 12160 */ 12161 static int convert_ctx_accesses(struct bpf_verifier_env *env) 12162 { 12163 const struct bpf_verifier_ops *ops = env->ops; 12164 int i, cnt, size, ctx_field_size, delta = 0; 12165 const int insn_cnt = env->prog->len; 12166 struct bpf_insn insn_buf[16], *insn; 12167 u32 target_size, size_default, off; 12168 struct bpf_prog *new_prog; 12169 enum bpf_access_type type; 12170 bool is_narrower_load; 12171 12172 if (ops->gen_prologue || env->seen_direct_write) { 12173 if (!ops->gen_prologue) { 12174 verbose(env, "bpf verifier is misconfigured\n"); 12175 return -EINVAL; 12176 } 12177 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 12178 env->prog); 12179 if (cnt >= ARRAY_SIZE(insn_buf)) { 12180 verbose(env, "bpf verifier is misconfigured\n"); 12181 return -EINVAL; 12182 } else if (cnt) { 12183 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 12184 if (!new_prog) 12185 return -ENOMEM; 12186 12187 env->prog = new_prog; 12188 delta += cnt - 1; 12189 } 12190 } 12191 12192 if (bpf_prog_is_dev_bound(env->prog->aux)) 12193 return 0; 12194 12195 insn = env->prog->insnsi + delta; 12196 12197 for (i = 0; i < insn_cnt; i++, insn++) { 12198 bpf_convert_ctx_access_t convert_ctx_access; 12199 12200 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 12201 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 12202 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 12203 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 12204 type = BPF_READ; 12205 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 12206 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 12207 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 12208 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 12209 type = BPF_WRITE; 12210 else 12211 continue; 12212 12213 if (type == BPF_WRITE && 12214 env->insn_aux_data[i + delta].sanitize_stack_off) { 12215 struct bpf_insn patch[] = { 12216 /* Sanitize suspicious stack slot with zero. 12217 * There are no memory dependencies for this store, 12218 * since it's only using frame pointer and immediate 12219 * constant of zero 12220 */ 12221 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 12222 env->insn_aux_data[i + delta].sanitize_stack_off, 12223 0), 12224 /* the original STX instruction will immediately 12225 * overwrite the same stack slot with appropriate value 12226 */ 12227 *insn, 12228 }; 12229 12230 cnt = ARRAY_SIZE(patch); 12231 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 12232 if (!new_prog) 12233 return -ENOMEM; 12234 12235 delta += cnt - 1; 12236 env->prog = new_prog; 12237 insn = new_prog->insnsi + i + delta; 12238 continue; 12239 } 12240 12241 switch (env->insn_aux_data[i + delta].ptr_type) { 12242 case PTR_TO_CTX: 12243 if (!ops->convert_ctx_access) 12244 continue; 12245 convert_ctx_access = ops->convert_ctx_access; 12246 break; 12247 case PTR_TO_SOCKET: 12248 case PTR_TO_SOCK_COMMON: 12249 convert_ctx_access = bpf_sock_convert_ctx_access; 12250 break; 12251 case PTR_TO_TCP_SOCK: 12252 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 12253 break; 12254 case PTR_TO_XDP_SOCK: 12255 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 12256 break; 12257 case PTR_TO_BTF_ID: 12258 if (type == BPF_READ) { 12259 insn->code = BPF_LDX | BPF_PROBE_MEM | 12260 BPF_SIZE((insn)->code); 12261 env->prog->aux->num_exentries++; 12262 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) { 12263 verbose(env, "Writes through BTF pointers are not allowed\n"); 12264 return -EINVAL; 12265 } 12266 continue; 12267 default: 12268 continue; 12269 } 12270 12271 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 12272 size = BPF_LDST_BYTES(insn); 12273 12274 /* If the read access is a narrower load of the field, 12275 * convert to a 4/8-byte load, to minimum program type specific 12276 * convert_ctx_access changes. If conversion is successful, 12277 * we will apply proper mask to the result. 12278 */ 12279 is_narrower_load = size < ctx_field_size; 12280 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 12281 off = insn->off; 12282 if (is_narrower_load) { 12283 u8 size_code; 12284 12285 if (type == BPF_WRITE) { 12286 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 12287 return -EINVAL; 12288 } 12289 12290 size_code = BPF_H; 12291 if (ctx_field_size == 4) 12292 size_code = BPF_W; 12293 else if (ctx_field_size == 8) 12294 size_code = BPF_DW; 12295 12296 insn->off = off & ~(size_default - 1); 12297 insn->code = BPF_LDX | BPF_MEM | size_code; 12298 } 12299 12300 target_size = 0; 12301 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 12302 &target_size); 12303 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 12304 (ctx_field_size && !target_size)) { 12305 verbose(env, "bpf verifier is misconfigured\n"); 12306 return -EINVAL; 12307 } 12308 12309 if (is_narrower_load && size < target_size) { 12310 u8 shift = bpf_ctx_narrow_access_offset( 12311 off, size, size_default) * 8; 12312 if (ctx_field_size <= 4) { 12313 if (shift) 12314 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 12315 insn->dst_reg, 12316 shift); 12317 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 12318 (1 << size * 8) - 1); 12319 } else { 12320 if (shift) 12321 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 12322 insn->dst_reg, 12323 shift); 12324 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 12325 (1ULL << size * 8) - 1); 12326 } 12327 } 12328 12329 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12330 if (!new_prog) 12331 return -ENOMEM; 12332 12333 delta += cnt - 1; 12334 12335 /* keep walking new program and skip insns we just inserted */ 12336 env->prog = new_prog; 12337 insn = new_prog->insnsi + i + delta; 12338 } 12339 12340 return 0; 12341 } 12342 12343 static int jit_subprogs(struct bpf_verifier_env *env) 12344 { 12345 struct bpf_prog *prog = env->prog, **func, *tmp; 12346 int i, j, subprog_start, subprog_end = 0, len, subprog; 12347 struct bpf_map *map_ptr; 12348 struct bpf_insn *insn; 12349 void *old_bpf_func; 12350 int err, num_exentries; 12351 12352 if (env->subprog_cnt <= 1) 12353 return 0; 12354 12355 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12356 if (bpf_pseudo_func(insn)) { 12357 env->insn_aux_data[i].call_imm = insn->imm; 12358 /* subprog is encoded in insn[1].imm */ 12359 continue; 12360 } 12361 12362 if (!bpf_pseudo_call(insn)) 12363 continue; 12364 /* Upon error here we cannot fall back to interpreter but 12365 * need a hard reject of the program. Thus -EFAULT is 12366 * propagated in any case. 12367 */ 12368 subprog = find_subprog(env, i + insn->imm + 1); 12369 if (subprog < 0) { 12370 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 12371 i + insn->imm + 1); 12372 return -EFAULT; 12373 } 12374 /* temporarily remember subprog id inside insn instead of 12375 * aux_data, since next loop will split up all insns into funcs 12376 */ 12377 insn->off = subprog; 12378 /* remember original imm in case JIT fails and fallback 12379 * to interpreter will be needed 12380 */ 12381 env->insn_aux_data[i].call_imm = insn->imm; 12382 /* point imm to __bpf_call_base+1 from JITs point of view */ 12383 insn->imm = 1; 12384 } 12385 12386 err = bpf_prog_alloc_jited_linfo(prog); 12387 if (err) 12388 goto out_undo_insn; 12389 12390 err = -ENOMEM; 12391 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 12392 if (!func) 12393 goto out_undo_insn; 12394 12395 for (i = 0; i < env->subprog_cnt; i++) { 12396 subprog_start = subprog_end; 12397 subprog_end = env->subprog_info[i + 1].start; 12398 12399 len = subprog_end - subprog_start; 12400 /* BPF_PROG_RUN doesn't call subprogs directly, 12401 * hence main prog stats include the runtime of subprogs. 12402 * subprogs don't have IDs and not reachable via prog_get_next_id 12403 * func[i]->stats will never be accessed and stays NULL 12404 */ 12405 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 12406 if (!func[i]) 12407 goto out_free; 12408 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 12409 len * sizeof(struct bpf_insn)); 12410 func[i]->type = prog->type; 12411 func[i]->len = len; 12412 if (bpf_prog_calc_tag(func[i])) 12413 goto out_free; 12414 func[i]->is_func = 1; 12415 func[i]->aux->func_idx = i; 12416 /* Below members will be freed only at prog->aux */ 12417 func[i]->aux->btf = prog->aux->btf; 12418 func[i]->aux->func_info = prog->aux->func_info; 12419 func[i]->aux->poke_tab = prog->aux->poke_tab; 12420 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 12421 12422 for (j = 0; j < prog->aux->size_poke_tab; j++) { 12423 struct bpf_jit_poke_descriptor *poke; 12424 12425 poke = &prog->aux->poke_tab[j]; 12426 if (poke->insn_idx < subprog_end && 12427 poke->insn_idx >= subprog_start) 12428 poke->aux = func[i]->aux; 12429 } 12430 12431 /* Use bpf_prog_F_tag to indicate functions in stack traces. 12432 * Long term would need debug info to populate names 12433 */ 12434 func[i]->aux->name[0] = 'F'; 12435 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 12436 func[i]->jit_requested = 1; 12437 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 12438 func[i]->aux->linfo = prog->aux->linfo; 12439 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 12440 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 12441 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 12442 num_exentries = 0; 12443 insn = func[i]->insnsi; 12444 for (j = 0; j < func[i]->len; j++, insn++) { 12445 if (BPF_CLASS(insn->code) == BPF_LDX && 12446 BPF_MODE(insn->code) == BPF_PROBE_MEM) 12447 num_exentries++; 12448 } 12449 func[i]->aux->num_exentries = num_exentries; 12450 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 12451 func[i] = bpf_int_jit_compile(func[i]); 12452 if (!func[i]->jited) { 12453 err = -ENOTSUPP; 12454 goto out_free; 12455 } 12456 cond_resched(); 12457 } 12458 12459 /* at this point all bpf functions were successfully JITed 12460 * now populate all bpf_calls with correct addresses and 12461 * run last pass of JIT 12462 */ 12463 for (i = 0; i < env->subprog_cnt; i++) { 12464 insn = func[i]->insnsi; 12465 for (j = 0; j < func[i]->len; j++, insn++) { 12466 if (bpf_pseudo_func(insn)) { 12467 subprog = insn[1].imm; 12468 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 12469 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 12470 continue; 12471 } 12472 if (!bpf_pseudo_call(insn)) 12473 continue; 12474 subprog = insn->off; 12475 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 12476 __bpf_call_base; 12477 } 12478 12479 /* we use the aux data to keep a list of the start addresses 12480 * of the JITed images for each function in the program 12481 * 12482 * for some architectures, such as powerpc64, the imm field 12483 * might not be large enough to hold the offset of the start 12484 * address of the callee's JITed image from __bpf_call_base 12485 * 12486 * in such cases, we can lookup the start address of a callee 12487 * by using its subprog id, available from the off field of 12488 * the call instruction, as an index for this list 12489 */ 12490 func[i]->aux->func = func; 12491 func[i]->aux->func_cnt = env->subprog_cnt; 12492 } 12493 for (i = 0; i < env->subprog_cnt; i++) { 12494 old_bpf_func = func[i]->bpf_func; 12495 tmp = bpf_int_jit_compile(func[i]); 12496 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 12497 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 12498 err = -ENOTSUPP; 12499 goto out_free; 12500 } 12501 cond_resched(); 12502 } 12503 12504 /* finally lock prog and jit images for all functions and 12505 * populate kallsysm 12506 */ 12507 for (i = 0; i < env->subprog_cnt; i++) { 12508 bpf_prog_lock_ro(func[i]); 12509 bpf_prog_kallsyms_add(func[i]); 12510 } 12511 12512 /* Last step: make now unused interpreter insns from main 12513 * prog consistent for later dump requests, so they can 12514 * later look the same as if they were interpreted only. 12515 */ 12516 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12517 if (bpf_pseudo_func(insn)) { 12518 insn[0].imm = env->insn_aux_data[i].call_imm; 12519 insn[1].imm = find_subprog(env, i + insn[0].imm + 1); 12520 continue; 12521 } 12522 if (!bpf_pseudo_call(insn)) 12523 continue; 12524 insn->off = env->insn_aux_data[i].call_imm; 12525 subprog = find_subprog(env, i + insn->off + 1); 12526 insn->imm = subprog; 12527 } 12528 12529 prog->jited = 1; 12530 prog->bpf_func = func[0]->bpf_func; 12531 prog->aux->func = func; 12532 prog->aux->func_cnt = env->subprog_cnt; 12533 bpf_prog_jit_attempt_done(prog); 12534 return 0; 12535 out_free: 12536 /* We failed JIT'ing, so at this point we need to unregister poke 12537 * descriptors from subprogs, so that kernel is not attempting to 12538 * patch it anymore as we're freeing the subprog JIT memory. 12539 */ 12540 for (i = 0; i < prog->aux->size_poke_tab; i++) { 12541 map_ptr = prog->aux->poke_tab[i].tail_call.map; 12542 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 12543 } 12544 /* At this point we're guaranteed that poke descriptors are not 12545 * live anymore. We can just unlink its descriptor table as it's 12546 * released with the main prog. 12547 */ 12548 for (i = 0; i < env->subprog_cnt; i++) { 12549 if (!func[i]) 12550 continue; 12551 func[i]->aux->poke_tab = NULL; 12552 bpf_jit_free(func[i]); 12553 } 12554 kfree(func); 12555 out_undo_insn: 12556 /* cleanup main prog to be interpreted */ 12557 prog->jit_requested = 0; 12558 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12559 if (!bpf_pseudo_call(insn)) 12560 continue; 12561 insn->off = 0; 12562 insn->imm = env->insn_aux_data[i].call_imm; 12563 } 12564 bpf_prog_jit_attempt_done(prog); 12565 return err; 12566 } 12567 12568 static int fixup_call_args(struct bpf_verifier_env *env) 12569 { 12570 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12571 struct bpf_prog *prog = env->prog; 12572 struct bpf_insn *insn = prog->insnsi; 12573 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 12574 int i, depth; 12575 #endif 12576 int err = 0; 12577 12578 if (env->prog->jit_requested && 12579 !bpf_prog_is_dev_bound(env->prog->aux)) { 12580 err = jit_subprogs(env); 12581 if (err == 0) 12582 return 0; 12583 if (err == -EFAULT) 12584 return err; 12585 } 12586 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12587 if (has_kfunc_call) { 12588 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 12589 return -EINVAL; 12590 } 12591 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 12592 /* When JIT fails the progs with bpf2bpf calls and tail_calls 12593 * have to be rejected, since interpreter doesn't support them yet. 12594 */ 12595 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 12596 return -EINVAL; 12597 } 12598 for (i = 0; i < prog->len; i++, insn++) { 12599 if (bpf_pseudo_func(insn)) { 12600 /* When JIT fails the progs with callback calls 12601 * have to be rejected, since interpreter doesn't support them yet. 12602 */ 12603 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 12604 return -EINVAL; 12605 } 12606 12607 if (!bpf_pseudo_call(insn)) 12608 continue; 12609 depth = get_callee_stack_depth(env, insn, i); 12610 if (depth < 0) 12611 return depth; 12612 bpf_patch_call_args(insn, depth); 12613 } 12614 err = 0; 12615 #endif 12616 return err; 12617 } 12618 12619 static int fixup_kfunc_call(struct bpf_verifier_env *env, 12620 struct bpf_insn *insn) 12621 { 12622 const struct bpf_kfunc_desc *desc; 12623 12624 /* insn->imm has the btf func_id. Replace it with 12625 * an address (relative to __bpf_base_call). 12626 */ 12627 desc = find_kfunc_desc(env->prog, insn->imm); 12628 if (!desc) { 12629 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 12630 insn->imm); 12631 return -EFAULT; 12632 } 12633 12634 insn->imm = desc->imm; 12635 12636 return 0; 12637 } 12638 12639 /* Do various post-verification rewrites in a single program pass. 12640 * These rewrites simplify JIT and interpreter implementations. 12641 */ 12642 static int do_misc_fixups(struct bpf_verifier_env *env) 12643 { 12644 struct bpf_prog *prog = env->prog; 12645 bool expect_blinding = bpf_jit_blinding_enabled(prog); 12646 enum bpf_prog_type prog_type = resolve_prog_type(prog); 12647 struct bpf_insn *insn = prog->insnsi; 12648 const struct bpf_func_proto *fn; 12649 const int insn_cnt = prog->len; 12650 const struct bpf_map_ops *ops; 12651 struct bpf_insn_aux_data *aux; 12652 struct bpf_insn insn_buf[16]; 12653 struct bpf_prog *new_prog; 12654 struct bpf_map *map_ptr; 12655 int i, ret, cnt, delta = 0; 12656 12657 for (i = 0; i < insn_cnt; i++, insn++) { 12658 /* Make divide-by-zero exceptions impossible. */ 12659 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 12660 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 12661 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 12662 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 12663 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 12664 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 12665 struct bpf_insn *patchlet; 12666 struct bpf_insn chk_and_div[] = { 12667 /* [R,W]x div 0 -> 0 */ 12668 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 12669 BPF_JNE | BPF_K, insn->src_reg, 12670 0, 2, 0), 12671 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 12672 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 12673 *insn, 12674 }; 12675 struct bpf_insn chk_and_mod[] = { 12676 /* [R,W]x mod 0 -> [R,W]x */ 12677 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 12678 BPF_JEQ | BPF_K, insn->src_reg, 12679 0, 1 + (is64 ? 0 : 1), 0), 12680 *insn, 12681 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 12682 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 12683 }; 12684 12685 patchlet = isdiv ? chk_and_div : chk_and_mod; 12686 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 12687 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 12688 12689 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 12690 if (!new_prog) 12691 return -ENOMEM; 12692 12693 delta += cnt - 1; 12694 env->prog = prog = new_prog; 12695 insn = new_prog->insnsi + i + delta; 12696 continue; 12697 } 12698 12699 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 12700 if (BPF_CLASS(insn->code) == BPF_LD && 12701 (BPF_MODE(insn->code) == BPF_ABS || 12702 BPF_MODE(insn->code) == BPF_IND)) { 12703 cnt = env->ops->gen_ld_abs(insn, insn_buf); 12704 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 12705 verbose(env, "bpf verifier is misconfigured\n"); 12706 return -EINVAL; 12707 } 12708 12709 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12710 if (!new_prog) 12711 return -ENOMEM; 12712 12713 delta += cnt - 1; 12714 env->prog = prog = new_prog; 12715 insn = new_prog->insnsi + i + delta; 12716 continue; 12717 } 12718 12719 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 12720 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 12721 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 12722 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 12723 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 12724 struct bpf_insn *patch = &insn_buf[0]; 12725 bool issrc, isneg, isimm; 12726 u32 off_reg; 12727 12728 aux = &env->insn_aux_data[i + delta]; 12729 if (!aux->alu_state || 12730 aux->alu_state == BPF_ALU_NON_POINTER) 12731 continue; 12732 12733 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 12734 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 12735 BPF_ALU_SANITIZE_SRC; 12736 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 12737 12738 off_reg = issrc ? insn->src_reg : insn->dst_reg; 12739 if (isimm) { 12740 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 12741 } else { 12742 if (isneg) 12743 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 12744 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 12745 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 12746 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 12747 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 12748 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 12749 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 12750 } 12751 if (!issrc) 12752 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 12753 insn->src_reg = BPF_REG_AX; 12754 if (isneg) 12755 insn->code = insn->code == code_add ? 12756 code_sub : code_add; 12757 *patch++ = *insn; 12758 if (issrc && isneg && !isimm) 12759 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 12760 cnt = patch - insn_buf; 12761 12762 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12763 if (!new_prog) 12764 return -ENOMEM; 12765 12766 delta += cnt - 1; 12767 env->prog = prog = new_prog; 12768 insn = new_prog->insnsi + i + delta; 12769 continue; 12770 } 12771 12772 if (insn->code != (BPF_JMP | BPF_CALL)) 12773 continue; 12774 if (insn->src_reg == BPF_PSEUDO_CALL) 12775 continue; 12776 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 12777 ret = fixup_kfunc_call(env, insn); 12778 if (ret) 12779 return ret; 12780 continue; 12781 } 12782 12783 if (insn->imm == BPF_FUNC_get_route_realm) 12784 prog->dst_needed = 1; 12785 if (insn->imm == BPF_FUNC_get_prandom_u32) 12786 bpf_user_rnd_init_once(); 12787 if (insn->imm == BPF_FUNC_override_return) 12788 prog->kprobe_override = 1; 12789 if (insn->imm == BPF_FUNC_tail_call) { 12790 /* If we tail call into other programs, we 12791 * cannot make any assumptions since they can 12792 * be replaced dynamically during runtime in 12793 * the program array. 12794 */ 12795 prog->cb_access = 1; 12796 if (!allow_tail_call_in_subprogs(env)) 12797 prog->aux->stack_depth = MAX_BPF_STACK; 12798 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 12799 12800 /* mark bpf_tail_call as different opcode to avoid 12801 * conditional branch in the interpreter for every normal 12802 * call and to prevent accidental JITing by JIT compiler 12803 * that doesn't support bpf_tail_call yet 12804 */ 12805 insn->imm = 0; 12806 insn->code = BPF_JMP | BPF_TAIL_CALL; 12807 12808 aux = &env->insn_aux_data[i + delta]; 12809 if (env->bpf_capable && !expect_blinding && 12810 prog->jit_requested && 12811 !bpf_map_key_poisoned(aux) && 12812 !bpf_map_ptr_poisoned(aux) && 12813 !bpf_map_ptr_unpriv(aux)) { 12814 struct bpf_jit_poke_descriptor desc = { 12815 .reason = BPF_POKE_REASON_TAIL_CALL, 12816 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 12817 .tail_call.key = bpf_map_key_immediate(aux), 12818 .insn_idx = i + delta, 12819 }; 12820 12821 ret = bpf_jit_add_poke_descriptor(prog, &desc); 12822 if (ret < 0) { 12823 verbose(env, "adding tail call poke descriptor failed\n"); 12824 return ret; 12825 } 12826 12827 insn->imm = ret + 1; 12828 continue; 12829 } 12830 12831 if (!bpf_map_ptr_unpriv(aux)) 12832 continue; 12833 12834 /* instead of changing every JIT dealing with tail_call 12835 * emit two extra insns: 12836 * if (index >= max_entries) goto out; 12837 * index &= array->index_mask; 12838 * to avoid out-of-bounds cpu speculation 12839 */ 12840 if (bpf_map_ptr_poisoned(aux)) { 12841 verbose(env, "tail_call abusing map_ptr\n"); 12842 return -EINVAL; 12843 } 12844 12845 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 12846 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 12847 map_ptr->max_entries, 2); 12848 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 12849 container_of(map_ptr, 12850 struct bpf_array, 12851 map)->index_mask); 12852 insn_buf[2] = *insn; 12853 cnt = 3; 12854 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12855 if (!new_prog) 12856 return -ENOMEM; 12857 12858 delta += cnt - 1; 12859 env->prog = prog = new_prog; 12860 insn = new_prog->insnsi + i + delta; 12861 continue; 12862 } 12863 12864 if (insn->imm == BPF_FUNC_timer_set_callback) { 12865 /* The verifier will process callback_fn as many times as necessary 12866 * with different maps and the register states prepared by 12867 * set_timer_callback_state will be accurate. 12868 * 12869 * The following use case is valid: 12870 * map1 is shared by prog1, prog2, prog3. 12871 * prog1 calls bpf_timer_init for some map1 elements 12872 * prog2 calls bpf_timer_set_callback for some map1 elements. 12873 * Those that were not bpf_timer_init-ed will return -EINVAL. 12874 * prog3 calls bpf_timer_start for some map1 elements. 12875 * Those that were not both bpf_timer_init-ed and 12876 * bpf_timer_set_callback-ed will return -EINVAL. 12877 */ 12878 struct bpf_insn ld_addrs[2] = { 12879 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 12880 }; 12881 12882 insn_buf[0] = ld_addrs[0]; 12883 insn_buf[1] = ld_addrs[1]; 12884 insn_buf[2] = *insn; 12885 cnt = 3; 12886 12887 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12888 if (!new_prog) 12889 return -ENOMEM; 12890 12891 delta += cnt - 1; 12892 env->prog = prog = new_prog; 12893 insn = new_prog->insnsi + i + delta; 12894 goto patch_call_imm; 12895 } 12896 12897 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 12898 * and other inlining handlers are currently limited to 64 bit 12899 * only. 12900 */ 12901 if (prog->jit_requested && BITS_PER_LONG == 64 && 12902 (insn->imm == BPF_FUNC_map_lookup_elem || 12903 insn->imm == BPF_FUNC_map_update_elem || 12904 insn->imm == BPF_FUNC_map_delete_elem || 12905 insn->imm == BPF_FUNC_map_push_elem || 12906 insn->imm == BPF_FUNC_map_pop_elem || 12907 insn->imm == BPF_FUNC_map_peek_elem || 12908 insn->imm == BPF_FUNC_redirect_map)) { 12909 aux = &env->insn_aux_data[i + delta]; 12910 if (bpf_map_ptr_poisoned(aux)) 12911 goto patch_call_imm; 12912 12913 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 12914 ops = map_ptr->ops; 12915 if (insn->imm == BPF_FUNC_map_lookup_elem && 12916 ops->map_gen_lookup) { 12917 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 12918 if (cnt == -EOPNOTSUPP) 12919 goto patch_map_ops_generic; 12920 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 12921 verbose(env, "bpf verifier is misconfigured\n"); 12922 return -EINVAL; 12923 } 12924 12925 new_prog = bpf_patch_insn_data(env, i + delta, 12926 insn_buf, cnt); 12927 if (!new_prog) 12928 return -ENOMEM; 12929 12930 delta += cnt - 1; 12931 env->prog = prog = new_prog; 12932 insn = new_prog->insnsi + i + delta; 12933 continue; 12934 } 12935 12936 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 12937 (void *(*)(struct bpf_map *map, void *key))NULL)); 12938 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 12939 (int (*)(struct bpf_map *map, void *key))NULL)); 12940 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 12941 (int (*)(struct bpf_map *map, void *key, void *value, 12942 u64 flags))NULL)); 12943 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 12944 (int (*)(struct bpf_map *map, void *value, 12945 u64 flags))NULL)); 12946 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 12947 (int (*)(struct bpf_map *map, void *value))NULL)); 12948 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 12949 (int (*)(struct bpf_map *map, void *value))NULL)); 12950 BUILD_BUG_ON(!__same_type(ops->map_redirect, 12951 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL)); 12952 12953 patch_map_ops_generic: 12954 switch (insn->imm) { 12955 case BPF_FUNC_map_lookup_elem: 12956 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 12957 __bpf_call_base; 12958 continue; 12959 case BPF_FUNC_map_update_elem: 12960 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 12961 __bpf_call_base; 12962 continue; 12963 case BPF_FUNC_map_delete_elem: 12964 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 12965 __bpf_call_base; 12966 continue; 12967 case BPF_FUNC_map_push_elem: 12968 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 12969 __bpf_call_base; 12970 continue; 12971 case BPF_FUNC_map_pop_elem: 12972 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 12973 __bpf_call_base; 12974 continue; 12975 case BPF_FUNC_map_peek_elem: 12976 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 12977 __bpf_call_base; 12978 continue; 12979 case BPF_FUNC_redirect_map: 12980 insn->imm = BPF_CAST_CALL(ops->map_redirect) - 12981 __bpf_call_base; 12982 continue; 12983 } 12984 12985 goto patch_call_imm; 12986 } 12987 12988 /* Implement bpf_jiffies64 inline. */ 12989 if (prog->jit_requested && BITS_PER_LONG == 64 && 12990 insn->imm == BPF_FUNC_jiffies64) { 12991 struct bpf_insn ld_jiffies_addr[2] = { 12992 BPF_LD_IMM64(BPF_REG_0, 12993 (unsigned long)&jiffies), 12994 }; 12995 12996 insn_buf[0] = ld_jiffies_addr[0]; 12997 insn_buf[1] = ld_jiffies_addr[1]; 12998 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 12999 BPF_REG_0, 0); 13000 cnt = 3; 13001 13002 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 13003 cnt); 13004 if (!new_prog) 13005 return -ENOMEM; 13006 13007 delta += cnt - 1; 13008 env->prog = prog = new_prog; 13009 insn = new_prog->insnsi + i + delta; 13010 continue; 13011 } 13012 13013 /* Implement bpf_get_func_ip inline. */ 13014 if (prog_type == BPF_PROG_TYPE_TRACING && 13015 insn->imm == BPF_FUNC_get_func_ip) { 13016 /* Load IP address from ctx - 8 */ 13017 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 13018 13019 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 13020 if (!new_prog) 13021 return -ENOMEM; 13022 13023 env->prog = prog = new_prog; 13024 insn = new_prog->insnsi + i + delta; 13025 continue; 13026 } 13027 13028 patch_call_imm: 13029 fn = env->ops->get_func_proto(insn->imm, env->prog); 13030 /* all functions that have prototype and verifier allowed 13031 * programs to call them, must be real in-kernel functions 13032 */ 13033 if (!fn->func) { 13034 verbose(env, 13035 "kernel subsystem misconfigured func %s#%d\n", 13036 func_id_name(insn->imm), insn->imm); 13037 return -EFAULT; 13038 } 13039 insn->imm = fn->func - __bpf_call_base; 13040 } 13041 13042 /* Since poke tab is now finalized, publish aux to tracker. */ 13043 for (i = 0; i < prog->aux->size_poke_tab; i++) { 13044 map_ptr = prog->aux->poke_tab[i].tail_call.map; 13045 if (!map_ptr->ops->map_poke_track || 13046 !map_ptr->ops->map_poke_untrack || 13047 !map_ptr->ops->map_poke_run) { 13048 verbose(env, "bpf verifier is misconfigured\n"); 13049 return -EINVAL; 13050 } 13051 13052 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 13053 if (ret < 0) { 13054 verbose(env, "tracking tail call prog failed\n"); 13055 return ret; 13056 } 13057 } 13058 13059 sort_kfunc_descs_by_imm(env->prog); 13060 13061 return 0; 13062 } 13063 13064 static void free_states(struct bpf_verifier_env *env) 13065 { 13066 struct bpf_verifier_state_list *sl, *sln; 13067 int i; 13068 13069 sl = env->free_list; 13070 while (sl) { 13071 sln = sl->next; 13072 free_verifier_state(&sl->state, false); 13073 kfree(sl); 13074 sl = sln; 13075 } 13076 env->free_list = NULL; 13077 13078 if (!env->explored_states) 13079 return; 13080 13081 for (i = 0; i < state_htab_size(env); i++) { 13082 sl = env->explored_states[i]; 13083 13084 while (sl) { 13085 sln = sl->next; 13086 free_verifier_state(&sl->state, false); 13087 kfree(sl); 13088 sl = sln; 13089 } 13090 env->explored_states[i] = NULL; 13091 } 13092 } 13093 13094 /* The verifier is using insn_aux_data[] to store temporary data during 13095 * verification and to store information for passes that run after the 13096 * verification like dead code sanitization. do_check_common() for subprogram N 13097 * may analyze many other subprograms. sanitize_insn_aux_data() clears all 13098 * temporary data after do_check_common() finds that subprogram N cannot be 13099 * verified independently. pass_cnt counts the number of times 13100 * do_check_common() was run and insn->aux->seen tells the pass number 13101 * insn_aux_data was touched. These variables are compared to clear temporary 13102 * data from failed pass. For testing and experiments do_check_common() can be 13103 * run multiple times even when prior attempt to verify is unsuccessful. 13104 * 13105 * Note that special handling is needed on !env->bypass_spec_v1 if this is 13106 * ever called outside of error path with subsequent program rejection. 13107 */ 13108 static void sanitize_insn_aux_data(struct bpf_verifier_env *env) 13109 { 13110 struct bpf_insn *insn = env->prog->insnsi; 13111 struct bpf_insn_aux_data *aux; 13112 int i, class; 13113 13114 for (i = 0; i < env->prog->len; i++) { 13115 class = BPF_CLASS(insn[i].code); 13116 if (class != BPF_LDX && class != BPF_STX) 13117 continue; 13118 aux = &env->insn_aux_data[i]; 13119 if (aux->seen != env->pass_cnt) 13120 continue; 13121 memset(aux, 0, offsetof(typeof(*aux), orig_idx)); 13122 } 13123 } 13124 13125 static int do_check_common(struct bpf_verifier_env *env, int subprog) 13126 { 13127 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 13128 struct bpf_verifier_state *state; 13129 struct bpf_reg_state *regs; 13130 int ret, i; 13131 13132 env->prev_linfo = NULL; 13133 env->pass_cnt++; 13134 13135 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 13136 if (!state) 13137 return -ENOMEM; 13138 state->curframe = 0; 13139 state->speculative = false; 13140 state->branches = 1; 13141 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 13142 if (!state->frame[0]) { 13143 kfree(state); 13144 return -ENOMEM; 13145 } 13146 env->cur_state = state; 13147 init_func_state(env, state->frame[0], 13148 BPF_MAIN_FUNC /* callsite */, 13149 0 /* frameno */, 13150 subprog); 13151 13152 regs = state->frame[state->curframe]->regs; 13153 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 13154 ret = btf_prepare_func_args(env, subprog, regs); 13155 if (ret) 13156 goto out; 13157 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 13158 if (regs[i].type == PTR_TO_CTX) 13159 mark_reg_known_zero(env, regs, i); 13160 else if (regs[i].type == SCALAR_VALUE) 13161 mark_reg_unknown(env, regs, i); 13162 else if (regs[i].type == PTR_TO_MEM_OR_NULL) { 13163 const u32 mem_size = regs[i].mem_size; 13164 13165 mark_reg_known_zero(env, regs, i); 13166 regs[i].mem_size = mem_size; 13167 regs[i].id = ++env->id_gen; 13168 } 13169 } 13170 } else { 13171 /* 1st arg to a function */ 13172 regs[BPF_REG_1].type = PTR_TO_CTX; 13173 mark_reg_known_zero(env, regs, BPF_REG_1); 13174 ret = btf_check_subprog_arg_match(env, subprog, regs); 13175 if (ret == -EFAULT) 13176 /* unlikely verifier bug. abort. 13177 * ret == 0 and ret < 0 are sadly acceptable for 13178 * main() function due to backward compatibility. 13179 * Like socket filter program may be written as: 13180 * int bpf_prog(struct pt_regs *ctx) 13181 * and never dereference that ctx in the program. 13182 * 'struct pt_regs' is a type mismatch for socket 13183 * filter that should be using 'struct __sk_buff'. 13184 */ 13185 goto out; 13186 } 13187 13188 ret = do_check(env); 13189 out: 13190 /* check for NULL is necessary, since cur_state can be freed inside 13191 * do_check() under memory pressure. 13192 */ 13193 if (env->cur_state) { 13194 free_verifier_state(env->cur_state, true); 13195 env->cur_state = NULL; 13196 } 13197 while (!pop_stack(env, NULL, NULL, false)); 13198 if (!ret && pop_log) 13199 bpf_vlog_reset(&env->log, 0); 13200 free_states(env); 13201 if (ret) 13202 /* clean aux data in case subprog was rejected */ 13203 sanitize_insn_aux_data(env); 13204 return ret; 13205 } 13206 13207 /* Verify all global functions in a BPF program one by one based on their BTF. 13208 * All global functions must pass verification. Otherwise the whole program is rejected. 13209 * Consider: 13210 * int bar(int); 13211 * int foo(int f) 13212 * { 13213 * return bar(f); 13214 * } 13215 * int bar(int b) 13216 * { 13217 * ... 13218 * } 13219 * foo() will be verified first for R1=any_scalar_value. During verification it 13220 * will be assumed that bar() already verified successfully and call to bar() 13221 * from foo() will be checked for type match only. Later bar() will be verified 13222 * independently to check that it's safe for R1=any_scalar_value. 13223 */ 13224 static int do_check_subprogs(struct bpf_verifier_env *env) 13225 { 13226 struct bpf_prog_aux *aux = env->prog->aux; 13227 int i, ret; 13228 13229 if (!aux->func_info) 13230 return 0; 13231 13232 for (i = 1; i < env->subprog_cnt; i++) { 13233 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 13234 continue; 13235 env->insn_idx = env->subprog_info[i].start; 13236 WARN_ON_ONCE(env->insn_idx == 0); 13237 ret = do_check_common(env, i); 13238 if (ret) { 13239 return ret; 13240 } else if (env->log.level & BPF_LOG_LEVEL) { 13241 verbose(env, 13242 "Func#%d is safe for any args that match its prototype\n", 13243 i); 13244 } 13245 } 13246 return 0; 13247 } 13248 13249 static int do_check_main(struct bpf_verifier_env *env) 13250 { 13251 int ret; 13252 13253 env->insn_idx = 0; 13254 ret = do_check_common(env, 0); 13255 if (!ret) 13256 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 13257 return ret; 13258 } 13259 13260 13261 static void print_verification_stats(struct bpf_verifier_env *env) 13262 { 13263 int i; 13264 13265 if (env->log.level & BPF_LOG_STATS) { 13266 verbose(env, "verification time %lld usec\n", 13267 div_u64(env->verification_time, 1000)); 13268 verbose(env, "stack depth "); 13269 for (i = 0; i < env->subprog_cnt; i++) { 13270 u32 depth = env->subprog_info[i].stack_depth; 13271 13272 verbose(env, "%d", depth); 13273 if (i + 1 < env->subprog_cnt) 13274 verbose(env, "+"); 13275 } 13276 verbose(env, "\n"); 13277 } 13278 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 13279 "total_states %d peak_states %d mark_read %d\n", 13280 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 13281 env->max_states_per_insn, env->total_states, 13282 env->peak_states, env->longest_mark_read_walk); 13283 } 13284 13285 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 13286 { 13287 const struct btf_type *t, *func_proto; 13288 const struct bpf_struct_ops *st_ops; 13289 const struct btf_member *member; 13290 struct bpf_prog *prog = env->prog; 13291 u32 btf_id, member_idx; 13292 const char *mname; 13293 13294 if (!prog->gpl_compatible) { 13295 verbose(env, "struct ops programs must have a GPL compatible license\n"); 13296 return -EINVAL; 13297 } 13298 13299 btf_id = prog->aux->attach_btf_id; 13300 st_ops = bpf_struct_ops_find(btf_id); 13301 if (!st_ops) { 13302 verbose(env, "attach_btf_id %u is not a supported struct\n", 13303 btf_id); 13304 return -ENOTSUPP; 13305 } 13306 13307 t = st_ops->type; 13308 member_idx = prog->expected_attach_type; 13309 if (member_idx >= btf_type_vlen(t)) { 13310 verbose(env, "attach to invalid member idx %u of struct %s\n", 13311 member_idx, st_ops->name); 13312 return -EINVAL; 13313 } 13314 13315 member = &btf_type_member(t)[member_idx]; 13316 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 13317 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 13318 NULL); 13319 if (!func_proto) { 13320 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 13321 mname, member_idx, st_ops->name); 13322 return -EINVAL; 13323 } 13324 13325 if (st_ops->check_member) { 13326 int err = st_ops->check_member(t, member); 13327 13328 if (err) { 13329 verbose(env, "attach to unsupported member %s of struct %s\n", 13330 mname, st_ops->name); 13331 return err; 13332 } 13333 } 13334 13335 prog->aux->attach_func_proto = func_proto; 13336 prog->aux->attach_func_name = mname; 13337 env->ops = st_ops->verifier_ops; 13338 13339 return 0; 13340 } 13341 #define SECURITY_PREFIX "security_" 13342 13343 static int check_attach_modify_return(unsigned long addr, const char *func_name) 13344 { 13345 if (within_error_injection_list(addr) || 13346 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 13347 return 0; 13348 13349 return -EINVAL; 13350 } 13351 13352 /* list of non-sleepable functions that are otherwise on 13353 * ALLOW_ERROR_INJECTION list 13354 */ 13355 BTF_SET_START(btf_non_sleepable_error_inject) 13356 /* Three functions below can be called from sleepable and non-sleepable context. 13357 * Assume non-sleepable from bpf safety point of view. 13358 */ 13359 BTF_ID(func, __add_to_page_cache_locked) 13360 BTF_ID(func, should_fail_alloc_page) 13361 BTF_ID(func, should_failslab) 13362 BTF_SET_END(btf_non_sleepable_error_inject) 13363 13364 static int check_non_sleepable_error_inject(u32 btf_id) 13365 { 13366 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 13367 } 13368 13369 int bpf_check_attach_target(struct bpf_verifier_log *log, 13370 const struct bpf_prog *prog, 13371 const struct bpf_prog *tgt_prog, 13372 u32 btf_id, 13373 struct bpf_attach_target_info *tgt_info) 13374 { 13375 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 13376 const char prefix[] = "btf_trace_"; 13377 int ret = 0, subprog = -1, i; 13378 const struct btf_type *t; 13379 bool conservative = true; 13380 const char *tname; 13381 struct btf *btf; 13382 long addr = 0; 13383 13384 if (!btf_id) { 13385 bpf_log(log, "Tracing programs must provide btf_id\n"); 13386 return -EINVAL; 13387 } 13388 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 13389 if (!btf) { 13390 bpf_log(log, 13391 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 13392 return -EINVAL; 13393 } 13394 t = btf_type_by_id(btf, btf_id); 13395 if (!t) { 13396 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 13397 return -EINVAL; 13398 } 13399 tname = btf_name_by_offset(btf, t->name_off); 13400 if (!tname) { 13401 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 13402 return -EINVAL; 13403 } 13404 if (tgt_prog) { 13405 struct bpf_prog_aux *aux = tgt_prog->aux; 13406 13407 for (i = 0; i < aux->func_info_cnt; i++) 13408 if (aux->func_info[i].type_id == btf_id) { 13409 subprog = i; 13410 break; 13411 } 13412 if (subprog == -1) { 13413 bpf_log(log, "Subprog %s doesn't exist\n", tname); 13414 return -EINVAL; 13415 } 13416 conservative = aux->func_info_aux[subprog].unreliable; 13417 if (prog_extension) { 13418 if (conservative) { 13419 bpf_log(log, 13420 "Cannot replace static functions\n"); 13421 return -EINVAL; 13422 } 13423 if (!prog->jit_requested) { 13424 bpf_log(log, 13425 "Extension programs should be JITed\n"); 13426 return -EINVAL; 13427 } 13428 } 13429 if (!tgt_prog->jited) { 13430 bpf_log(log, "Can attach to only JITed progs\n"); 13431 return -EINVAL; 13432 } 13433 if (tgt_prog->type == prog->type) { 13434 /* Cannot fentry/fexit another fentry/fexit program. 13435 * Cannot attach program extension to another extension. 13436 * It's ok to attach fentry/fexit to extension program. 13437 */ 13438 bpf_log(log, "Cannot recursively attach\n"); 13439 return -EINVAL; 13440 } 13441 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 13442 prog_extension && 13443 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 13444 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 13445 /* Program extensions can extend all program types 13446 * except fentry/fexit. The reason is the following. 13447 * The fentry/fexit programs are used for performance 13448 * analysis, stats and can be attached to any program 13449 * type except themselves. When extension program is 13450 * replacing XDP function it is necessary to allow 13451 * performance analysis of all functions. Both original 13452 * XDP program and its program extension. Hence 13453 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 13454 * allowed. If extending of fentry/fexit was allowed it 13455 * would be possible to create long call chain 13456 * fentry->extension->fentry->extension beyond 13457 * reasonable stack size. Hence extending fentry is not 13458 * allowed. 13459 */ 13460 bpf_log(log, "Cannot extend fentry/fexit\n"); 13461 return -EINVAL; 13462 } 13463 } else { 13464 if (prog_extension) { 13465 bpf_log(log, "Cannot replace kernel functions\n"); 13466 return -EINVAL; 13467 } 13468 } 13469 13470 switch (prog->expected_attach_type) { 13471 case BPF_TRACE_RAW_TP: 13472 if (tgt_prog) { 13473 bpf_log(log, 13474 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 13475 return -EINVAL; 13476 } 13477 if (!btf_type_is_typedef(t)) { 13478 bpf_log(log, "attach_btf_id %u is not a typedef\n", 13479 btf_id); 13480 return -EINVAL; 13481 } 13482 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 13483 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 13484 btf_id, tname); 13485 return -EINVAL; 13486 } 13487 tname += sizeof(prefix) - 1; 13488 t = btf_type_by_id(btf, t->type); 13489 if (!btf_type_is_ptr(t)) 13490 /* should never happen in valid vmlinux build */ 13491 return -EINVAL; 13492 t = btf_type_by_id(btf, t->type); 13493 if (!btf_type_is_func_proto(t)) 13494 /* should never happen in valid vmlinux build */ 13495 return -EINVAL; 13496 13497 break; 13498 case BPF_TRACE_ITER: 13499 if (!btf_type_is_func(t)) { 13500 bpf_log(log, "attach_btf_id %u is not a function\n", 13501 btf_id); 13502 return -EINVAL; 13503 } 13504 t = btf_type_by_id(btf, t->type); 13505 if (!btf_type_is_func_proto(t)) 13506 return -EINVAL; 13507 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13508 if (ret) 13509 return ret; 13510 break; 13511 default: 13512 if (!prog_extension) 13513 return -EINVAL; 13514 fallthrough; 13515 case BPF_MODIFY_RETURN: 13516 case BPF_LSM_MAC: 13517 case BPF_TRACE_FENTRY: 13518 case BPF_TRACE_FEXIT: 13519 if (!btf_type_is_func(t)) { 13520 bpf_log(log, "attach_btf_id %u is not a function\n", 13521 btf_id); 13522 return -EINVAL; 13523 } 13524 if (prog_extension && 13525 btf_check_type_match(log, prog, btf, t)) 13526 return -EINVAL; 13527 t = btf_type_by_id(btf, t->type); 13528 if (!btf_type_is_func_proto(t)) 13529 return -EINVAL; 13530 13531 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 13532 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 13533 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 13534 return -EINVAL; 13535 13536 if (tgt_prog && conservative) 13537 t = NULL; 13538 13539 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13540 if (ret < 0) 13541 return ret; 13542 13543 if (tgt_prog) { 13544 if (subprog == 0) 13545 addr = (long) tgt_prog->bpf_func; 13546 else 13547 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 13548 } else { 13549 addr = kallsyms_lookup_name(tname); 13550 if (!addr) { 13551 bpf_log(log, 13552 "The address of function %s cannot be found\n", 13553 tname); 13554 return -ENOENT; 13555 } 13556 } 13557 13558 if (prog->aux->sleepable) { 13559 ret = -EINVAL; 13560 switch (prog->type) { 13561 case BPF_PROG_TYPE_TRACING: 13562 /* fentry/fexit/fmod_ret progs can be sleepable only if they are 13563 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 13564 */ 13565 if (!check_non_sleepable_error_inject(btf_id) && 13566 within_error_injection_list(addr)) 13567 ret = 0; 13568 break; 13569 case BPF_PROG_TYPE_LSM: 13570 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 13571 * Only some of them are sleepable. 13572 */ 13573 if (bpf_lsm_is_sleepable_hook(btf_id)) 13574 ret = 0; 13575 break; 13576 default: 13577 break; 13578 } 13579 if (ret) { 13580 bpf_log(log, "%s is not sleepable\n", tname); 13581 return ret; 13582 } 13583 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 13584 if (tgt_prog) { 13585 bpf_log(log, "can't modify return codes of BPF programs\n"); 13586 return -EINVAL; 13587 } 13588 ret = check_attach_modify_return(addr, tname); 13589 if (ret) { 13590 bpf_log(log, "%s() is not modifiable\n", tname); 13591 return ret; 13592 } 13593 } 13594 13595 break; 13596 } 13597 tgt_info->tgt_addr = addr; 13598 tgt_info->tgt_name = tname; 13599 tgt_info->tgt_type = t; 13600 return 0; 13601 } 13602 13603 BTF_SET_START(btf_id_deny) 13604 BTF_ID_UNUSED 13605 #ifdef CONFIG_SMP 13606 BTF_ID(func, migrate_disable) 13607 BTF_ID(func, migrate_enable) 13608 #endif 13609 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 13610 BTF_ID(func, rcu_read_unlock_strict) 13611 #endif 13612 BTF_SET_END(btf_id_deny) 13613 13614 static int check_attach_btf_id(struct bpf_verifier_env *env) 13615 { 13616 struct bpf_prog *prog = env->prog; 13617 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 13618 struct bpf_attach_target_info tgt_info = {}; 13619 u32 btf_id = prog->aux->attach_btf_id; 13620 struct bpf_trampoline *tr; 13621 int ret; 13622 u64 key; 13623 13624 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 13625 if (prog->aux->sleepable) 13626 /* attach_btf_id checked to be zero already */ 13627 return 0; 13628 verbose(env, "Syscall programs can only be sleepable\n"); 13629 return -EINVAL; 13630 } 13631 13632 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 13633 prog->type != BPF_PROG_TYPE_LSM) { 13634 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n"); 13635 return -EINVAL; 13636 } 13637 13638 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 13639 return check_struct_ops_btf_id(env); 13640 13641 if (prog->type != BPF_PROG_TYPE_TRACING && 13642 prog->type != BPF_PROG_TYPE_LSM && 13643 prog->type != BPF_PROG_TYPE_EXT) 13644 return 0; 13645 13646 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 13647 if (ret) 13648 return ret; 13649 13650 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 13651 /* to make freplace equivalent to their targets, they need to 13652 * inherit env->ops and expected_attach_type for the rest of the 13653 * verification 13654 */ 13655 env->ops = bpf_verifier_ops[tgt_prog->type]; 13656 prog->expected_attach_type = tgt_prog->expected_attach_type; 13657 } 13658 13659 /* store info about the attachment target that will be used later */ 13660 prog->aux->attach_func_proto = tgt_info.tgt_type; 13661 prog->aux->attach_func_name = tgt_info.tgt_name; 13662 13663 if (tgt_prog) { 13664 prog->aux->saved_dst_prog_type = tgt_prog->type; 13665 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 13666 } 13667 13668 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 13669 prog->aux->attach_btf_trace = true; 13670 return 0; 13671 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 13672 if (!bpf_iter_prog_supported(prog)) 13673 return -EINVAL; 13674 return 0; 13675 } 13676 13677 if (prog->type == BPF_PROG_TYPE_LSM) { 13678 ret = bpf_lsm_verify_prog(&env->log, prog); 13679 if (ret < 0) 13680 return ret; 13681 } else if (prog->type == BPF_PROG_TYPE_TRACING && 13682 btf_id_set_contains(&btf_id_deny, btf_id)) { 13683 return -EINVAL; 13684 } 13685 13686 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 13687 tr = bpf_trampoline_get(key, &tgt_info); 13688 if (!tr) 13689 return -ENOMEM; 13690 13691 prog->aux->dst_trampoline = tr; 13692 return 0; 13693 } 13694 13695 struct btf *bpf_get_btf_vmlinux(void) 13696 { 13697 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 13698 mutex_lock(&bpf_verifier_lock); 13699 if (!btf_vmlinux) 13700 btf_vmlinux = btf_parse_vmlinux(); 13701 mutex_unlock(&bpf_verifier_lock); 13702 } 13703 return btf_vmlinux; 13704 } 13705 13706 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 13707 { 13708 u64 start_time = ktime_get_ns(); 13709 struct bpf_verifier_env *env; 13710 struct bpf_verifier_log *log; 13711 int i, len, ret = -EINVAL; 13712 bool is_priv; 13713 13714 /* no program is valid */ 13715 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 13716 return -EINVAL; 13717 13718 /* 'struct bpf_verifier_env' can be global, but since it's not small, 13719 * allocate/free it every time bpf_check() is called 13720 */ 13721 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 13722 if (!env) 13723 return -ENOMEM; 13724 log = &env->log; 13725 13726 len = (*prog)->len; 13727 env->insn_aux_data = 13728 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 13729 ret = -ENOMEM; 13730 if (!env->insn_aux_data) 13731 goto err_free_env; 13732 for (i = 0; i < len; i++) 13733 env->insn_aux_data[i].orig_idx = i; 13734 env->prog = *prog; 13735 env->ops = bpf_verifier_ops[env->prog->type]; 13736 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 13737 is_priv = bpf_capable(); 13738 13739 bpf_get_btf_vmlinux(); 13740 13741 /* grab the mutex to protect few globals used by verifier */ 13742 if (!is_priv) 13743 mutex_lock(&bpf_verifier_lock); 13744 13745 if (attr->log_level || attr->log_buf || attr->log_size) { 13746 /* user requested verbose verifier output 13747 * and supplied buffer to store the verification trace 13748 */ 13749 log->level = attr->log_level; 13750 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 13751 log->len_total = attr->log_size; 13752 13753 ret = -EINVAL; 13754 /* log attributes have to be sane */ 13755 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 13756 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 13757 goto err_unlock; 13758 } 13759 13760 if (IS_ERR(btf_vmlinux)) { 13761 /* Either gcc or pahole or kernel are broken. */ 13762 verbose(env, "in-kernel BTF is malformed\n"); 13763 ret = PTR_ERR(btf_vmlinux); 13764 goto skip_full_check; 13765 } 13766 13767 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 13768 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 13769 env->strict_alignment = true; 13770 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 13771 env->strict_alignment = false; 13772 13773 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 13774 env->allow_uninit_stack = bpf_allow_uninit_stack(); 13775 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access(); 13776 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 13777 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 13778 env->bpf_capable = bpf_capable(); 13779 13780 if (is_priv) 13781 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 13782 13783 env->explored_states = kvcalloc(state_htab_size(env), 13784 sizeof(struct bpf_verifier_state_list *), 13785 GFP_USER); 13786 ret = -ENOMEM; 13787 if (!env->explored_states) 13788 goto skip_full_check; 13789 13790 ret = add_subprog_and_kfunc(env); 13791 if (ret < 0) 13792 goto skip_full_check; 13793 13794 ret = check_subprogs(env); 13795 if (ret < 0) 13796 goto skip_full_check; 13797 13798 ret = check_btf_info(env, attr, uattr); 13799 if (ret < 0) 13800 goto skip_full_check; 13801 13802 ret = check_attach_btf_id(env); 13803 if (ret) 13804 goto skip_full_check; 13805 13806 ret = resolve_pseudo_ldimm64(env); 13807 if (ret < 0) 13808 goto skip_full_check; 13809 13810 if (bpf_prog_is_dev_bound(env->prog->aux)) { 13811 ret = bpf_prog_offload_verifier_prep(env->prog); 13812 if (ret) 13813 goto skip_full_check; 13814 } 13815 13816 ret = check_cfg(env); 13817 if (ret < 0) 13818 goto skip_full_check; 13819 13820 ret = do_check_subprogs(env); 13821 ret = ret ?: do_check_main(env); 13822 13823 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 13824 ret = bpf_prog_offload_finalize(env); 13825 13826 skip_full_check: 13827 kvfree(env->explored_states); 13828 13829 if (ret == 0) 13830 ret = check_max_stack_depth(env); 13831 13832 /* instruction rewrites happen after this point */ 13833 if (is_priv) { 13834 if (ret == 0) 13835 opt_hard_wire_dead_code_branches(env); 13836 if (ret == 0) 13837 ret = opt_remove_dead_code(env); 13838 if (ret == 0) 13839 ret = opt_remove_nops(env); 13840 } else { 13841 if (ret == 0) 13842 sanitize_dead_code(env); 13843 } 13844 13845 if (ret == 0) 13846 /* program is valid, convert *(u32*)(ctx + off) accesses */ 13847 ret = convert_ctx_accesses(env); 13848 13849 if (ret == 0) 13850 ret = do_misc_fixups(env); 13851 13852 /* do 32-bit optimization after insn patching has done so those patched 13853 * insns could be handled correctly. 13854 */ 13855 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 13856 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 13857 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 13858 : false; 13859 } 13860 13861 if (ret == 0) 13862 ret = fixup_call_args(env); 13863 13864 env->verification_time = ktime_get_ns() - start_time; 13865 print_verification_stats(env); 13866 13867 if (log->level && bpf_verifier_log_full(log)) 13868 ret = -ENOSPC; 13869 if (log->level && !log->ubuf) { 13870 ret = -EFAULT; 13871 goto err_release_maps; 13872 } 13873 13874 if (ret) 13875 goto err_release_maps; 13876 13877 if (env->used_map_cnt) { 13878 /* if program passed verifier, update used_maps in bpf_prog_info */ 13879 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 13880 sizeof(env->used_maps[0]), 13881 GFP_KERNEL); 13882 13883 if (!env->prog->aux->used_maps) { 13884 ret = -ENOMEM; 13885 goto err_release_maps; 13886 } 13887 13888 memcpy(env->prog->aux->used_maps, env->used_maps, 13889 sizeof(env->used_maps[0]) * env->used_map_cnt); 13890 env->prog->aux->used_map_cnt = env->used_map_cnt; 13891 } 13892 if (env->used_btf_cnt) { 13893 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 13894 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 13895 sizeof(env->used_btfs[0]), 13896 GFP_KERNEL); 13897 if (!env->prog->aux->used_btfs) { 13898 ret = -ENOMEM; 13899 goto err_release_maps; 13900 } 13901 13902 memcpy(env->prog->aux->used_btfs, env->used_btfs, 13903 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 13904 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 13905 } 13906 if (env->used_map_cnt || env->used_btf_cnt) { 13907 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 13908 * bpf_ld_imm64 instructions 13909 */ 13910 convert_pseudo_ld_imm64(env); 13911 } 13912 13913 adjust_btf_func(env); 13914 13915 err_release_maps: 13916 if (!env->prog->aux->used_maps) 13917 /* if we didn't copy map pointers into bpf_prog_info, release 13918 * them now. Otherwise free_used_maps() will release them. 13919 */ 13920 release_maps(env); 13921 if (!env->prog->aux->used_btfs) 13922 release_btfs(env); 13923 13924 /* extension progs temporarily inherit the attach_type of their targets 13925 for verification purposes, so set it back to zero before returning 13926 */ 13927 if (env->prog->type == BPF_PROG_TYPE_EXT) 13928 env->prog->expected_attach_type = 0; 13929 13930 *prog = env->prog; 13931 err_unlock: 13932 if (!is_priv) 13933 mutex_unlock(&bpf_verifier_lock); 13934 vfree(env->insn_aux_data); 13935 err_free_env: 13936 kfree(env); 13937 return ret; 13938 } 13939