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/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30
31 #include "disasm.h"
32
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35 [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43
44 /* bpf_check() is a static code analyzer that walks eBPF program
45 * instruction by instruction and updates register/stack state.
46 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47 *
48 * The first pass is depth-first-search to check that the program is a DAG.
49 * It rejects the following programs:
50 * - larger than BPF_MAXINSNS insns
51 * - if loop is present (detected via back-edge)
52 * - unreachable insns exist (shouldn't be a forest. program = one function)
53 * - out of bounds or malformed jumps
54 * The second pass is all possible path descent from the 1st insn.
55 * Since it's analyzing all paths through the program, the length of the
56 * analysis is limited to 64k insn, which may be hit even if total number of
57 * insn is less then 4K, but there are too many branches that change stack/regs.
58 * Number of 'branches to be analyzed' is limited to 1k
59 *
60 * On entry to each instruction, each register has a type, and the instruction
61 * changes the types of the registers depending on instruction semantics.
62 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63 * copied to R1.
64 *
65 * All registers are 64-bit.
66 * R0 - return register
67 * R1-R5 argument passing registers
68 * R6-R9 callee saved registers
69 * R10 - frame pointer read-only
70 *
71 * At the start of BPF program the register R1 contains a pointer to bpf_context
72 * and has type PTR_TO_CTX.
73 *
74 * Verifier tracks arithmetic operations on pointers in case:
75 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77 * 1st insn copies R10 (which has FRAME_PTR) type into R1
78 * and 2nd arithmetic instruction is pattern matched to recognize
79 * that it wants to construct a pointer to some element within stack.
80 * So after 2nd insn, the register R1 has type PTR_TO_STACK
81 * (and -20 constant is saved for further stack bounds checking).
82 * Meaning that this reg is a pointer to stack plus known immediate constant.
83 *
84 * Most of the time the registers have SCALAR_VALUE type, which
85 * means the register has some value, but it's not a valid pointer.
86 * (like pointer plus pointer becomes SCALAR_VALUE type)
87 *
88 * When verifier sees load or store instructions the type of base register
89 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90 * four pointer types recognized by check_mem_access() function.
91 *
92 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93 * and the range of [ptr, ptr + map's value_size) is accessible.
94 *
95 * registers used to pass values to function calls are checked against
96 * function argument constraints.
97 *
98 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99 * It means that the register type passed to this function must be
100 * PTR_TO_STACK and it will be used inside the function as
101 * 'pointer to map element key'
102 *
103 * For example the argument constraints for bpf_map_lookup_elem():
104 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105 * .arg1_type = ARG_CONST_MAP_PTR,
106 * .arg2_type = ARG_PTR_TO_MAP_KEY,
107 *
108 * ret_type says that this function returns 'pointer to map elem value or null'
109 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110 * 2nd argument should be a pointer to stack, which will be used inside
111 * the helper function as a pointer to map element key.
112 *
113 * On the kernel side the helper function looks like:
114 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115 * {
116 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117 * void *key = (void *) (unsigned long) r2;
118 * void *value;
119 *
120 * here kernel can access 'key' and 'map' pointers safely, knowing that
121 * [key, key + map->key_size) bytes are valid and were initialized on
122 * the stack of eBPF program.
123 * }
124 *
125 * Corresponding eBPF program may look like:
126 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
127 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
129 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130 * here verifier looks at prototype of map_lookup_elem() and sees:
131 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133 *
134 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136 * and were initialized prior to this call.
137 * If it's ok, then verifier allows this BPF_CALL insn and looks at
138 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140 * returns either pointer to map value or NULL.
141 *
142 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143 * insn, the register holding that pointer in the true branch changes state to
144 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145 * branch. See check_cond_jmp_op().
146 *
147 * After the call R0 is set to return type of the function and registers R1-R5
148 * are set to NOT_INIT to indicate that they are no longer readable.
149 *
150 * The following reference types represent a potential reference to a kernel
151 * resource which, after first being allocated, must be checked and freed by
152 * the BPF program:
153 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154 *
155 * When the verifier sees a helper call return a reference type, it allocates a
156 * pointer id for the reference and stores it in the current function state.
157 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159 * passes through a NULL-check conditional. For the branch wherein the state is
160 * changed to CONST_IMM, the verifier releases the reference.
161 *
162 * For each helper function that allocates a reference, such as
163 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164 * bpf_sk_release(). When a reference type passes into the release function,
165 * the verifier also releases the reference. If any unchecked or unreleased
166 * reference remains at the end of the program, the verifier rejects it.
167 */
168
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171 /* verifer state is 'st'
172 * before processing instruction 'insn_idx'
173 * and after processing instruction 'prev_insn_idx'
174 */
175 struct bpf_verifier_state st;
176 int insn_idx;
177 int prev_insn_idx;
178 struct bpf_verifier_stack_elem *next;
179 /* length of verifier log at the time this state was pushed on stack */
180 u32 log_pos;
181 };
182
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
184 #define BPF_COMPLEXITY_LIMIT_STATES 64
185
186 #define BPF_MAP_KEY_POISON (1ULL << 63)
187 #define BPF_MAP_KEY_SEEN (1ULL << 62)
188
189 #define BPF_MAP_PTR_UNPRIV 1UL
190 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
191 POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199 struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201 u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215 const struct bpf_map *map, bool unpriv)
216 {
217 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218 unpriv |= bpf_map_ptr_unpriv(aux);
219 aux->map_ptr_state = (unsigned long)map |
220 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225 return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240 bool poisoned = bpf_map_key_poisoned(aux);
241
242 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245
bpf_helper_call(const struct bpf_insn * insn)246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248 return insn->code == (BPF_JMP | BPF_CALL) &&
249 insn->src_reg == 0;
250 }
251
bpf_pseudo_call(const struct bpf_insn * insn)252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254 return insn->code == (BPF_JMP | BPF_CALL) &&
255 insn->src_reg == BPF_PSEUDO_CALL;
256 }
257
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260 return insn->code == (BPF_JMP | BPF_CALL) &&
261 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263
264 struct bpf_call_arg_meta {
265 struct bpf_map *map_ptr;
266 bool raw_mode;
267 bool pkt_access;
268 u8 release_regno;
269 int regno;
270 int access_size;
271 int mem_size;
272 u64 msize_max_value;
273 int ref_obj_id;
274 int dynptr_id;
275 int map_uid;
276 int func_id;
277 struct btf *btf;
278 u32 btf_id;
279 struct btf *ret_btf;
280 u32 ret_btf_id;
281 u32 subprogno;
282 struct btf_field *kptr_field;
283 };
284
285 struct bpf_kfunc_call_arg_meta {
286 /* In parameters */
287 struct btf *btf;
288 u32 func_id;
289 u32 kfunc_flags;
290 const struct btf_type *func_proto;
291 const char *func_name;
292 /* Out parameters */
293 u32 ref_obj_id;
294 u8 release_regno;
295 bool r0_rdonly;
296 u32 ret_btf_id;
297 u64 r0_size;
298 u32 subprogno;
299 struct {
300 u64 value;
301 bool found;
302 } arg_constant;
303
304 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305 * generally to pass info about user-defined local kptr types to later
306 * verification logic
307 * bpf_obj_drop
308 * Record the local kptr type to be drop'd
309 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310 * Record the local kptr type to be refcount_incr'd and use
311 * arg_owning_ref to determine whether refcount_acquire should be
312 * fallible
313 */
314 struct btf *arg_btf;
315 u32 arg_btf_id;
316 bool arg_owning_ref;
317
318 struct {
319 struct btf_field *field;
320 } arg_list_head;
321 struct {
322 struct btf_field *field;
323 } arg_rbtree_root;
324 struct {
325 enum bpf_dynptr_type type;
326 u32 id;
327 u32 ref_obj_id;
328 } initialized_dynptr;
329 struct {
330 u8 spi;
331 u8 frameno;
332 } iter;
333 u64 mem_size;
334 };
335
336 struct btf *btf_vmlinux;
337
338 static DEFINE_MUTEX(bpf_verifier_lock);
339
340 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343 const struct bpf_line_info *linfo;
344 const struct bpf_prog *prog;
345 u32 i, nr_linfo;
346
347 prog = env->prog;
348 nr_linfo = prog->aux->nr_linfo;
349
350 if (!nr_linfo || insn_off >= prog->len)
351 return NULL;
352
353 linfo = prog->aux->linfo;
354 for (i = 1; i < nr_linfo; i++)
355 if (insn_off < linfo[i].insn_off)
356 break;
357
358 return &linfo[i - 1];
359 }
360
verbose(void * private_data,const char * fmt,...)361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363 struct bpf_verifier_env *env = private_data;
364 va_list args;
365
366 if (!bpf_verifier_log_needed(&env->log))
367 return;
368
369 va_start(args, fmt);
370 bpf_verifier_vlog(&env->log, fmt, args);
371 va_end(args);
372 }
373
ltrim(const char * s)374 static const char *ltrim(const char *s)
375 {
376 while (isspace(*s))
377 s++;
378
379 return s;
380 }
381
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383 u32 insn_off,
384 const char *prefix_fmt, ...)
385 {
386 const struct bpf_line_info *linfo;
387
388 if (!bpf_verifier_log_needed(&env->log))
389 return;
390
391 linfo = find_linfo(env, insn_off);
392 if (!linfo || linfo == env->prev_linfo)
393 return;
394
395 if (prefix_fmt) {
396 va_list args;
397
398 va_start(args, prefix_fmt);
399 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400 va_end(args);
401 }
402
403 verbose(env, "%s\n",
404 ltrim(btf_name_by_offset(env->prog->aux->btf,
405 linfo->line_off)));
406
407 env->prev_linfo = linfo;
408 }
409
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411 struct bpf_reg_state *reg,
412 struct tnum *range, const char *ctx,
413 const char *reg_name)
414 {
415 char tn_buf[48];
416
417 verbose(env, "At %s the register %s ", ctx, reg_name);
418 if (!tnum_is_unknown(reg->var_off)) {
419 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420 verbose(env, "has value %s", tn_buf);
421 } else {
422 verbose(env, "has unknown scalar value");
423 }
424 tnum_strn(tn_buf, sizeof(tn_buf), *range);
425 verbose(env, " should have been in %s\n", tn_buf);
426 }
427
type_is_pkt_pointer(enum bpf_reg_type type)428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430 type = base_type(type);
431 return type == PTR_TO_PACKET ||
432 type == PTR_TO_PACKET_META;
433 }
434
type_is_sk_pointer(enum bpf_reg_type type)435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437 return type == PTR_TO_SOCKET ||
438 type == PTR_TO_SOCK_COMMON ||
439 type == PTR_TO_TCP_SOCK ||
440 type == PTR_TO_XDP_SOCK;
441 }
442
type_may_be_null(u32 type)443 static bool type_may_be_null(u32 type)
444 {
445 return type & PTR_MAYBE_NULL;
446 }
447
reg_not_null(const struct bpf_reg_state * reg)448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450 enum bpf_reg_type type;
451
452 type = reg->type;
453 if (type_may_be_null(type))
454 return false;
455
456 type = base_type(type);
457 return type == PTR_TO_SOCKET ||
458 type == PTR_TO_TCP_SOCK ||
459 type == PTR_TO_MAP_VALUE ||
460 type == PTR_TO_MAP_KEY ||
461 type == PTR_TO_SOCK_COMMON ||
462 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463 type == PTR_TO_MEM;
464 }
465
type_is_ptr_alloc_obj(u32 type)466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470
type_is_non_owning_ref(u32 type)471 static bool type_is_non_owning_ref(u32 type)
472 {
473 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475
reg_btf_record(const struct bpf_reg_state * reg)476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478 struct btf_record *rec = NULL;
479 struct btf_struct_meta *meta;
480
481 if (reg->type == PTR_TO_MAP_VALUE) {
482 rec = reg->map_ptr->record;
483 } else if (type_is_ptr_alloc_obj(reg->type)) {
484 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485 if (meta)
486 rec = meta->record;
487 }
488 return rec;
489 }
490
subprog_is_global(const struct bpf_verifier_env * env,int subprog)491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494
495 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502
type_is_rdonly_mem(u32 type)503 static bool type_is_rdonly_mem(u32 type)
504 {
505 return type & MEM_RDONLY;
506 }
507
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)508 static bool is_acquire_function(enum bpf_func_id func_id,
509 const struct bpf_map *map)
510 {
511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512
513 if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 func_id == BPF_FUNC_sk_lookup_udp ||
515 func_id == BPF_FUNC_skc_lookup_tcp ||
516 func_id == BPF_FUNC_ringbuf_reserve ||
517 func_id == BPF_FUNC_kptr_xchg)
518 return true;
519
520 if (func_id == BPF_FUNC_map_lookup_elem &&
521 (map_type == BPF_MAP_TYPE_SOCKMAP ||
522 map_type == BPF_MAP_TYPE_SOCKHASH))
523 return true;
524
525 return false;
526 }
527
is_ptr_cast_function(enum bpf_func_id func_id)528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530 return func_id == BPF_FUNC_tcp_sock ||
531 func_id == BPF_FUNC_sk_fullsock ||
532 func_id == BPF_FUNC_skc_to_tcp_sock ||
533 func_id == BPF_FUNC_skc_to_tcp6_sock ||
534 func_id == BPF_FUNC_skc_to_udp6_sock ||
535 func_id == BPF_FUNC_skc_to_mptcp_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539
is_dynptr_ref_function(enum bpf_func_id func_id)540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542 return func_id == BPF_FUNC_dynptr_data;
543 }
544
545 static bool is_sync_callback_calling_kfunc(u32 btf_id);
546
is_sync_callback_calling_function(enum bpf_func_id func_id)547 static bool is_sync_callback_calling_function(enum bpf_func_id func_id)
548 {
549 return func_id == BPF_FUNC_for_each_map_elem ||
550 func_id == BPF_FUNC_find_vma ||
551 func_id == BPF_FUNC_loop ||
552 func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554
is_async_callback_calling_function(enum bpf_func_id func_id)555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557 return func_id == BPF_FUNC_timer_set_callback;
558 }
559
is_callback_calling_function(enum bpf_func_id func_id)560 static bool is_callback_calling_function(enum bpf_func_id func_id)
561 {
562 return is_sync_callback_calling_function(func_id) ||
563 is_async_callback_calling_function(func_id);
564 }
565
is_sync_callback_calling_insn(struct bpf_insn * insn)566 static bool is_sync_callback_calling_insn(struct bpf_insn *insn)
567 {
568 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) ||
569 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm));
570 }
571
is_storage_get_function(enum bpf_func_id func_id)572 static bool is_storage_get_function(enum bpf_func_id func_id)
573 {
574 return func_id == BPF_FUNC_sk_storage_get ||
575 func_id == BPF_FUNC_inode_storage_get ||
576 func_id == BPF_FUNC_task_storage_get ||
577 func_id == BPF_FUNC_cgrp_storage_get;
578 }
579
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)580 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
581 const struct bpf_map *map)
582 {
583 int ref_obj_uses = 0;
584
585 if (is_ptr_cast_function(func_id))
586 ref_obj_uses++;
587 if (is_acquire_function(func_id, map))
588 ref_obj_uses++;
589 if (is_dynptr_ref_function(func_id))
590 ref_obj_uses++;
591
592 return ref_obj_uses > 1;
593 }
594
is_cmpxchg_insn(const struct bpf_insn * insn)595 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
596 {
597 return BPF_CLASS(insn->code) == BPF_STX &&
598 BPF_MODE(insn->code) == BPF_ATOMIC &&
599 insn->imm == BPF_CMPXCHG;
600 }
601
602 /* string representation of 'enum bpf_reg_type'
603 *
604 * Note that reg_type_str() can not appear more than once in a single verbose()
605 * statement.
606 */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)607 static const char *reg_type_str(struct bpf_verifier_env *env,
608 enum bpf_reg_type type)
609 {
610 char postfix[16] = {0}, prefix[64] = {0};
611 static const char * const str[] = {
612 [NOT_INIT] = "?",
613 [SCALAR_VALUE] = "scalar",
614 [PTR_TO_CTX] = "ctx",
615 [CONST_PTR_TO_MAP] = "map_ptr",
616 [PTR_TO_MAP_VALUE] = "map_value",
617 [PTR_TO_STACK] = "fp",
618 [PTR_TO_PACKET] = "pkt",
619 [PTR_TO_PACKET_META] = "pkt_meta",
620 [PTR_TO_PACKET_END] = "pkt_end",
621 [PTR_TO_FLOW_KEYS] = "flow_keys",
622 [PTR_TO_SOCKET] = "sock",
623 [PTR_TO_SOCK_COMMON] = "sock_common",
624 [PTR_TO_TCP_SOCK] = "tcp_sock",
625 [PTR_TO_TP_BUFFER] = "tp_buffer",
626 [PTR_TO_XDP_SOCK] = "xdp_sock",
627 [PTR_TO_BTF_ID] = "ptr_",
628 [PTR_TO_MEM] = "mem",
629 [PTR_TO_BUF] = "buf",
630 [PTR_TO_FUNC] = "func",
631 [PTR_TO_MAP_KEY] = "map_key",
632 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr",
633 };
634
635 if (type & PTR_MAYBE_NULL) {
636 if (base_type(type) == PTR_TO_BTF_ID)
637 strncpy(postfix, "or_null_", 16);
638 else
639 strncpy(postfix, "_or_null", 16);
640 }
641
642 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
643 type & MEM_RDONLY ? "rdonly_" : "",
644 type & MEM_RINGBUF ? "ringbuf_" : "",
645 type & MEM_USER ? "user_" : "",
646 type & MEM_PERCPU ? "percpu_" : "",
647 type & MEM_RCU ? "rcu_" : "",
648 type & PTR_UNTRUSTED ? "untrusted_" : "",
649 type & PTR_TRUSTED ? "trusted_" : ""
650 );
651
652 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
653 prefix, str[base_type(type)], postfix);
654 return env->tmp_str_buf;
655 }
656
657 static char slot_type_char[] = {
658 [STACK_INVALID] = '?',
659 [STACK_SPILL] = 'r',
660 [STACK_MISC] = 'm',
661 [STACK_ZERO] = '0',
662 [STACK_DYNPTR] = 'd',
663 [STACK_ITER] = 'i',
664 };
665
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)666 static void print_liveness(struct bpf_verifier_env *env,
667 enum bpf_reg_liveness live)
668 {
669 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
670 verbose(env, "_");
671 if (live & REG_LIVE_READ)
672 verbose(env, "r");
673 if (live & REG_LIVE_WRITTEN)
674 verbose(env, "w");
675 if (live & REG_LIVE_DONE)
676 verbose(env, "D");
677 }
678
__get_spi(s32 off)679 static int __get_spi(s32 off)
680 {
681 return (-off - 1) / BPF_REG_SIZE;
682 }
683
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)684 static struct bpf_func_state *func(struct bpf_verifier_env *env,
685 const struct bpf_reg_state *reg)
686 {
687 struct bpf_verifier_state *cur = env->cur_state;
688
689 return cur->frame[reg->frameno];
690 }
691
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)692 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
693 {
694 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
695
696 /* We need to check that slots between [spi - nr_slots + 1, spi] are
697 * within [0, allocated_stack).
698 *
699 * Please note that the spi grows downwards. For example, a dynptr
700 * takes the size of two stack slots; the first slot will be at
701 * spi and the second slot will be at spi - 1.
702 */
703 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
704 }
705
stack_slot_obj_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * obj_kind,int nr_slots)706 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
707 const char *obj_kind, int nr_slots)
708 {
709 int off, spi;
710
711 if (!tnum_is_const(reg->var_off)) {
712 verbose(env, "%s has to be at a constant offset\n", obj_kind);
713 return -EINVAL;
714 }
715
716 off = reg->off + reg->var_off.value;
717 if (off % BPF_REG_SIZE) {
718 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
719 return -EINVAL;
720 }
721
722 spi = __get_spi(off);
723 if (spi + 1 < nr_slots) {
724 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
725 return -EINVAL;
726 }
727
728 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
729 return -ERANGE;
730 return spi;
731 }
732
dynptr_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg)733 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
734 {
735 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
736 }
737
iter_get_spi(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)738 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
739 {
740 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
741 }
742
btf_type_name(const struct btf * btf,u32 id)743 static const char *btf_type_name(const struct btf *btf, u32 id)
744 {
745 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
746 }
747
dynptr_type_str(enum bpf_dynptr_type type)748 static const char *dynptr_type_str(enum bpf_dynptr_type type)
749 {
750 switch (type) {
751 case BPF_DYNPTR_TYPE_LOCAL:
752 return "local";
753 case BPF_DYNPTR_TYPE_RINGBUF:
754 return "ringbuf";
755 case BPF_DYNPTR_TYPE_SKB:
756 return "skb";
757 case BPF_DYNPTR_TYPE_XDP:
758 return "xdp";
759 case BPF_DYNPTR_TYPE_INVALID:
760 return "<invalid>";
761 default:
762 WARN_ONCE(1, "unknown dynptr type %d\n", type);
763 return "<unknown>";
764 }
765 }
766
iter_type_str(const struct btf * btf,u32 btf_id)767 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
768 {
769 if (!btf || btf_id == 0)
770 return "<invalid>";
771
772 /* we already validated that type is valid and has conforming name */
773 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
774 }
775
iter_state_str(enum bpf_iter_state state)776 static const char *iter_state_str(enum bpf_iter_state state)
777 {
778 switch (state) {
779 case BPF_ITER_STATE_ACTIVE:
780 return "active";
781 case BPF_ITER_STATE_DRAINED:
782 return "drained";
783 case BPF_ITER_STATE_INVALID:
784 return "<invalid>";
785 default:
786 WARN_ONCE(1, "unknown iter state %d\n", state);
787 return "<unknown>";
788 }
789 }
790
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)791 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
792 {
793 env->scratched_regs |= 1U << regno;
794 }
795
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)796 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
797 {
798 env->scratched_stack_slots |= 1ULL << spi;
799 }
800
reg_scratched(const struct bpf_verifier_env * env,u32 regno)801 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
802 {
803 return (env->scratched_regs >> regno) & 1;
804 }
805
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)806 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
807 {
808 return (env->scratched_stack_slots >> regno) & 1;
809 }
810
verifier_state_scratched(const struct bpf_verifier_env * env)811 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
812 {
813 return env->scratched_regs || env->scratched_stack_slots;
814 }
815
mark_verifier_state_clean(struct bpf_verifier_env * env)816 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
817 {
818 env->scratched_regs = 0U;
819 env->scratched_stack_slots = 0ULL;
820 }
821
822 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)823 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
824 {
825 env->scratched_regs = ~0U;
826 env->scratched_stack_slots = ~0ULL;
827 }
828
arg_to_dynptr_type(enum bpf_arg_type arg_type)829 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
830 {
831 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
832 case DYNPTR_TYPE_LOCAL:
833 return BPF_DYNPTR_TYPE_LOCAL;
834 case DYNPTR_TYPE_RINGBUF:
835 return BPF_DYNPTR_TYPE_RINGBUF;
836 case DYNPTR_TYPE_SKB:
837 return BPF_DYNPTR_TYPE_SKB;
838 case DYNPTR_TYPE_XDP:
839 return BPF_DYNPTR_TYPE_XDP;
840 default:
841 return BPF_DYNPTR_TYPE_INVALID;
842 }
843 }
844
get_dynptr_type_flag(enum bpf_dynptr_type type)845 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
846 {
847 switch (type) {
848 case BPF_DYNPTR_TYPE_LOCAL:
849 return DYNPTR_TYPE_LOCAL;
850 case BPF_DYNPTR_TYPE_RINGBUF:
851 return DYNPTR_TYPE_RINGBUF;
852 case BPF_DYNPTR_TYPE_SKB:
853 return DYNPTR_TYPE_SKB;
854 case BPF_DYNPTR_TYPE_XDP:
855 return DYNPTR_TYPE_XDP;
856 default:
857 return 0;
858 }
859 }
860
dynptr_type_refcounted(enum bpf_dynptr_type type)861 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
862 {
863 return type == BPF_DYNPTR_TYPE_RINGBUF;
864 }
865
866 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
867 enum bpf_dynptr_type type,
868 bool first_slot, int dynptr_id);
869
870 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
871 struct bpf_reg_state *reg);
872
mark_dynptr_stack_regs(struct bpf_verifier_env * env,struct bpf_reg_state * sreg1,struct bpf_reg_state * sreg2,enum bpf_dynptr_type type)873 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
874 struct bpf_reg_state *sreg1,
875 struct bpf_reg_state *sreg2,
876 enum bpf_dynptr_type type)
877 {
878 int id = ++env->id_gen;
879
880 __mark_dynptr_reg(sreg1, type, true, id);
881 __mark_dynptr_reg(sreg2, type, false, id);
882 }
883
mark_dynptr_cb_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_dynptr_type type)884 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
885 struct bpf_reg_state *reg,
886 enum bpf_dynptr_type type)
887 {
888 __mark_dynptr_reg(reg, type, true, ++env->id_gen);
889 }
890
891 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
892 struct bpf_func_state *state, int spi);
893
mark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type,int insn_idx,int clone_ref_obj_id)894 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
895 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
896 {
897 struct bpf_func_state *state = func(env, reg);
898 enum bpf_dynptr_type type;
899 int spi, i, err;
900
901 spi = dynptr_get_spi(env, reg);
902 if (spi < 0)
903 return spi;
904
905 /* We cannot assume both spi and spi - 1 belong to the same dynptr,
906 * hence we need to call destroy_if_dynptr_stack_slot twice for both,
907 * to ensure that for the following example:
908 * [d1][d1][d2][d2]
909 * spi 3 2 1 0
910 * So marking spi = 2 should lead to destruction of both d1 and d2. In
911 * case they do belong to same dynptr, second call won't see slot_type
912 * as STACK_DYNPTR and will simply skip destruction.
913 */
914 err = destroy_if_dynptr_stack_slot(env, state, spi);
915 if (err)
916 return err;
917 err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
918 if (err)
919 return err;
920
921 for (i = 0; i < BPF_REG_SIZE; i++) {
922 state->stack[spi].slot_type[i] = STACK_DYNPTR;
923 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
924 }
925
926 type = arg_to_dynptr_type(arg_type);
927 if (type == BPF_DYNPTR_TYPE_INVALID)
928 return -EINVAL;
929
930 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
931 &state->stack[spi - 1].spilled_ptr, type);
932
933 if (dynptr_type_refcounted(type)) {
934 /* The id is used to track proper releasing */
935 int id;
936
937 if (clone_ref_obj_id)
938 id = clone_ref_obj_id;
939 else
940 id = acquire_reference_state(env, insn_idx);
941
942 if (id < 0)
943 return id;
944
945 state->stack[spi].spilled_ptr.ref_obj_id = id;
946 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
947 }
948
949 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
950 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
951
952 return 0;
953 }
954
invalidate_dynptr(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)955 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
956 {
957 int i;
958
959 for (i = 0; i < BPF_REG_SIZE; i++) {
960 state->stack[spi].slot_type[i] = STACK_INVALID;
961 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
962 }
963
964 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
965 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
966
967 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
968 *
969 * While we don't allow reading STACK_INVALID, it is still possible to
970 * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
971 * helpers or insns can do partial read of that part without failing,
972 * but check_stack_range_initialized, check_stack_read_var_off, and
973 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
974 * the slot conservatively. Hence we need to prevent those liveness
975 * marking walks.
976 *
977 * This was not a problem before because STACK_INVALID is only set by
978 * default (where the default reg state has its reg->parent as NULL), or
979 * in clean_live_states after REG_LIVE_DONE (at which point
980 * mark_reg_read won't walk reg->parent chain), but not randomly during
981 * verifier state exploration (like we did above). Hence, for our case
982 * parentage chain will still be live (i.e. reg->parent may be
983 * non-NULL), while earlier reg->parent was NULL, so we need
984 * REG_LIVE_WRITTEN to screen off read marker propagation when it is
985 * done later on reads or by mark_dynptr_read as well to unnecessary
986 * mark registers in verifier state.
987 */
988 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
989 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
990 }
991
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)992 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
993 {
994 struct bpf_func_state *state = func(env, reg);
995 int spi, ref_obj_id, i;
996
997 spi = dynptr_get_spi(env, reg);
998 if (spi < 0)
999 return spi;
1000
1001 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1002 invalidate_dynptr(env, state, spi);
1003 return 0;
1004 }
1005
1006 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
1007
1008 /* If the dynptr has a ref_obj_id, then we need to invalidate
1009 * two things:
1010 *
1011 * 1) Any dynptrs with a matching ref_obj_id (clones)
1012 * 2) Any slices derived from this dynptr.
1013 */
1014
1015 /* Invalidate any slices associated with this dynptr */
1016 WARN_ON_ONCE(release_reference(env, ref_obj_id));
1017
1018 /* Invalidate any dynptr clones */
1019 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1020 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1021 continue;
1022
1023 /* it should always be the case that if the ref obj id
1024 * matches then the stack slot also belongs to a
1025 * dynptr
1026 */
1027 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1028 verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1029 return -EFAULT;
1030 }
1031 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1032 invalidate_dynptr(env, state, i);
1033 }
1034
1035 return 0;
1036 }
1037
1038 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1039 struct bpf_reg_state *reg);
1040
mark_reg_invalid(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1041 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1042 {
1043 if (!env->allow_ptr_leaks)
1044 __mark_reg_not_init(env, reg);
1045 else
1046 __mark_reg_unknown(env, reg);
1047 }
1048
destroy_if_dynptr_stack_slot(struct bpf_verifier_env * env,struct bpf_func_state * state,int spi)1049 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1050 struct bpf_func_state *state, int spi)
1051 {
1052 struct bpf_func_state *fstate;
1053 struct bpf_reg_state *dreg;
1054 int i, dynptr_id;
1055
1056 /* We always ensure that STACK_DYNPTR is never set partially,
1057 * hence just checking for slot_type[0] is enough. This is
1058 * different for STACK_SPILL, where it may be only set for
1059 * 1 byte, so code has to use is_spilled_reg.
1060 */
1061 if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1062 return 0;
1063
1064 /* Reposition spi to first slot */
1065 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1066 spi = spi + 1;
1067
1068 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1069 verbose(env, "cannot overwrite referenced dynptr\n");
1070 return -EINVAL;
1071 }
1072
1073 mark_stack_slot_scratched(env, spi);
1074 mark_stack_slot_scratched(env, spi - 1);
1075
1076 /* Writing partially to one dynptr stack slot destroys both. */
1077 for (i = 0; i < BPF_REG_SIZE; i++) {
1078 state->stack[spi].slot_type[i] = STACK_INVALID;
1079 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1080 }
1081
1082 dynptr_id = state->stack[spi].spilled_ptr.id;
1083 /* Invalidate any slices associated with this dynptr */
1084 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1085 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1086 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1087 continue;
1088 if (dreg->dynptr_id == dynptr_id)
1089 mark_reg_invalid(env, dreg);
1090 }));
1091
1092 /* Do not release reference state, we are destroying dynptr on stack,
1093 * not using some helper to release it. Just reset register.
1094 */
1095 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1096 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1097
1098 /* Same reason as unmark_stack_slots_dynptr above */
1099 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1100 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1101
1102 return 0;
1103 }
1104
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1105 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1106 {
1107 int spi;
1108
1109 if (reg->type == CONST_PTR_TO_DYNPTR)
1110 return false;
1111
1112 spi = dynptr_get_spi(env, reg);
1113
1114 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1115 * error because this just means the stack state hasn't been updated yet.
1116 * We will do check_mem_access to check and update stack bounds later.
1117 */
1118 if (spi < 0 && spi != -ERANGE)
1119 return false;
1120
1121 /* We don't need to check if the stack slots are marked by previous
1122 * dynptr initializations because we allow overwriting existing unreferenced
1123 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1124 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1125 * touching are completely destructed before we reinitialize them for a new
1126 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1127 * instead of delaying it until the end where the user will get "Unreleased
1128 * reference" error.
1129 */
1130 return true;
1131 }
1132
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1133 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1134 {
1135 struct bpf_func_state *state = func(env, reg);
1136 int i, spi;
1137
1138 /* This already represents first slot of initialized bpf_dynptr.
1139 *
1140 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1141 * check_func_arg_reg_off's logic, so we don't need to check its
1142 * offset and alignment.
1143 */
1144 if (reg->type == CONST_PTR_TO_DYNPTR)
1145 return true;
1146
1147 spi = dynptr_get_spi(env, reg);
1148 if (spi < 0)
1149 return false;
1150 if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1151 return false;
1152
1153 for (i = 0; i < BPF_REG_SIZE; i++) {
1154 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1155 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1156 return false;
1157 }
1158
1159 return true;
1160 }
1161
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)1162 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1163 enum bpf_arg_type arg_type)
1164 {
1165 struct bpf_func_state *state = func(env, reg);
1166 enum bpf_dynptr_type dynptr_type;
1167 int spi;
1168
1169 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1170 if (arg_type == ARG_PTR_TO_DYNPTR)
1171 return true;
1172
1173 dynptr_type = arg_to_dynptr_type(arg_type);
1174 if (reg->type == CONST_PTR_TO_DYNPTR) {
1175 return reg->dynptr.type == dynptr_type;
1176 } else {
1177 spi = dynptr_get_spi(env, reg);
1178 if (spi < 0)
1179 return false;
1180 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1181 }
1182 }
1183
1184 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1185
mark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int insn_idx,struct btf * btf,u32 btf_id,int nr_slots)1186 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1187 struct bpf_reg_state *reg, int insn_idx,
1188 struct btf *btf, u32 btf_id, int nr_slots)
1189 {
1190 struct bpf_func_state *state = func(env, reg);
1191 int spi, i, j, id;
1192
1193 spi = iter_get_spi(env, reg, nr_slots);
1194 if (spi < 0)
1195 return spi;
1196
1197 id = acquire_reference_state(env, insn_idx);
1198 if (id < 0)
1199 return id;
1200
1201 for (i = 0; i < nr_slots; i++) {
1202 struct bpf_stack_state *slot = &state->stack[spi - i];
1203 struct bpf_reg_state *st = &slot->spilled_ptr;
1204
1205 __mark_reg_known_zero(st);
1206 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1207 st->live |= REG_LIVE_WRITTEN;
1208 st->ref_obj_id = i == 0 ? id : 0;
1209 st->iter.btf = btf;
1210 st->iter.btf_id = btf_id;
1211 st->iter.state = BPF_ITER_STATE_ACTIVE;
1212 st->iter.depth = 0;
1213
1214 for (j = 0; j < BPF_REG_SIZE; j++)
1215 slot->slot_type[j] = STACK_ITER;
1216
1217 mark_stack_slot_scratched(env, spi - i);
1218 }
1219
1220 return 0;
1221 }
1222
unmark_stack_slots_iter(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1223 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1224 struct bpf_reg_state *reg, int nr_slots)
1225 {
1226 struct bpf_func_state *state = func(env, reg);
1227 int spi, i, j;
1228
1229 spi = iter_get_spi(env, reg, nr_slots);
1230 if (spi < 0)
1231 return spi;
1232
1233 for (i = 0; i < nr_slots; i++) {
1234 struct bpf_stack_state *slot = &state->stack[spi - i];
1235 struct bpf_reg_state *st = &slot->spilled_ptr;
1236
1237 if (i == 0)
1238 WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1239
1240 __mark_reg_not_init(env, st);
1241
1242 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1243 st->live |= REG_LIVE_WRITTEN;
1244
1245 for (j = 0; j < BPF_REG_SIZE; j++)
1246 slot->slot_type[j] = STACK_INVALID;
1247
1248 mark_stack_slot_scratched(env, spi - i);
1249 }
1250
1251 return 0;
1252 }
1253
is_iter_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int nr_slots)1254 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1255 struct bpf_reg_state *reg, int nr_slots)
1256 {
1257 struct bpf_func_state *state = func(env, reg);
1258 int spi, i, j;
1259
1260 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1261 * will do check_mem_access to check and update stack bounds later, so
1262 * return true for that case.
1263 */
1264 spi = iter_get_spi(env, reg, nr_slots);
1265 if (spi == -ERANGE)
1266 return true;
1267 if (spi < 0)
1268 return false;
1269
1270 for (i = 0; i < nr_slots; i++) {
1271 struct bpf_stack_state *slot = &state->stack[spi - i];
1272
1273 for (j = 0; j < BPF_REG_SIZE; j++)
1274 if (slot->slot_type[j] == STACK_ITER)
1275 return false;
1276 }
1277
1278 return true;
1279 }
1280
is_iter_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct btf * btf,u32 btf_id,int nr_slots)1281 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1282 struct btf *btf, u32 btf_id, int nr_slots)
1283 {
1284 struct bpf_func_state *state = func(env, reg);
1285 int spi, i, j;
1286
1287 spi = iter_get_spi(env, reg, nr_slots);
1288 if (spi < 0)
1289 return false;
1290
1291 for (i = 0; i < nr_slots; i++) {
1292 struct bpf_stack_state *slot = &state->stack[spi - i];
1293 struct bpf_reg_state *st = &slot->spilled_ptr;
1294
1295 /* only main (first) slot has ref_obj_id set */
1296 if (i == 0 && !st->ref_obj_id)
1297 return false;
1298 if (i != 0 && st->ref_obj_id)
1299 return false;
1300 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1301 return false;
1302
1303 for (j = 0; j < BPF_REG_SIZE; j++)
1304 if (slot->slot_type[j] != STACK_ITER)
1305 return false;
1306 }
1307
1308 return true;
1309 }
1310
1311 /* Check if given stack slot is "special":
1312 * - spilled register state (STACK_SPILL);
1313 * - dynptr state (STACK_DYNPTR);
1314 * - iter state (STACK_ITER).
1315 */
is_stack_slot_special(const struct bpf_stack_state * stack)1316 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1317 {
1318 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1319
1320 switch (type) {
1321 case STACK_SPILL:
1322 case STACK_DYNPTR:
1323 case STACK_ITER:
1324 return true;
1325 case STACK_INVALID:
1326 case STACK_MISC:
1327 case STACK_ZERO:
1328 return false;
1329 default:
1330 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1331 return true;
1332 }
1333 }
1334
1335 /* The reg state of a pointer or a bounded scalar was saved when
1336 * it was spilled to the stack.
1337 */
is_spilled_reg(const struct bpf_stack_state * stack)1338 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1339 {
1340 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1341 }
1342
is_spilled_scalar_reg(const struct bpf_stack_state * stack)1343 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1344 {
1345 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1346 stack->spilled_ptr.type == SCALAR_VALUE;
1347 }
1348
scrub_spilled_slot(u8 * stype)1349 static void scrub_spilled_slot(u8 *stype)
1350 {
1351 if (*stype != STACK_INVALID)
1352 *stype = STACK_MISC;
1353 }
1354
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state,bool print_all)1355 static void print_verifier_state(struct bpf_verifier_env *env,
1356 const struct bpf_func_state *state,
1357 bool print_all)
1358 {
1359 const struct bpf_reg_state *reg;
1360 enum bpf_reg_type t;
1361 int i;
1362
1363 if (state->frameno)
1364 verbose(env, " frame%d:", state->frameno);
1365 for (i = 0; i < MAX_BPF_REG; i++) {
1366 reg = &state->regs[i];
1367 t = reg->type;
1368 if (t == NOT_INIT)
1369 continue;
1370 if (!print_all && !reg_scratched(env, i))
1371 continue;
1372 verbose(env, " R%d", i);
1373 print_liveness(env, reg->live);
1374 verbose(env, "=");
1375 if (t == SCALAR_VALUE && reg->precise)
1376 verbose(env, "P");
1377 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1378 tnum_is_const(reg->var_off)) {
1379 /* reg->off should be 0 for SCALAR_VALUE */
1380 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1381 verbose(env, "%lld", reg->var_off.value + reg->off);
1382 } else {
1383 const char *sep = "";
1384
1385 verbose(env, "%s", reg_type_str(env, t));
1386 if (base_type(t) == PTR_TO_BTF_ID)
1387 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1388 verbose(env, "(");
1389 /*
1390 * _a stands for append, was shortened to avoid multiline statements below.
1391 * This macro is used to output a comma separated list of attributes.
1392 */
1393 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1394
1395 if (reg->id)
1396 verbose_a("id=%d", reg->id);
1397 if (reg->ref_obj_id)
1398 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1399 if (type_is_non_owning_ref(reg->type))
1400 verbose_a("%s", "non_own_ref");
1401 if (t != SCALAR_VALUE)
1402 verbose_a("off=%d", reg->off);
1403 if (type_is_pkt_pointer(t))
1404 verbose_a("r=%d", reg->range);
1405 else if (base_type(t) == CONST_PTR_TO_MAP ||
1406 base_type(t) == PTR_TO_MAP_KEY ||
1407 base_type(t) == PTR_TO_MAP_VALUE)
1408 verbose_a("ks=%d,vs=%d",
1409 reg->map_ptr->key_size,
1410 reg->map_ptr->value_size);
1411 if (tnum_is_const(reg->var_off)) {
1412 /* Typically an immediate SCALAR_VALUE, but
1413 * could be a pointer whose offset is too big
1414 * for reg->off
1415 */
1416 verbose_a("imm=%llx", reg->var_off.value);
1417 } else {
1418 if (reg->smin_value != reg->umin_value &&
1419 reg->smin_value != S64_MIN)
1420 verbose_a("smin=%lld", (long long)reg->smin_value);
1421 if (reg->smax_value != reg->umax_value &&
1422 reg->smax_value != S64_MAX)
1423 verbose_a("smax=%lld", (long long)reg->smax_value);
1424 if (reg->umin_value != 0)
1425 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1426 if (reg->umax_value != U64_MAX)
1427 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1428 if (!tnum_is_unknown(reg->var_off)) {
1429 char tn_buf[48];
1430
1431 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1432 verbose_a("var_off=%s", tn_buf);
1433 }
1434 if (reg->s32_min_value != reg->smin_value &&
1435 reg->s32_min_value != S32_MIN)
1436 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1437 if (reg->s32_max_value != reg->smax_value &&
1438 reg->s32_max_value != S32_MAX)
1439 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1440 if (reg->u32_min_value != reg->umin_value &&
1441 reg->u32_min_value != U32_MIN)
1442 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1443 if (reg->u32_max_value != reg->umax_value &&
1444 reg->u32_max_value != U32_MAX)
1445 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1446 }
1447 #undef verbose_a
1448
1449 verbose(env, ")");
1450 }
1451 }
1452 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1453 char types_buf[BPF_REG_SIZE + 1];
1454 bool valid = false;
1455 int j;
1456
1457 for (j = 0; j < BPF_REG_SIZE; j++) {
1458 if (state->stack[i].slot_type[j] != STACK_INVALID)
1459 valid = true;
1460 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1461 }
1462 types_buf[BPF_REG_SIZE] = 0;
1463 if (!valid)
1464 continue;
1465 if (!print_all && !stack_slot_scratched(env, i))
1466 continue;
1467 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1468 case STACK_SPILL:
1469 reg = &state->stack[i].spilled_ptr;
1470 t = reg->type;
1471
1472 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473 print_liveness(env, reg->live);
1474 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1475 if (t == SCALAR_VALUE && reg->precise)
1476 verbose(env, "P");
1477 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1478 verbose(env, "%lld", reg->var_off.value + reg->off);
1479 break;
1480 case STACK_DYNPTR:
1481 i += BPF_DYNPTR_NR_SLOTS - 1;
1482 reg = &state->stack[i].spilled_ptr;
1483
1484 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485 print_liveness(env, reg->live);
1486 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1487 if (reg->ref_obj_id)
1488 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1489 break;
1490 case STACK_ITER:
1491 /* only main slot has ref_obj_id set; skip others */
1492 reg = &state->stack[i].spilled_ptr;
1493 if (!reg->ref_obj_id)
1494 continue;
1495
1496 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1497 print_liveness(env, reg->live);
1498 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1499 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1500 reg->ref_obj_id, iter_state_str(reg->iter.state),
1501 reg->iter.depth);
1502 break;
1503 case STACK_MISC:
1504 case STACK_ZERO:
1505 default:
1506 reg = &state->stack[i].spilled_ptr;
1507
1508 for (j = 0; j < BPF_REG_SIZE; j++)
1509 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1510 types_buf[BPF_REG_SIZE] = 0;
1511
1512 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1513 print_liveness(env, reg->live);
1514 verbose(env, "=%s", types_buf);
1515 break;
1516 }
1517 }
1518 if (state->acquired_refs && state->refs[0].id) {
1519 verbose(env, " refs=%d", state->refs[0].id);
1520 for (i = 1; i < state->acquired_refs; i++)
1521 if (state->refs[i].id)
1522 verbose(env, ",%d", state->refs[i].id);
1523 }
1524 if (state->in_callback_fn)
1525 verbose(env, " cb");
1526 if (state->in_async_callback_fn)
1527 verbose(env, " async_cb");
1528 verbose(env, "\n");
1529 if (!print_all)
1530 mark_verifier_state_clean(env);
1531 }
1532
vlog_alignment(u32 pos)1533 static inline u32 vlog_alignment(u32 pos)
1534 {
1535 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1536 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1537 }
1538
print_insn_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)1539 static void print_insn_state(struct bpf_verifier_env *env,
1540 const struct bpf_func_state *state)
1541 {
1542 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1543 /* remove new line character */
1544 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1545 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1546 } else {
1547 verbose(env, "%d:", env->insn_idx);
1548 }
1549 print_verifier_state(env, state, false);
1550 }
1551
1552 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1553 * small to hold src. This is different from krealloc since we don't want to preserve
1554 * the contents of dst.
1555 *
1556 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1557 * not be allocated.
1558 */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1559 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1560 {
1561 size_t alloc_bytes;
1562 void *orig = dst;
1563 size_t bytes;
1564
1565 if (ZERO_OR_NULL_PTR(src))
1566 goto out;
1567
1568 if (unlikely(check_mul_overflow(n, size, &bytes)))
1569 return NULL;
1570
1571 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1572 dst = krealloc(orig, alloc_bytes, flags);
1573 if (!dst) {
1574 kfree(orig);
1575 return NULL;
1576 }
1577
1578 memcpy(dst, src, bytes);
1579 out:
1580 return dst ? dst : ZERO_SIZE_PTR;
1581 }
1582
1583 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1584 * small to hold new_n items. new items are zeroed out if the array grows.
1585 *
1586 * Contrary to krealloc_array, does not free arr if new_n is zero.
1587 */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1588 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1589 {
1590 size_t alloc_size;
1591 void *new_arr;
1592
1593 if (!new_n || old_n == new_n)
1594 goto out;
1595
1596 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1597 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1598 if (!new_arr) {
1599 kfree(arr);
1600 return NULL;
1601 }
1602 arr = new_arr;
1603
1604 if (new_n > old_n)
1605 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1606
1607 out:
1608 return arr ? arr : ZERO_SIZE_PTR;
1609 }
1610
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1611 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1614 sizeof(struct bpf_reference_state), GFP_KERNEL);
1615 if (!dst->refs)
1616 return -ENOMEM;
1617
1618 dst->acquired_refs = src->acquired_refs;
1619 return 0;
1620 }
1621
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1622 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1623 {
1624 size_t n = src->allocated_stack / BPF_REG_SIZE;
1625
1626 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1627 GFP_KERNEL);
1628 if (!dst->stack)
1629 return -ENOMEM;
1630
1631 dst->allocated_stack = src->allocated_stack;
1632 return 0;
1633 }
1634
resize_reference_state(struct bpf_func_state * state,size_t n)1635 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1636 {
1637 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1638 sizeof(struct bpf_reference_state));
1639 if (!state->refs)
1640 return -ENOMEM;
1641
1642 state->acquired_refs = n;
1643 return 0;
1644 }
1645
1646 /* Possibly update state->allocated_stack to be at least size bytes. Also
1647 * possibly update the function's high-water mark in its bpf_subprog_info.
1648 */
grow_stack_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int size)1649 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size)
1650 {
1651 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1652
1653 if (old_n >= n)
1654 return 0;
1655
1656 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1657 if (!state->stack)
1658 return -ENOMEM;
1659
1660 state->allocated_stack = size;
1661
1662 /* update known max for given subprogram */
1663 if (env->subprog_info[state->subprogno].stack_depth < size)
1664 env->subprog_info[state->subprogno].stack_depth = size;
1665
1666 return 0;
1667 }
1668
1669 /* Acquire a pointer id from the env and update the state->refs to include
1670 * this new pointer reference.
1671 * On success, returns a valid pointer id to associate with the register
1672 * On failure, returns a negative errno.
1673 */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1674 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1675 {
1676 struct bpf_func_state *state = cur_func(env);
1677 int new_ofs = state->acquired_refs;
1678 int id, err;
1679
1680 err = resize_reference_state(state, state->acquired_refs + 1);
1681 if (err)
1682 return err;
1683 id = ++env->id_gen;
1684 state->refs[new_ofs].id = id;
1685 state->refs[new_ofs].insn_idx = insn_idx;
1686 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1687
1688 return id;
1689 }
1690
1691 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1692 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1693 {
1694 int i, last_idx;
1695
1696 last_idx = state->acquired_refs - 1;
1697 for (i = 0; i < state->acquired_refs; i++) {
1698 if (state->refs[i].id == ptr_id) {
1699 /* Cannot release caller references in callbacks */
1700 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1701 return -EINVAL;
1702 if (last_idx && i != last_idx)
1703 memcpy(&state->refs[i], &state->refs[last_idx],
1704 sizeof(*state->refs));
1705 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1706 state->acquired_refs--;
1707 return 0;
1708 }
1709 }
1710 return -EINVAL;
1711 }
1712
free_func_state(struct bpf_func_state * state)1713 static void free_func_state(struct bpf_func_state *state)
1714 {
1715 if (!state)
1716 return;
1717 kfree(state->refs);
1718 kfree(state->stack);
1719 kfree(state);
1720 }
1721
clear_jmp_history(struct bpf_verifier_state * state)1722 static void clear_jmp_history(struct bpf_verifier_state *state)
1723 {
1724 kfree(state->jmp_history);
1725 state->jmp_history = NULL;
1726 state->jmp_history_cnt = 0;
1727 }
1728
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1729 static void free_verifier_state(struct bpf_verifier_state *state,
1730 bool free_self)
1731 {
1732 int i;
1733
1734 for (i = 0; i <= state->curframe; i++) {
1735 free_func_state(state->frame[i]);
1736 state->frame[i] = NULL;
1737 }
1738 clear_jmp_history(state);
1739 if (free_self)
1740 kfree(state);
1741 }
1742
1743 /* copy verifier state from src to dst growing dst stack space
1744 * when necessary to accommodate larger src stack
1745 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1746 static int copy_func_state(struct bpf_func_state *dst,
1747 const struct bpf_func_state *src)
1748 {
1749 int err;
1750
1751 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1752 err = copy_reference_state(dst, src);
1753 if (err)
1754 return err;
1755 return copy_stack_state(dst, src);
1756 }
1757
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1758 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1759 const struct bpf_verifier_state *src)
1760 {
1761 struct bpf_func_state *dst;
1762 int i, err;
1763
1764 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1765 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1766 GFP_USER);
1767 if (!dst_state->jmp_history)
1768 return -ENOMEM;
1769 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1770
1771 /* if dst has more stack frames then src frame, free them */
1772 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1773 free_func_state(dst_state->frame[i]);
1774 dst_state->frame[i] = NULL;
1775 }
1776 dst_state->speculative = src->speculative;
1777 dst_state->active_rcu_lock = src->active_rcu_lock;
1778 dst_state->curframe = src->curframe;
1779 dst_state->active_lock.ptr = src->active_lock.ptr;
1780 dst_state->active_lock.id = src->active_lock.id;
1781 dst_state->branches = src->branches;
1782 dst_state->parent = src->parent;
1783 dst_state->first_insn_idx = src->first_insn_idx;
1784 dst_state->last_insn_idx = src->last_insn_idx;
1785 dst_state->dfs_depth = src->dfs_depth;
1786 dst_state->callback_unroll_depth = src->callback_unroll_depth;
1787 dst_state->used_as_loop_entry = src->used_as_loop_entry;
1788 for (i = 0; i <= src->curframe; i++) {
1789 dst = dst_state->frame[i];
1790 if (!dst) {
1791 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1792 if (!dst)
1793 return -ENOMEM;
1794 dst_state->frame[i] = dst;
1795 }
1796 err = copy_func_state(dst, src->frame[i]);
1797 if (err)
1798 return err;
1799 }
1800 return 0;
1801 }
1802
state_htab_size(struct bpf_verifier_env * env)1803 static u32 state_htab_size(struct bpf_verifier_env *env)
1804 {
1805 return env->prog->len;
1806 }
1807
explored_state(struct bpf_verifier_env * env,int idx)1808 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1809 {
1810 struct bpf_verifier_state *cur = env->cur_state;
1811 struct bpf_func_state *state = cur->frame[cur->curframe];
1812
1813 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1814 }
1815
same_callsites(struct bpf_verifier_state * a,struct bpf_verifier_state * b)1816 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1817 {
1818 int fr;
1819
1820 if (a->curframe != b->curframe)
1821 return false;
1822
1823 for (fr = a->curframe; fr >= 0; fr--)
1824 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1825 return false;
1826
1827 return true;
1828 }
1829
1830 /* Open coded iterators allow back-edges in the state graph in order to
1831 * check unbounded loops that iterators.
1832 *
1833 * In is_state_visited() it is necessary to know if explored states are
1834 * part of some loops in order to decide whether non-exact states
1835 * comparison could be used:
1836 * - non-exact states comparison establishes sub-state relation and uses
1837 * read and precision marks to do so, these marks are propagated from
1838 * children states and thus are not guaranteed to be final in a loop;
1839 * - exact states comparison just checks if current and explored states
1840 * are identical (and thus form a back-edge).
1841 *
1842 * Paper "A New Algorithm for Identifying Loops in Decompilation"
1843 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1844 * algorithm for loop structure detection and gives an overview of
1845 * relevant terminology. It also has helpful illustrations.
1846 *
1847 * [1] https://api.semanticscholar.org/CorpusID:15784067
1848 *
1849 * We use a similar algorithm but because loop nested structure is
1850 * irrelevant for verifier ours is significantly simpler and resembles
1851 * strongly connected components algorithm from Sedgewick's textbook.
1852 *
1853 * Define topmost loop entry as a first node of the loop traversed in a
1854 * depth first search starting from initial state. The goal of the loop
1855 * tracking algorithm is to associate topmost loop entries with states
1856 * derived from these entries.
1857 *
1858 * For each step in the DFS states traversal algorithm needs to identify
1859 * the following situations:
1860 *
1861 * initial initial initial
1862 * | | |
1863 * V V V
1864 * ... ... .---------> hdr
1865 * | | | |
1866 * V V | V
1867 * cur .-> succ | .------...
1868 * | | | | | |
1869 * V | V | V V
1870 * succ '-- cur | ... ...
1871 * | | |
1872 * | V V
1873 * | succ <- cur
1874 * | |
1875 * | V
1876 * | ...
1877 * | |
1878 * '----'
1879 *
1880 * (A) successor state of cur (B) successor state of cur or it's entry
1881 * not yet traversed are in current DFS path, thus cur and succ
1882 * are members of the same outermost loop
1883 *
1884 * initial initial
1885 * | |
1886 * V V
1887 * ... ...
1888 * | |
1889 * V V
1890 * .------... .------...
1891 * | | | |
1892 * V V V V
1893 * .-> hdr ... ... ...
1894 * | | | | |
1895 * | V V V V
1896 * | succ <- cur succ <- cur
1897 * | | |
1898 * | V V
1899 * | ... ...
1900 * | | |
1901 * '----' exit
1902 *
1903 * (C) successor state of cur is a part of some loop but this loop
1904 * does not include cur or successor state is not in a loop at all.
1905 *
1906 * Algorithm could be described as the following python code:
1907 *
1908 * traversed = set() # Set of traversed nodes
1909 * entries = {} # Mapping from node to loop entry
1910 * depths = {} # Depth level assigned to graph node
1911 * path = set() # Current DFS path
1912 *
1913 * # Find outermost loop entry known for n
1914 * def get_loop_entry(n):
1915 * h = entries.get(n, None)
1916 * while h in entries and entries[h] != h:
1917 * h = entries[h]
1918 * return h
1919 *
1920 * # Update n's loop entry if h's outermost entry comes
1921 * # before n's outermost entry in current DFS path.
1922 * def update_loop_entry(n, h):
1923 * n1 = get_loop_entry(n) or n
1924 * h1 = get_loop_entry(h) or h
1925 * if h1 in path and depths[h1] <= depths[n1]:
1926 * entries[n] = h1
1927 *
1928 * def dfs(n, depth):
1929 * traversed.add(n)
1930 * path.add(n)
1931 * depths[n] = depth
1932 * for succ in G.successors(n):
1933 * if succ not in traversed:
1934 * # Case A: explore succ and update cur's loop entry
1935 * # only if succ's entry is in current DFS path.
1936 * dfs(succ, depth + 1)
1937 * h = get_loop_entry(succ)
1938 * update_loop_entry(n, h)
1939 * else:
1940 * # Case B or C depending on `h1 in path` check in update_loop_entry().
1941 * update_loop_entry(n, succ)
1942 * path.remove(n)
1943 *
1944 * To adapt this algorithm for use with verifier:
1945 * - use st->branch == 0 as a signal that DFS of succ had been finished
1946 * and cur's loop entry has to be updated (case A), handle this in
1947 * update_branch_counts();
1948 * - use st->branch > 0 as a signal that st is in the current DFS path;
1949 * - handle cases B and C in is_state_visited();
1950 * - update topmost loop entry for intermediate states in get_loop_entry().
1951 */
get_loop_entry(struct bpf_verifier_state * st)1952 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1953 {
1954 struct bpf_verifier_state *topmost = st->loop_entry, *old;
1955
1956 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1957 topmost = topmost->loop_entry;
1958 /* Update loop entries for intermediate states to avoid this
1959 * traversal in future get_loop_entry() calls.
1960 */
1961 while (st && st->loop_entry != topmost) {
1962 old = st->loop_entry;
1963 st->loop_entry = topmost;
1964 st = old;
1965 }
1966 return topmost;
1967 }
1968
update_loop_entry(struct bpf_verifier_state * cur,struct bpf_verifier_state * hdr)1969 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1970 {
1971 struct bpf_verifier_state *cur1, *hdr1;
1972
1973 cur1 = get_loop_entry(cur) ?: cur;
1974 hdr1 = get_loop_entry(hdr) ?: hdr;
1975 /* The head1->branches check decides between cases B and C in
1976 * comment for get_loop_entry(). If hdr1->branches == 0 then
1977 * head's topmost loop entry is not in current DFS path,
1978 * hence 'cur' and 'hdr' are not in the same loop and there is
1979 * no need to update cur->loop_entry.
1980 */
1981 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
1982 cur->loop_entry = hdr;
1983 hdr->used_as_loop_entry = true;
1984 }
1985 }
1986
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1987 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1988 {
1989 while (st) {
1990 u32 br = --st->branches;
1991
1992 /* br == 0 signals that DFS exploration for 'st' is finished,
1993 * thus it is necessary to update parent's loop entry if it
1994 * turned out that st is a part of some loop.
1995 * This is a part of 'case A' in get_loop_entry() comment.
1996 */
1997 if (br == 0 && st->parent && st->loop_entry)
1998 update_loop_entry(st->parent, st->loop_entry);
1999
2000 /* WARN_ON(br > 1) technically makes sense here,
2001 * but see comment in push_stack(), hence:
2002 */
2003 WARN_ONCE((int)br < 0,
2004 "BUG update_branch_counts:branches_to_explore=%d\n",
2005 br);
2006 if (br)
2007 break;
2008 st = st->parent;
2009 }
2010 }
2011
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)2012 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2013 int *insn_idx, bool pop_log)
2014 {
2015 struct bpf_verifier_state *cur = env->cur_state;
2016 struct bpf_verifier_stack_elem *elem, *head = env->head;
2017 int err;
2018
2019 if (env->head == NULL)
2020 return -ENOENT;
2021
2022 if (cur) {
2023 err = copy_verifier_state(cur, &head->st);
2024 if (err)
2025 return err;
2026 }
2027 if (pop_log)
2028 bpf_vlog_reset(&env->log, head->log_pos);
2029 if (insn_idx)
2030 *insn_idx = head->insn_idx;
2031 if (prev_insn_idx)
2032 *prev_insn_idx = head->prev_insn_idx;
2033 elem = head->next;
2034 free_verifier_state(&head->st, false);
2035 kfree(head);
2036 env->head = elem;
2037 env->stack_size--;
2038 return 0;
2039 }
2040
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)2041 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2042 int insn_idx, int prev_insn_idx,
2043 bool speculative)
2044 {
2045 struct bpf_verifier_state *cur = env->cur_state;
2046 struct bpf_verifier_stack_elem *elem;
2047 int err;
2048
2049 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2050 if (!elem)
2051 goto err;
2052
2053 elem->insn_idx = insn_idx;
2054 elem->prev_insn_idx = prev_insn_idx;
2055 elem->next = env->head;
2056 elem->log_pos = env->log.end_pos;
2057 env->head = elem;
2058 env->stack_size++;
2059 err = copy_verifier_state(&elem->st, cur);
2060 if (err)
2061 goto err;
2062 elem->st.speculative |= speculative;
2063 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2064 verbose(env, "The sequence of %d jumps is too complex.\n",
2065 env->stack_size);
2066 goto err;
2067 }
2068 if (elem->st.parent) {
2069 ++elem->st.parent->branches;
2070 /* WARN_ON(branches > 2) technically makes sense here,
2071 * but
2072 * 1. speculative states will bump 'branches' for non-branch
2073 * instructions
2074 * 2. is_state_visited() heuristics may decide not to create
2075 * a new state for a sequence of branches and all such current
2076 * and cloned states will be pointing to a single parent state
2077 * which might have large 'branches' count.
2078 */
2079 }
2080 return &elem->st;
2081 err:
2082 free_verifier_state(env->cur_state, true);
2083 env->cur_state = NULL;
2084 /* pop all elements and return */
2085 while (!pop_stack(env, NULL, NULL, false));
2086 return NULL;
2087 }
2088
2089 #define CALLER_SAVED_REGS 6
2090 static const int caller_saved[CALLER_SAVED_REGS] = {
2091 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2092 };
2093
2094 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)2095 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2096 {
2097 reg->var_off = tnum_const(imm);
2098 reg->smin_value = (s64)imm;
2099 reg->smax_value = (s64)imm;
2100 reg->umin_value = imm;
2101 reg->umax_value = imm;
2102
2103 reg->s32_min_value = (s32)imm;
2104 reg->s32_max_value = (s32)imm;
2105 reg->u32_min_value = (u32)imm;
2106 reg->u32_max_value = (u32)imm;
2107 }
2108
2109 /* Mark the unknown part of a register (variable offset or scalar value) as
2110 * known to have the value @imm.
2111 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)2112 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2113 {
2114 /* Clear off and union(map_ptr, range) */
2115 memset(((u8 *)reg) + sizeof(reg->type), 0,
2116 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2117 reg->id = 0;
2118 reg->ref_obj_id = 0;
2119 ___mark_reg_known(reg, imm);
2120 }
2121
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)2122 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2123 {
2124 reg->var_off = tnum_const_subreg(reg->var_off, imm);
2125 reg->s32_min_value = (s32)imm;
2126 reg->s32_max_value = (s32)imm;
2127 reg->u32_min_value = (u32)imm;
2128 reg->u32_max_value = (u32)imm;
2129 }
2130
2131 /* Mark the 'variable offset' part of a register as zero. This should be
2132 * used only on registers holding a pointer type.
2133 */
__mark_reg_known_zero(struct bpf_reg_state * reg)2134 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2135 {
2136 __mark_reg_known(reg, 0);
2137 }
2138
__mark_reg_const_zero(struct bpf_reg_state * reg)2139 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2140 {
2141 __mark_reg_known(reg, 0);
2142 reg->type = SCALAR_VALUE;
2143 }
2144
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2145 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2146 struct bpf_reg_state *regs, u32 regno)
2147 {
2148 if (WARN_ON(regno >= MAX_BPF_REG)) {
2149 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2150 /* Something bad happened, let's kill all regs */
2151 for (regno = 0; regno < MAX_BPF_REG; regno++)
2152 __mark_reg_not_init(env, regs + regno);
2153 return;
2154 }
2155 __mark_reg_known_zero(regs + regno);
2156 }
2157
__mark_dynptr_reg(struct bpf_reg_state * reg,enum bpf_dynptr_type type,bool first_slot,int dynptr_id)2158 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2159 bool first_slot, int dynptr_id)
2160 {
2161 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2162 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2163 * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2164 */
2165 __mark_reg_known_zero(reg);
2166 reg->type = CONST_PTR_TO_DYNPTR;
2167 /* Give each dynptr a unique id to uniquely associate slices to it. */
2168 reg->id = dynptr_id;
2169 reg->dynptr.type = type;
2170 reg->dynptr.first_slot = first_slot;
2171 }
2172
mark_ptr_not_null_reg(struct bpf_reg_state * reg)2173 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2174 {
2175 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2176 const struct bpf_map *map = reg->map_ptr;
2177
2178 if (map->inner_map_meta) {
2179 reg->type = CONST_PTR_TO_MAP;
2180 reg->map_ptr = map->inner_map_meta;
2181 /* transfer reg's id which is unique for every map_lookup_elem
2182 * as UID of the inner map.
2183 */
2184 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2185 reg->map_uid = reg->id;
2186 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2187 reg->type = PTR_TO_XDP_SOCK;
2188 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2189 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2190 reg->type = PTR_TO_SOCKET;
2191 } else {
2192 reg->type = PTR_TO_MAP_VALUE;
2193 }
2194 return;
2195 }
2196
2197 reg->type &= ~PTR_MAYBE_NULL;
2198 }
2199
mark_reg_graph_node(struct bpf_reg_state * regs,u32 regno,struct btf_field_graph_root * ds_head)2200 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2201 struct btf_field_graph_root *ds_head)
2202 {
2203 __mark_reg_known_zero(®s[regno]);
2204 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2205 regs[regno].btf = ds_head->btf;
2206 regs[regno].btf_id = ds_head->value_btf_id;
2207 regs[regno].off = ds_head->node_offset;
2208 }
2209
reg_is_pkt_pointer(const struct bpf_reg_state * reg)2210 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2211 {
2212 return type_is_pkt_pointer(reg->type);
2213 }
2214
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)2215 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2216 {
2217 return reg_is_pkt_pointer(reg) ||
2218 reg->type == PTR_TO_PACKET_END;
2219 }
2220
reg_is_dynptr_slice_pkt(const struct bpf_reg_state * reg)2221 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2222 {
2223 return base_type(reg->type) == PTR_TO_MEM &&
2224 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2225 }
2226
2227 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
reg_is_init_pkt_pointer(const struct bpf_reg_state * reg,enum bpf_reg_type which)2228 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2229 enum bpf_reg_type which)
2230 {
2231 /* The register can already have a range from prior markings.
2232 * This is fine as long as it hasn't been advanced from its
2233 * origin.
2234 */
2235 return reg->type == which &&
2236 reg->id == 0 &&
2237 reg->off == 0 &&
2238 tnum_equals_const(reg->var_off, 0);
2239 }
2240
2241 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)2242 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2243 {
2244 reg->smin_value = S64_MIN;
2245 reg->smax_value = S64_MAX;
2246 reg->umin_value = 0;
2247 reg->umax_value = U64_MAX;
2248
2249 reg->s32_min_value = S32_MIN;
2250 reg->s32_max_value = S32_MAX;
2251 reg->u32_min_value = 0;
2252 reg->u32_max_value = U32_MAX;
2253 }
2254
__mark_reg64_unbounded(struct bpf_reg_state * reg)2255 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2256 {
2257 reg->smin_value = S64_MIN;
2258 reg->smax_value = S64_MAX;
2259 reg->umin_value = 0;
2260 reg->umax_value = U64_MAX;
2261 }
2262
__mark_reg32_unbounded(struct bpf_reg_state * reg)2263 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2264 {
2265 reg->s32_min_value = S32_MIN;
2266 reg->s32_max_value = S32_MAX;
2267 reg->u32_min_value = 0;
2268 reg->u32_max_value = U32_MAX;
2269 }
2270
__update_reg32_bounds(struct bpf_reg_state * reg)2271 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2272 {
2273 struct tnum var32_off = tnum_subreg(reg->var_off);
2274
2275 /* min signed is max(sign bit) | min(other bits) */
2276 reg->s32_min_value = max_t(s32, reg->s32_min_value,
2277 var32_off.value | (var32_off.mask & S32_MIN));
2278 /* max signed is min(sign bit) | max(other bits) */
2279 reg->s32_max_value = min_t(s32, reg->s32_max_value,
2280 var32_off.value | (var32_off.mask & S32_MAX));
2281 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2282 reg->u32_max_value = min(reg->u32_max_value,
2283 (u32)(var32_off.value | var32_off.mask));
2284 }
2285
__update_reg64_bounds(struct bpf_reg_state * reg)2286 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2287 {
2288 /* min signed is max(sign bit) | min(other bits) */
2289 reg->smin_value = max_t(s64, reg->smin_value,
2290 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2291 /* max signed is min(sign bit) | max(other bits) */
2292 reg->smax_value = min_t(s64, reg->smax_value,
2293 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2294 reg->umin_value = max(reg->umin_value, reg->var_off.value);
2295 reg->umax_value = min(reg->umax_value,
2296 reg->var_off.value | reg->var_off.mask);
2297 }
2298
__update_reg_bounds(struct bpf_reg_state * reg)2299 static void __update_reg_bounds(struct bpf_reg_state *reg)
2300 {
2301 __update_reg32_bounds(reg);
2302 __update_reg64_bounds(reg);
2303 }
2304
2305 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)2306 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2307 {
2308 /* Learn sign from signed bounds.
2309 * If we cannot cross the sign boundary, then signed and unsigned bounds
2310 * are the same, so combine. This works even in the negative case, e.g.
2311 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2312 */
2313 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2314 reg->s32_min_value = reg->u32_min_value =
2315 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2316 reg->s32_max_value = reg->u32_max_value =
2317 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2318 return;
2319 }
2320 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2321 * boundary, so we must be careful.
2322 */
2323 if ((s32)reg->u32_max_value >= 0) {
2324 /* Positive. We can't learn anything from the smin, but smax
2325 * is positive, hence safe.
2326 */
2327 reg->s32_min_value = reg->u32_min_value;
2328 reg->s32_max_value = reg->u32_max_value =
2329 min_t(u32, reg->s32_max_value, reg->u32_max_value);
2330 } else if ((s32)reg->u32_min_value < 0) {
2331 /* Negative. We can't learn anything from the smax, but smin
2332 * is negative, hence safe.
2333 */
2334 reg->s32_min_value = reg->u32_min_value =
2335 max_t(u32, reg->s32_min_value, reg->u32_min_value);
2336 reg->s32_max_value = reg->u32_max_value;
2337 }
2338 }
2339
__reg64_deduce_bounds(struct bpf_reg_state * reg)2340 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2341 {
2342 /* Learn sign from signed bounds.
2343 * If we cannot cross the sign boundary, then signed and unsigned bounds
2344 * are the same, so combine. This works even in the negative case, e.g.
2345 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2346 */
2347 if (reg->smin_value >= 0 || reg->smax_value < 0) {
2348 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2349 reg->umin_value);
2350 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2351 reg->umax_value);
2352 return;
2353 }
2354 /* Learn sign from unsigned bounds. Signed bounds cross the sign
2355 * boundary, so we must be careful.
2356 */
2357 if ((s64)reg->umax_value >= 0) {
2358 /* Positive. We can't learn anything from the smin, but smax
2359 * is positive, hence safe.
2360 */
2361 reg->smin_value = reg->umin_value;
2362 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2363 reg->umax_value);
2364 } else if ((s64)reg->umin_value < 0) {
2365 /* Negative. We can't learn anything from the smax, but smin
2366 * is negative, hence safe.
2367 */
2368 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2369 reg->umin_value);
2370 reg->smax_value = reg->umax_value;
2371 }
2372 }
2373
__reg_deduce_bounds(struct bpf_reg_state * reg)2374 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2375 {
2376 __reg32_deduce_bounds(reg);
2377 __reg64_deduce_bounds(reg);
2378 }
2379
2380 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)2381 static void __reg_bound_offset(struct bpf_reg_state *reg)
2382 {
2383 struct tnum var64_off = tnum_intersect(reg->var_off,
2384 tnum_range(reg->umin_value,
2385 reg->umax_value));
2386 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2387 tnum_range(reg->u32_min_value,
2388 reg->u32_max_value));
2389
2390 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2391 }
2392
reg_bounds_sync(struct bpf_reg_state * reg)2393 static void reg_bounds_sync(struct bpf_reg_state *reg)
2394 {
2395 /* We might have learned new bounds from the var_off. */
2396 __update_reg_bounds(reg);
2397 /* We might have learned something about the sign bit. */
2398 __reg_deduce_bounds(reg);
2399 /* We might have learned some bits from the bounds. */
2400 __reg_bound_offset(reg);
2401 /* Intersecting with the old var_off might have improved our bounds
2402 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2403 * then new var_off is (0; 0x7f...fc) which improves our umax.
2404 */
2405 __update_reg_bounds(reg);
2406 }
2407
__reg32_bound_s64(s32 a)2408 static bool __reg32_bound_s64(s32 a)
2409 {
2410 return a >= 0 && a <= S32_MAX;
2411 }
2412
__reg_assign_32_into_64(struct bpf_reg_state * reg)2413 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2414 {
2415 reg->umin_value = reg->u32_min_value;
2416 reg->umax_value = reg->u32_max_value;
2417
2418 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2419 * be positive otherwise set to worse case bounds and refine later
2420 * from tnum.
2421 */
2422 if (__reg32_bound_s64(reg->s32_min_value) &&
2423 __reg32_bound_s64(reg->s32_max_value)) {
2424 reg->smin_value = reg->s32_min_value;
2425 reg->smax_value = reg->s32_max_value;
2426 } else {
2427 reg->smin_value = 0;
2428 reg->smax_value = U32_MAX;
2429 }
2430 }
2431
__reg_combine_32_into_64(struct bpf_reg_state * reg)2432 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2433 {
2434 /* special case when 64-bit register has upper 32-bit register
2435 * zeroed. Typically happens after zext or <<32, >>32 sequence
2436 * allowing us to use 32-bit bounds directly,
2437 */
2438 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2439 __reg_assign_32_into_64(reg);
2440 } else {
2441 /* Otherwise the best we can do is push lower 32bit known and
2442 * unknown bits into register (var_off set from jmp logic)
2443 * then learn as much as possible from the 64-bit tnum
2444 * known and unknown bits. The previous smin/smax bounds are
2445 * invalid here because of jmp32 compare so mark them unknown
2446 * so they do not impact tnum bounds calculation.
2447 */
2448 __mark_reg64_unbounded(reg);
2449 }
2450 reg_bounds_sync(reg);
2451 }
2452
__reg64_bound_s32(s64 a)2453 static bool __reg64_bound_s32(s64 a)
2454 {
2455 return a >= S32_MIN && a <= S32_MAX;
2456 }
2457
__reg64_bound_u32(u64 a)2458 static bool __reg64_bound_u32(u64 a)
2459 {
2460 return a >= U32_MIN && a <= U32_MAX;
2461 }
2462
__reg_combine_64_into_32(struct bpf_reg_state * reg)2463 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2464 {
2465 __mark_reg32_unbounded(reg);
2466 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2467 reg->s32_min_value = (s32)reg->smin_value;
2468 reg->s32_max_value = (s32)reg->smax_value;
2469 }
2470 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2471 reg->u32_min_value = (u32)reg->umin_value;
2472 reg->u32_max_value = (u32)reg->umax_value;
2473 }
2474 reg_bounds_sync(reg);
2475 }
2476
2477 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2479 struct bpf_reg_state *reg)
2480 {
2481 /*
2482 * Clear type, off, and union(map_ptr, range) and
2483 * padding between 'type' and union
2484 */
2485 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2486 reg->type = SCALAR_VALUE;
2487 reg->id = 0;
2488 reg->ref_obj_id = 0;
2489 reg->var_off = tnum_unknown;
2490 reg->frameno = 0;
2491 reg->precise = !env->bpf_capable;
2492 __mark_reg_unbounded(reg);
2493 }
2494
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2495 static void mark_reg_unknown(struct bpf_verifier_env *env,
2496 struct bpf_reg_state *regs, u32 regno)
2497 {
2498 if (WARN_ON(regno >= MAX_BPF_REG)) {
2499 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2500 /* Something bad happened, let's kill all regs except FP */
2501 for (regno = 0; regno < BPF_REG_FP; regno++)
2502 __mark_reg_not_init(env, regs + regno);
2503 return;
2504 }
2505 __mark_reg_unknown(env, regs + regno);
2506 }
2507
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)2508 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2509 struct bpf_reg_state *reg)
2510 {
2511 __mark_reg_unknown(env, reg);
2512 reg->type = NOT_INIT;
2513 }
2514
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)2515 static void mark_reg_not_init(struct bpf_verifier_env *env,
2516 struct bpf_reg_state *regs, u32 regno)
2517 {
2518 if (WARN_ON(regno >= MAX_BPF_REG)) {
2519 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2520 /* Something bad happened, let's kill all regs except FP */
2521 for (regno = 0; regno < BPF_REG_FP; regno++)
2522 __mark_reg_not_init(env, regs + regno);
2523 return;
2524 }
2525 __mark_reg_not_init(env, regs + regno);
2526 }
2527
mark_btf_ld_reg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum bpf_reg_type reg_type,struct btf * btf,u32 btf_id,enum bpf_type_flag flag)2528 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2529 struct bpf_reg_state *regs, u32 regno,
2530 enum bpf_reg_type reg_type,
2531 struct btf *btf, u32 btf_id,
2532 enum bpf_type_flag flag)
2533 {
2534 if (reg_type == SCALAR_VALUE) {
2535 mark_reg_unknown(env, regs, regno);
2536 return;
2537 }
2538 mark_reg_known_zero(env, regs, regno);
2539 regs[regno].type = PTR_TO_BTF_ID | flag;
2540 regs[regno].btf = btf;
2541 regs[regno].btf_id = btf_id;
2542 if (type_may_be_null(flag))
2543 regs[regno].id = ++env->id_gen;
2544 }
2545
2546 #define DEF_NOT_SUBREG (0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)2547 static void init_reg_state(struct bpf_verifier_env *env,
2548 struct bpf_func_state *state)
2549 {
2550 struct bpf_reg_state *regs = state->regs;
2551 int i;
2552
2553 for (i = 0; i < MAX_BPF_REG; i++) {
2554 mark_reg_not_init(env, regs, i);
2555 regs[i].live = REG_LIVE_NONE;
2556 regs[i].parent = NULL;
2557 regs[i].subreg_def = DEF_NOT_SUBREG;
2558 }
2559
2560 /* frame pointer */
2561 regs[BPF_REG_FP].type = PTR_TO_STACK;
2562 mark_reg_known_zero(env, regs, BPF_REG_FP);
2563 regs[BPF_REG_FP].frameno = state->frameno;
2564 }
2565
2566 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)2567 static void init_func_state(struct bpf_verifier_env *env,
2568 struct bpf_func_state *state,
2569 int callsite, int frameno, int subprogno)
2570 {
2571 state->callsite = callsite;
2572 state->frameno = frameno;
2573 state->subprogno = subprogno;
2574 state->callback_ret_range = tnum_range(0, 0);
2575 init_reg_state(env, state);
2576 mark_verifier_state_scratched(env);
2577 }
2578
2579 /* Similar to push_stack(), but for async callbacks */
push_async_cb(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,int subprog)2580 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2581 int insn_idx, int prev_insn_idx,
2582 int subprog)
2583 {
2584 struct bpf_verifier_stack_elem *elem;
2585 struct bpf_func_state *frame;
2586
2587 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2588 if (!elem)
2589 goto err;
2590
2591 elem->insn_idx = insn_idx;
2592 elem->prev_insn_idx = prev_insn_idx;
2593 elem->next = env->head;
2594 elem->log_pos = env->log.end_pos;
2595 env->head = elem;
2596 env->stack_size++;
2597 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2598 verbose(env,
2599 "The sequence of %d jumps is too complex for async cb.\n",
2600 env->stack_size);
2601 goto err;
2602 }
2603 /* Unlike push_stack() do not copy_verifier_state().
2604 * The caller state doesn't matter.
2605 * This is async callback. It starts in a fresh stack.
2606 * Initialize it similar to do_check_common().
2607 */
2608 elem->st.branches = 1;
2609 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2610 if (!frame)
2611 goto err;
2612 init_func_state(env, frame,
2613 BPF_MAIN_FUNC /* callsite */,
2614 0 /* frameno within this callchain */,
2615 subprog /* subprog number within this prog */);
2616 elem->st.frame[0] = frame;
2617 return &elem->st;
2618 err:
2619 free_verifier_state(env->cur_state, true);
2620 env->cur_state = NULL;
2621 /* pop all elements and return */
2622 while (!pop_stack(env, NULL, NULL, false));
2623 return NULL;
2624 }
2625
2626
2627 enum reg_arg_type {
2628 SRC_OP, /* register is used as source operand */
2629 DST_OP, /* register is used as destination operand */
2630 DST_OP_NO_MARK /* same as above, check only, don't mark */
2631 };
2632
cmp_subprogs(const void * a,const void * b)2633 static int cmp_subprogs(const void *a, const void *b)
2634 {
2635 return ((struct bpf_subprog_info *)a)->start -
2636 ((struct bpf_subprog_info *)b)->start;
2637 }
2638
find_subprog(struct bpf_verifier_env * env,int off)2639 static int find_subprog(struct bpf_verifier_env *env, int off)
2640 {
2641 struct bpf_subprog_info *p;
2642
2643 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2644 sizeof(env->subprog_info[0]), cmp_subprogs);
2645 if (!p)
2646 return -ENOENT;
2647 return p - env->subprog_info;
2648
2649 }
2650
add_subprog(struct bpf_verifier_env * env,int off)2651 static int add_subprog(struct bpf_verifier_env *env, int off)
2652 {
2653 int insn_cnt = env->prog->len;
2654 int ret;
2655
2656 if (off >= insn_cnt || off < 0) {
2657 verbose(env, "call to invalid destination\n");
2658 return -EINVAL;
2659 }
2660 ret = find_subprog(env, off);
2661 if (ret >= 0)
2662 return ret;
2663 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2664 verbose(env, "too many subprograms\n");
2665 return -E2BIG;
2666 }
2667 /* determine subprog starts. The end is one before the next starts */
2668 env->subprog_info[env->subprog_cnt++].start = off;
2669 sort(env->subprog_info, env->subprog_cnt,
2670 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2671 return env->subprog_cnt - 1;
2672 }
2673
2674 #define MAX_KFUNC_DESCS 256
2675 #define MAX_KFUNC_BTFS 256
2676
2677 struct bpf_kfunc_desc {
2678 struct btf_func_model func_model;
2679 u32 func_id;
2680 s32 imm;
2681 u16 offset;
2682 unsigned long addr;
2683 };
2684
2685 struct bpf_kfunc_btf {
2686 struct btf *btf;
2687 struct module *module;
2688 u16 offset;
2689 };
2690
2691 struct bpf_kfunc_desc_tab {
2692 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2693 * verification. JITs do lookups by bpf_insn, where func_id may not be
2694 * available, therefore at the end of verification do_misc_fixups()
2695 * sorts this by imm and offset.
2696 */
2697 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2698 u32 nr_descs;
2699 };
2700
2701 struct bpf_kfunc_btf_tab {
2702 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2703 u32 nr_descs;
2704 };
2705
kfunc_desc_cmp_by_id_off(const void * a,const void * b)2706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2707 {
2708 const struct bpf_kfunc_desc *d0 = a;
2709 const struct bpf_kfunc_desc *d1 = b;
2710
2711 /* func_id is not greater than BTF_MAX_TYPE */
2712 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2713 }
2714
kfunc_btf_cmp_by_off(const void * a,const void * b)2715 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2716 {
2717 const struct bpf_kfunc_btf *d0 = a;
2718 const struct bpf_kfunc_btf *d1 = b;
2719
2720 return d0->offset - d1->offset;
2721 }
2722
2723 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)2724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2725 {
2726 struct bpf_kfunc_desc desc = {
2727 .func_id = func_id,
2728 .offset = offset,
2729 };
2730 struct bpf_kfunc_desc_tab *tab;
2731
2732 tab = prog->aux->kfunc_tab;
2733 return bsearch(&desc, tab->descs, tab->nr_descs,
2734 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2735 }
2736
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)2737 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2738 u16 btf_fd_idx, u8 **func_addr)
2739 {
2740 const struct bpf_kfunc_desc *desc;
2741
2742 desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2743 if (!desc)
2744 return -EFAULT;
2745
2746 *func_addr = (u8 *)desc->addr;
2747 return 0;
2748 }
2749
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2750 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2751 s16 offset)
2752 {
2753 struct bpf_kfunc_btf kf_btf = { .offset = offset };
2754 struct bpf_kfunc_btf_tab *tab;
2755 struct bpf_kfunc_btf *b;
2756 struct module *mod;
2757 struct btf *btf;
2758 int btf_fd;
2759
2760 tab = env->prog->aux->kfunc_btf_tab;
2761 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2762 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2763 if (!b) {
2764 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2765 verbose(env, "too many different module BTFs\n");
2766 return ERR_PTR(-E2BIG);
2767 }
2768
2769 if (bpfptr_is_null(env->fd_array)) {
2770 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2771 return ERR_PTR(-EPROTO);
2772 }
2773
2774 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2775 offset * sizeof(btf_fd),
2776 sizeof(btf_fd)))
2777 return ERR_PTR(-EFAULT);
2778
2779 btf = btf_get_by_fd(btf_fd);
2780 if (IS_ERR(btf)) {
2781 verbose(env, "invalid module BTF fd specified\n");
2782 return btf;
2783 }
2784
2785 if (!btf_is_module(btf)) {
2786 verbose(env, "BTF fd for kfunc is not a module BTF\n");
2787 btf_put(btf);
2788 return ERR_PTR(-EINVAL);
2789 }
2790
2791 mod = btf_try_get_module(btf);
2792 if (!mod) {
2793 btf_put(btf);
2794 return ERR_PTR(-ENXIO);
2795 }
2796
2797 b = &tab->descs[tab->nr_descs++];
2798 b->btf = btf;
2799 b->module = mod;
2800 b->offset = offset;
2801
2802 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2803 kfunc_btf_cmp_by_off, NULL);
2804 }
2805 return b->btf;
2806 }
2807
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)2808 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2809 {
2810 if (!tab)
2811 return;
2812
2813 while (tab->nr_descs--) {
2814 module_put(tab->descs[tab->nr_descs].module);
2815 btf_put(tab->descs[tab->nr_descs].btf);
2816 }
2817 kfree(tab);
2818 }
2819
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2820 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2821 {
2822 if (offset) {
2823 if (offset < 0) {
2824 /* In the future, this can be allowed to increase limit
2825 * of fd index into fd_array, interpreted as u16.
2826 */
2827 verbose(env, "negative offset disallowed for kernel module function call\n");
2828 return ERR_PTR(-EINVAL);
2829 }
2830
2831 return __find_kfunc_desc_btf(env, offset);
2832 }
2833 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2834 }
2835
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2836 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2837 {
2838 const struct btf_type *func, *func_proto;
2839 struct bpf_kfunc_btf_tab *btf_tab;
2840 struct bpf_kfunc_desc_tab *tab;
2841 struct bpf_prog_aux *prog_aux;
2842 struct bpf_kfunc_desc *desc;
2843 const char *func_name;
2844 struct btf *desc_btf;
2845 unsigned long call_imm;
2846 unsigned long addr;
2847 int err;
2848
2849 prog_aux = env->prog->aux;
2850 tab = prog_aux->kfunc_tab;
2851 btf_tab = prog_aux->kfunc_btf_tab;
2852 if (!tab) {
2853 if (!btf_vmlinux) {
2854 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2855 return -ENOTSUPP;
2856 }
2857
2858 if (!env->prog->jit_requested) {
2859 verbose(env, "JIT is required for calling kernel function\n");
2860 return -ENOTSUPP;
2861 }
2862
2863 if (!bpf_jit_supports_kfunc_call()) {
2864 verbose(env, "JIT does not support calling kernel function\n");
2865 return -ENOTSUPP;
2866 }
2867
2868 if (!env->prog->gpl_compatible) {
2869 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2870 return -EINVAL;
2871 }
2872
2873 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2874 if (!tab)
2875 return -ENOMEM;
2876 prog_aux->kfunc_tab = tab;
2877 }
2878
2879 /* func_id == 0 is always invalid, but instead of returning an error, be
2880 * conservative and wait until the code elimination pass before returning
2881 * error, so that invalid calls that get pruned out can be in BPF programs
2882 * loaded from userspace. It is also required that offset be untouched
2883 * for such calls.
2884 */
2885 if (!func_id && !offset)
2886 return 0;
2887
2888 if (!btf_tab && offset) {
2889 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2890 if (!btf_tab)
2891 return -ENOMEM;
2892 prog_aux->kfunc_btf_tab = btf_tab;
2893 }
2894
2895 desc_btf = find_kfunc_desc_btf(env, offset);
2896 if (IS_ERR(desc_btf)) {
2897 verbose(env, "failed to find BTF for kernel function\n");
2898 return PTR_ERR(desc_btf);
2899 }
2900
2901 if (find_kfunc_desc(env->prog, func_id, offset))
2902 return 0;
2903
2904 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2905 verbose(env, "too many different kernel function calls\n");
2906 return -E2BIG;
2907 }
2908
2909 func = btf_type_by_id(desc_btf, func_id);
2910 if (!func || !btf_type_is_func(func)) {
2911 verbose(env, "kernel btf_id %u is not a function\n",
2912 func_id);
2913 return -EINVAL;
2914 }
2915 func_proto = btf_type_by_id(desc_btf, func->type);
2916 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2917 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2918 func_id);
2919 return -EINVAL;
2920 }
2921
2922 func_name = btf_name_by_offset(desc_btf, func->name_off);
2923 addr = kallsyms_lookup_name(func_name);
2924 if (!addr) {
2925 verbose(env, "cannot find address for kernel function %s\n",
2926 func_name);
2927 return -EINVAL;
2928 }
2929 specialize_kfunc(env, func_id, offset, &addr);
2930
2931 if (bpf_jit_supports_far_kfunc_call()) {
2932 call_imm = func_id;
2933 } else {
2934 call_imm = BPF_CALL_IMM(addr);
2935 /* Check whether the relative offset overflows desc->imm */
2936 if ((unsigned long)(s32)call_imm != call_imm) {
2937 verbose(env, "address of kernel function %s is out of range\n",
2938 func_name);
2939 return -EINVAL;
2940 }
2941 }
2942
2943 if (bpf_dev_bound_kfunc_id(func_id)) {
2944 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2945 if (err)
2946 return err;
2947 }
2948
2949 desc = &tab->descs[tab->nr_descs++];
2950 desc->func_id = func_id;
2951 desc->imm = call_imm;
2952 desc->offset = offset;
2953 desc->addr = addr;
2954 err = btf_distill_func_proto(&env->log, desc_btf,
2955 func_proto, func_name,
2956 &desc->func_model);
2957 if (!err)
2958 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2959 kfunc_desc_cmp_by_id_off, NULL);
2960 return err;
2961 }
2962
kfunc_desc_cmp_by_imm_off(const void * a,const void * b)2963 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2964 {
2965 const struct bpf_kfunc_desc *d0 = a;
2966 const struct bpf_kfunc_desc *d1 = b;
2967
2968 if (d0->imm != d1->imm)
2969 return d0->imm < d1->imm ? -1 : 1;
2970 if (d0->offset != d1->offset)
2971 return d0->offset < d1->offset ? -1 : 1;
2972 return 0;
2973 }
2974
sort_kfunc_descs_by_imm_off(struct bpf_prog * prog)2975 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2976 {
2977 struct bpf_kfunc_desc_tab *tab;
2978
2979 tab = prog->aux->kfunc_tab;
2980 if (!tab)
2981 return;
2982
2983 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2984 kfunc_desc_cmp_by_imm_off, NULL);
2985 }
2986
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)2987 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2988 {
2989 return !!prog->aux->kfunc_tab;
2990 }
2991
2992 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)2993 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2994 const struct bpf_insn *insn)
2995 {
2996 const struct bpf_kfunc_desc desc = {
2997 .imm = insn->imm,
2998 .offset = insn->off,
2999 };
3000 const struct bpf_kfunc_desc *res;
3001 struct bpf_kfunc_desc_tab *tab;
3002
3003 tab = prog->aux->kfunc_tab;
3004 res = bsearch(&desc, tab->descs, tab->nr_descs,
3005 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3006
3007 return res ? &res->func_model : NULL;
3008 }
3009
add_subprog_and_kfunc(struct bpf_verifier_env * env)3010 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3011 {
3012 struct bpf_subprog_info *subprog = env->subprog_info;
3013 struct bpf_insn *insn = env->prog->insnsi;
3014 int i, ret, insn_cnt = env->prog->len;
3015
3016 /* Add entry function. */
3017 ret = add_subprog(env, 0);
3018 if (ret)
3019 return ret;
3020
3021 for (i = 0; i < insn_cnt; i++, insn++) {
3022 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3023 !bpf_pseudo_kfunc_call(insn))
3024 continue;
3025
3026 if (!env->bpf_capable) {
3027 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3028 return -EPERM;
3029 }
3030
3031 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3032 ret = add_subprog(env, i + insn->imm + 1);
3033 else
3034 ret = add_kfunc_call(env, insn->imm, insn->off);
3035
3036 if (ret < 0)
3037 return ret;
3038 }
3039
3040 /* Add a fake 'exit' subprog which could simplify subprog iteration
3041 * logic. 'subprog_cnt' should not be increased.
3042 */
3043 subprog[env->subprog_cnt].start = insn_cnt;
3044
3045 if (env->log.level & BPF_LOG_LEVEL2)
3046 for (i = 0; i < env->subprog_cnt; i++)
3047 verbose(env, "func#%d @%d\n", i, subprog[i].start);
3048
3049 return 0;
3050 }
3051
check_subprogs(struct bpf_verifier_env * env)3052 static int check_subprogs(struct bpf_verifier_env *env)
3053 {
3054 int i, subprog_start, subprog_end, off, cur_subprog = 0;
3055 struct bpf_subprog_info *subprog = env->subprog_info;
3056 struct bpf_insn *insn = env->prog->insnsi;
3057 int insn_cnt = env->prog->len;
3058
3059 /* now check that all jumps are within the same subprog */
3060 subprog_start = subprog[cur_subprog].start;
3061 subprog_end = subprog[cur_subprog + 1].start;
3062 for (i = 0; i < insn_cnt; i++) {
3063 u8 code = insn[i].code;
3064
3065 if (code == (BPF_JMP | BPF_CALL) &&
3066 insn[i].src_reg == 0 &&
3067 insn[i].imm == BPF_FUNC_tail_call)
3068 subprog[cur_subprog].has_tail_call = true;
3069 if (BPF_CLASS(code) == BPF_LD &&
3070 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3071 subprog[cur_subprog].has_ld_abs = true;
3072 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3073 goto next;
3074 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3075 goto next;
3076 if (code == (BPF_JMP32 | BPF_JA))
3077 off = i + insn[i].imm + 1;
3078 else
3079 off = i + insn[i].off + 1;
3080 if (off < subprog_start || off >= subprog_end) {
3081 verbose(env, "jump out of range from insn %d to %d\n", i, off);
3082 return -EINVAL;
3083 }
3084 next:
3085 if (i == subprog_end - 1) {
3086 /* to avoid fall-through from one subprog into another
3087 * the last insn of the subprog should be either exit
3088 * or unconditional jump back
3089 */
3090 if (code != (BPF_JMP | BPF_EXIT) &&
3091 code != (BPF_JMP32 | BPF_JA) &&
3092 code != (BPF_JMP | BPF_JA)) {
3093 verbose(env, "last insn is not an exit or jmp\n");
3094 return -EINVAL;
3095 }
3096 subprog_start = subprog_end;
3097 cur_subprog++;
3098 if (cur_subprog < env->subprog_cnt)
3099 subprog_end = subprog[cur_subprog + 1].start;
3100 }
3101 }
3102 return 0;
3103 }
3104
3105 /* Parentage chain of this register (or stack slot) should take care of all
3106 * issues like callee-saved registers, stack slot allocation time, etc.
3107 */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)3108 static int mark_reg_read(struct bpf_verifier_env *env,
3109 const struct bpf_reg_state *state,
3110 struct bpf_reg_state *parent, u8 flag)
3111 {
3112 bool writes = parent == state->parent; /* Observe write marks */
3113 int cnt = 0;
3114
3115 while (parent) {
3116 /* if read wasn't screened by an earlier write ... */
3117 if (writes && state->live & REG_LIVE_WRITTEN)
3118 break;
3119 if (parent->live & REG_LIVE_DONE) {
3120 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3121 reg_type_str(env, parent->type),
3122 parent->var_off.value, parent->off);
3123 return -EFAULT;
3124 }
3125 /* The first condition is more likely to be true than the
3126 * second, checked it first.
3127 */
3128 if ((parent->live & REG_LIVE_READ) == flag ||
3129 parent->live & REG_LIVE_READ64)
3130 /* The parentage chain never changes and
3131 * this parent was already marked as LIVE_READ.
3132 * There is no need to keep walking the chain again and
3133 * keep re-marking all parents as LIVE_READ.
3134 * This case happens when the same register is read
3135 * multiple times without writes into it in-between.
3136 * Also, if parent has the stronger REG_LIVE_READ64 set,
3137 * then no need to set the weak REG_LIVE_READ32.
3138 */
3139 break;
3140 /* ... then we depend on parent's value */
3141 parent->live |= flag;
3142 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3143 if (flag == REG_LIVE_READ64)
3144 parent->live &= ~REG_LIVE_READ32;
3145 state = parent;
3146 parent = state->parent;
3147 writes = true;
3148 cnt++;
3149 }
3150
3151 if (env->longest_mark_read_walk < cnt)
3152 env->longest_mark_read_walk = cnt;
3153 return 0;
3154 }
3155
mark_dynptr_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3156 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3157 {
3158 struct bpf_func_state *state = func(env, reg);
3159 int spi, ret;
3160
3161 /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3162 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3163 * check_kfunc_call.
3164 */
3165 if (reg->type == CONST_PTR_TO_DYNPTR)
3166 return 0;
3167 spi = dynptr_get_spi(env, reg);
3168 if (spi < 0)
3169 return spi;
3170 /* Caller ensures dynptr is valid and initialized, which means spi is in
3171 * bounds and spi is the first dynptr slot. Simply mark stack slot as
3172 * read.
3173 */
3174 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3175 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3176 if (ret)
3177 return ret;
3178 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3179 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3180 }
3181
mark_iter_read(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi,int nr_slots)3182 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3183 int spi, int nr_slots)
3184 {
3185 struct bpf_func_state *state = func(env, reg);
3186 int err, i;
3187
3188 for (i = 0; i < nr_slots; i++) {
3189 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3190
3191 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3192 if (err)
3193 return err;
3194
3195 mark_stack_slot_scratched(env, spi - i);
3196 }
3197
3198 return 0;
3199 }
3200
3201 /* This function is supposed to be used by the following 32-bit optimization
3202 * code only. It returns TRUE if the source or destination register operates
3203 * on 64-bit, otherwise return FALSE.
3204 */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)3205 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3206 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3207 {
3208 u8 code, class, op;
3209
3210 code = insn->code;
3211 class = BPF_CLASS(code);
3212 op = BPF_OP(code);
3213 if (class == BPF_JMP) {
3214 /* BPF_EXIT for "main" will reach here. Return TRUE
3215 * conservatively.
3216 */
3217 if (op == BPF_EXIT)
3218 return true;
3219 if (op == BPF_CALL) {
3220 /* BPF to BPF call will reach here because of marking
3221 * caller saved clobber with DST_OP_NO_MARK for which we
3222 * don't care the register def because they are anyway
3223 * marked as NOT_INIT already.
3224 */
3225 if (insn->src_reg == BPF_PSEUDO_CALL)
3226 return false;
3227 /* Helper call will reach here because of arg type
3228 * check, conservatively return TRUE.
3229 */
3230 if (t == SRC_OP)
3231 return true;
3232
3233 return false;
3234 }
3235 }
3236
3237 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3238 return false;
3239
3240 if (class == BPF_ALU64 || class == BPF_JMP ||
3241 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3242 return true;
3243
3244 if (class == BPF_ALU || class == BPF_JMP32)
3245 return false;
3246
3247 if (class == BPF_LDX) {
3248 if (t != SRC_OP)
3249 return BPF_SIZE(code) == BPF_DW;
3250 /* LDX source must be ptr. */
3251 return true;
3252 }
3253
3254 if (class == BPF_STX) {
3255 /* BPF_STX (including atomic variants) has multiple source
3256 * operands, one of which is a ptr. Check whether the caller is
3257 * asking about it.
3258 */
3259 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3260 return true;
3261 return BPF_SIZE(code) == BPF_DW;
3262 }
3263
3264 if (class == BPF_LD) {
3265 u8 mode = BPF_MODE(code);
3266
3267 /* LD_IMM64 */
3268 if (mode == BPF_IMM)
3269 return true;
3270
3271 /* Both LD_IND and LD_ABS return 32-bit data. */
3272 if (t != SRC_OP)
3273 return false;
3274
3275 /* Implicit ctx ptr. */
3276 if (regno == BPF_REG_6)
3277 return true;
3278
3279 /* Explicit source could be any width. */
3280 return true;
3281 }
3282
3283 if (class == BPF_ST)
3284 /* The only source register for BPF_ST is a ptr. */
3285 return true;
3286
3287 /* Conservatively return true at default. */
3288 return true;
3289 }
3290
3291 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)3292 static int insn_def_regno(const struct bpf_insn *insn)
3293 {
3294 switch (BPF_CLASS(insn->code)) {
3295 case BPF_JMP:
3296 case BPF_JMP32:
3297 case BPF_ST:
3298 return -1;
3299 case BPF_STX:
3300 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3301 (insn->imm & BPF_FETCH)) {
3302 if (insn->imm == BPF_CMPXCHG)
3303 return BPF_REG_0;
3304 else
3305 return insn->src_reg;
3306 } else {
3307 return -1;
3308 }
3309 default:
3310 return insn->dst_reg;
3311 }
3312 }
3313
3314 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)3315 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3316 {
3317 int dst_reg = insn_def_regno(insn);
3318
3319 if (dst_reg == -1)
3320 return false;
3321
3322 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3323 }
3324
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)3325 static void mark_insn_zext(struct bpf_verifier_env *env,
3326 struct bpf_reg_state *reg)
3327 {
3328 s32 def_idx = reg->subreg_def;
3329
3330 if (def_idx == DEF_NOT_SUBREG)
3331 return;
3332
3333 env->insn_aux_data[def_idx - 1].zext_dst = true;
3334 /* The dst will be zero extended, so won't be sub-register anymore. */
3335 reg->subreg_def = DEF_NOT_SUBREG;
3336 }
3337
__check_reg_arg(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno,enum reg_arg_type t)3338 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno,
3339 enum reg_arg_type t)
3340 {
3341 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3342 struct bpf_reg_state *reg;
3343 bool rw64;
3344
3345 if (regno >= MAX_BPF_REG) {
3346 verbose(env, "R%d is invalid\n", regno);
3347 return -EINVAL;
3348 }
3349
3350 mark_reg_scratched(env, regno);
3351
3352 reg = ®s[regno];
3353 rw64 = is_reg64(env, insn, regno, reg, t);
3354 if (t == SRC_OP) {
3355 /* check whether register used as source operand can be read */
3356 if (reg->type == NOT_INIT) {
3357 verbose(env, "R%d !read_ok\n", regno);
3358 return -EACCES;
3359 }
3360 /* We don't need to worry about FP liveness because it's read-only */
3361 if (regno == BPF_REG_FP)
3362 return 0;
3363
3364 if (rw64)
3365 mark_insn_zext(env, reg);
3366
3367 return mark_reg_read(env, reg, reg->parent,
3368 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3369 } else {
3370 /* check whether register used as dest operand can be written to */
3371 if (regno == BPF_REG_FP) {
3372 verbose(env, "frame pointer is read only\n");
3373 return -EACCES;
3374 }
3375 reg->live |= REG_LIVE_WRITTEN;
3376 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3377 if (t == DST_OP)
3378 mark_reg_unknown(env, regs, regno);
3379 }
3380 return 0;
3381 }
3382
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)3383 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3384 enum reg_arg_type t)
3385 {
3386 struct bpf_verifier_state *vstate = env->cur_state;
3387 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3388
3389 return __check_reg_arg(env, state->regs, regno, t);
3390 }
3391
mark_jmp_point(struct bpf_verifier_env * env,int idx)3392 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3393 {
3394 env->insn_aux_data[idx].jmp_point = true;
3395 }
3396
is_jmp_point(struct bpf_verifier_env * env,int insn_idx)3397 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3398 {
3399 return env->insn_aux_data[insn_idx].jmp_point;
3400 }
3401
3402 /* for any branch, call, exit record the history of jmps in the given state */
push_jmp_history(struct bpf_verifier_env * env,struct bpf_verifier_state * cur)3403 static int push_jmp_history(struct bpf_verifier_env *env,
3404 struct bpf_verifier_state *cur)
3405 {
3406 u32 cnt = cur->jmp_history_cnt;
3407 struct bpf_idx_pair *p;
3408 size_t alloc_size;
3409
3410 if (!is_jmp_point(env, env->insn_idx))
3411 return 0;
3412
3413 cnt++;
3414 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3415 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3416 if (!p)
3417 return -ENOMEM;
3418 p[cnt - 1].idx = env->insn_idx;
3419 p[cnt - 1].prev_idx = env->prev_insn_idx;
3420 cur->jmp_history = p;
3421 cur->jmp_history_cnt = cnt;
3422 return 0;
3423 }
3424
3425 /* Backtrack one insn at a time. If idx is not at the top of recorded
3426 * history then previous instruction came from straight line execution.
3427 * Return -ENOENT if we exhausted all instructions within given state.
3428 *
3429 * It's legal to have a bit of a looping with the same starting and ending
3430 * insn index within the same state, e.g.: 3->4->5->3, so just because current
3431 * instruction index is the same as state's first_idx doesn't mean we are
3432 * done. If there is still some jump history left, we should keep going. We
3433 * need to take into account that we might have a jump history between given
3434 * state's parent and itself, due to checkpointing. In this case, we'll have
3435 * history entry recording a jump from last instruction of parent state and
3436 * first instruction of given state.
3437 */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)3438 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3439 u32 *history)
3440 {
3441 u32 cnt = *history;
3442
3443 if (i == st->first_insn_idx) {
3444 if (cnt == 0)
3445 return -ENOENT;
3446 if (cnt == 1 && st->jmp_history[0].idx == i)
3447 return -ENOENT;
3448 }
3449
3450 if (cnt && st->jmp_history[cnt - 1].idx == i) {
3451 i = st->jmp_history[cnt - 1].prev_idx;
3452 (*history)--;
3453 } else {
3454 i--;
3455 }
3456 return i;
3457 }
3458
disasm_kfunc_name(void * data,const struct bpf_insn * insn)3459 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3460 {
3461 const struct btf_type *func;
3462 struct btf *desc_btf;
3463
3464 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3465 return NULL;
3466
3467 desc_btf = find_kfunc_desc_btf(data, insn->off);
3468 if (IS_ERR(desc_btf))
3469 return "<error>";
3470
3471 func = btf_type_by_id(desc_btf, insn->imm);
3472 return btf_name_by_offset(desc_btf, func->name_off);
3473 }
3474
bt_init(struct backtrack_state * bt,u32 frame)3475 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3476 {
3477 bt->frame = frame;
3478 }
3479
bt_reset(struct backtrack_state * bt)3480 static inline void bt_reset(struct backtrack_state *bt)
3481 {
3482 struct bpf_verifier_env *env = bt->env;
3483
3484 memset(bt, 0, sizeof(*bt));
3485 bt->env = env;
3486 }
3487
bt_empty(struct backtrack_state * bt)3488 static inline u32 bt_empty(struct backtrack_state *bt)
3489 {
3490 u64 mask = 0;
3491 int i;
3492
3493 for (i = 0; i <= bt->frame; i++)
3494 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3495
3496 return mask == 0;
3497 }
3498
bt_subprog_enter(struct backtrack_state * bt)3499 static inline int bt_subprog_enter(struct backtrack_state *bt)
3500 {
3501 if (bt->frame == MAX_CALL_FRAMES - 1) {
3502 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3503 WARN_ONCE(1, "verifier backtracking bug");
3504 return -EFAULT;
3505 }
3506 bt->frame++;
3507 return 0;
3508 }
3509
bt_subprog_exit(struct backtrack_state * bt)3510 static inline int bt_subprog_exit(struct backtrack_state *bt)
3511 {
3512 if (bt->frame == 0) {
3513 verbose(bt->env, "BUG subprog exit from frame 0\n");
3514 WARN_ONCE(1, "verifier backtracking bug");
3515 return -EFAULT;
3516 }
3517 bt->frame--;
3518 return 0;
3519 }
3520
bt_set_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3521 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3522 {
3523 bt->reg_masks[frame] |= 1 << reg;
3524 }
3525
bt_clear_frame_reg(struct backtrack_state * bt,u32 frame,u32 reg)3526 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3527 {
3528 bt->reg_masks[frame] &= ~(1 << reg);
3529 }
3530
bt_set_reg(struct backtrack_state * bt,u32 reg)3531 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3532 {
3533 bt_set_frame_reg(bt, bt->frame, reg);
3534 }
3535
bt_clear_reg(struct backtrack_state * bt,u32 reg)3536 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3537 {
3538 bt_clear_frame_reg(bt, bt->frame, reg);
3539 }
3540
bt_set_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3541 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3542 {
3543 bt->stack_masks[frame] |= 1ull << slot;
3544 }
3545
bt_clear_frame_slot(struct backtrack_state * bt,u32 frame,u32 slot)3546 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3547 {
3548 bt->stack_masks[frame] &= ~(1ull << slot);
3549 }
3550
bt_set_slot(struct backtrack_state * bt,u32 slot)3551 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3552 {
3553 bt_set_frame_slot(bt, bt->frame, slot);
3554 }
3555
bt_clear_slot(struct backtrack_state * bt,u32 slot)3556 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3557 {
3558 bt_clear_frame_slot(bt, bt->frame, slot);
3559 }
3560
bt_frame_reg_mask(struct backtrack_state * bt,u32 frame)3561 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3562 {
3563 return bt->reg_masks[frame];
3564 }
3565
bt_reg_mask(struct backtrack_state * bt)3566 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3567 {
3568 return bt->reg_masks[bt->frame];
3569 }
3570
bt_frame_stack_mask(struct backtrack_state * bt,u32 frame)3571 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3572 {
3573 return bt->stack_masks[frame];
3574 }
3575
bt_stack_mask(struct backtrack_state * bt)3576 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3577 {
3578 return bt->stack_masks[bt->frame];
3579 }
3580
bt_is_reg_set(struct backtrack_state * bt,u32 reg)3581 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3582 {
3583 return bt->reg_masks[bt->frame] & (1 << reg);
3584 }
3585
bt_is_slot_set(struct backtrack_state * bt,u32 slot)3586 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3587 {
3588 return bt->stack_masks[bt->frame] & (1ull << slot);
3589 }
3590
3591 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
fmt_reg_mask(char * buf,ssize_t buf_sz,u32 reg_mask)3592 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3593 {
3594 DECLARE_BITMAP(mask, 64);
3595 bool first = true;
3596 int i, n;
3597
3598 buf[0] = '\0';
3599
3600 bitmap_from_u64(mask, reg_mask);
3601 for_each_set_bit(i, mask, 32) {
3602 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3603 first = false;
3604 buf += n;
3605 buf_sz -= n;
3606 if (buf_sz < 0)
3607 break;
3608 }
3609 }
3610 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
fmt_stack_mask(char * buf,ssize_t buf_sz,u64 stack_mask)3611 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3612 {
3613 DECLARE_BITMAP(mask, 64);
3614 bool first = true;
3615 int i, n;
3616
3617 buf[0] = '\0';
3618
3619 bitmap_from_u64(mask, stack_mask);
3620 for_each_set_bit(i, mask, 64) {
3621 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3622 first = false;
3623 buf += n;
3624 buf_sz -= n;
3625 if (buf_sz < 0)
3626 break;
3627 }
3628 }
3629
3630 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx);
3631
3632 /* For given verifier state backtrack_insn() is called from the last insn to
3633 * the first insn. Its purpose is to compute a bitmask of registers and
3634 * stack slots that needs precision in the parent verifier state.
3635 *
3636 * @idx is an index of the instruction we are currently processing;
3637 * @subseq_idx is an index of the subsequent instruction that:
3638 * - *would be* executed next, if jump history is viewed in forward order;
3639 * - *was* processed previously during backtracking.
3640 */
backtrack_insn(struct bpf_verifier_env * env,int idx,int subseq_idx,struct backtrack_state * bt)3641 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3642 struct backtrack_state *bt)
3643 {
3644 const struct bpf_insn_cbs cbs = {
3645 .cb_call = disasm_kfunc_name,
3646 .cb_print = verbose,
3647 .private_data = env,
3648 };
3649 struct bpf_insn *insn = env->prog->insnsi + idx;
3650 u8 class = BPF_CLASS(insn->code);
3651 u8 opcode = BPF_OP(insn->code);
3652 u8 mode = BPF_MODE(insn->code);
3653 u32 dreg = insn->dst_reg;
3654 u32 sreg = insn->src_reg;
3655 u32 spi, i;
3656
3657 if (insn->code == 0)
3658 return 0;
3659 if (env->log.level & BPF_LOG_LEVEL2) {
3660 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3661 verbose(env, "mark_precise: frame%d: regs=%s ",
3662 bt->frame, env->tmp_str_buf);
3663 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3664 verbose(env, "stack=%s before ", env->tmp_str_buf);
3665 verbose(env, "%d: ", idx);
3666 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3667 }
3668
3669 if (class == BPF_ALU || class == BPF_ALU64) {
3670 if (!bt_is_reg_set(bt, dreg))
3671 return 0;
3672 if (opcode == BPF_END || opcode == BPF_NEG) {
3673 /* sreg is reserved and unused
3674 * dreg still need precision before this insn
3675 */
3676 return 0;
3677 } else if (opcode == BPF_MOV) {
3678 if (BPF_SRC(insn->code) == BPF_X) {
3679 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3680 * dreg needs precision after this insn
3681 * sreg needs precision before this insn
3682 */
3683 bt_clear_reg(bt, dreg);
3684 if (sreg != BPF_REG_FP)
3685 bt_set_reg(bt, sreg);
3686 } else {
3687 /* dreg = K
3688 * dreg needs precision after this insn.
3689 * Corresponding register is already marked
3690 * as precise=true in this verifier state.
3691 * No further markings in parent are necessary
3692 */
3693 bt_clear_reg(bt, dreg);
3694 }
3695 } else {
3696 if (BPF_SRC(insn->code) == BPF_X) {
3697 /* dreg += sreg
3698 * both dreg and sreg need precision
3699 * before this insn
3700 */
3701 if (sreg != BPF_REG_FP)
3702 bt_set_reg(bt, sreg);
3703 } /* else dreg += K
3704 * dreg still needs precision before this insn
3705 */
3706 }
3707 } else if (class == BPF_LDX) {
3708 if (!bt_is_reg_set(bt, dreg))
3709 return 0;
3710 bt_clear_reg(bt, dreg);
3711
3712 /* scalars can only be spilled into stack w/o losing precision.
3713 * Load from any other memory can be zero extended.
3714 * The desire to keep that precision is already indicated
3715 * by 'precise' mark in corresponding register of this state.
3716 * No further tracking necessary.
3717 */
3718 if (insn->src_reg != BPF_REG_FP)
3719 return 0;
3720
3721 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3722 * that [fp - off] slot contains scalar that needs to be
3723 * tracked with precision
3724 */
3725 spi = (-insn->off - 1) / BPF_REG_SIZE;
3726 if (spi >= 64) {
3727 verbose(env, "BUG spi %d\n", spi);
3728 WARN_ONCE(1, "verifier backtracking bug");
3729 return -EFAULT;
3730 }
3731 bt_set_slot(bt, spi);
3732 } else if (class == BPF_STX || class == BPF_ST) {
3733 if (bt_is_reg_set(bt, dreg))
3734 /* stx & st shouldn't be using _scalar_ dst_reg
3735 * to access memory. It means backtracking
3736 * encountered a case of pointer subtraction.
3737 */
3738 return -ENOTSUPP;
3739 /* scalars can only be spilled into stack */
3740 if (insn->dst_reg != BPF_REG_FP)
3741 return 0;
3742 spi = (-insn->off - 1) / BPF_REG_SIZE;
3743 if (spi >= 64) {
3744 verbose(env, "BUG spi %d\n", spi);
3745 WARN_ONCE(1, "verifier backtracking bug");
3746 return -EFAULT;
3747 }
3748 if (!bt_is_slot_set(bt, spi))
3749 return 0;
3750 bt_clear_slot(bt, spi);
3751 if (class == BPF_STX)
3752 bt_set_reg(bt, sreg);
3753 } else if (class == BPF_JMP || class == BPF_JMP32) {
3754 if (bpf_pseudo_call(insn)) {
3755 int subprog_insn_idx, subprog;
3756
3757 subprog_insn_idx = idx + insn->imm + 1;
3758 subprog = find_subprog(env, subprog_insn_idx);
3759 if (subprog < 0)
3760 return -EFAULT;
3761
3762 if (subprog_is_global(env, subprog)) {
3763 /* check that jump history doesn't have any
3764 * extra instructions from subprog; the next
3765 * instruction after call to global subprog
3766 * should be literally next instruction in
3767 * caller program
3768 */
3769 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3770 /* r1-r5 are invalidated after subprog call,
3771 * so for global func call it shouldn't be set
3772 * anymore
3773 */
3774 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3775 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3776 WARN_ONCE(1, "verifier backtracking bug");
3777 return -EFAULT;
3778 }
3779 /* global subprog always sets R0 */
3780 bt_clear_reg(bt, BPF_REG_0);
3781 return 0;
3782 } else {
3783 /* static subprog call instruction, which
3784 * means that we are exiting current subprog,
3785 * so only r1-r5 could be still requested as
3786 * precise, r0 and r6-r10 or any stack slot in
3787 * the current frame should be zero by now
3788 */
3789 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3790 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3791 WARN_ONCE(1, "verifier backtracking bug");
3792 return -EFAULT;
3793 }
3794 /* we don't track register spills perfectly,
3795 * so fallback to force-precise instead of failing */
3796 if (bt_stack_mask(bt) != 0)
3797 return -ENOTSUPP;
3798 /* propagate r1-r5 to the caller */
3799 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3800 if (bt_is_reg_set(bt, i)) {
3801 bt_clear_reg(bt, i);
3802 bt_set_frame_reg(bt, bt->frame - 1, i);
3803 }
3804 }
3805 if (bt_subprog_exit(bt))
3806 return -EFAULT;
3807 return 0;
3808 }
3809 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) {
3810 /* exit from callback subprog to callback-calling helper or
3811 * kfunc call. Use idx/subseq_idx check to discern it from
3812 * straight line code backtracking.
3813 * Unlike the subprog call handling above, we shouldn't
3814 * propagate precision of r1-r5 (if any requested), as they are
3815 * not actually arguments passed directly to callback subprogs
3816 */
3817 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3818 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3819 WARN_ONCE(1, "verifier backtracking bug");
3820 return -EFAULT;
3821 }
3822 if (bt_stack_mask(bt) != 0)
3823 return -ENOTSUPP;
3824 /* clear r1-r5 in callback subprog's mask */
3825 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3826 bt_clear_reg(bt, i);
3827 if (bt_subprog_exit(bt))
3828 return -EFAULT;
3829 return 0;
3830 } else if (opcode == BPF_CALL) {
3831 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3832 * catch this error later. Make backtracking conservative
3833 * with ENOTSUPP.
3834 */
3835 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3836 return -ENOTSUPP;
3837 /* regular helper call sets R0 */
3838 bt_clear_reg(bt, BPF_REG_0);
3839 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3840 /* if backtracing was looking for registers R1-R5
3841 * they should have been found already.
3842 */
3843 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3844 WARN_ONCE(1, "verifier backtracking bug");
3845 return -EFAULT;
3846 }
3847 } else if (opcode == BPF_EXIT) {
3848 bool r0_precise;
3849
3850 /* Backtracking to a nested function call, 'idx' is a part of
3851 * the inner frame 'subseq_idx' is a part of the outer frame.
3852 * In case of a regular function call, instructions giving
3853 * precision to registers R1-R5 should have been found already.
3854 * In case of a callback, it is ok to have R1-R5 marked for
3855 * backtracking, as these registers are set by the function
3856 * invoking callback.
3857 */
3858 if (subseq_idx >= 0 && calls_callback(env, subseq_idx))
3859 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3860 bt_clear_reg(bt, i);
3861 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3862 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3863 WARN_ONCE(1, "verifier backtracking bug");
3864 return -EFAULT;
3865 }
3866
3867 /* BPF_EXIT in subprog or callback always returns
3868 * right after the call instruction, so by checking
3869 * whether the instruction at subseq_idx-1 is subprog
3870 * call or not we can distinguish actual exit from
3871 * *subprog* from exit from *callback*. In the former
3872 * case, we need to propagate r0 precision, if
3873 * necessary. In the former we never do that.
3874 */
3875 r0_precise = subseq_idx - 1 >= 0 &&
3876 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3877 bt_is_reg_set(bt, BPF_REG_0);
3878
3879 bt_clear_reg(bt, BPF_REG_0);
3880 if (bt_subprog_enter(bt))
3881 return -EFAULT;
3882
3883 if (r0_precise)
3884 bt_set_reg(bt, BPF_REG_0);
3885 /* r6-r9 and stack slots will stay set in caller frame
3886 * bitmasks until we return back from callee(s)
3887 */
3888 return 0;
3889 } else if (BPF_SRC(insn->code) == BPF_X) {
3890 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3891 return 0;
3892 /* dreg <cond> sreg
3893 * Both dreg and sreg need precision before
3894 * this insn. If only sreg was marked precise
3895 * before it would be equally necessary to
3896 * propagate it to dreg.
3897 */
3898 bt_set_reg(bt, dreg);
3899 bt_set_reg(bt, sreg);
3900 /* else dreg <cond> K
3901 * Only dreg still needs precision before
3902 * this insn, so for the K-based conditional
3903 * there is nothing new to be marked.
3904 */
3905 }
3906 } else if (class == BPF_LD) {
3907 if (!bt_is_reg_set(bt, dreg))
3908 return 0;
3909 bt_clear_reg(bt, dreg);
3910 /* It's ld_imm64 or ld_abs or ld_ind.
3911 * For ld_imm64 no further tracking of precision
3912 * into parent is necessary
3913 */
3914 if (mode == BPF_IND || mode == BPF_ABS)
3915 /* to be analyzed */
3916 return -ENOTSUPP;
3917 }
3918 return 0;
3919 }
3920
3921 /* the scalar precision tracking algorithm:
3922 * . at the start all registers have precise=false.
3923 * . scalar ranges are tracked as normal through alu and jmp insns.
3924 * . once precise value of the scalar register is used in:
3925 * . ptr + scalar alu
3926 * . if (scalar cond K|scalar)
3927 * . helper_call(.., scalar, ...) where ARG_CONST is expected
3928 * backtrack through the verifier states and mark all registers and
3929 * stack slots with spilled constants that these scalar regisers
3930 * should be precise.
3931 * . during state pruning two registers (or spilled stack slots)
3932 * are equivalent if both are not precise.
3933 *
3934 * Note the verifier cannot simply walk register parentage chain,
3935 * since many different registers and stack slots could have been
3936 * used to compute single precise scalar.
3937 *
3938 * The approach of starting with precise=true for all registers and then
3939 * backtrack to mark a register as not precise when the verifier detects
3940 * that program doesn't care about specific value (e.g., when helper
3941 * takes register as ARG_ANYTHING parameter) is not safe.
3942 *
3943 * It's ok to walk single parentage chain of the verifier states.
3944 * It's possible that this backtracking will go all the way till 1st insn.
3945 * All other branches will be explored for needing precision later.
3946 *
3947 * The backtracking needs to deal with cases like:
3948 * 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)
3949 * r9 -= r8
3950 * r5 = r9
3951 * if r5 > 0x79f goto pc+7
3952 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3953 * r5 += 1
3954 * ...
3955 * call bpf_perf_event_output#25
3956 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3957 *
3958 * and this case:
3959 * r6 = 1
3960 * call foo // uses callee's r6 inside to compute r0
3961 * r0 += r6
3962 * if r0 == 0 goto
3963 *
3964 * to track above reg_mask/stack_mask needs to be independent for each frame.
3965 *
3966 * Also if parent's curframe > frame where backtracking started,
3967 * the verifier need to mark registers in both frames, otherwise callees
3968 * may incorrectly prune callers. This is similar to
3969 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3970 *
3971 * For now backtracking falls back into conservative marking.
3972 */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)3973 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3974 struct bpf_verifier_state *st)
3975 {
3976 struct bpf_func_state *func;
3977 struct bpf_reg_state *reg;
3978 int i, j;
3979
3980 if (env->log.level & BPF_LOG_LEVEL2) {
3981 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3982 st->curframe);
3983 }
3984
3985 /* big hammer: mark all scalars precise in this path.
3986 * pop_stack may still get !precise scalars.
3987 * We also skip current state and go straight to first parent state,
3988 * because precision markings in current non-checkpointed state are
3989 * not needed. See why in the comment in __mark_chain_precision below.
3990 */
3991 for (st = st->parent; st; st = st->parent) {
3992 for (i = 0; i <= st->curframe; i++) {
3993 func = st->frame[i];
3994 for (j = 0; j < BPF_REG_FP; j++) {
3995 reg = &func->regs[j];
3996 if (reg->type != SCALAR_VALUE || reg->precise)
3997 continue;
3998 reg->precise = true;
3999 if (env->log.level & BPF_LOG_LEVEL2) {
4000 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4001 i, j);
4002 }
4003 }
4004 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4005 if (!is_spilled_reg(&func->stack[j]))
4006 continue;
4007 reg = &func->stack[j].spilled_ptr;
4008 if (reg->type != SCALAR_VALUE || reg->precise)
4009 continue;
4010 reg->precise = true;
4011 if (env->log.level & BPF_LOG_LEVEL2) {
4012 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4013 i, -(j + 1) * 8);
4014 }
4015 }
4016 }
4017 }
4018 }
4019
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4020 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4021 {
4022 struct bpf_func_state *func;
4023 struct bpf_reg_state *reg;
4024 int i, j;
4025
4026 for (i = 0; i <= st->curframe; i++) {
4027 func = st->frame[i];
4028 for (j = 0; j < BPF_REG_FP; j++) {
4029 reg = &func->regs[j];
4030 if (reg->type != SCALAR_VALUE)
4031 continue;
4032 reg->precise = false;
4033 }
4034 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4035 if (!is_spilled_reg(&func->stack[j]))
4036 continue;
4037 reg = &func->stack[j].spilled_ptr;
4038 if (reg->type != SCALAR_VALUE)
4039 continue;
4040 reg->precise = false;
4041 }
4042 }
4043 }
4044
idset_contains(struct bpf_idset * s,u32 id)4045 static bool idset_contains(struct bpf_idset *s, u32 id)
4046 {
4047 u32 i;
4048
4049 for (i = 0; i < s->count; ++i)
4050 if (s->ids[i] == id)
4051 return true;
4052
4053 return false;
4054 }
4055
idset_push(struct bpf_idset * s,u32 id)4056 static int idset_push(struct bpf_idset *s, u32 id)
4057 {
4058 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4059 return -EFAULT;
4060 s->ids[s->count++] = id;
4061 return 0;
4062 }
4063
idset_reset(struct bpf_idset * s)4064 static void idset_reset(struct bpf_idset *s)
4065 {
4066 s->count = 0;
4067 }
4068
4069 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4070 * Mark all registers with these IDs as precise.
4071 */
mark_precise_scalar_ids(struct bpf_verifier_env * env,struct bpf_verifier_state * st)4072 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4073 {
4074 struct bpf_idset *precise_ids = &env->idset_scratch;
4075 struct backtrack_state *bt = &env->bt;
4076 struct bpf_func_state *func;
4077 struct bpf_reg_state *reg;
4078 DECLARE_BITMAP(mask, 64);
4079 int i, fr;
4080
4081 idset_reset(precise_ids);
4082
4083 for (fr = bt->frame; fr >= 0; fr--) {
4084 func = st->frame[fr];
4085
4086 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4087 for_each_set_bit(i, mask, 32) {
4088 reg = &func->regs[i];
4089 if (!reg->id || reg->type != SCALAR_VALUE)
4090 continue;
4091 if (idset_push(precise_ids, reg->id))
4092 return -EFAULT;
4093 }
4094
4095 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4096 for_each_set_bit(i, mask, 64) {
4097 if (i >= func->allocated_stack / BPF_REG_SIZE)
4098 break;
4099 if (!is_spilled_scalar_reg(&func->stack[i]))
4100 continue;
4101 reg = &func->stack[i].spilled_ptr;
4102 if (!reg->id)
4103 continue;
4104 if (idset_push(precise_ids, reg->id))
4105 return -EFAULT;
4106 }
4107 }
4108
4109 for (fr = 0; fr <= st->curframe; ++fr) {
4110 func = st->frame[fr];
4111
4112 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4113 reg = &func->regs[i];
4114 if (!reg->id)
4115 continue;
4116 if (!idset_contains(precise_ids, reg->id))
4117 continue;
4118 bt_set_frame_reg(bt, fr, i);
4119 }
4120 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4121 if (!is_spilled_scalar_reg(&func->stack[i]))
4122 continue;
4123 reg = &func->stack[i].spilled_ptr;
4124 if (!reg->id)
4125 continue;
4126 if (!idset_contains(precise_ids, reg->id))
4127 continue;
4128 bt_set_frame_slot(bt, fr, i);
4129 }
4130 }
4131
4132 return 0;
4133 }
4134
4135 /*
4136 * __mark_chain_precision() backtracks BPF program instruction sequence and
4137 * chain of verifier states making sure that register *regno* (if regno >= 0)
4138 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4139 * SCALARS, as well as any other registers and slots that contribute to
4140 * a tracked state of given registers/stack slots, depending on specific BPF
4141 * assembly instructions (see backtrack_insns() for exact instruction handling
4142 * logic). This backtracking relies on recorded jmp_history and is able to
4143 * traverse entire chain of parent states. This process ends only when all the
4144 * necessary registers/slots and their transitive dependencies are marked as
4145 * precise.
4146 *
4147 * One important and subtle aspect is that precise marks *do not matter* in
4148 * the currently verified state (current state). It is important to understand
4149 * why this is the case.
4150 *
4151 * First, note that current state is the state that is not yet "checkpointed",
4152 * i.e., it is not yet put into env->explored_states, and it has no children
4153 * states as well. It's ephemeral, and can end up either a) being discarded if
4154 * compatible explored state is found at some point or BPF_EXIT instruction is
4155 * reached or b) checkpointed and put into env->explored_states, branching out
4156 * into one or more children states.
4157 *
4158 * In the former case, precise markings in current state are completely
4159 * ignored by state comparison code (see regsafe() for details). Only
4160 * checkpointed ("old") state precise markings are important, and if old
4161 * state's register/slot is precise, regsafe() assumes current state's
4162 * register/slot as precise and checks value ranges exactly and precisely. If
4163 * states turn out to be compatible, current state's necessary precise
4164 * markings and any required parent states' precise markings are enforced
4165 * after the fact with propagate_precision() logic, after the fact. But it's
4166 * important to realize that in this case, even after marking current state
4167 * registers/slots as precise, we immediately discard current state. So what
4168 * actually matters is any of the precise markings propagated into current
4169 * state's parent states, which are always checkpointed (due to b) case above).
4170 * As such, for scenario a) it doesn't matter if current state has precise
4171 * markings set or not.
4172 *
4173 * Now, for the scenario b), checkpointing and forking into child(ren)
4174 * state(s). Note that before current state gets to checkpointing step, any
4175 * processed instruction always assumes precise SCALAR register/slot
4176 * knowledge: if precise value or range is useful to prune jump branch, BPF
4177 * verifier takes this opportunity enthusiastically. Similarly, when
4178 * register's value is used to calculate offset or memory address, exact
4179 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4180 * what we mentioned above about state comparison ignoring precise markings
4181 * during state comparison, BPF verifier ignores and also assumes precise
4182 * markings *at will* during instruction verification process. But as verifier
4183 * assumes precision, it also propagates any precision dependencies across
4184 * parent states, which are not yet finalized, so can be further restricted
4185 * based on new knowledge gained from restrictions enforced by their children
4186 * states. This is so that once those parent states are finalized, i.e., when
4187 * they have no more active children state, state comparison logic in
4188 * is_state_visited() would enforce strict and precise SCALAR ranges, if
4189 * required for correctness.
4190 *
4191 * To build a bit more intuition, note also that once a state is checkpointed,
4192 * the path we took to get to that state is not important. This is crucial
4193 * property for state pruning. When state is checkpointed and finalized at
4194 * some instruction index, it can be correctly and safely used to "short
4195 * circuit" any *compatible* state that reaches exactly the same instruction
4196 * index. I.e., if we jumped to that instruction from a completely different
4197 * code path than original finalized state was derived from, it doesn't
4198 * matter, current state can be discarded because from that instruction
4199 * forward having a compatible state will ensure we will safely reach the
4200 * exit. States describe preconditions for further exploration, but completely
4201 * forget the history of how we got here.
4202 *
4203 * This also means that even if we needed precise SCALAR range to get to
4204 * finalized state, but from that point forward *that same* SCALAR register is
4205 * never used in a precise context (i.e., it's precise value is not needed for
4206 * correctness), it's correct and safe to mark such register as "imprecise"
4207 * (i.e., precise marking set to false). This is what we rely on when we do
4208 * not set precise marking in current state. If no child state requires
4209 * precision for any given SCALAR register, it's safe to dictate that it can
4210 * be imprecise. If any child state does require this register to be precise,
4211 * we'll mark it precise later retroactively during precise markings
4212 * propagation from child state to parent states.
4213 *
4214 * Skipping precise marking setting in current state is a mild version of
4215 * relying on the above observation. But we can utilize this property even
4216 * more aggressively by proactively forgetting any precise marking in the
4217 * current state (which we inherited from the parent state), right before we
4218 * checkpoint it and branch off into new child state. This is done by
4219 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4220 * finalized states which help in short circuiting more future states.
4221 */
__mark_chain_precision(struct bpf_verifier_env * env,int regno)4222 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4223 {
4224 struct backtrack_state *bt = &env->bt;
4225 struct bpf_verifier_state *st = env->cur_state;
4226 int first_idx = st->first_insn_idx;
4227 int last_idx = env->insn_idx;
4228 int subseq_idx = -1;
4229 struct bpf_func_state *func;
4230 struct bpf_reg_state *reg;
4231 bool skip_first = true;
4232 int i, fr, err;
4233
4234 if (!env->bpf_capable)
4235 return 0;
4236
4237 /* set frame number from which we are starting to backtrack */
4238 bt_init(bt, env->cur_state->curframe);
4239
4240 /* Do sanity checks against current state of register and/or stack
4241 * slot, but don't set precise flag in current state, as precision
4242 * tracking in the current state is unnecessary.
4243 */
4244 func = st->frame[bt->frame];
4245 if (regno >= 0) {
4246 reg = &func->regs[regno];
4247 if (reg->type != SCALAR_VALUE) {
4248 WARN_ONCE(1, "backtracing misuse");
4249 return -EFAULT;
4250 }
4251 bt_set_reg(bt, regno);
4252 }
4253
4254 if (bt_empty(bt))
4255 return 0;
4256
4257 for (;;) {
4258 DECLARE_BITMAP(mask, 64);
4259 u32 history = st->jmp_history_cnt;
4260
4261 if (env->log.level & BPF_LOG_LEVEL2) {
4262 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4263 bt->frame, last_idx, first_idx, subseq_idx);
4264 }
4265
4266 /* If some register with scalar ID is marked as precise,
4267 * make sure that all registers sharing this ID are also precise.
4268 * This is needed to estimate effect of find_equal_scalars().
4269 * Do this at the last instruction of each state,
4270 * bpf_reg_state::id fields are valid for these instructions.
4271 *
4272 * Allows to track precision in situation like below:
4273 *
4274 * r2 = unknown value
4275 * ...
4276 * --- state #0 ---
4277 * ...
4278 * r1 = r2 // r1 and r2 now share the same ID
4279 * ...
4280 * --- state #1 {r1.id = A, r2.id = A} ---
4281 * ...
4282 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4283 * ...
4284 * --- state #2 {r1.id = A, r2.id = A} ---
4285 * r3 = r10
4286 * r3 += r1 // need to mark both r1 and r2
4287 */
4288 if (mark_precise_scalar_ids(env, st))
4289 return -EFAULT;
4290
4291 if (last_idx < 0) {
4292 /* we are at the entry into subprog, which
4293 * is expected for global funcs, but only if
4294 * requested precise registers are R1-R5
4295 * (which are global func's input arguments)
4296 */
4297 if (st->curframe == 0 &&
4298 st->frame[0]->subprogno > 0 &&
4299 st->frame[0]->callsite == BPF_MAIN_FUNC &&
4300 bt_stack_mask(bt) == 0 &&
4301 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4302 bitmap_from_u64(mask, bt_reg_mask(bt));
4303 for_each_set_bit(i, mask, 32) {
4304 reg = &st->frame[0]->regs[i];
4305 bt_clear_reg(bt, i);
4306 if (reg->type == SCALAR_VALUE)
4307 reg->precise = true;
4308 }
4309 return 0;
4310 }
4311
4312 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4313 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4314 WARN_ONCE(1, "verifier backtracking bug");
4315 return -EFAULT;
4316 }
4317
4318 for (i = last_idx;;) {
4319 if (skip_first) {
4320 err = 0;
4321 skip_first = false;
4322 } else {
4323 err = backtrack_insn(env, i, subseq_idx, bt);
4324 }
4325 if (err == -ENOTSUPP) {
4326 mark_all_scalars_precise(env, env->cur_state);
4327 bt_reset(bt);
4328 return 0;
4329 } else if (err) {
4330 return err;
4331 }
4332 if (bt_empty(bt))
4333 /* Found assignment(s) into tracked register in this state.
4334 * Since this state is already marked, just return.
4335 * Nothing to be tracked further in the parent state.
4336 */
4337 return 0;
4338 subseq_idx = i;
4339 i = get_prev_insn_idx(st, i, &history);
4340 if (i == -ENOENT)
4341 break;
4342 if (i >= env->prog->len) {
4343 /* This can happen if backtracking reached insn 0
4344 * and there are still reg_mask or stack_mask
4345 * to backtrack.
4346 * It means the backtracking missed the spot where
4347 * particular register was initialized with a constant.
4348 */
4349 verbose(env, "BUG backtracking idx %d\n", i);
4350 WARN_ONCE(1, "verifier backtracking bug");
4351 return -EFAULT;
4352 }
4353 }
4354 st = st->parent;
4355 if (!st)
4356 break;
4357
4358 for (fr = bt->frame; fr >= 0; fr--) {
4359 func = st->frame[fr];
4360 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4361 for_each_set_bit(i, mask, 32) {
4362 reg = &func->regs[i];
4363 if (reg->type != SCALAR_VALUE) {
4364 bt_clear_frame_reg(bt, fr, i);
4365 continue;
4366 }
4367 if (reg->precise)
4368 bt_clear_frame_reg(bt, fr, i);
4369 else
4370 reg->precise = true;
4371 }
4372
4373 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4374 for_each_set_bit(i, mask, 64) {
4375 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4376 /* the sequence of instructions:
4377 * 2: (bf) r3 = r10
4378 * 3: (7b) *(u64 *)(r3 -8) = r0
4379 * 4: (79) r4 = *(u64 *)(r10 -8)
4380 * doesn't contain jmps. It's backtracked
4381 * as a single block.
4382 * During backtracking insn 3 is not recognized as
4383 * stack access, so at the end of backtracking
4384 * stack slot fp-8 is still marked in stack_mask.
4385 * However the parent state may not have accessed
4386 * fp-8 and it's "unallocated" stack space.
4387 * In such case fallback to conservative.
4388 */
4389 mark_all_scalars_precise(env, env->cur_state);
4390 bt_reset(bt);
4391 return 0;
4392 }
4393
4394 if (!is_spilled_scalar_reg(&func->stack[i])) {
4395 bt_clear_frame_slot(bt, fr, i);
4396 continue;
4397 }
4398 reg = &func->stack[i].spilled_ptr;
4399 if (reg->precise)
4400 bt_clear_frame_slot(bt, fr, i);
4401 else
4402 reg->precise = true;
4403 }
4404 if (env->log.level & BPF_LOG_LEVEL2) {
4405 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4406 bt_frame_reg_mask(bt, fr));
4407 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4408 fr, env->tmp_str_buf);
4409 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4410 bt_frame_stack_mask(bt, fr));
4411 verbose(env, "stack=%s: ", env->tmp_str_buf);
4412 print_verifier_state(env, func, true);
4413 }
4414 }
4415
4416 if (bt_empty(bt))
4417 return 0;
4418
4419 subseq_idx = first_idx;
4420 last_idx = st->last_insn_idx;
4421 first_idx = st->first_insn_idx;
4422 }
4423
4424 /* if we still have requested precise regs or slots, we missed
4425 * something (e.g., stack access through non-r10 register), so
4426 * fallback to marking all precise
4427 */
4428 if (!bt_empty(bt)) {
4429 mark_all_scalars_precise(env, env->cur_state);
4430 bt_reset(bt);
4431 }
4432
4433 return 0;
4434 }
4435
mark_chain_precision(struct bpf_verifier_env * env,int regno)4436 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4437 {
4438 return __mark_chain_precision(env, regno);
4439 }
4440
4441 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4442 * desired reg and stack masks across all relevant frames
4443 */
mark_chain_precision_batch(struct bpf_verifier_env * env)4444 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4445 {
4446 return __mark_chain_precision(env, -1);
4447 }
4448
is_spillable_regtype(enum bpf_reg_type type)4449 static bool is_spillable_regtype(enum bpf_reg_type type)
4450 {
4451 switch (base_type(type)) {
4452 case PTR_TO_MAP_VALUE:
4453 case PTR_TO_STACK:
4454 case PTR_TO_CTX:
4455 case PTR_TO_PACKET:
4456 case PTR_TO_PACKET_META:
4457 case PTR_TO_PACKET_END:
4458 case PTR_TO_FLOW_KEYS:
4459 case CONST_PTR_TO_MAP:
4460 case PTR_TO_SOCKET:
4461 case PTR_TO_SOCK_COMMON:
4462 case PTR_TO_TCP_SOCK:
4463 case PTR_TO_XDP_SOCK:
4464 case PTR_TO_BTF_ID:
4465 case PTR_TO_BUF:
4466 case PTR_TO_MEM:
4467 case PTR_TO_FUNC:
4468 case PTR_TO_MAP_KEY:
4469 return true;
4470 default:
4471 return false;
4472 }
4473 }
4474
4475 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)4476 static bool register_is_null(struct bpf_reg_state *reg)
4477 {
4478 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4479 }
4480
register_is_const(struct bpf_reg_state * reg)4481 static bool register_is_const(struct bpf_reg_state *reg)
4482 {
4483 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4484 }
4485
__is_scalar_unbounded(struct bpf_reg_state * reg)4486 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4487 {
4488 return tnum_is_unknown(reg->var_off) &&
4489 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4490 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4491 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4492 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4493 }
4494
register_is_bounded(struct bpf_reg_state * reg)4495 static bool register_is_bounded(struct bpf_reg_state *reg)
4496 {
4497 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4498 }
4499
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)4500 static bool __is_pointer_value(bool allow_ptr_leaks,
4501 const struct bpf_reg_state *reg)
4502 {
4503 if (allow_ptr_leaks)
4504 return false;
4505
4506 return reg->type != SCALAR_VALUE;
4507 }
4508
4509 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)4510 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4511 {
4512 struct bpf_reg_state *parent = dst->parent;
4513 enum bpf_reg_liveness live = dst->live;
4514
4515 *dst = *src;
4516 dst->parent = parent;
4517 dst->live = live;
4518 }
4519
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)4520 static void save_register_state(struct bpf_func_state *state,
4521 int spi, struct bpf_reg_state *reg,
4522 int size)
4523 {
4524 int i;
4525
4526 copy_register_state(&state->stack[spi].spilled_ptr, reg);
4527 if (size == BPF_REG_SIZE)
4528 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4529
4530 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4531 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4532
4533 /* size < 8 bytes spill */
4534 for (; i; i--)
4535 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4536 }
4537
is_bpf_st_mem(struct bpf_insn * insn)4538 static bool is_bpf_st_mem(struct bpf_insn *insn)
4539 {
4540 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4541 }
4542
4543 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4544 * stack boundary and alignment are checked in check_mem_access()
4545 */
check_stack_write_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)4546 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4547 /* stack frame we're writing to */
4548 struct bpf_func_state *state,
4549 int off, int size, int value_regno,
4550 int insn_idx)
4551 {
4552 struct bpf_func_state *cur; /* state of the current function */
4553 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4554 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4555 struct bpf_reg_state *reg = NULL;
4556 u32 dst_reg = insn->dst_reg;
4557
4558 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4559 * so it's aligned access and [off, off + size) are within stack limits
4560 */
4561 if (!env->allow_ptr_leaks &&
4562 is_spilled_reg(&state->stack[spi]) &&
4563 size != BPF_REG_SIZE) {
4564 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4565 return -EACCES;
4566 }
4567
4568 cur = env->cur_state->frame[env->cur_state->curframe];
4569 if (value_regno >= 0)
4570 reg = &cur->regs[value_regno];
4571 if (!env->bypass_spec_v4) {
4572 bool sanitize = reg && is_spillable_regtype(reg->type);
4573
4574 for (i = 0; i < size; i++) {
4575 u8 type = state->stack[spi].slot_type[i];
4576
4577 if (type != STACK_MISC && type != STACK_ZERO) {
4578 sanitize = true;
4579 break;
4580 }
4581 }
4582
4583 if (sanitize)
4584 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4585 }
4586
4587 err = destroy_if_dynptr_stack_slot(env, state, spi);
4588 if (err)
4589 return err;
4590
4591 mark_stack_slot_scratched(env, spi);
4592 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4593 !register_is_null(reg) && env->bpf_capable) {
4594 if (dst_reg != BPF_REG_FP) {
4595 /* The backtracking logic can only recognize explicit
4596 * stack slot address like [fp - 8]. Other spill of
4597 * scalar via different register has to be conservative.
4598 * Backtrack from here and mark all registers as precise
4599 * that contributed into 'reg' being a constant.
4600 */
4601 err = mark_chain_precision(env, value_regno);
4602 if (err)
4603 return err;
4604 }
4605 save_register_state(state, spi, reg, size);
4606 /* Break the relation on a narrowing spill. */
4607 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4608 state->stack[spi].spilled_ptr.id = 0;
4609 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4610 insn->imm != 0 && env->bpf_capable) {
4611 struct bpf_reg_state fake_reg = {};
4612
4613 __mark_reg_known(&fake_reg, insn->imm);
4614 fake_reg.type = SCALAR_VALUE;
4615 save_register_state(state, spi, &fake_reg, size);
4616 } else if (reg && is_spillable_regtype(reg->type)) {
4617 /* register containing pointer is being spilled into stack */
4618 if (size != BPF_REG_SIZE) {
4619 verbose_linfo(env, insn_idx, "; ");
4620 verbose(env, "invalid size of register spill\n");
4621 return -EACCES;
4622 }
4623 if (state != cur && reg->type == PTR_TO_STACK) {
4624 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4625 return -EINVAL;
4626 }
4627 save_register_state(state, spi, reg, size);
4628 } else {
4629 u8 type = STACK_MISC;
4630
4631 /* regular write of data into stack destroys any spilled ptr */
4632 state->stack[spi].spilled_ptr.type = NOT_INIT;
4633 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4634 if (is_stack_slot_special(&state->stack[spi]))
4635 for (i = 0; i < BPF_REG_SIZE; i++)
4636 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4637
4638 /* only mark the slot as written if all 8 bytes were written
4639 * otherwise read propagation may incorrectly stop too soon
4640 * when stack slots are partially written.
4641 * This heuristic means that read propagation will be
4642 * conservative, since it will add reg_live_read marks
4643 * to stack slots all the way to first state when programs
4644 * writes+reads less than 8 bytes
4645 */
4646 if (size == BPF_REG_SIZE)
4647 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4648
4649 /* when we zero initialize stack slots mark them as such */
4650 if ((reg && register_is_null(reg)) ||
4651 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4652 /* backtracking doesn't work for STACK_ZERO yet. */
4653 err = mark_chain_precision(env, value_regno);
4654 if (err)
4655 return err;
4656 type = STACK_ZERO;
4657 }
4658
4659 /* Mark slots affected by this stack write. */
4660 for (i = 0; i < size; i++)
4661 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4662 type;
4663 }
4664 return 0;
4665 }
4666
4667 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4668 * known to contain a variable offset.
4669 * This function checks whether the write is permitted and conservatively
4670 * tracks the effects of the write, considering that each stack slot in the
4671 * dynamic range is potentially written to.
4672 *
4673 * 'off' includes 'regno->off'.
4674 * 'value_regno' can be -1, meaning that an unknown value is being written to
4675 * the stack.
4676 *
4677 * Spilled pointers in range are not marked as written because we don't know
4678 * what's going to be actually written. This means that read propagation for
4679 * future reads cannot be terminated by this write.
4680 *
4681 * For privileged programs, uninitialized stack slots are considered
4682 * initialized by this write (even though we don't know exactly what offsets
4683 * are going to be written to). The idea is that we don't want the verifier to
4684 * reject future reads that access slots written to through variable offsets.
4685 */
check_stack_write_var_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int ptr_regno,int off,int size,int value_regno,int insn_idx)4686 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4687 /* func where register points to */
4688 struct bpf_func_state *state,
4689 int ptr_regno, int off, int size,
4690 int value_regno, int insn_idx)
4691 {
4692 struct bpf_func_state *cur; /* state of the current function */
4693 int min_off, max_off;
4694 int i, err;
4695 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4696 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4697 bool writing_zero = false;
4698 /* set if the fact that we're writing a zero is used to let any
4699 * stack slots remain STACK_ZERO
4700 */
4701 bool zero_used = false;
4702
4703 cur = env->cur_state->frame[env->cur_state->curframe];
4704 ptr_reg = &cur->regs[ptr_regno];
4705 min_off = ptr_reg->smin_value + off;
4706 max_off = ptr_reg->smax_value + off + size;
4707 if (value_regno >= 0)
4708 value_reg = &cur->regs[value_regno];
4709 if ((value_reg && register_is_null(value_reg)) ||
4710 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4711 writing_zero = true;
4712
4713 for (i = min_off; i < max_off; i++) {
4714 int spi;
4715
4716 spi = __get_spi(i);
4717 err = destroy_if_dynptr_stack_slot(env, state, spi);
4718 if (err)
4719 return err;
4720 }
4721
4722 /* Variable offset writes destroy any spilled pointers in range. */
4723 for (i = min_off; i < max_off; i++) {
4724 u8 new_type, *stype;
4725 int slot, spi;
4726
4727 slot = -i - 1;
4728 spi = slot / BPF_REG_SIZE;
4729 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4730 mark_stack_slot_scratched(env, spi);
4731
4732 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4733 /* Reject the write if range we may write to has not
4734 * been initialized beforehand. If we didn't reject
4735 * here, the ptr status would be erased below (even
4736 * though not all slots are actually overwritten),
4737 * possibly opening the door to leaks.
4738 *
4739 * We do however catch STACK_INVALID case below, and
4740 * only allow reading possibly uninitialized memory
4741 * later for CAP_PERFMON, as the write may not happen to
4742 * that slot.
4743 */
4744 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4745 insn_idx, i);
4746 return -EINVAL;
4747 }
4748
4749 /* Erase all spilled pointers. */
4750 state->stack[spi].spilled_ptr.type = NOT_INIT;
4751
4752 /* Update the slot type. */
4753 new_type = STACK_MISC;
4754 if (writing_zero && *stype == STACK_ZERO) {
4755 new_type = STACK_ZERO;
4756 zero_used = true;
4757 }
4758 /* If the slot is STACK_INVALID, we check whether it's OK to
4759 * pretend that it will be initialized by this write. The slot
4760 * might not actually be written to, and so if we mark it as
4761 * initialized future reads might leak uninitialized memory.
4762 * For privileged programs, we will accept such reads to slots
4763 * that may or may not be written because, if we're reject
4764 * them, the error would be too confusing.
4765 */
4766 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4767 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4768 insn_idx, i);
4769 return -EINVAL;
4770 }
4771 *stype = new_type;
4772 }
4773 if (zero_used) {
4774 /* backtracking doesn't work for STACK_ZERO yet. */
4775 err = mark_chain_precision(env, value_regno);
4776 if (err)
4777 return err;
4778 }
4779 return 0;
4780 }
4781
4782 /* When register 'dst_regno' is assigned some values from stack[min_off,
4783 * max_off), we set the register's type according to the types of the
4784 * respective stack slots. If all the stack values are known to be zeros, then
4785 * so is the destination reg. Otherwise, the register is considered to be
4786 * SCALAR. This function does not deal with register filling; the caller must
4787 * ensure that all spilled registers in the stack range have been marked as
4788 * read.
4789 */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)4790 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4791 /* func where src register points to */
4792 struct bpf_func_state *ptr_state,
4793 int min_off, int max_off, int dst_regno)
4794 {
4795 struct bpf_verifier_state *vstate = env->cur_state;
4796 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4797 int i, slot, spi;
4798 u8 *stype;
4799 int zeros = 0;
4800
4801 for (i = min_off; i < max_off; i++) {
4802 slot = -i - 1;
4803 spi = slot / BPF_REG_SIZE;
4804 mark_stack_slot_scratched(env, spi);
4805 stype = ptr_state->stack[spi].slot_type;
4806 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4807 break;
4808 zeros++;
4809 }
4810 if (zeros == max_off - min_off) {
4811 /* any access_size read into register is zero extended,
4812 * so the whole register == const_zero
4813 */
4814 __mark_reg_const_zero(&state->regs[dst_regno]);
4815 /* backtracking doesn't support STACK_ZERO yet,
4816 * so mark it precise here, so that later
4817 * backtracking can stop here.
4818 * Backtracking may not need this if this register
4819 * doesn't participate in pointer adjustment.
4820 * Forward propagation of precise flag is not
4821 * necessary either. This mark is only to stop
4822 * backtracking. Any register that contributed
4823 * to const 0 was marked precise before spill.
4824 */
4825 state->regs[dst_regno].precise = true;
4826 } else {
4827 /* have read misc data from the stack */
4828 mark_reg_unknown(env, state->regs, dst_regno);
4829 }
4830 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4831 }
4832
4833 /* Read the stack at 'off' and put the results into the register indicated by
4834 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4835 * spilled reg.
4836 *
4837 * 'dst_regno' can be -1, meaning that the read value is not going to a
4838 * register.
4839 *
4840 * The access is assumed to be within the current stack bounds.
4841 */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)4842 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4843 /* func where src register points to */
4844 struct bpf_func_state *reg_state,
4845 int off, int size, int dst_regno)
4846 {
4847 struct bpf_verifier_state *vstate = env->cur_state;
4848 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4849 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4850 struct bpf_reg_state *reg;
4851 u8 *stype, type;
4852
4853 stype = reg_state->stack[spi].slot_type;
4854 reg = ®_state->stack[spi].spilled_ptr;
4855
4856 mark_stack_slot_scratched(env, spi);
4857
4858 if (is_spilled_reg(®_state->stack[spi])) {
4859 u8 spill_size = 1;
4860
4861 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4862 spill_size++;
4863
4864 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4865 if (reg->type != SCALAR_VALUE) {
4866 verbose_linfo(env, env->insn_idx, "; ");
4867 verbose(env, "invalid size of register fill\n");
4868 return -EACCES;
4869 }
4870
4871 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4872 if (dst_regno < 0)
4873 return 0;
4874
4875 if (!(off % BPF_REG_SIZE) && size == spill_size) {
4876 /* The earlier check_reg_arg() has decided the
4877 * subreg_def for this insn. Save it first.
4878 */
4879 s32 subreg_def = state->regs[dst_regno].subreg_def;
4880
4881 copy_register_state(&state->regs[dst_regno], reg);
4882 state->regs[dst_regno].subreg_def = subreg_def;
4883 } else {
4884 for (i = 0; i < size; i++) {
4885 type = stype[(slot - i) % BPF_REG_SIZE];
4886 if (type == STACK_SPILL)
4887 continue;
4888 if (type == STACK_MISC)
4889 continue;
4890 if (type == STACK_INVALID && env->allow_uninit_stack)
4891 continue;
4892 verbose(env, "invalid read from stack off %d+%d size %d\n",
4893 off, i, size);
4894 return -EACCES;
4895 }
4896 mark_reg_unknown(env, state->regs, dst_regno);
4897 }
4898 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4899 return 0;
4900 }
4901
4902 if (dst_regno >= 0) {
4903 /* restore register state from stack */
4904 copy_register_state(&state->regs[dst_regno], reg);
4905 /* mark reg as written since spilled pointer state likely
4906 * has its liveness marks cleared by is_state_visited()
4907 * which resets stack/reg liveness for state transitions
4908 */
4909 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4910 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4911 /* If dst_regno==-1, the caller is asking us whether
4912 * it is acceptable to use this value as a SCALAR_VALUE
4913 * (e.g. for XADD).
4914 * We must not allow unprivileged callers to do that
4915 * with spilled pointers.
4916 */
4917 verbose(env, "leaking pointer from stack off %d\n",
4918 off);
4919 return -EACCES;
4920 }
4921 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4922 } else {
4923 for (i = 0; i < size; i++) {
4924 type = stype[(slot - i) % BPF_REG_SIZE];
4925 if (type == STACK_MISC)
4926 continue;
4927 if (type == STACK_ZERO)
4928 continue;
4929 if (type == STACK_INVALID && env->allow_uninit_stack)
4930 continue;
4931 verbose(env, "invalid read from stack off %d+%d size %d\n",
4932 off, i, size);
4933 return -EACCES;
4934 }
4935 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4936 if (dst_regno >= 0)
4937 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4938 }
4939 return 0;
4940 }
4941
4942 enum bpf_access_src {
4943 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
4944 ACCESS_HELPER = 2, /* the access is performed by a helper */
4945 };
4946
4947 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4948 int regno, int off, int access_size,
4949 bool zero_size_allowed,
4950 enum bpf_access_src type,
4951 struct bpf_call_arg_meta *meta);
4952
reg_state(struct bpf_verifier_env * env,int regno)4953 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4954 {
4955 return cur_regs(env) + regno;
4956 }
4957
4958 /* Read the stack at 'ptr_regno + off' and put the result into the register
4959 * 'dst_regno'.
4960 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4961 * but not its variable offset.
4962 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4963 *
4964 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4965 * filling registers (i.e. reads of spilled register cannot be detected when
4966 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4967 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4968 * offset; for a fixed offset check_stack_read_fixed_off should be used
4969 * instead.
4970 */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)4971 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4972 int ptr_regno, int off, int size, int dst_regno)
4973 {
4974 /* The state of the source register. */
4975 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4976 struct bpf_func_state *ptr_state = func(env, reg);
4977 int err;
4978 int min_off, max_off;
4979
4980 /* Note that we pass a NULL meta, so raw access will not be permitted.
4981 */
4982 err = check_stack_range_initialized(env, ptr_regno, off, size,
4983 false, ACCESS_DIRECT, NULL);
4984 if (err)
4985 return err;
4986
4987 min_off = reg->smin_value + off;
4988 max_off = reg->smax_value + off;
4989 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4990 return 0;
4991 }
4992
4993 /* check_stack_read dispatches to check_stack_read_fixed_off or
4994 * check_stack_read_var_off.
4995 *
4996 * The caller must ensure that the offset falls within the allocated stack
4997 * bounds.
4998 *
4999 * 'dst_regno' is a register which will receive the value from the stack. It
5000 * can be -1, meaning that the read value is not going to a register.
5001 */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)5002 static int check_stack_read(struct bpf_verifier_env *env,
5003 int ptr_regno, int off, int size,
5004 int dst_regno)
5005 {
5006 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5007 struct bpf_func_state *state = func(env, reg);
5008 int err;
5009 /* Some accesses are only permitted with a static offset. */
5010 bool var_off = !tnum_is_const(reg->var_off);
5011
5012 /* The offset is required to be static when reads don't go to a
5013 * register, in order to not leak pointers (see
5014 * check_stack_read_fixed_off).
5015 */
5016 if (dst_regno < 0 && var_off) {
5017 char tn_buf[48];
5018
5019 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5020 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5021 tn_buf, off, size);
5022 return -EACCES;
5023 }
5024 /* Variable offset is prohibited for unprivileged mode for simplicity
5025 * since it requires corresponding support in Spectre masking for stack
5026 * ALU. See also retrieve_ptr_limit(). The check in
5027 * check_stack_access_for_ptr_arithmetic() called by
5028 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5029 * with variable offsets, therefore no check is required here. Further,
5030 * just checking it here would be insufficient as speculative stack
5031 * writes could still lead to unsafe speculative behaviour.
5032 */
5033 if (!var_off) {
5034 off += reg->var_off.value;
5035 err = check_stack_read_fixed_off(env, state, off, size,
5036 dst_regno);
5037 } else {
5038 /* Variable offset stack reads need more conservative handling
5039 * than fixed offset ones. Note that dst_regno >= 0 on this
5040 * branch.
5041 */
5042 err = check_stack_read_var_off(env, ptr_regno, off, size,
5043 dst_regno);
5044 }
5045 return err;
5046 }
5047
5048
5049 /* check_stack_write dispatches to check_stack_write_fixed_off or
5050 * check_stack_write_var_off.
5051 *
5052 * 'ptr_regno' is the register used as a pointer into the stack.
5053 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5054 * 'value_regno' is the register whose value we're writing to the stack. It can
5055 * be -1, meaning that we're not writing from a register.
5056 *
5057 * The caller must ensure that the offset falls within the maximum stack size.
5058 */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)5059 static int check_stack_write(struct bpf_verifier_env *env,
5060 int ptr_regno, int off, int size,
5061 int value_regno, int insn_idx)
5062 {
5063 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5064 struct bpf_func_state *state = func(env, reg);
5065 int err;
5066
5067 if (tnum_is_const(reg->var_off)) {
5068 off += reg->var_off.value;
5069 err = check_stack_write_fixed_off(env, state, off, size,
5070 value_regno, insn_idx);
5071 } else {
5072 /* Variable offset stack reads need more conservative handling
5073 * than fixed offset ones.
5074 */
5075 err = check_stack_write_var_off(env, state,
5076 ptr_regno, off, size,
5077 value_regno, insn_idx);
5078 }
5079 return err;
5080 }
5081
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)5082 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5083 int off, int size, enum bpf_access_type type)
5084 {
5085 struct bpf_reg_state *regs = cur_regs(env);
5086 struct bpf_map *map = regs[regno].map_ptr;
5087 u32 cap = bpf_map_flags_to_cap(map);
5088
5089 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5090 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5091 map->value_size, off, size);
5092 return -EACCES;
5093 }
5094
5095 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5096 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5097 map->value_size, off, size);
5098 return -EACCES;
5099 }
5100
5101 return 0;
5102 }
5103
5104 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
__check_mem_access(struct bpf_verifier_env * env,int regno,int off,int size,u32 mem_size,bool zero_size_allowed)5105 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5106 int off, int size, u32 mem_size,
5107 bool zero_size_allowed)
5108 {
5109 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5110 struct bpf_reg_state *reg;
5111
5112 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5113 return 0;
5114
5115 reg = &cur_regs(env)[regno];
5116 switch (reg->type) {
5117 case PTR_TO_MAP_KEY:
5118 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5119 mem_size, off, size);
5120 break;
5121 case PTR_TO_MAP_VALUE:
5122 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5123 mem_size, off, size);
5124 break;
5125 case PTR_TO_PACKET:
5126 case PTR_TO_PACKET_META:
5127 case PTR_TO_PACKET_END:
5128 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5129 off, size, regno, reg->id, off, mem_size);
5130 break;
5131 case PTR_TO_MEM:
5132 default:
5133 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5134 mem_size, off, size);
5135 }
5136
5137 return -EACCES;
5138 }
5139
5140 /* check read/write into a memory region with possible variable offset */
check_mem_region_access(struct bpf_verifier_env * env,u32 regno,int off,int size,u32 mem_size,bool zero_size_allowed)5141 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5142 int off, int size, u32 mem_size,
5143 bool zero_size_allowed)
5144 {
5145 struct bpf_verifier_state *vstate = env->cur_state;
5146 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5147 struct bpf_reg_state *reg = &state->regs[regno];
5148 int err;
5149
5150 /* We may have adjusted the register pointing to memory region, so we
5151 * need to try adding each of min_value and max_value to off
5152 * to make sure our theoretical access will be safe.
5153 *
5154 * The minimum value is only important with signed
5155 * comparisons where we can't assume the floor of a
5156 * value is 0. If we are using signed variables for our
5157 * index'es we need to make sure that whatever we use
5158 * will have a set floor within our range.
5159 */
5160 if (reg->smin_value < 0 &&
5161 (reg->smin_value == S64_MIN ||
5162 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5163 reg->smin_value + off < 0)) {
5164 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5165 regno);
5166 return -EACCES;
5167 }
5168 err = __check_mem_access(env, regno, reg->smin_value + off, size,
5169 mem_size, zero_size_allowed);
5170 if (err) {
5171 verbose(env, "R%d min value is outside of the allowed memory range\n",
5172 regno);
5173 return err;
5174 }
5175
5176 /* If we haven't set a max value then we need to bail since we can't be
5177 * sure we won't do bad things.
5178 * If reg->umax_value + off could overflow, treat that as unbounded too.
5179 */
5180 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5181 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5182 regno);
5183 return -EACCES;
5184 }
5185 err = __check_mem_access(env, regno, reg->umax_value + off, size,
5186 mem_size, zero_size_allowed);
5187 if (err) {
5188 verbose(env, "R%d max value is outside of the allowed memory range\n",
5189 regno);
5190 return err;
5191 }
5192
5193 return 0;
5194 }
5195
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)5196 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5197 const struct bpf_reg_state *reg, int regno,
5198 bool fixed_off_ok)
5199 {
5200 /* Access to this pointer-typed register or passing it to a helper
5201 * is only allowed in its original, unmodified form.
5202 */
5203
5204 if (reg->off < 0) {
5205 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5206 reg_type_str(env, reg->type), regno, reg->off);
5207 return -EACCES;
5208 }
5209
5210 if (!fixed_off_ok && reg->off) {
5211 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5212 reg_type_str(env, reg->type), regno, reg->off);
5213 return -EACCES;
5214 }
5215
5216 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5217 char tn_buf[48];
5218
5219 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5220 verbose(env, "variable %s access var_off=%s disallowed\n",
5221 reg_type_str(env, reg->type), tn_buf);
5222 return -EACCES;
5223 }
5224
5225 return 0;
5226 }
5227
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)5228 int check_ptr_off_reg(struct bpf_verifier_env *env,
5229 const struct bpf_reg_state *reg, int regno)
5230 {
5231 return __check_ptr_off_reg(env, reg, regno, false);
5232 }
5233
map_kptr_match_type(struct bpf_verifier_env * env,struct btf_field * kptr_field,struct bpf_reg_state * reg,u32 regno)5234 static int map_kptr_match_type(struct bpf_verifier_env *env,
5235 struct btf_field *kptr_field,
5236 struct bpf_reg_state *reg, u32 regno)
5237 {
5238 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5239 int perm_flags;
5240 const char *reg_name = "";
5241
5242 if (btf_is_kernel(reg->btf)) {
5243 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5244
5245 /* Only unreferenced case accepts untrusted pointers */
5246 if (kptr_field->type == BPF_KPTR_UNREF)
5247 perm_flags |= PTR_UNTRUSTED;
5248 } else {
5249 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5250 }
5251
5252 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5253 goto bad_type;
5254
5255 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5256 reg_name = btf_type_name(reg->btf, reg->btf_id);
5257
5258 /* For ref_ptr case, release function check should ensure we get one
5259 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5260 * normal store of unreferenced kptr, we must ensure var_off is zero.
5261 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5262 * reg->off and reg->ref_obj_id are not needed here.
5263 */
5264 if (__check_ptr_off_reg(env, reg, regno, true))
5265 return -EACCES;
5266
5267 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5268 * we also need to take into account the reg->off.
5269 *
5270 * We want to support cases like:
5271 *
5272 * struct foo {
5273 * struct bar br;
5274 * struct baz bz;
5275 * };
5276 *
5277 * struct foo *v;
5278 * v = func(); // PTR_TO_BTF_ID
5279 * val->foo = v; // reg->off is zero, btf and btf_id match type
5280 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5281 * // first member type of struct after comparison fails
5282 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5283 * // to match type
5284 *
5285 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5286 * is zero. We must also ensure that btf_struct_ids_match does not walk
5287 * the struct to match type against first member of struct, i.e. reject
5288 * second case from above. Hence, when type is BPF_KPTR_REF, we set
5289 * strict mode to true for type match.
5290 */
5291 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5292 kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5293 kptr_field->type == BPF_KPTR_REF))
5294 goto bad_type;
5295 return 0;
5296 bad_type:
5297 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5298 reg_type_str(env, reg->type), reg_name);
5299 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5300 if (kptr_field->type == BPF_KPTR_UNREF)
5301 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5302 targ_name);
5303 else
5304 verbose(env, "\n");
5305 return -EINVAL;
5306 }
5307
5308 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5309 * can dereference RCU protected pointers and result is PTR_TRUSTED.
5310 */
in_rcu_cs(struct bpf_verifier_env * env)5311 static bool in_rcu_cs(struct bpf_verifier_env *env)
5312 {
5313 return env->cur_state->active_rcu_lock ||
5314 env->cur_state->active_lock.ptr ||
5315 !env->prog->aux->sleepable;
5316 }
5317
5318 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5319 BTF_SET_START(rcu_protected_types)
BTF_ID(struct,prog_test_ref_kfunc)5320 BTF_ID(struct, prog_test_ref_kfunc)
5321 BTF_ID(struct, cgroup)
5322 BTF_ID(struct, bpf_cpumask)
5323 BTF_ID(struct, task_struct)
5324 BTF_SET_END(rcu_protected_types)
5325
5326 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5327 {
5328 if (!btf_is_kernel(btf))
5329 return false;
5330 return btf_id_set_contains(&rcu_protected_types, btf_id);
5331 }
5332
rcu_safe_kptr(const struct btf_field * field)5333 static bool rcu_safe_kptr(const struct btf_field *field)
5334 {
5335 const struct btf_field_kptr *kptr = &field->kptr;
5336
5337 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5338 }
5339
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct btf_field * kptr_field)5340 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5341 int value_regno, int insn_idx,
5342 struct btf_field *kptr_field)
5343 {
5344 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5345 int class = BPF_CLASS(insn->code);
5346 struct bpf_reg_state *val_reg;
5347
5348 /* Things we already checked for in check_map_access and caller:
5349 * - Reject cases where variable offset may touch kptr
5350 * - size of access (must be BPF_DW)
5351 * - tnum_is_const(reg->var_off)
5352 * - kptr_field->offset == off + reg->var_off.value
5353 */
5354 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5355 if (BPF_MODE(insn->code) != BPF_MEM) {
5356 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5357 return -EACCES;
5358 }
5359
5360 /* We only allow loading referenced kptr, since it will be marked as
5361 * untrusted, similar to unreferenced kptr.
5362 */
5363 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5364 verbose(env, "store to referenced kptr disallowed\n");
5365 return -EACCES;
5366 }
5367
5368 if (class == BPF_LDX) {
5369 val_reg = reg_state(env, value_regno);
5370 /* We can simply mark the value_regno receiving the pointer
5371 * value from map as PTR_TO_BTF_ID, with the correct type.
5372 */
5373 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5374 kptr_field->kptr.btf_id,
5375 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5376 PTR_MAYBE_NULL | MEM_RCU :
5377 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5378 } else if (class == BPF_STX) {
5379 val_reg = reg_state(env, value_regno);
5380 if (!register_is_null(val_reg) &&
5381 map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5382 return -EACCES;
5383 } else if (class == BPF_ST) {
5384 if (insn->imm) {
5385 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5386 kptr_field->offset);
5387 return -EACCES;
5388 }
5389 } else {
5390 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5391 return -EACCES;
5392 }
5393 return 0;
5394 }
5395
5396 /* check read/write into a map element with possible variable offset */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed,enum bpf_access_src src)5397 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5398 int off, int size, bool zero_size_allowed,
5399 enum bpf_access_src src)
5400 {
5401 struct bpf_verifier_state *vstate = env->cur_state;
5402 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5403 struct bpf_reg_state *reg = &state->regs[regno];
5404 struct bpf_map *map = reg->map_ptr;
5405 struct btf_record *rec;
5406 int err, i;
5407
5408 err = check_mem_region_access(env, regno, off, size, map->value_size,
5409 zero_size_allowed);
5410 if (err)
5411 return err;
5412
5413 if (IS_ERR_OR_NULL(map->record))
5414 return 0;
5415 rec = map->record;
5416 for (i = 0; i < rec->cnt; i++) {
5417 struct btf_field *field = &rec->fields[i];
5418 u32 p = field->offset;
5419
5420 /* If any part of a field can be touched by load/store, reject
5421 * this program. To check that [x1, x2) overlaps with [y1, y2),
5422 * it is sufficient to check x1 < y2 && y1 < x2.
5423 */
5424 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5425 p < reg->umax_value + off + size) {
5426 switch (field->type) {
5427 case BPF_KPTR_UNREF:
5428 case BPF_KPTR_REF:
5429 if (src != ACCESS_DIRECT) {
5430 verbose(env, "kptr cannot be accessed indirectly by helper\n");
5431 return -EACCES;
5432 }
5433 if (!tnum_is_const(reg->var_off)) {
5434 verbose(env, "kptr access cannot have variable offset\n");
5435 return -EACCES;
5436 }
5437 if (p != off + reg->var_off.value) {
5438 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5439 p, off + reg->var_off.value);
5440 return -EACCES;
5441 }
5442 if (size != bpf_size_to_bytes(BPF_DW)) {
5443 verbose(env, "kptr access size must be BPF_DW\n");
5444 return -EACCES;
5445 }
5446 break;
5447 default:
5448 verbose(env, "%s cannot be accessed directly by load/store\n",
5449 btf_field_type_name(field->type));
5450 return -EACCES;
5451 }
5452 }
5453 }
5454 return 0;
5455 }
5456
5457 #define MAX_PACKET_OFF 0xffff
5458
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)5459 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5460 const struct bpf_call_arg_meta *meta,
5461 enum bpf_access_type t)
5462 {
5463 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5464
5465 switch (prog_type) {
5466 /* Program types only with direct read access go here! */
5467 case BPF_PROG_TYPE_LWT_IN:
5468 case BPF_PROG_TYPE_LWT_OUT:
5469 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5470 case BPF_PROG_TYPE_SK_REUSEPORT:
5471 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5472 case BPF_PROG_TYPE_CGROUP_SKB:
5473 if (t == BPF_WRITE)
5474 return false;
5475 fallthrough;
5476
5477 /* Program types with direct read + write access go here! */
5478 case BPF_PROG_TYPE_SCHED_CLS:
5479 case BPF_PROG_TYPE_SCHED_ACT:
5480 case BPF_PROG_TYPE_XDP:
5481 case BPF_PROG_TYPE_LWT_XMIT:
5482 case BPF_PROG_TYPE_SK_SKB:
5483 case BPF_PROG_TYPE_SK_MSG:
5484 if (meta)
5485 return meta->pkt_access;
5486
5487 env->seen_direct_write = true;
5488 return true;
5489
5490 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5491 if (t == BPF_WRITE)
5492 env->seen_direct_write = true;
5493
5494 return true;
5495
5496 default:
5497 return false;
5498 }
5499 }
5500
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)5501 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5502 int size, bool zero_size_allowed)
5503 {
5504 struct bpf_reg_state *regs = cur_regs(env);
5505 struct bpf_reg_state *reg = ®s[regno];
5506 int err;
5507
5508 /* We may have added a variable offset to the packet pointer; but any
5509 * reg->range we have comes after that. We are only checking the fixed
5510 * offset.
5511 */
5512
5513 /* We don't allow negative numbers, because we aren't tracking enough
5514 * detail to prove they're safe.
5515 */
5516 if (reg->smin_value < 0) {
5517 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5518 regno);
5519 return -EACCES;
5520 }
5521
5522 err = reg->range < 0 ? -EINVAL :
5523 __check_mem_access(env, regno, off, size, reg->range,
5524 zero_size_allowed);
5525 if (err) {
5526 verbose(env, "R%d offset is outside of the packet\n", regno);
5527 return err;
5528 }
5529
5530 /* __check_mem_access has made sure "off + size - 1" is within u16.
5531 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5532 * otherwise find_good_pkt_pointers would have refused to set range info
5533 * that __check_mem_access would have rejected this pkt access.
5534 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5535 */
5536 env->prog->aux->max_pkt_offset =
5537 max_t(u32, env->prog->aux->max_pkt_offset,
5538 off + reg->umax_value + size - 1);
5539
5540 return err;
5541 }
5542
5543 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type,struct btf ** btf,u32 * btf_id)5544 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5545 enum bpf_access_type t, enum bpf_reg_type *reg_type,
5546 struct btf **btf, u32 *btf_id)
5547 {
5548 struct bpf_insn_access_aux info = {
5549 .reg_type = *reg_type,
5550 .log = &env->log,
5551 };
5552
5553 if (env->ops->is_valid_access &&
5554 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5555 /* A non zero info.ctx_field_size indicates that this field is a
5556 * candidate for later verifier transformation to load the whole
5557 * field and then apply a mask when accessed with a narrower
5558 * access than actual ctx access size. A zero info.ctx_field_size
5559 * will only allow for whole field access and rejects any other
5560 * type of narrower access.
5561 */
5562 *reg_type = info.reg_type;
5563
5564 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5565 *btf = info.btf;
5566 *btf_id = info.btf_id;
5567 } else {
5568 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5569 }
5570 /* remember the offset of last byte accessed in ctx */
5571 if (env->prog->aux->max_ctx_offset < off + size)
5572 env->prog->aux->max_ctx_offset = off + size;
5573 return 0;
5574 }
5575
5576 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5577 return -EACCES;
5578 }
5579
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)5580 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5581 int size)
5582 {
5583 if (size < 0 || off < 0 ||
5584 (u64)off + size > sizeof(struct bpf_flow_keys)) {
5585 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5586 off, size);
5587 return -EACCES;
5588 }
5589 return 0;
5590 }
5591
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)5592 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5593 u32 regno, int off, int size,
5594 enum bpf_access_type t)
5595 {
5596 struct bpf_reg_state *regs = cur_regs(env);
5597 struct bpf_reg_state *reg = ®s[regno];
5598 struct bpf_insn_access_aux info = {};
5599 bool valid;
5600
5601 if (reg->smin_value < 0) {
5602 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5603 regno);
5604 return -EACCES;
5605 }
5606
5607 switch (reg->type) {
5608 case PTR_TO_SOCK_COMMON:
5609 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5610 break;
5611 case PTR_TO_SOCKET:
5612 valid = bpf_sock_is_valid_access(off, size, t, &info);
5613 break;
5614 case PTR_TO_TCP_SOCK:
5615 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5616 break;
5617 case PTR_TO_XDP_SOCK:
5618 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5619 break;
5620 default:
5621 valid = false;
5622 }
5623
5624
5625 if (valid) {
5626 env->insn_aux_data[insn_idx].ctx_field_size =
5627 info.ctx_field_size;
5628 return 0;
5629 }
5630
5631 verbose(env, "R%d invalid %s access off=%d size=%d\n",
5632 regno, reg_type_str(env, reg->type), off, size);
5633
5634 return -EACCES;
5635 }
5636
is_pointer_value(struct bpf_verifier_env * env,int regno)5637 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5638 {
5639 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5640 }
5641
is_ctx_reg(struct bpf_verifier_env * env,int regno)5642 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5643 {
5644 const struct bpf_reg_state *reg = reg_state(env, regno);
5645
5646 return reg->type == PTR_TO_CTX;
5647 }
5648
is_sk_reg(struct bpf_verifier_env * env,int regno)5649 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5650 {
5651 const struct bpf_reg_state *reg = reg_state(env, regno);
5652
5653 return type_is_sk_pointer(reg->type);
5654 }
5655
is_pkt_reg(struct bpf_verifier_env * env,int regno)5656 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5657 {
5658 const struct bpf_reg_state *reg = reg_state(env, regno);
5659
5660 return type_is_pkt_pointer(reg->type);
5661 }
5662
is_flow_key_reg(struct bpf_verifier_env * env,int regno)5663 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5664 {
5665 const struct bpf_reg_state *reg = reg_state(env, regno);
5666
5667 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5668 return reg->type == PTR_TO_FLOW_KEYS;
5669 }
5670
5671 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5672 #ifdef CONFIG_NET
5673 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5674 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5675 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5676 #endif
5677 [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5678 };
5679
is_trusted_reg(const struct bpf_reg_state * reg)5680 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5681 {
5682 /* A referenced register is always trusted. */
5683 if (reg->ref_obj_id)
5684 return true;
5685
5686 /* Types listed in the reg2btf_ids are always trusted */
5687 if (reg2btf_ids[base_type(reg->type)] &&
5688 !bpf_type_has_unsafe_modifiers(reg->type))
5689 return true;
5690
5691 /* If a register is not referenced, it is trusted if it has the
5692 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5693 * other type modifiers may be safe, but we elect to take an opt-in
5694 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5695 * not.
5696 *
5697 * Eventually, we should make PTR_TRUSTED the single source of truth
5698 * for whether a register is trusted.
5699 */
5700 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5701 !bpf_type_has_unsafe_modifiers(reg->type);
5702 }
5703
is_rcu_reg(const struct bpf_reg_state * reg)5704 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5705 {
5706 return reg->type & MEM_RCU;
5707 }
5708
clear_trusted_flags(enum bpf_type_flag * flag)5709 static void clear_trusted_flags(enum bpf_type_flag *flag)
5710 {
5711 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5712 }
5713
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)5714 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5715 const struct bpf_reg_state *reg,
5716 int off, int size, bool strict)
5717 {
5718 struct tnum reg_off;
5719 int ip_align;
5720
5721 /* Byte size accesses are always allowed. */
5722 if (!strict || size == 1)
5723 return 0;
5724
5725 /* For platforms that do not have a Kconfig enabling
5726 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5727 * NET_IP_ALIGN is universally set to '2'. And on platforms
5728 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5729 * to this code only in strict mode where we want to emulate
5730 * the NET_IP_ALIGN==2 checking. Therefore use an
5731 * unconditional IP align value of '2'.
5732 */
5733 ip_align = 2;
5734
5735 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5736 if (!tnum_is_aligned(reg_off, size)) {
5737 char tn_buf[48];
5738
5739 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5740 verbose(env,
5741 "misaligned packet access off %d+%s+%d+%d size %d\n",
5742 ip_align, tn_buf, reg->off, off, size);
5743 return -EACCES;
5744 }
5745
5746 return 0;
5747 }
5748
check_generic_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,const char * pointer_desc,int off,int size,bool strict)5749 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5750 const struct bpf_reg_state *reg,
5751 const char *pointer_desc,
5752 int off, int size, bool strict)
5753 {
5754 struct tnum reg_off;
5755
5756 /* Byte size accesses are always allowed. */
5757 if (!strict || size == 1)
5758 return 0;
5759
5760 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5761 if (!tnum_is_aligned(reg_off, size)) {
5762 char tn_buf[48];
5763
5764 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5765 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5766 pointer_desc, tn_buf, reg->off, off, size);
5767 return -EACCES;
5768 }
5769
5770 return 0;
5771 }
5772
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)5773 static int check_ptr_alignment(struct bpf_verifier_env *env,
5774 const struct bpf_reg_state *reg, int off,
5775 int size, bool strict_alignment_once)
5776 {
5777 bool strict = env->strict_alignment || strict_alignment_once;
5778 const char *pointer_desc = "";
5779
5780 switch (reg->type) {
5781 case PTR_TO_PACKET:
5782 case PTR_TO_PACKET_META:
5783 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5784 * right in front, treat it the very same way.
5785 */
5786 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5787 case PTR_TO_FLOW_KEYS:
5788 pointer_desc = "flow keys ";
5789 break;
5790 case PTR_TO_MAP_KEY:
5791 pointer_desc = "key ";
5792 break;
5793 case PTR_TO_MAP_VALUE:
5794 pointer_desc = "value ";
5795 break;
5796 case PTR_TO_CTX:
5797 pointer_desc = "context ";
5798 break;
5799 case PTR_TO_STACK:
5800 pointer_desc = "stack ";
5801 /* The stack spill tracking logic in check_stack_write_fixed_off()
5802 * and check_stack_read_fixed_off() relies on stack accesses being
5803 * aligned.
5804 */
5805 strict = true;
5806 break;
5807 case PTR_TO_SOCKET:
5808 pointer_desc = "sock ";
5809 break;
5810 case PTR_TO_SOCK_COMMON:
5811 pointer_desc = "sock_common ";
5812 break;
5813 case PTR_TO_TCP_SOCK:
5814 pointer_desc = "tcp_sock ";
5815 break;
5816 case PTR_TO_XDP_SOCK:
5817 pointer_desc = "xdp_sock ";
5818 break;
5819 default:
5820 break;
5821 }
5822 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5823 strict);
5824 }
5825
5826 /* starting from main bpf function walk all instructions of the function
5827 * and recursively walk all callees that given function can call.
5828 * Ignore jump and exit insns.
5829 * Since recursion is prevented by check_cfg() this algorithm
5830 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5831 */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx)5832 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5833 {
5834 struct bpf_subprog_info *subprog = env->subprog_info;
5835 struct bpf_insn *insn = env->prog->insnsi;
5836 int depth = 0, frame = 0, i, subprog_end;
5837 bool tail_call_reachable = false;
5838 int ret_insn[MAX_CALL_FRAMES];
5839 int ret_prog[MAX_CALL_FRAMES];
5840 int j;
5841
5842 i = subprog[idx].start;
5843 process_func:
5844 /* protect against potential stack overflow that might happen when
5845 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5846 * depth for such case down to 256 so that the worst case scenario
5847 * would result in 8k stack size (32 which is tailcall limit * 256 =
5848 * 8k).
5849 *
5850 * To get the idea what might happen, see an example:
5851 * func1 -> sub rsp, 128
5852 * subfunc1 -> sub rsp, 256
5853 * tailcall1 -> add rsp, 256
5854 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5855 * subfunc2 -> sub rsp, 64
5856 * subfunc22 -> sub rsp, 128
5857 * tailcall2 -> add rsp, 128
5858 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5859 *
5860 * tailcall will unwind the current stack frame but it will not get rid
5861 * of caller's stack as shown on the example above.
5862 */
5863 if (idx && subprog[idx].has_tail_call && depth >= 256) {
5864 verbose(env,
5865 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5866 depth);
5867 return -EACCES;
5868 }
5869 /* round up to 32-bytes, since this is granularity
5870 * of interpreter stack size
5871 */
5872 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5873 if (depth > MAX_BPF_STACK) {
5874 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5875 frame + 1, depth);
5876 return -EACCES;
5877 }
5878 continue_func:
5879 subprog_end = subprog[idx + 1].start;
5880 for (; i < subprog_end; i++) {
5881 int next_insn, sidx;
5882
5883 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5884 continue;
5885 /* remember insn and function to return to */
5886 ret_insn[frame] = i + 1;
5887 ret_prog[frame] = idx;
5888
5889 /* find the callee */
5890 next_insn = i + insn[i].imm + 1;
5891 sidx = find_subprog(env, next_insn);
5892 if (sidx < 0) {
5893 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5894 next_insn);
5895 return -EFAULT;
5896 }
5897 if (subprog[sidx].is_async_cb) {
5898 if (subprog[sidx].has_tail_call) {
5899 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5900 return -EFAULT;
5901 }
5902 /* async callbacks don't increase bpf prog stack size unless called directly */
5903 if (!bpf_pseudo_call(insn + i))
5904 continue;
5905 }
5906 i = next_insn;
5907 idx = sidx;
5908
5909 if (subprog[idx].has_tail_call)
5910 tail_call_reachable = true;
5911
5912 frame++;
5913 if (frame >= MAX_CALL_FRAMES) {
5914 verbose(env, "the call stack of %d frames is too deep !\n",
5915 frame);
5916 return -E2BIG;
5917 }
5918 goto process_func;
5919 }
5920 /* if tail call got detected across bpf2bpf calls then mark each of the
5921 * currently present subprog frames as tail call reachable subprogs;
5922 * this info will be utilized by JIT so that we will be preserving the
5923 * tail call counter throughout bpf2bpf calls combined with tailcalls
5924 */
5925 if (tail_call_reachable)
5926 for (j = 0; j < frame; j++)
5927 subprog[ret_prog[j]].tail_call_reachable = true;
5928 if (subprog[0].tail_call_reachable)
5929 env->prog->aux->tail_call_reachable = true;
5930
5931 /* end of for() loop means the last insn of the 'subprog'
5932 * was reached. Doesn't matter whether it was JA or EXIT
5933 */
5934 if (frame == 0)
5935 return 0;
5936 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5937 frame--;
5938 i = ret_insn[frame];
5939 idx = ret_prog[frame];
5940 goto continue_func;
5941 }
5942
check_max_stack_depth(struct bpf_verifier_env * env)5943 static int check_max_stack_depth(struct bpf_verifier_env *env)
5944 {
5945 struct bpf_subprog_info *si = env->subprog_info;
5946 int ret;
5947
5948 for (int i = 0; i < env->subprog_cnt; i++) {
5949 if (!i || si[i].is_async_cb) {
5950 ret = check_max_stack_depth_subprog(env, i);
5951 if (ret < 0)
5952 return ret;
5953 }
5954 continue;
5955 }
5956 return 0;
5957 }
5958
5959 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)5960 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5961 const struct bpf_insn *insn, int idx)
5962 {
5963 int start = idx + insn->imm + 1, subprog;
5964
5965 subprog = find_subprog(env, start);
5966 if (subprog < 0) {
5967 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5968 start);
5969 return -EFAULT;
5970 }
5971 return env->subprog_info[subprog].stack_depth;
5972 }
5973 #endif
5974
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)5975 static int __check_buffer_access(struct bpf_verifier_env *env,
5976 const char *buf_info,
5977 const struct bpf_reg_state *reg,
5978 int regno, int off, int size)
5979 {
5980 if (off < 0) {
5981 verbose(env,
5982 "R%d invalid %s buffer access: off=%d, size=%d\n",
5983 regno, buf_info, off, size);
5984 return -EACCES;
5985 }
5986 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5987 char tn_buf[48];
5988
5989 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5990 verbose(env,
5991 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5992 regno, off, tn_buf);
5993 return -EACCES;
5994 }
5995
5996 return 0;
5997 }
5998
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)5999 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6000 const struct bpf_reg_state *reg,
6001 int regno, int off, int size)
6002 {
6003 int err;
6004
6005 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6006 if (err)
6007 return err;
6008
6009 if (off + size > env->prog->aux->max_tp_access)
6010 env->prog->aux->max_tp_access = off + size;
6011
6012 return 0;
6013 }
6014
check_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size,bool zero_size_allowed,u32 * max_access)6015 static int check_buffer_access(struct bpf_verifier_env *env,
6016 const struct bpf_reg_state *reg,
6017 int regno, int off, int size,
6018 bool zero_size_allowed,
6019 u32 *max_access)
6020 {
6021 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6022 int err;
6023
6024 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6025 if (err)
6026 return err;
6027
6028 if (off + size > *max_access)
6029 *max_access = off + size;
6030
6031 return 0;
6032 }
6033
6034 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)6035 static void zext_32_to_64(struct bpf_reg_state *reg)
6036 {
6037 reg->var_off = tnum_subreg(reg->var_off);
6038 __reg_assign_32_into_64(reg);
6039 }
6040
6041 /* truncate register to smaller size (in bytes)
6042 * must be called with size < BPF_REG_SIZE
6043 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)6044 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6045 {
6046 u64 mask;
6047
6048 /* clear high bits in bit representation */
6049 reg->var_off = tnum_cast(reg->var_off, size);
6050
6051 /* fix arithmetic bounds */
6052 mask = ((u64)1 << (size * 8)) - 1;
6053 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6054 reg->umin_value &= mask;
6055 reg->umax_value &= mask;
6056 } else {
6057 reg->umin_value = 0;
6058 reg->umax_value = mask;
6059 }
6060 reg->smin_value = reg->umin_value;
6061 reg->smax_value = reg->umax_value;
6062
6063 /* If size is smaller than 32bit register the 32bit register
6064 * values are also truncated so we push 64-bit bounds into
6065 * 32-bit bounds. Above were truncated < 32-bits already.
6066 */
6067 if (size >= 4)
6068 return;
6069 __reg_combine_64_into_32(reg);
6070 }
6071
set_sext64_default_val(struct bpf_reg_state * reg,int size)6072 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6073 {
6074 if (size == 1) {
6075 reg->smin_value = reg->s32_min_value = S8_MIN;
6076 reg->smax_value = reg->s32_max_value = S8_MAX;
6077 } else if (size == 2) {
6078 reg->smin_value = reg->s32_min_value = S16_MIN;
6079 reg->smax_value = reg->s32_max_value = S16_MAX;
6080 } else {
6081 /* size == 4 */
6082 reg->smin_value = reg->s32_min_value = S32_MIN;
6083 reg->smax_value = reg->s32_max_value = S32_MAX;
6084 }
6085 reg->umin_value = reg->u32_min_value = 0;
6086 reg->umax_value = U64_MAX;
6087 reg->u32_max_value = U32_MAX;
6088 reg->var_off = tnum_unknown;
6089 }
6090
coerce_reg_to_size_sx(struct bpf_reg_state * reg,int size)6091 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6092 {
6093 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6094 u64 top_smax_value, top_smin_value;
6095 u64 num_bits = size * 8;
6096
6097 if (tnum_is_const(reg->var_off)) {
6098 u64_cval = reg->var_off.value;
6099 if (size == 1)
6100 reg->var_off = tnum_const((s8)u64_cval);
6101 else if (size == 2)
6102 reg->var_off = tnum_const((s16)u64_cval);
6103 else
6104 /* size == 4 */
6105 reg->var_off = tnum_const((s32)u64_cval);
6106
6107 u64_cval = reg->var_off.value;
6108 reg->smax_value = reg->smin_value = u64_cval;
6109 reg->umax_value = reg->umin_value = u64_cval;
6110 reg->s32_max_value = reg->s32_min_value = u64_cval;
6111 reg->u32_max_value = reg->u32_min_value = u64_cval;
6112 return;
6113 }
6114
6115 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6116 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6117
6118 if (top_smax_value != top_smin_value)
6119 goto out;
6120
6121 /* find the s64_min and s64_min after sign extension */
6122 if (size == 1) {
6123 init_s64_max = (s8)reg->smax_value;
6124 init_s64_min = (s8)reg->smin_value;
6125 } else if (size == 2) {
6126 init_s64_max = (s16)reg->smax_value;
6127 init_s64_min = (s16)reg->smin_value;
6128 } else {
6129 init_s64_max = (s32)reg->smax_value;
6130 init_s64_min = (s32)reg->smin_value;
6131 }
6132
6133 s64_max = max(init_s64_max, init_s64_min);
6134 s64_min = min(init_s64_max, init_s64_min);
6135
6136 /* both of s64_max/s64_min positive or negative */
6137 if ((s64_max >= 0) == (s64_min >= 0)) {
6138 reg->smin_value = reg->s32_min_value = s64_min;
6139 reg->smax_value = reg->s32_max_value = s64_max;
6140 reg->umin_value = reg->u32_min_value = s64_min;
6141 reg->umax_value = reg->u32_max_value = s64_max;
6142 reg->var_off = tnum_range(s64_min, s64_max);
6143 return;
6144 }
6145
6146 out:
6147 set_sext64_default_val(reg, size);
6148 }
6149
set_sext32_default_val(struct bpf_reg_state * reg,int size)6150 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6151 {
6152 if (size == 1) {
6153 reg->s32_min_value = S8_MIN;
6154 reg->s32_max_value = S8_MAX;
6155 } else {
6156 /* size == 2 */
6157 reg->s32_min_value = S16_MIN;
6158 reg->s32_max_value = S16_MAX;
6159 }
6160 reg->u32_min_value = 0;
6161 reg->u32_max_value = U32_MAX;
6162 reg->var_off = tnum_subreg(tnum_unknown);
6163 }
6164
coerce_subreg_to_size_sx(struct bpf_reg_state * reg,int size)6165 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6166 {
6167 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6168 u32 top_smax_value, top_smin_value;
6169 u32 num_bits = size * 8;
6170
6171 if (tnum_is_const(reg->var_off)) {
6172 u32_val = reg->var_off.value;
6173 if (size == 1)
6174 reg->var_off = tnum_const((s8)u32_val);
6175 else
6176 reg->var_off = tnum_const((s16)u32_val);
6177
6178 u32_val = reg->var_off.value;
6179 reg->s32_min_value = reg->s32_max_value = u32_val;
6180 reg->u32_min_value = reg->u32_max_value = u32_val;
6181 return;
6182 }
6183
6184 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6185 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6186
6187 if (top_smax_value != top_smin_value)
6188 goto out;
6189
6190 /* find the s32_min and s32_min after sign extension */
6191 if (size == 1) {
6192 init_s32_max = (s8)reg->s32_max_value;
6193 init_s32_min = (s8)reg->s32_min_value;
6194 } else {
6195 /* size == 2 */
6196 init_s32_max = (s16)reg->s32_max_value;
6197 init_s32_min = (s16)reg->s32_min_value;
6198 }
6199 s32_max = max(init_s32_max, init_s32_min);
6200 s32_min = min(init_s32_max, init_s32_min);
6201
6202 if ((s32_min >= 0) == (s32_max >= 0)) {
6203 reg->s32_min_value = s32_min;
6204 reg->s32_max_value = s32_max;
6205 reg->u32_min_value = (u32)s32_min;
6206 reg->u32_max_value = (u32)s32_max;
6207 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max));
6208 return;
6209 }
6210
6211 out:
6212 set_sext32_default_val(reg, size);
6213 }
6214
bpf_map_is_rdonly(const struct bpf_map * map)6215 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6216 {
6217 /* A map is considered read-only if the following condition are true:
6218 *
6219 * 1) BPF program side cannot change any of the map content. The
6220 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6221 * and was set at map creation time.
6222 * 2) The map value(s) have been initialized from user space by a
6223 * loader and then "frozen", such that no new map update/delete
6224 * operations from syscall side are possible for the rest of
6225 * the map's lifetime from that point onwards.
6226 * 3) Any parallel/pending map update/delete operations from syscall
6227 * side have been completed. Only after that point, it's safe to
6228 * assume that map value(s) are immutable.
6229 */
6230 return (map->map_flags & BPF_F_RDONLY_PROG) &&
6231 READ_ONCE(map->frozen) &&
6232 !bpf_map_write_active(map);
6233 }
6234
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val,bool is_ldsx)6235 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6236 bool is_ldsx)
6237 {
6238 void *ptr;
6239 u64 addr;
6240 int err;
6241
6242 err = map->ops->map_direct_value_addr(map, &addr, off);
6243 if (err)
6244 return err;
6245 ptr = (void *)(long)addr + off;
6246
6247 switch (size) {
6248 case sizeof(u8):
6249 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6250 break;
6251 case sizeof(u16):
6252 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6253 break;
6254 case sizeof(u32):
6255 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6256 break;
6257 case sizeof(u64):
6258 *val = *(u64 *)ptr;
6259 break;
6260 default:
6261 return -EINVAL;
6262 }
6263 return 0;
6264 }
6265
6266 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu)
6267 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null)
6268 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted)
6269 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null)
6270
6271 /*
6272 * Allow list few fields as RCU trusted or full trusted.
6273 * This logic doesn't allow mix tagging and will be removed once GCC supports
6274 * btf_type_tag.
6275 */
6276
6277 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
BTF_TYPE_SAFE_RCU(struct task_struct)6278 BTF_TYPE_SAFE_RCU(struct task_struct) {
6279 const cpumask_t *cpus_ptr;
6280 struct css_set __rcu *cgroups;
6281 struct task_struct __rcu *real_parent;
6282 struct task_struct *group_leader;
6283 };
6284
BTF_TYPE_SAFE_RCU(struct cgroup)6285 BTF_TYPE_SAFE_RCU(struct cgroup) {
6286 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6287 struct kernfs_node *kn;
6288 };
6289
BTF_TYPE_SAFE_RCU(struct css_set)6290 BTF_TYPE_SAFE_RCU(struct css_set) {
6291 struct cgroup *dfl_cgrp;
6292 };
6293
6294 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)6295 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6296 struct file __rcu *exe_file;
6297 };
6298
6299 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6300 * because bpf prog accessible sockets are SOCK_RCU_FREE.
6301 */
BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)6302 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6303 struct sock *sk;
6304 };
6305
BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)6306 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6307 struct sock *sk;
6308 };
6309
6310 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)6311 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6312 struct seq_file *seq;
6313 };
6314
BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)6315 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6316 struct bpf_iter_meta *meta;
6317 struct task_struct *task;
6318 };
6319
BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)6320 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6321 struct file *file;
6322 };
6323
BTF_TYPE_SAFE_TRUSTED(struct file)6324 BTF_TYPE_SAFE_TRUSTED(struct file) {
6325 struct inode *f_inode;
6326 };
6327
BTF_TYPE_SAFE_TRUSTED(struct dentry)6328 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6329 /* no negative dentry-s in places where bpf can see it */
6330 struct inode *d_inode;
6331 };
6332
BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)6333 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
6334 struct sock *sk;
6335 };
6336
type_is_rcu(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6337 static bool type_is_rcu(struct bpf_verifier_env *env,
6338 struct bpf_reg_state *reg,
6339 const char *field_name, u32 btf_id)
6340 {
6341 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6342 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6343 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6344
6345 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6346 }
6347
type_is_rcu_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6348 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6349 struct bpf_reg_state *reg,
6350 const char *field_name, u32 btf_id)
6351 {
6352 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6353 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6354 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6355
6356 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6357 }
6358
type_is_trusted(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6359 static bool type_is_trusted(struct bpf_verifier_env *env,
6360 struct bpf_reg_state *reg,
6361 const char *field_name, u32 btf_id)
6362 {
6363 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6364 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6365 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6366 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6367 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6368
6369 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6370 }
6371
type_is_trusted_or_null(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const char * field_name,u32 btf_id)6372 static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
6373 struct bpf_reg_state *reg,
6374 const char *field_name, u32 btf_id)
6375 {
6376 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
6377
6378 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
6379 "__safe_trusted_or_null");
6380 }
6381
check_ptr_to_btf_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)6382 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6383 struct bpf_reg_state *regs,
6384 int regno, int off, int size,
6385 enum bpf_access_type atype,
6386 int value_regno)
6387 {
6388 struct bpf_reg_state *reg = regs + regno;
6389 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6390 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6391 const char *field_name = NULL;
6392 enum bpf_type_flag flag = 0;
6393 u32 btf_id = 0;
6394 int ret;
6395
6396 if (!env->allow_ptr_leaks) {
6397 verbose(env,
6398 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6399 tname);
6400 return -EPERM;
6401 }
6402 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6403 verbose(env,
6404 "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6405 tname);
6406 return -EINVAL;
6407 }
6408 if (off < 0) {
6409 verbose(env,
6410 "R%d is ptr_%s invalid negative access: off=%d\n",
6411 regno, tname, off);
6412 return -EACCES;
6413 }
6414 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6415 char tn_buf[48];
6416
6417 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6418 verbose(env,
6419 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6420 regno, tname, off, tn_buf);
6421 return -EACCES;
6422 }
6423
6424 if (reg->type & MEM_USER) {
6425 verbose(env,
6426 "R%d is ptr_%s access user memory: off=%d\n",
6427 regno, tname, off);
6428 return -EACCES;
6429 }
6430
6431 if (reg->type & MEM_PERCPU) {
6432 verbose(env,
6433 "R%d is ptr_%s access percpu memory: off=%d\n",
6434 regno, tname, off);
6435 return -EACCES;
6436 }
6437
6438 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6439 if (!btf_is_kernel(reg->btf)) {
6440 verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6441 return -EFAULT;
6442 }
6443 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6444 } else {
6445 /* Writes are permitted with default btf_struct_access for
6446 * program allocated objects (which always have ref_obj_id > 0),
6447 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6448 */
6449 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6450 verbose(env, "only read is supported\n");
6451 return -EACCES;
6452 }
6453
6454 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6455 !reg->ref_obj_id) {
6456 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6457 return -EFAULT;
6458 }
6459
6460 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6461 }
6462
6463 if (ret < 0)
6464 return ret;
6465
6466 if (ret != PTR_TO_BTF_ID) {
6467 /* just mark; */
6468
6469 } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6470 /* If this is an untrusted pointer, all pointers formed by walking it
6471 * also inherit the untrusted flag.
6472 */
6473 flag = PTR_UNTRUSTED;
6474
6475 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6476 /* By default any pointer obtained from walking a trusted pointer is no
6477 * longer trusted, unless the field being accessed has explicitly been
6478 * marked as inheriting its parent's state of trust (either full or RCU).
6479 * For example:
6480 * 'cgroups' pointer is untrusted if task->cgroups dereference
6481 * happened in a sleepable program outside of bpf_rcu_read_lock()
6482 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6483 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6484 *
6485 * A regular RCU-protected pointer with __rcu tag can also be deemed
6486 * trusted if we are in an RCU CS. Such pointer can be NULL.
6487 */
6488 if (type_is_trusted(env, reg, field_name, btf_id)) {
6489 flag |= PTR_TRUSTED;
6490 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
6491 flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
6492 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6493 if (type_is_rcu(env, reg, field_name, btf_id)) {
6494 /* ignore __rcu tag and mark it MEM_RCU */
6495 flag |= MEM_RCU;
6496 } else if (flag & MEM_RCU ||
6497 type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6498 /* __rcu tagged pointers can be NULL */
6499 flag |= MEM_RCU | PTR_MAYBE_NULL;
6500
6501 /* We always trust them */
6502 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6503 flag & PTR_UNTRUSTED)
6504 flag &= ~PTR_UNTRUSTED;
6505 } else if (flag & (MEM_PERCPU | MEM_USER)) {
6506 /* keep as-is */
6507 } else {
6508 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6509 clear_trusted_flags(&flag);
6510 }
6511 } else {
6512 /*
6513 * If not in RCU CS or MEM_RCU pointer can be NULL then
6514 * aggressively mark as untrusted otherwise such
6515 * pointers will be plain PTR_TO_BTF_ID without flags
6516 * and will be allowed to be passed into helpers for
6517 * compat reasons.
6518 */
6519 flag = PTR_UNTRUSTED;
6520 }
6521 } else {
6522 /* Old compat. Deprecated */
6523 clear_trusted_flags(&flag);
6524 }
6525
6526 if (atype == BPF_READ && value_regno >= 0)
6527 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6528
6529 return 0;
6530 }
6531
check_ptr_to_map_access(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int regno,int off,int size,enum bpf_access_type atype,int value_regno)6532 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6533 struct bpf_reg_state *regs,
6534 int regno, int off, int size,
6535 enum bpf_access_type atype,
6536 int value_regno)
6537 {
6538 struct bpf_reg_state *reg = regs + regno;
6539 struct bpf_map *map = reg->map_ptr;
6540 struct bpf_reg_state map_reg;
6541 enum bpf_type_flag flag = 0;
6542 const struct btf_type *t;
6543 const char *tname;
6544 u32 btf_id;
6545 int ret;
6546
6547 if (!btf_vmlinux) {
6548 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6549 return -ENOTSUPP;
6550 }
6551
6552 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6553 verbose(env, "map_ptr access not supported for map type %d\n",
6554 map->map_type);
6555 return -ENOTSUPP;
6556 }
6557
6558 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6559 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6560
6561 if (!env->allow_ptr_leaks) {
6562 verbose(env,
6563 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6564 tname);
6565 return -EPERM;
6566 }
6567
6568 if (off < 0) {
6569 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6570 regno, tname, off);
6571 return -EACCES;
6572 }
6573
6574 if (atype != BPF_READ) {
6575 verbose(env, "only read from %s is supported\n", tname);
6576 return -EACCES;
6577 }
6578
6579 /* Simulate access to a PTR_TO_BTF_ID */
6580 memset(&map_reg, 0, sizeof(map_reg));
6581 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6582 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6583 if (ret < 0)
6584 return ret;
6585
6586 if (value_regno >= 0)
6587 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6588
6589 return 0;
6590 }
6591
6592 /* Check that the stack access at the given offset is within bounds. The
6593 * maximum valid offset is -1.
6594 *
6595 * The minimum valid offset is -MAX_BPF_STACK for writes, and
6596 * -state->allocated_stack for reads.
6597 */
check_stack_slot_within_bounds(struct bpf_verifier_env * env,s64 off,struct bpf_func_state * state,enum bpf_access_type t)6598 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env,
6599 s64 off,
6600 struct bpf_func_state *state,
6601 enum bpf_access_type t)
6602 {
6603 int min_valid_off;
6604
6605 if (t == BPF_WRITE || env->allow_uninit_stack)
6606 min_valid_off = -MAX_BPF_STACK;
6607 else
6608 min_valid_off = -state->allocated_stack;
6609
6610 if (off < min_valid_off || off > -1)
6611 return -EACCES;
6612 return 0;
6613 }
6614
6615 /* Check that the stack access at 'regno + off' falls within the maximum stack
6616 * bounds.
6617 *
6618 * 'off' includes `regno->offset`, but not its dynamic part (if any).
6619 */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum bpf_access_src src,enum bpf_access_type type)6620 static int check_stack_access_within_bounds(
6621 struct bpf_verifier_env *env,
6622 int regno, int off, int access_size,
6623 enum bpf_access_src src, enum bpf_access_type type)
6624 {
6625 struct bpf_reg_state *regs = cur_regs(env);
6626 struct bpf_reg_state *reg = regs + regno;
6627 struct bpf_func_state *state = func(env, reg);
6628 s64 min_off, max_off;
6629 int err;
6630 char *err_extra;
6631
6632 if (src == ACCESS_HELPER)
6633 /* We don't know if helpers are reading or writing (or both). */
6634 err_extra = " indirect access to";
6635 else if (type == BPF_READ)
6636 err_extra = " read from";
6637 else
6638 err_extra = " write to";
6639
6640 if (tnum_is_const(reg->var_off)) {
6641 min_off = (s64)reg->var_off.value + off;
6642 max_off = min_off + access_size;
6643 } else {
6644 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6645 reg->smin_value <= -BPF_MAX_VAR_OFF) {
6646 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6647 err_extra, regno);
6648 return -EACCES;
6649 }
6650 min_off = reg->smin_value + off;
6651 max_off = reg->smax_value + off + access_size;
6652 }
6653
6654 err = check_stack_slot_within_bounds(env, min_off, state, type);
6655 if (!err && max_off > 0)
6656 err = -EINVAL; /* out of stack access into non-negative offsets */
6657 if (!err && access_size < 0)
6658 /* access_size should not be negative (or overflow an int); others checks
6659 * along the way should have prevented such an access.
6660 */
6661 err = -EFAULT; /* invalid negative access size; integer overflow? */
6662
6663 if (err) {
6664 if (tnum_is_const(reg->var_off)) {
6665 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6666 err_extra, regno, off, access_size);
6667 } else {
6668 char tn_buf[48];
6669
6670 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6671 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6672 err_extra, regno, tn_buf, access_size);
6673 }
6674 return err;
6675 }
6676
6677 return grow_stack_state(env, state, round_up(-min_off, BPF_REG_SIZE));
6678 }
6679
6680 /* check whether memory at (regno + off) is accessible for t = (read | write)
6681 * if t==write, value_regno is a register which value is stored into memory
6682 * if t==read, value_regno is a register which will receive the value from memory
6683 * if t==write && value_regno==-1, some unknown value is stored into memory
6684 * if t==read && value_regno==-1, don't care what we read from memory
6685 */
check_mem_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno,bool strict_alignment_once,bool is_ldsx)6686 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6687 int off, int bpf_size, enum bpf_access_type t,
6688 int value_regno, bool strict_alignment_once, bool is_ldsx)
6689 {
6690 struct bpf_reg_state *regs = cur_regs(env);
6691 struct bpf_reg_state *reg = regs + regno;
6692 int size, err = 0;
6693
6694 size = bpf_size_to_bytes(bpf_size);
6695 if (size < 0)
6696 return size;
6697
6698 /* alignment checks will add in reg->off themselves */
6699 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6700 if (err)
6701 return err;
6702
6703 /* for access checks, reg->off is just part of off */
6704 off += reg->off;
6705
6706 if (reg->type == PTR_TO_MAP_KEY) {
6707 if (t == BPF_WRITE) {
6708 verbose(env, "write to change key R%d not allowed\n", regno);
6709 return -EACCES;
6710 }
6711
6712 err = check_mem_region_access(env, regno, off, size,
6713 reg->map_ptr->key_size, false);
6714 if (err)
6715 return err;
6716 if (value_regno >= 0)
6717 mark_reg_unknown(env, regs, value_regno);
6718 } else if (reg->type == PTR_TO_MAP_VALUE) {
6719 struct btf_field *kptr_field = NULL;
6720
6721 if (t == BPF_WRITE && value_regno >= 0 &&
6722 is_pointer_value(env, value_regno)) {
6723 verbose(env, "R%d leaks addr into map\n", value_regno);
6724 return -EACCES;
6725 }
6726 err = check_map_access_type(env, regno, off, size, t);
6727 if (err)
6728 return err;
6729 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6730 if (err)
6731 return err;
6732 if (tnum_is_const(reg->var_off))
6733 kptr_field = btf_record_find(reg->map_ptr->record,
6734 off + reg->var_off.value, BPF_KPTR);
6735 if (kptr_field) {
6736 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6737 } else if (t == BPF_READ && value_regno >= 0) {
6738 struct bpf_map *map = reg->map_ptr;
6739
6740 /* if map is read-only, track its contents as scalars */
6741 if (tnum_is_const(reg->var_off) &&
6742 bpf_map_is_rdonly(map) &&
6743 map->ops->map_direct_value_addr) {
6744 int map_off = off + reg->var_off.value;
6745 u64 val = 0;
6746
6747 err = bpf_map_direct_read(map, map_off, size,
6748 &val, is_ldsx);
6749 if (err)
6750 return err;
6751
6752 regs[value_regno].type = SCALAR_VALUE;
6753 __mark_reg_known(®s[value_regno], val);
6754 } else {
6755 mark_reg_unknown(env, regs, value_regno);
6756 }
6757 }
6758 } else if (base_type(reg->type) == PTR_TO_MEM) {
6759 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6760
6761 if (type_may_be_null(reg->type)) {
6762 verbose(env, "R%d invalid mem access '%s'\n", regno,
6763 reg_type_str(env, reg->type));
6764 return -EACCES;
6765 }
6766
6767 if (t == BPF_WRITE && rdonly_mem) {
6768 verbose(env, "R%d cannot write into %s\n",
6769 regno, reg_type_str(env, reg->type));
6770 return -EACCES;
6771 }
6772
6773 if (t == BPF_WRITE && value_regno >= 0 &&
6774 is_pointer_value(env, value_regno)) {
6775 verbose(env, "R%d leaks addr into mem\n", value_regno);
6776 return -EACCES;
6777 }
6778
6779 err = check_mem_region_access(env, regno, off, size,
6780 reg->mem_size, false);
6781 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6782 mark_reg_unknown(env, regs, value_regno);
6783 } else if (reg->type == PTR_TO_CTX) {
6784 enum bpf_reg_type reg_type = SCALAR_VALUE;
6785 struct btf *btf = NULL;
6786 u32 btf_id = 0;
6787
6788 if (t == BPF_WRITE && value_regno >= 0 &&
6789 is_pointer_value(env, value_regno)) {
6790 verbose(env, "R%d leaks addr into ctx\n", value_regno);
6791 return -EACCES;
6792 }
6793
6794 err = check_ptr_off_reg(env, reg, regno);
6795 if (err < 0)
6796 return err;
6797
6798 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
6799 &btf_id);
6800 if (err)
6801 verbose_linfo(env, insn_idx, "; ");
6802 if (!err && t == BPF_READ && value_regno >= 0) {
6803 /* ctx access returns either a scalar, or a
6804 * PTR_TO_PACKET[_META,_END]. In the latter
6805 * case, we know the offset is zero.
6806 */
6807 if (reg_type == SCALAR_VALUE) {
6808 mark_reg_unknown(env, regs, value_regno);
6809 } else {
6810 mark_reg_known_zero(env, regs,
6811 value_regno);
6812 if (type_may_be_null(reg_type))
6813 regs[value_regno].id = ++env->id_gen;
6814 /* A load of ctx field could have different
6815 * actual load size with the one encoded in the
6816 * insn. When the dst is PTR, it is for sure not
6817 * a sub-register.
6818 */
6819 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6820 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6821 regs[value_regno].btf = btf;
6822 regs[value_regno].btf_id = btf_id;
6823 }
6824 }
6825 regs[value_regno].type = reg_type;
6826 }
6827
6828 } else if (reg->type == PTR_TO_STACK) {
6829 /* Basic bounds checks. */
6830 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6831 if (err)
6832 return err;
6833
6834 if (t == BPF_READ)
6835 err = check_stack_read(env, regno, off, size,
6836 value_regno);
6837 else
6838 err = check_stack_write(env, regno, off, size,
6839 value_regno, insn_idx);
6840 } else if (reg_is_pkt_pointer(reg)) {
6841 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6842 verbose(env, "cannot write into packet\n");
6843 return -EACCES;
6844 }
6845 if (t == BPF_WRITE && value_regno >= 0 &&
6846 is_pointer_value(env, value_regno)) {
6847 verbose(env, "R%d leaks addr into packet\n",
6848 value_regno);
6849 return -EACCES;
6850 }
6851 err = check_packet_access(env, regno, off, size, false);
6852 if (!err && t == BPF_READ && value_regno >= 0)
6853 mark_reg_unknown(env, regs, value_regno);
6854 } else if (reg->type == PTR_TO_FLOW_KEYS) {
6855 if (t == BPF_WRITE && value_regno >= 0 &&
6856 is_pointer_value(env, value_regno)) {
6857 verbose(env, "R%d leaks addr into flow keys\n",
6858 value_regno);
6859 return -EACCES;
6860 }
6861
6862 err = check_flow_keys_access(env, off, size);
6863 if (!err && t == BPF_READ && value_regno >= 0)
6864 mark_reg_unknown(env, regs, value_regno);
6865 } else if (type_is_sk_pointer(reg->type)) {
6866 if (t == BPF_WRITE) {
6867 verbose(env, "R%d cannot write into %s\n",
6868 regno, reg_type_str(env, reg->type));
6869 return -EACCES;
6870 }
6871 err = check_sock_access(env, insn_idx, regno, off, size, t);
6872 if (!err && value_regno >= 0)
6873 mark_reg_unknown(env, regs, value_regno);
6874 } else if (reg->type == PTR_TO_TP_BUFFER) {
6875 err = check_tp_buffer_access(env, reg, regno, off, size);
6876 if (!err && t == BPF_READ && value_regno >= 0)
6877 mark_reg_unknown(env, regs, value_regno);
6878 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6879 !type_may_be_null(reg->type)) {
6880 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6881 value_regno);
6882 } else if (reg->type == CONST_PTR_TO_MAP) {
6883 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6884 value_regno);
6885 } else if (base_type(reg->type) == PTR_TO_BUF) {
6886 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6887 u32 *max_access;
6888
6889 if (rdonly_mem) {
6890 if (t == BPF_WRITE) {
6891 verbose(env, "R%d cannot write into %s\n",
6892 regno, reg_type_str(env, reg->type));
6893 return -EACCES;
6894 }
6895 max_access = &env->prog->aux->max_rdonly_access;
6896 } else {
6897 max_access = &env->prog->aux->max_rdwr_access;
6898 }
6899
6900 err = check_buffer_access(env, reg, regno, off, size, false,
6901 max_access);
6902
6903 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6904 mark_reg_unknown(env, regs, value_regno);
6905 } else {
6906 verbose(env, "R%d invalid mem access '%s'\n", regno,
6907 reg_type_str(env, reg->type));
6908 return -EACCES;
6909 }
6910
6911 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6912 regs[value_regno].type == SCALAR_VALUE) {
6913 if (!is_ldsx)
6914 /* b/h/w load zero-extends, mark upper bits as known 0 */
6915 coerce_reg_to_size(®s[value_regno], size);
6916 else
6917 coerce_reg_to_size_sx(®s[value_regno], size);
6918 }
6919 return err;
6920 }
6921
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)6922 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6923 {
6924 int load_reg;
6925 int err;
6926
6927 switch (insn->imm) {
6928 case BPF_ADD:
6929 case BPF_ADD | BPF_FETCH:
6930 case BPF_AND:
6931 case BPF_AND | BPF_FETCH:
6932 case BPF_OR:
6933 case BPF_OR | BPF_FETCH:
6934 case BPF_XOR:
6935 case BPF_XOR | BPF_FETCH:
6936 case BPF_XCHG:
6937 case BPF_CMPXCHG:
6938 break;
6939 default:
6940 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6941 return -EINVAL;
6942 }
6943
6944 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6945 verbose(env, "invalid atomic operand size\n");
6946 return -EINVAL;
6947 }
6948
6949 /* check src1 operand */
6950 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6951 if (err)
6952 return err;
6953
6954 /* check src2 operand */
6955 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6956 if (err)
6957 return err;
6958
6959 if (insn->imm == BPF_CMPXCHG) {
6960 /* Check comparison of R0 with memory location */
6961 const u32 aux_reg = BPF_REG_0;
6962
6963 err = check_reg_arg(env, aux_reg, SRC_OP);
6964 if (err)
6965 return err;
6966
6967 if (is_pointer_value(env, aux_reg)) {
6968 verbose(env, "R%d leaks addr into mem\n", aux_reg);
6969 return -EACCES;
6970 }
6971 }
6972
6973 if (is_pointer_value(env, insn->src_reg)) {
6974 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6975 return -EACCES;
6976 }
6977
6978 if (is_ctx_reg(env, insn->dst_reg) ||
6979 is_pkt_reg(env, insn->dst_reg) ||
6980 is_flow_key_reg(env, insn->dst_reg) ||
6981 is_sk_reg(env, insn->dst_reg)) {
6982 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6983 insn->dst_reg,
6984 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6985 return -EACCES;
6986 }
6987
6988 if (insn->imm & BPF_FETCH) {
6989 if (insn->imm == BPF_CMPXCHG)
6990 load_reg = BPF_REG_0;
6991 else
6992 load_reg = insn->src_reg;
6993
6994 /* check and record load of old value */
6995 err = check_reg_arg(env, load_reg, DST_OP);
6996 if (err)
6997 return err;
6998 } else {
6999 /* This instruction accesses a memory location but doesn't
7000 * actually load it into a register.
7001 */
7002 load_reg = -1;
7003 }
7004
7005 /* Check whether we can read the memory, with second call for fetch
7006 * case to simulate the register fill.
7007 */
7008 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7009 BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7010 if (!err && load_reg >= 0)
7011 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7012 BPF_SIZE(insn->code), BPF_READ, load_reg,
7013 true, false);
7014 if (err)
7015 return err;
7016
7017 /* Check whether we can write into the same memory. */
7018 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7019 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7020 if (err)
7021 return err;
7022
7023 return 0;
7024 }
7025
7026 /* When register 'regno' is used to read the stack (either directly or through
7027 * a helper function) make sure that it's within stack boundary and, depending
7028 * on the access type and privileges, that all elements of the stack are
7029 * initialized.
7030 *
7031 * 'off' includes 'regno->off', but not its dynamic part (if any).
7032 *
7033 * All registers that have been spilled on the stack in the slots within the
7034 * read offsets are marked as read.
7035 */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum bpf_access_src type,struct bpf_call_arg_meta * meta)7036 static int check_stack_range_initialized(
7037 struct bpf_verifier_env *env, int regno, int off,
7038 int access_size, bool zero_size_allowed,
7039 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7040 {
7041 struct bpf_reg_state *reg = reg_state(env, regno);
7042 struct bpf_func_state *state = func(env, reg);
7043 int err, min_off, max_off, i, j, slot, spi;
7044 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7045 enum bpf_access_type bounds_check_type;
7046 /* Some accesses can write anything into the stack, others are
7047 * read-only.
7048 */
7049 bool clobber = false;
7050
7051 if (access_size == 0 && !zero_size_allowed) {
7052 verbose(env, "invalid zero-sized read\n");
7053 return -EACCES;
7054 }
7055
7056 if (type == ACCESS_HELPER) {
7057 /* The bounds checks for writes are more permissive than for
7058 * reads. However, if raw_mode is not set, we'll do extra
7059 * checks below.
7060 */
7061 bounds_check_type = BPF_WRITE;
7062 clobber = true;
7063 } else {
7064 bounds_check_type = BPF_READ;
7065 }
7066 err = check_stack_access_within_bounds(env, regno, off, access_size,
7067 type, bounds_check_type);
7068 if (err)
7069 return err;
7070
7071
7072 if (tnum_is_const(reg->var_off)) {
7073 min_off = max_off = reg->var_off.value + off;
7074 } else {
7075 /* Variable offset is prohibited for unprivileged mode for
7076 * simplicity since it requires corresponding support in
7077 * Spectre masking for stack ALU.
7078 * See also retrieve_ptr_limit().
7079 */
7080 if (!env->bypass_spec_v1) {
7081 char tn_buf[48];
7082
7083 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7084 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7085 regno, err_extra, tn_buf);
7086 return -EACCES;
7087 }
7088 /* Only initialized buffer on stack is allowed to be accessed
7089 * with variable offset. With uninitialized buffer it's hard to
7090 * guarantee that whole memory is marked as initialized on
7091 * helper return since specific bounds are unknown what may
7092 * cause uninitialized stack leaking.
7093 */
7094 if (meta && meta->raw_mode)
7095 meta = NULL;
7096
7097 min_off = reg->smin_value + off;
7098 max_off = reg->smax_value + off;
7099 }
7100
7101 if (meta && meta->raw_mode) {
7102 /* Ensure we won't be overwriting dynptrs when simulating byte
7103 * by byte access in check_helper_call using meta.access_size.
7104 * This would be a problem if we have a helper in the future
7105 * which takes:
7106 *
7107 * helper(uninit_mem, len, dynptr)
7108 *
7109 * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7110 * may end up writing to dynptr itself when touching memory from
7111 * arg 1. This can be relaxed on a case by case basis for known
7112 * safe cases, but reject due to the possibilitiy of aliasing by
7113 * default.
7114 */
7115 for (i = min_off; i < max_off + access_size; i++) {
7116 int stack_off = -i - 1;
7117
7118 spi = __get_spi(i);
7119 /* raw_mode may write past allocated_stack */
7120 if (state->allocated_stack <= stack_off)
7121 continue;
7122 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7123 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7124 return -EACCES;
7125 }
7126 }
7127 meta->access_size = access_size;
7128 meta->regno = regno;
7129 return 0;
7130 }
7131
7132 for (i = min_off; i < max_off + access_size; i++) {
7133 u8 *stype;
7134
7135 slot = -i - 1;
7136 spi = slot / BPF_REG_SIZE;
7137 if (state->allocated_stack <= slot) {
7138 verbose(env, "verifier bug: allocated_stack too small");
7139 return -EFAULT;
7140 }
7141
7142 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7143 if (*stype == STACK_MISC)
7144 goto mark;
7145 if ((*stype == STACK_ZERO) ||
7146 (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7147 if (clobber) {
7148 /* helper can write anything into the stack */
7149 *stype = STACK_MISC;
7150 }
7151 goto mark;
7152 }
7153
7154 if (is_spilled_reg(&state->stack[spi]) &&
7155 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7156 env->allow_ptr_leaks)) {
7157 if (clobber) {
7158 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7159 for (j = 0; j < BPF_REG_SIZE; j++)
7160 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7161 }
7162 goto mark;
7163 }
7164
7165 if (tnum_is_const(reg->var_off)) {
7166 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7167 err_extra, regno, min_off, i - min_off, access_size);
7168 } else {
7169 char tn_buf[48];
7170
7171 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7172 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7173 err_extra, regno, tn_buf, i - min_off, access_size);
7174 }
7175 return -EACCES;
7176 mark:
7177 /* reading any byte out of 8-byte 'spill_slot' will cause
7178 * the whole slot to be marked as 'read'
7179 */
7180 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7181 state->stack[spi].spilled_ptr.parent,
7182 REG_LIVE_READ64);
7183 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7184 * be sure that whether stack slot is written to or not. Hence,
7185 * we must still conservatively propagate reads upwards even if
7186 * helper may write to the entire memory range.
7187 */
7188 }
7189 return 0;
7190 }
7191
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7192 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7193 int access_size, bool zero_size_allowed,
7194 struct bpf_call_arg_meta *meta)
7195 {
7196 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7197 u32 *max_access;
7198
7199 switch (base_type(reg->type)) {
7200 case PTR_TO_PACKET:
7201 case PTR_TO_PACKET_META:
7202 return check_packet_access(env, regno, reg->off, access_size,
7203 zero_size_allowed);
7204 case PTR_TO_MAP_KEY:
7205 if (meta && meta->raw_mode) {
7206 verbose(env, "R%d cannot write into %s\n", regno,
7207 reg_type_str(env, reg->type));
7208 return -EACCES;
7209 }
7210 return check_mem_region_access(env, regno, reg->off, access_size,
7211 reg->map_ptr->key_size, false);
7212 case PTR_TO_MAP_VALUE:
7213 if (check_map_access_type(env, regno, reg->off, access_size,
7214 meta && meta->raw_mode ? BPF_WRITE :
7215 BPF_READ))
7216 return -EACCES;
7217 return check_map_access(env, regno, reg->off, access_size,
7218 zero_size_allowed, ACCESS_HELPER);
7219 case PTR_TO_MEM:
7220 if (type_is_rdonly_mem(reg->type)) {
7221 if (meta && meta->raw_mode) {
7222 verbose(env, "R%d cannot write into %s\n", regno,
7223 reg_type_str(env, reg->type));
7224 return -EACCES;
7225 }
7226 }
7227 return check_mem_region_access(env, regno, reg->off,
7228 access_size, reg->mem_size,
7229 zero_size_allowed);
7230 case PTR_TO_BUF:
7231 if (type_is_rdonly_mem(reg->type)) {
7232 if (meta && meta->raw_mode) {
7233 verbose(env, "R%d cannot write into %s\n", regno,
7234 reg_type_str(env, reg->type));
7235 return -EACCES;
7236 }
7237
7238 max_access = &env->prog->aux->max_rdonly_access;
7239 } else {
7240 max_access = &env->prog->aux->max_rdwr_access;
7241 }
7242 return check_buffer_access(env, reg, regno, reg->off,
7243 access_size, zero_size_allowed,
7244 max_access);
7245 case PTR_TO_STACK:
7246 return check_stack_range_initialized(
7247 env,
7248 regno, reg->off, access_size,
7249 zero_size_allowed, ACCESS_HELPER, meta);
7250 case PTR_TO_BTF_ID:
7251 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7252 access_size, BPF_READ, -1);
7253 case PTR_TO_CTX:
7254 /* in case the function doesn't know how to access the context,
7255 * (because we are in a program of type SYSCALL for example), we
7256 * can not statically check its size.
7257 * Dynamically check it now.
7258 */
7259 if (!env->ops->convert_ctx_access) {
7260 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7261 int offset = access_size - 1;
7262
7263 /* Allow zero-byte read from PTR_TO_CTX */
7264 if (access_size == 0)
7265 return zero_size_allowed ? 0 : -EACCES;
7266
7267 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7268 atype, -1, false, false);
7269 }
7270
7271 fallthrough;
7272 default: /* scalar_value or invalid ptr */
7273 /* Allow zero-byte read from NULL, regardless of pointer type */
7274 if (zero_size_allowed && access_size == 0 &&
7275 register_is_null(reg))
7276 return 0;
7277
7278 verbose(env, "R%d type=%s ", regno,
7279 reg_type_str(env, reg->type));
7280 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7281 return -EACCES;
7282 }
7283 }
7284
check_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,bool zero_size_allowed,struct bpf_call_arg_meta * meta)7285 static int check_mem_size_reg(struct bpf_verifier_env *env,
7286 struct bpf_reg_state *reg, u32 regno,
7287 bool zero_size_allowed,
7288 struct bpf_call_arg_meta *meta)
7289 {
7290 int err;
7291
7292 /* This is used to refine r0 return value bounds for helpers
7293 * that enforce this value as an upper bound on return values.
7294 * See do_refine_retval_range() for helpers that can refine
7295 * the return value. C type of helper is u32 so we pull register
7296 * bound from umax_value however, if negative verifier errors
7297 * out. Only upper bounds can be learned because retval is an
7298 * int type and negative retvals are allowed.
7299 */
7300 meta->msize_max_value = reg->umax_value;
7301
7302 /* The register is SCALAR_VALUE; the access check
7303 * happens using its boundaries.
7304 */
7305 if (!tnum_is_const(reg->var_off))
7306 /* For unprivileged variable accesses, disable raw
7307 * mode so that the program is required to
7308 * initialize all the memory that the helper could
7309 * just partially fill up.
7310 */
7311 meta = NULL;
7312
7313 if (reg->smin_value < 0) {
7314 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7315 regno);
7316 return -EACCES;
7317 }
7318
7319 if (reg->umin_value == 0) {
7320 err = check_helper_mem_access(env, regno - 1, 0,
7321 zero_size_allowed,
7322 meta);
7323 if (err)
7324 return err;
7325 }
7326
7327 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7328 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7329 regno);
7330 return -EACCES;
7331 }
7332 err = check_helper_mem_access(env, regno - 1,
7333 reg->umax_value,
7334 zero_size_allowed, meta);
7335 if (!err)
7336 err = mark_chain_precision(env, regno);
7337 return err;
7338 }
7339
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)7340 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7341 u32 regno, u32 mem_size)
7342 {
7343 bool may_be_null = type_may_be_null(reg->type);
7344 struct bpf_reg_state saved_reg;
7345 struct bpf_call_arg_meta meta;
7346 int err;
7347
7348 if (register_is_null(reg))
7349 return 0;
7350
7351 memset(&meta, 0, sizeof(meta));
7352 /* Assuming that the register contains a value check if the memory
7353 * access is safe. Temporarily save and restore the register's state as
7354 * the conversion shouldn't be visible to a caller.
7355 */
7356 if (may_be_null) {
7357 saved_reg = *reg;
7358 mark_ptr_not_null_reg(reg);
7359 }
7360
7361 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7362 /* Check access for BPF_WRITE */
7363 meta.raw_mode = true;
7364 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7365
7366 if (may_be_null)
7367 *reg = saved_reg;
7368
7369 return err;
7370 }
7371
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)7372 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7373 u32 regno)
7374 {
7375 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7376 bool may_be_null = type_may_be_null(mem_reg->type);
7377 struct bpf_reg_state saved_reg;
7378 struct bpf_call_arg_meta meta;
7379 int err;
7380
7381 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7382
7383 memset(&meta, 0, sizeof(meta));
7384
7385 if (may_be_null) {
7386 saved_reg = *mem_reg;
7387 mark_ptr_not_null_reg(mem_reg);
7388 }
7389
7390 err = check_mem_size_reg(env, reg, regno, true, &meta);
7391 /* Check access for BPF_WRITE */
7392 meta.raw_mode = true;
7393 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7394
7395 if (may_be_null)
7396 *mem_reg = saved_reg;
7397 return err;
7398 }
7399
7400 /* Implementation details:
7401 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7402 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7403 * Two bpf_map_lookups (even with the same key) will have different reg->id.
7404 * Two separate bpf_obj_new will also have different reg->id.
7405 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7406 * clears reg->id after value_or_null->value transition, since the verifier only
7407 * cares about the range of access to valid map value pointer and doesn't care
7408 * about actual address of the map element.
7409 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7410 * reg->id > 0 after value_or_null->value transition. By doing so
7411 * two bpf_map_lookups will be considered two different pointers that
7412 * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7413 * returned from bpf_obj_new.
7414 * The verifier allows taking only one bpf_spin_lock at a time to avoid
7415 * dead-locks.
7416 * Since only one bpf_spin_lock is allowed the checks are simpler than
7417 * reg_is_refcounted() logic. The verifier needs to remember only
7418 * one spin_lock instead of array of acquired_refs.
7419 * cur_state->active_lock remembers which map value element or allocated
7420 * object got locked and clears it after bpf_spin_unlock.
7421 */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)7422 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7423 bool is_lock)
7424 {
7425 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7426 struct bpf_verifier_state *cur = env->cur_state;
7427 bool is_const = tnum_is_const(reg->var_off);
7428 u64 val = reg->var_off.value;
7429 struct bpf_map *map = NULL;
7430 struct btf *btf = NULL;
7431 struct btf_record *rec;
7432
7433 if (!is_const) {
7434 verbose(env,
7435 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7436 regno);
7437 return -EINVAL;
7438 }
7439 if (reg->type == PTR_TO_MAP_VALUE) {
7440 map = reg->map_ptr;
7441 if (!map->btf) {
7442 verbose(env,
7443 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7444 map->name);
7445 return -EINVAL;
7446 }
7447 } else {
7448 btf = reg->btf;
7449 }
7450
7451 rec = reg_btf_record(reg);
7452 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7453 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7454 map ? map->name : "kptr");
7455 return -EINVAL;
7456 }
7457 if (rec->spin_lock_off != val + reg->off) {
7458 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7459 val + reg->off, rec->spin_lock_off);
7460 return -EINVAL;
7461 }
7462 if (is_lock) {
7463 if (cur->active_lock.ptr) {
7464 verbose(env,
7465 "Locking two bpf_spin_locks are not allowed\n");
7466 return -EINVAL;
7467 }
7468 if (map)
7469 cur->active_lock.ptr = map;
7470 else
7471 cur->active_lock.ptr = btf;
7472 cur->active_lock.id = reg->id;
7473 } else {
7474 void *ptr;
7475
7476 if (map)
7477 ptr = map;
7478 else
7479 ptr = btf;
7480
7481 if (!cur->active_lock.ptr) {
7482 verbose(env, "bpf_spin_unlock without taking a lock\n");
7483 return -EINVAL;
7484 }
7485 if (cur->active_lock.ptr != ptr ||
7486 cur->active_lock.id != reg->id) {
7487 verbose(env, "bpf_spin_unlock of different lock\n");
7488 return -EINVAL;
7489 }
7490
7491 invalidate_non_owning_refs(env);
7492
7493 cur->active_lock.ptr = NULL;
7494 cur->active_lock.id = 0;
7495 }
7496 return 0;
7497 }
7498
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7499 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7500 struct bpf_call_arg_meta *meta)
7501 {
7502 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7503 bool is_const = tnum_is_const(reg->var_off);
7504 struct bpf_map *map = reg->map_ptr;
7505 u64 val = reg->var_off.value;
7506
7507 if (!is_const) {
7508 verbose(env,
7509 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7510 regno);
7511 return -EINVAL;
7512 }
7513 if (!map->btf) {
7514 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7515 map->name);
7516 return -EINVAL;
7517 }
7518 if (!btf_record_has_field(map->record, BPF_TIMER)) {
7519 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7520 return -EINVAL;
7521 }
7522 if (map->record->timer_off != val + reg->off) {
7523 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7524 val + reg->off, map->record->timer_off);
7525 return -EINVAL;
7526 }
7527 if (meta->map_ptr) {
7528 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7529 return -EFAULT;
7530 }
7531 meta->map_uid = reg->map_uid;
7532 meta->map_ptr = map;
7533 return 0;
7534 }
7535
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)7536 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7537 struct bpf_call_arg_meta *meta)
7538 {
7539 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7540 struct bpf_map *map_ptr = reg->map_ptr;
7541 struct btf_field *kptr_field;
7542 u32 kptr_off;
7543
7544 if (!tnum_is_const(reg->var_off)) {
7545 verbose(env,
7546 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7547 regno);
7548 return -EINVAL;
7549 }
7550 if (!map_ptr->btf) {
7551 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7552 map_ptr->name);
7553 return -EINVAL;
7554 }
7555 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7556 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7557 return -EINVAL;
7558 }
7559
7560 meta->map_ptr = map_ptr;
7561 kptr_off = reg->off + reg->var_off.value;
7562 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7563 if (!kptr_field) {
7564 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7565 return -EACCES;
7566 }
7567 if (kptr_field->type != BPF_KPTR_REF) {
7568 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7569 return -EACCES;
7570 }
7571 meta->kptr_field = kptr_field;
7572 return 0;
7573 }
7574
7575 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7576 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7577 *
7578 * In both cases we deal with the first 8 bytes, but need to mark the next 8
7579 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7580 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7581 *
7582 * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7583 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7584 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7585 * mutate the view of the dynptr and also possibly destroy it. In the latter
7586 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7587 * memory that dynptr points to.
7588 *
7589 * The verifier will keep track both levels of mutation (bpf_dynptr's in
7590 * reg->type and the memory's in reg->dynptr.type), but there is no support for
7591 * readonly dynptr view yet, hence only the first case is tracked and checked.
7592 *
7593 * This is consistent with how C applies the const modifier to a struct object,
7594 * where the pointer itself inside bpf_dynptr becomes const but not what it
7595 * points to.
7596 *
7597 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7598 * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7599 */
process_dynptr_func(struct bpf_verifier_env * env,int regno,int insn_idx,enum bpf_arg_type arg_type,int clone_ref_obj_id)7600 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7601 enum bpf_arg_type arg_type, int clone_ref_obj_id)
7602 {
7603 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7604 int err;
7605
7606 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7607 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7608 */
7609 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7610 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7611 return -EFAULT;
7612 }
7613
7614 /* MEM_UNINIT - Points to memory that is an appropriate candidate for
7615 * constructing a mutable bpf_dynptr object.
7616 *
7617 * Currently, this is only possible with PTR_TO_STACK
7618 * pointing to a region of at least 16 bytes which doesn't
7619 * contain an existing bpf_dynptr.
7620 *
7621 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7622 * mutated or destroyed. However, the memory it points to
7623 * may be mutated.
7624 *
7625 * None - Points to a initialized dynptr that can be mutated and
7626 * destroyed, including mutation of the memory it points
7627 * to.
7628 */
7629 if (arg_type & MEM_UNINIT) {
7630 int i;
7631
7632 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7633 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7634 return -EINVAL;
7635 }
7636
7637 /* we write BPF_DW bits (8 bytes) at a time */
7638 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7639 err = check_mem_access(env, insn_idx, regno,
7640 i, BPF_DW, BPF_WRITE, -1, false, false);
7641 if (err)
7642 return err;
7643 }
7644
7645 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7646 } else /* MEM_RDONLY and None case from above */ {
7647 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7648 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7649 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7650 return -EINVAL;
7651 }
7652
7653 if (!is_dynptr_reg_valid_init(env, reg)) {
7654 verbose(env,
7655 "Expected an initialized dynptr as arg #%d\n",
7656 regno);
7657 return -EINVAL;
7658 }
7659
7660 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7661 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7662 verbose(env,
7663 "Expected a dynptr of type %s as arg #%d\n",
7664 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7665 return -EINVAL;
7666 }
7667
7668 err = mark_dynptr_read(env, reg);
7669 }
7670 return err;
7671 }
7672
iter_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,int spi)7673 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7674 {
7675 struct bpf_func_state *state = func(env, reg);
7676
7677 return state->stack[spi].spilled_ptr.ref_obj_id;
7678 }
7679
is_iter_kfunc(struct bpf_kfunc_call_arg_meta * meta)7680 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7681 {
7682 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7683 }
7684
is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta * meta)7685 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7686 {
7687 return meta->kfunc_flags & KF_ITER_NEW;
7688 }
7689
is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta * meta)7690 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7691 {
7692 return meta->kfunc_flags & KF_ITER_NEXT;
7693 }
7694
is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta * meta)7695 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7696 {
7697 return meta->kfunc_flags & KF_ITER_DESTROY;
7698 }
7699
is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta * meta,int arg)7700 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7701 {
7702 /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7703 * kfunc is iter state pointer
7704 */
7705 return arg == 0 && is_iter_kfunc(meta);
7706 }
7707
process_iter_arg(struct bpf_verifier_env * env,int regno,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7708 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7709 struct bpf_kfunc_call_arg_meta *meta)
7710 {
7711 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
7712 const struct btf_type *t;
7713 const struct btf_param *arg;
7714 int spi, err, i, nr_slots;
7715 u32 btf_id;
7716
7717 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7718 arg = &btf_params(meta->func_proto)[0];
7719 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */
7720 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */
7721 nr_slots = t->size / BPF_REG_SIZE;
7722
7723 if (is_iter_new_kfunc(meta)) {
7724 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7725 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7726 verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7727 iter_type_str(meta->btf, btf_id), regno);
7728 return -EINVAL;
7729 }
7730
7731 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7732 err = check_mem_access(env, insn_idx, regno,
7733 i, BPF_DW, BPF_WRITE, -1, false, false);
7734 if (err)
7735 return err;
7736 }
7737
7738 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7739 if (err)
7740 return err;
7741 } else {
7742 /* iter_next() or iter_destroy() expect initialized iter state*/
7743 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7744 verbose(env, "expected an initialized iter_%s as arg #%d\n",
7745 iter_type_str(meta->btf, btf_id), regno);
7746 return -EINVAL;
7747 }
7748
7749 spi = iter_get_spi(env, reg, nr_slots);
7750 if (spi < 0)
7751 return spi;
7752
7753 err = mark_iter_read(env, reg, spi, nr_slots);
7754 if (err)
7755 return err;
7756
7757 /* remember meta->iter info for process_iter_next_call() */
7758 meta->iter.spi = spi;
7759 meta->iter.frameno = reg->frameno;
7760 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7761
7762 if (is_iter_destroy_kfunc(meta)) {
7763 err = unmark_stack_slots_iter(env, reg, nr_slots);
7764 if (err)
7765 return err;
7766 }
7767 }
7768
7769 return 0;
7770 }
7771
7772 /* Look for a previous loop entry at insn_idx: nearest parent state
7773 * stopped at insn_idx with callsites matching those in cur->frame.
7774 */
find_prev_entry(struct bpf_verifier_env * env,struct bpf_verifier_state * cur,int insn_idx)7775 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7776 struct bpf_verifier_state *cur,
7777 int insn_idx)
7778 {
7779 struct bpf_verifier_state_list *sl;
7780 struct bpf_verifier_state *st;
7781
7782 /* Explored states are pushed in stack order, most recent states come first */
7783 sl = *explored_state(env, insn_idx);
7784 for (; sl; sl = sl->next) {
7785 /* If st->branches != 0 state is a part of current DFS verification path,
7786 * hence cur & st for a loop.
7787 */
7788 st = &sl->state;
7789 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7790 st->dfs_depth < cur->dfs_depth)
7791 return st;
7792 }
7793
7794 return NULL;
7795 }
7796
7797 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7798 static bool regs_exact(const struct bpf_reg_state *rold,
7799 const struct bpf_reg_state *rcur,
7800 struct bpf_idmap *idmap);
7801
maybe_widen_reg(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap)7802 static void maybe_widen_reg(struct bpf_verifier_env *env,
7803 struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7804 struct bpf_idmap *idmap)
7805 {
7806 if (rold->type != SCALAR_VALUE)
7807 return;
7808 if (rold->type != rcur->type)
7809 return;
7810 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7811 return;
7812 __mark_reg_unknown(env, rcur);
7813 }
7814
widen_imprecise_scalars(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7815 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7816 struct bpf_verifier_state *old,
7817 struct bpf_verifier_state *cur)
7818 {
7819 struct bpf_func_state *fold, *fcur;
7820 int i, fr;
7821
7822 reset_idmap_scratch(env);
7823 for (fr = old->curframe; fr >= 0; fr--) {
7824 fold = old->frame[fr];
7825 fcur = cur->frame[fr];
7826
7827 for (i = 0; i < MAX_BPF_REG; i++)
7828 maybe_widen_reg(env,
7829 &fold->regs[i],
7830 &fcur->regs[i],
7831 &env->idmap_scratch);
7832
7833 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7834 if (!is_spilled_reg(&fold->stack[i]) ||
7835 !is_spilled_reg(&fcur->stack[i]))
7836 continue;
7837
7838 maybe_widen_reg(env,
7839 &fold->stack[i].spilled_ptr,
7840 &fcur->stack[i].spilled_ptr,
7841 &env->idmap_scratch);
7842 }
7843 }
7844 return 0;
7845 }
7846
7847 /* process_iter_next_call() is called when verifier gets to iterator's next
7848 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7849 * to it as just "iter_next()" in comments below.
7850 *
7851 * BPF verifier relies on a crucial contract for any iter_next()
7852 * implementation: it should *eventually* return NULL, and once that happens
7853 * it should keep returning NULL. That is, once iterator exhausts elements to
7854 * iterate, it should never reset or spuriously return new elements.
7855 *
7856 * With the assumption of such contract, process_iter_next_call() simulates
7857 * a fork in the verifier state to validate loop logic correctness and safety
7858 * without having to simulate infinite amount of iterations.
7859 *
7860 * In current state, we first assume that iter_next() returned NULL and
7861 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7862 * conditions we should not form an infinite loop and should eventually reach
7863 * exit.
7864 *
7865 * Besides that, we also fork current state and enqueue it for later
7866 * verification. In a forked state we keep iterator state as ACTIVE
7867 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7868 * also bump iteration depth to prevent erroneous infinite loop detection
7869 * later on (see iter_active_depths_differ() comment for details). In this
7870 * state we assume that we'll eventually loop back to another iter_next()
7871 * calls (it could be in exactly same location or in some other instruction,
7872 * it doesn't matter, we don't make any unnecessary assumptions about this,
7873 * everything revolves around iterator state in a stack slot, not which
7874 * instruction is calling iter_next()). When that happens, we either will come
7875 * to iter_next() with equivalent state and can conclude that next iteration
7876 * will proceed in exactly the same way as we just verified, so it's safe to
7877 * assume that loop converges. If not, we'll go on another iteration
7878 * simulation with a different input state, until all possible starting states
7879 * are validated or we reach maximum number of instructions limit.
7880 *
7881 * This way, we will either exhaustively discover all possible input states
7882 * that iterator loop can start with and eventually will converge, or we'll
7883 * effectively regress into bounded loop simulation logic and either reach
7884 * maximum number of instructions if loop is not provably convergent, or there
7885 * is some statically known limit on number of iterations (e.g., if there is
7886 * an explicit `if n > 100 then break;` statement somewhere in the loop).
7887 *
7888 * Iteration convergence logic in is_state_visited() relies on exact
7889 * states comparison, which ignores read and precision marks.
7890 * This is necessary because read and precision marks are not finalized
7891 * while in the loop. Exact comparison might preclude convergence for
7892 * simple programs like below:
7893 *
7894 * i = 0;
7895 * while(iter_next(&it))
7896 * i++;
7897 *
7898 * At each iteration step i++ would produce a new distinct state and
7899 * eventually instruction processing limit would be reached.
7900 *
7901 * To avoid such behavior speculatively forget (widen) range for
7902 * imprecise scalar registers, if those registers were not precise at the
7903 * end of the previous iteration and do not match exactly.
7904 *
7905 * This is a conservative heuristic that allows to verify wide range of programs,
7906 * however it precludes verification of programs that conjure an
7907 * imprecise value on the first loop iteration and use it as precise on a second.
7908 * For example, the following safe program would fail to verify:
7909 *
7910 * struct bpf_num_iter it;
7911 * int arr[10];
7912 * int i = 0, a = 0;
7913 * bpf_iter_num_new(&it, 0, 10);
7914 * while (bpf_iter_num_next(&it)) {
7915 * if (a == 0) {
7916 * a = 1;
7917 * i = 7; // Because i changed verifier would forget
7918 * // it's range on second loop entry.
7919 * } else {
7920 * arr[i] = 42; // This would fail to verify.
7921 * }
7922 * }
7923 * bpf_iter_num_destroy(&it);
7924 */
process_iter_next_call(struct bpf_verifier_env * env,int insn_idx,struct bpf_kfunc_call_arg_meta * meta)7925 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7926 struct bpf_kfunc_call_arg_meta *meta)
7927 {
7928 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
7929 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7930 struct bpf_reg_state *cur_iter, *queued_iter;
7931 int iter_frameno = meta->iter.frameno;
7932 int iter_spi = meta->iter.spi;
7933
7934 BTF_TYPE_EMIT(struct bpf_iter);
7935
7936 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7937
7938 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7939 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7940 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7941 cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7942 return -EFAULT;
7943 }
7944
7945 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7946 /* Because iter_next() call is a checkpoint is_state_visitied()
7947 * should guarantee parent state with same call sites and insn_idx.
7948 */
7949 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
7950 !same_callsites(cur_st->parent, cur_st)) {
7951 verbose(env, "bug: bad parent state for iter next call");
7952 return -EFAULT;
7953 }
7954 /* Note cur_st->parent in the call below, it is necessary to skip
7955 * checkpoint created for cur_st by is_state_visited()
7956 * right at this instruction.
7957 */
7958 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
7959 /* branch out active iter state */
7960 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7961 if (!queued_st)
7962 return -ENOMEM;
7963
7964 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7965 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7966 queued_iter->iter.depth++;
7967 if (prev_st)
7968 widen_imprecise_scalars(env, prev_st, queued_st);
7969
7970 queued_fr = queued_st->frame[queued_st->curframe];
7971 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7972 }
7973
7974 /* switch to DRAINED state, but keep the depth unchanged */
7975 /* mark current iter state as drained and assume returned NULL */
7976 cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7977 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7978
7979 return 0;
7980 }
7981
arg_type_is_mem_size(enum bpf_arg_type type)7982 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7983 {
7984 return type == ARG_CONST_SIZE ||
7985 type == ARG_CONST_SIZE_OR_ZERO;
7986 }
7987
arg_type_is_release(enum bpf_arg_type type)7988 static bool arg_type_is_release(enum bpf_arg_type type)
7989 {
7990 return type & OBJ_RELEASE;
7991 }
7992
arg_type_is_dynptr(enum bpf_arg_type type)7993 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7994 {
7995 return base_type(type) == ARG_PTR_TO_DYNPTR;
7996 }
7997
int_ptr_type_to_size(enum bpf_arg_type type)7998 static int int_ptr_type_to_size(enum bpf_arg_type type)
7999 {
8000 if (type == ARG_PTR_TO_INT)
8001 return sizeof(u32);
8002 else if (type == ARG_PTR_TO_LONG)
8003 return sizeof(u64);
8004
8005 return -EINVAL;
8006 }
8007
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)8008 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8009 const struct bpf_call_arg_meta *meta,
8010 enum bpf_arg_type *arg_type)
8011 {
8012 if (!meta->map_ptr) {
8013 /* kernel subsystem misconfigured verifier */
8014 verbose(env, "invalid map_ptr to access map->type\n");
8015 return -EACCES;
8016 }
8017
8018 switch (meta->map_ptr->map_type) {
8019 case BPF_MAP_TYPE_SOCKMAP:
8020 case BPF_MAP_TYPE_SOCKHASH:
8021 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8022 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8023 } else {
8024 verbose(env, "invalid arg_type for sockmap/sockhash\n");
8025 return -EINVAL;
8026 }
8027 break;
8028 case BPF_MAP_TYPE_BLOOM_FILTER:
8029 if (meta->func_id == BPF_FUNC_map_peek_elem)
8030 *arg_type = ARG_PTR_TO_MAP_VALUE;
8031 break;
8032 default:
8033 break;
8034 }
8035 return 0;
8036 }
8037
8038 struct bpf_reg_types {
8039 const enum bpf_reg_type types[10];
8040 u32 *btf_id;
8041 };
8042
8043 static const struct bpf_reg_types sock_types = {
8044 .types = {
8045 PTR_TO_SOCK_COMMON,
8046 PTR_TO_SOCKET,
8047 PTR_TO_TCP_SOCK,
8048 PTR_TO_XDP_SOCK,
8049 },
8050 };
8051
8052 #ifdef CONFIG_NET
8053 static const struct bpf_reg_types btf_id_sock_common_types = {
8054 .types = {
8055 PTR_TO_SOCK_COMMON,
8056 PTR_TO_SOCKET,
8057 PTR_TO_TCP_SOCK,
8058 PTR_TO_XDP_SOCK,
8059 PTR_TO_BTF_ID,
8060 PTR_TO_BTF_ID | PTR_TRUSTED,
8061 },
8062 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8063 };
8064 #endif
8065
8066 static const struct bpf_reg_types mem_types = {
8067 .types = {
8068 PTR_TO_STACK,
8069 PTR_TO_PACKET,
8070 PTR_TO_PACKET_META,
8071 PTR_TO_MAP_KEY,
8072 PTR_TO_MAP_VALUE,
8073 PTR_TO_MEM,
8074 PTR_TO_MEM | MEM_RINGBUF,
8075 PTR_TO_BUF,
8076 PTR_TO_BTF_ID | PTR_TRUSTED,
8077 },
8078 };
8079
8080 static const struct bpf_reg_types int_ptr_types = {
8081 .types = {
8082 PTR_TO_STACK,
8083 PTR_TO_PACKET,
8084 PTR_TO_PACKET_META,
8085 PTR_TO_MAP_KEY,
8086 PTR_TO_MAP_VALUE,
8087 },
8088 };
8089
8090 static const struct bpf_reg_types spin_lock_types = {
8091 .types = {
8092 PTR_TO_MAP_VALUE,
8093 PTR_TO_BTF_ID | MEM_ALLOC,
8094 }
8095 };
8096
8097 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8098 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8099 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8100 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8101 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8102 static const struct bpf_reg_types btf_ptr_types = {
8103 .types = {
8104 PTR_TO_BTF_ID,
8105 PTR_TO_BTF_ID | PTR_TRUSTED,
8106 PTR_TO_BTF_ID | MEM_RCU,
8107 },
8108 };
8109 static const struct bpf_reg_types percpu_btf_ptr_types = {
8110 .types = {
8111 PTR_TO_BTF_ID | MEM_PERCPU,
8112 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8113 }
8114 };
8115 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8116 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8117 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8118 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8119 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8120 static const struct bpf_reg_types dynptr_types = {
8121 .types = {
8122 PTR_TO_STACK,
8123 CONST_PTR_TO_DYNPTR,
8124 }
8125 };
8126
8127 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8128 [ARG_PTR_TO_MAP_KEY] = &mem_types,
8129 [ARG_PTR_TO_MAP_VALUE] = &mem_types,
8130 [ARG_CONST_SIZE] = &scalar_types,
8131 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
8132 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
8133 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
8134 [ARG_PTR_TO_CTX] = &context_types,
8135 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
8136 #ifdef CONFIG_NET
8137 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8138 #endif
8139 [ARG_PTR_TO_SOCKET] = &fullsock_types,
8140 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
8141 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
8142 [ARG_PTR_TO_MEM] = &mem_types,
8143 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types,
8144 [ARG_PTR_TO_INT] = &int_ptr_types,
8145 [ARG_PTR_TO_LONG] = &int_ptr_types,
8146 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
8147 [ARG_PTR_TO_FUNC] = &func_ptr_types,
8148 [ARG_PTR_TO_STACK] = &stack_ptr_types,
8149 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
8150 [ARG_PTR_TO_TIMER] = &timer_types,
8151 [ARG_PTR_TO_KPTR] = &kptr_types,
8152 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
8153 };
8154
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id,struct bpf_call_arg_meta * meta)8155 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8156 enum bpf_arg_type arg_type,
8157 const u32 *arg_btf_id,
8158 struct bpf_call_arg_meta *meta)
8159 {
8160 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8161 enum bpf_reg_type expected, type = reg->type;
8162 const struct bpf_reg_types *compatible;
8163 int i, j;
8164
8165 compatible = compatible_reg_types[base_type(arg_type)];
8166 if (!compatible) {
8167 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8168 return -EFAULT;
8169 }
8170
8171 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8172 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8173 *
8174 * Same for MAYBE_NULL:
8175 *
8176 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8177 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8178 *
8179 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8180 *
8181 * Therefore we fold these flags depending on the arg_type before comparison.
8182 */
8183 if (arg_type & MEM_RDONLY)
8184 type &= ~MEM_RDONLY;
8185 if (arg_type & PTR_MAYBE_NULL)
8186 type &= ~PTR_MAYBE_NULL;
8187 if (base_type(arg_type) == ARG_PTR_TO_MEM)
8188 type &= ~DYNPTR_TYPE_FLAG_MASK;
8189
8190 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
8191 type &= ~MEM_ALLOC;
8192
8193 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8194 expected = compatible->types[i];
8195 if (expected == NOT_INIT)
8196 break;
8197
8198 if (type == expected)
8199 goto found;
8200 }
8201
8202 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8203 for (j = 0; j + 1 < i; j++)
8204 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8205 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8206 return -EACCES;
8207
8208 found:
8209 if (base_type(reg->type) != PTR_TO_BTF_ID)
8210 return 0;
8211
8212 if (compatible == &mem_types) {
8213 if (!(arg_type & MEM_RDONLY)) {
8214 verbose(env,
8215 "%s() may write into memory pointed by R%d type=%s\n",
8216 func_id_name(meta->func_id),
8217 regno, reg_type_str(env, reg->type));
8218 return -EACCES;
8219 }
8220 return 0;
8221 }
8222
8223 switch ((int)reg->type) {
8224 case PTR_TO_BTF_ID:
8225 case PTR_TO_BTF_ID | PTR_TRUSTED:
8226 case PTR_TO_BTF_ID | MEM_RCU:
8227 case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8228 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8229 {
8230 /* For bpf_sk_release, it needs to match against first member
8231 * 'struct sock_common', hence make an exception for it. This
8232 * allows bpf_sk_release to work for multiple socket types.
8233 */
8234 bool strict_type_match = arg_type_is_release(arg_type) &&
8235 meta->func_id != BPF_FUNC_sk_release;
8236
8237 if (type_may_be_null(reg->type) &&
8238 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8239 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8240 return -EACCES;
8241 }
8242
8243 if (!arg_btf_id) {
8244 if (!compatible->btf_id) {
8245 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8246 return -EFAULT;
8247 }
8248 arg_btf_id = compatible->btf_id;
8249 }
8250
8251 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8252 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8253 return -EACCES;
8254 } else {
8255 if (arg_btf_id == BPF_PTR_POISON) {
8256 verbose(env, "verifier internal error:");
8257 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8258 regno);
8259 return -EACCES;
8260 }
8261
8262 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8263 btf_vmlinux, *arg_btf_id,
8264 strict_type_match)) {
8265 verbose(env, "R%d is of type %s but %s is expected\n",
8266 regno, btf_type_name(reg->btf, reg->btf_id),
8267 btf_type_name(btf_vmlinux, *arg_btf_id));
8268 return -EACCES;
8269 }
8270 }
8271 break;
8272 }
8273 case PTR_TO_BTF_ID | MEM_ALLOC:
8274 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8275 meta->func_id != BPF_FUNC_kptr_xchg) {
8276 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8277 return -EFAULT;
8278 }
8279 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8280 if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8281 return -EACCES;
8282 }
8283 break;
8284 case PTR_TO_BTF_ID | MEM_PERCPU:
8285 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8286 /* Handled by helper specific checks */
8287 break;
8288 default:
8289 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8290 return -EFAULT;
8291 }
8292 return 0;
8293 }
8294
8295 static struct btf_field *
reg_find_field_offset(const struct bpf_reg_state * reg,s32 off,u32 fields)8296 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8297 {
8298 struct btf_field *field;
8299 struct btf_record *rec;
8300
8301 rec = reg_btf_record(reg);
8302 if (!rec)
8303 return NULL;
8304
8305 field = btf_record_find(rec, off, fields);
8306 if (!field)
8307 return NULL;
8308
8309 return field;
8310 }
8311
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)8312 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8313 const struct bpf_reg_state *reg, int regno,
8314 enum bpf_arg_type arg_type)
8315 {
8316 u32 type = reg->type;
8317
8318 /* When referenced register is passed to release function, its fixed
8319 * offset must be 0.
8320 *
8321 * We will check arg_type_is_release reg has ref_obj_id when storing
8322 * meta->release_regno.
8323 */
8324 if (arg_type_is_release(arg_type)) {
8325 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8326 * may not directly point to the object being released, but to
8327 * dynptr pointing to such object, which might be at some offset
8328 * on the stack. In that case, we simply to fallback to the
8329 * default handling.
8330 */
8331 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8332 return 0;
8333
8334 /* Doing check_ptr_off_reg check for the offset will catch this
8335 * because fixed_off_ok is false, but checking here allows us
8336 * to give the user a better error message.
8337 */
8338 if (reg->off) {
8339 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8340 regno);
8341 return -EINVAL;
8342 }
8343 return __check_ptr_off_reg(env, reg, regno, false);
8344 }
8345
8346 switch (type) {
8347 /* Pointer types where both fixed and variable offset is explicitly allowed: */
8348 case PTR_TO_STACK:
8349 case PTR_TO_PACKET:
8350 case PTR_TO_PACKET_META:
8351 case PTR_TO_MAP_KEY:
8352 case PTR_TO_MAP_VALUE:
8353 case PTR_TO_MEM:
8354 case PTR_TO_MEM | MEM_RDONLY:
8355 case PTR_TO_MEM | MEM_RINGBUF:
8356 case PTR_TO_BUF:
8357 case PTR_TO_BUF | MEM_RDONLY:
8358 case SCALAR_VALUE:
8359 return 0;
8360 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8361 * fixed offset.
8362 */
8363 case PTR_TO_BTF_ID:
8364 case PTR_TO_BTF_ID | MEM_ALLOC:
8365 case PTR_TO_BTF_ID | PTR_TRUSTED:
8366 case PTR_TO_BTF_ID | MEM_RCU:
8367 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8368 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8369 /* When referenced PTR_TO_BTF_ID is passed to release function,
8370 * its fixed offset must be 0. In the other cases, fixed offset
8371 * can be non-zero. This was already checked above. So pass
8372 * fixed_off_ok as true to allow fixed offset for all other
8373 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8374 * still need to do checks instead of returning.
8375 */
8376 return __check_ptr_off_reg(env, reg, regno, true);
8377 default:
8378 return __check_ptr_off_reg(env, reg, regno, false);
8379 }
8380 }
8381
get_dynptr_arg_reg(struct bpf_verifier_env * env,const struct bpf_func_proto * fn,struct bpf_reg_state * regs)8382 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8383 const struct bpf_func_proto *fn,
8384 struct bpf_reg_state *regs)
8385 {
8386 struct bpf_reg_state *state = NULL;
8387 int i;
8388
8389 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8390 if (arg_type_is_dynptr(fn->arg_type[i])) {
8391 if (state) {
8392 verbose(env, "verifier internal error: multiple dynptr args\n");
8393 return NULL;
8394 }
8395 state = ®s[BPF_REG_1 + i];
8396 }
8397
8398 if (!state)
8399 verbose(env, "verifier internal error: no dynptr arg found\n");
8400
8401 return state;
8402 }
8403
dynptr_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8404 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8405 {
8406 struct bpf_func_state *state = func(env, reg);
8407 int spi;
8408
8409 if (reg->type == CONST_PTR_TO_DYNPTR)
8410 return reg->id;
8411 spi = dynptr_get_spi(env, reg);
8412 if (spi < 0)
8413 return spi;
8414 return state->stack[spi].spilled_ptr.id;
8415 }
8416
dynptr_ref_obj_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8417 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8418 {
8419 struct bpf_func_state *state = func(env, reg);
8420 int spi;
8421
8422 if (reg->type == CONST_PTR_TO_DYNPTR)
8423 return reg->ref_obj_id;
8424 spi = dynptr_get_spi(env, reg);
8425 if (spi < 0)
8426 return spi;
8427 return state->stack[spi].spilled_ptr.ref_obj_id;
8428 }
8429
dynptr_get_type(struct bpf_verifier_env * env,struct bpf_reg_state * reg)8430 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8431 struct bpf_reg_state *reg)
8432 {
8433 struct bpf_func_state *state = func(env, reg);
8434 int spi;
8435
8436 if (reg->type == CONST_PTR_TO_DYNPTR)
8437 return reg->dynptr.type;
8438
8439 spi = __get_spi(reg->off);
8440 if (spi < 0) {
8441 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8442 return BPF_DYNPTR_TYPE_INVALID;
8443 }
8444
8445 return state->stack[spi].spilled_ptr.dynptr.type;
8446 }
8447
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn,int insn_idx)8448 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8449 struct bpf_call_arg_meta *meta,
8450 const struct bpf_func_proto *fn,
8451 int insn_idx)
8452 {
8453 u32 regno = BPF_REG_1 + arg;
8454 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
8455 enum bpf_arg_type arg_type = fn->arg_type[arg];
8456 enum bpf_reg_type type = reg->type;
8457 u32 *arg_btf_id = NULL;
8458 int err = 0;
8459
8460 if (arg_type == ARG_DONTCARE)
8461 return 0;
8462
8463 err = check_reg_arg(env, regno, SRC_OP);
8464 if (err)
8465 return err;
8466
8467 if (arg_type == ARG_ANYTHING) {
8468 if (is_pointer_value(env, regno)) {
8469 verbose(env, "R%d leaks addr into helper function\n",
8470 regno);
8471 return -EACCES;
8472 }
8473 return 0;
8474 }
8475
8476 if (type_is_pkt_pointer(type) &&
8477 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8478 verbose(env, "helper access to the packet is not allowed\n");
8479 return -EACCES;
8480 }
8481
8482 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8483 err = resolve_map_arg_type(env, meta, &arg_type);
8484 if (err)
8485 return err;
8486 }
8487
8488 if (register_is_null(reg) && type_may_be_null(arg_type))
8489 /* A NULL register has a SCALAR_VALUE type, so skip
8490 * type checking.
8491 */
8492 goto skip_type_check;
8493
8494 /* arg_btf_id and arg_size are in a union. */
8495 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8496 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8497 arg_btf_id = fn->arg_btf_id[arg];
8498
8499 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8500 if (err)
8501 return err;
8502
8503 err = check_func_arg_reg_off(env, reg, regno, arg_type);
8504 if (err)
8505 return err;
8506
8507 skip_type_check:
8508 if (arg_type_is_release(arg_type)) {
8509 if (arg_type_is_dynptr(arg_type)) {
8510 struct bpf_func_state *state = func(env, reg);
8511 int spi;
8512
8513 /* Only dynptr created on stack can be released, thus
8514 * the get_spi and stack state checks for spilled_ptr
8515 * should only be done before process_dynptr_func for
8516 * PTR_TO_STACK.
8517 */
8518 if (reg->type == PTR_TO_STACK) {
8519 spi = dynptr_get_spi(env, reg);
8520 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8521 verbose(env, "arg %d is an unacquired reference\n", regno);
8522 return -EINVAL;
8523 }
8524 } else {
8525 verbose(env, "cannot release unowned const bpf_dynptr\n");
8526 return -EINVAL;
8527 }
8528 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8529 verbose(env, "R%d must be referenced when passed to release function\n",
8530 regno);
8531 return -EINVAL;
8532 }
8533 if (meta->release_regno) {
8534 verbose(env, "verifier internal error: more than one release argument\n");
8535 return -EFAULT;
8536 }
8537 meta->release_regno = regno;
8538 }
8539
8540 if (reg->ref_obj_id) {
8541 if (meta->ref_obj_id) {
8542 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8543 regno, reg->ref_obj_id,
8544 meta->ref_obj_id);
8545 return -EFAULT;
8546 }
8547 meta->ref_obj_id = reg->ref_obj_id;
8548 }
8549
8550 switch (base_type(arg_type)) {
8551 case ARG_CONST_MAP_PTR:
8552 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8553 if (meta->map_ptr) {
8554 /* Use map_uid (which is unique id of inner map) to reject:
8555 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8556 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8557 * if (inner_map1 && inner_map2) {
8558 * timer = bpf_map_lookup_elem(inner_map1);
8559 * if (timer)
8560 * // mismatch would have been allowed
8561 * bpf_timer_init(timer, inner_map2);
8562 * }
8563 *
8564 * Comparing map_ptr is enough to distinguish normal and outer maps.
8565 */
8566 if (meta->map_ptr != reg->map_ptr ||
8567 meta->map_uid != reg->map_uid) {
8568 verbose(env,
8569 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8570 meta->map_uid, reg->map_uid);
8571 return -EINVAL;
8572 }
8573 }
8574 meta->map_ptr = reg->map_ptr;
8575 meta->map_uid = reg->map_uid;
8576 break;
8577 case ARG_PTR_TO_MAP_KEY:
8578 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8579 * check that [key, key + map->key_size) are within
8580 * stack limits and initialized
8581 */
8582 if (!meta->map_ptr) {
8583 /* in function declaration map_ptr must come before
8584 * map_key, so that it's verified and known before
8585 * we have to check map_key here. Otherwise it means
8586 * that kernel subsystem misconfigured verifier
8587 */
8588 verbose(env, "invalid map_ptr to access map->key\n");
8589 return -EACCES;
8590 }
8591 err = check_helper_mem_access(env, regno,
8592 meta->map_ptr->key_size, false,
8593 NULL);
8594 break;
8595 case ARG_PTR_TO_MAP_VALUE:
8596 if (type_may_be_null(arg_type) && register_is_null(reg))
8597 return 0;
8598
8599 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8600 * check [value, value + map->value_size) validity
8601 */
8602 if (!meta->map_ptr) {
8603 /* kernel subsystem misconfigured verifier */
8604 verbose(env, "invalid map_ptr to access map->value\n");
8605 return -EACCES;
8606 }
8607 meta->raw_mode = arg_type & MEM_UNINIT;
8608 err = check_helper_mem_access(env, regno,
8609 meta->map_ptr->value_size, false,
8610 meta);
8611 break;
8612 case ARG_PTR_TO_PERCPU_BTF_ID:
8613 if (!reg->btf_id) {
8614 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8615 return -EACCES;
8616 }
8617 meta->ret_btf = reg->btf;
8618 meta->ret_btf_id = reg->btf_id;
8619 break;
8620 case ARG_PTR_TO_SPIN_LOCK:
8621 if (in_rbtree_lock_required_cb(env)) {
8622 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8623 return -EACCES;
8624 }
8625 if (meta->func_id == BPF_FUNC_spin_lock) {
8626 err = process_spin_lock(env, regno, true);
8627 if (err)
8628 return err;
8629 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8630 err = process_spin_lock(env, regno, false);
8631 if (err)
8632 return err;
8633 } else {
8634 verbose(env, "verifier internal error\n");
8635 return -EFAULT;
8636 }
8637 break;
8638 case ARG_PTR_TO_TIMER:
8639 err = process_timer_func(env, regno, meta);
8640 if (err)
8641 return err;
8642 break;
8643 case ARG_PTR_TO_FUNC:
8644 meta->subprogno = reg->subprogno;
8645 break;
8646 case ARG_PTR_TO_MEM:
8647 /* The access to this pointer is only checked when we hit the
8648 * next is_mem_size argument below.
8649 */
8650 meta->raw_mode = arg_type & MEM_UNINIT;
8651 if (arg_type & MEM_FIXED_SIZE) {
8652 err = check_helper_mem_access(env, regno,
8653 fn->arg_size[arg], false,
8654 meta);
8655 }
8656 break;
8657 case ARG_CONST_SIZE:
8658 err = check_mem_size_reg(env, reg, regno, false, meta);
8659 break;
8660 case ARG_CONST_SIZE_OR_ZERO:
8661 err = check_mem_size_reg(env, reg, regno, true, meta);
8662 break;
8663 case ARG_PTR_TO_DYNPTR:
8664 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8665 if (err)
8666 return err;
8667 break;
8668 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8669 if (!tnum_is_const(reg->var_off)) {
8670 verbose(env, "R%d is not a known constant'\n",
8671 regno);
8672 return -EACCES;
8673 }
8674 meta->mem_size = reg->var_off.value;
8675 err = mark_chain_precision(env, regno);
8676 if (err)
8677 return err;
8678 break;
8679 case ARG_PTR_TO_INT:
8680 case ARG_PTR_TO_LONG:
8681 {
8682 int size = int_ptr_type_to_size(arg_type);
8683
8684 err = check_helper_mem_access(env, regno, size, false, meta);
8685 if (err)
8686 return err;
8687 err = check_ptr_alignment(env, reg, 0, size, true);
8688 break;
8689 }
8690 case ARG_PTR_TO_CONST_STR:
8691 {
8692 struct bpf_map *map = reg->map_ptr;
8693 int map_off;
8694 u64 map_addr;
8695 char *str_ptr;
8696
8697 if (!bpf_map_is_rdonly(map)) {
8698 verbose(env, "R%d does not point to a readonly map'\n", regno);
8699 return -EACCES;
8700 }
8701
8702 if (!tnum_is_const(reg->var_off)) {
8703 verbose(env, "R%d is not a constant address'\n", regno);
8704 return -EACCES;
8705 }
8706
8707 if (!map->ops->map_direct_value_addr) {
8708 verbose(env, "no direct value access support for this map type\n");
8709 return -EACCES;
8710 }
8711
8712 err = check_map_access(env, regno, reg->off,
8713 map->value_size - reg->off, false,
8714 ACCESS_HELPER);
8715 if (err)
8716 return err;
8717
8718 map_off = reg->off + reg->var_off.value;
8719 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8720 if (err) {
8721 verbose(env, "direct value access on string failed\n");
8722 return err;
8723 }
8724
8725 str_ptr = (char *)(long)(map_addr);
8726 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8727 verbose(env, "string is not zero-terminated\n");
8728 return -EINVAL;
8729 }
8730 break;
8731 }
8732 case ARG_PTR_TO_KPTR:
8733 err = process_kptr_func(env, regno, meta);
8734 if (err)
8735 return err;
8736 break;
8737 }
8738
8739 return err;
8740 }
8741
may_update_sockmap(struct bpf_verifier_env * env,int func_id)8742 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8743 {
8744 enum bpf_attach_type eatype = env->prog->expected_attach_type;
8745 enum bpf_prog_type type = resolve_prog_type(env->prog);
8746
8747 if (func_id != BPF_FUNC_map_update_elem &&
8748 func_id != BPF_FUNC_map_delete_elem)
8749 return false;
8750
8751 /* It's not possible to get access to a locked struct sock in these
8752 * contexts, so updating is safe.
8753 */
8754 switch (type) {
8755 case BPF_PROG_TYPE_TRACING:
8756 if (eatype == BPF_TRACE_ITER)
8757 return true;
8758 break;
8759 case BPF_PROG_TYPE_SOCK_OPS:
8760 /* map_update allowed only via dedicated helpers with event type checks */
8761 if (func_id == BPF_FUNC_map_delete_elem)
8762 return true;
8763 break;
8764 case BPF_PROG_TYPE_SOCKET_FILTER:
8765 case BPF_PROG_TYPE_SCHED_CLS:
8766 case BPF_PROG_TYPE_SCHED_ACT:
8767 case BPF_PROG_TYPE_XDP:
8768 case BPF_PROG_TYPE_SK_REUSEPORT:
8769 case BPF_PROG_TYPE_FLOW_DISSECTOR:
8770 case BPF_PROG_TYPE_SK_LOOKUP:
8771 return true;
8772 default:
8773 break;
8774 }
8775
8776 verbose(env, "cannot update sockmap in this context\n");
8777 return false;
8778 }
8779
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)8780 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8781 {
8782 return env->prog->jit_requested &&
8783 bpf_jit_supports_subprog_tailcalls();
8784 }
8785
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)8786 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8787 struct bpf_map *map, int func_id)
8788 {
8789 if (!map)
8790 return 0;
8791
8792 /* We need a two way check, first is from map perspective ... */
8793 switch (map->map_type) {
8794 case BPF_MAP_TYPE_PROG_ARRAY:
8795 if (func_id != BPF_FUNC_tail_call)
8796 goto error;
8797 break;
8798 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8799 if (func_id != BPF_FUNC_perf_event_read &&
8800 func_id != BPF_FUNC_perf_event_output &&
8801 func_id != BPF_FUNC_skb_output &&
8802 func_id != BPF_FUNC_perf_event_read_value &&
8803 func_id != BPF_FUNC_xdp_output)
8804 goto error;
8805 break;
8806 case BPF_MAP_TYPE_RINGBUF:
8807 if (func_id != BPF_FUNC_ringbuf_output &&
8808 func_id != BPF_FUNC_ringbuf_reserve &&
8809 func_id != BPF_FUNC_ringbuf_query &&
8810 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8811 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8812 func_id != BPF_FUNC_ringbuf_discard_dynptr)
8813 goto error;
8814 break;
8815 case BPF_MAP_TYPE_USER_RINGBUF:
8816 if (func_id != BPF_FUNC_user_ringbuf_drain)
8817 goto error;
8818 break;
8819 case BPF_MAP_TYPE_STACK_TRACE:
8820 if (func_id != BPF_FUNC_get_stackid)
8821 goto error;
8822 break;
8823 case BPF_MAP_TYPE_CGROUP_ARRAY:
8824 if (func_id != BPF_FUNC_skb_under_cgroup &&
8825 func_id != BPF_FUNC_current_task_under_cgroup)
8826 goto error;
8827 break;
8828 case BPF_MAP_TYPE_CGROUP_STORAGE:
8829 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8830 if (func_id != BPF_FUNC_get_local_storage)
8831 goto error;
8832 break;
8833 case BPF_MAP_TYPE_DEVMAP:
8834 case BPF_MAP_TYPE_DEVMAP_HASH:
8835 if (func_id != BPF_FUNC_redirect_map &&
8836 func_id != BPF_FUNC_map_lookup_elem)
8837 goto error;
8838 break;
8839 /* Restrict bpf side of cpumap and xskmap, open when use-cases
8840 * appear.
8841 */
8842 case BPF_MAP_TYPE_CPUMAP:
8843 if (func_id != BPF_FUNC_redirect_map)
8844 goto error;
8845 break;
8846 case BPF_MAP_TYPE_XSKMAP:
8847 if (func_id != BPF_FUNC_redirect_map &&
8848 func_id != BPF_FUNC_map_lookup_elem)
8849 goto error;
8850 break;
8851 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8852 case BPF_MAP_TYPE_HASH_OF_MAPS:
8853 if (func_id != BPF_FUNC_map_lookup_elem)
8854 goto error;
8855 break;
8856 case BPF_MAP_TYPE_SOCKMAP:
8857 if (func_id != BPF_FUNC_sk_redirect_map &&
8858 func_id != BPF_FUNC_sock_map_update &&
8859 func_id != BPF_FUNC_msg_redirect_map &&
8860 func_id != BPF_FUNC_sk_select_reuseport &&
8861 func_id != BPF_FUNC_map_lookup_elem &&
8862 !may_update_sockmap(env, func_id))
8863 goto error;
8864 break;
8865 case BPF_MAP_TYPE_SOCKHASH:
8866 if (func_id != BPF_FUNC_sk_redirect_hash &&
8867 func_id != BPF_FUNC_sock_hash_update &&
8868 func_id != BPF_FUNC_msg_redirect_hash &&
8869 func_id != BPF_FUNC_sk_select_reuseport &&
8870 func_id != BPF_FUNC_map_lookup_elem &&
8871 !may_update_sockmap(env, func_id))
8872 goto error;
8873 break;
8874 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8875 if (func_id != BPF_FUNC_sk_select_reuseport)
8876 goto error;
8877 break;
8878 case BPF_MAP_TYPE_QUEUE:
8879 case BPF_MAP_TYPE_STACK:
8880 if (func_id != BPF_FUNC_map_peek_elem &&
8881 func_id != BPF_FUNC_map_pop_elem &&
8882 func_id != BPF_FUNC_map_push_elem)
8883 goto error;
8884 break;
8885 case BPF_MAP_TYPE_SK_STORAGE:
8886 if (func_id != BPF_FUNC_sk_storage_get &&
8887 func_id != BPF_FUNC_sk_storage_delete &&
8888 func_id != BPF_FUNC_kptr_xchg)
8889 goto error;
8890 break;
8891 case BPF_MAP_TYPE_INODE_STORAGE:
8892 if (func_id != BPF_FUNC_inode_storage_get &&
8893 func_id != BPF_FUNC_inode_storage_delete &&
8894 func_id != BPF_FUNC_kptr_xchg)
8895 goto error;
8896 break;
8897 case BPF_MAP_TYPE_TASK_STORAGE:
8898 if (func_id != BPF_FUNC_task_storage_get &&
8899 func_id != BPF_FUNC_task_storage_delete &&
8900 func_id != BPF_FUNC_kptr_xchg)
8901 goto error;
8902 break;
8903 case BPF_MAP_TYPE_CGRP_STORAGE:
8904 if (func_id != BPF_FUNC_cgrp_storage_get &&
8905 func_id != BPF_FUNC_cgrp_storage_delete &&
8906 func_id != BPF_FUNC_kptr_xchg)
8907 goto error;
8908 break;
8909 case BPF_MAP_TYPE_BLOOM_FILTER:
8910 if (func_id != BPF_FUNC_map_peek_elem &&
8911 func_id != BPF_FUNC_map_push_elem)
8912 goto error;
8913 break;
8914 default:
8915 break;
8916 }
8917
8918 /* ... and second from the function itself. */
8919 switch (func_id) {
8920 case BPF_FUNC_tail_call:
8921 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8922 goto error;
8923 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8924 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8925 return -EINVAL;
8926 }
8927 break;
8928 case BPF_FUNC_perf_event_read:
8929 case BPF_FUNC_perf_event_output:
8930 case BPF_FUNC_perf_event_read_value:
8931 case BPF_FUNC_skb_output:
8932 case BPF_FUNC_xdp_output:
8933 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8934 goto error;
8935 break;
8936 case BPF_FUNC_ringbuf_output:
8937 case BPF_FUNC_ringbuf_reserve:
8938 case BPF_FUNC_ringbuf_query:
8939 case BPF_FUNC_ringbuf_reserve_dynptr:
8940 case BPF_FUNC_ringbuf_submit_dynptr:
8941 case BPF_FUNC_ringbuf_discard_dynptr:
8942 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8943 goto error;
8944 break;
8945 case BPF_FUNC_user_ringbuf_drain:
8946 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8947 goto error;
8948 break;
8949 case BPF_FUNC_get_stackid:
8950 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8951 goto error;
8952 break;
8953 case BPF_FUNC_current_task_under_cgroup:
8954 case BPF_FUNC_skb_under_cgroup:
8955 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8956 goto error;
8957 break;
8958 case BPF_FUNC_redirect_map:
8959 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8960 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8961 map->map_type != BPF_MAP_TYPE_CPUMAP &&
8962 map->map_type != BPF_MAP_TYPE_XSKMAP)
8963 goto error;
8964 break;
8965 case BPF_FUNC_sk_redirect_map:
8966 case BPF_FUNC_msg_redirect_map:
8967 case BPF_FUNC_sock_map_update:
8968 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8969 goto error;
8970 break;
8971 case BPF_FUNC_sk_redirect_hash:
8972 case BPF_FUNC_msg_redirect_hash:
8973 case BPF_FUNC_sock_hash_update:
8974 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8975 goto error;
8976 break;
8977 case BPF_FUNC_get_local_storage:
8978 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8979 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8980 goto error;
8981 break;
8982 case BPF_FUNC_sk_select_reuseport:
8983 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8984 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8985 map->map_type != BPF_MAP_TYPE_SOCKHASH)
8986 goto error;
8987 break;
8988 case BPF_FUNC_map_pop_elem:
8989 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8990 map->map_type != BPF_MAP_TYPE_STACK)
8991 goto error;
8992 break;
8993 case BPF_FUNC_map_peek_elem:
8994 case BPF_FUNC_map_push_elem:
8995 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8996 map->map_type != BPF_MAP_TYPE_STACK &&
8997 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8998 goto error;
8999 break;
9000 case BPF_FUNC_map_lookup_percpu_elem:
9001 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9002 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9003 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9004 goto error;
9005 break;
9006 case BPF_FUNC_sk_storage_get:
9007 case BPF_FUNC_sk_storage_delete:
9008 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9009 goto error;
9010 break;
9011 case BPF_FUNC_inode_storage_get:
9012 case BPF_FUNC_inode_storage_delete:
9013 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9014 goto error;
9015 break;
9016 case BPF_FUNC_task_storage_get:
9017 case BPF_FUNC_task_storage_delete:
9018 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9019 goto error;
9020 break;
9021 case BPF_FUNC_cgrp_storage_get:
9022 case BPF_FUNC_cgrp_storage_delete:
9023 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9024 goto error;
9025 break;
9026 default:
9027 break;
9028 }
9029
9030 return 0;
9031 error:
9032 verbose(env, "cannot pass map_type %d into func %s#%d\n",
9033 map->map_type, func_id_name(func_id), func_id);
9034 return -EINVAL;
9035 }
9036
check_raw_mode_ok(const struct bpf_func_proto * fn)9037 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9038 {
9039 int count = 0;
9040
9041 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9042 count++;
9043 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9044 count++;
9045 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9046 count++;
9047 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9048 count++;
9049 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9050 count++;
9051
9052 /* We only support one arg being in raw mode at the moment,
9053 * which is sufficient for the helper functions we have
9054 * right now.
9055 */
9056 return count <= 1;
9057 }
9058
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)9059 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9060 {
9061 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9062 bool has_size = fn->arg_size[arg] != 0;
9063 bool is_next_size = false;
9064
9065 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9066 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9067
9068 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9069 return is_next_size;
9070
9071 return has_size == is_next_size || is_next_size == is_fixed;
9072 }
9073
check_arg_pair_ok(const struct bpf_func_proto * fn)9074 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9075 {
9076 /* bpf_xxx(..., buf, len) call will access 'len'
9077 * bytes from memory 'buf'. Both arg types need
9078 * to be paired, so make sure there's no buggy
9079 * helper function specification.
9080 */
9081 if (arg_type_is_mem_size(fn->arg1_type) ||
9082 check_args_pair_invalid(fn, 0) ||
9083 check_args_pair_invalid(fn, 1) ||
9084 check_args_pair_invalid(fn, 2) ||
9085 check_args_pair_invalid(fn, 3) ||
9086 check_args_pair_invalid(fn, 4))
9087 return false;
9088
9089 return true;
9090 }
9091
check_btf_id_ok(const struct bpf_func_proto * fn)9092 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9093 {
9094 int i;
9095
9096 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9097 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9098 return !!fn->arg_btf_id[i];
9099 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9100 return fn->arg_btf_id[i] == BPF_PTR_POISON;
9101 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9102 /* arg_btf_id and arg_size are in a union. */
9103 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9104 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9105 return false;
9106 }
9107
9108 return true;
9109 }
9110
check_func_proto(const struct bpf_func_proto * fn,int func_id)9111 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9112 {
9113 return check_raw_mode_ok(fn) &&
9114 check_arg_pair_ok(fn) &&
9115 check_btf_id_ok(fn) ? 0 : -EINVAL;
9116 }
9117
9118 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9119 * are now invalid, so turn them into unknown SCALAR_VALUE.
9120 *
9121 * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9122 * since these slices point to packet data.
9123 */
clear_all_pkt_pointers(struct bpf_verifier_env * env)9124 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9125 {
9126 struct bpf_func_state *state;
9127 struct bpf_reg_state *reg;
9128
9129 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9130 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9131 mark_reg_invalid(env, reg);
9132 }));
9133 }
9134
9135 enum {
9136 AT_PKT_END = -1,
9137 BEYOND_PKT_END = -2,
9138 };
9139
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)9140 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9141 {
9142 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9143 struct bpf_reg_state *reg = &state->regs[regn];
9144
9145 if (reg->type != PTR_TO_PACKET)
9146 /* PTR_TO_PACKET_META is not supported yet */
9147 return;
9148
9149 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9150 * How far beyond pkt_end it goes is unknown.
9151 * if (!range_open) it's the case of pkt >= pkt_end
9152 * if (range_open) it's the case of pkt > pkt_end
9153 * hence this pointer is at least 1 byte bigger than pkt_end
9154 */
9155 if (range_open)
9156 reg->range = BEYOND_PKT_END;
9157 else
9158 reg->range = AT_PKT_END;
9159 }
9160
9161 /* The pointer with the specified id has released its reference to kernel
9162 * resources. Identify all copies of the same pointer and clear the reference.
9163 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)9164 static int release_reference(struct bpf_verifier_env *env,
9165 int ref_obj_id)
9166 {
9167 struct bpf_func_state *state;
9168 struct bpf_reg_state *reg;
9169 int err;
9170
9171 err = release_reference_state(cur_func(env), ref_obj_id);
9172 if (err)
9173 return err;
9174
9175 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9176 if (reg->ref_obj_id == ref_obj_id)
9177 mark_reg_invalid(env, reg);
9178 }));
9179
9180 return 0;
9181 }
9182
invalidate_non_owning_refs(struct bpf_verifier_env * env)9183 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9184 {
9185 struct bpf_func_state *unused;
9186 struct bpf_reg_state *reg;
9187
9188 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9189 if (type_is_non_owning_ref(reg->type))
9190 mark_reg_invalid(env, reg);
9191 }));
9192 }
9193
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9194 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9195 struct bpf_reg_state *regs)
9196 {
9197 int i;
9198
9199 /* after the call registers r0 - r5 were scratched */
9200 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9201 mark_reg_not_init(env, regs, caller_saved[i]);
9202 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK);
9203 }
9204 }
9205
9206 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9207 struct bpf_func_state *caller,
9208 struct bpf_func_state *callee,
9209 int insn_idx);
9210
9211 static int set_callee_state(struct bpf_verifier_env *env,
9212 struct bpf_func_state *caller,
9213 struct bpf_func_state *callee, int insn_idx);
9214
setup_func_entry(struct bpf_verifier_env * env,int subprog,int callsite,set_callee_state_fn set_callee_state_cb,struct bpf_verifier_state * state)9215 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite,
9216 set_callee_state_fn set_callee_state_cb,
9217 struct bpf_verifier_state *state)
9218 {
9219 struct bpf_func_state *caller, *callee;
9220 int err;
9221
9222 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9223 verbose(env, "the call stack of %d frames is too deep\n",
9224 state->curframe + 2);
9225 return -E2BIG;
9226 }
9227
9228 if (state->frame[state->curframe + 1]) {
9229 verbose(env, "verifier bug. Frame %d already allocated\n",
9230 state->curframe + 1);
9231 return -EFAULT;
9232 }
9233
9234 caller = state->frame[state->curframe];
9235 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9236 if (!callee)
9237 return -ENOMEM;
9238 state->frame[state->curframe + 1] = callee;
9239
9240 /* callee cannot access r0, r6 - r9 for reading and has to write
9241 * into its own stack before reading from it.
9242 * callee can read/write into caller's stack
9243 */
9244 init_func_state(env, callee,
9245 /* remember the callsite, it will be used by bpf_exit */
9246 callsite,
9247 state->curframe + 1 /* frameno within this callchain */,
9248 subprog /* subprog number within this prog */);
9249 /* Transfer references to the callee */
9250 err = copy_reference_state(callee, caller);
9251 err = err ?: set_callee_state_cb(env, caller, callee, callsite);
9252 if (err)
9253 goto err_out;
9254
9255 /* only increment it after check_reg_arg() finished */
9256 state->curframe++;
9257
9258 return 0;
9259
9260 err_out:
9261 free_func_state(callee);
9262 state->frame[state->curframe + 1] = NULL;
9263 return err;
9264 }
9265
push_callback_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)9266 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9267 int insn_idx, int subprog,
9268 set_callee_state_fn set_callee_state_cb)
9269 {
9270 struct bpf_verifier_state *state = env->cur_state, *callback_state;
9271 struct bpf_func_state *caller, *callee;
9272 int err;
9273
9274 caller = state->frame[state->curframe];
9275 err = btf_check_subprog_call(env, subprog, caller->regs);
9276 if (err == -EFAULT)
9277 return err;
9278
9279 /* set_callee_state is used for direct subprog calls, but we are
9280 * interested in validating only BPF helpers that can call subprogs as
9281 * callbacks
9282 */
9283 if (bpf_pseudo_kfunc_call(insn) &&
9284 !is_sync_callback_calling_kfunc(insn->imm)) {
9285 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9286 func_id_name(insn->imm), insn->imm);
9287 return -EFAULT;
9288 } else if (!bpf_pseudo_kfunc_call(insn) &&
9289 !is_callback_calling_function(insn->imm)) { /* helper */
9290 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9291 func_id_name(insn->imm), insn->imm);
9292 return -EFAULT;
9293 }
9294
9295 if (insn->code == (BPF_JMP | BPF_CALL) &&
9296 insn->src_reg == 0 &&
9297 insn->imm == BPF_FUNC_timer_set_callback) {
9298 struct bpf_verifier_state *async_cb;
9299
9300 /* there is no real recursion here. timer callbacks are async */
9301 env->subprog_info[subprog].is_async_cb = true;
9302 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9303 insn_idx, subprog);
9304 if (!async_cb)
9305 return -EFAULT;
9306 callee = async_cb->frame[0];
9307 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9308
9309 /* Convert bpf_timer_set_callback() args into timer callback args */
9310 err = set_callee_state_cb(env, caller, callee, insn_idx);
9311 if (err)
9312 return err;
9313
9314 return 0;
9315 }
9316
9317 /* for callback functions enqueue entry to callback and
9318 * proceed with next instruction within current frame.
9319 */
9320 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false);
9321 if (!callback_state)
9322 return -ENOMEM;
9323
9324 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb,
9325 callback_state);
9326 if (err)
9327 return err;
9328
9329 callback_state->callback_unroll_depth++;
9330 callback_state->frame[callback_state->curframe - 1]->callback_depth++;
9331 caller->callback_depth = 0;
9332 return 0;
9333 }
9334
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)9335 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9336 int *insn_idx)
9337 {
9338 struct bpf_verifier_state *state = env->cur_state;
9339 struct bpf_func_state *caller;
9340 int err, subprog, target_insn;
9341
9342 target_insn = *insn_idx + insn->imm + 1;
9343 subprog = find_subprog(env, target_insn);
9344 if (subprog < 0) {
9345 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn);
9346 return -EFAULT;
9347 }
9348
9349 caller = state->frame[state->curframe];
9350 err = btf_check_subprog_call(env, subprog, caller->regs);
9351 if (err == -EFAULT)
9352 return err;
9353 if (subprog_is_global(env, subprog)) {
9354 if (err) {
9355 verbose(env, "Caller passes invalid args into func#%d\n", subprog);
9356 return err;
9357 }
9358
9359 if (env->log.level & BPF_LOG_LEVEL)
9360 verbose(env, "Func#%d is global and valid. Skipping.\n", subprog);
9361 clear_caller_saved_regs(env, caller->regs);
9362
9363 /* All global functions return a 64-bit SCALAR_VALUE */
9364 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9365 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9366
9367 /* continue with next insn after call */
9368 return 0;
9369 }
9370
9371 /* for regular function entry setup new frame and continue
9372 * from that frame.
9373 */
9374 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
9375 if (err)
9376 return err;
9377
9378 clear_caller_saved_regs(env, caller->regs);
9379
9380 /* and go analyze first insn of the callee */
9381 *insn_idx = env->subprog_info[subprog].start - 1;
9382
9383 if (env->log.level & BPF_LOG_LEVEL) {
9384 verbose(env, "caller:\n");
9385 print_verifier_state(env, caller, true);
9386 verbose(env, "callee:\n");
9387 print_verifier_state(env, state->frame[state->curframe], true);
9388 }
9389
9390 return 0;
9391 }
9392
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)9393 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9394 struct bpf_func_state *caller,
9395 struct bpf_func_state *callee)
9396 {
9397 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9398 * void *callback_ctx, u64 flags);
9399 * callback_fn(struct bpf_map *map, void *key, void *value,
9400 * void *callback_ctx);
9401 */
9402 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9403
9404 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9405 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9406 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9407
9408 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9409 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9410 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9411
9412 /* pointer to stack or null */
9413 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9414
9415 /* unused */
9416 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9417 return 0;
9418 }
9419
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9420 static int set_callee_state(struct bpf_verifier_env *env,
9421 struct bpf_func_state *caller,
9422 struct bpf_func_state *callee, int insn_idx)
9423 {
9424 int i;
9425
9426 /* copy r1 - r5 args that callee can access. The copy includes parent
9427 * pointers, which connects us up to the liveness chain
9428 */
9429 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9430 callee->regs[i] = caller->regs[i];
9431 return 0;
9432 }
9433
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9434 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9435 struct bpf_func_state *caller,
9436 struct bpf_func_state *callee,
9437 int insn_idx)
9438 {
9439 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9440 struct bpf_map *map;
9441 int err;
9442
9443 if (bpf_map_ptr_poisoned(insn_aux)) {
9444 verbose(env, "tail_call abusing map_ptr\n");
9445 return -EINVAL;
9446 }
9447
9448 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9449 if (!map->ops->map_set_for_each_callback_args ||
9450 !map->ops->map_for_each_callback) {
9451 verbose(env, "callback function not allowed for map\n");
9452 return -ENOTSUPP;
9453 }
9454
9455 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9456 if (err)
9457 return err;
9458
9459 callee->in_callback_fn = true;
9460 callee->callback_ret_range = tnum_range(0, 1);
9461 return 0;
9462 }
9463
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9464 static int set_loop_callback_state(struct bpf_verifier_env *env,
9465 struct bpf_func_state *caller,
9466 struct bpf_func_state *callee,
9467 int insn_idx)
9468 {
9469 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9470 * u64 flags);
9471 * callback_fn(u32 index, void *callback_ctx);
9472 */
9473 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9474 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9475
9476 /* unused */
9477 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9478 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9479 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9480
9481 callee->in_callback_fn = true;
9482 callee->callback_ret_range = tnum_range(0, 1);
9483 return 0;
9484 }
9485
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9486 static int set_timer_callback_state(struct bpf_verifier_env *env,
9487 struct bpf_func_state *caller,
9488 struct bpf_func_state *callee,
9489 int insn_idx)
9490 {
9491 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9492
9493 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9494 * callback_fn(struct bpf_map *map, void *key, void *value);
9495 */
9496 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9497 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9498 callee->regs[BPF_REG_1].map_ptr = map_ptr;
9499
9500 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9501 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9502 callee->regs[BPF_REG_2].map_ptr = map_ptr;
9503
9504 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9505 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9506 callee->regs[BPF_REG_3].map_ptr = map_ptr;
9507
9508 /* unused */
9509 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9510 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9511 callee->in_async_callback_fn = true;
9512 callee->callback_ret_range = tnum_range(0, 1);
9513 return 0;
9514 }
9515
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9516 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9517 struct bpf_func_state *caller,
9518 struct bpf_func_state *callee,
9519 int insn_idx)
9520 {
9521 /* bpf_find_vma(struct task_struct *task, u64 addr,
9522 * void *callback_fn, void *callback_ctx, u64 flags)
9523 * (callback_fn)(struct task_struct *task,
9524 * struct vm_area_struct *vma, void *callback_ctx);
9525 */
9526 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9527
9528 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9529 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9530 callee->regs[BPF_REG_2].btf = btf_vmlinux;
9531 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9532
9533 /* pointer to stack or null */
9534 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9535
9536 /* unused */
9537 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9538 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9539 callee->in_callback_fn = true;
9540 callee->callback_ret_range = tnum_range(0, 1);
9541 return 0;
9542 }
9543
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9544 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9545 struct bpf_func_state *caller,
9546 struct bpf_func_state *callee,
9547 int insn_idx)
9548 {
9549 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9550 * callback_ctx, u64 flags);
9551 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9552 */
9553 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9554 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9555 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9556
9557 /* unused */
9558 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9559 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9560 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9561
9562 callee->in_callback_fn = true;
9563 callee->callback_ret_range = tnum_range(0, 1);
9564 return 0;
9565 }
9566
set_rbtree_add_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)9567 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9568 struct bpf_func_state *caller,
9569 struct bpf_func_state *callee,
9570 int insn_idx)
9571 {
9572 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9573 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9574 *
9575 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9576 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9577 * by this point, so look at 'root'
9578 */
9579 struct btf_field *field;
9580
9581 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9582 BPF_RB_ROOT);
9583 if (!field || !field->graph_root.value_btf_id)
9584 return -EFAULT;
9585
9586 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9587 ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9588 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9589 ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9590
9591 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9592 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9593 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9594 callee->in_callback_fn = true;
9595 callee->callback_ret_range = tnum_range(0, 1);
9596 return 0;
9597 }
9598
9599 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9600
9601 /* Are we currently verifying the callback for a rbtree helper that must
9602 * be called with lock held? If so, no need to complain about unreleased
9603 * lock
9604 */
in_rbtree_lock_required_cb(struct bpf_verifier_env * env)9605 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9606 {
9607 struct bpf_verifier_state *state = env->cur_state;
9608 struct bpf_insn *insn = env->prog->insnsi;
9609 struct bpf_func_state *callee;
9610 int kfunc_btf_id;
9611
9612 if (!state->curframe)
9613 return false;
9614
9615 callee = state->frame[state->curframe];
9616
9617 if (!callee->in_callback_fn)
9618 return false;
9619
9620 kfunc_btf_id = insn[callee->callsite].imm;
9621 return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9622 }
9623
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)9624 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9625 {
9626 struct bpf_verifier_state *state = env->cur_state, *prev_st;
9627 struct bpf_func_state *caller, *callee;
9628 struct bpf_reg_state *r0;
9629 bool in_callback_fn;
9630 int err;
9631
9632 callee = state->frame[state->curframe];
9633 r0 = &callee->regs[BPF_REG_0];
9634 if (r0->type == PTR_TO_STACK) {
9635 /* technically it's ok to return caller's stack pointer
9636 * (or caller's caller's pointer) back to the caller,
9637 * since these pointers are valid. Only current stack
9638 * pointer will be invalid as soon as function exits,
9639 * but let's be conservative
9640 */
9641 verbose(env, "cannot return stack pointer to the caller\n");
9642 return -EINVAL;
9643 }
9644
9645 caller = state->frame[state->curframe - 1];
9646 if (callee->in_callback_fn) {
9647 /* enforce R0 return value range [0, 1]. */
9648 struct tnum range = callee->callback_ret_range;
9649
9650 if (r0->type != SCALAR_VALUE) {
9651 verbose(env, "R0 not a scalar value\n");
9652 return -EACCES;
9653 }
9654
9655 /* we are going to rely on register's precise value */
9656 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9657 err = err ?: mark_chain_precision(env, BPF_REG_0);
9658 if (err)
9659 return err;
9660
9661 if (!tnum_in(range, r0->var_off)) {
9662 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9663 return -EINVAL;
9664 }
9665 if (!calls_callback(env, callee->callsite)) {
9666 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n",
9667 *insn_idx, callee->callsite);
9668 return -EFAULT;
9669 }
9670 } else {
9671 /* return to the caller whatever r0 had in the callee */
9672 caller->regs[BPF_REG_0] = *r0;
9673 }
9674
9675 /* callback_fn frame should have released its own additions to parent's
9676 * reference state at this point, or check_reference_leak would
9677 * complain, hence it must be the same as the caller. There is no need
9678 * to copy it back.
9679 */
9680 if (!callee->in_callback_fn) {
9681 /* Transfer references to the caller */
9682 err = copy_reference_state(caller, callee);
9683 if (err)
9684 return err;
9685 }
9686
9687 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
9688 * there function call logic would reschedule callback visit. If iteration
9689 * converges is_state_visited() would prune that visit eventually.
9690 */
9691 in_callback_fn = callee->in_callback_fn;
9692 if (in_callback_fn)
9693 *insn_idx = callee->callsite;
9694 else
9695 *insn_idx = callee->callsite + 1;
9696
9697 if (env->log.level & BPF_LOG_LEVEL) {
9698 verbose(env, "returning from callee:\n");
9699 print_verifier_state(env, callee, true);
9700 verbose(env, "to caller at %d:\n", *insn_idx);
9701 print_verifier_state(env, caller, true);
9702 }
9703 /* clear everything in the callee */
9704 free_func_state(callee);
9705 state->frame[state->curframe--] = NULL;
9706
9707 /* for callbacks widen imprecise scalars to make programs like below verify:
9708 *
9709 * struct ctx { int i; }
9710 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... }
9711 * ...
9712 * struct ctx = { .i = 0; }
9713 * bpf_loop(100, cb, &ctx, 0);
9714 *
9715 * This is similar to what is done in process_iter_next_call() for open
9716 * coded iterators.
9717 */
9718 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL;
9719 if (prev_st) {
9720 err = widen_imprecise_scalars(env, prev_st, state);
9721 if (err)
9722 return err;
9723 }
9724 return 0;
9725 }
9726
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)9727 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9728 int func_id,
9729 struct bpf_call_arg_meta *meta)
9730 {
9731 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
9732
9733 if (ret_type != RET_INTEGER)
9734 return;
9735
9736 switch (func_id) {
9737 case BPF_FUNC_get_stack:
9738 case BPF_FUNC_get_task_stack:
9739 case BPF_FUNC_probe_read_str:
9740 case BPF_FUNC_probe_read_kernel_str:
9741 case BPF_FUNC_probe_read_user_str:
9742 ret_reg->smax_value = meta->msize_max_value;
9743 ret_reg->s32_max_value = meta->msize_max_value;
9744 ret_reg->smin_value = -MAX_ERRNO;
9745 ret_reg->s32_min_value = -MAX_ERRNO;
9746 reg_bounds_sync(ret_reg);
9747 break;
9748 case BPF_FUNC_get_smp_processor_id:
9749 ret_reg->umax_value = nr_cpu_ids - 1;
9750 ret_reg->u32_max_value = nr_cpu_ids - 1;
9751 ret_reg->smax_value = nr_cpu_ids - 1;
9752 ret_reg->s32_max_value = nr_cpu_ids - 1;
9753 ret_reg->umin_value = 0;
9754 ret_reg->u32_min_value = 0;
9755 ret_reg->smin_value = 0;
9756 ret_reg->s32_min_value = 0;
9757 reg_bounds_sync(ret_reg);
9758 break;
9759 }
9760 }
9761
9762 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9763 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9764 int func_id, int insn_idx)
9765 {
9766 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9767 struct bpf_map *map = meta->map_ptr;
9768
9769 if (func_id != BPF_FUNC_tail_call &&
9770 func_id != BPF_FUNC_map_lookup_elem &&
9771 func_id != BPF_FUNC_map_update_elem &&
9772 func_id != BPF_FUNC_map_delete_elem &&
9773 func_id != BPF_FUNC_map_push_elem &&
9774 func_id != BPF_FUNC_map_pop_elem &&
9775 func_id != BPF_FUNC_map_peek_elem &&
9776 func_id != BPF_FUNC_for_each_map_elem &&
9777 func_id != BPF_FUNC_redirect_map &&
9778 func_id != BPF_FUNC_map_lookup_percpu_elem)
9779 return 0;
9780
9781 if (map == NULL) {
9782 verbose(env, "kernel subsystem misconfigured verifier\n");
9783 return -EINVAL;
9784 }
9785
9786 /* In case of read-only, some additional restrictions
9787 * need to be applied in order to prevent altering the
9788 * state of the map from program side.
9789 */
9790 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9791 (func_id == BPF_FUNC_map_delete_elem ||
9792 func_id == BPF_FUNC_map_update_elem ||
9793 func_id == BPF_FUNC_map_push_elem ||
9794 func_id == BPF_FUNC_map_pop_elem)) {
9795 verbose(env, "write into map forbidden\n");
9796 return -EACCES;
9797 }
9798
9799 if (!BPF_MAP_PTR(aux->map_ptr_state))
9800 bpf_map_ptr_store(aux, meta->map_ptr,
9801 !meta->map_ptr->bypass_spec_v1);
9802 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9803 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9804 !meta->map_ptr->bypass_spec_v1);
9805 return 0;
9806 }
9807
9808 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)9809 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9810 int func_id, int insn_idx)
9811 {
9812 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9813 struct bpf_reg_state *regs = cur_regs(env), *reg;
9814 struct bpf_map *map = meta->map_ptr;
9815 u64 val, max;
9816 int err;
9817
9818 if (func_id != BPF_FUNC_tail_call)
9819 return 0;
9820 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9821 verbose(env, "kernel subsystem misconfigured verifier\n");
9822 return -EINVAL;
9823 }
9824
9825 reg = ®s[BPF_REG_3];
9826 val = reg->var_off.value;
9827 max = map->max_entries;
9828
9829 if (!(register_is_const(reg) && val < max)) {
9830 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9831 return 0;
9832 }
9833
9834 err = mark_chain_precision(env, BPF_REG_3);
9835 if (err)
9836 return err;
9837 if (bpf_map_key_unseen(aux))
9838 bpf_map_key_store(aux, val);
9839 else if (!bpf_map_key_poisoned(aux) &&
9840 bpf_map_key_immediate(aux) != val)
9841 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9842 return 0;
9843 }
9844
check_reference_leak(struct bpf_verifier_env * env)9845 static int check_reference_leak(struct bpf_verifier_env *env)
9846 {
9847 struct bpf_func_state *state = cur_func(env);
9848 bool refs_lingering = false;
9849 int i;
9850
9851 if (state->frameno && !state->in_callback_fn)
9852 return 0;
9853
9854 for (i = 0; i < state->acquired_refs; i++) {
9855 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9856 continue;
9857 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9858 state->refs[i].id, state->refs[i].insn_idx);
9859 refs_lingering = true;
9860 }
9861 return refs_lingering ? -EINVAL : 0;
9862 }
9863
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)9864 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9865 struct bpf_reg_state *regs)
9866 {
9867 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
9868 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
9869 struct bpf_map *fmt_map = fmt_reg->map_ptr;
9870 struct bpf_bprintf_data data = {};
9871 int err, fmt_map_off, num_args;
9872 u64 fmt_addr;
9873 char *fmt;
9874
9875 /* data must be an array of u64 */
9876 if (data_len_reg->var_off.value % 8)
9877 return -EINVAL;
9878 num_args = data_len_reg->var_off.value / 8;
9879
9880 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9881 * and map_direct_value_addr is set.
9882 */
9883 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9884 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9885 fmt_map_off);
9886 if (err) {
9887 verbose(env, "verifier bug\n");
9888 return -EFAULT;
9889 }
9890 fmt = (char *)(long)fmt_addr + fmt_map_off;
9891
9892 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9893 * can focus on validating the format specifiers.
9894 */
9895 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9896 if (err < 0)
9897 verbose(env, "Invalid format string\n");
9898
9899 return err;
9900 }
9901
check_get_func_ip(struct bpf_verifier_env * env)9902 static int check_get_func_ip(struct bpf_verifier_env *env)
9903 {
9904 enum bpf_prog_type type = resolve_prog_type(env->prog);
9905 int func_id = BPF_FUNC_get_func_ip;
9906
9907 if (type == BPF_PROG_TYPE_TRACING) {
9908 if (!bpf_prog_has_trampoline(env->prog)) {
9909 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9910 func_id_name(func_id), func_id);
9911 return -ENOTSUPP;
9912 }
9913 return 0;
9914 } else if (type == BPF_PROG_TYPE_KPROBE) {
9915 return 0;
9916 }
9917
9918 verbose(env, "func %s#%d not supported for program type %d\n",
9919 func_id_name(func_id), func_id, type);
9920 return -ENOTSUPP;
9921 }
9922
cur_aux(struct bpf_verifier_env * env)9923 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9924 {
9925 return &env->insn_aux_data[env->insn_idx];
9926 }
9927
loop_flag_is_zero(struct bpf_verifier_env * env)9928 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9929 {
9930 struct bpf_reg_state *regs = cur_regs(env);
9931 struct bpf_reg_state *reg = ®s[BPF_REG_4];
9932 bool reg_is_null = register_is_null(reg);
9933
9934 if (reg_is_null)
9935 mark_chain_precision(env, BPF_REG_4);
9936
9937 return reg_is_null;
9938 }
9939
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)9940 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9941 {
9942 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9943
9944 if (!state->initialized) {
9945 state->initialized = 1;
9946 state->fit_for_inline = loop_flag_is_zero(env);
9947 state->callback_subprogno = subprogno;
9948 return;
9949 }
9950
9951 if (!state->fit_for_inline)
9952 return;
9953
9954 state->fit_for_inline = (loop_flag_is_zero(env) &&
9955 state->callback_subprogno == subprogno);
9956 }
9957
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)9958 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9959 int *insn_idx_p)
9960 {
9961 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9962 const struct bpf_func_proto *fn = NULL;
9963 enum bpf_return_type ret_type;
9964 enum bpf_type_flag ret_flag;
9965 struct bpf_reg_state *regs;
9966 struct bpf_call_arg_meta meta;
9967 int insn_idx = *insn_idx_p;
9968 bool changes_data;
9969 int i, err, func_id;
9970
9971 /* find function prototype */
9972 func_id = insn->imm;
9973 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9974 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9975 func_id);
9976 return -EINVAL;
9977 }
9978
9979 if (env->ops->get_func_proto)
9980 fn = env->ops->get_func_proto(func_id, env->prog);
9981 if (!fn) {
9982 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9983 func_id);
9984 return -EINVAL;
9985 }
9986
9987 /* eBPF programs must be GPL compatible to use GPL-ed functions */
9988 if (!env->prog->gpl_compatible && fn->gpl_only) {
9989 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9990 return -EINVAL;
9991 }
9992
9993 if (fn->allowed && !fn->allowed(env->prog)) {
9994 verbose(env, "helper call is not allowed in probe\n");
9995 return -EINVAL;
9996 }
9997
9998 if (!env->prog->aux->sleepable && fn->might_sleep) {
9999 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10000 return -EINVAL;
10001 }
10002
10003 /* With LD_ABS/IND some JITs save/restore skb from r1. */
10004 changes_data = bpf_helper_changes_pkt_data(fn->func);
10005 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10006 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10007 func_id_name(func_id), func_id);
10008 return -EINVAL;
10009 }
10010
10011 memset(&meta, 0, sizeof(meta));
10012 meta.pkt_access = fn->pkt_access;
10013
10014 err = check_func_proto(fn, func_id);
10015 if (err) {
10016 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10017 func_id_name(func_id), func_id);
10018 return err;
10019 }
10020
10021 if (env->cur_state->active_rcu_lock) {
10022 if (fn->might_sleep) {
10023 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10024 func_id_name(func_id), func_id);
10025 return -EINVAL;
10026 }
10027
10028 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10029 env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10030 }
10031
10032 meta.func_id = func_id;
10033 /* check args */
10034 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10035 err = check_func_arg(env, i, &meta, fn, insn_idx);
10036 if (err)
10037 return err;
10038 }
10039
10040 err = record_func_map(env, &meta, func_id, insn_idx);
10041 if (err)
10042 return err;
10043
10044 err = record_func_key(env, &meta, func_id, insn_idx);
10045 if (err)
10046 return err;
10047
10048 /* Mark slots with STACK_MISC in case of raw mode, stack offset
10049 * is inferred from register state.
10050 */
10051 for (i = 0; i < meta.access_size; i++) {
10052 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10053 BPF_WRITE, -1, false, false);
10054 if (err)
10055 return err;
10056 }
10057
10058 regs = cur_regs(env);
10059
10060 if (meta.release_regno) {
10061 err = -EINVAL;
10062 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10063 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10064 * is safe to do directly.
10065 */
10066 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10067 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10068 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10069 return -EFAULT;
10070 }
10071 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
10072 } else if (meta.ref_obj_id) {
10073 err = release_reference(env, meta.ref_obj_id);
10074 } else if (register_is_null(®s[meta.release_regno])) {
10075 /* meta.ref_obj_id can only be 0 if register that is meant to be
10076 * released is NULL, which must be > R0.
10077 */
10078 err = 0;
10079 }
10080 if (err) {
10081 verbose(env, "func %s#%d reference has not been acquired before\n",
10082 func_id_name(func_id), func_id);
10083 return err;
10084 }
10085 }
10086
10087 switch (func_id) {
10088 case BPF_FUNC_tail_call:
10089 err = check_reference_leak(env);
10090 if (err) {
10091 verbose(env, "tail_call would lead to reference leak\n");
10092 return err;
10093 }
10094 break;
10095 case BPF_FUNC_get_local_storage:
10096 /* check that flags argument in get_local_storage(map, flags) is 0,
10097 * this is required because get_local_storage() can't return an error.
10098 */
10099 if (!register_is_null(®s[BPF_REG_2])) {
10100 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10101 return -EINVAL;
10102 }
10103 break;
10104 case BPF_FUNC_for_each_map_elem:
10105 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10106 set_map_elem_callback_state);
10107 break;
10108 case BPF_FUNC_timer_set_callback:
10109 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10110 set_timer_callback_state);
10111 break;
10112 case BPF_FUNC_find_vma:
10113 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10114 set_find_vma_callback_state);
10115 break;
10116 case BPF_FUNC_snprintf:
10117 err = check_bpf_snprintf_call(env, regs);
10118 break;
10119 case BPF_FUNC_loop:
10120 update_loop_inline_state(env, meta.subprogno);
10121 /* Verifier relies on R1 value to determine if bpf_loop() iteration
10122 * is finished, thus mark it precise.
10123 */
10124 err = mark_chain_precision(env, BPF_REG_1);
10125 if (err)
10126 return err;
10127 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) {
10128 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10129 set_loop_callback_state);
10130 } else {
10131 cur_func(env)->callback_depth = 0;
10132 if (env->log.level & BPF_LOG_LEVEL2)
10133 verbose(env, "frame%d bpf_loop iteration limit reached\n",
10134 env->cur_state->curframe);
10135 }
10136 break;
10137 case BPF_FUNC_dynptr_from_mem:
10138 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10139 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10140 reg_type_str(env, regs[BPF_REG_1].type));
10141 return -EACCES;
10142 }
10143 break;
10144 case BPF_FUNC_set_retval:
10145 if (prog_type == BPF_PROG_TYPE_LSM &&
10146 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10147 if (!env->prog->aux->attach_func_proto->type) {
10148 /* Make sure programs that attach to void
10149 * hooks don't try to modify return value.
10150 */
10151 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10152 return -EINVAL;
10153 }
10154 }
10155 break;
10156 case BPF_FUNC_dynptr_data:
10157 {
10158 struct bpf_reg_state *reg;
10159 int id, ref_obj_id;
10160
10161 reg = get_dynptr_arg_reg(env, fn, regs);
10162 if (!reg)
10163 return -EFAULT;
10164
10165
10166 if (meta.dynptr_id) {
10167 verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10168 return -EFAULT;
10169 }
10170 if (meta.ref_obj_id) {
10171 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10172 return -EFAULT;
10173 }
10174
10175 id = dynptr_id(env, reg);
10176 if (id < 0) {
10177 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10178 return id;
10179 }
10180
10181 ref_obj_id = dynptr_ref_obj_id(env, reg);
10182 if (ref_obj_id < 0) {
10183 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10184 return ref_obj_id;
10185 }
10186
10187 meta.dynptr_id = id;
10188 meta.ref_obj_id = ref_obj_id;
10189
10190 break;
10191 }
10192 case BPF_FUNC_dynptr_write:
10193 {
10194 enum bpf_dynptr_type dynptr_type;
10195 struct bpf_reg_state *reg;
10196
10197 reg = get_dynptr_arg_reg(env, fn, regs);
10198 if (!reg)
10199 return -EFAULT;
10200
10201 dynptr_type = dynptr_get_type(env, reg);
10202 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10203 return -EFAULT;
10204
10205 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10206 /* this will trigger clear_all_pkt_pointers(), which will
10207 * invalidate all dynptr slices associated with the skb
10208 */
10209 changes_data = true;
10210
10211 break;
10212 }
10213 case BPF_FUNC_user_ringbuf_drain:
10214 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
10215 set_user_ringbuf_callback_state);
10216 break;
10217 }
10218
10219 if (err)
10220 return err;
10221
10222 /* reset caller saved regs */
10223 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10224 mark_reg_not_init(env, regs, caller_saved[i]);
10225 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10226 }
10227
10228 /* helper call returns 64-bit value. */
10229 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10230
10231 /* update return register (already marked as written above) */
10232 ret_type = fn->ret_type;
10233 ret_flag = type_flag(ret_type);
10234
10235 switch (base_type(ret_type)) {
10236 case RET_INTEGER:
10237 /* sets type to SCALAR_VALUE */
10238 mark_reg_unknown(env, regs, BPF_REG_0);
10239 break;
10240 case RET_VOID:
10241 regs[BPF_REG_0].type = NOT_INIT;
10242 break;
10243 case RET_PTR_TO_MAP_VALUE:
10244 /* There is no offset yet applied, variable or fixed */
10245 mark_reg_known_zero(env, regs, BPF_REG_0);
10246 /* remember map_ptr, so that check_map_access()
10247 * can check 'value_size' boundary of memory access
10248 * to map element returned from bpf_map_lookup_elem()
10249 */
10250 if (meta.map_ptr == NULL) {
10251 verbose(env,
10252 "kernel subsystem misconfigured verifier\n");
10253 return -EINVAL;
10254 }
10255 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10256 regs[BPF_REG_0].map_uid = meta.map_uid;
10257 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10258 if (!type_may_be_null(ret_type) &&
10259 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10260 regs[BPF_REG_0].id = ++env->id_gen;
10261 }
10262 break;
10263 case RET_PTR_TO_SOCKET:
10264 mark_reg_known_zero(env, regs, BPF_REG_0);
10265 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10266 break;
10267 case RET_PTR_TO_SOCK_COMMON:
10268 mark_reg_known_zero(env, regs, BPF_REG_0);
10269 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10270 break;
10271 case RET_PTR_TO_TCP_SOCK:
10272 mark_reg_known_zero(env, regs, BPF_REG_0);
10273 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10274 break;
10275 case RET_PTR_TO_MEM:
10276 mark_reg_known_zero(env, regs, BPF_REG_0);
10277 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10278 regs[BPF_REG_0].mem_size = meta.mem_size;
10279 break;
10280 case RET_PTR_TO_MEM_OR_BTF_ID:
10281 {
10282 const struct btf_type *t;
10283
10284 mark_reg_known_zero(env, regs, BPF_REG_0);
10285 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10286 if (!btf_type_is_struct(t)) {
10287 u32 tsize;
10288 const struct btf_type *ret;
10289 const char *tname;
10290
10291 /* resolve the type size of ksym. */
10292 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10293 if (IS_ERR(ret)) {
10294 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10295 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10296 tname, PTR_ERR(ret));
10297 return -EINVAL;
10298 }
10299 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10300 regs[BPF_REG_0].mem_size = tsize;
10301 } else {
10302 /* MEM_RDONLY may be carried from ret_flag, but it
10303 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10304 * it will confuse the check of PTR_TO_BTF_ID in
10305 * check_mem_access().
10306 */
10307 ret_flag &= ~MEM_RDONLY;
10308
10309 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10310 regs[BPF_REG_0].btf = meta.ret_btf;
10311 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10312 }
10313 break;
10314 }
10315 case RET_PTR_TO_BTF_ID:
10316 {
10317 struct btf *ret_btf;
10318 int ret_btf_id;
10319
10320 mark_reg_known_zero(env, regs, BPF_REG_0);
10321 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10322 if (func_id == BPF_FUNC_kptr_xchg) {
10323 ret_btf = meta.kptr_field->kptr.btf;
10324 ret_btf_id = meta.kptr_field->kptr.btf_id;
10325 if (!btf_is_kernel(ret_btf))
10326 regs[BPF_REG_0].type |= MEM_ALLOC;
10327 } else {
10328 if (fn->ret_btf_id == BPF_PTR_POISON) {
10329 verbose(env, "verifier internal error:");
10330 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10331 func_id_name(func_id));
10332 return -EINVAL;
10333 }
10334 ret_btf = btf_vmlinux;
10335 ret_btf_id = *fn->ret_btf_id;
10336 }
10337 if (ret_btf_id == 0) {
10338 verbose(env, "invalid return type %u of func %s#%d\n",
10339 base_type(ret_type), func_id_name(func_id),
10340 func_id);
10341 return -EINVAL;
10342 }
10343 regs[BPF_REG_0].btf = ret_btf;
10344 regs[BPF_REG_0].btf_id = ret_btf_id;
10345 break;
10346 }
10347 default:
10348 verbose(env, "unknown return type %u of func %s#%d\n",
10349 base_type(ret_type), func_id_name(func_id), func_id);
10350 return -EINVAL;
10351 }
10352
10353 if (type_may_be_null(regs[BPF_REG_0].type))
10354 regs[BPF_REG_0].id = ++env->id_gen;
10355
10356 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10357 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10358 func_id_name(func_id), func_id);
10359 return -EFAULT;
10360 }
10361
10362 if (is_dynptr_ref_function(func_id))
10363 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10364
10365 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10366 /* For release_reference() */
10367 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10368 } else if (is_acquire_function(func_id, meta.map_ptr)) {
10369 int id = acquire_reference_state(env, insn_idx);
10370
10371 if (id < 0)
10372 return id;
10373 /* For mark_ptr_or_null_reg() */
10374 regs[BPF_REG_0].id = id;
10375 /* For release_reference() */
10376 regs[BPF_REG_0].ref_obj_id = id;
10377 }
10378
10379 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10380
10381 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10382 if (err)
10383 return err;
10384
10385 if ((func_id == BPF_FUNC_get_stack ||
10386 func_id == BPF_FUNC_get_task_stack) &&
10387 !env->prog->has_callchain_buf) {
10388 const char *err_str;
10389
10390 #ifdef CONFIG_PERF_EVENTS
10391 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10392 err_str = "cannot get callchain buffer for func %s#%d\n";
10393 #else
10394 err = -ENOTSUPP;
10395 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10396 #endif
10397 if (err) {
10398 verbose(env, err_str, func_id_name(func_id), func_id);
10399 return err;
10400 }
10401
10402 env->prog->has_callchain_buf = true;
10403 }
10404
10405 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10406 env->prog->call_get_stack = true;
10407
10408 if (func_id == BPF_FUNC_get_func_ip) {
10409 if (check_get_func_ip(env))
10410 return -ENOTSUPP;
10411 env->prog->call_get_func_ip = true;
10412 }
10413
10414 if (changes_data)
10415 clear_all_pkt_pointers(env);
10416 return 0;
10417 }
10418
10419 /* mark_btf_func_reg_size() is used when the reg size is determined by
10420 * the BTF func_proto's return value size and argument.
10421 */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)10422 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10423 size_t reg_size)
10424 {
10425 struct bpf_reg_state *reg = &cur_regs(env)[regno];
10426
10427 if (regno == BPF_REG_0) {
10428 /* Function return value */
10429 reg->live |= REG_LIVE_WRITTEN;
10430 reg->subreg_def = reg_size == sizeof(u64) ?
10431 DEF_NOT_SUBREG : env->insn_idx + 1;
10432 } else {
10433 /* Function argument */
10434 if (reg_size == sizeof(u64)) {
10435 mark_insn_zext(env, reg);
10436 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10437 } else {
10438 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10439 }
10440 }
10441 }
10442
is_kfunc_acquire(struct bpf_kfunc_call_arg_meta * meta)10443 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10444 {
10445 return meta->kfunc_flags & KF_ACQUIRE;
10446 }
10447
is_kfunc_release(struct bpf_kfunc_call_arg_meta * meta)10448 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10449 {
10450 return meta->kfunc_flags & KF_RELEASE;
10451 }
10452
is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta * meta)10453 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10454 {
10455 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10456 }
10457
is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta * meta)10458 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10459 {
10460 return meta->kfunc_flags & KF_SLEEPABLE;
10461 }
10462
is_kfunc_destructive(struct bpf_kfunc_call_arg_meta * meta)10463 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10464 {
10465 return meta->kfunc_flags & KF_DESTRUCTIVE;
10466 }
10467
is_kfunc_rcu(struct bpf_kfunc_call_arg_meta * meta)10468 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10469 {
10470 return meta->kfunc_flags & KF_RCU;
10471 }
10472
__kfunc_param_match_suffix(const struct btf * btf,const struct btf_param * arg,const char * suffix)10473 static bool __kfunc_param_match_suffix(const struct btf *btf,
10474 const struct btf_param *arg,
10475 const char *suffix)
10476 {
10477 int suffix_len = strlen(suffix), len;
10478 const char *param_name;
10479
10480 /* In the future, this can be ported to use BTF tagging */
10481 param_name = btf_name_by_offset(btf, arg->name_off);
10482 if (str_is_empty(param_name))
10483 return false;
10484 len = strlen(param_name);
10485 if (len < suffix_len)
10486 return false;
10487 param_name += len - suffix_len;
10488 return !strncmp(param_name, suffix, suffix_len);
10489 }
10490
is_kfunc_arg_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10491 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10492 const struct btf_param *arg,
10493 const struct bpf_reg_state *reg)
10494 {
10495 const struct btf_type *t;
10496
10497 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10498 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10499 return false;
10500
10501 return __kfunc_param_match_suffix(btf, arg, "__sz");
10502 }
10503
is_kfunc_arg_const_mem_size(const struct btf * btf,const struct btf_param * arg,const struct bpf_reg_state * reg)10504 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10505 const struct btf_param *arg,
10506 const struct bpf_reg_state *reg)
10507 {
10508 const struct btf_type *t;
10509
10510 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10511 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10512 return false;
10513
10514 return __kfunc_param_match_suffix(btf, arg, "__szk");
10515 }
10516
is_kfunc_arg_optional(const struct btf * btf,const struct btf_param * arg)10517 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10518 {
10519 return __kfunc_param_match_suffix(btf, arg, "__opt");
10520 }
10521
is_kfunc_arg_constant(const struct btf * btf,const struct btf_param * arg)10522 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10523 {
10524 return __kfunc_param_match_suffix(btf, arg, "__k");
10525 }
10526
is_kfunc_arg_ignore(const struct btf * btf,const struct btf_param * arg)10527 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10528 {
10529 return __kfunc_param_match_suffix(btf, arg, "__ign");
10530 }
10531
is_kfunc_arg_alloc_obj(const struct btf * btf,const struct btf_param * arg)10532 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10533 {
10534 return __kfunc_param_match_suffix(btf, arg, "__alloc");
10535 }
10536
is_kfunc_arg_uninit(const struct btf * btf,const struct btf_param * arg)10537 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10538 {
10539 return __kfunc_param_match_suffix(btf, arg, "__uninit");
10540 }
10541
is_kfunc_arg_refcounted_kptr(const struct btf * btf,const struct btf_param * arg)10542 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10543 {
10544 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10545 }
10546
is_kfunc_arg_scalar_with_name(const struct btf * btf,const struct btf_param * arg,const char * name)10547 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10548 const struct btf_param *arg,
10549 const char *name)
10550 {
10551 int len, target_len = strlen(name);
10552 const char *param_name;
10553
10554 param_name = btf_name_by_offset(btf, arg->name_off);
10555 if (str_is_empty(param_name))
10556 return false;
10557 len = strlen(param_name);
10558 if (len != target_len)
10559 return false;
10560 if (strcmp(param_name, name))
10561 return false;
10562
10563 return true;
10564 }
10565
10566 enum {
10567 KF_ARG_DYNPTR_ID,
10568 KF_ARG_LIST_HEAD_ID,
10569 KF_ARG_LIST_NODE_ID,
10570 KF_ARG_RB_ROOT_ID,
10571 KF_ARG_RB_NODE_ID,
10572 };
10573
10574 BTF_ID_LIST(kf_arg_btf_ids)
BTF_ID(struct,bpf_dynptr_kern)10575 BTF_ID(struct, bpf_dynptr_kern)
10576 BTF_ID(struct, bpf_list_head)
10577 BTF_ID(struct, bpf_list_node)
10578 BTF_ID(struct, bpf_rb_root)
10579 BTF_ID(struct, bpf_rb_node)
10580
10581 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10582 const struct btf_param *arg, int type)
10583 {
10584 const struct btf_type *t;
10585 u32 res_id;
10586
10587 t = btf_type_skip_modifiers(btf, arg->type, NULL);
10588 if (!t)
10589 return false;
10590 if (!btf_type_is_ptr(t))
10591 return false;
10592 t = btf_type_skip_modifiers(btf, t->type, &res_id);
10593 if (!t)
10594 return false;
10595 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10596 }
10597
is_kfunc_arg_dynptr(const struct btf * btf,const struct btf_param * arg)10598 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10599 {
10600 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10601 }
10602
is_kfunc_arg_list_head(const struct btf * btf,const struct btf_param * arg)10603 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10604 {
10605 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10606 }
10607
is_kfunc_arg_list_node(const struct btf * btf,const struct btf_param * arg)10608 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10609 {
10610 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10611 }
10612
is_kfunc_arg_rbtree_root(const struct btf * btf,const struct btf_param * arg)10613 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10614 {
10615 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10616 }
10617
is_kfunc_arg_rbtree_node(const struct btf * btf,const struct btf_param * arg)10618 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10619 {
10620 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10621 }
10622
is_kfunc_arg_callback(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_param * arg)10623 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10624 const struct btf_param *arg)
10625 {
10626 const struct btf_type *t;
10627
10628 t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10629 if (!t)
10630 return false;
10631
10632 return true;
10633 }
10634
10635 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
__btf_type_is_scalar_struct(struct bpf_verifier_env * env,const struct btf * btf,const struct btf_type * t,int rec)10636 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10637 const struct btf *btf,
10638 const struct btf_type *t, int rec)
10639 {
10640 const struct btf_type *member_type;
10641 const struct btf_member *member;
10642 u32 i;
10643
10644 if (!btf_type_is_struct(t))
10645 return false;
10646
10647 for_each_member(i, t, member) {
10648 const struct btf_array *array;
10649
10650 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10651 if (btf_type_is_struct(member_type)) {
10652 if (rec >= 3) {
10653 verbose(env, "max struct nesting depth exceeded\n");
10654 return false;
10655 }
10656 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10657 return false;
10658 continue;
10659 }
10660 if (btf_type_is_array(member_type)) {
10661 array = btf_array(member_type);
10662 if (!array->nelems)
10663 return false;
10664 member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10665 if (!btf_type_is_scalar(member_type))
10666 return false;
10667 continue;
10668 }
10669 if (!btf_type_is_scalar(member_type))
10670 return false;
10671 }
10672 return true;
10673 }
10674
10675 enum kfunc_ptr_arg_type {
10676 KF_ARG_PTR_TO_CTX,
10677 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */
10678 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10679 KF_ARG_PTR_TO_DYNPTR,
10680 KF_ARG_PTR_TO_ITER,
10681 KF_ARG_PTR_TO_LIST_HEAD,
10682 KF_ARG_PTR_TO_LIST_NODE,
10683 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */
10684 KF_ARG_PTR_TO_MEM,
10685 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */
10686 KF_ARG_PTR_TO_CALLBACK,
10687 KF_ARG_PTR_TO_RB_ROOT,
10688 KF_ARG_PTR_TO_RB_NODE,
10689 };
10690
10691 enum special_kfunc_type {
10692 KF_bpf_obj_new_impl,
10693 KF_bpf_obj_drop_impl,
10694 KF_bpf_refcount_acquire_impl,
10695 KF_bpf_list_push_front_impl,
10696 KF_bpf_list_push_back_impl,
10697 KF_bpf_list_pop_front,
10698 KF_bpf_list_pop_back,
10699 KF_bpf_cast_to_kern_ctx,
10700 KF_bpf_rdonly_cast,
10701 KF_bpf_rcu_read_lock,
10702 KF_bpf_rcu_read_unlock,
10703 KF_bpf_rbtree_remove,
10704 KF_bpf_rbtree_add_impl,
10705 KF_bpf_rbtree_first,
10706 KF_bpf_dynptr_from_skb,
10707 KF_bpf_dynptr_from_xdp,
10708 KF_bpf_dynptr_slice,
10709 KF_bpf_dynptr_slice_rdwr,
10710 KF_bpf_dynptr_clone,
10711 };
10712
10713 BTF_SET_START(special_kfunc_set)
BTF_ID(func,bpf_obj_new_impl)10714 BTF_ID(func, bpf_obj_new_impl)
10715 BTF_ID(func, bpf_obj_drop_impl)
10716 BTF_ID(func, bpf_refcount_acquire_impl)
10717 BTF_ID(func, bpf_list_push_front_impl)
10718 BTF_ID(func, bpf_list_push_back_impl)
10719 BTF_ID(func, bpf_list_pop_front)
10720 BTF_ID(func, bpf_list_pop_back)
10721 BTF_ID(func, bpf_cast_to_kern_ctx)
10722 BTF_ID(func, bpf_rdonly_cast)
10723 BTF_ID(func, bpf_rbtree_remove)
10724 BTF_ID(func, bpf_rbtree_add_impl)
10725 BTF_ID(func, bpf_rbtree_first)
10726 BTF_ID(func, bpf_dynptr_from_skb)
10727 BTF_ID(func, bpf_dynptr_from_xdp)
10728 BTF_ID(func, bpf_dynptr_slice)
10729 BTF_ID(func, bpf_dynptr_slice_rdwr)
10730 BTF_ID(func, bpf_dynptr_clone)
10731 BTF_SET_END(special_kfunc_set)
10732
10733 BTF_ID_LIST(special_kfunc_list)
10734 BTF_ID(func, bpf_obj_new_impl)
10735 BTF_ID(func, bpf_obj_drop_impl)
10736 BTF_ID(func, bpf_refcount_acquire_impl)
10737 BTF_ID(func, bpf_list_push_front_impl)
10738 BTF_ID(func, bpf_list_push_back_impl)
10739 BTF_ID(func, bpf_list_pop_front)
10740 BTF_ID(func, bpf_list_pop_back)
10741 BTF_ID(func, bpf_cast_to_kern_ctx)
10742 BTF_ID(func, bpf_rdonly_cast)
10743 BTF_ID(func, bpf_rcu_read_lock)
10744 BTF_ID(func, bpf_rcu_read_unlock)
10745 BTF_ID(func, bpf_rbtree_remove)
10746 BTF_ID(func, bpf_rbtree_add_impl)
10747 BTF_ID(func, bpf_rbtree_first)
10748 BTF_ID(func, bpf_dynptr_from_skb)
10749 BTF_ID(func, bpf_dynptr_from_xdp)
10750 BTF_ID(func, bpf_dynptr_slice)
10751 BTF_ID(func, bpf_dynptr_slice_rdwr)
10752 BTF_ID(func, bpf_dynptr_clone)
10753
10754 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10755 {
10756 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10757 meta->arg_owning_ref) {
10758 return false;
10759 }
10760
10761 return meta->kfunc_flags & KF_RET_NULL;
10762 }
10763
is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta * meta)10764 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10765 {
10766 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10767 }
10768
is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta * meta)10769 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10770 {
10771 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10772 }
10773
10774 static enum kfunc_ptr_arg_type
get_kfunc_ptr_arg_type(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,const struct btf_type * t,const struct btf_type * ref_t,const char * ref_tname,const struct btf_param * args,int argno,int nargs)10775 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10776 struct bpf_kfunc_call_arg_meta *meta,
10777 const struct btf_type *t, const struct btf_type *ref_t,
10778 const char *ref_tname, const struct btf_param *args,
10779 int argno, int nargs)
10780 {
10781 u32 regno = argno + 1;
10782 struct bpf_reg_state *regs = cur_regs(env);
10783 struct bpf_reg_state *reg = ®s[regno];
10784 bool arg_mem_size = false;
10785
10786 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10787 return KF_ARG_PTR_TO_CTX;
10788
10789 /* In this function, we verify the kfunc's BTF as per the argument type,
10790 * leaving the rest of the verification with respect to the register
10791 * type to our caller. When a set of conditions hold in the BTF type of
10792 * arguments, we resolve it to a known kfunc_ptr_arg_type.
10793 */
10794 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10795 return KF_ARG_PTR_TO_CTX;
10796
10797 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10798 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10799
10800 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10801 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10802
10803 if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10804 return KF_ARG_PTR_TO_DYNPTR;
10805
10806 if (is_kfunc_arg_iter(meta, argno))
10807 return KF_ARG_PTR_TO_ITER;
10808
10809 if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10810 return KF_ARG_PTR_TO_LIST_HEAD;
10811
10812 if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10813 return KF_ARG_PTR_TO_LIST_NODE;
10814
10815 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10816 return KF_ARG_PTR_TO_RB_ROOT;
10817
10818 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10819 return KF_ARG_PTR_TO_RB_NODE;
10820
10821 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10822 if (!btf_type_is_struct(ref_t)) {
10823 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10824 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10825 return -EINVAL;
10826 }
10827 return KF_ARG_PTR_TO_BTF_ID;
10828 }
10829
10830 if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10831 return KF_ARG_PTR_TO_CALLBACK;
10832
10833
10834 if (argno + 1 < nargs &&
10835 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) ||
10836 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])))
10837 arg_mem_size = true;
10838
10839 /* This is the catch all argument type of register types supported by
10840 * check_helper_mem_access. However, we only allow when argument type is
10841 * pointer to scalar, or struct composed (recursively) of scalars. When
10842 * arg_mem_size is true, the pointer can be void *.
10843 */
10844 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10845 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10846 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10847 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10848 return -EINVAL;
10849 }
10850 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10851 }
10852
process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg,const struct btf_type * ref_t,const char * ref_tname,u32 ref_id,struct bpf_kfunc_call_arg_meta * meta,int argno)10853 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10854 struct bpf_reg_state *reg,
10855 const struct btf_type *ref_t,
10856 const char *ref_tname, u32 ref_id,
10857 struct bpf_kfunc_call_arg_meta *meta,
10858 int argno)
10859 {
10860 const struct btf_type *reg_ref_t;
10861 bool strict_type_match = false;
10862 const struct btf *reg_btf;
10863 const char *reg_ref_tname;
10864 u32 reg_ref_id;
10865
10866 if (base_type(reg->type) == PTR_TO_BTF_ID) {
10867 reg_btf = reg->btf;
10868 reg_ref_id = reg->btf_id;
10869 } else {
10870 reg_btf = btf_vmlinux;
10871 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10872 }
10873
10874 /* Enforce strict type matching for calls to kfuncs that are acquiring
10875 * or releasing a reference, or are no-cast aliases. We do _not_
10876 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10877 * as we want to enable BPF programs to pass types that are bitwise
10878 * equivalent without forcing them to explicitly cast with something
10879 * like bpf_cast_to_kern_ctx().
10880 *
10881 * For example, say we had a type like the following:
10882 *
10883 * struct bpf_cpumask {
10884 * cpumask_t cpumask;
10885 * refcount_t usage;
10886 * };
10887 *
10888 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10889 * to a struct cpumask, so it would be safe to pass a struct
10890 * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10891 *
10892 * The philosophy here is similar to how we allow scalars of different
10893 * types to be passed to kfuncs as long as the size is the same. The
10894 * only difference here is that we're simply allowing
10895 * btf_struct_ids_match() to walk the struct at the 0th offset, and
10896 * resolve types.
10897 */
10898 if (is_kfunc_acquire(meta) ||
10899 (is_kfunc_release(meta) && reg->ref_obj_id) ||
10900 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10901 strict_type_match = true;
10902
10903 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10904
10905 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id);
10906 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10907 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10908 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10909 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10910 btf_type_str(reg_ref_t), reg_ref_tname);
10911 return -EINVAL;
10912 }
10913 return 0;
10914 }
10915
ref_set_non_owning(struct bpf_verifier_env * env,struct bpf_reg_state * reg)10916 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10917 {
10918 struct bpf_verifier_state *state = env->cur_state;
10919 struct btf_record *rec = reg_btf_record(reg);
10920
10921 if (!state->active_lock.ptr) {
10922 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10923 return -EFAULT;
10924 }
10925
10926 if (type_flag(reg->type) & NON_OWN_REF) {
10927 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10928 return -EFAULT;
10929 }
10930
10931 reg->type |= NON_OWN_REF;
10932 if (rec->refcount_off >= 0)
10933 reg->type |= MEM_RCU;
10934
10935 return 0;
10936 }
10937
ref_convert_owning_non_owning(struct bpf_verifier_env * env,u32 ref_obj_id)10938 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10939 {
10940 struct bpf_func_state *state, *unused;
10941 struct bpf_reg_state *reg;
10942 int i;
10943
10944 state = cur_func(env);
10945
10946 if (!ref_obj_id) {
10947 verbose(env, "verifier internal error: ref_obj_id is zero for "
10948 "owning -> non-owning conversion\n");
10949 return -EFAULT;
10950 }
10951
10952 for (i = 0; i < state->acquired_refs; i++) {
10953 if (state->refs[i].id != ref_obj_id)
10954 continue;
10955
10956 /* Clear ref_obj_id here so release_reference doesn't clobber
10957 * the whole reg
10958 */
10959 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10960 if (reg->ref_obj_id == ref_obj_id) {
10961 reg->ref_obj_id = 0;
10962 ref_set_non_owning(env, reg);
10963 }
10964 }));
10965 return 0;
10966 }
10967
10968 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10969 return -EFAULT;
10970 }
10971
10972 /* Implementation details:
10973 *
10974 * Each register points to some region of memory, which we define as an
10975 * allocation. Each allocation may embed a bpf_spin_lock which protects any
10976 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10977 * allocation. The lock and the data it protects are colocated in the same
10978 * memory region.
10979 *
10980 * Hence, everytime a register holds a pointer value pointing to such
10981 * allocation, the verifier preserves a unique reg->id for it.
10982 *
10983 * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10984 * bpf_spin_lock is called.
10985 *
10986 * To enable this, lock state in the verifier captures two values:
10987 * active_lock.ptr = Register's type specific pointer
10988 * active_lock.id = A unique ID for each register pointer value
10989 *
10990 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10991 * supported register types.
10992 *
10993 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10994 * allocated objects is the reg->btf pointer.
10995 *
10996 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10997 * can establish the provenance of the map value statically for each distinct
10998 * lookup into such maps. They always contain a single map value hence unique
10999 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11000 *
11001 * So, in case of global variables, they use array maps with max_entries = 1,
11002 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11003 * into the same map value as max_entries is 1, as described above).
11004 *
11005 * In case of inner map lookups, the inner map pointer has same map_ptr as the
11006 * outer map pointer (in verifier context), but each lookup into an inner map
11007 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11008 * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11009 * will get different reg->id assigned to each lookup, hence different
11010 * active_lock.id.
11011 *
11012 * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11013 * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11014 * returned from bpf_obj_new. Each allocation receives a new reg->id.
11015 */
check_reg_allocation_locked(struct bpf_verifier_env * env,struct bpf_reg_state * reg)11016 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11017 {
11018 void *ptr;
11019 u32 id;
11020
11021 switch ((int)reg->type) {
11022 case PTR_TO_MAP_VALUE:
11023 ptr = reg->map_ptr;
11024 break;
11025 case PTR_TO_BTF_ID | MEM_ALLOC:
11026 ptr = reg->btf;
11027 break;
11028 default:
11029 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11030 return -EFAULT;
11031 }
11032 id = reg->id;
11033
11034 if (!env->cur_state->active_lock.ptr)
11035 return -EINVAL;
11036 if (env->cur_state->active_lock.ptr != ptr ||
11037 env->cur_state->active_lock.id != id) {
11038 verbose(env, "held lock and object are not in the same allocation\n");
11039 return -EINVAL;
11040 }
11041 return 0;
11042 }
11043
is_bpf_list_api_kfunc(u32 btf_id)11044 static bool is_bpf_list_api_kfunc(u32 btf_id)
11045 {
11046 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11047 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11048 btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11049 btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11050 }
11051
is_bpf_rbtree_api_kfunc(u32 btf_id)11052 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11053 {
11054 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11055 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11056 btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11057 }
11058
is_bpf_graph_api_kfunc(u32 btf_id)11059 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11060 {
11061 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11062 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11063 }
11064
is_sync_callback_calling_kfunc(u32 btf_id)11065 static bool is_sync_callback_calling_kfunc(u32 btf_id)
11066 {
11067 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11068 }
11069
is_rbtree_lock_required_kfunc(u32 btf_id)11070 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11071 {
11072 return is_bpf_rbtree_api_kfunc(btf_id);
11073 }
11074
check_kfunc_is_graph_root_api(struct bpf_verifier_env * env,enum btf_field_type head_field_type,u32 kfunc_btf_id)11075 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11076 enum btf_field_type head_field_type,
11077 u32 kfunc_btf_id)
11078 {
11079 bool ret;
11080
11081 switch (head_field_type) {
11082 case BPF_LIST_HEAD:
11083 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11084 break;
11085 case BPF_RB_ROOT:
11086 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11087 break;
11088 default:
11089 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11090 btf_field_type_name(head_field_type));
11091 return false;
11092 }
11093
11094 if (!ret)
11095 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11096 btf_field_type_name(head_field_type));
11097 return ret;
11098 }
11099
check_kfunc_is_graph_node_api(struct bpf_verifier_env * env,enum btf_field_type node_field_type,u32 kfunc_btf_id)11100 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11101 enum btf_field_type node_field_type,
11102 u32 kfunc_btf_id)
11103 {
11104 bool ret;
11105
11106 switch (node_field_type) {
11107 case BPF_LIST_NODE:
11108 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11109 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11110 break;
11111 case BPF_RB_NODE:
11112 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11113 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11114 break;
11115 default:
11116 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11117 btf_field_type_name(node_field_type));
11118 return false;
11119 }
11120
11121 if (!ret)
11122 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11123 btf_field_type_name(node_field_type));
11124 return ret;
11125 }
11126
11127 static int
__process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,struct btf_field ** head_field)11128 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11129 struct bpf_reg_state *reg, u32 regno,
11130 struct bpf_kfunc_call_arg_meta *meta,
11131 enum btf_field_type head_field_type,
11132 struct btf_field **head_field)
11133 {
11134 const char *head_type_name;
11135 struct btf_field *field;
11136 struct btf_record *rec;
11137 u32 head_off;
11138
11139 if (meta->btf != btf_vmlinux) {
11140 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11141 return -EFAULT;
11142 }
11143
11144 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11145 return -EFAULT;
11146
11147 head_type_name = btf_field_type_name(head_field_type);
11148 if (!tnum_is_const(reg->var_off)) {
11149 verbose(env,
11150 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11151 regno, head_type_name);
11152 return -EINVAL;
11153 }
11154
11155 rec = reg_btf_record(reg);
11156 head_off = reg->off + reg->var_off.value;
11157 field = btf_record_find(rec, head_off, head_field_type);
11158 if (!field) {
11159 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11160 return -EINVAL;
11161 }
11162
11163 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11164 if (check_reg_allocation_locked(env, reg)) {
11165 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11166 rec->spin_lock_off, head_type_name);
11167 return -EINVAL;
11168 }
11169
11170 if (*head_field) {
11171 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11172 return -EFAULT;
11173 }
11174 *head_field = field;
11175 return 0;
11176 }
11177
process_kf_arg_ptr_to_list_head(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11178 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11179 struct bpf_reg_state *reg, u32 regno,
11180 struct bpf_kfunc_call_arg_meta *meta)
11181 {
11182 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11183 &meta->arg_list_head.field);
11184 }
11185
process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11186 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11187 struct bpf_reg_state *reg, u32 regno,
11188 struct bpf_kfunc_call_arg_meta *meta)
11189 {
11190 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11191 &meta->arg_rbtree_root.field);
11192 }
11193
11194 static int
__process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta,enum btf_field_type head_field_type,enum btf_field_type node_field_type,struct btf_field ** node_field)11195 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11196 struct bpf_reg_state *reg, u32 regno,
11197 struct bpf_kfunc_call_arg_meta *meta,
11198 enum btf_field_type head_field_type,
11199 enum btf_field_type node_field_type,
11200 struct btf_field **node_field)
11201 {
11202 const char *node_type_name;
11203 const struct btf_type *et, *t;
11204 struct btf_field *field;
11205 u32 node_off;
11206
11207 if (meta->btf != btf_vmlinux) {
11208 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11209 return -EFAULT;
11210 }
11211
11212 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11213 return -EFAULT;
11214
11215 node_type_name = btf_field_type_name(node_field_type);
11216 if (!tnum_is_const(reg->var_off)) {
11217 verbose(env,
11218 "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11219 regno, node_type_name);
11220 return -EINVAL;
11221 }
11222
11223 node_off = reg->off + reg->var_off.value;
11224 field = reg_find_field_offset(reg, node_off, node_field_type);
11225 if (!field || field->offset != node_off) {
11226 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11227 return -EINVAL;
11228 }
11229
11230 field = *node_field;
11231
11232 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11233 t = btf_type_by_id(reg->btf, reg->btf_id);
11234 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11235 field->graph_root.value_btf_id, true)) {
11236 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11237 "in struct %s, but arg is at offset=%d in struct %s\n",
11238 btf_field_type_name(head_field_type),
11239 btf_field_type_name(node_field_type),
11240 field->graph_root.node_offset,
11241 btf_name_by_offset(field->graph_root.btf, et->name_off),
11242 node_off, btf_name_by_offset(reg->btf, t->name_off));
11243 return -EINVAL;
11244 }
11245 meta->arg_btf = reg->btf;
11246 meta->arg_btf_id = reg->btf_id;
11247
11248 if (node_off != field->graph_root.node_offset) {
11249 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11250 node_off, btf_field_type_name(node_field_type),
11251 field->graph_root.node_offset,
11252 btf_name_by_offset(field->graph_root.btf, et->name_off));
11253 return -EINVAL;
11254 }
11255
11256 return 0;
11257 }
11258
process_kf_arg_ptr_to_list_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11259 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11260 struct bpf_reg_state *reg, u32 regno,
11261 struct bpf_kfunc_call_arg_meta *meta)
11262 {
11263 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11264 BPF_LIST_HEAD, BPF_LIST_NODE,
11265 &meta->arg_list_head.field);
11266 }
11267
process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,struct bpf_kfunc_call_arg_meta * meta)11268 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11269 struct bpf_reg_state *reg, u32 regno,
11270 struct bpf_kfunc_call_arg_meta *meta)
11271 {
11272 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11273 BPF_RB_ROOT, BPF_RB_NODE,
11274 &meta->arg_rbtree_root.field);
11275 }
11276
check_kfunc_args(struct bpf_verifier_env * env,struct bpf_kfunc_call_arg_meta * meta,int insn_idx)11277 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11278 int insn_idx)
11279 {
11280 const char *func_name = meta->func_name, *ref_tname;
11281 const struct btf *btf = meta->btf;
11282 const struct btf_param *args;
11283 struct btf_record *rec;
11284 u32 i, nargs;
11285 int ret;
11286
11287 args = (const struct btf_param *)(meta->func_proto + 1);
11288 nargs = btf_type_vlen(meta->func_proto);
11289 if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11290 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11291 MAX_BPF_FUNC_REG_ARGS);
11292 return -EINVAL;
11293 }
11294
11295 /* Check that BTF function arguments match actual types that the
11296 * verifier sees.
11297 */
11298 for (i = 0; i < nargs; i++) {
11299 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1];
11300 const struct btf_type *t, *ref_t, *resolve_ret;
11301 enum bpf_arg_type arg_type = ARG_DONTCARE;
11302 u32 regno = i + 1, ref_id, type_size;
11303 bool is_ret_buf_sz = false;
11304 int kf_arg_type;
11305
11306 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11307
11308 if (is_kfunc_arg_ignore(btf, &args[i]))
11309 continue;
11310
11311 if (btf_type_is_scalar(t)) {
11312 if (reg->type != SCALAR_VALUE) {
11313 verbose(env, "R%d is not a scalar\n", regno);
11314 return -EINVAL;
11315 }
11316
11317 if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11318 if (meta->arg_constant.found) {
11319 verbose(env, "verifier internal error: only one constant argument permitted\n");
11320 return -EFAULT;
11321 }
11322 if (!tnum_is_const(reg->var_off)) {
11323 verbose(env, "R%d must be a known constant\n", regno);
11324 return -EINVAL;
11325 }
11326 ret = mark_chain_precision(env, regno);
11327 if (ret < 0)
11328 return ret;
11329 meta->arg_constant.found = true;
11330 meta->arg_constant.value = reg->var_off.value;
11331 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11332 meta->r0_rdonly = true;
11333 is_ret_buf_sz = true;
11334 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11335 is_ret_buf_sz = true;
11336 }
11337
11338 if (is_ret_buf_sz) {
11339 if (meta->r0_size) {
11340 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11341 return -EINVAL;
11342 }
11343
11344 if (!tnum_is_const(reg->var_off)) {
11345 verbose(env, "R%d is not a const\n", regno);
11346 return -EINVAL;
11347 }
11348
11349 meta->r0_size = reg->var_off.value;
11350 ret = mark_chain_precision(env, regno);
11351 if (ret)
11352 return ret;
11353 }
11354 continue;
11355 }
11356
11357 if (!btf_type_is_ptr(t)) {
11358 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11359 return -EINVAL;
11360 }
11361
11362 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11363 (register_is_null(reg) || type_may_be_null(reg->type))) {
11364 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11365 return -EACCES;
11366 }
11367
11368 if (reg->ref_obj_id) {
11369 if (is_kfunc_release(meta) && meta->ref_obj_id) {
11370 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11371 regno, reg->ref_obj_id,
11372 meta->ref_obj_id);
11373 return -EFAULT;
11374 }
11375 meta->ref_obj_id = reg->ref_obj_id;
11376 if (is_kfunc_release(meta))
11377 meta->release_regno = regno;
11378 }
11379
11380 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11381 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11382
11383 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11384 if (kf_arg_type < 0)
11385 return kf_arg_type;
11386
11387 switch (kf_arg_type) {
11388 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11389 case KF_ARG_PTR_TO_BTF_ID:
11390 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11391 break;
11392
11393 if (!is_trusted_reg(reg)) {
11394 if (!is_kfunc_rcu(meta)) {
11395 verbose(env, "R%d must be referenced or trusted\n", regno);
11396 return -EINVAL;
11397 }
11398 if (!is_rcu_reg(reg)) {
11399 verbose(env, "R%d must be a rcu pointer\n", regno);
11400 return -EINVAL;
11401 }
11402 }
11403
11404 fallthrough;
11405 case KF_ARG_PTR_TO_CTX:
11406 /* Trusted arguments have the same offset checks as release arguments */
11407 arg_type |= OBJ_RELEASE;
11408 break;
11409 case KF_ARG_PTR_TO_DYNPTR:
11410 case KF_ARG_PTR_TO_ITER:
11411 case KF_ARG_PTR_TO_LIST_HEAD:
11412 case KF_ARG_PTR_TO_LIST_NODE:
11413 case KF_ARG_PTR_TO_RB_ROOT:
11414 case KF_ARG_PTR_TO_RB_NODE:
11415 case KF_ARG_PTR_TO_MEM:
11416 case KF_ARG_PTR_TO_MEM_SIZE:
11417 case KF_ARG_PTR_TO_CALLBACK:
11418 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11419 /* Trusted by default */
11420 break;
11421 default:
11422 WARN_ON_ONCE(1);
11423 return -EFAULT;
11424 }
11425
11426 if (is_kfunc_release(meta) && reg->ref_obj_id)
11427 arg_type |= OBJ_RELEASE;
11428 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11429 if (ret < 0)
11430 return ret;
11431
11432 switch (kf_arg_type) {
11433 case KF_ARG_PTR_TO_CTX:
11434 if (reg->type != PTR_TO_CTX) {
11435 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11436 return -EINVAL;
11437 }
11438
11439 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11440 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11441 if (ret < 0)
11442 return -EINVAL;
11443 meta->ret_btf_id = ret;
11444 }
11445 break;
11446 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11447 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11448 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11449 return -EINVAL;
11450 }
11451 if (!reg->ref_obj_id) {
11452 verbose(env, "allocated object must be referenced\n");
11453 return -EINVAL;
11454 }
11455 if (meta->btf == btf_vmlinux &&
11456 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11457 meta->arg_btf = reg->btf;
11458 meta->arg_btf_id = reg->btf_id;
11459 }
11460 break;
11461 case KF_ARG_PTR_TO_DYNPTR:
11462 {
11463 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11464 int clone_ref_obj_id = 0;
11465
11466 if (reg->type != PTR_TO_STACK &&
11467 reg->type != CONST_PTR_TO_DYNPTR) {
11468 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11469 return -EINVAL;
11470 }
11471
11472 if (reg->type == CONST_PTR_TO_DYNPTR)
11473 dynptr_arg_type |= MEM_RDONLY;
11474
11475 if (is_kfunc_arg_uninit(btf, &args[i]))
11476 dynptr_arg_type |= MEM_UNINIT;
11477
11478 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11479 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11480 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11481 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11482 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11483 (dynptr_arg_type & MEM_UNINIT)) {
11484 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11485
11486 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11487 verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11488 return -EFAULT;
11489 }
11490
11491 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11492 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11493 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11494 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11495 return -EFAULT;
11496 }
11497 }
11498
11499 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11500 if (ret < 0)
11501 return ret;
11502
11503 if (!(dynptr_arg_type & MEM_UNINIT)) {
11504 int id = dynptr_id(env, reg);
11505
11506 if (id < 0) {
11507 verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11508 return id;
11509 }
11510 meta->initialized_dynptr.id = id;
11511 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11512 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11513 }
11514
11515 break;
11516 }
11517 case KF_ARG_PTR_TO_ITER:
11518 ret = process_iter_arg(env, regno, insn_idx, meta);
11519 if (ret < 0)
11520 return ret;
11521 break;
11522 case KF_ARG_PTR_TO_LIST_HEAD:
11523 if (reg->type != PTR_TO_MAP_VALUE &&
11524 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11525 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11526 return -EINVAL;
11527 }
11528 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11529 verbose(env, "allocated object must be referenced\n");
11530 return -EINVAL;
11531 }
11532 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11533 if (ret < 0)
11534 return ret;
11535 break;
11536 case KF_ARG_PTR_TO_RB_ROOT:
11537 if (reg->type != PTR_TO_MAP_VALUE &&
11538 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11539 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11540 return -EINVAL;
11541 }
11542 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11543 verbose(env, "allocated object must be referenced\n");
11544 return -EINVAL;
11545 }
11546 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11547 if (ret < 0)
11548 return ret;
11549 break;
11550 case KF_ARG_PTR_TO_LIST_NODE:
11551 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11552 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11553 return -EINVAL;
11554 }
11555 if (!reg->ref_obj_id) {
11556 verbose(env, "allocated object must be referenced\n");
11557 return -EINVAL;
11558 }
11559 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11560 if (ret < 0)
11561 return ret;
11562 break;
11563 case KF_ARG_PTR_TO_RB_NODE:
11564 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11565 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11566 verbose(env, "rbtree_remove node input must be non-owning ref\n");
11567 return -EINVAL;
11568 }
11569 if (in_rbtree_lock_required_cb(env)) {
11570 verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11571 return -EINVAL;
11572 }
11573 } else {
11574 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11575 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11576 return -EINVAL;
11577 }
11578 if (!reg->ref_obj_id) {
11579 verbose(env, "allocated object must be referenced\n");
11580 return -EINVAL;
11581 }
11582 }
11583
11584 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11585 if (ret < 0)
11586 return ret;
11587 break;
11588 case KF_ARG_PTR_TO_BTF_ID:
11589 /* Only base_type is checked, further checks are done here */
11590 if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11591 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11592 !reg2btf_ids[base_type(reg->type)]) {
11593 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11594 verbose(env, "expected %s or socket\n",
11595 reg_type_str(env, base_type(reg->type) |
11596 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11597 return -EINVAL;
11598 }
11599 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11600 if (ret < 0)
11601 return ret;
11602 break;
11603 case KF_ARG_PTR_TO_MEM:
11604 resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11605 if (IS_ERR(resolve_ret)) {
11606 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11607 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11608 return -EINVAL;
11609 }
11610 ret = check_mem_reg(env, reg, regno, type_size);
11611 if (ret < 0)
11612 return ret;
11613 break;
11614 case KF_ARG_PTR_TO_MEM_SIZE:
11615 {
11616 struct bpf_reg_state *buff_reg = ®s[regno];
11617 const struct btf_param *buff_arg = &args[i];
11618 struct bpf_reg_state *size_reg = ®s[regno + 1];
11619 const struct btf_param *size_arg = &args[i + 1];
11620
11621 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11622 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11623 if (ret < 0) {
11624 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11625 return ret;
11626 }
11627 }
11628
11629 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11630 if (meta->arg_constant.found) {
11631 verbose(env, "verifier internal error: only one constant argument permitted\n");
11632 return -EFAULT;
11633 }
11634 if (!tnum_is_const(size_reg->var_off)) {
11635 verbose(env, "R%d must be a known constant\n", regno + 1);
11636 return -EINVAL;
11637 }
11638 meta->arg_constant.found = true;
11639 meta->arg_constant.value = size_reg->var_off.value;
11640 }
11641
11642 /* Skip next '__sz' or '__szk' argument */
11643 i++;
11644 break;
11645 }
11646 case KF_ARG_PTR_TO_CALLBACK:
11647 if (reg->type != PTR_TO_FUNC) {
11648 verbose(env, "arg%d expected pointer to func\n", i);
11649 return -EINVAL;
11650 }
11651 meta->subprogno = reg->subprogno;
11652 break;
11653 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11654 if (!type_is_ptr_alloc_obj(reg->type)) {
11655 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11656 return -EINVAL;
11657 }
11658 if (!type_is_non_owning_ref(reg->type))
11659 meta->arg_owning_ref = true;
11660
11661 rec = reg_btf_record(reg);
11662 if (!rec) {
11663 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11664 return -EFAULT;
11665 }
11666
11667 if (rec->refcount_off < 0) {
11668 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11669 return -EINVAL;
11670 }
11671
11672 meta->arg_btf = reg->btf;
11673 meta->arg_btf_id = reg->btf_id;
11674 break;
11675 }
11676 }
11677
11678 if (is_kfunc_release(meta) && !meta->release_regno) {
11679 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11680 func_name);
11681 return -EINVAL;
11682 }
11683
11684 return 0;
11685 }
11686
fetch_kfunc_meta(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_kfunc_call_arg_meta * meta,const char ** kfunc_name)11687 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11688 struct bpf_insn *insn,
11689 struct bpf_kfunc_call_arg_meta *meta,
11690 const char **kfunc_name)
11691 {
11692 const struct btf_type *func, *func_proto;
11693 u32 func_id, *kfunc_flags;
11694 const char *func_name;
11695 struct btf *desc_btf;
11696
11697 if (kfunc_name)
11698 *kfunc_name = NULL;
11699
11700 if (!insn->imm)
11701 return -EINVAL;
11702
11703 desc_btf = find_kfunc_desc_btf(env, insn->off);
11704 if (IS_ERR(desc_btf))
11705 return PTR_ERR(desc_btf);
11706
11707 func_id = insn->imm;
11708 func = btf_type_by_id(desc_btf, func_id);
11709 func_name = btf_name_by_offset(desc_btf, func->name_off);
11710 if (kfunc_name)
11711 *kfunc_name = func_name;
11712 func_proto = btf_type_by_id(desc_btf, func->type);
11713
11714 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11715 if (!kfunc_flags) {
11716 return -EACCES;
11717 }
11718
11719 memset(meta, 0, sizeof(*meta));
11720 meta->btf = desc_btf;
11721 meta->func_id = func_id;
11722 meta->kfunc_flags = *kfunc_flags;
11723 meta->func_proto = func_proto;
11724 meta->func_name = func_name;
11725
11726 return 0;
11727 }
11728
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)11729 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11730 int *insn_idx_p)
11731 {
11732 const struct btf_type *t, *ptr_type;
11733 u32 i, nargs, ptr_type_id, release_ref_obj_id;
11734 struct bpf_reg_state *regs = cur_regs(env);
11735 const char *func_name, *ptr_type_name;
11736 bool sleepable, rcu_lock, rcu_unlock;
11737 struct bpf_kfunc_call_arg_meta meta;
11738 struct bpf_insn_aux_data *insn_aux;
11739 int err, insn_idx = *insn_idx_p;
11740 const struct btf_param *args;
11741 const struct btf_type *ret_t;
11742 struct btf *desc_btf;
11743
11744 /* skip for now, but return error when we find this in fixup_kfunc_call */
11745 if (!insn->imm)
11746 return 0;
11747
11748 err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11749 if (err == -EACCES && func_name)
11750 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11751 if (err)
11752 return err;
11753 desc_btf = meta.btf;
11754 insn_aux = &env->insn_aux_data[insn_idx];
11755
11756 insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11757
11758 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11759 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11760 return -EACCES;
11761 }
11762
11763 sleepable = is_kfunc_sleepable(&meta);
11764 if (sleepable && !env->prog->aux->sleepable) {
11765 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11766 return -EACCES;
11767 }
11768
11769 /* Check the arguments */
11770 err = check_kfunc_args(env, &meta, insn_idx);
11771 if (err < 0)
11772 return err;
11773
11774 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11775 err = push_callback_call(env, insn, insn_idx, meta.subprogno,
11776 set_rbtree_add_callback_state);
11777 if (err) {
11778 verbose(env, "kfunc %s#%d failed callback verification\n",
11779 func_name, meta.func_id);
11780 return err;
11781 }
11782 }
11783
11784 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11785 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11786
11787 if (env->cur_state->active_rcu_lock) {
11788 struct bpf_func_state *state;
11789 struct bpf_reg_state *reg;
11790
11791 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11792 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11793 return -EACCES;
11794 }
11795
11796 if (rcu_lock) {
11797 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11798 return -EINVAL;
11799 } else if (rcu_unlock) {
11800 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11801 if (reg->type & MEM_RCU) {
11802 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11803 reg->type |= PTR_UNTRUSTED;
11804 }
11805 }));
11806 env->cur_state->active_rcu_lock = false;
11807 } else if (sleepable) {
11808 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11809 return -EACCES;
11810 }
11811 } else if (rcu_lock) {
11812 env->cur_state->active_rcu_lock = true;
11813 } else if (rcu_unlock) {
11814 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11815 return -EINVAL;
11816 }
11817
11818 /* In case of release function, we get register number of refcounted
11819 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11820 */
11821 if (meta.release_regno) {
11822 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11823 if (err) {
11824 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11825 func_name, meta.func_id);
11826 return err;
11827 }
11828 }
11829
11830 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11831 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11832 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11833 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11834 insn_aux->insert_off = regs[BPF_REG_2].off;
11835 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11836 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11837 if (err) {
11838 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11839 func_name, meta.func_id);
11840 return err;
11841 }
11842
11843 err = release_reference(env, release_ref_obj_id);
11844 if (err) {
11845 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11846 func_name, meta.func_id);
11847 return err;
11848 }
11849 }
11850
11851 for (i = 0; i < CALLER_SAVED_REGS; i++)
11852 mark_reg_not_init(env, regs, caller_saved[i]);
11853
11854 /* Check return type */
11855 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11856
11857 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11858 /* Only exception is bpf_obj_new_impl */
11859 if (meta.btf != btf_vmlinux ||
11860 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11861 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11862 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11863 return -EINVAL;
11864 }
11865 }
11866
11867 if (btf_type_is_scalar(t)) {
11868 mark_reg_unknown(env, regs, BPF_REG_0);
11869 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11870 } else if (btf_type_is_ptr(t)) {
11871 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11872
11873 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11874 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11875 struct btf *ret_btf;
11876 u32 ret_btf_id;
11877
11878 if (unlikely(!bpf_global_ma_set))
11879 return -ENOMEM;
11880
11881 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11882 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11883 return -EINVAL;
11884 }
11885
11886 ret_btf = env->prog->aux->btf;
11887 ret_btf_id = meta.arg_constant.value;
11888
11889 /* This may be NULL due to user not supplying a BTF */
11890 if (!ret_btf) {
11891 verbose(env, "bpf_obj_new requires prog BTF\n");
11892 return -EINVAL;
11893 }
11894
11895 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11896 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11897 verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11898 return -EINVAL;
11899 }
11900
11901 mark_reg_known_zero(env, regs, BPF_REG_0);
11902 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11903 regs[BPF_REG_0].btf = ret_btf;
11904 regs[BPF_REG_0].btf_id = ret_btf_id;
11905
11906 insn_aux->obj_new_size = ret_t->size;
11907 insn_aux->kptr_struct_meta =
11908 btf_find_struct_meta(ret_btf, ret_btf_id);
11909 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11910 mark_reg_known_zero(env, regs, BPF_REG_0);
11911 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11912 regs[BPF_REG_0].btf = meta.arg_btf;
11913 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11914
11915 insn_aux->kptr_struct_meta =
11916 btf_find_struct_meta(meta.arg_btf,
11917 meta.arg_btf_id);
11918 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11919 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11920 struct btf_field *field = meta.arg_list_head.field;
11921
11922 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11923 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11924 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11925 struct btf_field *field = meta.arg_rbtree_root.field;
11926
11927 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11928 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11929 mark_reg_known_zero(env, regs, BPF_REG_0);
11930 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11931 regs[BPF_REG_0].btf = desc_btf;
11932 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11933 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11934 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11935 if (!ret_t || !btf_type_is_struct(ret_t)) {
11936 verbose(env,
11937 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11938 return -EINVAL;
11939 }
11940
11941 mark_reg_known_zero(env, regs, BPF_REG_0);
11942 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11943 regs[BPF_REG_0].btf = desc_btf;
11944 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11945 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11946 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11947 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11948
11949 mark_reg_known_zero(env, regs, BPF_REG_0);
11950
11951 if (!meta.arg_constant.found) {
11952 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11953 return -EFAULT;
11954 }
11955
11956 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11957
11958 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11959 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11960
11961 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11962 regs[BPF_REG_0].type |= MEM_RDONLY;
11963 } else {
11964 /* this will set env->seen_direct_write to true */
11965 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11966 verbose(env, "the prog does not allow writes to packet data\n");
11967 return -EINVAL;
11968 }
11969 }
11970
11971 if (!meta.initialized_dynptr.id) {
11972 verbose(env, "verifier internal error: no dynptr id\n");
11973 return -EFAULT;
11974 }
11975 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11976
11977 /* we don't need to set BPF_REG_0's ref obj id
11978 * because packet slices are not refcounted (see
11979 * dynptr_type_refcounted)
11980 */
11981 } else {
11982 verbose(env, "kernel function %s unhandled dynamic return type\n",
11983 meta.func_name);
11984 return -EFAULT;
11985 }
11986 } else if (!__btf_type_is_struct(ptr_type)) {
11987 if (!meta.r0_size) {
11988 __u32 sz;
11989
11990 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11991 meta.r0_size = sz;
11992 meta.r0_rdonly = true;
11993 }
11994 }
11995 if (!meta.r0_size) {
11996 ptr_type_name = btf_name_by_offset(desc_btf,
11997 ptr_type->name_off);
11998 verbose(env,
11999 "kernel function %s returns pointer type %s %s is not supported\n",
12000 func_name,
12001 btf_type_str(ptr_type),
12002 ptr_type_name);
12003 return -EINVAL;
12004 }
12005
12006 mark_reg_known_zero(env, regs, BPF_REG_0);
12007 regs[BPF_REG_0].type = PTR_TO_MEM;
12008 regs[BPF_REG_0].mem_size = meta.r0_size;
12009
12010 if (meta.r0_rdonly)
12011 regs[BPF_REG_0].type |= MEM_RDONLY;
12012
12013 /* Ensures we don't access the memory after a release_reference() */
12014 if (meta.ref_obj_id)
12015 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12016 } else {
12017 mark_reg_known_zero(env, regs, BPF_REG_0);
12018 regs[BPF_REG_0].btf = desc_btf;
12019 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12020 regs[BPF_REG_0].btf_id = ptr_type_id;
12021 }
12022
12023 if (is_kfunc_ret_null(&meta)) {
12024 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12025 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12026 regs[BPF_REG_0].id = ++env->id_gen;
12027 }
12028 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12029 if (is_kfunc_acquire(&meta)) {
12030 int id = acquire_reference_state(env, insn_idx);
12031
12032 if (id < 0)
12033 return id;
12034 if (is_kfunc_ret_null(&meta))
12035 regs[BPF_REG_0].id = id;
12036 regs[BPF_REG_0].ref_obj_id = id;
12037 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12038 ref_set_non_owning(env, ®s[BPF_REG_0]);
12039 }
12040
12041 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id)
12042 regs[BPF_REG_0].id = ++env->id_gen;
12043 } else if (btf_type_is_void(t)) {
12044 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12045 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
12046 insn_aux->kptr_struct_meta =
12047 btf_find_struct_meta(meta.arg_btf,
12048 meta.arg_btf_id);
12049 }
12050 }
12051 }
12052
12053 nargs = btf_type_vlen(meta.func_proto);
12054 args = (const struct btf_param *)(meta.func_proto + 1);
12055 for (i = 0; i < nargs; i++) {
12056 u32 regno = i + 1;
12057
12058 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12059 if (btf_type_is_ptr(t))
12060 mark_btf_func_reg_size(env, regno, sizeof(void *));
12061 else
12062 /* scalar. ensured by btf_check_kfunc_arg_match() */
12063 mark_btf_func_reg_size(env, regno, t->size);
12064 }
12065
12066 if (is_iter_next_kfunc(&meta)) {
12067 err = process_iter_next_call(env, insn_idx, &meta);
12068 if (err)
12069 return err;
12070 }
12071
12072 return 0;
12073 }
12074
signed_add_overflows(s64 a,s64 b)12075 static bool signed_add_overflows(s64 a, s64 b)
12076 {
12077 /* Do the add in u64, where overflow is well-defined */
12078 s64 res = (s64)((u64)a + (u64)b);
12079
12080 if (b < 0)
12081 return res > a;
12082 return res < a;
12083 }
12084
signed_add32_overflows(s32 a,s32 b)12085 static bool signed_add32_overflows(s32 a, s32 b)
12086 {
12087 /* Do the add in u32, where overflow is well-defined */
12088 s32 res = (s32)((u32)a + (u32)b);
12089
12090 if (b < 0)
12091 return res > a;
12092 return res < a;
12093 }
12094
signed_sub_overflows(s64 a,s64 b)12095 static bool signed_sub_overflows(s64 a, s64 b)
12096 {
12097 /* Do the sub in u64, where overflow is well-defined */
12098 s64 res = (s64)((u64)a - (u64)b);
12099
12100 if (b < 0)
12101 return res < a;
12102 return res > a;
12103 }
12104
signed_sub32_overflows(s32 a,s32 b)12105 static bool signed_sub32_overflows(s32 a, s32 b)
12106 {
12107 /* Do the sub in u32, where overflow is well-defined */
12108 s32 res = (s32)((u32)a - (u32)b);
12109
12110 if (b < 0)
12111 return res < a;
12112 return res > a;
12113 }
12114
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)12115 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12116 const struct bpf_reg_state *reg,
12117 enum bpf_reg_type type)
12118 {
12119 bool known = tnum_is_const(reg->var_off);
12120 s64 val = reg->var_off.value;
12121 s64 smin = reg->smin_value;
12122
12123 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12124 verbose(env, "math between %s pointer and %lld is not allowed\n",
12125 reg_type_str(env, type), val);
12126 return false;
12127 }
12128
12129 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12130 verbose(env, "%s pointer offset %d is not allowed\n",
12131 reg_type_str(env, type), reg->off);
12132 return false;
12133 }
12134
12135 if (smin == S64_MIN) {
12136 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12137 reg_type_str(env, type));
12138 return false;
12139 }
12140
12141 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12142 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12143 smin, reg_type_str(env, type));
12144 return false;
12145 }
12146
12147 return true;
12148 }
12149
12150 enum {
12151 REASON_BOUNDS = -1,
12152 REASON_TYPE = -2,
12153 REASON_PATHS = -3,
12154 REASON_LIMIT = -4,
12155 REASON_STACK = -5,
12156 };
12157
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)12158 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12159 u32 *alu_limit, bool mask_to_left)
12160 {
12161 u32 max = 0, ptr_limit = 0;
12162
12163 switch (ptr_reg->type) {
12164 case PTR_TO_STACK:
12165 /* Offset 0 is out-of-bounds, but acceptable start for the
12166 * left direction, see BPF_REG_FP. Also, unknown scalar
12167 * offset where we would need to deal with min/max bounds is
12168 * currently prohibited for unprivileged.
12169 */
12170 max = MAX_BPF_STACK + mask_to_left;
12171 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12172 break;
12173 case PTR_TO_MAP_VALUE:
12174 max = ptr_reg->map_ptr->value_size;
12175 ptr_limit = (mask_to_left ?
12176 ptr_reg->smin_value :
12177 ptr_reg->umax_value) + ptr_reg->off;
12178 break;
12179 default:
12180 return REASON_TYPE;
12181 }
12182
12183 if (ptr_limit >= max)
12184 return REASON_LIMIT;
12185 *alu_limit = ptr_limit;
12186 return 0;
12187 }
12188
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)12189 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12190 const struct bpf_insn *insn)
12191 {
12192 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12193 }
12194
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)12195 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12196 u32 alu_state, u32 alu_limit)
12197 {
12198 /* If we arrived here from different branches with different
12199 * state or limits to sanitize, then this won't work.
12200 */
12201 if (aux->alu_state &&
12202 (aux->alu_state != alu_state ||
12203 aux->alu_limit != alu_limit))
12204 return REASON_PATHS;
12205
12206 /* Corresponding fixup done in do_misc_fixups(). */
12207 aux->alu_state = alu_state;
12208 aux->alu_limit = alu_limit;
12209 return 0;
12210 }
12211
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)12212 static int sanitize_val_alu(struct bpf_verifier_env *env,
12213 struct bpf_insn *insn)
12214 {
12215 struct bpf_insn_aux_data *aux = cur_aux(env);
12216
12217 if (can_skip_alu_sanitation(env, insn))
12218 return 0;
12219
12220 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12221 }
12222
sanitize_needed(u8 opcode)12223 static bool sanitize_needed(u8 opcode)
12224 {
12225 return opcode == BPF_ADD || opcode == BPF_SUB;
12226 }
12227
12228 struct bpf_sanitize_info {
12229 struct bpf_insn_aux_data aux;
12230 bool mask_to_left;
12231 };
12232
12233 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)12234 sanitize_speculative_path(struct bpf_verifier_env *env,
12235 const struct bpf_insn *insn,
12236 u32 next_idx, u32 curr_idx)
12237 {
12238 struct bpf_verifier_state *branch;
12239 struct bpf_reg_state *regs;
12240
12241 branch = push_stack(env, next_idx, curr_idx, true);
12242 if (branch && insn) {
12243 regs = branch->frame[branch->curframe]->regs;
12244 if (BPF_SRC(insn->code) == BPF_K) {
12245 mark_reg_unknown(env, regs, insn->dst_reg);
12246 } else if (BPF_SRC(insn->code) == BPF_X) {
12247 mark_reg_unknown(env, regs, insn->dst_reg);
12248 mark_reg_unknown(env, regs, insn->src_reg);
12249 }
12250 }
12251 return branch;
12252 }
12253
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg,struct bpf_reg_state * dst_reg,struct bpf_sanitize_info * info,const bool commit_window)12254 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12255 struct bpf_insn *insn,
12256 const struct bpf_reg_state *ptr_reg,
12257 const struct bpf_reg_state *off_reg,
12258 struct bpf_reg_state *dst_reg,
12259 struct bpf_sanitize_info *info,
12260 const bool commit_window)
12261 {
12262 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12263 struct bpf_verifier_state *vstate = env->cur_state;
12264 bool off_is_imm = tnum_is_const(off_reg->var_off);
12265 bool off_is_neg = off_reg->smin_value < 0;
12266 bool ptr_is_dst_reg = ptr_reg == dst_reg;
12267 u8 opcode = BPF_OP(insn->code);
12268 u32 alu_state, alu_limit;
12269 struct bpf_reg_state tmp;
12270 bool ret;
12271 int err;
12272
12273 if (can_skip_alu_sanitation(env, insn))
12274 return 0;
12275
12276 /* We already marked aux for masking from non-speculative
12277 * paths, thus we got here in the first place. We only care
12278 * to explore bad access from here.
12279 */
12280 if (vstate->speculative)
12281 goto do_sim;
12282
12283 if (!commit_window) {
12284 if (!tnum_is_const(off_reg->var_off) &&
12285 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12286 return REASON_BOUNDS;
12287
12288 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
12289 (opcode == BPF_SUB && !off_is_neg);
12290 }
12291
12292 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12293 if (err < 0)
12294 return err;
12295
12296 if (commit_window) {
12297 /* In commit phase we narrow the masking window based on
12298 * the observed pointer move after the simulated operation.
12299 */
12300 alu_state = info->aux.alu_state;
12301 alu_limit = abs(info->aux.alu_limit - alu_limit);
12302 } else {
12303 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12304 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12305 alu_state |= ptr_is_dst_reg ?
12306 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12307
12308 /* Limit pruning on unknown scalars to enable deep search for
12309 * potential masking differences from other program paths.
12310 */
12311 if (!off_is_imm)
12312 env->explore_alu_limits = true;
12313 }
12314
12315 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12316 if (err < 0)
12317 return err;
12318 do_sim:
12319 /* If we're in commit phase, we're done here given we already
12320 * pushed the truncated dst_reg into the speculative verification
12321 * stack.
12322 *
12323 * Also, when register is a known constant, we rewrite register-based
12324 * operation to immediate-based, and thus do not need masking (and as
12325 * a consequence, do not need to simulate the zero-truncation either).
12326 */
12327 if (commit_window || off_is_imm)
12328 return 0;
12329
12330 /* Simulate and find potential out-of-bounds access under
12331 * speculative execution from truncation as a result of
12332 * masking when off was not within expected range. If off
12333 * sits in dst, then we temporarily need to move ptr there
12334 * to simulate dst (== 0) +/-= ptr. Needed, for example,
12335 * for cases where we use K-based arithmetic in one direction
12336 * and truncated reg-based in the other in order to explore
12337 * bad access.
12338 */
12339 if (!ptr_is_dst_reg) {
12340 tmp = *dst_reg;
12341 copy_register_state(dst_reg, ptr_reg);
12342 }
12343 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12344 env->insn_idx);
12345 if (!ptr_is_dst_reg && ret)
12346 *dst_reg = tmp;
12347 return !ret ? REASON_STACK : 0;
12348 }
12349
sanitize_mark_insn_seen(struct bpf_verifier_env * env)12350 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12351 {
12352 struct bpf_verifier_state *vstate = env->cur_state;
12353
12354 /* If we simulate paths under speculation, we don't update the
12355 * insn as 'seen' such that when we verify unreachable paths in
12356 * the non-speculative domain, sanitize_dead_code() can still
12357 * rewrite/sanitize them.
12358 */
12359 if (!vstate->speculative)
12360 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12361 }
12362
sanitize_err(struct bpf_verifier_env * env,const struct bpf_insn * insn,int reason,const struct bpf_reg_state * off_reg,const struct bpf_reg_state * dst_reg)12363 static int sanitize_err(struct bpf_verifier_env *env,
12364 const struct bpf_insn *insn, int reason,
12365 const struct bpf_reg_state *off_reg,
12366 const struct bpf_reg_state *dst_reg)
12367 {
12368 static const char *err = "pointer arithmetic with it prohibited for !root";
12369 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12370 u32 dst = insn->dst_reg, src = insn->src_reg;
12371
12372 switch (reason) {
12373 case REASON_BOUNDS:
12374 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12375 off_reg == dst_reg ? dst : src, err);
12376 break;
12377 case REASON_TYPE:
12378 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12379 off_reg == dst_reg ? src : dst, err);
12380 break;
12381 case REASON_PATHS:
12382 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12383 dst, op, err);
12384 break;
12385 case REASON_LIMIT:
12386 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12387 dst, op, err);
12388 break;
12389 case REASON_STACK:
12390 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12391 dst, err);
12392 break;
12393 default:
12394 verbose(env, "verifier internal error: unknown reason (%d)\n",
12395 reason);
12396 break;
12397 }
12398
12399 return -EACCES;
12400 }
12401
12402 /* check that stack access falls within stack limits and that 'reg' doesn't
12403 * have a variable offset.
12404 *
12405 * Variable offset is prohibited for unprivileged mode for simplicity since it
12406 * requires corresponding support in Spectre masking for stack ALU. See also
12407 * retrieve_ptr_limit().
12408 *
12409 *
12410 * 'off' includes 'reg->off'.
12411 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)12412 static int check_stack_access_for_ptr_arithmetic(
12413 struct bpf_verifier_env *env,
12414 int regno,
12415 const struct bpf_reg_state *reg,
12416 int off)
12417 {
12418 if (!tnum_is_const(reg->var_off)) {
12419 char tn_buf[48];
12420
12421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12422 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12423 regno, tn_buf, off);
12424 return -EACCES;
12425 }
12426
12427 if (off >= 0 || off < -MAX_BPF_STACK) {
12428 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12429 "prohibited for !root; off=%d\n", regno, off);
12430 return -EACCES;
12431 }
12432
12433 return 0;
12434 }
12435
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)12436 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12437 const struct bpf_insn *insn,
12438 const struct bpf_reg_state *dst_reg)
12439 {
12440 u32 dst = insn->dst_reg;
12441
12442 /* For unprivileged we require that resulting offset must be in bounds
12443 * in order to be able to sanitize access later on.
12444 */
12445 if (env->bypass_spec_v1)
12446 return 0;
12447
12448 switch (dst_reg->type) {
12449 case PTR_TO_STACK:
12450 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12451 dst_reg->off + dst_reg->var_off.value))
12452 return -EACCES;
12453 break;
12454 case PTR_TO_MAP_VALUE:
12455 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12456 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12457 "prohibited for !root\n", dst);
12458 return -EACCES;
12459 }
12460 break;
12461 default:
12462 break;
12463 }
12464
12465 return 0;
12466 }
12467
12468 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12469 * Caller should also handle BPF_MOV case separately.
12470 * If we return -EACCES, caller may want to try again treating pointer as a
12471 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
12472 */
adjust_ptr_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg)12473 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12474 struct bpf_insn *insn,
12475 const struct bpf_reg_state *ptr_reg,
12476 const struct bpf_reg_state *off_reg)
12477 {
12478 struct bpf_verifier_state *vstate = env->cur_state;
12479 struct bpf_func_state *state = vstate->frame[vstate->curframe];
12480 struct bpf_reg_state *regs = state->regs, *dst_reg;
12481 bool known = tnum_is_const(off_reg->var_off);
12482 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12483 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12484 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12485 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12486 struct bpf_sanitize_info info = {};
12487 u8 opcode = BPF_OP(insn->code);
12488 u32 dst = insn->dst_reg;
12489 int ret;
12490
12491 dst_reg = ®s[dst];
12492
12493 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12494 smin_val > smax_val || umin_val > umax_val) {
12495 /* Taint dst register if offset had invalid bounds derived from
12496 * e.g. dead branches.
12497 */
12498 __mark_reg_unknown(env, dst_reg);
12499 return 0;
12500 }
12501
12502 if (BPF_CLASS(insn->code) != BPF_ALU64) {
12503 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12504 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12505 __mark_reg_unknown(env, dst_reg);
12506 return 0;
12507 }
12508
12509 verbose(env,
12510 "R%d 32-bit pointer arithmetic prohibited\n",
12511 dst);
12512 return -EACCES;
12513 }
12514
12515 if (ptr_reg->type & PTR_MAYBE_NULL) {
12516 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12517 dst, reg_type_str(env, ptr_reg->type));
12518 return -EACCES;
12519 }
12520
12521 switch (base_type(ptr_reg->type)) {
12522 case PTR_TO_FLOW_KEYS:
12523 if (known)
12524 break;
12525 fallthrough;
12526 case CONST_PTR_TO_MAP:
12527 /* smin_val represents the known value */
12528 if (known && smin_val == 0 && opcode == BPF_ADD)
12529 break;
12530 fallthrough;
12531 case PTR_TO_PACKET_END:
12532 case PTR_TO_SOCKET:
12533 case PTR_TO_SOCK_COMMON:
12534 case PTR_TO_TCP_SOCK:
12535 case PTR_TO_XDP_SOCK:
12536 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12537 dst, reg_type_str(env, ptr_reg->type));
12538 return -EACCES;
12539 default:
12540 break;
12541 }
12542
12543 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12544 * The id may be overwritten later if we create a new variable offset.
12545 */
12546 dst_reg->type = ptr_reg->type;
12547 dst_reg->id = ptr_reg->id;
12548
12549 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12550 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12551 return -EINVAL;
12552
12553 /* pointer types do not carry 32-bit bounds at the moment. */
12554 __mark_reg32_unbounded(dst_reg);
12555
12556 if (sanitize_needed(opcode)) {
12557 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12558 &info, false);
12559 if (ret < 0)
12560 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12561 }
12562
12563 switch (opcode) {
12564 case BPF_ADD:
12565 /* We can take a fixed offset as long as it doesn't overflow
12566 * the s32 'off' field
12567 */
12568 if (known && (ptr_reg->off + smin_val ==
12569 (s64)(s32)(ptr_reg->off + smin_val))) {
12570 /* pointer += K. Accumulate it into fixed offset */
12571 dst_reg->smin_value = smin_ptr;
12572 dst_reg->smax_value = smax_ptr;
12573 dst_reg->umin_value = umin_ptr;
12574 dst_reg->umax_value = umax_ptr;
12575 dst_reg->var_off = ptr_reg->var_off;
12576 dst_reg->off = ptr_reg->off + smin_val;
12577 dst_reg->raw = ptr_reg->raw;
12578 break;
12579 }
12580 /* A new variable offset is created. Note that off_reg->off
12581 * == 0, since it's a scalar.
12582 * dst_reg gets the pointer type and since some positive
12583 * integer value was added to the pointer, give it a new 'id'
12584 * if it's a PTR_TO_PACKET.
12585 * this creates a new 'base' pointer, off_reg (variable) gets
12586 * added into the variable offset, and we copy the fixed offset
12587 * from ptr_reg.
12588 */
12589 if (signed_add_overflows(smin_ptr, smin_val) ||
12590 signed_add_overflows(smax_ptr, smax_val)) {
12591 dst_reg->smin_value = S64_MIN;
12592 dst_reg->smax_value = S64_MAX;
12593 } else {
12594 dst_reg->smin_value = smin_ptr + smin_val;
12595 dst_reg->smax_value = smax_ptr + smax_val;
12596 }
12597 if (umin_ptr + umin_val < umin_ptr ||
12598 umax_ptr + umax_val < umax_ptr) {
12599 dst_reg->umin_value = 0;
12600 dst_reg->umax_value = U64_MAX;
12601 } else {
12602 dst_reg->umin_value = umin_ptr + umin_val;
12603 dst_reg->umax_value = umax_ptr + umax_val;
12604 }
12605 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12606 dst_reg->off = ptr_reg->off;
12607 dst_reg->raw = ptr_reg->raw;
12608 if (reg_is_pkt_pointer(ptr_reg)) {
12609 dst_reg->id = ++env->id_gen;
12610 /* something was added to pkt_ptr, set range to zero */
12611 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12612 }
12613 break;
12614 case BPF_SUB:
12615 if (dst_reg == off_reg) {
12616 /* scalar -= pointer. Creates an unknown scalar */
12617 verbose(env, "R%d tried to subtract pointer from scalar\n",
12618 dst);
12619 return -EACCES;
12620 }
12621 /* We don't allow subtraction from FP, because (according to
12622 * test_verifier.c test "invalid fp arithmetic", JITs might not
12623 * be able to deal with it.
12624 */
12625 if (ptr_reg->type == PTR_TO_STACK) {
12626 verbose(env, "R%d subtraction from stack pointer prohibited\n",
12627 dst);
12628 return -EACCES;
12629 }
12630 if (known && (ptr_reg->off - smin_val ==
12631 (s64)(s32)(ptr_reg->off - smin_val))) {
12632 /* pointer -= K. Subtract it from fixed offset */
12633 dst_reg->smin_value = smin_ptr;
12634 dst_reg->smax_value = smax_ptr;
12635 dst_reg->umin_value = umin_ptr;
12636 dst_reg->umax_value = umax_ptr;
12637 dst_reg->var_off = ptr_reg->var_off;
12638 dst_reg->id = ptr_reg->id;
12639 dst_reg->off = ptr_reg->off - smin_val;
12640 dst_reg->raw = ptr_reg->raw;
12641 break;
12642 }
12643 /* A new variable offset is created. If the subtrahend is known
12644 * nonnegative, then any reg->range we had before is still good.
12645 */
12646 if (signed_sub_overflows(smin_ptr, smax_val) ||
12647 signed_sub_overflows(smax_ptr, smin_val)) {
12648 /* Overflow possible, we know nothing */
12649 dst_reg->smin_value = S64_MIN;
12650 dst_reg->smax_value = S64_MAX;
12651 } else {
12652 dst_reg->smin_value = smin_ptr - smax_val;
12653 dst_reg->smax_value = smax_ptr - smin_val;
12654 }
12655 if (umin_ptr < umax_val) {
12656 /* Overflow possible, we know nothing */
12657 dst_reg->umin_value = 0;
12658 dst_reg->umax_value = U64_MAX;
12659 } else {
12660 /* Cannot overflow (as long as bounds are consistent) */
12661 dst_reg->umin_value = umin_ptr - umax_val;
12662 dst_reg->umax_value = umax_ptr - umin_val;
12663 }
12664 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12665 dst_reg->off = ptr_reg->off;
12666 dst_reg->raw = ptr_reg->raw;
12667 if (reg_is_pkt_pointer(ptr_reg)) {
12668 dst_reg->id = ++env->id_gen;
12669 /* something was added to pkt_ptr, set range to zero */
12670 if (smin_val < 0)
12671 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12672 }
12673 break;
12674 case BPF_AND:
12675 case BPF_OR:
12676 case BPF_XOR:
12677 /* bitwise ops on pointers are troublesome, prohibit. */
12678 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12679 dst, bpf_alu_string[opcode >> 4]);
12680 return -EACCES;
12681 default:
12682 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12683 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12684 dst, bpf_alu_string[opcode >> 4]);
12685 return -EACCES;
12686 }
12687
12688 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12689 return -EINVAL;
12690 reg_bounds_sync(dst_reg);
12691 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12692 return -EACCES;
12693 if (sanitize_needed(opcode)) {
12694 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12695 &info, true);
12696 if (ret < 0)
12697 return sanitize_err(env, insn, ret, off_reg, dst_reg);
12698 }
12699
12700 return 0;
12701 }
12702
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12703 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12704 struct bpf_reg_state *src_reg)
12705 {
12706 s32 smin_val = src_reg->s32_min_value;
12707 s32 smax_val = src_reg->s32_max_value;
12708 u32 umin_val = src_reg->u32_min_value;
12709 u32 umax_val = src_reg->u32_max_value;
12710
12711 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12712 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12713 dst_reg->s32_min_value = S32_MIN;
12714 dst_reg->s32_max_value = S32_MAX;
12715 } else {
12716 dst_reg->s32_min_value += smin_val;
12717 dst_reg->s32_max_value += smax_val;
12718 }
12719 if (dst_reg->u32_min_value + umin_val < umin_val ||
12720 dst_reg->u32_max_value + umax_val < umax_val) {
12721 dst_reg->u32_min_value = 0;
12722 dst_reg->u32_max_value = U32_MAX;
12723 } else {
12724 dst_reg->u32_min_value += umin_val;
12725 dst_reg->u32_max_value += umax_val;
12726 }
12727 }
12728
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12729 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12730 struct bpf_reg_state *src_reg)
12731 {
12732 s64 smin_val = src_reg->smin_value;
12733 s64 smax_val = src_reg->smax_value;
12734 u64 umin_val = src_reg->umin_value;
12735 u64 umax_val = src_reg->umax_value;
12736
12737 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12738 signed_add_overflows(dst_reg->smax_value, smax_val)) {
12739 dst_reg->smin_value = S64_MIN;
12740 dst_reg->smax_value = S64_MAX;
12741 } else {
12742 dst_reg->smin_value += smin_val;
12743 dst_reg->smax_value += smax_val;
12744 }
12745 if (dst_reg->umin_value + umin_val < umin_val ||
12746 dst_reg->umax_value + umax_val < umax_val) {
12747 dst_reg->umin_value = 0;
12748 dst_reg->umax_value = U64_MAX;
12749 } else {
12750 dst_reg->umin_value += umin_val;
12751 dst_reg->umax_value += umax_val;
12752 }
12753 }
12754
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12755 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12756 struct bpf_reg_state *src_reg)
12757 {
12758 s32 smin_val = src_reg->s32_min_value;
12759 s32 smax_val = src_reg->s32_max_value;
12760 u32 umin_val = src_reg->u32_min_value;
12761 u32 umax_val = src_reg->u32_max_value;
12762
12763 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12764 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12765 /* Overflow possible, we know nothing */
12766 dst_reg->s32_min_value = S32_MIN;
12767 dst_reg->s32_max_value = S32_MAX;
12768 } else {
12769 dst_reg->s32_min_value -= smax_val;
12770 dst_reg->s32_max_value -= smin_val;
12771 }
12772 if (dst_reg->u32_min_value < umax_val) {
12773 /* Overflow possible, we know nothing */
12774 dst_reg->u32_min_value = 0;
12775 dst_reg->u32_max_value = U32_MAX;
12776 } else {
12777 /* Cannot overflow (as long as bounds are consistent) */
12778 dst_reg->u32_min_value -= umax_val;
12779 dst_reg->u32_max_value -= umin_val;
12780 }
12781 }
12782
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12783 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12784 struct bpf_reg_state *src_reg)
12785 {
12786 s64 smin_val = src_reg->smin_value;
12787 s64 smax_val = src_reg->smax_value;
12788 u64 umin_val = src_reg->umin_value;
12789 u64 umax_val = src_reg->umax_value;
12790
12791 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12792 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12793 /* Overflow possible, we know nothing */
12794 dst_reg->smin_value = S64_MIN;
12795 dst_reg->smax_value = S64_MAX;
12796 } else {
12797 dst_reg->smin_value -= smax_val;
12798 dst_reg->smax_value -= smin_val;
12799 }
12800 if (dst_reg->umin_value < umax_val) {
12801 /* Overflow possible, we know nothing */
12802 dst_reg->umin_value = 0;
12803 dst_reg->umax_value = U64_MAX;
12804 } else {
12805 /* Cannot overflow (as long as bounds are consistent) */
12806 dst_reg->umin_value -= umax_val;
12807 dst_reg->umax_value -= umin_val;
12808 }
12809 }
12810
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12811 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12812 struct bpf_reg_state *src_reg)
12813 {
12814 s32 smin_val = src_reg->s32_min_value;
12815 u32 umin_val = src_reg->u32_min_value;
12816 u32 umax_val = src_reg->u32_max_value;
12817
12818 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12819 /* Ain't nobody got time to multiply that sign */
12820 __mark_reg32_unbounded(dst_reg);
12821 return;
12822 }
12823 /* Both values are positive, so we can work with unsigned and
12824 * copy the result to signed (unless it exceeds S32_MAX).
12825 */
12826 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12827 /* Potential overflow, we know nothing */
12828 __mark_reg32_unbounded(dst_reg);
12829 return;
12830 }
12831 dst_reg->u32_min_value *= umin_val;
12832 dst_reg->u32_max_value *= umax_val;
12833 if (dst_reg->u32_max_value > S32_MAX) {
12834 /* Overflow possible, we know nothing */
12835 dst_reg->s32_min_value = S32_MIN;
12836 dst_reg->s32_max_value = S32_MAX;
12837 } else {
12838 dst_reg->s32_min_value = dst_reg->u32_min_value;
12839 dst_reg->s32_max_value = dst_reg->u32_max_value;
12840 }
12841 }
12842
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12843 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12844 struct bpf_reg_state *src_reg)
12845 {
12846 s64 smin_val = src_reg->smin_value;
12847 u64 umin_val = src_reg->umin_value;
12848 u64 umax_val = src_reg->umax_value;
12849
12850 if (smin_val < 0 || dst_reg->smin_value < 0) {
12851 /* Ain't nobody got time to multiply that sign */
12852 __mark_reg64_unbounded(dst_reg);
12853 return;
12854 }
12855 /* Both values are positive, so we can work with unsigned and
12856 * copy the result to signed (unless it exceeds S64_MAX).
12857 */
12858 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12859 /* Potential overflow, we know nothing */
12860 __mark_reg64_unbounded(dst_reg);
12861 return;
12862 }
12863 dst_reg->umin_value *= umin_val;
12864 dst_reg->umax_value *= umax_val;
12865 if (dst_reg->umax_value > S64_MAX) {
12866 /* Overflow possible, we know nothing */
12867 dst_reg->smin_value = S64_MIN;
12868 dst_reg->smax_value = S64_MAX;
12869 } else {
12870 dst_reg->smin_value = dst_reg->umin_value;
12871 dst_reg->smax_value = dst_reg->umax_value;
12872 }
12873 }
12874
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12875 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12876 struct bpf_reg_state *src_reg)
12877 {
12878 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12879 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12880 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12881 s32 smin_val = src_reg->s32_min_value;
12882 u32 umax_val = src_reg->u32_max_value;
12883
12884 if (src_known && dst_known) {
12885 __mark_reg32_known(dst_reg, var32_off.value);
12886 return;
12887 }
12888
12889 /* We get our minimum from the var_off, since that's inherently
12890 * bitwise. Our maximum is the minimum of the operands' maxima.
12891 */
12892 dst_reg->u32_min_value = var32_off.value;
12893 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12894 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12895 /* Lose signed bounds when ANDing negative numbers,
12896 * ain't nobody got time for that.
12897 */
12898 dst_reg->s32_min_value = S32_MIN;
12899 dst_reg->s32_max_value = S32_MAX;
12900 } else {
12901 /* ANDing two positives gives a positive, so safe to
12902 * cast result into s64.
12903 */
12904 dst_reg->s32_min_value = dst_reg->u32_min_value;
12905 dst_reg->s32_max_value = dst_reg->u32_max_value;
12906 }
12907 }
12908
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12909 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12910 struct bpf_reg_state *src_reg)
12911 {
12912 bool src_known = tnum_is_const(src_reg->var_off);
12913 bool dst_known = tnum_is_const(dst_reg->var_off);
12914 s64 smin_val = src_reg->smin_value;
12915 u64 umax_val = src_reg->umax_value;
12916
12917 if (src_known && dst_known) {
12918 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12919 return;
12920 }
12921
12922 /* We get our minimum from the var_off, since that's inherently
12923 * bitwise. Our maximum is the minimum of the operands' maxima.
12924 */
12925 dst_reg->umin_value = dst_reg->var_off.value;
12926 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12927 if (dst_reg->smin_value < 0 || smin_val < 0) {
12928 /* Lose signed bounds when ANDing negative numbers,
12929 * ain't nobody got time for that.
12930 */
12931 dst_reg->smin_value = S64_MIN;
12932 dst_reg->smax_value = S64_MAX;
12933 } else {
12934 /* ANDing two positives gives a positive, so safe to
12935 * cast result into s64.
12936 */
12937 dst_reg->smin_value = dst_reg->umin_value;
12938 dst_reg->smax_value = dst_reg->umax_value;
12939 }
12940 /* We may learn something more from the var_off */
12941 __update_reg_bounds(dst_reg);
12942 }
12943
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12944 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12945 struct bpf_reg_state *src_reg)
12946 {
12947 bool src_known = tnum_subreg_is_const(src_reg->var_off);
12948 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12949 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12950 s32 smin_val = src_reg->s32_min_value;
12951 u32 umin_val = src_reg->u32_min_value;
12952
12953 if (src_known && dst_known) {
12954 __mark_reg32_known(dst_reg, var32_off.value);
12955 return;
12956 }
12957
12958 /* We get our maximum from the var_off, and our minimum is the
12959 * maximum of the operands' minima
12960 */
12961 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12962 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12963 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12964 /* Lose signed bounds when ORing negative numbers,
12965 * ain't nobody got time for that.
12966 */
12967 dst_reg->s32_min_value = S32_MIN;
12968 dst_reg->s32_max_value = S32_MAX;
12969 } else {
12970 /* ORing two positives gives a positive, so safe to
12971 * cast result into s64.
12972 */
12973 dst_reg->s32_min_value = dst_reg->u32_min_value;
12974 dst_reg->s32_max_value = dst_reg->u32_max_value;
12975 }
12976 }
12977
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)12978 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12979 struct bpf_reg_state *src_reg)
12980 {
12981 bool src_known = tnum_is_const(src_reg->var_off);
12982 bool dst_known = tnum_is_const(dst_reg->var_off);
12983 s64 smin_val = src_reg->smin_value;
12984 u64 umin_val = src_reg->umin_value;
12985
12986 if (src_known && dst_known) {
12987 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12988 return;
12989 }
12990
12991 /* We get our maximum from the var_off, and our minimum is the
12992 * maximum of the operands' minima
12993 */
12994 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12995 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12996 if (dst_reg->smin_value < 0 || smin_val < 0) {
12997 /* Lose signed bounds when ORing negative numbers,
12998 * ain't nobody got time for that.
12999 */
13000 dst_reg->smin_value = S64_MIN;
13001 dst_reg->smax_value = S64_MAX;
13002 } else {
13003 /* ORing two positives gives a positive, so safe to
13004 * cast result into s64.
13005 */
13006 dst_reg->smin_value = dst_reg->umin_value;
13007 dst_reg->smax_value = dst_reg->umax_value;
13008 }
13009 /* We may learn something more from the var_off */
13010 __update_reg_bounds(dst_reg);
13011 }
13012
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13013 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13014 struct bpf_reg_state *src_reg)
13015 {
13016 bool src_known = tnum_subreg_is_const(src_reg->var_off);
13017 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13018 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13019 s32 smin_val = src_reg->s32_min_value;
13020
13021 if (src_known && dst_known) {
13022 __mark_reg32_known(dst_reg, var32_off.value);
13023 return;
13024 }
13025
13026 /* We get both minimum and maximum from the var32_off. */
13027 dst_reg->u32_min_value = var32_off.value;
13028 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13029
13030 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13031 /* XORing two positive sign numbers gives a positive,
13032 * so safe to cast u32 result into s32.
13033 */
13034 dst_reg->s32_min_value = dst_reg->u32_min_value;
13035 dst_reg->s32_max_value = dst_reg->u32_max_value;
13036 } else {
13037 dst_reg->s32_min_value = S32_MIN;
13038 dst_reg->s32_max_value = S32_MAX;
13039 }
13040 }
13041
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13042 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13043 struct bpf_reg_state *src_reg)
13044 {
13045 bool src_known = tnum_is_const(src_reg->var_off);
13046 bool dst_known = tnum_is_const(dst_reg->var_off);
13047 s64 smin_val = src_reg->smin_value;
13048
13049 if (src_known && dst_known) {
13050 /* dst_reg->var_off.value has been updated earlier */
13051 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13052 return;
13053 }
13054
13055 /* We get both minimum and maximum from the var_off. */
13056 dst_reg->umin_value = dst_reg->var_off.value;
13057 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13058
13059 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13060 /* XORing two positive sign numbers gives a positive,
13061 * so safe to cast u64 result into s64.
13062 */
13063 dst_reg->smin_value = dst_reg->umin_value;
13064 dst_reg->smax_value = dst_reg->umax_value;
13065 } else {
13066 dst_reg->smin_value = S64_MIN;
13067 dst_reg->smax_value = S64_MAX;
13068 }
13069
13070 __update_reg_bounds(dst_reg);
13071 }
13072
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13073 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13074 u64 umin_val, u64 umax_val)
13075 {
13076 /* We lose all sign bit information (except what we can pick
13077 * up from var_off)
13078 */
13079 dst_reg->s32_min_value = S32_MIN;
13080 dst_reg->s32_max_value = S32_MAX;
13081 /* If we might shift our top bit out, then we know nothing */
13082 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13083 dst_reg->u32_min_value = 0;
13084 dst_reg->u32_max_value = U32_MAX;
13085 } else {
13086 dst_reg->u32_min_value <<= umin_val;
13087 dst_reg->u32_max_value <<= umax_val;
13088 }
13089 }
13090
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13091 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13092 struct bpf_reg_state *src_reg)
13093 {
13094 u32 umax_val = src_reg->u32_max_value;
13095 u32 umin_val = src_reg->u32_min_value;
13096 /* u32 alu operation will zext upper bits */
13097 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13098
13099 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13100 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13101 /* Not required but being careful mark reg64 bounds as unknown so
13102 * that we are forced to pick them up from tnum and zext later and
13103 * if some path skips this step we are still safe.
13104 */
13105 __mark_reg64_unbounded(dst_reg);
13106 __update_reg32_bounds(dst_reg);
13107 }
13108
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)13109 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13110 u64 umin_val, u64 umax_val)
13111 {
13112 /* Special case <<32 because it is a common compiler pattern to sign
13113 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13114 * positive we know this shift will also be positive so we can track
13115 * bounds correctly. Otherwise we lose all sign bit information except
13116 * what we can pick up from var_off. Perhaps we can generalize this
13117 * later to shifts of any length.
13118 */
13119 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13120 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13121 else
13122 dst_reg->smax_value = S64_MAX;
13123
13124 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13125 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13126 else
13127 dst_reg->smin_value = S64_MIN;
13128
13129 /* If we might shift our top bit out, then we know nothing */
13130 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13131 dst_reg->umin_value = 0;
13132 dst_reg->umax_value = U64_MAX;
13133 } else {
13134 dst_reg->umin_value <<= umin_val;
13135 dst_reg->umax_value <<= umax_val;
13136 }
13137 }
13138
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13139 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13140 struct bpf_reg_state *src_reg)
13141 {
13142 u64 umax_val = src_reg->umax_value;
13143 u64 umin_val = src_reg->umin_value;
13144
13145 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13146 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13147 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13148
13149 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13150 /* We may learn something more from the var_off */
13151 __update_reg_bounds(dst_reg);
13152 }
13153
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13154 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13155 struct bpf_reg_state *src_reg)
13156 {
13157 struct tnum subreg = tnum_subreg(dst_reg->var_off);
13158 u32 umax_val = src_reg->u32_max_value;
13159 u32 umin_val = src_reg->u32_min_value;
13160
13161 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13162 * be negative, then either:
13163 * 1) src_reg might be zero, so the sign bit of the result is
13164 * unknown, so we lose our signed bounds
13165 * 2) it's known negative, thus the unsigned bounds capture the
13166 * signed bounds
13167 * 3) the signed bounds cross zero, so they tell us nothing
13168 * about the result
13169 * If the value in dst_reg is known nonnegative, then again the
13170 * unsigned bounds capture the signed bounds.
13171 * Thus, in all cases it suffices to blow away our signed bounds
13172 * and rely on inferring new ones from the unsigned bounds and
13173 * var_off of the result.
13174 */
13175 dst_reg->s32_min_value = S32_MIN;
13176 dst_reg->s32_max_value = S32_MAX;
13177
13178 dst_reg->var_off = tnum_rshift(subreg, umin_val);
13179 dst_reg->u32_min_value >>= umax_val;
13180 dst_reg->u32_max_value >>= umin_val;
13181
13182 __mark_reg64_unbounded(dst_reg);
13183 __update_reg32_bounds(dst_reg);
13184 }
13185
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13186 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13187 struct bpf_reg_state *src_reg)
13188 {
13189 u64 umax_val = src_reg->umax_value;
13190 u64 umin_val = src_reg->umin_value;
13191
13192 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
13193 * be negative, then either:
13194 * 1) src_reg might be zero, so the sign bit of the result is
13195 * unknown, so we lose our signed bounds
13196 * 2) it's known negative, thus the unsigned bounds capture the
13197 * signed bounds
13198 * 3) the signed bounds cross zero, so they tell us nothing
13199 * about the result
13200 * If the value in dst_reg is known nonnegative, then again the
13201 * unsigned bounds capture the signed bounds.
13202 * Thus, in all cases it suffices to blow away our signed bounds
13203 * and rely on inferring new ones from the unsigned bounds and
13204 * var_off of the result.
13205 */
13206 dst_reg->smin_value = S64_MIN;
13207 dst_reg->smax_value = S64_MAX;
13208 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13209 dst_reg->umin_value >>= umax_val;
13210 dst_reg->umax_value >>= umin_val;
13211
13212 /* Its not easy to operate on alu32 bounds here because it depends
13213 * on bits being shifted in. Take easy way out and mark unbounded
13214 * so we can recalculate later from tnum.
13215 */
13216 __mark_reg32_unbounded(dst_reg);
13217 __update_reg_bounds(dst_reg);
13218 }
13219
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13220 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13221 struct bpf_reg_state *src_reg)
13222 {
13223 u64 umin_val = src_reg->u32_min_value;
13224
13225 /* Upon reaching here, src_known is true and
13226 * umax_val is equal to umin_val.
13227 */
13228 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13229 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13230
13231 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13232
13233 /* blow away the dst_reg umin_value/umax_value and rely on
13234 * dst_reg var_off to refine the result.
13235 */
13236 dst_reg->u32_min_value = 0;
13237 dst_reg->u32_max_value = U32_MAX;
13238
13239 __mark_reg64_unbounded(dst_reg);
13240 __update_reg32_bounds(dst_reg);
13241 }
13242
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)13243 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13244 struct bpf_reg_state *src_reg)
13245 {
13246 u64 umin_val = src_reg->umin_value;
13247
13248 /* Upon reaching here, src_known is true and umax_val is equal
13249 * to umin_val.
13250 */
13251 dst_reg->smin_value >>= umin_val;
13252 dst_reg->smax_value >>= umin_val;
13253
13254 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13255
13256 /* blow away the dst_reg umin_value/umax_value and rely on
13257 * dst_reg var_off to refine the result.
13258 */
13259 dst_reg->umin_value = 0;
13260 dst_reg->umax_value = U64_MAX;
13261
13262 /* Its not easy to operate on alu32 bounds here because it depends
13263 * on bits being shifted in from upper 32-bits. Take easy way out
13264 * and mark unbounded so we can recalculate later from tnum.
13265 */
13266 __mark_reg32_unbounded(dst_reg);
13267 __update_reg_bounds(dst_reg);
13268 }
13269
13270 /* WARNING: This function does calculations on 64-bit values, but the actual
13271 * execution may occur on 32-bit values. Therefore, things like bitshifts
13272 * need extra checks in the 32-bit case.
13273 */
adjust_scalar_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state src_reg)13274 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13275 struct bpf_insn *insn,
13276 struct bpf_reg_state *dst_reg,
13277 struct bpf_reg_state src_reg)
13278 {
13279 struct bpf_reg_state *regs = cur_regs(env);
13280 u8 opcode = BPF_OP(insn->code);
13281 bool src_known;
13282 s64 smin_val, smax_val;
13283 u64 umin_val, umax_val;
13284 s32 s32_min_val, s32_max_val;
13285 u32 u32_min_val, u32_max_val;
13286 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13287 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13288 int ret;
13289
13290 smin_val = src_reg.smin_value;
13291 smax_val = src_reg.smax_value;
13292 umin_val = src_reg.umin_value;
13293 umax_val = src_reg.umax_value;
13294
13295 s32_min_val = src_reg.s32_min_value;
13296 s32_max_val = src_reg.s32_max_value;
13297 u32_min_val = src_reg.u32_min_value;
13298 u32_max_val = src_reg.u32_max_value;
13299
13300 if (alu32) {
13301 src_known = tnum_subreg_is_const(src_reg.var_off);
13302 if ((src_known &&
13303 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13304 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13305 /* Taint dst register if offset had invalid bounds
13306 * derived from e.g. dead branches.
13307 */
13308 __mark_reg_unknown(env, dst_reg);
13309 return 0;
13310 }
13311 } else {
13312 src_known = tnum_is_const(src_reg.var_off);
13313 if ((src_known &&
13314 (smin_val != smax_val || umin_val != umax_val)) ||
13315 smin_val > smax_val || umin_val > umax_val) {
13316 /* Taint dst register if offset had invalid bounds
13317 * derived from e.g. dead branches.
13318 */
13319 __mark_reg_unknown(env, dst_reg);
13320 return 0;
13321 }
13322 }
13323
13324 if (!src_known &&
13325 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13326 __mark_reg_unknown(env, dst_reg);
13327 return 0;
13328 }
13329
13330 if (sanitize_needed(opcode)) {
13331 ret = sanitize_val_alu(env, insn);
13332 if (ret < 0)
13333 return sanitize_err(env, insn, ret, NULL, NULL);
13334 }
13335
13336 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13337 * There are two classes of instructions: The first class we track both
13338 * alu32 and alu64 sign/unsigned bounds independently this provides the
13339 * greatest amount of precision when alu operations are mixed with jmp32
13340 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13341 * and BPF_OR. This is possible because these ops have fairly easy to
13342 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13343 * See alu32 verifier tests for examples. The second class of
13344 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13345 * with regards to tracking sign/unsigned bounds because the bits may
13346 * cross subreg boundaries in the alu64 case. When this happens we mark
13347 * the reg unbounded in the subreg bound space and use the resulting
13348 * tnum to calculate an approximation of the sign/unsigned bounds.
13349 */
13350 switch (opcode) {
13351 case BPF_ADD:
13352 scalar32_min_max_add(dst_reg, &src_reg);
13353 scalar_min_max_add(dst_reg, &src_reg);
13354 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13355 break;
13356 case BPF_SUB:
13357 scalar32_min_max_sub(dst_reg, &src_reg);
13358 scalar_min_max_sub(dst_reg, &src_reg);
13359 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13360 break;
13361 case BPF_MUL:
13362 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13363 scalar32_min_max_mul(dst_reg, &src_reg);
13364 scalar_min_max_mul(dst_reg, &src_reg);
13365 break;
13366 case BPF_AND:
13367 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13368 scalar32_min_max_and(dst_reg, &src_reg);
13369 scalar_min_max_and(dst_reg, &src_reg);
13370 break;
13371 case BPF_OR:
13372 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13373 scalar32_min_max_or(dst_reg, &src_reg);
13374 scalar_min_max_or(dst_reg, &src_reg);
13375 break;
13376 case BPF_XOR:
13377 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13378 scalar32_min_max_xor(dst_reg, &src_reg);
13379 scalar_min_max_xor(dst_reg, &src_reg);
13380 break;
13381 case BPF_LSH:
13382 if (umax_val >= insn_bitness) {
13383 /* Shifts greater than 31 or 63 are undefined.
13384 * This includes shifts by a negative number.
13385 */
13386 mark_reg_unknown(env, regs, insn->dst_reg);
13387 break;
13388 }
13389 if (alu32)
13390 scalar32_min_max_lsh(dst_reg, &src_reg);
13391 else
13392 scalar_min_max_lsh(dst_reg, &src_reg);
13393 break;
13394 case BPF_RSH:
13395 if (umax_val >= insn_bitness) {
13396 /* Shifts greater than 31 or 63 are undefined.
13397 * This includes shifts by a negative number.
13398 */
13399 mark_reg_unknown(env, regs, insn->dst_reg);
13400 break;
13401 }
13402 if (alu32)
13403 scalar32_min_max_rsh(dst_reg, &src_reg);
13404 else
13405 scalar_min_max_rsh(dst_reg, &src_reg);
13406 break;
13407 case BPF_ARSH:
13408 if (umax_val >= insn_bitness) {
13409 /* Shifts greater than 31 or 63 are undefined.
13410 * This includes shifts by a negative number.
13411 */
13412 mark_reg_unknown(env, regs, insn->dst_reg);
13413 break;
13414 }
13415 if (alu32)
13416 scalar32_min_max_arsh(dst_reg, &src_reg);
13417 else
13418 scalar_min_max_arsh(dst_reg, &src_reg);
13419 break;
13420 default:
13421 mark_reg_unknown(env, regs, insn->dst_reg);
13422 break;
13423 }
13424
13425 /* ALU32 ops are zero extended into 64bit register */
13426 if (alu32)
13427 zext_32_to_64(dst_reg);
13428 reg_bounds_sync(dst_reg);
13429 return 0;
13430 }
13431
13432 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13433 * and var_off.
13434 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)13435 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13436 struct bpf_insn *insn)
13437 {
13438 struct bpf_verifier_state *vstate = env->cur_state;
13439 struct bpf_func_state *state = vstate->frame[vstate->curframe];
13440 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13441 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13442 u8 opcode = BPF_OP(insn->code);
13443 int err;
13444
13445 dst_reg = ®s[insn->dst_reg];
13446 src_reg = NULL;
13447 if (dst_reg->type != SCALAR_VALUE)
13448 ptr_reg = dst_reg;
13449 else
13450 /* Make sure ID is cleared otherwise dst_reg min/max could be
13451 * incorrectly propagated into other registers by find_equal_scalars()
13452 */
13453 dst_reg->id = 0;
13454 if (BPF_SRC(insn->code) == BPF_X) {
13455 src_reg = ®s[insn->src_reg];
13456 if (src_reg->type != SCALAR_VALUE) {
13457 if (dst_reg->type != SCALAR_VALUE) {
13458 /* Combining two pointers by any ALU op yields
13459 * an arbitrary scalar. Disallow all math except
13460 * pointer subtraction
13461 */
13462 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13463 mark_reg_unknown(env, regs, insn->dst_reg);
13464 return 0;
13465 }
13466 verbose(env, "R%d pointer %s pointer prohibited\n",
13467 insn->dst_reg,
13468 bpf_alu_string[opcode >> 4]);
13469 return -EACCES;
13470 } else {
13471 /* scalar += pointer
13472 * This is legal, but we have to reverse our
13473 * src/dest handling in computing the range
13474 */
13475 err = mark_chain_precision(env, insn->dst_reg);
13476 if (err)
13477 return err;
13478 return adjust_ptr_min_max_vals(env, insn,
13479 src_reg, dst_reg);
13480 }
13481 } else if (ptr_reg) {
13482 /* pointer += scalar */
13483 err = mark_chain_precision(env, insn->src_reg);
13484 if (err)
13485 return err;
13486 return adjust_ptr_min_max_vals(env, insn,
13487 dst_reg, src_reg);
13488 } else if (dst_reg->precise) {
13489 /* if dst_reg is precise, src_reg should be precise as well */
13490 err = mark_chain_precision(env, insn->src_reg);
13491 if (err)
13492 return err;
13493 }
13494 } else {
13495 /* Pretend the src is a reg with a known value, since we only
13496 * need to be able to read from this state.
13497 */
13498 off_reg.type = SCALAR_VALUE;
13499 __mark_reg_known(&off_reg, insn->imm);
13500 src_reg = &off_reg;
13501 if (ptr_reg) /* pointer += K */
13502 return adjust_ptr_min_max_vals(env, insn,
13503 ptr_reg, src_reg);
13504 }
13505
13506 /* Got here implies adding two SCALAR_VALUEs */
13507 if (WARN_ON_ONCE(ptr_reg)) {
13508 print_verifier_state(env, state, true);
13509 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13510 return -EINVAL;
13511 }
13512 if (WARN_ON(!src_reg)) {
13513 print_verifier_state(env, state, true);
13514 verbose(env, "verifier internal error: no src_reg\n");
13515 return -EINVAL;
13516 }
13517 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13518 }
13519
13520 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)13521 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13522 {
13523 struct bpf_reg_state *regs = cur_regs(env);
13524 u8 opcode = BPF_OP(insn->code);
13525 int err;
13526
13527 if (opcode == BPF_END || opcode == BPF_NEG) {
13528 if (opcode == BPF_NEG) {
13529 if (BPF_SRC(insn->code) != BPF_K ||
13530 insn->src_reg != BPF_REG_0 ||
13531 insn->off != 0 || insn->imm != 0) {
13532 verbose(env, "BPF_NEG uses reserved fields\n");
13533 return -EINVAL;
13534 }
13535 } else {
13536 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13537 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13538 (BPF_CLASS(insn->code) == BPF_ALU64 &&
13539 BPF_SRC(insn->code) != BPF_TO_LE)) {
13540 verbose(env, "BPF_END uses reserved fields\n");
13541 return -EINVAL;
13542 }
13543 }
13544
13545 /* check src operand */
13546 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13547 if (err)
13548 return err;
13549
13550 if (is_pointer_value(env, insn->dst_reg)) {
13551 verbose(env, "R%d pointer arithmetic prohibited\n",
13552 insn->dst_reg);
13553 return -EACCES;
13554 }
13555
13556 /* check dest operand */
13557 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13558 if (err)
13559 return err;
13560
13561 } else if (opcode == BPF_MOV) {
13562
13563 if (BPF_SRC(insn->code) == BPF_X) {
13564 if (insn->imm != 0) {
13565 verbose(env, "BPF_MOV uses reserved fields\n");
13566 return -EINVAL;
13567 }
13568
13569 if (BPF_CLASS(insn->code) == BPF_ALU) {
13570 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13571 verbose(env, "BPF_MOV uses reserved fields\n");
13572 return -EINVAL;
13573 }
13574 } else {
13575 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13576 insn->off != 32) {
13577 verbose(env, "BPF_MOV uses reserved fields\n");
13578 return -EINVAL;
13579 }
13580 }
13581
13582 /* check src operand */
13583 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13584 if (err)
13585 return err;
13586 } else {
13587 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13588 verbose(env, "BPF_MOV uses reserved fields\n");
13589 return -EINVAL;
13590 }
13591 }
13592
13593 /* check dest operand, mark as required later */
13594 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13595 if (err)
13596 return err;
13597
13598 if (BPF_SRC(insn->code) == BPF_X) {
13599 struct bpf_reg_state *src_reg = regs + insn->src_reg;
13600 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13601 bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13602 !tnum_is_const(src_reg->var_off);
13603
13604 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13605 if (insn->off == 0) {
13606 /* case: R1 = R2
13607 * copy register state to dest reg
13608 */
13609 if (need_id)
13610 /* Assign src and dst registers the same ID
13611 * that will be used by find_equal_scalars()
13612 * to propagate min/max range.
13613 */
13614 src_reg->id = ++env->id_gen;
13615 copy_register_state(dst_reg, src_reg);
13616 dst_reg->live |= REG_LIVE_WRITTEN;
13617 dst_reg->subreg_def = DEF_NOT_SUBREG;
13618 } else {
13619 /* case: R1 = (s8, s16 s32)R2 */
13620 if (is_pointer_value(env, insn->src_reg)) {
13621 verbose(env,
13622 "R%d sign-extension part of pointer\n",
13623 insn->src_reg);
13624 return -EACCES;
13625 } else if (src_reg->type == SCALAR_VALUE) {
13626 bool no_sext;
13627
13628 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13629 if (no_sext && need_id)
13630 src_reg->id = ++env->id_gen;
13631 copy_register_state(dst_reg, src_reg);
13632 if (!no_sext)
13633 dst_reg->id = 0;
13634 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13635 dst_reg->live |= REG_LIVE_WRITTEN;
13636 dst_reg->subreg_def = DEF_NOT_SUBREG;
13637 } else {
13638 mark_reg_unknown(env, regs, insn->dst_reg);
13639 }
13640 }
13641 } else {
13642 /* R1 = (u32) R2 */
13643 if (is_pointer_value(env, insn->src_reg)) {
13644 verbose(env,
13645 "R%d partial copy of pointer\n",
13646 insn->src_reg);
13647 return -EACCES;
13648 } else if (src_reg->type == SCALAR_VALUE) {
13649 if (insn->off == 0) {
13650 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13651
13652 if (is_src_reg_u32 && need_id)
13653 src_reg->id = ++env->id_gen;
13654 copy_register_state(dst_reg, src_reg);
13655 /* Make sure ID is cleared if src_reg is not in u32
13656 * range otherwise dst_reg min/max could be incorrectly
13657 * propagated into src_reg by find_equal_scalars()
13658 */
13659 if (!is_src_reg_u32)
13660 dst_reg->id = 0;
13661 dst_reg->live |= REG_LIVE_WRITTEN;
13662 dst_reg->subreg_def = env->insn_idx + 1;
13663 } else {
13664 /* case: W1 = (s8, s16)W2 */
13665 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13666
13667 if (no_sext && need_id)
13668 src_reg->id = ++env->id_gen;
13669 copy_register_state(dst_reg, src_reg);
13670 if (!no_sext)
13671 dst_reg->id = 0;
13672 dst_reg->live |= REG_LIVE_WRITTEN;
13673 dst_reg->subreg_def = env->insn_idx + 1;
13674 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13675 }
13676 } else {
13677 mark_reg_unknown(env, regs,
13678 insn->dst_reg);
13679 }
13680 zext_32_to_64(dst_reg);
13681 reg_bounds_sync(dst_reg);
13682 }
13683 } else {
13684 /* case: R = imm
13685 * remember the value we stored into this reg
13686 */
13687 /* clear any state __mark_reg_known doesn't set */
13688 mark_reg_unknown(env, regs, insn->dst_reg);
13689 regs[insn->dst_reg].type = SCALAR_VALUE;
13690 if (BPF_CLASS(insn->code) == BPF_ALU64) {
13691 __mark_reg_known(regs + insn->dst_reg,
13692 insn->imm);
13693 } else {
13694 __mark_reg_known(regs + insn->dst_reg,
13695 (u32)insn->imm);
13696 }
13697 }
13698
13699 } else if (opcode > BPF_END) {
13700 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13701 return -EINVAL;
13702
13703 } else { /* all other ALU ops: and, sub, xor, add, ... */
13704
13705 if (BPF_SRC(insn->code) == BPF_X) {
13706 if (insn->imm != 0 || insn->off > 1 ||
13707 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13708 verbose(env, "BPF_ALU uses reserved fields\n");
13709 return -EINVAL;
13710 }
13711 /* check src1 operand */
13712 err = check_reg_arg(env, insn->src_reg, SRC_OP);
13713 if (err)
13714 return err;
13715 } else {
13716 if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13717 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13718 verbose(env, "BPF_ALU uses reserved fields\n");
13719 return -EINVAL;
13720 }
13721 }
13722
13723 /* check src2 operand */
13724 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13725 if (err)
13726 return err;
13727
13728 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13729 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13730 verbose(env, "div by zero\n");
13731 return -EINVAL;
13732 }
13733
13734 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13735 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13736 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13737
13738 if (insn->imm < 0 || insn->imm >= size) {
13739 verbose(env, "invalid shift %d\n", insn->imm);
13740 return -EINVAL;
13741 }
13742 }
13743
13744 /* check dest operand */
13745 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13746 if (err)
13747 return err;
13748
13749 return adjust_reg_min_max_vals(env, insn);
13750 }
13751
13752 return 0;
13753 }
13754
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)13755 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13756 struct bpf_reg_state *dst_reg,
13757 enum bpf_reg_type type,
13758 bool range_right_open)
13759 {
13760 struct bpf_func_state *state;
13761 struct bpf_reg_state *reg;
13762 int new_range;
13763
13764 if (dst_reg->off < 0 ||
13765 (dst_reg->off == 0 && range_right_open))
13766 /* This doesn't give us any range */
13767 return;
13768
13769 if (dst_reg->umax_value > MAX_PACKET_OFF ||
13770 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13771 /* Risk of overflow. For instance, ptr + (1<<63) may be less
13772 * than pkt_end, but that's because it's also less than pkt.
13773 */
13774 return;
13775
13776 new_range = dst_reg->off;
13777 if (range_right_open)
13778 new_range++;
13779
13780 /* Examples for register markings:
13781 *
13782 * pkt_data in dst register:
13783 *
13784 * r2 = r3;
13785 * r2 += 8;
13786 * if (r2 > pkt_end) goto <handle exception>
13787 * <access okay>
13788 *
13789 * r2 = r3;
13790 * r2 += 8;
13791 * if (r2 < pkt_end) goto <access okay>
13792 * <handle exception>
13793 *
13794 * Where:
13795 * r2 == dst_reg, pkt_end == src_reg
13796 * r2=pkt(id=n,off=8,r=0)
13797 * r3=pkt(id=n,off=0,r=0)
13798 *
13799 * pkt_data in src register:
13800 *
13801 * r2 = r3;
13802 * r2 += 8;
13803 * if (pkt_end >= r2) goto <access okay>
13804 * <handle exception>
13805 *
13806 * r2 = r3;
13807 * r2 += 8;
13808 * if (pkt_end <= r2) goto <handle exception>
13809 * <access okay>
13810 *
13811 * Where:
13812 * pkt_end == dst_reg, r2 == src_reg
13813 * r2=pkt(id=n,off=8,r=0)
13814 * r3=pkt(id=n,off=0,r=0)
13815 *
13816 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13817 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13818 * and [r3, r3 + 8-1) respectively is safe to access depending on
13819 * the check.
13820 */
13821
13822 /* If our ids match, then we must have the same max_value. And we
13823 * don't care about the other reg's fixed offset, since if it's too big
13824 * the range won't allow anything.
13825 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13826 */
13827 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13828 if (reg->type == type && reg->id == dst_reg->id)
13829 /* keep the maximum range already checked */
13830 reg->range = max(reg->range, new_range);
13831 }));
13832 }
13833
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)13834 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13835 {
13836 struct tnum subreg = tnum_subreg(reg->var_off);
13837 s32 sval = (s32)val;
13838
13839 switch (opcode) {
13840 case BPF_JEQ:
13841 if (tnum_is_const(subreg))
13842 return !!tnum_equals_const(subreg, val);
13843 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13844 return 0;
13845 break;
13846 case BPF_JNE:
13847 if (tnum_is_const(subreg))
13848 return !tnum_equals_const(subreg, val);
13849 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13850 return 1;
13851 break;
13852 case BPF_JSET:
13853 if ((~subreg.mask & subreg.value) & val)
13854 return 1;
13855 if (!((subreg.mask | subreg.value) & val))
13856 return 0;
13857 break;
13858 case BPF_JGT:
13859 if (reg->u32_min_value > val)
13860 return 1;
13861 else if (reg->u32_max_value <= val)
13862 return 0;
13863 break;
13864 case BPF_JSGT:
13865 if (reg->s32_min_value > sval)
13866 return 1;
13867 else if (reg->s32_max_value <= sval)
13868 return 0;
13869 break;
13870 case BPF_JLT:
13871 if (reg->u32_max_value < val)
13872 return 1;
13873 else if (reg->u32_min_value >= val)
13874 return 0;
13875 break;
13876 case BPF_JSLT:
13877 if (reg->s32_max_value < sval)
13878 return 1;
13879 else if (reg->s32_min_value >= sval)
13880 return 0;
13881 break;
13882 case BPF_JGE:
13883 if (reg->u32_min_value >= val)
13884 return 1;
13885 else if (reg->u32_max_value < val)
13886 return 0;
13887 break;
13888 case BPF_JSGE:
13889 if (reg->s32_min_value >= sval)
13890 return 1;
13891 else if (reg->s32_max_value < sval)
13892 return 0;
13893 break;
13894 case BPF_JLE:
13895 if (reg->u32_max_value <= val)
13896 return 1;
13897 else if (reg->u32_min_value > val)
13898 return 0;
13899 break;
13900 case BPF_JSLE:
13901 if (reg->s32_max_value <= sval)
13902 return 1;
13903 else if (reg->s32_min_value > sval)
13904 return 0;
13905 break;
13906 }
13907
13908 return -1;
13909 }
13910
13911
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)13912 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13913 {
13914 s64 sval = (s64)val;
13915
13916 switch (opcode) {
13917 case BPF_JEQ:
13918 if (tnum_is_const(reg->var_off))
13919 return !!tnum_equals_const(reg->var_off, val);
13920 else if (val < reg->umin_value || val > reg->umax_value)
13921 return 0;
13922 break;
13923 case BPF_JNE:
13924 if (tnum_is_const(reg->var_off))
13925 return !tnum_equals_const(reg->var_off, val);
13926 else if (val < reg->umin_value || val > reg->umax_value)
13927 return 1;
13928 break;
13929 case BPF_JSET:
13930 if ((~reg->var_off.mask & reg->var_off.value) & val)
13931 return 1;
13932 if (!((reg->var_off.mask | reg->var_off.value) & val))
13933 return 0;
13934 break;
13935 case BPF_JGT:
13936 if (reg->umin_value > val)
13937 return 1;
13938 else if (reg->umax_value <= val)
13939 return 0;
13940 break;
13941 case BPF_JSGT:
13942 if (reg->smin_value > sval)
13943 return 1;
13944 else if (reg->smax_value <= sval)
13945 return 0;
13946 break;
13947 case BPF_JLT:
13948 if (reg->umax_value < val)
13949 return 1;
13950 else if (reg->umin_value >= val)
13951 return 0;
13952 break;
13953 case BPF_JSLT:
13954 if (reg->smax_value < sval)
13955 return 1;
13956 else if (reg->smin_value >= sval)
13957 return 0;
13958 break;
13959 case BPF_JGE:
13960 if (reg->umin_value >= val)
13961 return 1;
13962 else if (reg->umax_value < val)
13963 return 0;
13964 break;
13965 case BPF_JSGE:
13966 if (reg->smin_value >= sval)
13967 return 1;
13968 else if (reg->smax_value < sval)
13969 return 0;
13970 break;
13971 case BPF_JLE:
13972 if (reg->umax_value <= val)
13973 return 1;
13974 else if (reg->umin_value > val)
13975 return 0;
13976 break;
13977 case BPF_JSLE:
13978 if (reg->smax_value <= sval)
13979 return 1;
13980 else if (reg->smin_value > sval)
13981 return 0;
13982 break;
13983 }
13984
13985 return -1;
13986 }
13987
13988 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13989 * and return:
13990 * 1 - branch will be taken and "goto target" will be executed
13991 * 0 - branch will not be taken and fall-through to next insn
13992 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13993 * range [0,10]
13994 */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)13995 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13996 bool is_jmp32)
13997 {
13998 if (__is_pointer_value(false, reg)) {
13999 if (!reg_not_null(reg))
14000 return -1;
14001
14002 /* If pointer is valid tests against zero will fail so we can
14003 * use this to direct branch taken.
14004 */
14005 if (val != 0)
14006 return -1;
14007
14008 switch (opcode) {
14009 case BPF_JEQ:
14010 return 0;
14011 case BPF_JNE:
14012 return 1;
14013 default:
14014 return -1;
14015 }
14016 }
14017
14018 if (is_jmp32)
14019 return is_branch32_taken(reg, val, opcode);
14020 return is_branch64_taken(reg, val, opcode);
14021 }
14022
flip_opcode(u32 opcode)14023 static int flip_opcode(u32 opcode)
14024 {
14025 /* How can we transform "a <op> b" into "b <op> a"? */
14026 static const u8 opcode_flip[16] = {
14027 /* these stay the same */
14028 [BPF_JEQ >> 4] = BPF_JEQ,
14029 [BPF_JNE >> 4] = BPF_JNE,
14030 [BPF_JSET >> 4] = BPF_JSET,
14031 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14032 [BPF_JGE >> 4] = BPF_JLE,
14033 [BPF_JGT >> 4] = BPF_JLT,
14034 [BPF_JLE >> 4] = BPF_JGE,
14035 [BPF_JLT >> 4] = BPF_JGT,
14036 [BPF_JSGE >> 4] = BPF_JSLE,
14037 [BPF_JSGT >> 4] = BPF_JSLT,
14038 [BPF_JSLE >> 4] = BPF_JSGE,
14039 [BPF_JSLT >> 4] = BPF_JSGT
14040 };
14041 return opcode_flip[opcode >> 4];
14042 }
14043
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)14044 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14045 struct bpf_reg_state *src_reg,
14046 u8 opcode)
14047 {
14048 struct bpf_reg_state *pkt;
14049
14050 if (src_reg->type == PTR_TO_PACKET_END) {
14051 pkt = dst_reg;
14052 } else if (dst_reg->type == PTR_TO_PACKET_END) {
14053 pkt = src_reg;
14054 opcode = flip_opcode(opcode);
14055 } else {
14056 return -1;
14057 }
14058
14059 if (pkt->range >= 0)
14060 return -1;
14061
14062 switch (opcode) {
14063 case BPF_JLE:
14064 /* pkt <= pkt_end */
14065 fallthrough;
14066 case BPF_JGT:
14067 /* pkt > pkt_end */
14068 if (pkt->range == BEYOND_PKT_END)
14069 /* pkt has at last one extra byte beyond pkt_end */
14070 return opcode == BPF_JGT;
14071 break;
14072 case BPF_JLT:
14073 /* pkt < pkt_end */
14074 fallthrough;
14075 case BPF_JGE:
14076 /* pkt >= pkt_end */
14077 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14078 return opcode == BPF_JGE;
14079 break;
14080 }
14081 return -1;
14082 }
14083
14084 /* Adjusts the register min/max values in the case that the dst_reg is the
14085 * variable register that we are working on, and src_reg is a constant or we're
14086 * simply doing a BPF_K check.
14087 * In JEQ/JNE cases we also adjust the var_off values.
14088 */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14089 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14090 struct bpf_reg_state *false_reg,
14091 u64 val, u32 val32,
14092 u8 opcode, bool is_jmp32)
14093 {
14094 struct tnum false_32off = tnum_subreg(false_reg->var_off);
14095 struct tnum false_64off = false_reg->var_off;
14096 struct tnum true_32off = tnum_subreg(true_reg->var_off);
14097 struct tnum true_64off = true_reg->var_off;
14098 s64 sval = (s64)val;
14099 s32 sval32 = (s32)val32;
14100
14101 /* If the dst_reg is a pointer, we can't learn anything about its
14102 * variable offset from the compare (unless src_reg were a pointer into
14103 * the same object, but we don't bother with that.
14104 * Since false_reg and true_reg have the same type by construction, we
14105 * only need to check one of them for pointerness.
14106 */
14107 if (__is_pointer_value(false, false_reg))
14108 return;
14109
14110 switch (opcode) {
14111 /* JEQ/JNE comparison doesn't change the register equivalence.
14112 *
14113 * r1 = r2;
14114 * if (r1 == 42) goto label;
14115 * ...
14116 * label: // here both r1 and r2 are known to be 42.
14117 *
14118 * Hence when marking register as known preserve it's ID.
14119 */
14120 case BPF_JEQ:
14121 if (is_jmp32) {
14122 __mark_reg32_known(true_reg, val32);
14123 true_32off = tnum_subreg(true_reg->var_off);
14124 } else {
14125 ___mark_reg_known(true_reg, val);
14126 true_64off = true_reg->var_off;
14127 }
14128 break;
14129 case BPF_JNE:
14130 if (is_jmp32) {
14131 __mark_reg32_known(false_reg, val32);
14132 false_32off = tnum_subreg(false_reg->var_off);
14133 } else {
14134 ___mark_reg_known(false_reg, val);
14135 false_64off = false_reg->var_off;
14136 }
14137 break;
14138 case BPF_JSET:
14139 if (is_jmp32) {
14140 false_32off = tnum_and(false_32off, tnum_const(~val32));
14141 if (is_power_of_2(val32))
14142 true_32off = tnum_or(true_32off,
14143 tnum_const(val32));
14144 } else {
14145 false_64off = tnum_and(false_64off, tnum_const(~val));
14146 if (is_power_of_2(val))
14147 true_64off = tnum_or(true_64off,
14148 tnum_const(val));
14149 }
14150 break;
14151 case BPF_JGE:
14152 case BPF_JGT:
14153 {
14154 if (is_jmp32) {
14155 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
14156 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14157
14158 false_reg->u32_max_value = min(false_reg->u32_max_value,
14159 false_umax);
14160 true_reg->u32_min_value = max(true_reg->u32_min_value,
14161 true_umin);
14162 } else {
14163 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
14164 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14165
14166 false_reg->umax_value = min(false_reg->umax_value, false_umax);
14167 true_reg->umin_value = max(true_reg->umin_value, true_umin);
14168 }
14169 break;
14170 }
14171 case BPF_JSGE:
14172 case BPF_JSGT:
14173 {
14174 if (is_jmp32) {
14175 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
14176 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14177
14178 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14179 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14180 } else {
14181 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
14182 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14183
14184 false_reg->smax_value = min(false_reg->smax_value, false_smax);
14185 true_reg->smin_value = max(true_reg->smin_value, true_smin);
14186 }
14187 break;
14188 }
14189 case BPF_JLE:
14190 case BPF_JLT:
14191 {
14192 if (is_jmp32) {
14193 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
14194 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14195
14196 false_reg->u32_min_value = max(false_reg->u32_min_value,
14197 false_umin);
14198 true_reg->u32_max_value = min(true_reg->u32_max_value,
14199 true_umax);
14200 } else {
14201 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
14202 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14203
14204 false_reg->umin_value = max(false_reg->umin_value, false_umin);
14205 true_reg->umax_value = min(true_reg->umax_value, true_umax);
14206 }
14207 break;
14208 }
14209 case BPF_JSLE:
14210 case BPF_JSLT:
14211 {
14212 if (is_jmp32) {
14213 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
14214 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14215
14216 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14217 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14218 } else {
14219 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
14220 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14221
14222 false_reg->smin_value = max(false_reg->smin_value, false_smin);
14223 true_reg->smax_value = min(true_reg->smax_value, true_smax);
14224 }
14225 break;
14226 }
14227 default:
14228 return;
14229 }
14230
14231 if (is_jmp32) {
14232 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14233 tnum_subreg(false_32off));
14234 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14235 tnum_subreg(true_32off));
14236 __reg_combine_32_into_64(false_reg);
14237 __reg_combine_32_into_64(true_reg);
14238 } else {
14239 false_reg->var_off = false_64off;
14240 true_reg->var_off = true_64off;
14241 __reg_combine_64_into_32(false_reg);
14242 __reg_combine_64_into_32(true_reg);
14243 }
14244 }
14245
14246 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14247 * the variable reg.
14248 */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u32 val32,u8 opcode,bool is_jmp32)14249 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14250 struct bpf_reg_state *false_reg,
14251 u64 val, u32 val32,
14252 u8 opcode, bool is_jmp32)
14253 {
14254 opcode = flip_opcode(opcode);
14255 /* This uses zero as "not present in table"; luckily the zero opcode,
14256 * BPF_JA, can't get here.
14257 */
14258 if (opcode)
14259 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14260 }
14261
14262 /* Regs are known to be equal, so intersect their min/max/var_off */
__reg_combine_min_max(struct bpf_reg_state * src_reg,struct bpf_reg_state * dst_reg)14263 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14264 struct bpf_reg_state *dst_reg)
14265 {
14266 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14267 dst_reg->umin_value);
14268 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14269 dst_reg->umax_value);
14270 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14271 dst_reg->smin_value);
14272 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14273 dst_reg->smax_value);
14274 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14275 dst_reg->var_off);
14276 reg_bounds_sync(src_reg);
14277 reg_bounds_sync(dst_reg);
14278 }
14279
reg_combine_min_max(struct bpf_reg_state * true_src,struct bpf_reg_state * true_dst,struct bpf_reg_state * false_src,struct bpf_reg_state * false_dst,u8 opcode)14280 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14281 struct bpf_reg_state *true_dst,
14282 struct bpf_reg_state *false_src,
14283 struct bpf_reg_state *false_dst,
14284 u8 opcode)
14285 {
14286 switch (opcode) {
14287 case BPF_JEQ:
14288 __reg_combine_min_max(true_src, true_dst);
14289 break;
14290 case BPF_JNE:
14291 __reg_combine_min_max(false_src, false_dst);
14292 break;
14293 }
14294 }
14295
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)14296 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14297 struct bpf_reg_state *reg, u32 id,
14298 bool is_null)
14299 {
14300 if (type_may_be_null(reg->type) && reg->id == id &&
14301 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14302 /* Old offset (both fixed and variable parts) should have been
14303 * known-zero, because we don't allow pointer arithmetic on
14304 * pointers that might be NULL. If we see this happening, don't
14305 * convert the register.
14306 *
14307 * But in some cases, some helpers that return local kptrs
14308 * advance offset for the returned pointer. In those cases, it
14309 * is fine to expect to see reg->off.
14310 */
14311 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14312 return;
14313 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14314 WARN_ON_ONCE(reg->off))
14315 return;
14316
14317 if (is_null) {
14318 reg->type = SCALAR_VALUE;
14319 /* We don't need id and ref_obj_id from this point
14320 * onwards anymore, thus we should better reset it,
14321 * so that state pruning has chances to take effect.
14322 */
14323 reg->id = 0;
14324 reg->ref_obj_id = 0;
14325
14326 return;
14327 }
14328
14329 mark_ptr_not_null_reg(reg);
14330
14331 if (!reg_may_point_to_spin_lock(reg)) {
14332 /* For not-NULL ptr, reg->ref_obj_id will be reset
14333 * in release_reference().
14334 *
14335 * reg->id is still used by spin_lock ptr. Other
14336 * than spin_lock ptr type, reg->id can be reset.
14337 */
14338 reg->id = 0;
14339 }
14340 }
14341 }
14342
14343 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14344 * be folded together at some point.
14345 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)14346 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14347 bool is_null)
14348 {
14349 struct bpf_func_state *state = vstate->frame[vstate->curframe];
14350 struct bpf_reg_state *regs = state->regs, *reg;
14351 u32 ref_obj_id = regs[regno].ref_obj_id;
14352 u32 id = regs[regno].id;
14353
14354 if (ref_obj_id && ref_obj_id == id && is_null)
14355 /* regs[regno] is in the " == NULL" branch.
14356 * No one could have freed the reference state before
14357 * doing the NULL check.
14358 */
14359 WARN_ON_ONCE(release_reference_state(state, id));
14360
14361 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14362 mark_ptr_or_null_reg(state, reg, id, is_null);
14363 }));
14364 }
14365
try_match_pkt_pointers(const struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,struct bpf_verifier_state * this_branch,struct bpf_verifier_state * other_branch)14366 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14367 struct bpf_reg_state *dst_reg,
14368 struct bpf_reg_state *src_reg,
14369 struct bpf_verifier_state *this_branch,
14370 struct bpf_verifier_state *other_branch)
14371 {
14372 if (BPF_SRC(insn->code) != BPF_X)
14373 return false;
14374
14375 /* Pointers are always 64-bit. */
14376 if (BPF_CLASS(insn->code) == BPF_JMP32)
14377 return false;
14378
14379 switch (BPF_OP(insn->code)) {
14380 case BPF_JGT:
14381 if ((dst_reg->type == PTR_TO_PACKET &&
14382 src_reg->type == PTR_TO_PACKET_END) ||
14383 (dst_reg->type == PTR_TO_PACKET_META &&
14384 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14385 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14386 find_good_pkt_pointers(this_branch, dst_reg,
14387 dst_reg->type, false);
14388 mark_pkt_end(other_branch, insn->dst_reg, true);
14389 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14390 src_reg->type == PTR_TO_PACKET) ||
14391 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14392 src_reg->type == PTR_TO_PACKET_META)) {
14393 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14394 find_good_pkt_pointers(other_branch, src_reg,
14395 src_reg->type, true);
14396 mark_pkt_end(this_branch, insn->src_reg, false);
14397 } else {
14398 return false;
14399 }
14400 break;
14401 case BPF_JLT:
14402 if ((dst_reg->type == PTR_TO_PACKET &&
14403 src_reg->type == PTR_TO_PACKET_END) ||
14404 (dst_reg->type == PTR_TO_PACKET_META &&
14405 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14406 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14407 find_good_pkt_pointers(other_branch, dst_reg,
14408 dst_reg->type, true);
14409 mark_pkt_end(this_branch, insn->dst_reg, false);
14410 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14411 src_reg->type == PTR_TO_PACKET) ||
14412 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14413 src_reg->type == PTR_TO_PACKET_META)) {
14414 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14415 find_good_pkt_pointers(this_branch, src_reg,
14416 src_reg->type, false);
14417 mark_pkt_end(other_branch, insn->src_reg, true);
14418 } else {
14419 return false;
14420 }
14421 break;
14422 case BPF_JGE:
14423 if ((dst_reg->type == PTR_TO_PACKET &&
14424 src_reg->type == PTR_TO_PACKET_END) ||
14425 (dst_reg->type == PTR_TO_PACKET_META &&
14426 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14427 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14428 find_good_pkt_pointers(this_branch, dst_reg,
14429 dst_reg->type, true);
14430 mark_pkt_end(other_branch, insn->dst_reg, false);
14431 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14432 src_reg->type == PTR_TO_PACKET) ||
14433 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14434 src_reg->type == PTR_TO_PACKET_META)) {
14435 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14436 find_good_pkt_pointers(other_branch, src_reg,
14437 src_reg->type, false);
14438 mark_pkt_end(this_branch, insn->src_reg, true);
14439 } else {
14440 return false;
14441 }
14442 break;
14443 case BPF_JLE:
14444 if ((dst_reg->type == PTR_TO_PACKET &&
14445 src_reg->type == PTR_TO_PACKET_END) ||
14446 (dst_reg->type == PTR_TO_PACKET_META &&
14447 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14448 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14449 find_good_pkt_pointers(other_branch, dst_reg,
14450 dst_reg->type, false);
14451 mark_pkt_end(this_branch, insn->dst_reg, true);
14452 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14453 src_reg->type == PTR_TO_PACKET) ||
14454 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14455 src_reg->type == PTR_TO_PACKET_META)) {
14456 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14457 find_good_pkt_pointers(this_branch, src_reg,
14458 src_reg->type, true);
14459 mark_pkt_end(other_branch, insn->src_reg, false);
14460 } else {
14461 return false;
14462 }
14463 break;
14464 default:
14465 return false;
14466 }
14467
14468 return true;
14469 }
14470
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)14471 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14472 struct bpf_reg_state *known_reg)
14473 {
14474 struct bpf_func_state *state;
14475 struct bpf_reg_state *reg;
14476
14477 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14478 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14479 copy_register_state(reg, known_reg);
14480 }));
14481 }
14482
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)14483 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14484 struct bpf_insn *insn, int *insn_idx)
14485 {
14486 struct bpf_verifier_state *this_branch = env->cur_state;
14487 struct bpf_verifier_state *other_branch;
14488 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14489 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14490 struct bpf_reg_state *eq_branch_regs;
14491 u8 opcode = BPF_OP(insn->code);
14492 bool is_jmp32;
14493 int pred = -1;
14494 int err;
14495
14496 /* Only conditional jumps are expected to reach here. */
14497 if (opcode == BPF_JA || opcode > BPF_JSLE) {
14498 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14499 return -EINVAL;
14500 }
14501
14502 /* check src2 operand */
14503 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14504 if (err)
14505 return err;
14506
14507 dst_reg = ®s[insn->dst_reg];
14508 if (BPF_SRC(insn->code) == BPF_X) {
14509 if (insn->imm != 0) {
14510 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14511 return -EINVAL;
14512 }
14513
14514 /* check src1 operand */
14515 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14516 if (err)
14517 return err;
14518
14519 src_reg = ®s[insn->src_reg];
14520 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14521 is_pointer_value(env, insn->src_reg)) {
14522 verbose(env, "R%d pointer comparison prohibited\n",
14523 insn->src_reg);
14524 return -EACCES;
14525 }
14526 } else {
14527 if (insn->src_reg != BPF_REG_0) {
14528 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14529 return -EINVAL;
14530 }
14531 }
14532
14533 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14534
14535 if (BPF_SRC(insn->code) == BPF_K) {
14536 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14537 } else if (src_reg->type == SCALAR_VALUE &&
14538 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14539 pred = is_branch_taken(dst_reg,
14540 tnum_subreg(src_reg->var_off).value,
14541 opcode,
14542 is_jmp32);
14543 } else if (src_reg->type == SCALAR_VALUE &&
14544 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14545 pred = is_branch_taken(dst_reg,
14546 src_reg->var_off.value,
14547 opcode,
14548 is_jmp32);
14549 } else if (dst_reg->type == SCALAR_VALUE &&
14550 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14551 pred = is_branch_taken(src_reg,
14552 tnum_subreg(dst_reg->var_off).value,
14553 flip_opcode(opcode),
14554 is_jmp32);
14555 } else if (dst_reg->type == SCALAR_VALUE &&
14556 !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14557 pred = is_branch_taken(src_reg,
14558 dst_reg->var_off.value,
14559 flip_opcode(opcode),
14560 is_jmp32);
14561 } else if (reg_is_pkt_pointer_any(dst_reg) &&
14562 reg_is_pkt_pointer_any(src_reg) &&
14563 !is_jmp32) {
14564 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14565 }
14566
14567 if (pred >= 0) {
14568 /* If we get here with a dst_reg pointer type it is because
14569 * above is_branch_taken() special cased the 0 comparison.
14570 */
14571 if (!__is_pointer_value(false, dst_reg))
14572 err = mark_chain_precision(env, insn->dst_reg);
14573 if (BPF_SRC(insn->code) == BPF_X && !err &&
14574 !__is_pointer_value(false, src_reg))
14575 err = mark_chain_precision(env, insn->src_reg);
14576 if (err)
14577 return err;
14578 }
14579
14580 if (pred == 1) {
14581 /* Only follow the goto, ignore fall-through. If needed, push
14582 * the fall-through branch for simulation under speculative
14583 * execution.
14584 */
14585 if (!env->bypass_spec_v1 &&
14586 !sanitize_speculative_path(env, insn, *insn_idx + 1,
14587 *insn_idx))
14588 return -EFAULT;
14589 if (env->log.level & BPF_LOG_LEVEL)
14590 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14591 *insn_idx += insn->off;
14592 return 0;
14593 } else if (pred == 0) {
14594 /* Only follow the fall-through branch, since that's where the
14595 * program will go. If needed, push the goto branch for
14596 * simulation under speculative execution.
14597 */
14598 if (!env->bypass_spec_v1 &&
14599 !sanitize_speculative_path(env, insn,
14600 *insn_idx + insn->off + 1,
14601 *insn_idx))
14602 return -EFAULT;
14603 if (env->log.level & BPF_LOG_LEVEL)
14604 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14605 return 0;
14606 }
14607
14608 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14609 false);
14610 if (!other_branch)
14611 return -EFAULT;
14612 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14613
14614 /* detect if we are comparing against a constant value so we can adjust
14615 * our min/max values for our dst register.
14616 * this is only legit if both are scalars (or pointers to the same
14617 * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14618 * because otherwise the different base pointers mean the offsets aren't
14619 * comparable.
14620 */
14621 if (BPF_SRC(insn->code) == BPF_X) {
14622 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
14623
14624 if (dst_reg->type == SCALAR_VALUE &&
14625 src_reg->type == SCALAR_VALUE) {
14626 if (tnum_is_const(src_reg->var_off) ||
14627 (is_jmp32 &&
14628 tnum_is_const(tnum_subreg(src_reg->var_off))))
14629 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14630 dst_reg,
14631 src_reg->var_off.value,
14632 tnum_subreg(src_reg->var_off).value,
14633 opcode, is_jmp32);
14634 else if (tnum_is_const(dst_reg->var_off) ||
14635 (is_jmp32 &&
14636 tnum_is_const(tnum_subreg(dst_reg->var_off))))
14637 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14638 src_reg,
14639 dst_reg->var_off.value,
14640 tnum_subreg(dst_reg->var_off).value,
14641 opcode, is_jmp32);
14642 else if (!is_jmp32 &&
14643 (opcode == BPF_JEQ || opcode == BPF_JNE))
14644 /* Comparing for equality, we can combine knowledge */
14645 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14646 &other_branch_regs[insn->dst_reg],
14647 src_reg, dst_reg, opcode);
14648 if (src_reg->id &&
14649 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14650 find_equal_scalars(this_branch, src_reg);
14651 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14652 }
14653
14654 }
14655 } else if (dst_reg->type == SCALAR_VALUE) {
14656 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14657 dst_reg, insn->imm, (u32)insn->imm,
14658 opcode, is_jmp32);
14659 }
14660
14661 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14662 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14663 find_equal_scalars(this_branch, dst_reg);
14664 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14665 }
14666
14667 /* if one pointer register is compared to another pointer
14668 * register check if PTR_MAYBE_NULL could be lifted.
14669 * E.g. register A - maybe null
14670 * register B - not null
14671 * for JNE A, B, ... - A is not null in the false branch;
14672 * for JEQ A, B, ... - A is not null in the true branch.
14673 *
14674 * Since PTR_TO_BTF_ID points to a kernel struct that does
14675 * not need to be null checked by the BPF program, i.e.,
14676 * could be null even without PTR_MAYBE_NULL marking, so
14677 * only propagate nullness when neither reg is that type.
14678 */
14679 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14680 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14681 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14682 base_type(src_reg->type) != PTR_TO_BTF_ID &&
14683 base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14684 eq_branch_regs = NULL;
14685 switch (opcode) {
14686 case BPF_JEQ:
14687 eq_branch_regs = other_branch_regs;
14688 break;
14689 case BPF_JNE:
14690 eq_branch_regs = regs;
14691 break;
14692 default:
14693 /* do nothing */
14694 break;
14695 }
14696 if (eq_branch_regs) {
14697 if (type_may_be_null(src_reg->type))
14698 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14699 else
14700 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14701 }
14702 }
14703
14704 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14705 * NOTE: these optimizations below are related with pointer comparison
14706 * which will never be JMP32.
14707 */
14708 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14709 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14710 type_may_be_null(dst_reg->type)) {
14711 /* Mark all identical registers in each branch as either
14712 * safe or unknown depending R == 0 or R != 0 conditional.
14713 */
14714 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14715 opcode == BPF_JNE);
14716 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14717 opcode == BPF_JEQ);
14718 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
14719 this_branch, other_branch) &&
14720 is_pointer_value(env, insn->dst_reg)) {
14721 verbose(env, "R%d pointer comparison prohibited\n",
14722 insn->dst_reg);
14723 return -EACCES;
14724 }
14725 if (env->log.level & BPF_LOG_LEVEL)
14726 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14727 return 0;
14728 }
14729
14730 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)14731 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14732 {
14733 struct bpf_insn_aux_data *aux = cur_aux(env);
14734 struct bpf_reg_state *regs = cur_regs(env);
14735 struct bpf_reg_state *dst_reg;
14736 struct bpf_map *map;
14737 int err;
14738
14739 if (BPF_SIZE(insn->code) != BPF_DW) {
14740 verbose(env, "invalid BPF_LD_IMM insn\n");
14741 return -EINVAL;
14742 }
14743 if (insn->off != 0) {
14744 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14745 return -EINVAL;
14746 }
14747
14748 err = check_reg_arg(env, insn->dst_reg, DST_OP);
14749 if (err)
14750 return err;
14751
14752 dst_reg = ®s[insn->dst_reg];
14753 if (insn->src_reg == 0) {
14754 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14755
14756 dst_reg->type = SCALAR_VALUE;
14757 __mark_reg_known(®s[insn->dst_reg], imm);
14758 return 0;
14759 }
14760
14761 /* All special src_reg cases are listed below. From this point onwards
14762 * we either succeed and assign a corresponding dst_reg->type after
14763 * zeroing the offset, or fail and reject the program.
14764 */
14765 mark_reg_known_zero(env, regs, insn->dst_reg);
14766
14767 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14768 dst_reg->type = aux->btf_var.reg_type;
14769 switch (base_type(dst_reg->type)) {
14770 case PTR_TO_MEM:
14771 dst_reg->mem_size = aux->btf_var.mem_size;
14772 break;
14773 case PTR_TO_BTF_ID:
14774 dst_reg->btf = aux->btf_var.btf;
14775 dst_reg->btf_id = aux->btf_var.btf_id;
14776 break;
14777 default:
14778 verbose(env, "bpf verifier is misconfigured\n");
14779 return -EFAULT;
14780 }
14781 return 0;
14782 }
14783
14784 if (insn->src_reg == BPF_PSEUDO_FUNC) {
14785 struct bpf_prog_aux *aux = env->prog->aux;
14786 u32 subprogno = find_subprog(env,
14787 env->insn_idx + insn->imm + 1);
14788
14789 if (!aux->func_info) {
14790 verbose(env, "missing btf func_info\n");
14791 return -EINVAL;
14792 }
14793 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14794 verbose(env, "callback function not static\n");
14795 return -EINVAL;
14796 }
14797
14798 dst_reg->type = PTR_TO_FUNC;
14799 dst_reg->subprogno = subprogno;
14800 return 0;
14801 }
14802
14803 map = env->used_maps[aux->map_index];
14804 dst_reg->map_ptr = map;
14805
14806 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14807 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14808 dst_reg->type = PTR_TO_MAP_VALUE;
14809 dst_reg->off = aux->map_off;
14810 WARN_ON_ONCE(map->max_entries != 1);
14811 /* We want reg->id to be same (0) as map_value is not distinct */
14812 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14813 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14814 dst_reg->type = CONST_PTR_TO_MAP;
14815 } else {
14816 verbose(env, "bpf verifier is misconfigured\n");
14817 return -EINVAL;
14818 }
14819
14820 return 0;
14821 }
14822
may_access_skb(enum bpf_prog_type type)14823 static bool may_access_skb(enum bpf_prog_type type)
14824 {
14825 switch (type) {
14826 case BPF_PROG_TYPE_SOCKET_FILTER:
14827 case BPF_PROG_TYPE_SCHED_CLS:
14828 case BPF_PROG_TYPE_SCHED_ACT:
14829 return true;
14830 default:
14831 return false;
14832 }
14833 }
14834
14835 /* verify safety of LD_ABS|LD_IND instructions:
14836 * - they can only appear in the programs where ctx == skb
14837 * - since they are wrappers of function calls, they scratch R1-R5 registers,
14838 * preserve R6-R9, and store return value into R0
14839 *
14840 * Implicit input:
14841 * ctx == skb == R6 == CTX
14842 *
14843 * Explicit input:
14844 * SRC == any register
14845 * IMM == 32-bit immediate
14846 *
14847 * Output:
14848 * R0 - 8/16/32-bit skb data converted to cpu endianness
14849 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)14850 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14851 {
14852 struct bpf_reg_state *regs = cur_regs(env);
14853 static const int ctx_reg = BPF_REG_6;
14854 u8 mode = BPF_MODE(insn->code);
14855 int i, err;
14856
14857 if (!may_access_skb(resolve_prog_type(env->prog))) {
14858 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14859 return -EINVAL;
14860 }
14861
14862 if (!env->ops->gen_ld_abs) {
14863 verbose(env, "bpf verifier is misconfigured\n");
14864 return -EINVAL;
14865 }
14866
14867 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14868 BPF_SIZE(insn->code) == BPF_DW ||
14869 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14870 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14871 return -EINVAL;
14872 }
14873
14874 /* check whether implicit source operand (register R6) is readable */
14875 err = check_reg_arg(env, ctx_reg, SRC_OP);
14876 if (err)
14877 return err;
14878
14879 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14880 * gen_ld_abs() may terminate the program at runtime, leading to
14881 * reference leak.
14882 */
14883 err = check_reference_leak(env);
14884 if (err) {
14885 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14886 return err;
14887 }
14888
14889 if (env->cur_state->active_lock.ptr) {
14890 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14891 return -EINVAL;
14892 }
14893
14894 if (env->cur_state->active_rcu_lock) {
14895 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14896 return -EINVAL;
14897 }
14898
14899 if (regs[ctx_reg].type != PTR_TO_CTX) {
14900 verbose(env,
14901 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14902 return -EINVAL;
14903 }
14904
14905 if (mode == BPF_IND) {
14906 /* check explicit source operand */
14907 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14908 if (err)
14909 return err;
14910 }
14911
14912 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
14913 if (err < 0)
14914 return err;
14915
14916 /* reset caller saved regs to unreadable */
14917 for (i = 0; i < CALLER_SAVED_REGS; i++) {
14918 mark_reg_not_init(env, regs, caller_saved[i]);
14919 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14920 }
14921
14922 /* mark destination R0 register as readable, since it contains
14923 * the value fetched from the packet.
14924 * Already marked as written above.
14925 */
14926 mark_reg_unknown(env, regs, BPF_REG_0);
14927 /* ld_abs load up to 32-bit skb data. */
14928 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14929 return 0;
14930 }
14931
check_return_code(struct bpf_verifier_env * env)14932 static int check_return_code(struct bpf_verifier_env *env)
14933 {
14934 struct tnum enforce_attach_type_range = tnum_unknown;
14935 const struct bpf_prog *prog = env->prog;
14936 struct bpf_reg_state *reg;
14937 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14938 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14939 int err;
14940 struct bpf_func_state *frame = env->cur_state->frame[0];
14941 const bool is_subprog = frame->subprogno;
14942
14943 /* LSM and struct_ops func-ptr's return type could be "void" */
14944 if (!is_subprog) {
14945 switch (prog_type) {
14946 case BPF_PROG_TYPE_LSM:
14947 if (prog->expected_attach_type == BPF_LSM_CGROUP)
14948 /* See below, can be 0 or 0-1 depending on hook. */
14949 break;
14950 fallthrough;
14951 case BPF_PROG_TYPE_STRUCT_OPS:
14952 if (!prog->aux->attach_func_proto->type)
14953 return 0;
14954 break;
14955 default:
14956 break;
14957 }
14958 }
14959
14960 /* eBPF calling convention is such that R0 is used
14961 * to return the value from eBPF program.
14962 * Make sure that it's readable at this time
14963 * of bpf_exit, which means that program wrote
14964 * something into it earlier
14965 */
14966 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14967 if (err)
14968 return err;
14969
14970 if (is_pointer_value(env, BPF_REG_0)) {
14971 verbose(env, "R0 leaks addr as return value\n");
14972 return -EACCES;
14973 }
14974
14975 reg = cur_regs(env) + BPF_REG_0;
14976
14977 if (frame->in_async_callback_fn) {
14978 /* enforce return zero from async callbacks like timer */
14979 if (reg->type != SCALAR_VALUE) {
14980 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14981 reg_type_str(env, reg->type));
14982 return -EINVAL;
14983 }
14984
14985 if (!tnum_in(const_0, reg->var_off)) {
14986 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14987 return -EINVAL;
14988 }
14989 return 0;
14990 }
14991
14992 if (is_subprog) {
14993 if (reg->type != SCALAR_VALUE) {
14994 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14995 reg_type_str(env, reg->type));
14996 return -EINVAL;
14997 }
14998 return 0;
14999 }
15000
15001 switch (prog_type) {
15002 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15003 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15004 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15005 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15006 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15007 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15008 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
15009 range = tnum_range(1, 1);
15010 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15011 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15012 range = tnum_range(0, 3);
15013 break;
15014 case BPF_PROG_TYPE_CGROUP_SKB:
15015 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15016 range = tnum_range(0, 3);
15017 enforce_attach_type_range = tnum_range(2, 3);
15018 }
15019 break;
15020 case BPF_PROG_TYPE_CGROUP_SOCK:
15021 case BPF_PROG_TYPE_SOCK_OPS:
15022 case BPF_PROG_TYPE_CGROUP_DEVICE:
15023 case BPF_PROG_TYPE_CGROUP_SYSCTL:
15024 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15025 break;
15026 case BPF_PROG_TYPE_RAW_TRACEPOINT:
15027 if (!env->prog->aux->attach_btf_id)
15028 return 0;
15029 range = tnum_const(0);
15030 break;
15031 case BPF_PROG_TYPE_TRACING:
15032 switch (env->prog->expected_attach_type) {
15033 case BPF_TRACE_FENTRY:
15034 case BPF_TRACE_FEXIT:
15035 range = tnum_const(0);
15036 break;
15037 case BPF_TRACE_RAW_TP:
15038 case BPF_MODIFY_RETURN:
15039 return 0;
15040 case BPF_TRACE_ITER:
15041 break;
15042 default:
15043 return -ENOTSUPP;
15044 }
15045 break;
15046 case BPF_PROG_TYPE_SK_LOOKUP:
15047 range = tnum_range(SK_DROP, SK_PASS);
15048 break;
15049
15050 case BPF_PROG_TYPE_LSM:
15051 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15052 /* Regular BPF_PROG_TYPE_LSM programs can return
15053 * any value.
15054 */
15055 return 0;
15056 }
15057 if (!env->prog->aux->attach_func_proto->type) {
15058 /* Make sure programs that attach to void
15059 * hooks don't try to modify return value.
15060 */
15061 range = tnum_range(1, 1);
15062 }
15063 break;
15064
15065 case BPF_PROG_TYPE_NETFILTER:
15066 range = tnum_range(NF_DROP, NF_ACCEPT);
15067 break;
15068 case BPF_PROG_TYPE_EXT:
15069 /* freplace program can return anything as its return value
15070 * depends on the to-be-replaced kernel func or bpf program.
15071 */
15072 default:
15073 return 0;
15074 }
15075
15076 if (reg->type != SCALAR_VALUE) {
15077 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
15078 reg_type_str(env, reg->type));
15079 return -EINVAL;
15080 }
15081
15082 if (!tnum_in(range, reg->var_off)) {
15083 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15084 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15085 prog_type == BPF_PROG_TYPE_LSM &&
15086 !prog->aux->attach_func_proto->type)
15087 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15088 return -EINVAL;
15089 }
15090
15091 if (!tnum_is_unknown(enforce_attach_type_range) &&
15092 tnum_in(enforce_attach_type_range, reg->var_off))
15093 env->prog->enforce_expected_attach_type = 1;
15094 return 0;
15095 }
15096
15097 /* non-recursive DFS pseudo code
15098 * 1 procedure DFS-iterative(G,v):
15099 * 2 label v as discovered
15100 * 3 let S be a stack
15101 * 4 S.push(v)
15102 * 5 while S is not empty
15103 * 6 t <- S.peek()
15104 * 7 if t is what we're looking for:
15105 * 8 return t
15106 * 9 for all edges e in G.adjacentEdges(t) do
15107 * 10 if edge e is already labelled
15108 * 11 continue with the next edge
15109 * 12 w <- G.adjacentVertex(t,e)
15110 * 13 if vertex w is not discovered and not explored
15111 * 14 label e as tree-edge
15112 * 15 label w as discovered
15113 * 16 S.push(w)
15114 * 17 continue at 5
15115 * 18 else if vertex w is discovered
15116 * 19 label e as back-edge
15117 * 20 else
15118 * 21 // vertex w is explored
15119 * 22 label e as forward- or cross-edge
15120 * 23 label t as explored
15121 * 24 S.pop()
15122 *
15123 * convention:
15124 * 0x10 - discovered
15125 * 0x11 - discovered and fall-through edge labelled
15126 * 0x12 - discovered and fall-through and branch edges labelled
15127 * 0x20 - explored
15128 */
15129
15130 enum {
15131 DISCOVERED = 0x10,
15132 EXPLORED = 0x20,
15133 FALLTHROUGH = 1,
15134 BRANCH = 2,
15135 };
15136
mark_prune_point(struct bpf_verifier_env * env,int idx)15137 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15138 {
15139 env->insn_aux_data[idx].prune_point = true;
15140 }
15141
is_prune_point(struct bpf_verifier_env * env,int insn_idx)15142 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15143 {
15144 return env->insn_aux_data[insn_idx].prune_point;
15145 }
15146
mark_force_checkpoint(struct bpf_verifier_env * env,int idx)15147 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15148 {
15149 env->insn_aux_data[idx].force_checkpoint = true;
15150 }
15151
is_force_checkpoint(struct bpf_verifier_env * env,int insn_idx)15152 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15153 {
15154 return env->insn_aux_data[insn_idx].force_checkpoint;
15155 }
15156
mark_calls_callback(struct bpf_verifier_env * env,int idx)15157 static void mark_calls_callback(struct bpf_verifier_env *env, int idx)
15158 {
15159 env->insn_aux_data[idx].calls_callback = true;
15160 }
15161
calls_callback(struct bpf_verifier_env * env,int insn_idx)15162 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx)
15163 {
15164 return env->insn_aux_data[insn_idx].calls_callback;
15165 }
15166
15167 enum {
15168 DONE_EXPLORING = 0,
15169 KEEP_EXPLORING = 1,
15170 };
15171
15172 /* t, w, e - match pseudo-code above:
15173 * t - index of current instruction
15174 * w - next instruction
15175 * e - edge
15176 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)15177 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
15178 {
15179 int *insn_stack = env->cfg.insn_stack;
15180 int *insn_state = env->cfg.insn_state;
15181
15182 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15183 return DONE_EXPLORING;
15184
15185 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15186 return DONE_EXPLORING;
15187
15188 if (w < 0 || w >= env->prog->len) {
15189 verbose_linfo(env, t, "%d: ", t);
15190 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15191 return -EINVAL;
15192 }
15193
15194 if (e == BRANCH) {
15195 /* mark branch target for state pruning */
15196 mark_prune_point(env, w);
15197 mark_jmp_point(env, w);
15198 }
15199
15200 if (insn_state[w] == 0) {
15201 /* tree-edge */
15202 insn_state[t] = DISCOVERED | e;
15203 insn_state[w] = DISCOVERED;
15204 if (env->cfg.cur_stack >= env->prog->len)
15205 return -E2BIG;
15206 insn_stack[env->cfg.cur_stack++] = w;
15207 return KEEP_EXPLORING;
15208 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15209 if (env->bpf_capable)
15210 return DONE_EXPLORING;
15211 verbose_linfo(env, t, "%d: ", t);
15212 verbose_linfo(env, w, "%d: ", w);
15213 verbose(env, "back-edge from insn %d to %d\n", t, w);
15214 return -EINVAL;
15215 } else if (insn_state[w] == EXPLORED) {
15216 /* forward- or cross-edge */
15217 insn_state[t] = DISCOVERED | e;
15218 } else {
15219 verbose(env, "insn state internal bug\n");
15220 return -EFAULT;
15221 }
15222 return DONE_EXPLORING;
15223 }
15224
visit_func_call_insn(int t,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)15225 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15226 struct bpf_verifier_env *env,
15227 bool visit_callee)
15228 {
15229 int ret, insn_sz;
15230
15231 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
15232 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
15233 if (ret)
15234 return ret;
15235
15236 mark_prune_point(env, t + insn_sz);
15237 /* when we exit from subprog, we need to record non-linear history */
15238 mark_jmp_point(env, t + insn_sz);
15239
15240 if (visit_callee) {
15241 mark_prune_point(env, t);
15242 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
15243 }
15244 return ret;
15245 }
15246
15247 /* Visits the instruction at index t and returns one of the following:
15248 * < 0 - an error occurred
15249 * DONE_EXPLORING - the instruction was fully explored
15250 * KEEP_EXPLORING - there is still work to be done before it is fully explored
15251 */
visit_insn(int t,struct bpf_verifier_env * env)15252 static int visit_insn(int t, struct bpf_verifier_env *env)
15253 {
15254 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15255 int ret, off, insn_sz;
15256
15257 if (bpf_pseudo_func(insn))
15258 return visit_func_call_insn(t, insns, env, true);
15259
15260 /* All non-branch instructions have a single fall-through edge. */
15261 if (BPF_CLASS(insn->code) != BPF_JMP &&
15262 BPF_CLASS(insn->code) != BPF_JMP32) {
15263 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
15264 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
15265 }
15266
15267 switch (BPF_OP(insn->code)) {
15268 case BPF_EXIT:
15269 return DONE_EXPLORING;
15270
15271 case BPF_CALL:
15272 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15273 /* Mark this call insn as a prune point to trigger
15274 * is_state_visited() check before call itself is
15275 * processed by __check_func_call(). Otherwise new
15276 * async state will be pushed for further exploration.
15277 */
15278 mark_prune_point(env, t);
15279 /* For functions that invoke callbacks it is not known how many times
15280 * callback would be called. Verifier models callback calling functions
15281 * by repeatedly visiting callback bodies and returning to origin call
15282 * instruction.
15283 * In order to stop such iteration verifier needs to identify when a
15284 * state identical some state from a previous iteration is reached.
15285 * Check below forces creation of checkpoint before callback calling
15286 * instruction to allow search for such identical states.
15287 */
15288 if (is_sync_callback_calling_insn(insn)) {
15289 mark_calls_callback(env, t);
15290 mark_force_checkpoint(env, t);
15291 mark_prune_point(env, t);
15292 mark_jmp_point(env, t);
15293 }
15294 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15295 struct bpf_kfunc_call_arg_meta meta;
15296
15297 ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15298 if (ret == 0 && is_iter_next_kfunc(&meta)) {
15299 mark_prune_point(env, t);
15300 /* Checking and saving state checkpoints at iter_next() call
15301 * is crucial for fast convergence of open-coded iterator loop
15302 * logic, so we need to force it. If we don't do that,
15303 * is_state_visited() might skip saving a checkpoint, causing
15304 * unnecessarily long sequence of not checkpointed
15305 * instructions and jumps, leading to exhaustion of jump
15306 * history buffer, and potentially other undesired outcomes.
15307 * It is expected that with correct open-coded iterators
15308 * convergence will happen quickly, so we don't run a risk of
15309 * exhausting memory.
15310 */
15311 mark_force_checkpoint(env, t);
15312 }
15313 }
15314 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15315
15316 case BPF_JA:
15317 if (BPF_SRC(insn->code) != BPF_K)
15318 return -EINVAL;
15319
15320 if (BPF_CLASS(insn->code) == BPF_JMP)
15321 off = insn->off;
15322 else
15323 off = insn->imm;
15324
15325 /* unconditional jump with single edge */
15326 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
15327 if (ret)
15328 return ret;
15329
15330 mark_prune_point(env, t + off + 1);
15331 mark_jmp_point(env, t + off + 1);
15332
15333 return ret;
15334
15335 default:
15336 /* conditional jump with two edges */
15337 mark_prune_point(env, t);
15338
15339 ret = push_insn(t, t + 1, FALLTHROUGH, env);
15340 if (ret)
15341 return ret;
15342
15343 return push_insn(t, t + insn->off + 1, BRANCH, env);
15344 }
15345 }
15346
15347 /* non-recursive depth-first-search to detect loops in BPF program
15348 * loop == back-edge in directed graph
15349 */
check_cfg(struct bpf_verifier_env * env)15350 static int check_cfg(struct bpf_verifier_env *env)
15351 {
15352 int insn_cnt = env->prog->len;
15353 int *insn_stack, *insn_state;
15354 int ret = 0;
15355 int i;
15356
15357 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15358 if (!insn_state)
15359 return -ENOMEM;
15360
15361 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15362 if (!insn_stack) {
15363 kvfree(insn_state);
15364 return -ENOMEM;
15365 }
15366
15367 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15368 insn_stack[0] = 0; /* 0 is the first instruction */
15369 env->cfg.cur_stack = 1;
15370
15371 while (env->cfg.cur_stack > 0) {
15372 int t = insn_stack[env->cfg.cur_stack - 1];
15373
15374 ret = visit_insn(t, env);
15375 switch (ret) {
15376 case DONE_EXPLORING:
15377 insn_state[t] = EXPLORED;
15378 env->cfg.cur_stack--;
15379 break;
15380 case KEEP_EXPLORING:
15381 break;
15382 default:
15383 if (ret > 0) {
15384 verbose(env, "visit_insn internal bug\n");
15385 ret = -EFAULT;
15386 }
15387 goto err_free;
15388 }
15389 }
15390
15391 if (env->cfg.cur_stack < 0) {
15392 verbose(env, "pop stack internal bug\n");
15393 ret = -EFAULT;
15394 goto err_free;
15395 }
15396
15397 for (i = 0; i < insn_cnt; i++) {
15398 struct bpf_insn *insn = &env->prog->insnsi[i];
15399
15400 if (insn_state[i] != EXPLORED) {
15401 verbose(env, "unreachable insn %d\n", i);
15402 ret = -EINVAL;
15403 goto err_free;
15404 }
15405 if (bpf_is_ldimm64(insn)) {
15406 if (insn_state[i + 1] != 0) {
15407 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
15408 ret = -EINVAL;
15409 goto err_free;
15410 }
15411 i++; /* skip second half of ldimm64 */
15412 }
15413 }
15414 ret = 0; /* cfg looks good */
15415
15416 err_free:
15417 kvfree(insn_state);
15418 kvfree(insn_stack);
15419 env->cfg.insn_state = env->cfg.insn_stack = NULL;
15420 return ret;
15421 }
15422
check_abnormal_return(struct bpf_verifier_env * env)15423 static int check_abnormal_return(struct bpf_verifier_env *env)
15424 {
15425 int i;
15426
15427 for (i = 1; i < env->subprog_cnt; i++) {
15428 if (env->subprog_info[i].has_ld_abs) {
15429 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15430 return -EINVAL;
15431 }
15432 if (env->subprog_info[i].has_tail_call) {
15433 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15434 return -EINVAL;
15435 }
15436 }
15437 return 0;
15438 }
15439
15440 /* The minimum supported BTF func info size */
15441 #define MIN_BPF_FUNCINFO_SIZE 8
15442 #define MAX_FUNCINFO_REC_SIZE 252
15443
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15444 static int check_btf_func(struct bpf_verifier_env *env,
15445 const union bpf_attr *attr,
15446 bpfptr_t uattr)
15447 {
15448 const struct btf_type *type, *func_proto, *ret_type;
15449 u32 i, nfuncs, urec_size, min_size;
15450 u32 krec_size = sizeof(struct bpf_func_info);
15451 struct bpf_func_info *krecord;
15452 struct bpf_func_info_aux *info_aux = NULL;
15453 struct bpf_prog *prog;
15454 const struct btf *btf;
15455 bpfptr_t urecord;
15456 u32 prev_offset = 0;
15457 bool scalar_return;
15458 int ret = -ENOMEM;
15459
15460 nfuncs = attr->func_info_cnt;
15461 if (!nfuncs) {
15462 if (check_abnormal_return(env))
15463 return -EINVAL;
15464 return 0;
15465 }
15466
15467 if (nfuncs != env->subprog_cnt) {
15468 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15469 return -EINVAL;
15470 }
15471
15472 urec_size = attr->func_info_rec_size;
15473 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15474 urec_size > MAX_FUNCINFO_REC_SIZE ||
15475 urec_size % sizeof(u32)) {
15476 verbose(env, "invalid func info rec size %u\n", urec_size);
15477 return -EINVAL;
15478 }
15479
15480 prog = env->prog;
15481 btf = prog->aux->btf;
15482
15483 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15484 min_size = min_t(u32, krec_size, urec_size);
15485
15486 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15487 if (!krecord)
15488 return -ENOMEM;
15489 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15490 if (!info_aux)
15491 goto err_free;
15492
15493 for (i = 0; i < nfuncs; i++) {
15494 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15495 if (ret) {
15496 if (ret == -E2BIG) {
15497 verbose(env, "nonzero tailing record in func info");
15498 /* set the size kernel expects so loader can zero
15499 * out the rest of the record.
15500 */
15501 if (copy_to_bpfptr_offset(uattr,
15502 offsetof(union bpf_attr, func_info_rec_size),
15503 &min_size, sizeof(min_size)))
15504 ret = -EFAULT;
15505 }
15506 goto err_free;
15507 }
15508
15509 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15510 ret = -EFAULT;
15511 goto err_free;
15512 }
15513
15514 /* check insn_off */
15515 ret = -EINVAL;
15516 if (i == 0) {
15517 if (krecord[i].insn_off) {
15518 verbose(env,
15519 "nonzero insn_off %u for the first func info record",
15520 krecord[i].insn_off);
15521 goto err_free;
15522 }
15523 } else if (krecord[i].insn_off <= prev_offset) {
15524 verbose(env,
15525 "same or smaller insn offset (%u) than previous func info record (%u)",
15526 krecord[i].insn_off, prev_offset);
15527 goto err_free;
15528 }
15529
15530 if (env->subprog_info[i].start != krecord[i].insn_off) {
15531 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15532 goto err_free;
15533 }
15534
15535 /* check type_id */
15536 type = btf_type_by_id(btf, krecord[i].type_id);
15537 if (!type || !btf_type_is_func(type)) {
15538 verbose(env, "invalid type id %d in func info",
15539 krecord[i].type_id);
15540 goto err_free;
15541 }
15542 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15543
15544 func_proto = btf_type_by_id(btf, type->type);
15545 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15546 /* btf_func_check() already verified it during BTF load */
15547 goto err_free;
15548 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15549 scalar_return =
15550 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15551 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15552 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15553 goto err_free;
15554 }
15555 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15556 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15557 goto err_free;
15558 }
15559
15560 prev_offset = krecord[i].insn_off;
15561 bpfptr_add(&urecord, urec_size);
15562 }
15563
15564 prog->aux->func_info = krecord;
15565 prog->aux->func_info_cnt = nfuncs;
15566 prog->aux->func_info_aux = info_aux;
15567 return 0;
15568
15569 err_free:
15570 kvfree(krecord);
15571 kfree(info_aux);
15572 return ret;
15573 }
15574
adjust_btf_func(struct bpf_verifier_env * env)15575 static void adjust_btf_func(struct bpf_verifier_env *env)
15576 {
15577 struct bpf_prog_aux *aux = env->prog->aux;
15578 int i;
15579
15580 if (!aux->func_info)
15581 return;
15582
15583 for (i = 0; i < env->subprog_cnt; i++)
15584 aux->func_info[i].insn_off = env->subprog_info[i].start;
15585 }
15586
15587 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
15588 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
15589
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15590 static int check_btf_line(struct bpf_verifier_env *env,
15591 const union bpf_attr *attr,
15592 bpfptr_t uattr)
15593 {
15594 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15595 struct bpf_subprog_info *sub;
15596 struct bpf_line_info *linfo;
15597 struct bpf_prog *prog;
15598 const struct btf *btf;
15599 bpfptr_t ulinfo;
15600 int err;
15601
15602 nr_linfo = attr->line_info_cnt;
15603 if (!nr_linfo)
15604 return 0;
15605 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15606 return -EINVAL;
15607
15608 rec_size = attr->line_info_rec_size;
15609 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15610 rec_size > MAX_LINEINFO_REC_SIZE ||
15611 rec_size & (sizeof(u32) - 1))
15612 return -EINVAL;
15613
15614 /* Need to zero it in case the userspace may
15615 * pass in a smaller bpf_line_info object.
15616 */
15617 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15618 GFP_KERNEL | __GFP_NOWARN);
15619 if (!linfo)
15620 return -ENOMEM;
15621
15622 prog = env->prog;
15623 btf = prog->aux->btf;
15624
15625 s = 0;
15626 sub = env->subprog_info;
15627 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15628 expected_size = sizeof(struct bpf_line_info);
15629 ncopy = min_t(u32, expected_size, rec_size);
15630 for (i = 0; i < nr_linfo; i++) {
15631 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15632 if (err) {
15633 if (err == -E2BIG) {
15634 verbose(env, "nonzero tailing record in line_info");
15635 if (copy_to_bpfptr_offset(uattr,
15636 offsetof(union bpf_attr, line_info_rec_size),
15637 &expected_size, sizeof(expected_size)))
15638 err = -EFAULT;
15639 }
15640 goto err_free;
15641 }
15642
15643 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15644 err = -EFAULT;
15645 goto err_free;
15646 }
15647
15648 /*
15649 * Check insn_off to ensure
15650 * 1) strictly increasing AND
15651 * 2) bounded by prog->len
15652 *
15653 * The linfo[0].insn_off == 0 check logically falls into
15654 * the later "missing bpf_line_info for func..." case
15655 * because the first linfo[0].insn_off must be the
15656 * first sub also and the first sub must have
15657 * subprog_info[0].start == 0.
15658 */
15659 if ((i && linfo[i].insn_off <= prev_offset) ||
15660 linfo[i].insn_off >= prog->len) {
15661 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15662 i, linfo[i].insn_off, prev_offset,
15663 prog->len);
15664 err = -EINVAL;
15665 goto err_free;
15666 }
15667
15668 if (!prog->insnsi[linfo[i].insn_off].code) {
15669 verbose(env,
15670 "Invalid insn code at line_info[%u].insn_off\n",
15671 i);
15672 err = -EINVAL;
15673 goto err_free;
15674 }
15675
15676 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15677 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15678 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15679 err = -EINVAL;
15680 goto err_free;
15681 }
15682
15683 if (s != env->subprog_cnt) {
15684 if (linfo[i].insn_off == sub[s].start) {
15685 sub[s].linfo_idx = i;
15686 s++;
15687 } else if (sub[s].start < linfo[i].insn_off) {
15688 verbose(env, "missing bpf_line_info for func#%u\n", s);
15689 err = -EINVAL;
15690 goto err_free;
15691 }
15692 }
15693
15694 prev_offset = linfo[i].insn_off;
15695 bpfptr_add(&ulinfo, rec_size);
15696 }
15697
15698 if (s != env->subprog_cnt) {
15699 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15700 env->subprog_cnt - s, s);
15701 err = -EINVAL;
15702 goto err_free;
15703 }
15704
15705 prog->aux->linfo = linfo;
15706 prog->aux->nr_linfo = nr_linfo;
15707
15708 return 0;
15709
15710 err_free:
15711 kvfree(linfo);
15712 return err;
15713 }
15714
15715 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
15716 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
15717
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15718 static int check_core_relo(struct bpf_verifier_env *env,
15719 const union bpf_attr *attr,
15720 bpfptr_t uattr)
15721 {
15722 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15723 struct bpf_core_relo core_relo = {};
15724 struct bpf_prog *prog = env->prog;
15725 const struct btf *btf = prog->aux->btf;
15726 struct bpf_core_ctx ctx = {
15727 .log = &env->log,
15728 .btf = btf,
15729 };
15730 bpfptr_t u_core_relo;
15731 int err;
15732
15733 nr_core_relo = attr->core_relo_cnt;
15734 if (!nr_core_relo)
15735 return 0;
15736 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15737 return -EINVAL;
15738
15739 rec_size = attr->core_relo_rec_size;
15740 if (rec_size < MIN_CORE_RELO_SIZE ||
15741 rec_size > MAX_CORE_RELO_SIZE ||
15742 rec_size % sizeof(u32))
15743 return -EINVAL;
15744
15745 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15746 expected_size = sizeof(struct bpf_core_relo);
15747 ncopy = min_t(u32, expected_size, rec_size);
15748
15749 /* Unlike func_info and line_info, copy and apply each CO-RE
15750 * relocation record one at a time.
15751 */
15752 for (i = 0; i < nr_core_relo; i++) {
15753 /* future proofing when sizeof(bpf_core_relo) changes */
15754 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15755 if (err) {
15756 if (err == -E2BIG) {
15757 verbose(env, "nonzero tailing record in core_relo");
15758 if (copy_to_bpfptr_offset(uattr,
15759 offsetof(union bpf_attr, core_relo_rec_size),
15760 &expected_size, sizeof(expected_size)))
15761 err = -EFAULT;
15762 }
15763 break;
15764 }
15765
15766 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15767 err = -EFAULT;
15768 break;
15769 }
15770
15771 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15772 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15773 i, core_relo.insn_off, prog->len);
15774 err = -EINVAL;
15775 break;
15776 }
15777
15778 err = bpf_core_apply(&ctx, &core_relo, i,
15779 &prog->insnsi[core_relo.insn_off / 8]);
15780 if (err)
15781 break;
15782 bpfptr_add(&u_core_relo, rec_size);
15783 }
15784 return err;
15785 }
15786
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)15787 static int check_btf_info(struct bpf_verifier_env *env,
15788 const union bpf_attr *attr,
15789 bpfptr_t uattr)
15790 {
15791 struct btf *btf;
15792 int err;
15793
15794 if (!attr->func_info_cnt && !attr->line_info_cnt) {
15795 if (check_abnormal_return(env))
15796 return -EINVAL;
15797 return 0;
15798 }
15799
15800 btf = btf_get_by_fd(attr->prog_btf_fd);
15801 if (IS_ERR(btf))
15802 return PTR_ERR(btf);
15803 if (btf_is_kernel(btf)) {
15804 btf_put(btf);
15805 return -EACCES;
15806 }
15807 env->prog->aux->btf = btf;
15808
15809 err = check_btf_func(env, attr, uattr);
15810 if (err)
15811 return err;
15812
15813 err = check_btf_line(env, attr, uattr);
15814 if (err)
15815 return err;
15816
15817 err = check_core_relo(env, attr, uattr);
15818 if (err)
15819 return err;
15820
15821 return 0;
15822 }
15823
15824 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)15825 static bool range_within(struct bpf_reg_state *old,
15826 struct bpf_reg_state *cur)
15827 {
15828 return old->umin_value <= cur->umin_value &&
15829 old->umax_value >= cur->umax_value &&
15830 old->smin_value <= cur->smin_value &&
15831 old->smax_value >= cur->smax_value &&
15832 old->u32_min_value <= cur->u32_min_value &&
15833 old->u32_max_value >= cur->u32_max_value &&
15834 old->s32_min_value <= cur->s32_min_value &&
15835 old->s32_max_value >= cur->s32_max_value;
15836 }
15837
15838 /* If in the old state two registers had the same id, then they need to have
15839 * the same id in the new state as well. But that id could be different from
15840 * the old state, so we need to track the mapping from old to new ids.
15841 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15842 * regs with old id 5 must also have new id 9 for the new state to be safe. But
15843 * regs with a different old id could still have new id 9, we don't care about
15844 * that.
15845 * So we look through our idmap to see if this old id has been seen before. If
15846 * so, we require the new id to match; otherwise, we add the id pair to the map.
15847 */
check_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15848 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15849 {
15850 struct bpf_id_pair *map = idmap->map;
15851 unsigned int i;
15852
15853 /* either both IDs should be set or both should be zero */
15854 if (!!old_id != !!cur_id)
15855 return false;
15856
15857 if (old_id == 0) /* cur_id == 0 as well */
15858 return true;
15859
15860 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15861 if (!map[i].old) {
15862 /* Reached an empty slot; haven't seen this id before */
15863 map[i].old = old_id;
15864 map[i].cur = cur_id;
15865 return true;
15866 }
15867 if (map[i].old == old_id)
15868 return map[i].cur == cur_id;
15869 if (map[i].cur == cur_id)
15870 return false;
15871 }
15872 /* We ran out of idmap slots, which should be impossible */
15873 WARN_ON_ONCE(1);
15874 return false;
15875 }
15876
15877 /* Similar to check_ids(), but allocate a unique temporary ID
15878 * for 'old_id' or 'cur_id' of zero.
15879 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15880 */
check_scalar_ids(u32 old_id,u32 cur_id,struct bpf_idmap * idmap)15881 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15882 {
15883 old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15884 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15885
15886 return check_ids(old_id, cur_id, idmap);
15887 }
15888
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)15889 static void clean_func_state(struct bpf_verifier_env *env,
15890 struct bpf_func_state *st)
15891 {
15892 enum bpf_reg_liveness live;
15893 int i, j;
15894
15895 for (i = 0; i < BPF_REG_FP; i++) {
15896 live = st->regs[i].live;
15897 /* liveness must not touch this register anymore */
15898 st->regs[i].live |= REG_LIVE_DONE;
15899 if (!(live & REG_LIVE_READ))
15900 /* since the register is unused, clear its state
15901 * to make further comparison simpler
15902 */
15903 __mark_reg_not_init(env, &st->regs[i]);
15904 }
15905
15906 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15907 live = st->stack[i].spilled_ptr.live;
15908 /* liveness must not touch this stack slot anymore */
15909 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15910 if (!(live & REG_LIVE_READ)) {
15911 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15912 for (j = 0; j < BPF_REG_SIZE; j++)
15913 st->stack[i].slot_type[j] = STACK_INVALID;
15914 }
15915 }
15916 }
15917
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)15918 static void clean_verifier_state(struct bpf_verifier_env *env,
15919 struct bpf_verifier_state *st)
15920 {
15921 int i;
15922
15923 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15924 /* all regs in this state in all frames were already marked */
15925 return;
15926
15927 for (i = 0; i <= st->curframe; i++)
15928 clean_func_state(env, st->frame[i]);
15929 }
15930
15931 /* the parentage chains form a tree.
15932 * the verifier states are added to state lists at given insn and
15933 * pushed into state stack for future exploration.
15934 * when the verifier reaches bpf_exit insn some of the verifer states
15935 * stored in the state lists have their final liveness state already,
15936 * but a lot of states will get revised from liveness point of view when
15937 * the verifier explores other branches.
15938 * Example:
15939 * 1: r0 = 1
15940 * 2: if r1 == 100 goto pc+1
15941 * 3: r0 = 2
15942 * 4: exit
15943 * when the verifier reaches exit insn the register r0 in the state list of
15944 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15945 * of insn 2 and goes exploring further. At the insn 4 it will walk the
15946 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15947 *
15948 * Since the verifier pushes the branch states as it sees them while exploring
15949 * the program the condition of walking the branch instruction for the second
15950 * time means that all states below this branch were already explored and
15951 * their final liveness marks are already propagated.
15952 * Hence when the verifier completes the search of state list in is_state_visited()
15953 * we can call this clean_live_states() function to mark all liveness states
15954 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15955 * will not be used.
15956 * This function also clears the registers and stack for states that !READ
15957 * to simplify state merging.
15958 *
15959 * Important note here that walking the same branch instruction in the callee
15960 * doesn't meant that the states are DONE. The verifier has to compare
15961 * the callsites
15962 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)15963 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15964 struct bpf_verifier_state *cur)
15965 {
15966 struct bpf_verifier_state_list *sl;
15967
15968 sl = *explored_state(env, insn);
15969 while (sl) {
15970 if (sl->state.branches)
15971 goto next;
15972 if (sl->state.insn_idx != insn ||
15973 !same_callsites(&sl->state, cur))
15974 goto next;
15975 clean_verifier_state(env, &sl->state);
15976 next:
15977 sl = sl->next;
15978 }
15979 }
15980
regs_exact(const struct bpf_reg_state * rold,const struct bpf_reg_state * rcur,struct bpf_idmap * idmap)15981 static bool regs_exact(const struct bpf_reg_state *rold,
15982 const struct bpf_reg_state *rcur,
15983 struct bpf_idmap *idmap)
15984 {
15985 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15986 check_ids(rold->id, rcur->id, idmap) &&
15987 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15988 }
15989
15990 /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_idmap * idmap,bool exact)15991 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15992 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
15993 {
15994 if (exact)
15995 return regs_exact(rold, rcur, idmap);
15996
15997 if (!(rold->live & REG_LIVE_READ))
15998 /* explored state didn't use this */
15999 return true;
16000 if (rold->type == NOT_INIT)
16001 /* explored state can't have used this */
16002 return true;
16003 if (rcur->type == NOT_INIT)
16004 return false;
16005
16006 /* Enforce that register types have to match exactly, including their
16007 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16008 * rule.
16009 *
16010 * One can make a point that using a pointer register as unbounded
16011 * SCALAR would be technically acceptable, but this could lead to
16012 * pointer leaks because scalars are allowed to leak while pointers
16013 * are not. We could make this safe in special cases if root is
16014 * calling us, but it's probably not worth the hassle.
16015 *
16016 * Also, register types that are *not* MAYBE_NULL could technically be
16017 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16018 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16019 * to the same map).
16020 * However, if the old MAYBE_NULL register then got NULL checked,
16021 * doing so could have affected others with the same id, and we can't
16022 * check for that because we lost the id when we converted to
16023 * a non-MAYBE_NULL variant.
16024 * So, as a general rule we don't allow mixing MAYBE_NULL and
16025 * non-MAYBE_NULL registers as well.
16026 */
16027 if (rold->type != rcur->type)
16028 return false;
16029
16030 switch (base_type(rold->type)) {
16031 case SCALAR_VALUE:
16032 if (env->explore_alu_limits) {
16033 /* explore_alu_limits disables tnum_in() and range_within()
16034 * logic and requires everything to be strict
16035 */
16036 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16037 check_scalar_ids(rold->id, rcur->id, idmap);
16038 }
16039 if (!rold->precise)
16040 return true;
16041 /* Why check_ids() for scalar registers?
16042 *
16043 * Consider the following BPF code:
16044 * 1: r6 = ... unbound scalar, ID=a ...
16045 * 2: r7 = ... unbound scalar, ID=b ...
16046 * 3: if (r6 > r7) goto +1
16047 * 4: r6 = r7
16048 * 5: if (r6 > X) goto ...
16049 * 6: ... memory operation using r7 ...
16050 *
16051 * First verification path is [1-6]:
16052 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16053 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16054 * r7 <= X, because r6 and r7 share same id.
16055 * Next verification path is [1-4, 6].
16056 *
16057 * Instruction (6) would be reached in two states:
16058 * I. r6{.id=b}, r7{.id=b} via path 1-6;
16059 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16060 *
16061 * Use check_ids() to distinguish these states.
16062 * ---
16063 * Also verify that new value satisfies old value range knowledge.
16064 */
16065 return range_within(rold, rcur) &&
16066 tnum_in(rold->var_off, rcur->var_off) &&
16067 check_scalar_ids(rold->id, rcur->id, idmap);
16068 case PTR_TO_MAP_KEY:
16069 case PTR_TO_MAP_VALUE:
16070 case PTR_TO_MEM:
16071 case PTR_TO_BUF:
16072 case PTR_TO_TP_BUFFER:
16073 /* If the new min/max/var_off satisfy the old ones and
16074 * everything else matches, we are OK.
16075 */
16076 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16077 range_within(rold, rcur) &&
16078 tnum_in(rold->var_off, rcur->var_off) &&
16079 check_ids(rold->id, rcur->id, idmap) &&
16080 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16081 case PTR_TO_PACKET_META:
16082 case PTR_TO_PACKET:
16083 /* We must have at least as much range as the old ptr
16084 * did, so that any accesses which were safe before are
16085 * still safe. This is true even if old range < old off,
16086 * since someone could have accessed through (ptr - k), or
16087 * even done ptr -= k in a register, to get a safe access.
16088 */
16089 if (rold->range > rcur->range)
16090 return false;
16091 /* If the offsets don't match, we can't trust our alignment;
16092 * nor can we be sure that we won't fall out of range.
16093 */
16094 if (rold->off != rcur->off)
16095 return false;
16096 /* id relations must be preserved */
16097 if (!check_ids(rold->id, rcur->id, idmap))
16098 return false;
16099 /* new val must satisfy old val knowledge */
16100 return range_within(rold, rcur) &&
16101 tnum_in(rold->var_off, rcur->var_off);
16102 case PTR_TO_STACK:
16103 /* two stack pointers are equal only if they're pointing to
16104 * the same stack frame, since fp-8 in foo != fp-8 in bar
16105 */
16106 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16107 default:
16108 return regs_exact(rold, rcur, idmap);
16109 }
16110 }
16111
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap,bool exact)16112 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16113 struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16114 {
16115 int i, spi;
16116
16117 /* walk slots of the explored stack and ignore any additional
16118 * slots in the current stack, since explored(safe) state
16119 * didn't use them
16120 */
16121 for (i = 0; i < old->allocated_stack; i++) {
16122 struct bpf_reg_state *old_reg, *cur_reg;
16123
16124 spi = i / BPF_REG_SIZE;
16125
16126 if (exact &&
16127 (i >= cur->allocated_stack ||
16128 old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16129 cur->stack[spi].slot_type[i % BPF_REG_SIZE]))
16130 return false;
16131
16132 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16133 i += BPF_REG_SIZE - 1;
16134 /* explored state didn't use this */
16135 continue;
16136 }
16137
16138 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16139 continue;
16140
16141 if (env->allow_uninit_stack &&
16142 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16143 continue;
16144
16145 /* explored stack has more populated slots than current stack
16146 * and these slots were used
16147 */
16148 if (i >= cur->allocated_stack)
16149 return false;
16150
16151 /* if old state was safe with misc data in the stack
16152 * it will be safe with zero-initialized stack.
16153 * The opposite is not true
16154 */
16155 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16156 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16157 continue;
16158 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16159 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16160 /* Ex: old explored (safe) state has STACK_SPILL in
16161 * this stack slot, but current has STACK_MISC ->
16162 * this verifier states are not equivalent,
16163 * return false to continue verification of this path
16164 */
16165 return false;
16166 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16167 continue;
16168 /* Both old and cur are having same slot_type */
16169 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16170 case STACK_SPILL:
16171 /* when explored and current stack slot are both storing
16172 * spilled registers, check that stored pointers types
16173 * are the same as well.
16174 * Ex: explored safe path could have stored
16175 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16176 * but current path has stored:
16177 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16178 * such verifier states are not equivalent.
16179 * return false to continue verification of this path
16180 */
16181 if (!regsafe(env, &old->stack[spi].spilled_ptr,
16182 &cur->stack[spi].spilled_ptr, idmap, exact))
16183 return false;
16184 break;
16185 case STACK_DYNPTR:
16186 old_reg = &old->stack[spi].spilled_ptr;
16187 cur_reg = &cur->stack[spi].spilled_ptr;
16188 if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16189 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16190 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16191 return false;
16192 break;
16193 case STACK_ITER:
16194 old_reg = &old->stack[spi].spilled_ptr;
16195 cur_reg = &cur->stack[spi].spilled_ptr;
16196 /* iter.depth is not compared between states as it
16197 * doesn't matter for correctness and would otherwise
16198 * prevent convergence; we maintain it only to prevent
16199 * infinite loop check triggering, see
16200 * iter_active_depths_differ()
16201 */
16202 if (old_reg->iter.btf != cur_reg->iter.btf ||
16203 old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16204 old_reg->iter.state != cur_reg->iter.state ||
16205 /* ignore {old_reg,cur_reg}->iter.depth, see above */
16206 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16207 return false;
16208 break;
16209 case STACK_MISC:
16210 case STACK_ZERO:
16211 case STACK_INVALID:
16212 continue;
16213 /* Ensure that new unhandled slot types return false by default */
16214 default:
16215 return false;
16216 }
16217 }
16218 return true;
16219 }
16220
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_idmap * idmap)16221 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16222 struct bpf_idmap *idmap)
16223 {
16224 int i;
16225
16226 if (old->acquired_refs != cur->acquired_refs)
16227 return false;
16228
16229 for (i = 0; i < old->acquired_refs; i++) {
16230 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16231 return false;
16232 }
16233
16234 return true;
16235 }
16236
16237 /* compare two verifier states
16238 *
16239 * all states stored in state_list are known to be valid, since
16240 * verifier reached 'bpf_exit' instruction through them
16241 *
16242 * this function is called when verifier exploring different branches of
16243 * execution popped from the state stack. If it sees an old state that has
16244 * more strict register state and more strict stack state then this execution
16245 * branch doesn't need to be explored further, since verifier already
16246 * concluded that more strict state leads to valid finish.
16247 *
16248 * Therefore two states are equivalent if register state is more conservative
16249 * and explored stack state is more conservative than the current one.
16250 * Example:
16251 * explored current
16252 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16253 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16254 *
16255 * In other words if current stack state (one being explored) has more
16256 * valid slots than old one that already passed validation, it means
16257 * the verifier can stop exploring and conclude that current state is valid too
16258 *
16259 * Similarly with registers. If explored state has register type as invalid
16260 * whereas register type in current state is meaningful, it means that
16261 * the current state will reach 'bpf_exit' instruction safely
16262 */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,bool exact)16263 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16264 struct bpf_func_state *cur, bool exact)
16265 {
16266 int i;
16267
16268 if (old->callback_depth > cur->callback_depth)
16269 return false;
16270
16271 for (i = 0; i < MAX_BPF_REG; i++)
16272 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16273 &env->idmap_scratch, exact))
16274 return false;
16275
16276 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16277 return false;
16278
16279 if (!refsafe(old, cur, &env->idmap_scratch))
16280 return false;
16281
16282 return true;
16283 }
16284
reset_idmap_scratch(struct bpf_verifier_env * env)16285 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16286 {
16287 env->idmap_scratch.tmp_id_gen = env->id_gen;
16288 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16289 }
16290
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur,bool exact)16291 static bool states_equal(struct bpf_verifier_env *env,
16292 struct bpf_verifier_state *old,
16293 struct bpf_verifier_state *cur,
16294 bool exact)
16295 {
16296 int i;
16297
16298 if (old->curframe != cur->curframe)
16299 return false;
16300
16301 reset_idmap_scratch(env);
16302
16303 /* Verification state from speculative execution simulation
16304 * must never prune a non-speculative execution one.
16305 */
16306 if (old->speculative && !cur->speculative)
16307 return false;
16308
16309 if (old->active_lock.ptr != cur->active_lock.ptr)
16310 return false;
16311
16312 /* Old and cur active_lock's have to be either both present
16313 * or both absent.
16314 */
16315 if (!!old->active_lock.id != !!cur->active_lock.id)
16316 return false;
16317
16318 if (old->active_lock.id &&
16319 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16320 return false;
16321
16322 if (old->active_rcu_lock != cur->active_rcu_lock)
16323 return false;
16324
16325 /* for states to be equal callsites have to be the same
16326 * and all frame states need to be equivalent
16327 */
16328 for (i = 0; i <= old->curframe; i++) {
16329 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16330 return false;
16331 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16332 return false;
16333 }
16334 return true;
16335 }
16336
16337 /* Return 0 if no propagation happened. Return negative error code if error
16338 * happened. Otherwise, return the propagated bit.
16339 */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)16340 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16341 struct bpf_reg_state *reg,
16342 struct bpf_reg_state *parent_reg)
16343 {
16344 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16345 u8 flag = reg->live & REG_LIVE_READ;
16346 int err;
16347
16348 /* When comes here, read flags of PARENT_REG or REG could be any of
16349 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16350 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16351 */
16352 if (parent_flag == REG_LIVE_READ64 ||
16353 /* Or if there is no read flag from REG. */
16354 !flag ||
16355 /* Or if the read flag from REG is the same as PARENT_REG. */
16356 parent_flag == flag)
16357 return 0;
16358
16359 err = mark_reg_read(env, reg, parent_reg, flag);
16360 if (err)
16361 return err;
16362
16363 return flag;
16364 }
16365
16366 /* A write screens off any subsequent reads; but write marks come from the
16367 * straight-line code between a state and its parent. When we arrive at an
16368 * equivalent state (jump target or such) we didn't arrive by the straight-line
16369 * code, so read marks in the state must propagate to the parent regardless
16370 * of the state's write marks. That's what 'parent == state->parent' comparison
16371 * in mark_reg_read() is for.
16372 */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)16373 static int propagate_liveness(struct bpf_verifier_env *env,
16374 const struct bpf_verifier_state *vstate,
16375 struct bpf_verifier_state *vparent)
16376 {
16377 struct bpf_reg_state *state_reg, *parent_reg;
16378 struct bpf_func_state *state, *parent;
16379 int i, frame, err = 0;
16380
16381 if (vparent->curframe != vstate->curframe) {
16382 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16383 vparent->curframe, vstate->curframe);
16384 return -EFAULT;
16385 }
16386 /* Propagate read liveness of registers... */
16387 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16388 for (frame = 0; frame <= vstate->curframe; frame++) {
16389 parent = vparent->frame[frame];
16390 state = vstate->frame[frame];
16391 parent_reg = parent->regs;
16392 state_reg = state->regs;
16393 /* We don't need to worry about FP liveness, it's read-only */
16394 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16395 err = propagate_liveness_reg(env, &state_reg[i],
16396 &parent_reg[i]);
16397 if (err < 0)
16398 return err;
16399 if (err == REG_LIVE_READ64)
16400 mark_insn_zext(env, &parent_reg[i]);
16401 }
16402
16403 /* Propagate stack slots. */
16404 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16405 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16406 parent_reg = &parent->stack[i].spilled_ptr;
16407 state_reg = &state->stack[i].spilled_ptr;
16408 err = propagate_liveness_reg(env, state_reg,
16409 parent_reg);
16410 if (err < 0)
16411 return err;
16412 }
16413 }
16414 return 0;
16415 }
16416
16417 /* find precise scalars in the previous equivalent state and
16418 * propagate them into the current state
16419 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)16420 static int propagate_precision(struct bpf_verifier_env *env,
16421 const struct bpf_verifier_state *old)
16422 {
16423 struct bpf_reg_state *state_reg;
16424 struct bpf_func_state *state;
16425 int i, err = 0, fr;
16426 bool first;
16427
16428 for (fr = old->curframe; fr >= 0; fr--) {
16429 state = old->frame[fr];
16430 state_reg = state->regs;
16431 first = true;
16432 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16433 if (state_reg->type != SCALAR_VALUE ||
16434 !state_reg->precise ||
16435 !(state_reg->live & REG_LIVE_READ))
16436 continue;
16437 if (env->log.level & BPF_LOG_LEVEL2) {
16438 if (first)
16439 verbose(env, "frame %d: propagating r%d", fr, i);
16440 else
16441 verbose(env, ",r%d", i);
16442 }
16443 bt_set_frame_reg(&env->bt, fr, i);
16444 first = false;
16445 }
16446
16447 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16448 if (!is_spilled_reg(&state->stack[i]))
16449 continue;
16450 state_reg = &state->stack[i].spilled_ptr;
16451 if (state_reg->type != SCALAR_VALUE ||
16452 !state_reg->precise ||
16453 !(state_reg->live & REG_LIVE_READ))
16454 continue;
16455 if (env->log.level & BPF_LOG_LEVEL2) {
16456 if (first)
16457 verbose(env, "frame %d: propagating fp%d",
16458 fr, (-i - 1) * BPF_REG_SIZE);
16459 else
16460 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16461 }
16462 bt_set_frame_slot(&env->bt, fr, i);
16463 first = false;
16464 }
16465 if (!first)
16466 verbose(env, "\n");
16467 }
16468
16469 err = mark_chain_precision_batch(env);
16470 if (err < 0)
16471 return err;
16472
16473 return 0;
16474 }
16475
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16476 static bool states_maybe_looping(struct bpf_verifier_state *old,
16477 struct bpf_verifier_state *cur)
16478 {
16479 struct bpf_func_state *fold, *fcur;
16480 int i, fr = cur->curframe;
16481
16482 if (old->curframe != fr)
16483 return false;
16484
16485 fold = old->frame[fr];
16486 fcur = cur->frame[fr];
16487 for (i = 0; i < MAX_BPF_REG; i++)
16488 if (memcmp(&fold->regs[i], &fcur->regs[i],
16489 offsetof(struct bpf_reg_state, parent)))
16490 return false;
16491 return true;
16492 }
16493
is_iter_next_insn(struct bpf_verifier_env * env,int insn_idx)16494 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16495 {
16496 return env->insn_aux_data[insn_idx].is_iter_next;
16497 }
16498
16499 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16500 * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16501 * states to match, which otherwise would look like an infinite loop. So while
16502 * iter_next() calls are taken care of, we still need to be careful and
16503 * prevent erroneous and too eager declaration of "ininite loop", when
16504 * iterators are involved.
16505 *
16506 * Here's a situation in pseudo-BPF assembly form:
16507 *
16508 * 0: again: ; set up iter_next() call args
16509 * 1: r1 = &it ; <CHECKPOINT HERE>
16510 * 2: call bpf_iter_num_next ; this is iter_next() call
16511 * 3: if r0 == 0 goto done
16512 * 4: ... something useful here ...
16513 * 5: goto again ; another iteration
16514 * 6: done:
16515 * 7: r1 = &it
16516 * 8: call bpf_iter_num_destroy ; clean up iter state
16517 * 9: exit
16518 *
16519 * This is a typical loop. Let's assume that we have a prune point at 1:,
16520 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16521 * again`, assuming other heuristics don't get in a way).
16522 *
16523 * When we first time come to 1:, let's say we have some state X. We proceed
16524 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16525 * Now we come back to validate that forked ACTIVE state. We proceed through
16526 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16527 * are converging. But the problem is that we don't know that yet, as this
16528 * convergence has to happen at iter_next() call site only. So if nothing is
16529 * done, at 1: verifier will use bounded loop logic and declare infinite
16530 * looping (and would be *technically* correct, if not for iterator's
16531 * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16532 * don't want that. So what we do in process_iter_next_call() when we go on
16533 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16534 * a different iteration. So when we suspect an infinite loop, we additionally
16535 * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16536 * pretend we are not looping and wait for next iter_next() call.
16537 *
16538 * This only applies to ACTIVE state. In DRAINED state we don't expect to
16539 * loop, because that would actually mean infinite loop, as DRAINED state is
16540 * "sticky", and so we'll keep returning into the same instruction with the
16541 * same state (at least in one of possible code paths).
16542 *
16543 * This approach allows to keep infinite loop heuristic even in the face of
16544 * active iterator. E.g., C snippet below is and will be detected as
16545 * inifintely looping:
16546 *
16547 * struct bpf_iter_num it;
16548 * int *p, x;
16549 *
16550 * bpf_iter_num_new(&it, 0, 10);
16551 * while ((p = bpf_iter_num_next(&t))) {
16552 * x = p;
16553 * while (x--) {} // <<-- infinite loop here
16554 * }
16555 *
16556 */
iter_active_depths_differ(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)16557 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16558 {
16559 struct bpf_reg_state *slot, *cur_slot;
16560 struct bpf_func_state *state;
16561 int i, fr;
16562
16563 for (fr = old->curframe; fr >= 0; fr--) {
16564 state = old->frame[fr];
16565 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16566 if (state->stack[i].slot_type[0] != STACK_ITER)
16567 continue;
16568
16569 slot = &state->stack[i].spilled_ptr;
16570 if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16571 continue;
16572
16573 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16574 if (cur_slot->iter.depth != slot->iter.depth)
16575 return true;
16576 }
16577 }
16578 return false;
16579 }
16580
is_state_visited(struct bpf_verifier_env * env,int insn_idx)16581 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16582 {
16583 struct bpf_verifier_state_list *new_sl;
16584 struct bpf_verifier_state_list *sl, **pprev;
16585 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16586 int i, j, n, err, states_cnt = 0;
16587 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16588 bool add_new_state = force_new_state;
16589 bool force_exact;
16590
16591 /* bpf progs typically have pruning point every 4 instructions
16592 * http://vger.kernel.org/bpfconf2019.html#session-1
16593 * Do not add new state for future pruning if the verifier hasn't seen
16594 * at least 2 jumps and at least 8 instructions.
16595 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16596 * In tests that amounts to up to 50% reduction into total verifier
16597 * memory consumption and 20% verifier time speedup.
16598 */
16599 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16600 env->insn_processed - env->prev_insn_processed >= 8)
16601 add_new_state = true;
16602
16603 pprev = explored_state(env, insn_idx);
16604 sl = *pprev;
16605
16606 clean_live_states(env, insn_idx, cur);
16607
16608 while (sl) {
16609 states_cnt++;
16610 if (sl->state.insn_idx != insn_idx)
16611 goto next;
16612
16613 if (sl->state.branches) {
16614 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16615
16616 if (frame->in_async_callback_fn &&
16617 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16618 /* Different async_entry_cnt means that the verifier is
16619 * processing another entry into async callback.
16620 * Seeing the same state is not an indication of infinite
16621 * loop or infinite recursion.
16622 * But finding the same state doesn't mean that it's safe
16623 * to stop processing the current state. The previous state
16624 * hasn't yet reached bpf_exit, since state.branches > 0.
16625 * Checking in_async_callback_fn alone is not enough either.
16626 * Since the verifier still needs to catch infinite loops
16627 * inside async callbacks.
16628 */
16629 goto skip_inf_loop_check;
16630 }
16631 /* BPF open-coded iterators loop detection is special.
16632 * states_maybe_looping() logic is too simplistic in detecting
16633 * states that *might* be equivalent, because it doesn't know
16634 * about ID remapping, so don't even perform it.
16635 * See process_iter_next_call() and iter_active_depths_differ()
16636 * for overview of the logic. When current and one of parent
16637 * states are detected as equivalent, it's a good thing: we prove
16638 * convergence and can stop simulating further iterations.
16639 * It's safe to assume that iterator loop will finish, taking into
16640 * account iter_next() contract of eventually returning
16641 * sticky NULL result.
16642 *
16643 * Note, that states have to be compared exactly in this case because
16644 * read and precision marks might not be finalized inside the loop.
16645 * E.g. as in the program below:
16646 *
16647 * 1. r7 = -16
16648 * 2. r6 = bpf_get_prandom_u32()
16649 * 3. while (bpf_iter_num_next(&fp[-8])) {
16650 * 4. if (r6 != 42) {
16651 * 5. r7 = -32
16652 * 6. r6 = bpf_get_prandom_u32()
16653 * 7. continue
16654 * 8. }
16655 * 9. r0 = r10
16656 * 10. r0 += r7
16657 * 11. r8 = *(u64 *)(r0 + 0)
16658 * 12. r6 = bpf_get_prandom_u32()
16659 * 13. }
16660 *
16661 * Here verifier would first visit path 1-3, create a checkpoint at 3
16662 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16663 * not have read or precision mark for r7 yet, thus inexact states
16664 * comparison would discard current state with r7=-32
16665 * => unsafe memory access at 11 would not be caught.
16666 */
16667 if (is_iter_next_insn(env, insn_idx)) {
16668 if (states_equal(env, &sl->state, cur, true)) {
16669 struct bpf_func_state *cur_frame;
16670 struct bpf_reg_state *iter_state, *iter_reg;
16671 int spi;
16672
16673 cur_frame = cur->frame[cur->curframe];
16674 /* btf_check_iter_kfuncs() enforces that
16675 * iter state pointer is always the first arg
16676 */
16677 iter_reg = &cur_frame->regs[BPF_REG_1];
16678 /* current state is valid due to states_equal(),
16679 * so we can assume valid iter and reg state,
16680 * no need for extra (re-)validations
16681 */
16682 spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16683 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16684 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16685 update_loop_entry(cur, &sl->state);
16686 goto hit;
16687 }
16688 }
16689 goto skip_inf_loop_check;
16690 }
16691 if (calls_callback(env, insn_idx)) {
16692 if (states_equal(env, &sl->state, cur, true))
16693 goto hit;
16694 goto skip_inf_loop_check;
16695 }
16696 /* attempt to detect infinite loop to avoid unnecessary doomed work */
16697 if (states_maybe_looping(&sl->state, cur) &&
16698 states_equal(env, &sl->state, cur, false) &&
16699 !iter_active_depths_differ(&sl->state, cur) &&
16700 sl->state.callback_unroll_depth == cur->callback_unroll_depth) {
16701 verbose_linfo(env, insn_idx, "; ");
16702 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16703 verbose(env, "cur state:");
16704 print_verifier_state(env, cur->frame[cur->curframe], true);
16705 verbose(env, "old state:");
16706 print_verifier_state(env, sl->state.frame[cur->curframe], true);
16707 return -EINVAL;
16708 }
16709 /* if the verifier is processing a loop, avoid adding new state
16710 * too often, since different loop iterations have distinct
16711 * states and may not help future pruning.
16712 * This threshold shouldn't be too low to make sure that
16713 * a loop with large bound will be rejected quickly.
16714 * The most abusive loop will be:
16715 * r1 += 1
16716 * if r1 < 1000000 goto pc-2
16717 * 1M insn_procssed limit / 100 == 10k peak states.
16718 * This threshold shouldn't be too high either, since states
16719 * at the end of the loop are likely to be useful in pruning.
16720 */
16721 skip_inf_loop_check:
16722 if (!force_new_state &&
16723 env->jmps_processed - env->prev_jmps_processed < 20 &&
16724 env->insn_processed - env->prev_insn_processed < 100)
16725 add_new_state = false;
16726 goto miss;
16727 }
16728 /* If sl->state is a part of a loop and this loop's entry is a part of
16729 * current verification path then states have to be compared exactly.
16730 * 'force_exact' is needed to catch the following case:
16731 *
16732 * initial Here state 'succ' was processed first,
16733 * | it was eventually tracked to produce a
16734 * V state identical to 'hdr'.
16735 * .---------> hdr All branches from 'succ' had been explored
16736 * | | and thus 'succ' has its .branches == 0.
16737 * | V
16738 * | .------... Suppose states 'cur' and 'succ' correspond
16739 * | | | to the same instruction + callsites.
16740 * | V V In such case it is necessary to check
16741 * | ... ... if 'succ' and 'cur' are states_equal().
16742 * | | | If 'succ' and 'cur' are a part of the
16743 * | V V same loop exact flag has to be set.
16744 * | succ <- cur To check if that is the case, verify
16745 * | | if loop entry of 'succ' is in current
16746 * | V DFS path.
16747 * | ...
16748 * | |
16749 * '----'
16750 *
16751 * Additional details are in the comment before get_loop_entry().
16752 */
16753 loop_entry = get_loop_entry(&sl->state);
16754 force_exact = loop_entry && loop_entry->branches > 0;
16755 if (states_equal(env, &sl->state, cur, force_exact)) {
16756 if (force_exact)
16757 update_loop_entry(cur, loop_entry);
16758 hit:
16759 sl->hit_cnt++;
16760 /* reached equivalent register/stack state,
16761 * prune the search.
16762 * Registers read by the continuation are read by us.
16763 * If we have any write marks in env->cur_state, they
16764 * will prevent corresponding reads in the continuation
16765 * from reaching our parent (an explored_state). Our
16766 * own state will get the read marks recorded, but
16767 * they'll be immediately forgotten as we're pruning
16768 * this state and will pop a new one.
16769 */
16770 err = propagate_liveness(env, &sl->state, cur);
16771
16772 /* if previous state reached the exit with precision and
16773 * current state is equivalent to it (except precsion marks)
16774 * the precision needs to be propagated back in
16775 * the current state.
16776 */
16777 err = err ? : push_jmp_history(env, cur);
16778 err = err ? : propagate_precision(env, &sl->state);
16779 if (err)
16780 return err;
16781 return 1;
16782 }
16783 miss:
16784 /* when new state is not going to be added do not increase miss count.
16785 * Otherwise several loop iterations will remove the state
16786 * recorded earlier. The goal of these heuristics is to have
16787 * states from some iterations of the loop (some in the beginning
16788 * and some at the end) to help pruning.
16789 */
16790 if (add_new_state)
16791 sl->miss_cnt++;
16792 /* heuristic to determine whether this state is beneficial
16793 * to keep checking from state equivalence point of view.
16794 * Higher numbers increase max_states_per_insn and verification time,
16795 * but do not meaningfully decrease insn_processed.
16796 * 'n' controls how many times state could miss before eviction.
16797 * Use bigger 'n' for checkpoints because evicting checkpoint states
16798 * too early would hinder iterator convergence.
16799 */
16800 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
16801 if (sl->miss_cnt > sl->hit_cnt * n + n) {
16802 /* the state is unlikely to be useful. Remove it to
16803 * speed up verification
16804 */
16805 *pprev = sl->next;
16806 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
16807 !sl->state.used_as_loop_entry) {
16808 u32 br = sl->state.branches;
16809
16810 WARN_ONCE(br,
16811 "BUG live_done but branches_to_explore %d\n",
16812 br);
16813 free_verifier_state(&sl->state, false);
16814 kfree(sl);
16815 env->peak_states--;
16816 } else {
16817 /* cannot free this state, since parentage chain may
16818 * walk it later. Add it for free_list instead to
16819 * be freed at the end of verification
16820 */
16821 sl->next = env->free_list;
16822 env->free_list = sl;
16823 }
16824 sl = *pprev;
16825 continue;
16826 }
16827 next:
16828 pprev = &sl->next;
16829 sl = *pprev;
16830 }
16831
16832 if (env->max_states_per_insn < states_cnt)
16833 env->max_states_per_insn = states_cnt;
16834
16835 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16836 return 0;
16837
16838 if (!add_new_state)
16839 return 0;
16840
16841 /* There were no equivalent states, remember the current one.
16842 * Technically the current state is not proven to be safe yet,
16843 * but it will either reach outer most bpf_exit (which means it's safe)
16844 * or it will be rejected. When there are no loops the verifier won't be
16845 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16846 * again on the way to bpf_exit.
16847 * When looping the sl->state.branches will be > 0 and this state
16848 * will not be considered for equivalence until branches == 0.
16849 */
16850 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16851 if (!new_sl)
16852 return -ENOMEM;
16853 env->total_states++;
16854 env->peak_states++;
16855 env->prev_jmps_processed = env->jmps_processed;
16856 env->prev_insn_processed = env->insn_processed;
16857
16858 /* forget precise markings we inherited, see __mark_chain_precision */
16859 if (env->bpf_capable)
16860 mark_all_scalars_imprecise(env, cur);
16861
16862 /* add new state to the head of linked list */
16863 new = &new_sl->state;
16864 err = copy_verifier_state(new, cur);
16865 if (err) {
16866 free_verifier_state(new, false);
16867 kfree(new_sl);
16868 return err;
16869 }
16870 new->insn_idx = insn_idx;
16871 WARN_ONCE(new->branches != 1,
16872 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16873
16874 cur->parent = new;
16875 cur->first_insn_idx = insn_idx;
16876 cur->dfs_depth = new->dfs_depth + 1;
16877 clear_jmp_history(cur);
16878 new_sl->next = *explored_state(env, insn_idx);
16879 *explored_state(env, insn_idx) = new_sl;
16880 /* connect new state to parentage chain. Current frame needs all
16881 * registers connected. Only r6 - r9 of the callers are alive (pushed
16882 * to the stack implicitly by JITs) so in callers' frames connect just
16883 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16884 * the state of the call instruction (with WRITTEN set), and r0 comes
16885 * from callee with its full parentage chain, anyway.
16886 */
16887 /* clear write marks in current state: the writes we did are not writes
16888 * our child did, so they don't screen off its reads from us.
16889 * (There are no read marks in current state, because reads always mark
16890 * their parent and current state never has children yet. Only
16891 * explored_states can get read marks.)
16892 */
16893 for (j = 0; j <= cur->curframe; j++) {
16894 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16895 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16896 for (i = 0; i < BPF_REG_FP; i++)
16897 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16898 }
16899
16900 /* all stack frames are accessible from callee, clear them all */
16901 for (j = 0; j <= cur->curframe; j++) {
16902 struct bpf_func_state *frame = cur->frame[j];
16903 struct bpf_func_state *newframe = new->frame[j];
16904
16905 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16906 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16907 frame->stack[i].spilled_ptr.parent =
16908 &newframe->stack[i].spilled_ptr;
16909 }
16910 }
16911 return 0;
16912 }
16913
16914 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)16915 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16916 {
16917 switch (base_type(type)) {
16918 case PTR_TO_CTX:
16919 case PTR_TO_SOCKET:
16920 case PTR_TO_SOCK_COMMON:
16921 case PTR_TO_TCP_SOCK:
16922 case PTR_TO_XDP_SOCK:
16923 case PTR_TO_BTF_ID:
16924 return false;
16925 default:
16926 return true;
16927 }
16928 }
16929
16930 /* If an instruction was previously used with particular pointer types, then we
16931 * need to be careful to avoid cases such as the below, where it may be ok
16932 * for one branch accessing the pointer, but not ok for the other branch:
16933 *
16934 * R1 = sock_ptr
16935 * goto X;
16936 * ...
16937 * R1 = some_other_valid_ptr;
16938 * goto X;
16939 * ...
16940 * R2 = *(u32 *)(R1 + 0);
16941 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)16942 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16943 {
16944 return src != prev && (!reg_type_mismatch_ok(src) ||
16945 !reg_type_mismatch_ok(prev));
16946 }
16947
save_aux_ptr_type(struct bpf_verifier_env * env,enum bpf_reg_type type,bool allow_trust_missmatch)16948 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16949 bool allow_trust_missmatch)
16950 {
16951 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16952
16953 if (*prev_type == NOT_INIT) {
16954 /* Saw a valid insn
16955 * dst_reg = *(u32 *)(src_reg + off)
16956 * save type to validate intersecting paths
16957 */
16958 *prev_type = type;
16959 } else if (reg_type_mismatch(type, *prev_type)) {
16960 /* Abuser program is trying to use the same insn
16961 * dst_reg = *(u32*) (src_reg + off)
16962 * with different pointer types:
16963 * src_reg == ctx in one branch and
16964 * src_reg == stack|map in some other branch.
16965 * Reject it.
16966 */
16967 if (allow_trust_missmatch &&
16968 base_type(type) == PTR_TO_BTF_ID &&
16969 base_type(*prev_type) == PTR_TO_BTF_ID) {
16970 /*
16971 * Have to support a use case when one path through
16972 * the program yields TRUSTED pointer while another
16973 * is UNTRUSTED. Fallback to UNTRUSTED to generate
16974 * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16975 */
16976 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16977 } else {
16978 verbose(env, "same insn cannot be used with different pointers\n");
16979 return -EINVAL;
16980 }
16981 }
16982
16983 return 0;
16984 }
16985
do_check(struct bpf_verifier_env * env)16986 static int do_check(struct bpf_verifier_env *env)
16987 {
16988 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16989 struct bpf_verifier_state *state = env->cur_state;
16990 struct bpf_insn *insns = env->prog->insnsi;
16991 struct bpf_reg_state *regs;
16992 int insn_cnt = env->prog->len;
16993 bool do_print_state = false;
16994 int prev_insn_idx = -1;
16995
16996 for (;;) {
16997 struct bpf_insn *insn;
16998 u8 class;
16999 int err;
17000
17001 env->prev_insn_idx = prev_insn_idx;
17002 if (env->insn_idx >= insn_cnt) {
17003 verbose(env, "invalid insn idx %d insn_cnt %d\n",
17004 env->insn_idx, insn_cnt);
17005 return -EFAULT;
17006 }
17007
17008 insn = &insns[env->insn_idx];
17009 class = BPF_CLASS(insn->code);
17010
17011 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17012 verbose(env,
17013 "BPF program is too large. Processed %d insn\n",
17014 env->insn_processed);
17015 return -E2BIG;
17016 }
17017
17018 state->last_insn_idx = env->prev_insn_idx;
17019
17020 if (is_prune_point(env, env->insn_idx)) {
17021 err = is_state_visited(env, env->insn_idx);
17022 if (err < 0)
17023 return err;
17024 if (err == 1) {
17025 /* found equivalent state, can prune the search */
17026 if (env->log.level & BPF_LOG_LEVEL) {
17027 if (do_print_state)
17028 verbose(env, "\nfrom %d to %d%s: safe\n",
17029 env->prev_insn_idx, env->insn_idx,
17030 env->cur_state->speculative ?
17031 " (speculative execution)" : "");
17032 else
17033 verbose(env, "%d: safe\n", env->insn_idx);
17034 }
17035 goto process_bpf_exit;
17036 }
17037 }
17038
17039 if (is_jmp_point(env, env->insn_idx)) {
17040 err = push_jmp_history(env, state);
17041 if (err)
17042 return err;
17043 }
17044
17045 if (signal_pending(current))
17046 return -EAGAIN;
17047
17048 if (need_resched())
17049 cond_resched();
17050
17051 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17052 verbose(env, "\nfrom %d to %d%s:",
17053 env->prev_insn_idx, env->insn_idx,
17054 env->cur_state->speculative ?
17055 " (speculative execution)" : "");
17056 print_verifier_state(env, state->frame[state->curframe], true);
17057 do_print_state = false;
17058 }
17059
17060 if (env->log.level & BPF_LOG_LEVEL) {
17061 const struct bpf_insn_cbs cbs = {
17062 .cb_call = disasm_kfunc_name,
17063 .cb_print = verbose,
17064 .private_data = env,
17065 };
17066
17067 if (verifier_state_scratched(env))
17068 print_insn_state(env, state->frame[state->curframe]);
17069
17070 verbose_linfo(env, env->insn_idx, "; ");
17071 env->prev_log_pos = env->log.end_pos;
17072 verbose(env, "%d: ", env->insn_idx);
17073 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17074 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17075 env->prev_log_pos = env->log.end_pos;
17076 }
17077
17078 if (bpf_prog_is_offloaded(env->prog->aux)) {
17079 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17080 env->prev_insn_idx);
17081 if (err)
17082 return err;
17083 }
17084
17085 regs = cur_regs(env);
17086 sanitize_mark_insn_seen(env);
17087 prev_insn_idx = env->insn_idx;
17088
17089 if (class == BPF_ALU || class == BPF_ALU64) {
17090 err = check_alu_op(env, insn);
17091 if (err)
17092 return err;
17093
17094 } else if (class == BPF_LDX) {
17095 enum bpf_reg_type src_reg_type;
17096
17097 /* check for reserved fields is already done */
17098
17099 /* check src operand */
17100 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17101 if (err)
17102 return err;
17103
17104 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17105 if (err)
17106 return err;
17107
17108 src_reg_type = regs[insn->src_reg].type;
17109
17110 /* check that memory (src_reg + off) is readable,
17111 * the state of dst_reg will be updated by this func
17112 */
17113 err = check_mem_access(env, env->insn_idx, insn->src_reg,
17114 insn->off, BPF_SIZE(insn->code),
17115 BPF_READ, insn->dst_reg, false,
17116 BPF_MODE(insn->code) == BPF_MEMSX);
17117 if (err)
17118 return err;
17119
17120 err = save_aux_ptr_type(env, src_reg_type, true);
17121 if (err)
17122 return err;
17123 } else if (class == BPF_STX) {
17124 enum bpf_reg_type dst_reg_type;
17125
17126 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17127 err = check_atomic(env, env->insn_idx, insn);
17128 if (err)
17129 return err;
17130 env->insn_idx++;
17131 continue;
17132 }
17133
17134 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17135 verbose(env, "BPF_STX uses reserved fields\n");
17136 return -EINVAL;
17137 }
17138
17139 /* check src1 operand */
17140 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17141 if (err)
17142 return err;
17143 /* check src2 operand */
17144 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17145 if (err)
17146 return err;
17147
17148 dst_reg_type = regs[insn->dst_reg].type;
17149
17150 /* check that memory (dst_reg + off) is writeable */
17151 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17152 insn->off, BPF_SIZE(insn->code),
17153 BPF_WRITE, insn->src_reg, false, false);
17154 if (err)
17155 return err;
17156
17157 err = save_aux_ptr_type(env, dst_reg_type, false);
17158 if (err)
17159 return err;
17160 } else if (class == BPF_ST) {
17161 enum bpf_reg_type dst_reg_type;
17162
17163 if (BPF_MODE(insn->code) != BPF_MEM ||
17164 insn->src_reg != BPF_REG_0) {
17165 verbose(env, "BPF_ST uses reserved fields\n");
17166 return -EINVAL;
17167 }
17168 /* check src operand */
17169 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17170 if (err)
17171 return err;
17172
17173 dst_reg_type = regs[insn->dst_reg].type;
17174
17175 /* check that memory (dst_reg + off) is writeable */
17176 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17177 insn->off, BPF_SIZE(insn->code),
17178 BPF_WRITE, -1, false, false);
17179 if (err)
17180 return err;
17181
17182 err = save_aux_ptr_type(env, dst_reg_type, false);
17183 if (err)
17184 return err;
17185 } else if (class == BPF_JMP || class == BPF_JMP32) {
17186 u8 opcode = BPF_OP(insn->code);
17187
17188 env->jmps_processed++;
17189 if (opcode == BPF_CALL) {
17190 if (BPF_SRC(insn->code) != BPF_K ||
17191 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17192 && insn->off != 0) ||
17193 (insn->src_reg != BPF_REG_0 &&
17194 insn->src_reg != BPF_PSEUDO_CALL &&
17195 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17196 insn->dst_reg != BPF_REG_0 ||
17197 class == BPF_JMP32) {
17198 verbose(env, "BPF_CALL uses reserved fields\n");
17199 return -EINVAL;
17200 }
17201
17202 if (env->cur_state->active_lock.ptr) {
17203 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17204 (insn->src_reg == BPF_PSEUDO_CALL) ||
17205 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17206 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17207 verbose(env, "function calls are not allowed while holding a lock\n");
17208 return -EINVAL;
17209 }
17210 }
17211 if (insn->src_reg == BPF_PSEUDO_CALL)
17212 err = check_func_call(env, insn, &env->insn_idx);
17213 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
17214 err = check_kfunc_call(env, insn, &env->insn_idx);
17215 else
17216 err = check_helper_call(env, insn, &env->insn_idx);
17217 if (err)
17218 return err;
17219
17220 mark_reg_scratched(env, BPF_REG_0);
17221 } else if (opcode == BPF_JA) {
17222 if (BPF_SRC(insn->code) != BPF_K ||
17223 insn->src_reg != BPF_REG_0 ||
17224 insn->dst_reg != BPF_REG_0 ||
17225 (class == BPF_JMP && insn->imm != 0) ||
17226 (class == BPF_JMP32 && insn->off != 0)) {
17227 verbose(env, "BPF_JA uses reserved fields\n");
17228 return -EINVAL;
17229 }
17230
17231 if (class == BPF_JMP)
17232 env->insn_idx += insn->off + 1;
17233 else
17234 env->insn_idx += insn->imm + 1;
17235 continue;
17236
17237 } else if (opcode == BPF_EXIT) {
17238 if (BPF_SRC(insn->code) != BPF_K ||
17239 insn->imm != 0 ||
17240 insn->src_reg != BPF_REG_0 ||
17241 insn->dst_reg != BPF_REG_0 ||
17242 class == BPF_JMP32) {
17243 verbose(env, "BPF_EXIT uses reserved fields\n");
17244 return -EINVAL;
17245 }
17246
17247 if (env->cur_state->active_lock.ptr &&
17248 !in_rbtree_lock_required_cb(env)) {
17249 verbose(env, "bpf_spin_unlock is missing\n");
17250 return -EINVAL;
17251 }
17252
17253 if (env->cur_state->active_rcu_lock &&
17254 !in_rbtree_lock_required_cb(env)) {
17255 verbose(env, "bpf_rcu_read_unlock is missing\n");
17256 return -EINVAL;
17257 }
17258
17259 /* We must do check_reference_leak here before
17260 * prepare_func_exit to handle the case when
17261 * state->curframe > 0, it may be a callback
17262 * function, for which reference_state must
17263 * match caller reference state when it exits.
17264 */
17265 err = check_reference_leak(env);
17266 if (err)
17267 return err;
17268
17269 if (state->curframe) {
17270 /* exit from nested function */
17271 err = prepare_func_exit(env, &env->insn_idx);
17272 if (err)
17273 return err;
17274 do_print_state = true;
17275 continue;
17276 }
17277
17278 err = check_return_code(env);
17279 if (err)
17280 return err;
17281 process_bpf_exit:
17282 mark_verifier_state_scratched(env);
17283 update_branch_counts(env, env->cur_state);
17284 err = pop_stack(env, &prev_insn_idx,
17285 &env->insn_idx, pop_log);
17286 if (err < 0) {
17287 if (err != -ENOENT)
17288 return err;
17289 break;
17290 } else {
17291 do_print_state = true;
17292 continue;
17293 }
17294 } else {
17295 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17296 if (err)
17297 return err;
17298 }
17299 } else if (class == BPF_LD) {
17300 u8 mode = BPF_MODE(insn->code);
17301
17302 if (mode == BPF_ABS || mode == BPF_IND) {
17303 err = check_ld_abs(env, insn);
17304 if (err)
17305 return err;
17306
17307 } else if (mode == BPF_IMM) {
17308 err = check_ld_imm(env, insn);
17309 if (err)
17310 return err;
17311
17312 env->insn_idx++;
17313 sanitize_mark_insn_seen(env);
17314 } else {
17315 verbose(env, "invalid BPF_LD mode\n");
17316 return -EINVAL;
17317 }
17318 } else {
17319 verbose(env, "unknown insn class %d\n", class);
17320 return -EINVAL;
17321 }
17322
17323 env->insn_idx++;
17324 }
17325
17326 return 0;
17327 }
17328
find_btf_percpu_datasec(struct btf * btf)17329 static int find_btf_percpu_datasec(struct btf *btf)
17330 {
17331 const struct btf_type *t;
17332 const char *tname;
17333 int i, n;
17334
17335 /*
17336 * Both vmlinux and module each have their own ".data..percpu"
17337 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17338 * types to look at only module's own BTF types.
17339 */
17340 n = btf_nr_types(btf);
17341 if (btf_is_module(btf))
17342 i = btf_nr_types(btf_vmlinux);
17343 else
17344 i = 1;
17345
17346 for(; i < n; i++) {
17347 t = btf_type_by_id(btf, i);
17348 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17349 continue;
17350
17351 tname = btf_name_by_offset(btf, t->name_off);
17352 if (!strcmp(tname, ".data..percpu"))
17353 return i;
17354 }
17355
17356 return -ENOENT;
17357 }
17358
17359 /* replace pseudo btf_id with kernel symbol address */
check_pseudo_btf_id(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn_aux_data * aux)17360 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17361 struct bpf_insn *insn,
17362 struct bpf_insn_aux_data *aux)
17363 {
17364 const struct btf_var_secinfo *vsi;
17365 const struct btf_type *datasec;
17366 struct btf_mod_pair *btf_mod;
17367 const struct btf_type *t;
17368 const char *sym_name;
17369 bool percpu = false;
17370 u32 type, id = insn->imm;
17371 struct btf *btf;
17372 s32 datasec_id;
17373 u64 addr;
17374 int i, btf_fd, err;
17375
17376 btf_fd = insn[1].imm;
17377 if (btf_fd) {
17378 btf = btf_get_by_fd(btf_fd);
17379 if (IS_ERR(btf)) {
17380 verbose(env, "invalid module BTF object FD specified.\n");
17381 return -EINVAL;
17382 }
17383 } else {
17384 if (!btf_vmlinux) {
17385 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17386 return -EINVAL;
17387 }
17388 btf = btf_vmlinux;
17389 btf_get(btf);
17390 }
17391
17392 t = btf_type_by_id(btf, id);
17393 if (!t) {
17394 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17395 err = -ENOENT;
17396 goto err_put;
17397 }
17398
17399 if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17400 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17401 err = -EINVAL;
17402 goto err_put;
17403 }
17404
17405 sym_name = btf_name_by_offset(btf, t->name_off);
17406 addr = kallsyms_lookup_name(sym_name);
17407 if (!addr) {
17408 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17409 sym_name);
17410 err = -ENOENT;
17411 goto err_put;
17412 }
17413 insn[0].imm = (u32)addr;
17414 insn[1].imm = addr >> 32;
17415
17416 if (btf_type_is_func(t)) {
17417 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17418 aux->btf_var.mem_size = 0;
17419 goto check_btf;
17420 }
17421
17422 datasec_id = find_btf_percpu_datasec(btf);
17423 if (datasec_id > 0) {
17424 datasec = btf_type_by_id(btf, datasec_id);
17425 for_each_vsi(i, datasec, vsi) {
17426 if (vsi->type == id) {
17427 percpu = true;
17428 break;
17429 }
17430 }
17431 }
17432
17433 type = t->type;
17434 t = btf_type_skip_modifiers(btf, type, NULL);
17435 if (percpu) {
17436 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17437 aux->btf_var.btf = btf;
17438 aux->btf_var.btf_id = type;
17439 } else if (!btf_type_is_struct(t)) {
17440 const struct btf_type *ret;
17441 const char *tname;
17442 u32 tsize;
17443
17444 /* resolve the type size of ksym. */
17445 ret = btf_resolve_size(btf, t, &tsize);
17446 if (IS_ERR(ret)) {
17447 tname = btf_name_by_offset(btf, t->name_off);
17448 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17449 tname, PTR_ERR(ret));
17450 err = -EINVAL;
17451 goto err_put;
17452 }
17453 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17454 aux->btf_var.mem_size = tsize;
17455 } else {
17456 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17457 aux->btf_var.btf = btf;
17458 aux->btf_var.btf_id = type;
17459 }
17460 check_btf:
17461 /* check whether we recorded this BTF (and maybe module) already */
17462 for (i = 0; i < env->used_btf_cnt; i++) {
17463 if (env->used_btfs[i].btf == btf) {
17464 btf_put(btf);
17465 return 0;
17466 }
17467 }
17468
17469 if (env->used_btf_cnt >= MAX_USED_BTFS) {
17470 err = -E2BIG;
17471 goto err_put;
17472 }
17473
17474 btf_mod = &env->used_btfs[env->used_btf_cnt];
17475 btf_mod->btf = btf;
17476 btf_mod->module = NULL;
17477
17478 /* if we reference variables from kernel module, bump its refcount */
17479 if (btf_is_module(btf)) {
17480 btf_mod->module = btf_try_get_module(btf);
17481 if (!btf_mod->module) {
17482 err = -ENXIO;
17483 goto err_put;
17484 }
17485 }
17486
17487 env->used_btf_cnt++;
17488
17489 return 0;
17490 err_put:
17491 btf_put(btf);
17492 return err;
17493 }
17494
is_tracing_prog_type(enum bpf_prog_type type)17495 static bool is_tracing_prog_type(enum bpf_prog_type type)
17496 {
17497 switch (type) {
17498 case BPF_PROG_TYPE_KPROBE:
17499 case BPF_PROG_TYPE_TRACEPOINT:
17500 case BPF_PROG_TYPE_PERF_EVENT:
17501 case BPF_PROG_TYPE_RAW_TRACEPOINT:
17502 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17503 return true;
17504 default:
17505 return false;
17506 }
17507 }
17508
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)17509 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17510 struct bpf_map *map,
17511 struct bpf_prog *prog)
17512
17513 {
17514 enum bpf_prog_type prog_type = resolve_prog_type(prog);
17515
17516 if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17517 btf_record_has_field(map->record, BPF_RB_ROOT)) {
17518 if (is_tracing_prog_type(prog_type)) {
17519 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17520 return -EINVAL;
17521 }
17522 }
17523
17524 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17525 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17526 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17527 return -EINVAL;
17528 }
17529
17530 if (is_tracing_prog_type(prog_type)) {
17531 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17532 return -EINVAL;
17533 }
17534 }
17535
17536 if (btf_record_has_field(map->record, BPF_TIMER)) {
17537 if (is_tracing_prog_type(prog_type)) {
17538 verbose(env, "tracing progs cannot use bpf_timer yet\n");
17539 return -EINVAL;
17540 }
17541 }
17542
17543 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17544 !bpf_offload_prog_map_match(prog, map)) {
17545 verbose(env, "offload device mismatch between prog and map\n");
17546 return -EINVAL;
17547 }
17548
17549 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17550 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17551 return -EINVAL;
17552 }
17553
17554 if (prog->aux->sleepable)
17555 switch (map->map_type) {
17556 case BPF_MAP_TYPE_HASH:
17557 case BPF_MAP_TYPE_LRU_HASH:
17558 case BPF_MAP_TYPE_ARRAY:
17559 case BPF_MAP_TYPE_PERCPU_HASH:
17560 case BPF_MAP_TYPE_PERCPU_ARRAY:
17561 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17562 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17563 case BPF_MAP_TYPE_HASH_OF_MAPS:
17564 case BPF_MAP_TYPE_RINGBUF:
17565 case BPF_MAP_TYPE_USER_RINGBUF:
17566 case BPF_MAP_TYPE_INODE_STORAGE:
17567 case BPF_MAP_TYPE_SK_STORAGE:
17568 case BPF_MAP_TYPE_TASK_STORAGE:
17569 case BPF_MAP_TYPE_CGRP_STORAGE:
17570 break;
17571 default:
17572 verbose(env,
17573 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17574 return -EINVAL;
17575 }
17576
17577 return 0;
17578 }
17579
bpf_map_is_cgroup_storage(struct bpf_map * map)17580 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17581 {
17582 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17583 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17584 }
17585
17586 /* find and rewrite pseudo imm in ld_imm64 instructions:
17587 *
17588 * 1. if it accesses map FD, replace it with actual map pointer.
17589 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17590 *
17591 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17592 */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)17593 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17594 {
17595 struct bpf_insn *insn = env->prog->insnsi;
17596 int insn_cnt = env->prog->len;
17597 int i, j, err;
17598
17599 err = bpf_prog_calc_tag(env->prog);
17600 if (err)
17601 return err;
17602
17603 for (i = 0; i < insn_cnt; i++, insn++) {
17604 if (BPF_CLASS(insn->code) == BPF_LDX &&
17605 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17606 insn->imm != 0)) {
17607 verbose(env, "BPF_LDX uses reserved fields\n");
17608 return -EINVAL;
17609 }
17610
17611 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17612 struct bpf_insn_aux_data *aux;
17613 struct bpf_map *map;
17614 struct fd f;
17615 u64 addr;
17616 u32 fd;
17617
17618 if (i == insn_cnt - 1 || insn[1].code != 0 ||
17619 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17620 insn[1].off != 0) {
17621 verbose(env, "invalid bpf_ld_imm64 insn\n");
17622 return -EINVAL;
17623 }
17624
17625 if (insn[0].src_reg == 0)
17626 /* valid generic load 64-bit imm */
17627 goto next_insn;
17628
17629 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17630 aux = &env->insn_aux_data[i];
17631 err = check_pseudo_btf_id(env, insn, aux);
17632 if (err)
17633 return err;
17634 goto next_insn;
17635 }
17636
17637 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17638 aux = &env->insn_aux_data[i];
17639 aux->ptr_type = PTR_TO_FUNC;
17640 goto next_insn;
17641 }
17642
17643 /* In final convert_pseudo_ld_imm64() step, this is
17644 * converted into regular 64-bit imm load insn.
17645 */
17646 switch (insn[0].src_reg) {
17647 case BPF_PSEUDO_MAP_VALUE:
17648 case BPF_PSEUDO_MAP_IDX_VALUE:
17649 break;
17650 case BPF_PSEUDO_MAP_FD:
17651 case BPF_PSEUDO_MAP_IDX:
17652 if (insn[1].imm == 0)
17653 break;
17654 fallthrough;
17655 default:
17656 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17657 return -EINVAL;
17658 }
17659
17660 switch (insn[0].src_reg) {
17661 case BPF_PSEUDO_MAP_IDX_VALUE:
17662 case BPF_PSEUDO_MAP_IDX:
17663 if (bpfptr_is_null(env->fd_array)) {
17664 verbose(env, "fd_idx without fd_array is invalid\n");
17665 return -EPROTO;
17666 }
17667 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17668 insn[0].imm * sizeof(fd),
17669 sizeof(fd)))
17670 return -EFAULT;
17671 break;
17672 default:
17673 fd = insn[0].imm;
17674 break;
17675 }
17676
17677 f = fdget(fd);
17678 map = __bpf_map_get(f);
17679 if (IS_ERR(map)) {
17680 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd);
17681 return PTR_ERR(map);
17682 }
17683
17684 err = check_map_prog_compatibility(env, map, env->prog);
17685 if (err) {
17686 fdput(f);
17687 return err;
17688 }
17689
17690 aux = &env->insn_aux_data[i];
17691 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17692 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17693 addr = (unsigned long)map;
17694 } else {
17695 u32 off = insn[1].imm;
17696
17697 if (off >= BPF_MAX_VAR_OFF) {
17698 verbose(env, "direct value offset of %u is not allowed\n", off);
17699 fdput(f);
17700 return -EINVAL;
17701 }
17702
17703 if (!map->ops->map_direct_value_addr) {
17704 verbose(env, "no direct value access support for this map type\n");
17705 fdput(f);
17706 return -EINVAL;
17707 }
17708
17709 err = map->ops->map_direct_value_addr(map, &addr, off);
17710 if (err) {
17711 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17712 map->value_size, off);
17713 fdput(f);
17714 return err;
17715 }
17716
17717 aux->map_off = off;
17718 addr += off;
17719 }
17720
17721 insn[0].imm = (u32)addr;
17722 insn[1].imm = addr >> 32;
17723
17724 /* check whether we recorded this map already */
17725 for (j = 0; j < env->used_map_cnt; j++) {
17726 if (env->used_maps[j] == map) {
17727 aux->map_index = j;
17728 fdput(f);
17729 goto next_insn;
17730 }
17731 }
17732
17733 if (env->used_map_cnt >= MAX_USED_MAPS) {
17734 fdput(f);
17735 return -E2BIG;
17736 }
17737
17738 /* hold the map. If the program is rejected by verifier,
17739 * the map will be released by release_maps() or it
17740 * will be used by the valid program until it's unloaded
17741 * and all maps are released in free_used_maps()
17742 */
17743 bpf_map_inc(map);
17744
17745 aux->map_index = env->used_map_cnt;
17746 env->used_maps[env->used_map_cnt++] = map;
17747
17748 if (bpf_map_is_cgroup_storage(map) &&
17749 bpf_cgroup_storage_assign(env->prog->aux, map)) {
17750 verbose(env, "only one cgroup storage of each type is allowed\n");
17751 fdput(f);
17752 return -EBUSY;
17753 }
17754
17755 fdput(f);
17756 next_insn:
17757 insn++;
17758 i++;
17759 continue;
17760 }
17761
17762 /* Basic sanity check before we invest more work here. */
17763 if (!bpf_opcode_in_insntable(insn->code)) {
17764 verbose(env, "unknown opcode %02x\n", insn->code);
17765 return -EINVAL;
17766 }
17767 }
17768
17769 /* now all pseudo BPF_LD_IMM64 instructions load valid
17770 * 'struct bpf_map *' into a register instead of user map_fd.
17771 * These pointers will be used later by verifier to validate map access.
17772 */
17773 return 0;
17774 }
17775
17776 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)17777 static void release_maps(struct bpf_verifier_env *env)
17778 {
17779 __bpf_free_used_maps(env->prog->aux, env->used_maps,
17780 env->used_map_cnt);
17781 }
17782
17783 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)17784 static void release_btfs(struct bpf_verifier_env *env)
17785 {
17786 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17787 env->used_btf_cnt);
17788 }
17789
17790 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)17791 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17792 {
17793 struct bpf_insn *insn = env->prog->insnsi;
17794 int insn_cnt = env->prog->len;
17795 int i;
17796
17797 for (i = 0; i < insn_cnt; i++, insn++) {
17798 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17799 continue;
17800 if (insn->src_reg == BPF_PSEUDO_FUNC)
17801 continue;
17802 insn->src_reg = 0;
17803 }
17804 }
17805
17806 /* single env->prog->insni[off] instruction was replaced with the range
17807 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
17808 * [0, off) and [off, end) to new locations, so the patched range stays zero
17809 */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_insn_aux_data * new_data,struct bpf_prog * new_prog,u32 off,u32 cnt)17810 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17811 struct bpf_insn_aux_data *new_data,
17812 struct bpf_prog *new_prog, u32 off, u32 cnt)
17813 {
17814 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17815 struct bpf_insn *insn = new_prog->insnsi;
17816 u32 old_seen = old_data[off].seen;
17817 u32 prog_len;
17818 int i;
17819
17820 /* aux info at OFF always needs adjustment, no matter fast path
17821 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17822 * original insn at old prog.
17823 */
17824 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17825
17826 if (cnt == 1)
17827 return;
17828 prog_len = new_prog->len;
17829
17830 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17831 memcpy(new_data + off + cnt - 1, old_data + off,
17832 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17833 for (i = off; i < off + cnt - 1; i++) {
17834 /* Expand insni[off]'s seen count to the patched range. */
17835 new_data[i].seen = old_seen;
17836 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17837 }
17838 env->insn_aux_data = new_data;
17839 vfree(old_data);
17840 }
17841
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)17842 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17843 {
17844 int i;
17845
17846 if (len == 1)
17847 return;
17848 /* NOTE: fake 'exit' subprog should be updated as well. */
17849 for (i = 0; i <= env->subprog_cnt; i++) {
17850 if (env->subprog_info[i].start <= off)
17851 continue;
17852 env->subprog_info[i].start += len - 1;
17853 }
17854 }
17855
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)17856 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17857 {
17858 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17859 int i, sz = prog->aux->size_poke_tab;
17860 struct bpf_jit_poke_descriptor *desc;
17861
17862 for (i = 0; i < sz; i++) {
17863 desc = &tab[i];
17864 if (desc->insn_idx <= off)
17865 continue;
17866 desc->insn_idx += len - 1;
17867 }
17868 }
17869
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)17870 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17871 const struct bpf_insn *patch, u32 len)
17872 {
17873 struct bpf_prog *new_prog;
17874 struct bpf_insn_aux_data *new_data = NULL;
17875
17876 if (len > 1) {
17877 new_data = vzalloc(array_size(env->prog->len + len - 1,
17878 sizeof(struct bpf_insn_aux_data)));
17879 if (!new_data)
17880 return NULL;
17881 }
17882
17883 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17884 if (IS_ERR(new_prog)) {
17885 if (PTR_ERR(new_prog) == -ERANGE)
17886 verbose(env,
17887 "insn %d cannot be patched due to 16-bit range\n",
17888 env->insn_aux_data[off].orig_idx);
17889 vfree(new_data);
17890 return NULL;
17891 }
17892 adjust_insn_aux_data(env, new_data, new_prog, off, len);
17893 adjust_subprog_starts(env, off, len);
17894 adjust_poke_descs(new_prog, off, len);
17895 return new_prog;
17896 }
17897
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)17898 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17899 u32 off, u32 cnt)
17900 {
17901 int i, j;
17902
17903 /* find first prog starting at or after off (first to remove) */
17904 for (i = 0; i < env->subprog_cnt; i++)
17905 if (env->subprog_info[i].start >= off)
17906 break;
17907 /* find first prog starting at or after off + cnt (first to stay) */
17908 for (j = i; j < env->subprog_cnt; j++)
17909 if (env->subprog_info[j].start >= off + cnt)
17910 break;
17911 /* if j doesn't start exactly at off + cnt, we are just removing
17912 * the front of previous prog
17913 */
17914 if (env->subprog_info[j].start != off + cnt)
17915 j--;
17916
17917 if (j > i) {
17918 struct bpf_prog_aux *aux = env->prog->aux;
17919 int move;
17920
17921 /* move fake 'exit' subprog as well */
17922 move = env->subprog_cnt + 1 - j;
17923
17924 memmove(env->subprog_info + i,
17925 env->subprog_info + j,
17926 sizeof(*env->subprog_info) * move);
17927 env->subprog_cnt -= j - i;
17928
17929 /* remove func_info */
17930 if (aux->func_info) {
17931 move = aux->func_info_cnt - j;
17932
17933 memmove(aux->func_info + i,
17934 aux->func_info + j,
17935 sizeof(*aux->func_info) * move);
17936 aux->func_info_cnt -= j - i;
17937 /* func_info->insn_off is set after all code rewrites,
17938 * in adjust_btf_func() - no need to adjust
17939 */
17940 }
17941 } else {
17942 /* convert i from "first prog to remove" to "first to adjust" */
17943 if (env->subprog_info[i].start == off)
17944 i++;
17945 }
17946
17947 /* update fake 'exit' subprog as well */
17948 for (; i <= env->subprog_cnt; i++)
17949 env->subprog_info[i].start -= cnt;
17950
17951 return 0;
17952 }
17953
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)17954 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17955 u32 cnt)
17956 {
17957 struct bpf_prog *prog = env->prog;
17958 u32 i, l_off, l_cnt, nr_linfo;
17959 struct bpf_line_info *linfo;
17960
17961 nr_linfo = prog->aux->nr_linfo;
17962 if (!nr_linfo)
17963 return 0;
17964
17965 linfo = prog->aux->linfo;
17966
17967 /* find first line info to remove, count lines to be removed */
17968 for (i = 0; i < nr_linfo; i++)
17969 if (linfo[i].insn_off >= off)
17970 break;
17971
17972 l_off = i;
17973 l_cnt = 0;
17974 for (; i < nr_linfo; i++)
17975 if (linfo[i].insn_off < off + cnt)
17976 l_cnt++;
17977 else
17978 break;
17979
17980 /* First live insn doesn't match first live linfo, it needs to "inherit"
17981 * last removed linfo. prog is already modified, so prog->len == off
17982 * means no live instructions after (tail of the program was removed).
17983 */
17984 if (prog->len != off && l_cnt &&
17985 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17986 l_cnt--;
17987 linfo[--i].insn_off = off + cnt;
17988 }
17989
17990 /* remove the line info which refer to the removed instructions */
17991 if (l_cnt) {
17992 memmove(linfo + l_off, linfo + i,
17993 sizeof(*linfo) * (nr_linfo - i));
17994
17995 prog->aux->nr_linfo -= l_cnt;
17996 nr_linfo = prog->aux->nr_linfo;
17997 }
17998
17999 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18000 for (i = l_off; i < nr_linfo; i++)
18001 linfo[i].insn_off -= cnt;
18002
18003 /* fix up all subprogs (incl. 'exit') which start >= off */
18004 for (i = 0; i <= env->subprog_cnt; i++)
18005 if (env->subprog_info[i].linfo_idx > l_off) {
18006 /* program may have started in the removed region but
18007 * may not be fully removed
18008 */
18009 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18010 env->subprog_info[i].linfo_idx -= l_cnt;
18011 else
18012 env->subprog_info[i].linfo_idx = l_off;
18013 }
18014
18015 return 0;
18016 }
18017
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)18018 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18019 {
18020 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18021 unsigned int orig_prog_len = env->prog->len;
18022 int err;
18023
18024 if (bpf_prog_is_offloaded(env->prog->aux))
18025 bpf_prog_offload_remove_insns(env, off, cnt);
18026
18027 err = bpf_remove_insns(env->prog, off, cnt);
18028 if (err)
18029 return err;
18030
18031 err = adjust_subprog_starts_after_remove(env, off, cnt);
18032 if (err)
18033 return err;
18034
18035 err = bpf_adj_linfo_after_remove(env, off, cnt);
18036 if (err)
18037 return err;
18038
18039 memmove(aux_data + off, aux_data + off + cnt,
18040 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18041
18042 return 0;
18043 }
18044
18045 /* The verifier does more data flow analysis than llvm and will not
18046 * explore branches that are dead at run time. Malicious programs can
18047 * have dead code too. Therefore replace all dead at-run-time code
18048 * with 'ja -1'.
18049 *
18050 * Just nops are not optimal, e.g. if they would sit at the end of the
18051 * program and through another bug we would manage to jump there, then
18052 * we'd execute beyond program memory otherwise. Returning exception
18053 * code also wouldn't work since we can have subprogs where the dead
18054 * code could be located.
18055 */
sanitize_dead_code(struct bpf_verifier_env * env)18056 static void sanitize_dead_code(struct bpf_verifier_env *env)
18057 {
18058 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18059 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18060 struct bpf_insn *insn = env->prog->insnsi;
18061 const int insn_cnt = env->prog->len;
18062 int i;
18063
18064 for (i = 0; i < insn_cnt; i++) {
18065 if (aux_data[i].seen)
18066 continue;
18067 memcpy(insn + i, &trap, sizeof(trap));
18068 aux_data[i].zext_dst = false;
18069 }
18070 }
18071
insn_is_cond_jump(u8 code)18072 static bool insn_is_cond_jump(u8 code)
18073 {
18074 u8 op;
18075
18076 op = BPF_OP(code);
18077 if (BPF_CLASS(code) == BPF_JMP32)
18078 return op != BPF_JA;
18079
18080 if (BPF_CLASS(code) != BPF_JMP)
18081 return false;
18082
18083 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18084 }
18085
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)18086 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18087 {
18088 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18089 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18090 struct bpf_insn *insn = env->prog->insnsi;
18091 const int insn_cnt = env->prog->len;
18092 int i;
18093
18094 for (i = 0; i < insn_cnt; i++, insn++) {
18095 if (!insn_is_cond_jump(insn->code))
18096 continue;
18097
18098 if (!aux_data[i + 1].seen)
18099 ja.off = insn->off;
18100 else if (!aux_data[i + 1 + insn->off].seen)
18101 ja.off = 0;
18102 else
18103 continue;
18104
18105 if (bpf_prog_is_offloaded(env->prog->aux))
18106 bpf_prog_offload_replace_insn(env, i, &ja);
18107
18108 memcpy(insn, &ja, sizeof(ja));
18109 }
18110 }
18111
opt_remove_dead_code(struct bpf_verifier_env * env)18112 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18113 {
18114 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18115 int insn_cnt = env->prog->len;
18116 int i, err;
18117
18118 for (i = 0; i < insn_cnt; i++) {
18119 int j;
18120
18121 j = 0;
18122 while (i + j < insn_cnt && !aux_data[i + j].seen)
18123 j++;
18124 if (!j)
18125 continue;
18126
18127 err = verifier_remove_insns(env, i, j);
18128 if (err)
18129 return err;
18130 insn_cnt = env->prog->len;
18131 }
18132
18133 return 0;
18134 }
18135
opt_remove_nops(struct bpf_verifier_env * env)18136 static int opt_remove_nops(struct bpf_verifier_env *env)
18137 {
18138 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18139 struct bpf_insn *insn = env->prog->insnsi;
18140 int insn_cnt = env->prog->len;
18141 int i, err;
18142
18143 for (i = 0; i < insn_cnt; i++) {
18144 if (memcmp(&insn[i], &ja, sizeof(ja)))
18145 continue;
18146
18147 err = verifier_remove_insns(env, i, 1);
18148 if (err)
18149 return err;
18150 insn_cnt--;
18151 i--;
18152 }
18153
18154 return 0;
18155 }
18156
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)18157 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18158 const union bpf_attr *attr)
18159 {
18160 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18161 struct bpf_insn_aux_data *aux = env->insn_aux_data;
18162 int i, patch_len, delta = 0, len = env->prog->len;
18163 struct bpf_insn *insns = env->prog->insnsi;
18164 struct bpf_prog *new_prog;
18165 bool rnd_hi32;
18166
18167 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18168 zext_patch[1] = BPF_ZEXT_REG(0);
18169 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18170 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18171 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18172 for (i = 0; i < len; i++) {
18173 int adj_idx = i + delta;
18174 struct bpf_insn insn;
18175 int load_reg;
18176
18177 insn = insns[adj_idx];
18178 load_reg = insn_def_regno(&insn);
18179 if (!aux[adj_idx].zext_dst) {
18180 u8 code, class;
18181 u32 imm_rnd;
18182
18183 if (!rnd_hi32)
18184 continue;
18185
18186 code = insn.code;
18187 class = BPF_CLASS(code);
18188 if (load_reg == -1)
18189 continue;
18190
18191 /* NOTE: arg "reg" (the fourth one) is only used for
18192 * BPF_STX + SRC_OP, so it is safe to pass NULL
18193 * here.
18194 */
18195 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18196 if (class == BPF_LD &&
18197 BPF_MODE(code) == BPF_IMM)
18198 i++;
18199 continue;
18200 }
18201
18202 /* ctx load could be transformed into wider load. */
18203 if (class == BPF_LDX &&
18204 aux[adj_idx].ptr_type == PTR_TO_CTX)
18205 continue;
18206
18207 imm_rnd = get_random_u32();
18208 rnd_hi32_patch[0] = insn;
18209 rnd_hi32_patch[1].imm = imm_rnd;
18210 rnd_hi32_patch[3].dst_reg = load_reg;
18211 patch = rnd_hi32_patch;
18212 patch_len = 4;
18213 goto apply_patch_buffer;
18214 }
18215
18216 /* Add in an zero-extend instruction if a) the JIT has requested
18217 * it or b) it's a CMPXCHG.
18218 *
18219 * The latter is because: BPF_CMPXCHG always loads a value into
18220 * R0, therefore always zero-extends. However some archs'
18221 * equivalent instruction only does this load when the
18222 * comparison is successful. This detail of CMPXCHG is
18223 * orthogonal to the general zero-extension behaviour of the
18224 * CPU, so it's treated independently of bpf_jit_needs_zext.
18225 */
18226 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18227 continue;
18228
18229 /* Zero-extension is done by the caller. */
18230 if (bpf_pseudo_kfunc_call(&insn))
18231 continue;
18232
18233 if (WARN_ON(load_reg == -1)) {
18234 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18235 return -EFAULT;
18236 }
18237
18238 zext_patch[0] = insn;
18239 zext_patch[1].dst_reg = load_reg;
18240 zext_patch[1].src_reg = load_reg;
18241 patch = zext_patch;
18242 patch_len = 2;
18243 apply_patch_buffer:
18244 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18245 if (!new_prog)
18246 return -ENOMEM;
18247 env->prog = new_prog;
18248 insns = new_prog->insnsi;
18249 aux = env->insn_aux_data;
18250 delta += patch_len - 1;
18251 }
18252
18253 return 0;
18254 }
18255
18256 /* convert load instructions that access fields of a context type into a
18257 * sequence of instructions that access fields of the underlying structure:
18258 * struct __sk_buff -> struct sk_buff
18259 * struct bpf_sock_ops -> struct sock
18260 */
convert_ctx_accesses(struct bpf_verifier_env * env)18261 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18262 {
18263 const struct bpf_verifier_ops *ops = env->ops;
18264 int i, cnt, size, ctx_field_size, delta = 0;
18265 const int insn_cnt = env->prog->len;
18266 struct bpf_insn insn_buf[16], *insn;
18267 u32 target_size, size_default, off;
18268 struct bpf_prog *new_prog;
18269 enum bpf_access_type type;
18270 bool is_narrower_load;
18271
18272 if (ops->gen_prologue || env->seen_direct_write) {
18273 if (!ops->gen_prologue) {
18274 verbose(env, "bpf verifier is misconfigured\n");
18275 return -EINVAL;
18276 }
18277 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18278 env->prog);
18279 if (cnt >= ARRAY_SIZE(insn_buf)) {
18280 verbose(env, "bpf verifier is misconfigured\n");
18281 return -EINVAL;
18282 } else if (cnt) {
18283 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18284 if (!new_prog)
18285 return -ENOMEM;
18286
18287 env->prog = new_prog;
18288 delta += cnt - 1;
18289 }
18290 }
18291
18292 if (bpf_prog_is_offloaded(env->prog->aux))
18293 return 0;
18294
18295 insn = env->prog->insnsi + delta;
18296
18297 for (i = 0; i < insn_cnt; i++, insn++) {
18298 bpf_convert_ctx_access_t convert_ctx_access;
18299 u8 mode;
18300
18301 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18302 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18303 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18304 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18305 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18306 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18307 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18308 type = BPF_READ;
18309 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18310 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18311 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18312 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18313 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18314 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18315 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18316 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18317 type = BPF_WRITE;
18318 } else {
18319 continue;
18320 }
18321
18322 if (type == BPF_WRITE &&
18323 env->insn_aux_data[i + delta].sanitize_stack_spill) {
18324 struct bpf_insn patch[] = {
18325 *insn,
18326 BPF_ST_NOSPEC(),
18327 };
18328
18329 cnt = ARRAY_SIZE(patch);
18330 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18331 if (!new_prog)
18332 return -ENOMEM;
18333
18334 delta += cnt - 1;
18335 env->prog = new_prog;
18336 insn = new_prog->insnsi + i + delta;
18337 continue;
18338 }
18339
18340 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18341 case PTR_TO_CTX:
18342 if (!ops->convert_ctx_access)
18343 continue;
18344 convert_ctx_access = ops->convert_ctx_access;
18345 break;
18346 case PTR_TO_SOCKET:
18347 case PTR_TO_SOCK_COMMON:
18348 convert_ctx_access = bpf_sock_convert_ctx_access;
18349 break;
18350 case PTR_TO_TCP_SOCK:
18351 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18352 break;
18353 case PTR_TO_XDP_SOCK:
18354 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18355 break;
18356 case PTR_TO_BTF_ID:
18357 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18358 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18359 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18360 * be said once it is marked PTR_UNTRUSTED, hence we must handle
18361 * any faults for loads into such types. BPF_WRITE is disallowed
18362 * for this case.
18363 */
18364 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18365 if (type == BPF_READ) {
18366 if (BPF_MODE(insn->code) == BPF_MEM)
18367 insn->code = BPF_LDX | BPF_PROBE_MEM |
18368 BPF_SIZE((insn)->code);
18369 else
18370 insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18371 BPF_SIZE((insn)->code);
18372 env->prog->aux->num_exentries++;
18373 }
18374 continue;
18375 default:
18376 continue;
18377 }
18378
18379 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18380 size = BPF_LDST_BYTES(insn);
18381 mode = BPF_MODE(insn->code);
18382
18383 /* If the read access is a narrower load of the field,
18384 * convert to a 4/8-byte load, to minimum program type specific
18385 * convert_ctx_access changes. If conversion is successful,
18386 * we will apply proper mask to the result.
18387 */
18388 is_narrower_load = size < ctx_field_size;
18389 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18390 off = insn->off;
18391 if (is_narrower_load) {
18392 u8 size_code;
18393
18394 if (type == BPF_WRITE) {
18395 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18396 return -EINVAL;
18397 }
18398
18399 size_code = BPF_H;
18400 if (ctx_field_size == 4)
18401 size_code = BPF_W;
18402 else if (ctx_field_size == 8)
18403 size_code = BPF_DW;
18404
18405 insn->off = off & ~(size_default - 1);
18406 insn->code = BPF_LDX | BPF_MEM | size_code;
18407 }
18408
18409 target_size = 0;
18410 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18411 &target_size);
18412 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18413 (ctx_field_size && !target_size)) {
18414 verbose(env, "bpf verifier is misconfigured\n");
18415 return -EINVAL;
18416 }
18417
18418 if (is_narrower_load && size < target_size) {
18419 u8 shift = bpf_ctx_narrow_access_offset(
18420 off, size, size_default) * 8;
18421 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18422 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18423 return -EINVAL;
18424 }
18425 if (ctx_field_size <= 4) {
18426 if (shift)
18427 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18428 insn->dst_reg,
18429 shift);
18430 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18431 (1 << size * 8) - 1);
18432 } else {
18433 if (shift)
18434 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18435 insn->dst_reg,
18436 shift);
18437 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18438 (1ULL << size * 8) - 1);
18439 }
18440 }
18441 if (mode == BPF_MEMSX)
18442 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18443 insn->dst_reg, insn->dst_reg,
18444 size * 8, 0);
18445
18446 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18447 if (!new_prog)
18448 return -ENOMEM;
18449
18450 delta += cnt - 1;
18451
18452 /* keep walking new program and skip insns we just inserted */
18453 env->prog = new_prog;
18454 insn = new_prog->insnsi + i + delta;
18455 }
18456
18457 return 0;
18458 }
18459
jit_subprogs(struct bpf_verifier_env * env)18460 static int jit_subprogs(struct bpf_verifier_env *env)
18461 {
18462 struct bpf_prog *prog = env->prog, **func, *tmp;
18463 int i, j, subprog_start, subprog_end = 0, len, subprog;
18464 struct bpf_map *map_ptr;
18465 struct bpf_insn *insn;
18466 void *old_bpf_func;
18467 int err, num_exentries;
18468
18469 if (env->subprog_cnt <= 1)
18470 return 0;
18471
18472 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18473 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18474 continue;
18475
18476 /* Upon error here we cannot fall back to interpreter but
18477 * need a hard reject of the program. Thus -EFAULT is
18478 * propagated in any case.
18479 */
18480 subprog = find_subprog(env, i + insn->imm + 1);
18481 if (subprog < 0) {
18482 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18483 i + insn->imm + 1);
18484 return -EFAULT;
18485 }
18486 /* temporarily remember subprog id inside insn instead of
18487 * aux_data, since next loop will split up all insns into funcs
18488 */
18489 insn->off = subprog;
18490 /* remember original imm in case JIT fails and fallback
18491 * to interpreter will be needed
18492 */
18493 env->insn_aux_data[i].call_imm = insn->imm;
18494 /* point imm to __bpf_call_base+1 from JITs point of view */
18495 insn->imm = 1;
18496 if (bpf_pseudo_func(insn))
18497 /* jit (e.g. x86_64) may emit fewer instructions
18498 * if it learns a u32 imm is the same as a u64 imm.
18499 * Force a non zero here.
18500 */
18501 insn[1].imm = 1;
18502 }
18503
18504 err = bpf_prog_alloc_jited_linfo(prog);
18505 if (err)
18506 goto out_undo_insn;
18507
18508 err = -ENOMEM;
18509 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18510 if (!func)
18511 goto out_undo_insn;
18512
18513 for (i = 0; i < env->subprog_cnt; i++) {
18514 subprog_start = subprog_end;
18515 subprog_end = env->subprog_info[i + 1].start;
18516
18517 len = subprog_end - subprog_start;
18518 /* bpf_prog_run() doesn't call subprogs directly,
18519 * hence main prog stats include the runtime of subprogs.
18520 * subprogs don't have IDs and not reachable via prog_get_next_id
18521 * func[i]->stats will never be accessed and stays NULL
18522 */
18523 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18524 if (!func[i])
18525 goto out_free;
18526 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18527 len * sizeof(struct bpf_insn));
18528 func[i]->type = prog->type;
18529 func[i]->len = len;
18530 if (bpf_prog_calc_tag(func[i]))
18531 goto out_free;
18532 func[i]->is_func = 1;
18533 func[i]->aux->func_idx = i;
18534 /* Below members will be freed only at prog->aux */
18535 func[i]->aux->btf = prog->aux->btf;
18536 func[i]->aux->func_info = prog->aux->func_info;
18537 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18538 func[i]->aux->poke_tab = prog->aux->poke_tab;
18539 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18540
18541 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18542 struct bpf_jit_poke_descriptor *poke;
18543
18544 poke = &prog->aux->poke_tab[j];
18545 if (poke->insn_idx < subprog_end &&
18546 poke->insn_idx >= subprog_start)
18547 poke->aux = func[i]->aux;
18548 }
18549
18550 func[i]->aux->name[0] = 'F';
18551 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18552 func[i]->jit_requested = 1;
18553 func[i]->blinding_requested = prog->blinding_requested;
18554 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18555 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18556 func[i]->aux->linfo = prog->aux->linfo;
18557 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18558 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18559 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18560 num_exentries = 0;
18561 insn = func[i]->insnsi;
18562 for (j = 0; j < func[i]->len; j++, insn++) {
18563 if (BPF_CLASS(insn->code) == BPF_LDX &&
18564 (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18565 BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18566 num_exentries++;
18567 }
18568 func[i]->aux->num_exentries = num_exentries;
18569 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18570 func[i] = bpf_int_jit_compile(func[i]);
18571 if (!func[i]->jited) {
18572 err = -ENOTSUPP;
18573 goto out_free;
18574 }
18575 cond_resched();
18576 }
18577
18578 /* at this point all bpf functions were successfully JITed
18579 * now populate all bpf_calls with correct addresses and
18580 * run last pass of JIT
18581 */
18582 for (i = 0; i < env->subprog_cnt; i++) {
18583 insn = func[i]->insnsi;
18584 for (j = 0; j < func[i]->len; j++, insn++) {
18585 if (bpf_pseudo_func(insn)) {
18586 subprog = insn->off;
18587 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18588 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18589 continue;
18590 }
18591 if (!bpf_pseudo_call(insn))
18592 continue;
18593 subprog = insn->off;
18594 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18595 }
18596
18597 /* we use the aux data to keep a list of the start addresses
18598 * of the JITed images for each function in the program
18599 *
18600 * for some architectures, such as powerpc64, the imm field
18601 * might not be large enough to hold the offset of the start
18602 * address of the callee's JITed image from __bpf_call_base
18603 *
18604 * in such cases, we can lookup the start address of a callee
18605 * by using its subprog id, available from the off field of
18606 * the call instruction, as an index for this list
18607 */
18608 func[i]->aux->func = func;
18609 func[i]->aux->func_cnt = env->subprog_cnt;
18610 }
18611 for (i = 0; i < env->subprog_cnt; i++) {
18612 old_bpf_func = func[i]->bpf_func;
18613 tmp = bpf_int_jit_compile(func[i]);
18614 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18615 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18616 err = -ENOTSUPP;
18617 goto out_free;
18618 }
18619 cond_resched();
18620 }
18621
18622 /* finally lock prog and jit images for all functions and
18623 * populate kallsysm. Begin at the first subprogram, since
18624 * bpf_prog_load will add the kallsyms for the main program.
18625 */
18626 for (i = 1; i < env->subprog_cnt; i++) {
18627 bpf_prog_lock_ro(func[i]);
18628 bpf_prog_kallsyms_add(func[i]);
18629 }
18630
18631 /* Last step: make now unused interpreter insns from main
18632 * prog consistent for later dump requests, so they can
18633 * later look the same as if they were interpreted only.
18634 */
18635 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18636 if (bpf_pseudo_func(insn)) {
18637 insn[0].imm = env->insn_aux_data[i].call_imm;
18638 insn[1].imm = insn->off;
18639 insn->off = 0;
18640 continue;
18641 }
18642 if (!bpf_pseudo_call(insn))
18643 continue;
18644 insn->off = env->insn_aux_data[i].call_imm;
18645 subprog = find_subprog(env, i + insn->off + 1);
18646 insn->imm = subprog;
18647 }
18648
18649 prog->jited = 1;
18650 prog->bpf_func = func[0]->bpf_func;
18651 prog->jited_len = func[0]->jited_len;
18652 prog->aux->extable = func[0]->aux->extable;
18653 prog->aux->num_exentries = func[0]->aux->num_exentries;
18654 prog->aux->func = func;
18655 prog->aux->func_cnt = env->subprog_cnt;
18656 bpf_prog_jit_attempt_done(prog);
18657 return 0;
18658 out_free:
18659 /* We failed JIT'ing, so at this point we need to unregister poke
18660 * descriptors from subprogs, so that kernel is not attempting to
18661 * patch it anymore as we're freeing the subprog JIT memory.
18662 */
18663 for (i = 0; i < prog->aux->size_poke_tab; i++) {
18664 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18665 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18666 }
18667 /* At this point we're guaranteed that poke descriptors are not
18668 * live anymore. We can just unlink its descriptor table as it's
18669 * released with the main prog.
18670 */
18671 for (i = 0; i < env->subprog_cnt; i++) {
18672 if (!func[i])
18673 continue;
18674 func[i]->aux->poke_tab = NULL;
18675 bpf_jit_free(func[i]);
18676 }
18677 kfree(func);
18678 out_undo_insn:
18679 /* cleanup main prog to be interpreted */
18680 prog->jit_requested = 0;
18681 prog->blinding_requested = 0;
18682 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18683 if (!bpf_pseudo_call(insn))
18684 continue;
18685 insn->off = 0;
18686 insn->imm = env->insn_aux_data[i].call_imm;
18687 }
18688 bpf_prog_jit_attempt_done(prog);
18689 return err;
18690 }
18691
fixup_call_args(struct bpf_verifier_env * env)18692 static int fixup_call_args(struct bpf_verifier_env *env)
18693 {
18694 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18695 struct bpf_prog *prog = env->prog;
18696 struct bpf_insn *insn = prog->insnsi;
18697 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18698 int i, depth;
18699 #endif
18700 int err = 0;
18701
18702 if (env->prog->jit_requested &&
18703 !bpf_prog_is_offloaded(env->prog->aux)) {
18704 err = jit_subprogs(env);
18705 if (err == 0)
18706 return 0;
18707 if (err == -EFAULT)
18708 return err;
18709 }
18710 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18711 if (has_kfunc_call) {
18712 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18713 return -EINVAL;
18714 }
18715 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18716 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18717 * have to be rejected, since interpreter doesn't support them yet.
18718 */
18719 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18720 return -EINVAL;
18721 }
18722 for (i = 0; i < prog->len; i++, insn++) {
18723 if (bpf_pseudo_func(insn)) {
18724 /* When JIT fails the progs with callback calls
18725 * have to be rejected, since interpreter doesn't support them yet.
18726 */
18727 verbose(env, "callbacks are not allowed in non-JITed programs\n");
18728 return -EINVAL;
18729 }
18730
18731 if (!bpf_pseudo_call(insn))
18732 continue;
18733 depth = get_callee_stack_depth(env, insn, i);
18734 if (depth < 0)
18735 return depth;
18736 bpf_patch_call_args(insn, depth);
18737 }
18738 err = 0;
18739 #endif
18740 return err;
18741 }
18742
18743 /* replace a generic kfunc with a specialized version if necessary */
specialize_kfunc(struct bpf_verifier_env * env,u32 func_id,u16 offset,unsigned long * addr)18744 static void specialize_kfunc(struct bpf_verifier_env *env,
18745 u32 func_id, u16 offset, unsigned long *addr)
18746 {
18747 struct bpf_prog *prog = env->prog;
18748 bool seen_direct_write;
18749 void *xdp_kfunc;
18750 bool is_rdonly;
18751
18752 if (bpf_dev_bound_kfunc_id(func_id)) {
18753 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18754 if (xdp_kfunc) {
18755 *addr = (unsigned long)xdp_kfunc;
18756 return;
18757 }
18758 /* fallback to default kfunc when not supported by netdev */
18759 }
18760
18761 if (offset)
18762 return;
18763
18764 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18765 seen_direct_write = env->seen_direct_write;
18766 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18767
18768 if (is_rdonly)
18769 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18770
18771 /* restore env->seen_direct_write to its original value, since
18772 * may_access_direct_pkt_data mutates it
18773 */
18774 env->seen_direct_write = seen_direct_write;
18775 }
18776 }
18777
__fixup_collection_insert_kfunc(struct bpf_insn_aux_data * insn_aux,u16 struct_meta_reg,u16 node_offset_reg,struct bpf_insn * insn,struct bpf_insn * insn_buf,int * cnt)18778 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18779 u16 struct_meta_reg,
18780 u16 node_offset_reg,
18781 struct bpf_insn *insn,
18782 struct bpf_insn *insn_buf,
18783 int *cnt)
18784 {
18785 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18786 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18787
18788 insn_buf[0] = addr[0];
18789 insn_buf[1] = addr[1];
18790 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18791 insn_buf[3] = *insn;
18792 *cnt = 4;
18793 }
18794
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_insn * insn_buf,int insn_idx,int * cnt)18795 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18796 struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18797 {
18798 const struct bpf_kfunc_desc *desc;
18799
18800 if (!insn->imm) {
18801 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18802 return -EINVAL;
18803 }
18804
18805 *cnt = 0;
18806
18807 /* insn->imm has the btf func_id. Replace it with an offset relative to
18808 * __bpf_call_base, unless the JIT needs to call functions that are
18809 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18810 */
18811 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18812 if (!desc) {
18813 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18814 insn->imm);
18815 return -EFAULT;
18816 }
18817
18818 if (!bpf_jit_supports_far_kfunc_call())
18819 insn->imm = BPF_CALL_IMM(desc->addr);
18820 if (insn->off)
18821 return 0;
18822 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18823 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18824 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18825 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18826
18827 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18828 insn_buf[1] = addr[0];
18829 insn_buf[2] = addr[1];
18830 insn_buf[3] = *insn;
18831 *cnt = 4;
18832 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18833 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18834 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18835 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18836
18837 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18838 !kptr_struct_meta) {
18839 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18840 insn_idx);
18841 return -EFAULT;
18842 }
18843
18844 insn_buf[0] = addr[0];
18845 insn_buf[1] = addr[1];
18846 insn_buf[2] = *insn;
18847 *cnt = 3;
18848 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18849 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18850 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18851 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18852 int struct_meta_reg = BPF_REG_3;
18853 int node_offset_reg = BPF_REG_4;
18854
18855 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18856 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18857 struct_meta_reg = BPF_REG_4;
18858 node_offset_reg = BPF_REG_5;
18859 }
18860
18861 if (!kptr_struct_meta) {
18862 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18863 insn_idx);
18864 return -EFAULT;
18865 }
18866
18867 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18868 node_offset_reg, insn, insn_buf, cnt);
18869 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18870 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18871 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18872 *cnt = 1;
18873 }
18874 return 0;
18875 }
18876
18877 /* Do various post-verification rewrites in a single program pass.
18878 * These rewrites simplify JIT and interpreter implementations.
18879 */
do_misc_fixups(struct bpf_verifier_env * env)18880 static int do_misc_fixups(struct bpf_verifier_env *env)
18881 {
18882 struct bpf_prog *prog = env->prog;
18883 enum bpf_attach_type eatype = prog->expected_attach_type;
18884 enum bpf_prog_type prog_type = resolve_prog_type(prog);
18885 struct bpf_insn *insn = prog->insnsi;
18886 const struct bpf_func_proto *fn;
18887 const int insn_cnt = prog->len;
18888 const struct bpf_map_ops *ops;
18889 struct bpf_insn_aux_data *aux;
18890 struct bpf_insn insn_buf[16];
18891 struct bpf_prog *new_prog;
18892 struct bpf_map *map_ptr;
18893 int i, ret, cnt, delta = 0;
18894
18895 for (i = 0; i < insn_cnt; i++, insn++) {
18896 /* Make divide-by-zero exceptions impossible. */
18897 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18898 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18899 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18900 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18901 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18902 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18903 struct bpf_insn *patchlet;
18904 struct bpf_insn chk_and_div[] = {
18905 /* [R,W]x div 0 -> 0 */
18906 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18907 BPF_JNE | BPF_K, insn->src_reg,
18908 0, 2, 0),
18909 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18910 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18911 *insn,
18912 };
18913 struct bpf_insn chk_and_mod[] = {
18914 /* [R,W]x mod 0 -> [R,W]x */
18915 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18916 BPF_JEQ | BPF_K, insn->src_reg,
18917 0, 1 + (is64 ? 0 : 1), 0),
18918 *insn,
18919 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18920 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18921 };
18922
18923 patchlet = isdiv ? chk_and_div : chk_and_mod;
18924 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18925 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18926
18927 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18928 if (!new_prog)
18929 return -ENOMEM;
18930
18931 delta += cnt - 1;
18932 env->prog = prog = new_prog;
18933 insn = new_prog->insnsi + i + delta;
18934 continue;
18935 }
18936
18937 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18938 if (BPF_CLASS(insn->code) == BPF_LD &&
18939 (BPF_MODE(insn->code) == BPF_ABS ||
18940 BPF_MODE(insn->code) == BPF_IND)) {
18941 cnt = env->ops->gen_ld_abs(insn, insn_buf);
18942 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18943 verbose(env, "bpf verifier is misconfigured\n");
18944 return -EINVAL;
18945 }
18946
18947 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18948 if (!new_prog)
18949 return -ENOMEM;
18950
18951 delta += cnt - 1;
18952 env->prog = prog = new_prog;
18953 insn = new_prog->insnsi + i + delta;
18954 continue;
18955 }
18956
18957 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18958 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18959 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18960 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18961 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18962 struct bpf_insn *patch = &insn_buf[0];
18963 bool issrc, isneg, isimm;
18964 u32 off_reg;
18965
18966 aux = &env->insn_aux_data[i + delta];
18967 if (!aux->alu_state ||
18968 aux->alu_state == BPF_ALU_NON_POINTER)
18969 continue;
18970
18971 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18972 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18973 BPF_ALU_SANITIZE_SRC;
18974 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18975
18976 off_reg = issrc ? insn->src_reg : insn->dst_reg;
18977 if (isimm) {
18978 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18979 } else {
18980 if (isneg)
18981 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18982 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18983 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18984 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18985 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18986 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18987 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18988 }
18989 if (!issrc)
18990 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18991 insn->src_reg = BPF_REG_AX;
18992 if (isneg)
18993 insn->code = insn->code == code_add ?
18994 code_sub : code_add;
18995 *patch++ = *insn;
18996 if (issrc && isneg && !isimm)
18997 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18998 cnt = patch - insn_buf;
18999
19000 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19001 if (!new_prog)
19002 return -ENOMEM;
19003
19004 delta += cnt - 1;
19005 env->prog = prog = new_prog;
19006 insn = new_prog->insnsi + i + delta;
19007 continue;
19008 }
19009
19010 if (insn->code != (BPF_JMP | BPF_CALL))
19011 continue;
19012 if (insn->src_reg == BPF_PSEUDO_CALL)
19013 continue;
19014 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19015 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19016 if (ret)
19017 return ret;
19018 if (cnt == 0)
19019 continue;
19020
19021 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19022 if (!new_prog)
19023 return -ENOMEM;
19024
19025 delta += cnt - 1;
19026 env->prog = prog = new_prog;
19027 insn = new_prog->insnsi + i + delta;
19028 continue;
19029 }
19030
19031 if (insn->imm == BPF_FUNC_get_route_realm)
19032 prog->dst_needed = 1;
19033 if (insn->imm == BPF_FUNC_get_prandom_u32)
19034 bpf_user_rnd_init_once();
19035 if (insn->imm == BPF_FUNC_override_return)
19036 prog->kprobe_override = 1;
19037 if (insn->imm == BPF_FUNC_tail_call) {
19038 /* If we tail call into other programs, we
19039 * cannot make any assumptions since they can
19040 * be replaced dynamically during runtime in
19041 * the program array.
19042 */
19043 prog->cb_access = 1;
19044 if (!allow_tail_call_in_subprogs(env))
19045 prog->aux->stack_depth = MAX_BPF_STACK;
19046 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19047
19048 /* mark bpf_tail_call as different opcode to avoid
19049 * conditional branch in the interpreter for every normal
19050 * call and to prevent accidental JITing by JIT compiler
19051 * that doesn't support bpf_tail_call yet
19052 */
19053 insn->imm = 0;
19054 insn->code = BPF_JMP | BPF_TAIL_CALL;
19055
19056 aux = &env->insn_aux_data[i + delta];
19057 if (env->bpf_capable && !prog->blinding_requested &&
19058 prog->jit_requested &&
19059 !bpf_map_key_poisoned(aux) &&
19060 !bpf_map_ptr_poisoned(aux) &&
19061 !bpf_map_ptr_unpriv(aux)) {
19062 struct bpf_jit_poke_descriptor desc = {
19063 .reason = BPF_POKE_REASON_TAIL_CALL,
19064 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19065 .tail_call.key = bpf_map_key_immediate(aux),
19066 .insn_idx = i + delta,
19067 };
19068
19069 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19070 if (ret < 0) {
19071 verbose(env, "adding tail call poke descriptor failed\n");
19072 return ret;
19073 }
19074
19075 insn->imm = ret + 1;
19076 continue;
19077 }
19078
19079 if (!bpf_map_ptr_unpriv(aux))
19080 continue;
19081
19082 /* instead of changing every JIT dealing with tail_call
19083 * emit two extra insns:
19084 * if (index >= max_entries) goto out;
19085 * index &= array->index_mask;
19086 * to avoid out-of-bounds cpu speculation
19087 */
19088 if (bpf_map_ptr_poisoned(aux)) {
19089 verbose(env, "tail_call abusing map_ptr\n");
19090 return -EINVAL;
19091 }
19092
19093 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19094 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19095 map_ptr->max_entries, 2);
19096 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19097 container_of(map_ptr,
19098 struct bpf_array,
19099 map)->index_mask);
19100 insn_buf[2] = *insn;
19101 cnt = 3;
19102 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19103 if (!new_prog)
19104 return -ENOMEM;
19105
19106 delta += cnt - 1;
19107 env->prog = prog = new_prog;
19108 insn = new_prog->insnsi + i + delta;
19109 continue;
19110 }
19111
19112 if (insn->imm == BPF_FUNC_timer_set_callback) {
19113 /* The verifier will process callback_fn as many times as necessary
19114 * with different maps and the register states prepared by
19115 * set_timer_callback_state will be accurate.
19116 *
19117 * The following use case is valid:
19118 * map1 is shared by prog1, prog2, prog3.
19119 * prog1 calls bpf_timer_init for some map1 elements
19120 * prog2 calls bpf_timer_set_callback for some map1 elements.
19121 * Those that were not bpf_timer_init-ed will return -EINVAL.
19122 * prog3 calls bpf_timer_start for some map1 elements.
19123 * Those that were not both bpf_timer_init-ed and
19124 * bpf_timer_set_callback-ed will return -EINVAL.
19125 */
19126 struct bpf_insn ld_addrs[2] = {
19127 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19128 };
19129
19130 insn_buf[0] = ld_addrs[0];
19131 insn_buf[1] = ld_addrs[1];
19132 insn_buf[2] = *insn;
19133 cnt = 3;
19134
19135 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19136 if (!new_prog)
19137 return -ENOMEM;
19138
19139 delta += cnt - 1;
19140 env->prog = prog = new_prog;
19141 insn = new_prog->insnsi + i + delta;
19142 goto patch_call_imm;
19143 }
19144
19145 if (is_storage_get_function(insn->imm)) {
19146 if (!env->prog->aux->sleepable ||
19147 env->insn_aux_data[i + delta].storage_get_func_atomic)
19148 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19149 else
19150 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19151 insn_buf[1] = *insn;
19152 cnt = 2;
19153
19154 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19155 if (!new_prog)
19156 return -ENOMEM;
19157
19158 delta += cnt - 1;
19159 env->prog = prog = new_prog;
19160 insn = new_prog->insnsi + i + delta;
19161 goto patch_call_imm;
19162 }
19163
19164 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19165 * and other inlining handlers are currently limited to 64 bit
19166 * only.
19167 */
19168 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19169 (insn->imm == BPF_FUNC_map_lookup_elem ||
19170 insn->imm == BPF_FUNC_map_update_elem ||
19171 insn->imm == BPF_FUNC_map_delete_elem ||
19172 insn->imm == BPF_FUNC_map_push_elem ||
19173 insn->imm == BPF_FUNC_map_pop_elem ||
19174 insn->imm == BPF_FUNC_map_peek_elem ||
19175 insn->imm == BPF_FUNC_redirect_map ||
19176 insn->imm == BPF_FUNC_for_each_map_elem ||
19177 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19178 aux = &env->insn_aux_data[i + delta];
19179 if (bpf_map_ptr_poisoned(aux))
19180 goto patch_call_imm;
19181
19182 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19183 ops = map_ptr->ops;
19184 if (insn->imm == BPF_FUNC_map_lookup_elem &&
19185 ops->map_gen_lookup) {
19186 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19187 if (cnt == -EOPNOTSUPP)
19188 goto patch_map_ops_generic;
19189 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19190 verbose(env, "bpf verifier is misconfigured\n");
19191 return -EINVAL;
19192 }
19193
19194 new_prog = bpf_patch_insn_data(env, i + delta,
19195 insn_buf, cnt);
19196 if (!new_prog)
19197 return -ENOMEM;
19198
19199 delta += cnt - 1;
19200 env->prog = prog = new_prog;
19201 insn = new_prog->insnsi + i + delta;
19202 continue;
19203 }
19204
19205 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19206 (void *(*)(struct bpf_map *map, void *key))NULL));
19207 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19208 (long (*)(struct bpf_map *map, void *key))NULL));
19209 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19210 (long (*)(struct bpf_map *map, void *key, void *value,
19211 u64 flags))NULL));
19212 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19213 (long (*)(struct bpf_map *map, void *value,
19214 u64 flags))NULL));
19215 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19216 (long (*)(struct bpf_map *map, void *value))NULL));
19217 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19218 (long (*)(struct bpf_map *map, void *value))NULL));
19219 BUILD_BUG_ON(!__same_type(ops->map_redirect,
19220 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19221 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19222 (long (*)(struct bpf_map *map,
19223 bpf_callback_t callback_fn,
19224 void *callback_ctx,
19225 u64 flags))NULL));
19226 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19227 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19228
19229 patch_map_ops_generic:
19230 switch (insn->imm) {
19231 case BPF_FUNC_map_lookup_elem:
19232 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19233 continue;
19234 case BPF_FUNC_map_update_elem:
19235 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19236 continue;
19237 case BPF_FUNC_map_delete_elem:
19238 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19239 continue;
19240 case BPF_FUNC_map_push_elem:
19241 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19242 continue;
19243 case BPF_FUNC_map_pop_elem:
19244 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19245 continue;
19246 case BPF_FUNC_map_peek_elem:
19247 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19248 continue;
19249 case BPF_FUNC_redirect_map:
19250 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19251 continue;
19252 case BPF_FUNC_for_each_map_elem:
19253 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19254 continue;
19255 case BPF_FUNC_map_lookup_percpu_elem:
19256 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19257 continue;
19258 }
19259
19260 goto patch_call_imm;
19261 }
19262
19263 /* Implement bpf_jiffies64 inline. */
19264 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19265 insn->imm == BPF_FUNC_jiffies64) {
19266 struct bpf_insn ld_jiffies_addr[2] = {
19267 BPF_LD_IMM64(BPF_REG_0,
19268 (unsigned long)&jiffies),
19269 };
19270
19271 insn_buf[0] = ld_jiffies_addr[0];
19272 insn_buf[1] = ld_jiffies_addr[1];
19273 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19274 BPF_REG_0, 0);
19275 cnt = 3;
19276
19277 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19278 cnt);
19279 if (!new_prog)
19280 return -ENOMEM;
19281
19282 delta += cnt - 1;
19283 env->prog = prog = new_prog;
19284 insn = new_prog->insnsi + i + delta;
19285 continue;
19286 }
19287
19288 /* Implement bpf_get_func_arg inline. */
19289 if (prog_type == BPF_PROG_TYPE_TRACING &&
19290 insn->imm == BPF_FUNC_get_func_arg) {
19291 /* Load nr_args from ctx - 8 */
19292 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19293 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19294 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19295 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19296 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19297 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19298 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19299 insn_buf[7] = BPF_JMP_A(1);
19300 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19301 cnt = 9;
19302
19303 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19304 if (!new_prog)
19305 return -ENOMEM;
19306
19307 delta += cnt - 1;
19308 env->prog = prog = new_prog;
19309 insn = new_prog->insnsi + i + delta;
19310 continue;
19311 }
19312
19313 /* Implement bpf_get_func_ret inline. */
19314 if (prog_type == BPF_PROG_TYPE_TRACING &&
19315 insn->imm == BPF_FUNC_get_func_ret) {
19316 if (eatype == BPF_TRACE_FEXIT ||
19317 eatype == BPF_MODIFY_RETURN) {
19318 /* Load nr_args from ctx - 8 */
19319 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19320 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19321 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19322 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19323 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19324 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19325 cnt = 6;
19326 } else {
19327 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19328 cnt = 1;
19329 }
19330
19331 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19332 if (!new_prog)
19333 return -ENOMEM;
19334
19335 delta += cnt - 1;
19336 env->prog = prog = new_prog;
19337 insn = new_prog->insnsi + i + delta;
19338 continue;
19339 }
19340
19341 /* Implement get_func_arg_cnt inline. */
19342 if (prog_type == BPF_PROG_TYPE_TRACING &&
19343 insn->imm == BPF_FUNC_get_func_arg_cnt) {
19344 /* Load nr_args from ctx - 8 */
19345 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19346
19347 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19348 if (!new_prog)
19349 return -ENOMEM;
19350
19351 env->prog = prog = new_prog;
19352 insn = new_prog->insnsi + i + delta;
19353 continue;
19354 }
19355
19356 /* Implement bpf_get_func_ip inline. */
19357 if (prog_type == BPF_PROG_TYPE_TRACING &&
19358 insn->imm == BPF_FUNC_get_func_ip) {
19359 /* Load IP address from ctx - 16 */
19360 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19361
19362 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19363 if (!new_prog)
19364 return -ENOMEM;
19365
19366 env->prog = prog = new_prog;
19367 insn = new_prog->insnsi + i + delta;
19368 continue;
19369 }
19370
19371 patch_call_imm:
19372 fn = env->ops->get_func_proto(insn->imm, env->prog);
19373 /* all functions that have prototype and verifier allowed
19374 * programs to call them, must be real in-kernel functions
19375 */
19376 if (!fn->func) {
19377 verbose(env,
19378 "kernel subsystem misconfigured func %s#%d\n",
19379 func_id_name(insn->imm), insn->imm);
19380 return -EFAULT;
19381 }
19382 insn->imm = fn->func - __bpf_call_base;
19383 }
19384
19385 /* Since poke tab is now finalized, publish aux to tracker. */
19386 for (i = 0; i < prog->aux->size_poke_tab; i++) {
19387 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19388 if (!map_ptr->ops->map_poke_track ||
19389 !map_ptr->ops->map_poke_untrack ||
19390 !map_ptr->ops->map_poke_run) {
19391 verbose(env, "bpf verifier is misconfigured\n");
19392 return -EINVAL;
19393 }
19394
19395 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19396 if (ret < 0) {
19397 verbose(env, "tracking tail call prog failed\n");
19398 return ret;
19399 }
19400 }
19401
19402 sort_kfunc_descs_by_imm_off(env->prog);
19403
19404 return 0;
19405 }
19406
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)19407 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19408 int position,
19409 s32 stack_base,
19410 u32 callback_subprogno,
19411 u32 *cnt)
19412 {
19413 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19414 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19415 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19416 int reg_loop_max = BPF_REG_6;
19417 int reg_loop_cnt = BPF_REG_7;
19418 int reg_loop_ctx = BPF_REG_8;
19419
19420 struct bpf_prog *new_prog;
19421 u32 callback_start;
19422 u32 call_insn_offset;
19423 s32 callback_offset;
19424
19425 /* This represents an inlined version of bpf_iter.c:bpf_loop,
19426 * be careful to modify this code in sync.
19427 */
19428 struct bpf_insn insn_buf[] = {
19429 /* Return error and jump to the end of the patch if
19430 * expected number of iterations is too big.
19431 */
19432 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19433 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19434 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19435 /* spill R6, R7, R8 to use these as loop vars */
19436 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19437 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19438 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19439 /* initialize loop vars */
19440 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19441 BPF_MOV32_IMM(reg_loop_cnt, 0),
19442 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19443 /* loop header,
19444 * if reg_loop_cnt >= reg_loop_max skip the loop body
19445 */
19446 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19447 /* callback call,
19448 * correct callback offset would be set after patching
19449 */
19450 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19451 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19452 BPF_CALL_REL(0),
19453 /* increment loop counter */
19454 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19455 /* jump to loop header if callback returned 0 */
19456 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19457 /* return value of bpf_loop,
19458 * set R0 to the number of iterations
19459 */
19460 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19461 /* restore original values of R6, R7, R8 */
19462 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19463 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19464 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19465 };
19466
19467 *cnt = ARRAY_SIZE(insn_buf);
19468 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19469 if (!new_prog)
19470 return new_prog;
19471
19472 /* callback start is known only after patching */
19473 callback_start = env->subprog_info[callback_subprogno].start;
19474 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19475 call_insn_offset = position + 12;
19476 callback_offset = callback_start - call_insn_offset - 1;
19477 new_prog->insnsi[call_insn_offset].imm = callback_offset;
19478
19479 return new_prog;
19480 }
19481
is_bpf_loop_call(struct bpf_insn * insn)19482 static bool is_bpf_loop_call(struct bpf_insn *insn)
19483 {
19484 return insn->code == (BPF_JMP | BPF_CALL) &&
19485 insn->src_reg == 0 &&
19486 insn->imm == BPF_FUNC_loop;
19487 }
19488
19489 /* For all sub-programs in the program (including main) check
19490 * insn_aux_data to see if there are bpf_loop calls that require
19491 * inlining. If such calls are found the calls are replaced with a
19492 * sequence of instructions produced by `inline_bpf_loop` function and
19493 * subprog stack_depth is increased by the size of 3 registers.
19494 * This stack space is used to spill values of the R6, R7, R8. These
19495 * registers are used to store the loop bound, counter and context
19496 * variables.
19497 */
optimize_bpf_loop(struct bpf_verifier_env * env)19498 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19499 {
19500 struct bpf_subprog_info *subprogs = env->subprog_info;
19501 int i, cur_subprog = 0, cnt, delta = 0;
19502 struct bpf_insn *insn = env->prog->insnsi;
19503 int insn_cnt = env->prog->len;
19504 u16 stack_depth = subprogs[cur_subprog].stack_depth;
19505 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19506 u16 stack_depth_extra = 0;
19507
19508 for (i = 0; i < insn_cnt; i++, insn++) {
19509 struct bpf_loop_inline_state *inline_state =
19510 &env->insn_aux_data[i + delta].loop_inline_state;
19511
19512 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19513 struct bpf_prog *new_prog;
19514
19515 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19516 new_prog = inline_bpf_loop(env,
19517 i + delta,
19518 -(stack_depth + stack_depth_extra),
19519 inline_state->callback_subprogno,
19520 &cnt);
19521 if (!new_prog)
19522 return -ENOMEM;
19523
19524 delta += cnt - 1;
19525 env->prog = new_prog;
19526 insn = new_prog->insnsi + i + delta;
19527 }
19528
19529 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19530 subprogs[cur_subprog].stack_depth += stack_depth_extra;
19531 cur_subprog++;
19532 stack_depth = subprogs[cur_subprog].stack_depth;
19533 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19534 stack_depth_extra = 0;
19535 }
19536 }
19537
19538 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19539
19540 return 0;
19541 }
19542
free_states(struct bpf_verifier_env * env)19543 static void free_states(struct bpf_verifier_env *env)
19544 {
19545 struct bpf_verifier_state_list *sl, *sln;
19546 int i;
19547
19548 sl = env->free_list;
19549 while (sl) {
19550 sln = sl->next;
19551 free_verifier_state(&sl->state, false);
19552 kfree(sl);
19553 sl = sln;
19554 }
19555 env->free_list = NULL;
19556
19557 if (!env->explored_states)
19558 return;
19559
19560 for (i = 0; i < state_htab_size(env); i++) {
19561 sl = env->explored_states[i];
19562
19563 while (sl) {
19564 sln = sl->next;
19565 free_verifier_state(&sl->state, false);
19566 kfree(sl);
19567 sl = sln;
19568 }
19569 env->explored_states[i] = NULL;
19570 }
19571 }
19572
do_check_common(struct bpf_verifier_env * env,int subprog)19573 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19574 {
19575 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19576 struct bpf_verifier_state *state;
19577 struct bpf_reg_state *regs;
19578 int ret, i;
19579
19580 env->prev_linfo = NULL;
19581 env->pass_cnt++;
19582
19583 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19584 if (!state)
19585 return -ENOMEM;
19586 state->curframe = 0;
19587 state->speculative = false;
19588 state->branches = 1;
19589 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19590 if (!state->frame[0]) {
19591 kfree(state);
19592 return -ENOMEM;
19593 }
19594 env->cur_state = state;
19595 init_func_state(env, state->frame[0],
19596 BPF_MAIN_FUNC /* callsite */,
19597 0 /* frameno */,
19598 subprog);
19599 state->first_insn_idx = env->subprog_info[subprog].start;
19600 state->last_insn_idx = -1;
19601
19602 regs = state->frame[state->curframe]->regs;
19603 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19604 ret = btf_prepare_func_args(env, subprog, regs);
19605 if (ret)
19606 goto out;
19607 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19608 if (regs[i].type == PTR_TO_CTX)
19609 mark_reg_known_zero(env, regs, i);
19610 else if (regs[i].type == SCALAR_VALUE)
19611 mark_reg_unknown(env, regs, i);
19612 else if (base_type(regs[i].type) == PTR_TO_MEM) {
19613 const u32 mem_size = regs[i].mem_size;
19614
19615 mark_reg_known_zero(env, regs, i);
19616 regs[i].mem_size = mem_size;
19617 regs[i].id = ++env->id_gen;
19618 }
19619 }
19620 } else {
19621 /* 1st arg to a function */
19622 regs[BPF_REG_1].type = PTR_TO_CTX;
19623 mark_reg_known_zero(env, regs, BPF_REG_1);
19624 ret = btf_check_subprog_arg_match(env, subprog, regs);
19625 if (ret == -EFAULT)
19626 /* unlikely verifier bug. abort.
19627 * ret == 0 and ret < 0 are sadly acceptable for
19628 * main() function due to backward compatibility.
19629 * Like socket filter program may be written as:
19630 * int bpf_prog(struct pt_regs *ctx)
19631 * and never dereference that ctx in the program.
19632 * 'struct pt_regs' is a type mismatch for socket
19633 * filter that should be using 'struct __sk_buff'.
19634 */
19635 goto out;
19636 }
19637
19638 ret = do_check(env);
19639 out:
19640 /* check for NULL is necessary, since cur_state can be freed inside
19641 * do_check() under memory pressure.
19642 */
19643 if (env->cur_state) {
19644 free_verifier_state(env->cur_state, true);
19645 env->cur_state = NULL;
19646 }
19647 while (!pop_stack(env, NULL, NULL, false));
19648 if (!ret && pop_log)
19649 bpf_vlog_reset(&env->log, 0);
19650 free_states(env);
19651 return ret;
19652 }
19653
19654 /* Verify all global functions in a BPF program one by one based on their BTF.
19655 * All global functions must pass verification. Otherwise the whole program is rejected.
19656 * Consider:
19657 * int bar(int);
19658 * int foo(int f)
19659 * {
19660 * return bar(f);
19661 * }
19662 * int bar(int b)
19663 * {
19664 * ...
19665 * }
19666 * foo() will be verified first for R1=any_scalar_value. During verification it
19667 * will be assumed that bar() already verified successfully and call to bar()
19668 * from foo() will be checked for type match only. Later bar() will be verified
19669 * independently to check that it's safe for R1=any_scalar_value.
19670 */
do_check_subprogs(struct bpf_verifier_env * env)19671 static int do_check_subprogs(struct bpf_verifier_env *env)
19672 {
19673 struct bpf_prog_aux *aux = env->prog->aux;
19674 int i, ret;
19675
19676 if (!aux->func_info)
19677 return 0;
19678
19679 for (i = 1; i < env->subprog_cnt; i++) {
19680 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19681 continue;
19682 env->insn_idx = env->subprog_info[i].start;
19683 WARN_ON_ONCE(env->insn_idx == 0);
19684 ret = do_check_common(env, i);
19685 if (ret) {
19686 return ret;
19687 } else if (env->log.level & BPF_LOG_LEVEL) {
19688 verbose(env,
19689 "Func#%d is safe for any args that match its prototype\n",
19690 i);
19691 }
19692 }
19693 return 0;
19694 }
19695
do_check_main(struct bpf_verifier_env * env)19696 static int do_check_main(struct bpf_verifier_env *env)
19697 {
19698 int ret;
19699
19700 env->insn_idx = 0;
19701 ret = do_check_common(env, 0);
19702 if (!ret)
19703 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19704 return ret;
19705 }
19706
19707
print_verification_stats(struct bpf_verifier_env * env)19708 static void print_verification_stats(struct bpf_verifier_env *env)
19709 {
19710 int i;
19711
19712 if (env->log.level & BPF_LOG_STATS) {
19713 verbose(env, "verification time %lld usec\n",
19714 div_u64(env->verification_time, 1000));
19715 verbose(env, "stack depth ");
19716 for (i = 0; i < env->subprog_cnt; i++) {
19717 u32 depth = env->subprog_info[i].stack_depth;
19718
19719 verbose(env, "%d", depth);
19720 if (i + 1 < env->subprog_cnt)
19721 verbose(env, "+");
19722 }
19723 verbose(env, "\n");
19724 }
19725 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19726 "total_states %d peak_states %d mark_read %d\n",
19727 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19728 env->max_states_per_insn, env->total_states,
19729 env->peak_states, env->longest_mark_read_walk);
19730 }
19731
check_struct_ops_btf_id(struct bpf_verifier_env * env)19732 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19733 {
19734 const struct btf_type *t, *func_proto;
19735 const struct bpf_struct_ops *st_ops;
19736 const struct btf_member *member;
19737 struct bpf_prog *prog = env->prog;
19738 u32 btf_id, member_idx;
19739 const char *mname;
19740
19741 if (!prog->gpl_compatible) {
19742 verbose(env, "struct ops programs must have a GPL compatible license\n");
19743 return -EINVAL;
19744 }
19745
19746 btf_id = prog->aux->attach_btf_id;
19747 st_ops = bpf_struct_ops_find(btf_id);
19748 if (!st_ops) {
19749 verbose(env, "attach_btf_id %u is not a supported struct\n",
19750 btf_id);
19751 return -ENOTSUPP;
19752 }
19753
19754 t = st_ops->type;
19755 member_idx = prog->expected_attach_type;
19756 if (member_idx >= btf_type_vlen(t)) {
19757 verbose(env, "attach to invalid member idx %u of struct %s\n",
19758 member_idx, st_ops->name);
19759 return -EINVAL;
19760 }
19761
19762 member = &btf_type_member(t)[member_idx];
19763 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19764 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19765 NULL);
19766 if (!func_proto) {
19767 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19768 mname, member_idx, st_ops->name);
19769 return -EINVAL;
19770 }
19771
19772 if (st_ops->check_member) {
19773 int err = st_ops->check_member(t, member, prog);
19774
19775 if (err) {
19776 verbose(env, "attach to unsupported member %s of struct %s\n",
19777 mname, st_ops->name);
19778 return err;
19779 }
19780 }
19781
19782 prog->aux->attach_func_proto = func_proto;
19783 prog->aux->attach_func_name = mname;
19784 env->ops = st_ops->verifier_ops;
19785
19786 return 0;
19787 }
19788 #define SECURITY_PREFIX "security_"
19789
check_attach_modify_return(unsigned long addr,const char * func_name)19790 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19791 {
19792 if (within_error_injection_list(addr) ||
19793 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19794 return 0;
19795
19796 return -EINVAL;
19797 }
19798
19799 /* list of non-sleepable functions that are otherwise on
19800 * ALLOW_ERROR_INJECTION list
19801 */
19802 BTF_SET_START(btf_non_sleepable_error_inject)
19803 /* Three functions below can be called from sleepable and non-sleepable context.
19804 * Assume non-sleepable from bpf safety point of view.
19805 */
BTF_ID(func,__filemap_add_folio)19806 BTF_ID(func, __filemap_add_folio)
19807 BTF_ID(func, should_fail_alloc_page)
19808 BTF_ID(func, should_failslab)
19809 BTF_SET_END(btf_non_sleepable_error_inject)
19810
19811 static int check_non_sleepable_error_inject(u32 btf_id)
19812 {
19813 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19814 }
19815
bpf_check_attach_target(struct bpf_verifier_log * log,const struct bpf_prog * prog,const struct bpf_prog * tgt_prog,u32 btf_id,struct bpf_attach_target_info * tgt_info)19816 int bpf_check_attach_target(struct bpf_verifier_log *log,
19817 const struct bpf_prog *prog,
19818 const struct bpf_prog *tgt_prog,
19819 u32 btf_id,
19820 struct bpf_attach_target_info *tgt_info)
19821 {
19822 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19823 const char prefix[] = "btf_trace_";
19824 int ret = 0, subprog = -1, i;
19825 const struct btf_type *t;
19826 bool conservative = true;
19827 const char *tname;
19828 struct btf *btf;
19829 long addr = 0;
19830 struct module *mod = NULL;
19831
19832 if (!btf_id) {
19833 bpf_log(log, "Tracing programs must provide btf_id\n");
19834 return -EINVAL;
19835 }
19836 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19837 if (!btf) {
19838 bpf_log(log,
19839 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19840 return -EINVAL;
19841 }
19842 t = btf_type_by_id(btf, btf_id);
19843 if (!t) {
19844 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19845 return -EINVAL;
19846 }
19847 tname = btf_name_by_offset(btf, t->name_off);
19848 if (!tname) {
19849 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19850 return -EINVAL;
19851 }
19852 if (tgt_prog) {
19853 struct bpf_prog_aux *aux = tgt_prog->aux;
19854
19855 if (bpf_prog_is_dev_bound(prog->aux) &&
19856 !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19857 bpf_log(log, "Target program bound device mismatch");
19858 return -EINVAL;
19859 }
19860
19861 for (i = 0; i < aux->func_info_cnt; i++)
19862 if (aux->func_info[i].type_id == btf_id) {
19863 subprog = i;
19864 break;
19865 }
19866 if (subprog == -1) {
19867 bpf_log(log, "Subprog %s doesn't exist\n", tname);
19868 return -EINVAL;
19869 }
19870 conservative = aux->func_info_aux[subprog].unreliable;
19871 if (prog_extension) {
19872 if (conservative) {
19873 bpf_log(log,
19874 "Cannot replace static functions\n");
19875 return -EINVAL;
19876 }
19877 if (!prog->jit_requested) {
19878 bpf_log(log,
19879 "Extension programs should be JITed\n");
19880 return -EINVAL;
19881 }
19882 }
19883 if (!tgt_prog->jited) {
19884 bpf_log(log, "Can attach to only JITed progs\n");
19885 return -EINVAL;
19886 }
19887 if (tgt_prog->type == prog->type) {
19888 /* Cannot fentry/fexit another fentry/fexit program.
19889 * Cannot attach program extension to another extension.
19890 * It's ok to attach fentry/fexit to extension program.
19891 */
19892 bpf_log(log, "Cannot recursively attach\n");
19893 return -EINVAL;
19894 }
19895 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19896 prog_extension &&
19897 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19898 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19899 /* Program extensions can extend all program types
19900 * except fentry/fexit. The reason is the following.
19901 * The fentry/fexit programs are used for performance
19902 * analysis, stats and can be attached to any program
19903 * type except themselves. When extension program is
19904 * replacing XDP function it is necessary to allow
19905 * performance analysis of all functions. Both original
19906 * XDP program and its program extension. Hence
19907 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19908 * allowed. If extending of fentry/fexit was allowed it
19909 * would be possible to create long call chain
19910 * fentry->extension->fentry->extension beyond
19911 * reasonable stack size. Hence extending fentry is not
19912 * allowed.
19913 */
19914 bpf_log(log, "Cannot extend fentry/fexit\n");
19915 return -EINVAL;
19916 }
19917 } else {
19918 if (prog_extension) {
19919 bpf_log(log, "Cannot replace kernel functions\n");
19920 return -EINVAL;
19921 }
19922 }
19923
19924 switch (prog->expected_attach_type) {
19925 case BPF_TRACE_RAW_TP:
19926 if (tgt_prog) {
19927 bpf_log(log,
19928 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19929 return -EINVAL;
19930 }
19931 if (!btf_type_is_typedef(t)) {
19932 bpf_log(log, "attach_btf_id %u is not a typedef\n",
19933 btf_id);
19934 return -EINVAL;
19935 }
19936 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19937 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19938 btf_id, tname);
19939 return -EINVAL;
19940 }
19941 tname += sizeof(prefix) - 1;
19942 t = btf_type_by_id(btf, t->type);
19943 if (!btf_type_is_ptr(t))
19944 /* should never happen in valid vmlinux build */
19945 return -EINVAL;
19946 t = btf_type_by_id(btf, t->type);
19947 if (!btf_type_is_func_proto(t))
19948 /* should never happen in valid vmlinux build */
19949 return -EINVAL;
19950
19951 break;
19952 case BPF_TRACE_ITER:
19953 if (!btf_type_is_func(t)) {
19954 bpf_log(log, "attach_btf_id %u is not a function\n",
19955 btf_id);
19956 return -EINVAL;
19957 }
19958 t = btf_type_by_id(btf, t->type);
19959 if (!btf_type_is_func_proto(t))
19960 return -EINVAL;
19961 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19962 if (ret)
19963 return ret;
19964 break;
19965 default:
19966 if (!prog_extension)
19967 return -EINVAL;
19968 fallthrough;
19969 case BPF_MODIFY_RETURN:
19970 case BPF_LSM_MAC:
19971 case BPF_LSM_CGROUP:
19972 case BPF_TRACE_FENTRY:
19973 case BPF_TRACE_FEXIT:
19974 if (!btf_type_is_func(t)) {
19975 bpf_log(log, "attach_btf_id %u is not a function\n",
19976 btf_id);
19977 return -EINVAL;
19978 }
19979 if (prog_extension &&
19980 btf_check_type_match(log, prog, btf, t))
19981 return -EINVAL;
19982 t = btf_type_by_id(btf, t->type);
19983 if (!btf_type_is_func_proto(t))
19984 return -EINVAL;
19985
19986 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19987 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19988 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19989 return -EINVAL;
19990
19991 if (tgt_prog && conservative)
19992 t = NULL;
19993
19994 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19995 if (ret < 0)
19996 return ret;
19997
19998 if (tgt_prog) {
19999 if (subprog == 0)
20000 addr = (long) tgt_prog->bpf_func;
20001 else
20002 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20003 } else {
20004 if (btf_is_module(btf)) {
20005 mod = btf_try_get_module(btf);
20006 if (mod)
20007 addr = find_kallsyms_symbol_value(mod, tname);
20008 else
20009 addr = 0;
20010 } else {
20011 addr = kallsyms_lookup_name(tname);
20012 }
20013 if (!addr) {
20014 module_put(mod);
20015 bpf_log(log,
20016 "The address of function %s cannot be found\n",
20017 tname);
20018 return -ENOENT;
20019 }
20020 }
20021
20022 if (prog->aux->sleepable) {
20023 ret = -EINVAL;
20024 switch (prog->type) {
20025 case BPF_PROG_TYPE_TRACING:
20026
20027 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20028 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20029 */
20030 if (!check_non_sleepable_error_inject(btf_id) &&
20031 within_error_injection_list(addr))
20032 ret = 0;
20033 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20034 * in the fmodret id set with the KF_SLEEPABLE flag.
20035 */
20036 else {
20037 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20038 prog);
20039
20040 if (flags && (*flags & KF_SLEEPABLE))
20041 ret = 0;
20042 }
20043 break;
20044 case BPF_PROG_TYPE_LSM:
20045 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20046 * Only some of them are sleepable.
20047 */
20048 if (bpf_lsm_is_sleepable_hook(btf_id))
20049 ret = 0;
20050 break;
20051 default:
20052 break;
20053 }
20054 if (ret) {
20055 module_put(mod);
20056 bpf_log(log, "%s is not sleepable\n", tname);
20057 return ret;
20058 }
20059 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20060 if (tgt_prog) {
20061 module_put(mod);
20062 bpf_log(log, "can't modify return codes of BPF programs\n");
20063 return -EINVAL;
20064 }
20065 ret = -EINVAL;
20066 if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20067 !check_attach_modify_return(addr, tname))
20068 ret = 0;
20069 if (ret) {
20070 module_put(mod);
20071 bpf_log(log, "%s() is not modifiable\n", tname);
20072 return ret;
20073 }
20074 }
20075
20076 break;
20077 }
20078 tgt_info->tgt_addr = addr;
20079 tgt_info->tgt_name = tname;
20080 tgt_info->tgt_type = t;
20081 tgt_info->tgt_mod = mod;
20082 return 0;
20083 }
20084
BTF_SET_START(btf_id_deny)20085 BTF_SET_START(btf_id_deny)
20086 BTF_ID_UNUSED
20087 #ifdef CONFIG_SMP
20088 BTF_ID(func, migrate_disable)
20089 BTF_ID(func, migrate_enable)
20090 #endif
20091 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20092 BTF_ID(func, rcu_read_unlock_strict)
20093 #endif
20094 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20095 BTF_ID(func, preempt_count_add)
20096 BTF_ID(func, preempt_count_sub)
20097 #endif
20098 #ifdef CONFIG_PREEMPT_RCU
20099 BTF_ID(func, __rcu_read_lock)
20100 BTF_ID(func, __rcu_read_unlock)
20101 #endif
20102 BTF_SET_END(btf_id_deny)
20103
20104 static bool can_be_sleepable(struct bpf_prog *prog)
20105 {
20106 if (prog->type == BPF_PROG_TYPE_TRACING) {
20107 switch (prog->expected_attach_type) {
20108 case BPF_TRACE_FENTRY:
20109 case BPF_TRACE_FEXIT:
20110 case BPF_MODIFY_RETURN:
20111 case BPF_TRACE_ITER:
20112 return true;
20113 default:
20114 return false;
20115 }
20116 }
20117 return prog->type == BPF_PROG_TYPE_LSM ||
20118 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20119 prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20120 }
20121
check_attach_btf_id(struct bpf_verifier_env * env)20122 static int check_attach_btf_id(struct bpf_verifier_env *env)
20123 {
20124 struct bpf_prog *prog = env->prog;
20125 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20126 struct bpf_attach_target_info tgt_info = {};
20127 u32 btf_id = prog->aux->attach_btf_id;
20128 struct bpf_trampoline *tr;
20129 int ret;
20130 u64 key;
20131
20132 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20133 if (prog->aux->sleepable)
20134 /* attach_btf_id checked to be zero already */
20135 return 0;
20136 verbose(env, "Syscall programs can only be sleepable\n");
20137 return -EINVAL;
20138 }
20139
20140 if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20141 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20142 return -EINVAL;
20143 }
20144
20145 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20146 return check_struct_ops_btf_id(env);
20147
20148 if (prog->type != BPF_PROG_TYPE_TRACING &&
20149 prog->type != BPF_PROG_TYPE_LSM &&
20150 prog->type != BPF_PROG_TYPE_EXT)
20151 return 0;
20152
20153 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20154 if (ret)
20155 return ret;
20156
20157 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20158 /* to make freplace equivalent to their targets, they need to
20159 * inherit env->ops and expected_attach_type for the rest of the
20160 * verification
20161 */
20162 env->ops = bpf_verifier_ops[tgt_prog->type];
20163 prog->expected_attach_type = tgt_prog->expected_attach_type;
20164 }
20165
20166 /* store info about the attachment target that will be used later */
20167 prog->aux->attach_func_proto = tgt_info.tgt_type;
20168 prog->aux->attach_func_name = tgt_info.tgt_name;
20169 prog->aux->mod = tgt_info.tgt_mod;
20170
20171 if (tgt_prog) {
20172 prog->aux->saved_dst_prog_type = tgt_prog->type;
20173 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20174 }
20175
20176 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20177 prog->aux->attach_btf_trace = true;
20178 return 0;
20179 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20180 if (!bpf_iter_prog_supported(prog))
20181 return -EINVAL;
20182 return 0;
20183 }
20184
20185 if (prog->type == BPF_PROG_TYPE_LSM) {
20186 ret = bpf_lsm_verify_prog(&env->log, prog);
20187 if (ret < 0)
20188 return ret;
20189 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20190 btf_id_set_contains(&btf_id_deny, btf_id)) {
20191 return -EINVAL;
20192 }
20193
20194 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20195 tr = bpf_trampoline_get(key, &tgt_info);
20196 if (!tr)
20197 return -ENOMEM;
20198
20199 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20200 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20201
20202 prog->aux->dst_trampoline = tr;
20203 return 0;
20204 }
20205
bpf_get_btf_vmlinux(void)20206 struct btf *bpf_get_btf_vmlinux(void)
20207 {
20208 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20209 mutex_lock(&bpf_verifier_lock);
20210 if (!btf_vmlinux)
20211 btf_vmlinux = btf_parse_vmlinux();
20212 mutex_unlock(&bpf_verifier_lock);
20213 }
20214 return btf_vmlinux;
20215 }
20216
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr,__u32 uattr_size)20217 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20218 {
20219 u64 start_time = ktime_get_ns();
20220 struct bpf_verifier_env *env;
20221 int i, len, ret = -EINVAL, err;
20222 u32 log_true_size;
20223 bool is_priv;
20224
20225 /* no program is valid */
20226 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20227 return -EINVAL;
20228
20229 /* 'struct bpf_verifier_env' can be global, but since it's not small,
20230 * allocate/free it every time bpf_check() is called
20231 */
20232 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20233 if (!env)
20234 return -ENOMEM;
20235
20236 env->bt.env = env;
20237
20238 len = (*prog)->len;
20239 env->insn_aux_data =
20240 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20241 ret = -ENOMEM;
20242 if (!env->insn_aux_data)
20243 goto err_free_env;
20244 for (i = 0; i < len; i++)
20245 env->insn_aux_data[i].orig_idx = i;
20246 env->prog = *prog;
20247 env->ops = bpf_verifier_ops[env->prog->type];
20248 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20249 is_priv = bpf_capable();
20250
20251 bpf_get_btf_vmlinux();
20252
20253 /* grab the mutex to protect few globals used by verifier */
20254 if (!is_priv)
20255 mutex_lock(&bpf_verifier_lock);
20256
20257 /* user could have requested verbose verifier output
20258 * and supplied buffer to store the verification trace
20259 */
20260 ret = bpf_vlog_init(&env->log, attr->log_level,
20261 (char __user *) (unsigned long) attr->log_buf,
20262 attr->log_size);
20263 if (ret)
20264 goto err_unlock;
20265
20266 mark_verifier_state_clean(env);
20267
20268 if (IS_ERR(btf_vmlinux)) {
20269 /* Either gcc or pahole or kernel are broken. */
20270 verbose(env, "in-kernel BTF is malformed\n");
20271 ret = PTR_ERR(btf_vmlinux);
20272 goto skip_full_check;
20273 }
20274
20275 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20276 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20277 env->strict_alignment = true;
20278 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20279 env->strict_alignment = false;
20280
20281 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20282 env->allow_uninit_stack = bpf_allow_uninit_stack();
20283 env->bypass_spec_v1 = bpf_bypass_spec_v1();
20284 env->bypass_spec_v4 = bpf_bypass_spec_v4();
20285 env->bpf_capable = bpf_capable();
20286
20287 if (is_priv)
20288 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20289
20290 env->explored_states = kvcalloc(state_htab_size(env),
20291 sizeof(struct bpf_verifier_state_list *),
20292 GFP_USER);
20293 ret = -ENOMEM;
20294 if (!env->explored_states)
20295 goto skip_full_check;
20296
20297 ret = add_subprog_and_kfunc(env);
20298 if (ret < 0)
20299 goto skip_full_check;
20300
20301 ret = check_subprogs(env);
20302 if (ret < 0)
20303 goto skip_full_check;
20304
20305 ret = check_btf_info(env, attr, uattr);
20306 if (ret < 0)
20307 goto skip_full_check;
20308
20309 ret = check_attach_btf_id(env);
20310 if (ret)
20311 goto skip_full_check;
20312
20313 ret = resolve_pseudo_ldimm64(env);
20314 if (ret < 0)
20315 goto skip_full_check;
20316
20317 if (bpf_prog_is_offloaded(env->prog->aux)) {
20318 ret = bpf_prog_offload_verifier_prep(env->prog);
20319 if (ret)
20320 goto skip_full_check;
20321 }
20322
20323 ret = check_cfg(env);
20324 if (ret < 0)
20325 goto skip_full_check;
20326
20327 ret = do_check_subprogs(env);
20328 ret = ret ?: do_check_main(env);
20329
20330 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20331 ret = bpf_prog_offload_finalize(env);
20332
20333 skip_full_check:
20334 kvfree(env->explored_states);
20335
20336 if (ret == 0)
20337 ret = check_max_stack_depth(env);
20338
20339 /* instruction rewrites happen after this point */
20340 if (ret == 0)
20341 ret = optimize_bpf_loop(env);
20342
20343 if (is_priv) {
20344 if (ret == 0)
20345 opt_hard_wire_dead_code_branches(env);
20346 if (ret == 0)
20347 ret = opt_remove_dead_code(env);
20348 if (ret == 0)
20349 ret = opt_remove_nops(env);
20350 } else {
20351 if (ret == 0)
20352 sanitize_dead_code(env);
20353 }
20354
20355 if (ret == 0)
20356 /* program is valid, convert *(u32*)(ctx + off) accesses */
20357 ret = convert_ctx_accesses(env);
20358
20359 if (ret == 0)
20360 ret = do_misc_fixups(env);
20361
20362 /* do 32-bit optimization after insn patching has done so those patched
20363 * insns could be handled correctly.
20364 */
20365 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20366 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20367 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20368 : false;
20369 }
20370
20371 if (ret == 0)
20372 ret = fixup_call_args(env);
20373
20374 env->verification_time = ktime_get_ns() - start_time;
20375 print_verification_stats(env);
20376 env->prog->aux->verified_insns = env->insn_processed;
20377
20378 /* preserve original error even if log finalization is successful */
20379 err = bpf_vlog_finalize(&env->log, &log_true_size);
20380 if (err)
20381 ret = err;
20382
20383 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20384 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20385 &log_true_size, sizeof(log_true_size))) {
20386 ret = -EFAULT;
20387 goto err_release_maps;
20388 }
20389
20390 if (ret)
20391 goto err_release_maps;
20392
20393 if (env->used_map_cnt) {
20394 /* if program passed verifier, update used_maps in bpf_prog_info */
20395 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20396 sizeof(env->used_maps[0]),
20397 GFP_KERNEL);
20398
20399 if (!env->prog->aux->used_maps) {
20400 ret = -ENOMEM;
20401 goto err_release_maps;
20402 }
20403
20404 memcpy(env->prog->aux->used_maps, env->used_maps,
20405 sizeof(env->used_maps[0]) * env->used_map_cnt);
20406 env->prog->aux->used_map_cnt = env->used_map_cnt;
20407 }
20408 if (env->used_btf_cnt) {
20409 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20410 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20411 sizeof(env->used_btfs[0]),
20412 GFP_KERNEL);
20413 if (!env->prog->aux->used_btfs) {
20414 ret = -ENOMEM;
20415 goto err_release_maps;
20416 }
20417
20418 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20419 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20420 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20421 }
20422 if (env->used_map_cnt || env->used_btf_cnt) {
20423 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20424 * bpf_ld_imm64 instructions
20425 */
20426 convert_pseudo_ld_imm64(env);
20427 }
20428
20429 adjust_btf_func(env);
20430
20431 err_release_maps:
20432 if (!env->prog->aux->used_maps)
20433 /* if we didn't copy map pointers into bpf_prog_info, release
20434 * them now. Otherwise free_used_maps() will release them.
20435 */
20436 release_maps(env);
20437 if (!env->prog->aux->used_btfs)
20438 release_btfs(env);
20439
20440 /* extension progs temporarily inherit the attach_type of their targets
20441 for verification purposes, so set it back to zero before returning
20442 */
20443 if (env->prog->type == BPF_PROG_TYPE_EXT)
20444 env->prog->expected_attach_type = 0;
20445
20446 *prog = env->prog;
20447 err_unlock:
20448 if (!is_priv)
20449 mutex_unlock(&bpf_verifier_lock);
20450 vfree(env->insn_aux_data);
20451 err_free_env:
20452 kfree(env);
20453 return ret;
20454 }
20455