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
28 #include "disasm.h"
29
30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
32 [_id] = & _name ## _verifier_ops,
33 #define BPF_MAP_TYPE(_id, _ops)
34 #define BPF_LINK_TYPE(_id, _name)
35 #include <linux/bpf_types.h>
36 #undef BPF_PROG_TYPE
37 #undef BPF_MAP_TYPE
38 #undef BPF_LINK_TYPE
39 };
40
41 /* bpf_check() is a static code analyzer that walks eBPF program
42 * instruction by instruction and updates register/stack state.
43 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
44 *
45 * The first pass is depth-first-search to check that the program is a DAG.
46 * It rejects the following programs:
47 * - larger than BPF_MAXINSNS insns
48 * - if loop is present (detected via back-edge)
49 * - unreachable insns exist (shouldn't be a forest. program = one function)
50 * - out of bounds or malformed jumps
51 * The second pass is all possible path descent from the 1st insn.
52 * Since it's analyzing all paths through the program, the length of the
53 * analysis is limited to 64k insn, which may be hit even if total number of
54 * insn is less then 4K, but there are too many branches that change stack/regs.
55 * Number of 'branches to be analyzed' is limited to 1k
56 *
57 * On entry to each instruction, each register has a type, and the instruction
58 * changes the types of the registers depending on instruction semantics.
59 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
60 * copied to R1.
61 *
62 * All registers are 64-bit.
63 * R0 - return register
64 * R1-R5 argument passing registers
65 * R6-R9 callee saved registers
66 * R10 - frame pointer read-only
67 *
68 * At the start of BPF program the register R1 contains a pointer to bpf_context
69 * and has type PTR_TO_CTX.
70 *
71 * Verifier tracks arithmetic operations on pointers in case:
72 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
73 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
74 * 1st insn copies R10 (which has FRAME_PTR) type into R1
75 * and 2nd arithmetic instruction is pattern matched to recognize
76 * that it wants to construct a pointer to some element within stack.
77 * So after 2nd insn, the register R1 has type PTR_TO_STACK
78 * (and -20 constant is saved for further stack bounds checking).
79 * Meaning that this reg is a pointer to stack plus known immediate constant.
80 *
81 * Most of the time the registers have SCALAR_VALUE type, which
82 * means the register has some value, but it's not a valid pointer.
83 * (like pointer plus pointer becomes SCALAR_VALUE type)
84 *
85 * When verifier sees load or store instructions the type of base register
86 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
87 * four pointer types recognized by check_mem_access() function.
88 *
89 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
90 * and the range of [ptr, ptr + map's value_size) is accessible.
91 *
92 * registers used to pass values to function calls are checked against
93 * function argument constraints.
94 *
95 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
96 * It means that the register type passed to this function must be
97 * PTR_TO_STACK and it will be used inside the function as
98 * 'pointer to map element key'
99 *
100 * For example the argument constraints for bpf_map_lookup_elem():
101 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
102 * .arg1_type = ARG_CONST_MAP_PTR,
103 * .arg2_type = ARG_PTR_TO_MAP_KEY,
104 *
105 * ret_type says that this function returns 'pointer to map elem value or null'
106 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
107 * 2nd argument should be a pointer to stack, which will be used inside
108 * the helper function as a pointer to map element key.
109 *
110 * On the kernel side the helper function looks like:
111 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
112 * {
113 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
114 * void *key = (void *) (unsigned long) r2;
115 * void *value;
116 *
117 * here kernel can access 'key' and 'map' pointers safely, knowing that
118 * [key, key + map->key_size) bytes are valid and were initialized on
119 * the stack of eBPF program.
120 * }
121 *
122 * Corresponding eBPF program may look like:
123 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
124 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
125 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
126 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
127 * here verifier looks at prototype of map_lookup_elem() and sees:
128 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
129 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
130 *
131 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
132 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
133 * and were initialized prior to this call.
134 * If it's ok, then verifier allows this BPF_CALL insn and looks at
135 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
136 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
137 * returns either pointer to map value or NULL.
138 *
139 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
140 * insn, the register holding that pointer in the true branch changes state to
141 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
142 * branch. See check_cond_jmp_op().
143 *
144 * After the call R0 is set to return type of the function and registers R1-R5
145 * are set to NOT_INIT to indicate that they are no longer readable.
146 *
147 * The following reference types represent a potential reference to a kernel
148 * resource which, after first being allocated, must be checked and freed by
149 * the BPF program:
150 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
151 *
152 * When the verifier sees a helper call return a reference type, it allocates a
153 * pointer id for the reference and stores it in the current function state.
154 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
155 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
156 * passes through a NULL-check conditional. For the branch wherein the state is
157 * changed to CONST_IMM, the verifier releases the reference.
158 *
159 * For each helper function that allocates a reference, such as
160 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
161 * bpf_sk_release(). When a reference type passes into the release function,
162 * the verifier also releases the reference. If any unchecked or unreleased
163 * reference remains at the end of the program, the verifier rejects it.
164 */
165
166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
167 struct bpf_verifier_stack_elem {
168 /* verifer state is 'st'
169 * before processing instruction 'insn_idx'
170 * and after processing instruction 'prev_insn_idx'
171 */
172 struct bpf_verifier_state st;
173 int insn_idx;
174 int prev_insn_idx;
175 struct bpf_verifier_stack_elem *next;
176 /* length of verifier log at the time this state was pushed on stack */
177 u32 log_pos;
178 };
179
180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
181 #define BPF_COMPLEXITY_LIMIT_STATES 64
182
183 #define BPF_MAP_KEY_POISON (1ULL << 63)
184 #define BPF_MAP_KEY_SEEN (1ULL << 62)
185
186 #define BPF_MAP_PTR_UNPRIV 1UL
187 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
188 POISON_POINTER_DELTA))
189 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
190
191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
193
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
195 {
196 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
197 }
198
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
200 {
201 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
202 }
203
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
205 const struct bpf_map *map, bool unpriv)
206 {
207 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
208 unpriv |= bpf_map_ptr_unpriv(aux);
209 aux->map_ptr_state = (unsigned long)map |
210 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
211 }
212
bpf_map_key_poisoned(const struct bpf_insn_aux_data * aux)213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
214 {
215 return aux->map_key_state & BPF_MAP_KEY_POISON;
216 }
217
bpf_map_key_unseen(const struct bpf_insn_aux_data * aux)218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
219 {
220 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
221 }
222
bpf_map_key_immediate(const struct bpf_insn_aux_data * aux)223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
224 {
225 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
226 }
227
bpf_map_key_store(struct bpf_insn_aux_data * aux,u64 state)228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
229 {
230 bool poisoned = bpf_map_key_poisoned(aux);
231
232 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
233 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
234 }
235
bpf_pseudo_call(const struct bpf_insn * insn)236 static bool bpf_pseudo_call(const struct bpf_insn *insn)
237 {
238 return insn->code == (BPF_JMP | BPF_CALL) &&
239 insn->src_reg == BPF_PSEUDO_CALL;
240 }
241
bpf_pseudo_kfunc_call(const struct bpf_insn * insn)242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
243 {
244 return insn->code == (BPF_JMP | BPF_CALL) &&
245 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
246 }
247
248 struct bpf_call_arg_meta {
249 struct bpf_map *map_ptr;
250 bool raw_mode;
251 bool pkt_access;
252 u8 release_regno;
253 int regno;
254 int access_size;
255 int mem_size;
256 u64 msize_max_value;
257 int ref_obj_id;
258 int map_uid;
259 int func_id;
260 struct btf *btf;
261 u32 btf_id;
262 struct btf *ret_btf;
263 u32 ret_btf_id;
264 u32 subprogno;
265 struct bpf_map_value_off_desc *kptr_off_desc;
266 u8 uninit_dynptr_regno;
267 };
268
269 struct btf *btf_vmlinux;
270
271 static DEFINE_MUTEX(bpf_verifier_lock);
272
273 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
275 {
276 const struct bpf_line_info *linfo;
277 const struct bpf_prog *prog;
278 u32 i, nr_linfo;
279
280 prog = env->prog;
281 nr_linfo = prog->aux->nr_linfo;
282
283 if (!nr_linfo || insn_off >= prog->len)
284 return NULL;
285
286 linfo = prog->aux->linfo;
287 for (i = 1; i < nr_linfo; i++)
288 if (insn_off < linfo[i].insn_off)
289 break;
290
291 return &linfo[i - 1];
292 }
293
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
295 va_list args)
296 {
297 unsigned int n;
298
299 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
300
301 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
302 "verifier log line truncated - local buffer too short\n");
303
304 if (log->level == BPF_LOG_KERNEL) {
305 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
306
307 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
308 return;
309 }
310
311 n = min(log->len_total - log->len_used - 1, n);
312 log->kbuf[n] = '\0';
313 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
314 log->len_used += n;
315 else
316 log->ubuf = NULL;
317 }
318
bpf_vlog_reset(struct bpf_verifier_log * log,u32 new_pos)319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
320 {
321 char zero = 0;
322
323 if (!bpf_verifier_log_needed(log))
324 return;
325
326 log->len_used = new_pos;
327 if (put_user(zero, log->ubuf + new_pos))
328 log->ubuf = NULL;
329 }
330
331 /* log_level controls verbosity level of eBPF verifier.
332 * bpf_verifier_log_write() is used to dump the verification trace to the log,
333 * so the user can figure out what's wrong with the program
334 */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
336 const char *fmt, ...)
337 {
338 va_list args;
339
340 if (!bpf_verifier_log_needed(&env->log))
341 return;
342
343 va_start(args, fmt);
344 bpf_verifier_vlog(&env->log, fmt, args);
345 va_end(args);
346 }
347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
348
verbose(void * private_data,const char * fmt,...)349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
350 {
351 struct bpf_verifier_env *env = private_data;
352 va_list args;
353
354 if (!bpf_verifier_log_needed(&env->log))
355 return;
356
357 va_start(args, fmt);
358 bpf_verifier_vlog(&env->log, fmt, args);
359 va_end(args);
360 }
361
bpf_log(struct bpf_verifier_log * log,const char * fmt,...)362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
363 const char *fmt, ...)
364 {
365 va_list args;
366
367 if (!bpf_verifier_log_needed(log))
368 return;
369
370 va_start(args, fmt);
371 bpf_verifier_vlog(log, fmt, args);
372 va_end(args);
373 }
374 EXPORT_SYMBOL_GPL(bpf_log);
375
ltrim(const char * s)376 static const char *ltrim(const char *s)
377 {
378 while (isspace(*s))
379 s++;
380
381 return s;
382 }
383
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
385 u32 insn_off,
386 const char *prefix_fmt, ...)
387 {
388 const struct bpf_line_info *linfo;
389
390 if (!bpf_verifier_log_needed(&env->log))
391 return;
392
393 linfo = find_linfo(env, insn_off);
394 if (!linfo || linfo == env->prev_linfo)
395 return;
396
397 if (prefix_fmt) {
398 va_list args;
399
400 va_start(args, prefix_fmt);
401 bpf_verifier_vlog(&env->log, prefix_fmt, args);
402 va_end(args);
403 }
404
405 verbose(env, "%s\n",
406 ltrim(btf_name_by_offset(env->prog->aux->btf,
407 linfo->line_off)));
408
409 env->prev_linfo = linfo;
410 }
411
verbose_invalid_scalar(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct tnum * range,const char * ctx,const char * reg_name)412 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
413 struct bpf_reg_state *reg,
414 struct tnum *range, const char *ctx,
415 const char *reg_name)
416 {
417 char tn_buf[48];
418
419 verbose(env, "At %s the register %s ", ctx, reg_name);
420 if (!tnum_is_unknown(reg->var_off)) {
421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
422 verbose(env, "has value %s", tn_buf);
423 } else {
424 verbose(env, "has unknown scalar value");
425 }
426 tnum_strn(tn_buf, sizeof(tn_buf), *range);
427 verbose(env, " should have been in %s\n", tn_buf);
428 }
429
type_is_pkt_pointer(enum bpf_reg_type type)430 static bool type_is_pkt_pointer(enum bpf_reg_type type)
431 {
432 type = base_type(type);
433 return type == PTR_TO_PACKET ||
434 type == PTR_TO_PACKET_META;
435 }
436
type_is_sk_pointer(enum bpf_reg_type type)437 static bool type_is_sk_pointer(enum bpf_reg_type type)
438 {
439 return type == PTR_TO_SOCKET ||
440 type == PTR_TO_SOCK_COMMON ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_XDP_SOCK;
443 }
444
reg_type_not_null(enum bpf_reg_type type)445 static bool reg_type_not_null(enum bpf_reg_type type)
446 {
447 return type == PTR_TO_SOCKET ||
448 type == PTR_TO_TCP_SOCK ||
449 type == PTR_TO_MAP_VALUE ||
450 type == PTR_TO_MAP_KEY ||
451 type == PTR_TO_SOCK_COMMON;
452 }
453
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)454 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
455 {
456 return reg->type == PTR_TO_MAP_VALUE &&
457 map_value_has_spin_lock(reg->map_ptr);
458 }
459
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)460 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
461 {
462 type = base_type(type);
463 return type == PTR_TO_SOCKET || type == PTR_TO_TCP_SOCK ||
464 type == PTR_TO_MEM || type == PTR_TO_BTF_ID;
465 }
466
type_is_rdonly_mem(u32 type)467 static bool type_is_rdonly_mem(u32 type)
468 {
469 return type & MEM_RDONLY;
470 }
471
type_may_be_null(u32 type)472 static bool type_may_be_null(u32 type)
473 {
474 return type & PTR_MAYBE_NULL;
475 }
476
is_acquire_function(enum bpf_func_id func_id,const struct bpf_map * map)477 static bool is_acquire_function(enum bpf_func_id func_id,
478 const struct bpf_map *map)
479 {
480 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482 if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 func_id == BPF_FUNC_sk_lookup_udp ||
484 func_id == BPF_FUNC_skc_lookup_tcp ||
485 func_id == BPF_FUNC_ringbuf_reserve ||
486 func_id == BPF_FUNC_kptr_xchg)
487 return true;
488
489 if (func_id == BPF_FUNC_map_lookup_elem &&
490 (map_type == BPF_MAP_TYPE_SOCKMAP ||
491 map_type == BPF_MAP_TYPE_SOCKHASH))
492 return true;
493
494 return false;
495 }
496
is_ptr_cast_function(enum bpf_func_id func_id)497 static bool is_ptr_cast_function(enum bpf_func_id func_id)
498 {
499 return func_id == BPF_FUNC_tcp_sock ||
500 func_id == BPF_FUNC_sk_fullsock ||
501 func_id == BPF_FUNC_skc_to_tcp_sock ||
502 func_id == BPF_FUNC_skc_to_tcp6_sock ||
503 func_id == BPF_FUNC_skc_to_udp6_sock ||
504 func_id == BPF_FUNC_skc_to_mptcp_sock ||
505 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
506 func_id == BPF_FUNC_skc_to_tcp_request_sock;
507 }
508
is_dynptr_ref_function(enum bpf_func_id func_id)509 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
510 {
511 return func_id == BPF_FUNC_dynptr_data;
512 }
513
is_callback_calling_function(enum bpf_func_id func_id)514 static bool is_callback_calling_function(enum bpf_func_id func_id)
515 {
516 return func_id == BPF_FUNC_for_each_map_elem ||
517 func_id == BPF_FUNC_timer_set_callback ||
518 func_id == BPF_FUNC_find_vma ||
519 func_id == BPF_FUNC_loop ||
520 func_id == BPF_FUNC_user_ringbuf_drain;
521 }
522
helper_multiple_ref_obj_use(enum bpf_func_id func_id,const struct bpf_map * map)523 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
524 const struct bpf_map *map)
525 {
526 int ref_obj_uses = 0;
527
528 if (is_ptr_cast_function(func_id))
529 ref_obj_uses++;
530 if (is_acquire_function(func_id, map))
531 ref_obj_uses++;
532 if (is_dynptr_ref_function(func_id))
533 ref_obj_uses++;
534
535 return ref_obj_uses > 1;
536 }
537
is_cmpxchg_insn(const struct bpf_insn * insn)538 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
539 {
540 return BPF_CLASS(insn->code) == BPF_STX &&
541 BPF_MODE(insn->code) == BPF_ATOMIC &&
542 insn->imm == BPF_CMPXCHG;
543 }
544
545 /* string representation of 'enum bpf_reg_type'
546 *
547 * Note that reg_type_str() can not appear more than once in a single verbose()
548 * statement.
549 */
reg_type_str(struct bpf_verifier_env * env,enum bpf_reg_type type)550 static const char *reg_type_str(struct bpf_verifier_env *env,
551 enum bpf_reg_type type)
552 {
553 char postfix[16] = {0}, prefix[32] = {0};
554 static const char * const str[] = {
555 [NOT_INIT] = "?",
556 [SCALAR_VALUE] = "scalar",
557 [PTR_TO_CTX] = "ctx",
558 [CONST_PTR_TO_MAP] = "map_ptr",
559 [PTR_TO_MAP_VALUE] = "map_value",
560 [PTR_TO_STACK] = "fp",
561 [PTR_TO_PACKET] = "pkt",
562 [PTR_TO_PACKET_META] = "pkt_meta",
563 [PTR_TO_PACKET_END] = "pkt_end",
564 [PTR_TO_FLOW_KEYS] = "flow_keys",
565 [PTR_TO_SOCKET] = "sock",
566 [PTR_TO_SOCK_COMMON] = "sock_common",
567 [PTR_TO_TCP_SOCK] = "tcp_sock",
568 [PTR_TO_TP_BUFFER] = "tp_buffer",
569 [PTR_TO_XDP_SOCK] = "xdp_sock",
570 [PTR_TO_BTF_ID] = "ptr_",
571 [PTR_TO_MEM] = "mem",
572 [PTR_TO_BUF] = "buf",
573 [PTR_TO_FUNC] = "func",
574 [PTR_TO_MAP_KEY] = "map_key",
575 [PTR_TO_DYNPTR] = "dynptr_ptr",
576 };
577
578 if (type & PTR_MAYBE_NULL) {
579 if (base_type(type) == PTR_TO_BTF_ID)
580 strncpy(postfix, "or_null_", 16);
581 else
582 strncpy(postfix, "_or_null", 16);
583 }
584
585 if (type & MEM_RDONLY)
586 strncpy(prefix, "rdonly_", 32);
587 if (type & MEM_ALLOC)
588 strncpy(prefix, "alloc_", 32);
589 if (type & MEM_USER)
590 strncpy(prefix, "user_", 32);
591 if (type & MEM_PERCPU)
592 strncpy(prefix, "percpu_", 32);
593 if (type & PTR_UNTRUSTED)
594 strncpy(prefix, "untrusted_", 32);
595
596 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s",
597 prefix, str[base_type(type)], postfix);
598 return env->type_str_buf;
599 }
600
601 static char slot_type_char[] = {
602 [STACK_INVALID] = '?',
603 [STACK_SPILL] = 'r',
604 [STACK_MISC] = 'm',
605 [STACK_ZERO] = '0',
606 [STACK_DYNPTR] = 'd',
607 };
608
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)609 static void print_liveness(struct bpf_verifier_env *env,
610 enum bpf_reg_liveness live)
611 {
612 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
613 verbose(env, "_");
614 if (live & REG_LIVE_READ)
615 verbose(env, "r");
616 if (live & REG_LIVE_WRITTEN)
617 verbose(env, "w");
618 if (live & REG_LIVE_DONE)
619 verbose(env, "D");
620 }
621
get_spi(s32 off)622 static int get_spi(s32 off)
623 {
624 return (-off - 1) / BPF_REG_SIZE;
625 }
626
is_spi_bounds_valid(struct bpf_func_state * state,int spi,int nr_slots)627 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
628 {
629 int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
630
631 /* We need to check that slots between [spi - nr_slots + 1, spi] are
632 * within [0, allocated_stack).
633 *
634 * Please note that the spi grows downwards. For example, a dynptr
635 * takes the size of two stack slots; the first slot will be at
636 * spi and the second slot will be at spi - 1.
637 */
638 return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
639 }
640
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)641 static struct bpf_func_state *func(struct bpf_verifier_env *env,
642 const struct bpf_reg_state *reg)
643 {
644 struct bpf_verifier_state *cur = env->cur_state;
645
646 return cur->frame[reg->frameno];
647 }
648
kernel_type_name(const struct btf * btf,u32 id)649 static const char *kernel_type_name(const struct btf* btf, u32 id)
650 {
651 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
652 }
653
mark_reg_scratched(struct bpf_verifier_env * env,u32 regno)654 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
655 {
656 env->scratched_regs |= 1U << regno;
657 }
658
mark_stack_slot_scratched(struct bpf_verifier_env * env,u32 spi)659 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
660 {
661 env->scratched_stack_slots |= 1ULL << spi;
662 }
663
reg_scratched(const struct bpf_verifier_env * env,u32 regno)664 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
665 {
666 return (env->scratched_regs >> regno) & 1;
667 }
668
stack_slot_scratched(const struct bpf_verifier_env * env,u64 regno)669 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
670 {
671 return (env->scratched_stack_slots >> regno) & 1;
672 }
673
verifier_state_scratched(const struct bpf_verifier_env * env)674 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
675 {
676 return env->scratched_regs || env->scratched_stack_slots;
677 }
678
mark_verifier_state_clean(struct bpf_verifier_env * env)679 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
680 {
681 env->scratched_regs = 0U;
682 env->scratched_stack_slots = 0ULL;
683 }
684
685 /* Used for printing the entire verifier state. */
mark_verifier_state_scratched(struct bpf_verifier_env * env)686 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
687 {
688 env->scratched_regs = ~0U;
689 env->scratched_stack_slots = ~0ULL;
690 }
691
arg_to_dynptr_type(enum bpf_arg_type arg_type)692 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
693 {
694 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
695 case DYNPTR_TYPE_LOCAL:
696 return BPF_DYNPTR_TYPE_LOCAL;
697 case DYNPTR_TYPE_RINGBUF:
698 return BPF_DYNPTR_TYPE_RINGBUF;
699 default:
700 return BPF_DYNPTR_TYPE_INVALID;
701 }
702 }
703
dynptr_type_refcounted(enum bpf_dynptr_type type)704 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
705 {
706 return type == BPF_DYNPTR_TYPE_RINGBUF;
707 }
708
mark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type,int insn_idx)709 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
710 enum bpf_arg_type arg_type, int insn_idx)
711 {
712 struct bpf_func_state *state = func(env, reg);
713 enum bpf_dynptr_type type;
714 int spi, i, id;
715
716 spi = get_spi(reg->off);
717
718 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
719 return -EINVAL;
720
721 for (i = 0; i < BPF_REG_SIZE; i++) {
722 state->stack[spi].slot_type[i] = STACK_DYNPTR;
723 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
724 }
725
726 type = arg_to_dynptr_type(arg_type);
727 if (type == BPF_DYNPTR_TYPE_INVALID)
728 return -EINVAL;
729
730 state->stack[spi].spilled_ptr.dynptr.first_slot = true;
731 state->stack[spi].spilled_ptr.dynptr.type = type;
732 state->stack[spi - 1].spilled_ptr.dynptr.type = type;
733
734 if (dynptr_type_refcounted(type)) {
735 /* The id is used to track proper releasing */
736 id = acquire_reference_state(env, insn_idx);
737 if (id < 0)
738 return id;
739
740 state->stack[spi].spilled_ptr.id = id;
741 state->stack[spi - 1].spilled_ptr.id = id;
742 }
743
744 return 0;
745 }
746
unmark_stack_slots_dynptr(struct bpf_verifier_env * env,struct bpf_reg_state * reg)747 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
748 {
749 struct bpf_func_state *state = func(env, reg);
750 int spi, i;
751
752 spi = get_spi(reg->off);
753
754 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
755 return -EINVAL;
756
757 for (i = 0; i < BPF_REG_SIZE; i++) {
758 state->stack[spi].slot_type[i] = STACK_INVALID;
759 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
760 }
761
762 /* Invalidate any slices associated with this dynptr */
763 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
764 release_reference(env, state->stack[spi].spilled_ptr.id);
765 state->stack[spi].spilled_ptr.id = 0;
766 state->stack[spi - 1].spilled_ptr.id = 0;
767 }
768
769 state->stack[spi].spilled_ptr.dynptr.first_slot = false;
770 state->stack[spi].spilled_ptr.dynptr.type = 0;
771 state->stack[spi - 1].spilled_ptr.dynptr.type = 0;
772
773 return 0;
774 }
775
is_dynptr_reg_valid_uninit(struct bpf_verifier_env * env,struct bpf_reg_state * reg)776 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
777 {
778 struct bpf_func_state *state = func(env, reg);
779 int spi = get_spi(reg->off);
780 int i;
781
782 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS))
783 return true;
784
785 for (i = 0; i < BPF_REG_SIZE; i++) {
786 if (state->stack[spi].slot_type[i] == STACK_DYNPTR ||
787 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR)
788 return false;
789 }
790
791 return true;
792 }
793
is_dynptr_reg_valid_init(struct bpf_verifier_env * env,struct bpf_reg_state * reg)794 bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env,
795 struct bpf_reg_state *reg)
796 {
797 struct bpf_func_state *state = func(env, reg);
798 int spi = get_spi(reg->off);
799 int i;
800
801 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
802 !state->stack[spi].spilled_ptr.dynptr.first_slot)
803 return false;
804
805 for (i = 0; i < BPF_REG_SIZE; i++) {
806 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
807 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
808 return false;
809 }
810
811 return true;
812 }
813
is_dynptr_type_expected(struct bpf_verifier_env * env,struct bpf_reg_state * reg,enum bpf_arg_type arg_type)814 bool is_dynptr_type_expected(struct bpf_verifier_env *env,
815 struct bpf_reg_state *reg,
816 enum bpf_arg_type arg_type)
817 {
818 struct bpf_func_state *state = func(env, reg);
819 enum bpf_dynptr_type dynptr_type;
820 int spi = get_spi(reg->off);
821
822 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
823 if (arg_type == ARG_PTR_TO_DYNPTR)
824 return true;
825
826 dynptr_type = arg_to_dynptr_type(arg_type);
827
828 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
829 }
830
831 /* The reg state of a pointer or a bounded scalar was saved when
832 * it was spilled to the stack.
833 */
is_spilled_reg(const struct bpf_stack_state * stack)834 static bool is_spilled_reg(const struct bpf_stack_state *stack)
835 {
836 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
837 }
838
scrub_spilled_slot(u8 * stype)839 static void scrub_spilled_slot(u8 *stype)
840 {
841 if (*stype != STACK_INVALID)
842 *stype = STACK_MISC;
843 }
844
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state,bool print_all)845 static void print_verifier_state(struct bpf_verifier_env *env,
846 const struct bpf_func_state *state,
847 bool print_all)
848 {
849 const struct bpf_reg_state *reg;
850 enum bpf_reg_type t;
851 int i;
852
853 if (state->frameno)
854 verbose(env, " frame%d:", state->frameno);
855 for (i = 0; i < MAX_BPF_REG; i++) {
856 reg = &state->regs[i];
857 t = reg->type;
858 if (t == NOT_INIT)
859 continue;
860 if (!print_all && !reg_scratched(env, i))
861 continue;
862 verbose(env, " R%d", i);
863 print_liveness(env, reg->live);
864 verbose(env, "=");
865 if (t == SCALAR_VALUE && reg->precise)
866 verbose(env, "P");
867 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
868 tnum_is_const(reg->var_off)) {
869 /* reg->off should be 0 for SCALAR_VALUE */
870 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
871 verbose(env, "%lld", reg->var_off.value + reg->off);
872 } else {
873 const char *sep = "";
874
875 verbose(env, "%s", reg_type_str(env, t));
876 if (base_type(t) == PTR_TO_BTF_ID)
877 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
878 verbose(env, "(");
879 /*
880 * _a stands for append, was shortened to avoid multiline statements below.
881 * This macro is used to output a comma separated list of attributes.
882 */
883 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
884
885 if (reg->id)
886 verbose_a("id=%d", reg->id);
887 if (reg_type_may_be_refcounted_or_null(t) && reg->ref_obj_id)
888 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
889 if (t != SCALAR_VALUE)
890 verbose_a("off=%d", reg->off);
891 if (type_is_pkt_pointer(t))
892 verbose_a("r=%d", reg->range);
893 else if (base_type(t) == CONST_PTR_TO_MAP ||
894 base_type(t) == PTR_TO_MAP_KEY ||
895 base_type(t) == PTR_TO_MAP_VALUE)
896 verbose_a("ks=%d,vs=%d",
897 reg->map_ptr->key_size,
898 reg->map_ptr->value_size);
899 if (tnum_is_const(reg->var_off)) {
900 /* Typically an immediate SCALAR_VALUE, but
901 * could be a pointer whose offset is too big
902 * for reg->off
903 */
904 verbose_a("imm=%llx", reg->var_off.value);
905 } else {
906 if (reg->smin_value != reg->umin_value &&
907 reg->smin_value != S64_MIN)
908 verbose_a("smin=%lld", (long long)reg->smin_value);
909 if (reg->smax_value != reg->umax_value &&
910 reg->smax_value != S64_MAX)
911 verbose_a("smax=%lld", (long long)reg->smax_value);
912 if (reg->umin_value != 0)
913 verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
914 if (reg->umax_value != U64_MAX)
915 verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
916 if (!tnum_is_unknown(reg->var_off)) {
917 char tn_buf[48];
918
919 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
920 verbose_a("var_off=%s", tn_buf);
921 }
922 if (reg->s32_min_value != reg->smin_value &&
923 reg->s32_min_value != S32_MIN)
924 verbose_a("s32_min=%d", (int)(reg->s32_min_value));
925 if (reg->s32_max_value != reg->smax_value &&
926 reg->s32_max_value != S32_MAX)
927 verbose_a("s32_max=%d", (int)(reg->s32_max_value));
928 if (reg->u32_min_value != reg->umin_value &&
929 reg->u32_min_value != U32_MIN)
930 verbose_a("u32_min=%d", (int)(reg->u32_min_value));
931 if (reg->u32_max_value != reg->umax_value &&
932 reg->u32_max_value != U32_MAX)
933 verbose_a("u32_max=%d", (int)(reg->u32_max_value));
934 }
935 #undef verbose_a
936
937 verbose(env, ")");
938 }
939 }
940 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
941 char types_buf[BPF_REG_SIZE + 1];
942 bool valid = false;
943 int j;
944
945 for (j = 0; j < BPF_REG_SIZE; j++) {
946 if (state->stack[i].slot_type[j] != STACK_INVALID)
947 valid = true;
948 types_buf[j] = slot_type_char[
949 state->stack[i].slot_type[j]];
950 }
951 types_buf[BPF_REG_SIZE] = 0;
952 if (!valid)
953 continue;
954 if (!print_all && !stack_slot_scratched(env, i))
955 continue;
956 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
957 print_liveness(env, state->stack[i].spilled_ptr.live);
958 if (is_spilled_reg(&state->stack[i])) {
959 reg = &state->stack[i].spilled_ptr;
960 t = reg->type;
961 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
962 if (t == SCALAR_VALUE && reg->precise)
963 verbose(env, "P");
964 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
965 verbose(env, "%lld", reg->var_off.value + reg->off);
966 } else {
967 verbose(env, "=%s", types_buf);
968 }
969 }
970 if (state->acquired_refs && state->refs[0].id) {
971 verbose(env, " refs=%d", state->refs[0].id);
972 for (i = 1; i < state->acquired_refs; i++)
973 if (state->refs[i].id)
974 verbose(env, ",%d", state->refs[i].id);
975 }
976 if (state->in_callback_fn)
977 verbose(env, " cb");
978 if (state->in_async_callback_fn)
979 verbose(env, " async_cb");
980 verbose(env, "\n");
981 if (!print_all)
982 mark_verifier_state_clean(env);
983 }
984
vlog_alignment(u32 pos)985 static inline u32 vlog_alignment(u32 pos)
986 {
987 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
988 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
989 }
990
print_insn_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)991 static void print_insn_state(struct bpf_verifier_env *env,
992 const struct bpf_func_state *state)
993 {
994 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
995 /* remove new line character */
996 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
997 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
998 } else {
999 verbose(env, "%d:", env->insn_idx);
1000 }
1001 print_verifier_state(env, state, false);
1002 }
1003
1004 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1005 * small to hold src. This is different from krealloc since we don't want to preserve
1006 * the contents of dst.
1007 *
1008 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1009 * not be allocated.
1010 */
copy_array(void * dst,const void * src,size_t n,size_t size,gfp_t flags)1011 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1012 {
1013 size_t alloc_bytes;
1014 void *orig = dst;
1015 size_t bytes;
1016
1017 if (ZERO_OR_NULL_PTR(src))
1018 goto out;
1019
1020 if (unlikely(check_mul_overflow(n, size, &bytes)))
1021 return NULL;
1022
1023 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1024 dst = krealloc(orig, alloc_bytes, flags);
1025 if (!dst) {
1026 kfree(orig);
1027 return NULL;
1028 }
1029
1030 memcpy(dst, src, bytes);
1031 out:
1032 return dst ? dst : ZERO_SIZE_PTR;
1033 }
1034
1035 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1036 * small to hold new_n items. new items are zeroed out if the array grows.
1037 *
1038 * Contrary to krealloc_array, does not free arr if new_n is zero.
1039 */
realloc_array(void * arr,size_t old_n,size_t new_n,size_t size)1040 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1041 {
1042 size_t alloc_size;
1043 void *new_arr;
1044
1045 if (!new_n || old_n == new_n)
1046 goto out;
1047
1048 alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1049 new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1050 if (!new_arr) {
1051 kfree(arr);
1052 return NULL;
1053 }
1054 arr = new_arr;
1055
1056 if (new_n > old_n)
1057 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1058
1059 out:
1060 return arr ? arr : ZERO_SIZE_PTR;
1061 }
1062
copy_reference_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1063 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1064 {
1065 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1066 sizeof(struct bpf_reference_state), GFP_KERNEL);
1067 if (!dst->refs)
1068 return -ENOMEM;
1069
1070 dst->acquired_refs = src->acquired_refs;
1071 return 0;
1072 }
1073
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1074 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1075 {
1076 size_t n = src->allocated_stack / BPF_REG_SIZE;
1077
1078 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1079 GFP_KERNEL);
1080 if (!dst->stack)
1081 return -ENOMEM;
1082
1083 dst->allocated_stack = src->allocated_stack;
1084 return 0;
1085 }
1086
resize_reference_state(struct bpf_func_state * state,size_t n)1087 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1088 {
1089 state->refs = realloc_array(state->refs, state->acquired_refs, n,
1090 sizeof(struct bpf_reference_state));
1091 if (!state->refs)
1092 return -ENOMEM;
1093
1094 state->acquired_refs = n;
1095 return 0;
1096 }
1097
grow_stack_state(struct bpf_func_state * state,int size)1098 static int grow_stack_state(struct bpf_func_state *state, int size)
1099 {
1100 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1101
1102 if (old_n >= n)
1103 return 0;
1104
1105 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1106 if (!state->stack)
1107 return -ENOMEM;
1108
1109 state->allocated_stack = size;
1110 return 0;
1111 }
1112
1113 /* Acquire a pointer id from the env and update the state->refs to include
1114 * this new pointer reference.
1115 * On success, returns a valid pointer id to associate with the register
1116 * On failure, returns a negative errno.
1117 */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)1118 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1119 {
1120 struct bpf_func_state *state = cur_func(env);
1121 int new_ofs = state->acquired_refs;
1122 int id, err;
1123
1124 err = resize_reference_state(state, state->acquired_refs + 1);
1125 if (err)
1126 return err;
1127 id = ++env->id_gen;
1128 state->refs[new_ofs].id = id;
1129 state->refs[new_ofs].insn_idx = insn_idx;
1130 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1131
1132 return id;
1133 }
1134
1135 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)1136 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1137 {
1138 int i, last_idx;
1139
1140 last_idx = state->acquired_refs - 1;
1141 for (i = 0; i < state->acquired_refs; i++) {
1142 if (state->refs[i].id == ptr_id) {
1143 /* Cannot release caller references in callbacks */
1144 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1145 return -EINVAL;
1146 if (last_idx && i != last_idx)
1147 memcpy(&state->refs[i], &state->refs[last_idx],
1148 sizeof(*state->refs));
1149 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1150 state->acquired_refs--;
1151 return 0;
1152 }
1153 }
1154 return -EINVAL;
1155 }
1156
free_func_state(struct bpf_func_state * state)1157 static void free_func_state(struct bpf_func_state *state)
1158 {
1159 if (!state)
1160 return;
1161 kfree(state->refs);
1162 kfree(state->stack);
1163 kfree(state);
1164 }
1165
clear_jmp_history(struct bpf_verifier_state * state)1166 static void clear_jmp_history(struct bpf_verifier_state *state)
1167 {
1168 kfree(state->jmp_history);
1169 state->jmp_history = NULL;
1170 state->jmp_history_cnt = 0;
1171 }
1172
free_verifier_state(struct bpf_verifier_state * state,bool free_self)1173 static void free_verifier_state(struct bpf_verifier_state *state,
1174 bool free_self)
1175 {
1176 int i;
1177
1178 for (i = 0; i <= state->curframe; i++) {
1179 free_func_state(state->frame[i]);
1180 state->frame[i] = NULL;
1181 }
1182 clear_jmp_history(state);
1183 if (free_self)
1184 kfree(state);
1185 }
1186
1187 /* copy verifier state from src to dst growing dst stack space
1188 * when necessary to accommodate larger src stack
1189 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)1190 static int copy_func_state(struct bpf_func_state *dst,
1191 const struct bpf_func_state *src)
1192 {
1193 int err;
1194
1195 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1196 err = copy_reference_state(dst, src);
1197 if (err)
1198 return err;
1199 return copy_stack_state(dst, src);
1200 }
1201
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)1202 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1203 const struct bpf_verifier_state *src)
1204 {
1205 struct bpf_func_state *dst;
1206 int i, err;
1207
1208 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1209 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1210 GFP_USER);
1211 if (!dst_state->jmp_history)
1212 return -ENOMEM;
1213 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1214
1215 /* if dst has more stack frames then src frame, free them */
1216 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1217 free_func_state(dst_state->frame[i]);
1218 dst_state->frame[i] = NULL;
1219 }
1220 dst_state->speculative = src->speculative;
1221 dst_state->curframe = src->curframe;
1222 dst_state->active_spin_lock = src->active_spin_lock;
1223 dst_state->branches = src->branches;
1224 dst_state->parent = src->parent;
1225 dst_state->first_insn_idx = src->first_insn_idx;
1226 dst_state->last_insn_idx = src->last_insn_idx;
1227 for (i = 0; i <= src->curframe; i++) {
1228 dst = dst_state->frame[i];
1229 if (!dst) {
1230 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1231 if (!dst)
1232 return -ENOMEM;
1233 dst_state->frame[i] = dst;
1234 }
1235 err = copy_func_state(dst, src->frame[i]);
1236 if (err)
1237 return err;
1238 }
1239 return 0;
1240 }
1241
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1242 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1243 {
1244 while (st) {
1245 u32 br = --st->branches;
1246
1247 /* WARN_ON(br > 1) technically makes sense here,
1248 * but see comment in push_stack(), hence:
1249 */
1250 WARN_ONCE((int)br < 0,
1251 "BUG update_branch_counts:branches_to_explore=%d\n",
1252 br);
1253 if (br)
1254 break;
1255 st = st->parent;
1256 }
1257 }
1258
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)1259 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1260 int *insn_idx, bool pop_log)
1261 {
1262 struct bpf_verifier_state *cur = env->cur_state;
1263 struct bpf_verifier_stack_elem *elem, *head = env->head;
1264 int err;
1265
1266 if (env->head == NULL)
1267 return -ENOENT;
1268
1269 if (cur) {
1270 err = copy_verifier_state(cur, &head->st);
1271 if (err)
1272 return err;
1273 }
1274 if (pop_log)
1275 bpf_vlog_reset(&env->log, head->log_pos);
1276 if (insn_idx)
1277 *insn_idx = head->insn_idx;
1278 if (prev_insn_idx)
1279 *prev_insn_idx = head->prev_insn_idx;
1280 elem = head->next;
1281 free_verifier_state(&head->st, false);
1282 kfree(head);
1283 env->head = elem;
1284 env->stack_size--;
1285 return 0;
1286 }
1287
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)1288 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1289 int insn_idx, int prev_insn_idx,
1290 bool speculative)
1291 {
1292 struct bpf_verifier_state *cur = env->cur_state;
1293 struct bpf_verifier_stack_elem *elem;
1294 int err;
1295
1296 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1297 if (!elem)
1298 goto err;
1299
1300 elem->insn_idx = insn_idx;
1301 elem->prev_insn_idx = prev_insn_idx;
1302 elem->next = env->head;
1303 elem->log_pos = env->log.len_used;
1304 env->head = elem;
1305 env->stack_size++;
1306 err = copy_verifier_state(&elem->st, cur);
1307 if (err)
1308 goto err;
1309 elem->st.speculative |= speculative;
1310 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1311 verbose(env, "The sequence of %d jumps is too complex.\n",
1312 env->stack_size);
1313 goto err;
1314 }
1315 if (elem->st.parent) {
1316 ++elem->st.parent->branches;
1317 /* WARN_ON(branches > 2) technically makes sense here,
1318 * but
1319 * 1. speculative states will bump 'branches' for non-branch
1320 * instructions
1321 * 2. is_state_visited() heuristics may decide not to create
1322 * a new state for a sequence of branches and all such current
1323 * and cloned states will be pointing to a single parent state
1324 * which might have large 'branches' count.
1325 */
1326 }
1327 return &elem->st;
1328 err:
1329 free_verifier_state(env->cur_state, true);
1330 env->cur_state = NULL;
1331 /* pop all elements and return */
1332 while (!pop_stack(env, NULL, NULL, false));
1333 return NULL;
1334 }
1335
1336 #define CALLER_SAVED_REGS 6
1337 static const int caller_saved[CALLER_SAVED_REGS] = {
1338 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1339 };
1340
1341 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1342 struct bpf_reg_state *reg);
1343
1344 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1345 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1346 {
1347 reg->var_off = tnum_const(imm);
1348 reg->smin_value = (s64)imm;
1349 reg->smax_value = (s64)imm;
1350 reg->umin_value = imm;
1351 reg->umax_value = imm;
1352
1353 reg->s32_min_value = (s32)imm;
1354 reg->s32_max_value = (s32)imm;
1355 reg->u32_min_value = (u32)imm;
1356 reg->u32_max_value = (u32)imm;
1357 }
1358
1359 /* Mark the unknown part of a register (variable offset or scalar value) as
1360 * known to have the value @imm.
1361 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1362 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1363 {
1364 /* Clear id, off, and union(map_ptr, range) */
1365 memset(((u8 *)reg) + sizeof(reg->type), 0,
1366 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1367 ___mark_reg_known(reg, imm);
1368 }
1369
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1370 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1371 {
1372 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1373 reg->s32_min_value = (s32)imm;
1374 reg->s32_max_value = (s32)imm;
1375 reg->u32_min_value = (u32)imm;
1376 reg->u32_max_value = (u32)imm;
1377 }
1378
1379 /* Mark the 'variable offset' part of a register as zero. This should be
1380 * used only on registers holding a pointer type.
1381 */
__mark_reg_known_zero(struct bpf_reg_state * reg)1382 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1383 {
1384 __mark_reg_known(reg, 0);
1385 }
1386
__mark_reg_const_zero(struct bpf_reg_state * reg)1387 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1388 {
1389 __mark_reg_known(reg, 0);
1390 reg->type = SCALAR_VALUE;
1391 }
1392
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1393 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1394 struct bpf_reg_state *regs, u32 regno)
1395 {
1396 if (WARN_ON(regno >= MAX_BPF_REG)) {
1397 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1398 /* Something bad happened, let's kill all regs */
1399 for (regno = 0; regno < MAX_BPF_REG; regno++)
1400 __mark_reg_not_init(env, regs + regno);
1401 return;
1402 }
1403 __mark_reg_known_zero(regs + regno);
1404 }
1405
mark_ptr_not_null_reg(struct bpf_reg_state * reg)1406 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1407 {
1408 if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1409 const struct bpf_map *map = reg->map_ptr;
1410
1411 if (map->inner_map_meta) {
1412 reg->type = CONST_PTR_TO_MAP;
1413 reg->map_ptr = map->inner_map_meta;
1414 /* transfer reg's id which is unique for every map_lookup_elem
1415 * as UID of the inner map.
1416 */
1417 if (map_value_has_timer(map->inner_map_meta))
1418 reg->map_uid = reg->id;
1419 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1420 reg->type = PTR_TO_XDP_SOCK;
1421 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1422 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1423 reg->type = PTR_TO_SOCKET;
1424 } else {
1425 reg->type = PTR_TO_MAP_VALUE;
1426 }
1427 return;
1428 }
1429
1430 reg->type &= ~PTR_MAYBE_NULL;
1431 }
1432
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1433 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1434 {
1435 return type_is_pkt_pointer(reg->type);
1436 }
1437
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1438 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1439 {
1440 return reg_is_pkt_pointer(reg) ||
1441 reg->type == PTR_TO_PACKET_END;
1442 }
1443
1444 /* 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)1445 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1446 enum bpf_reg_type which)
1447 {
1448 /* The register can already have a range from prior markings.
1449 * This is fine as long as it hasn't been advanced from its
1450 * origin.
1451 */
1452 return reg->type == which &&
1453 reg->id == 0 &&
1454 reg->off == 0 &&
1455 tnum_equals_const(reg->var_off, 0);
1456 }
1457
1458 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1459 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1460 {
1461 reg->smin_value = S64_MIN;
1462 reg->smax_value = S64_MAX;
1463 reg->umin_value = 0;
1464 reg->umax_value = U64_MAX;
1465
1466 reg->s32_min_value = S32_MIN;
1467 reg->s32_max_value = S32_MAX;
1468 reg->u32_min_value = 0;
1469 reg->u32_max_value = U32_MAX;
1470 }
1471
__mark_reg64_unbounded(struct bpf_reg_state * reg)1472 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1473 {
1474 reg->smin_value = S64_MIN;
1475 reg->smax_value = S64_MAX;
1476 reg->umin_value = 0;
1477 reg->umax_value = U64_MAX;
1478 }
1479
__mark_reg32_unbounded(struct bpf_reg_state * reg)1480 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1481 {
1482 reg->s32_min_value = S32_MIN;
1483 reg->s32_max_value = S32_MAX;
1484 reg->u32_min_value = 0;
1485 reg->u32_max_value = U32_MAX;
1486 }
1487
__update_reg32_bounds(struct bpf_reg_state * reg)1488 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1489 {
1490 struct tnum var32_off = tnum_subreg(reg->var_off);
1491
1492 /* min signed is max(sign bit) | min(other bits) */
1493 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1494 var32_off.value | (var32_off.mask & S32_MIN));
1495 /* max signed is min(sign bit) | max(other bits) */
1496 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1497 var32_off.value | (var32_off.mask & S32_MAX));
1498 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1499 reg->u32_max_value = min(reg->u32_max_value,
1500 (u32)(var32_off.value | var32_off.mask));
1501 }
1502
__update_reg64_bounds(struct bpf_reg_state * reg)1503 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1504 {
1505 /* min signed is max(sign bit) | min(other bits) */
1506 reg->smin_value = max_t(s64, reg->smin_value,
1507 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1508 /* max signed is min(sign bit) | max(other bits) */
1509 reg->smax_value = min_t(s64, reg->smax_value,
1510 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1511 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1512 reg->umax_value = min(reg->umax_value,
1513 reg->var_off.value | reg->var_off.mask);
1514 }
1515
__update_reg_bounds(struct bpf_reg_state * reg)1516 static void __update_reg_bounds(struct bpf_reg_state *reg)
1517 {
1518 __update_reg32_bounds(reg);
1519 __update_reg64_bounds(reg);
1520 }
1521
1522 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1523 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1524 {
1525 /* Learn sign from signed bounds.
1526 * If we cannot cross the sign boundary, then signed and unsigned bounds
1527 * are the same, so combine. This works even in the negative case, e.g.
1528 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1529 */
1530 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1531 reg->s32_min_value = reg->u32_min_value =
1532 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1533 reg->s32_max_value = reg->u32_max_value =
1534 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1535 return;
1536 }
1537 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1538 * boundary, so we must be careful.
1539 */
1540 if ((s32)reg->u32_max_value >= 0) {
1541 /* Positive. We can't learn anything from the smin, but smax
1542 * is positive, hence safe.
1543 */
1544 reg->s32_min_value = reg->u32_min_value;
1545 reg->s32_max_value = reg->u32_max_value =
1546 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1547 } else if ((s32)reg->u32_min_value < 0) {
1548 /* Negative. We can't learn anything from the smax, but smin
1549 * is negative, hence safe.
1550 */
1551 reg->s32_min_value = reg->u32_min_value =
1552 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1553 reg->s32_max_value = reg->u32_max_value;
1554 }
1555 }
1556
__reg64_deduce_bounds(struct bpf_reg_state * reg)1557 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1558 {
1559 /* Learn sign from signed bounds.
1560 * If we cannot cross the sign boundary, then signed and unsigned bounds
1561 * are the same, so combine. This works even in the negative case, e.g.
1562 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1563 */
1564 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1565 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1566 reg->umin_value);
1567 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1568 reg->umax_value);
1569 return;
1570 }
1571 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1572 * boundary, so we must be careful.
1573 */
1574 if ((s64)reg->umax_value >= 0) {
1575 /* Positive. We can't learn anything from the smin, but smax
1576 * is positive, hence safe.
1577 */
1578 reg->smin_value = reg->umin_value;
1579 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1580 reg->umax_value);
1581 } else if ((s64)reg->umin_value < 0) {
1582 /* Negative. We can't learn anything from the smax, but smin
1583 * is negative, hence safe.
1584 */
1585 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1586 reg->umin_value);
1587 reg->smax_value = reg->umax_value;
1588 }
1589 }
1590
__reg_deduce_bounds(struct bpf_reg_state * reg)1591 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1592 {
1593 __reg32_deduce_bounds(reg);
1594 __reg64_deduce_bounds(reg);
1595 }
1596
1597 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1598 static void __reg_bound_offset(struct bpf_reg_state *reg)
1599 {
1600 struct tnum var64_off = tnum_intersect(reg->var_off,
1601 tnum_range(reg->umin_value,
1602 reg->umax_value));
1603 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
1604 tnum_range(reg->u32_min_value,
1605 reg->u32_max_value));
1606
1607 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1608 }
1609
reg_bounds_sync(struct bpf_reg_state * reg)1610 static void reg_bounds_sync(struct bpf_reg_state *reg)
1611 {
1612 /* We might have learned new bounds from the var_off. */
1613 __update_reg_bounds(reg);
1614 /* We might have learned something about the sign bit. */
1615 __reg_deduce_bounds(reg);
1616 /* We might have learned some bits from the bounds. */
1617 __reg_bound_offset(reg);
1618 /* Intersecting with the old var_off might have improved our bounds
1619 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1620 * then new var_off is (0; 0x7f...fc) which improves our umax.
1621 */
1622 __update_reg_bounds(reg);
1623 }
1624
__reg32_bound_s64(s32 a)1625 static bool __reg32_bound_s64(s32 a)
1626 {
1627 return a >= 0 && a <= S32_MAX;
1628 }
1629
__reg_assign_32_into_64(struct bpf_reg_state * reg)1630 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1631 {
1632 reg->umin_value = reg->u32_min_value;
1633 reg->umax_value = reg->u32_max_value;
1634
1635 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1636 * be positive otherwise set to worse case bounds and refine later
1637 * from tnum.
1638 */
1639 if (__reg32_bound_s64(reg->s32_min_value) &&
1640 __reg32_bound_s64(reg->s32_max_value)) {
1641 reg->smin_value = reg->s32_min_value;
1642 reg->smax_value = reg->s32_max_value;
1643 } else {
1644 reg->smin_value = 0;
1645 reg->smax_value = U32_MAX;
1646 }
1647 }
1648
__reg_combine_32_into_64(struct bpf_reg_state * reg)1649 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1650 {
1651 /* special case when 64-bit register has upper 32-bit register
1652 * zeroed. Typically happens after zext or <<32, >>32 sequence
1653 * allowing us to use 32-bit bounds directly,
1654 */
1655 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1656 __reg_assign_32_into_64(reg);
1657 } else {
1658 /* Otherwise the best we can do is push lower 32bit known and
1659 * unknown bits into register (var_off set from jmp logic)
1660 * then learn as much as possible from the 64-bit tnum
1661 * known and unknown bits. The previous smin/smax bounds are
1662 * invalid here because of jmp32 compare so mark them unknown
1663 * so they do not impact tnum bounds calculation.
1664 */
1665 __mark_reg64_unbounded(reg);
1666 }
1667 reg_bounds_sync(reg);
1668 }
1669
__reg64_bound_s32(s64 a)1670 static bool __reg64_bound_s32(s64 a)
1671 {
1672 return a >= S32_MIN && a <= S32_MAX;
1673 }
1674
__reg64_bound_u32(u64 a)1675 static bool __reg64_bound_u32(u64 a)
1676 {
1677 return a >= U32_MIN && a <= U32_MAX;
1678 }
1679
__reg_combine_64_into_32(struct bpf_reg_state * reg)1680 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1681 {
1682 __mark_reg32_unbounded(reg);
1683 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1684 reg->s32_min_value = (s32)reg->smin_value;
1685 reg->s32_max_value = (s32)reg->smax_value;
1686 }
1687 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1688 reg->u32_min_value = (u32)reg->umin_value;
1689 reg->u32_max_value = (u32)reg->umax_value;
1690 }
1691 reg_bounds_sync(reg);
1692 }
1693
1694 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1695 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1696 struct bpf_reg_state *reg)
1697 {
1698 /*
1699 * Clear type, id, off, and union(map_ptr, range) and
1700 * padding between 'type' and union
1701 */
1702 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1703 reg->type = SCALAR_VALUE;
1704 reg->var_off = tnum_unknown;
1705 reg->frameno = 0;
1706 reg->precise = !env->bpf_capable;
1707 __mark_reg_unbounded(reg);
1708 }
1709
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1710 static void mark_reg_unknown(struct bpf_verifier_env *env,
1711 struct bpf_reg_state *regs, u32 regno)
1712 {
1713 if (WARN_ON(regno >= MAX_BPF_REG)) {
1714 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1715 /* Something bad happened, let's kill all regs except FP */
1716 for (regno = 0; regno < BPF_REG_FP; regno++)
1717 __mark_reg_not_init(env, regs + regno);
1718 return;
1719 }
1720 __mark_reg_unknown(env, regs + regno);
1721 }
1722
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1723 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1724 struct bpf_reg_state *reg)
1725 {
1726 __mark_reg_unknown(env, reg);
1727 reg->type = NOT_INIT;
1728 }
1729
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1730 static void mark_reg_not_init(struct bpf_verifier_env *env,
1731 struct bpf_reg_state *regs, u32 regno)
1732 {
1733 if (WARN_ON(regno >= MAX_BPF_REG)) {
1734 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1735 /* Something bad happened, let's kill all regs except FP */
1736 for (regno = 0; regno < BPF_REG_FP; regno++)
1737 __mark_reg_not_init(env, regs + regno);
1738 return;
1739 }
1740 __mark_reg_not_init(env, regs + regno);
1741 }
1742
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)1743 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1744 struct bpf_reg_state *regs, u32 regno,
1745 enum bpf_reg_type reg_type,
1746 struct btf *btf, u32 btf_id,
1747 enum bpf_type_flag flag)
1748 {
1749 if (reg_type == SCALAR_VALUE) {
1750 mark_reg_unknown(env, regs, regno);
1751 return;
1752 }
1753 mark_reg_known_zero(env, regs, regno);
1754 regs[regno].type = PTR_TO_BTF_ID | flag;
1755 regs[regno].btf = btf;
1756 regs[regno].btf_id = btf_id;
1757 }
1758
1759 #define DEF_NOT_SUBREG (0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1760 static void init_reg_state(struct bpf_verifier_env *env,
1761 struct bpf_func_state *state)
1762 {
1763 struct bpf_reg_state *regs = state->regs;
1764 int i;
1765
1766 for (i = 0; i < MAX_BPF_REG; i++) {
1767 mark_reg_not_init(env, regs, i);
1768 regs[i].live = REG_LIVE_NONE;
1769 regs[i].parent = NULL;
1770 regs[i].subreg_def = DEF_NOT_SUBREG;
1771 }
1772
1773 /* frame pointer */
1774 regs[BPF_REG_FP].type = PTR_TO_STACK;
1775 mark_reg_known_zero(env, regs, BPF_REG_FP);
1776 regs[BPF_REG_FP].frameno = state->frameno;
1777 }
1778
1779 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1780 static void init_func_state(struct bpf_verifier_env *env,
1781 struct bpf_func_state *state,
1782 int callsite, int frameno, int subprogno)
1783 {
1784 state->callsite = callsite;
1785 state->frameno = frameno;
1786 state->subprogno = subprogno;
1787 state->callback_ret_range = tnum_range(0, 0);
1788 init_reg_state(env, state);
1789 mark_verifier_state_scratched(env);
1790 }
1791
1792 /* 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)1793 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1794 int insn_idx, int prev_insn_idx,
1795 int subprog)
1796 {
1797 struct bpf_verifier_stack_elem *elem;
1798 struct bpf_func_state *frame;
1799
1800 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1801 if (!elem)
1802 goto err;
1803
1804 elem->insn_idx = insn_idx;
1805 elem->prev_insn_idx = prev_insn_idx;
1806 elem->next = env->head;
1807 elem->log_pos = env->log.len_used;
1808 env->head = elem;
1809 env->stack_size++;
1810 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1811 verbose(env,
1812 "The sequence of %d jumps is too complex for async cb.\n",
1813 env->stack_size);
1814 goto err;
1815 }
1816 /* Unlike push_stack() do not copy_verifier_state().
1817 * The caller state doesn't matter.
1818 * This is async callback. It starts in a fresh stack.
1819 * Initialize it similar to do_check_common().
1820 */
1821 elem->st.branches = 1;
1822 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1823 if (!frame)
1824 goto err;
1825 init_func_state(env, frame,
1826 BPF_MAIN_FUNC /* callsite */,
1827 0 /* frameno within this callchain */,
1828 subprog /* subprog number within this prog */);
1829 elem->st.frame[0] = frame;
1830 return &elem->st;
1831 err:
1832 free_verifier_state(env->cur_state, true);
1833 env->cur_state = NULL;
1834 /* pop all elements and return */
1835 while (!pop_stack(env, NULL, NULL, false));
1836 return NULL;
1837 }
1838
1839
1840 enum reg_arg_type {
1841 SRC_OP, /* register is used as source operand */
1842 DST_OP, /* register is used as destination operand */
1843 DST_OP_NO_MARK /* same as above, check only, don't mark */
1844 };
1845
cmp_subprogs(const void * a,const void * b)1846 static int cmp_subprogs(const void *a, const void *b)
1847 {
1848 return ((struct bpf_subprog_info *)a)->start -
1849 ((struct bpf_subprog_info *)b)->start;
1850 }
1851
find_subprog(struct bpf_verifier_env * env,int off)1852 static int find_subprog(struct bpf_verifier_env *env, int off)
1853 {
1854 struct bpf_subprog_info *p;
1855
1856 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1857 sizeof(env->subprog_info[0]), cmp_subprogs);
1858 if (!p)
1859 return -ENOENT;
1860 return p - env->subprog_info;
1861
1862 }
1863
add_subprog(struct bpf_verifier_env * env,int off)1864 static int add_subprog(struct bpf_verifier_env *env, int off)
1865 {
1866 int insn_cnt = env->prog->len;
1867 int ret;
1868
1869 if (off >= insn_cnt || off < 0) {
1870 verbose(env, "call to invalid destination\n");
1871 return -EINVAL;
1872 }
1873 ret = find_subprog(env, off);
1874 if (ret >= 0)
1875 return ret;
1876 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1877 verbose(env, "too many subprograms\n");
1878 return -E2BIG;
1879 }
1880 /* determine subprog starts. The end is one before the next starts */
1881 env->subprog_info[env->subprog_cnt++].start = off;
1882 sort(env->subprog_info, env->subprog_cnt,
1883 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1884 return env->subprog_cnt - 1;
1885 }
1886
1887 #define MAX_KFUNC_DESCS 256
1888 #define MAX_KFUNC_BTFS 256
1889
1890 struct bpf_kfunc_desc {
1891 struct btf_func_model func_model;
1892 u32 func_id;
1893 s32 imm;
1894 u16 offset;
1895 };
1896
1897 struct bpf_kfunc_btf {
1898 struct btf *btf;
1899 struct module *module;
1900 u16 offset;
1901 };
1902
1903 struct bpf_kfunc_desc_tab {
1904 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1905 u32 nr_descs;
1906 };
1907
1908 struct bpf_kfunc_btf_tab {
1909 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1910 u32 nr_descs;
1911 };
1912
kfunc_desc_cmp_by_id_off(const void * a,const void * b)1913 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
1914 {
1915 const struct bpf_kfunc_desc *d0 = a;
1916 const struct bpf_kfunc_desc *d1 = b;
1917
1918 /* func_id is not greater than BTF_MAX_TYPE */
1919 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1920 }
1921
kfunc_btf_cmp_by_off(const void * a,const void * b)1922 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1923 {
1924 const struct bpf_kfunc_btf *d0 = a;
1925 const struct bpf_kfunc_btf *d1 = b;
1926
1927 return d0->offset - d1->offset;
1928 }
1929
1930 static const struct bpf_kfunc_desc *
find_kfunc_desc(const struct bpf_prog * prog,u32 func_id,u16 offset)1931 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
1932 {
1933 struct bpf_kfunc_desc desc = {
1934 .func_id = func_id,
1935 .offset = offset,
1936 };
1937 struct bpf_kfunc_desc_tab *tab;
1938
1939 tab = prog->aux->kfunc_tab;
1940 return bsearch(&desc, tab->descs, tab->nr_descs,
1941 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
1942 }
1943
__find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)1944 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1945 s16 offset)
1946 {
1947 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1948 struct bpf_kfunc_btf_tab *tab;
1949 struct bpf_kfunc_btf *b;
1950 struct module *mod;
1951 struct btf *btf;
1952 int btf_fd;
1953
1954 tab = env->prog->aux->kfunc_btf_tab;
1955 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1956 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1957 if (!b) {
1958 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1959 verbose(env, "too many different module BTFs\n");
1960 return ERR_PTR(-E2BIG);
1961 }
1962
1963 if (bpfptr_is_null(env->fd_array)) {
1964 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1965 return ERR_PTR(-EPROTO);
1966 }
1967
1968 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1969 offset * sizeof(btf_fd),
1970 sizeof(btf_fd)))
1971 return ERR_PTR(-EFAULT);
1972
1973 btf = btf_get_by_fd(btf_fd);
1974 if (IS_ERR(btf)) {
1975 verbose(env, "invalid module BTF fd specified\n");
1976 return btf;
1977 }
1978
1979 if (!btf_is_module(btf)) {
1980 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1981 btf_put(btf);
1982 return ERR_PTR(-EINVAL);
1983 }
1984
1985 mod = btf_try_get_module(btf);
1986 if (!mod) {
1987 btf_put(btf);
1988 return ERR_PTR(-ENXIO);
1989 }
1990
1991 b = &tab->descs[tab->nr_descs++];
1992 b->btf = btf;
1993 b->module = mod;
1994 b->offset = offset;
1995
1996 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1997 kfunc_btf_cmp_by_off, NULL);
1998 }
1999 return b->btf;
2000 }
2001
bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab * tab)2002 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2003 {
2004 if (!tab)
2005 return;
2006
2007 while (tab->nr_descs--) {
2008 module_put(tab->descs[tab->nr_descs].module);
2009 btf_put(tab->descs[tab->nr_descs].btf);
2010 }
2011 kfree(tab);
2012 }
2013
find_kfunc_desc_btf(struct bpf_verifier_env * env,s16 offset)2014 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2015 {
2016 if (offset) {
2017 if (offset < 0) {
2018 /* In the future, this can be allowed to increase limit
2019 * of fd index into fd_array, interpreted as u16.
2020 */
2021 verbose(env, "negative offset disallowed for kernel module function call\n");
2022 return ERR_PTR(-EINVAL);
2023 }
2024
2025 return __find_kfunc_desc_btf(env, offset);
2026 }
2027 return btf_vmlinux ?: ERR_PTR(-ENOENT);
2028 }
2029
add_kfunc_call(struct bpf_verifier_env * env,u32 func_id,s16 offset)2030 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2031 {
2032 const struct btf_type *func, *func_proto;
2033 struct bpf_kfunc_btf_tab *btf_tab;
2034 struct bpf_kfunc_desc_tab *tab;
2035 struct bpf_prog_aux *prog_aux;
2036 struct bpf_kfunc_desc *desc;
2037 const char *func_name;
2038 struct btf *desc_btf;
2039 unsigned long call_imm;
2040 unsigned long addr;
2041 int err;
2042
2043 prog_aux = env->prog->aux;
2044 tab = prog_aux->kfunc_tab;
2045 btf_tab = prog_aux->kfunc_btf_tab;
2046 if (!tab) {
2047 if (!btf_vmlinux) {
2048 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2049 return -ENOTSUPP;
2050 }
2051
2052 if (!env->prog->jit_requested) {
2053 verbose(env, "JIT is required for calling kernel function\n");
2054 return -ENOTSUPP;
2055 }
2056
2057 if (!bpf_jit_supports_kfunc_call()) {
2058 verbose(env, "JIT does not support calling kernel function\n");
2059 return -ENOTSUPP;
2060 }
2061
2062 if (!env->prog->gpl_compatible) {
2063 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2064 return -EINVAL;
2065 }
2066
2067 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2068 if (!tab)
2069 return -ENOMEM;
2070 prog_aux->kfunc_tab = tab;
2071 }
2072
2073 /* func_id == 0 is always invalid, but instead of returning an error, be
2074 * conservative and wait until the code elimination pass before returning
2075 * error, so that invalid calls that get pruned out can be in BPF programs
2076 * loaded from userspace. It is also required that offset be untouched
2077 * for such calls.
2078 */
2079 if (!func_id && !offset)
2080 return 0;
2081
2082 if (!btf_tab && offset) {
2083 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2084 if (!btf_tab)
2085 return -ENOMEM;
2086 prog_aux->kfunc_btf_tab = btf_tab;
2087 }
2088
2089 desc_btf = find_kfunc_desc_btf(env, offset);
2090 if (IS_ERR(desc_btf)) {
2091 verbose(env, "failed to find BTF for kernel function\n");
2092 return PTR_ERR(desc_btf);
2093 }
2094
2095 if (find_kfunc_desc(env->prog, func_id, offset))
2096 return 0;
2097
2098 if (tab->nr_descs == MAX_KFUNC_DESCS) {
2099 verbose(env, "too many different kernel function calls\n");
2100 return -E2BIG;
2101 }
2102
2103 func = btf_type_by_id(desc_btf, func_id);
2104 if (!func || !btf_type_is_func(func)) {
2105 verbose(env, "kernel btf_id %u is not a function\n",
2106 func_id);
2107 return -EINVAL;
2108 }
2109 func_proto = btf_type_by_id(desc_btf, func->type);
2110 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2111 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2112 func_id);
2113 return -EINVAL;
2114 }
2115
2116 func_name = btf_name_by_offset(desc_btf, func->name_off);
2117 addr = kallsyms_lookup_name(func_name);
2118 if (!addr) {
2119 verbose(env, "cannot find address for kernel function %s\n",
2120 func_name);
2121 return -EINVAL;
2122 }
2123
2124 call_imm = BPF_CALL_IMM(addr);
2125 /* Check whether or not the relative offset overflows desc->imm */
2126 if ((unsigned long)(s32)call_imm != call_imm) {
2127 verbose(env, "address of kernel function %s is out of range\n",
2128 func_name);
2129 return -EINVAL;
2130 }
2131
2132 desc = &tab->descs[tab->nr_descs++];
2133 desc->func_id = func_id;
2134 desc->imm = call_imm;
2135 desc->offset = offset;
2136 err = btf_distill_func_proto(&env->log, desc_btf,
2137 func_proto, func_name,
2138 &desc->func_model);
2139 if (!err)
2140 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2141 kfunc_desc_cmp_by_id_off, NULL);
2142 return err;
2143 }
2144
kfunc_desc_cmp_by_imm(const void * a,const void * b)2145 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
2146 {
2147 const struct bpf_kfunc_desc *d0 = a;
2148 const struct bpf_kfunc_desc *d1 = b;
2149
2150 if (d0->imm > d1->imm)
2151 return 1;
2152 else if (d0->imm < d1->imm)
2153 return -1;
2154 return 0;
2155 }
2156
sort_kfunc_descs_by_imm(struct bpf_prog * prog)2157 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
2158 {
2159 struct bpf_kfunc_desc_tab *tab;
2160
2161 tab = prog->aux->kfunc_tab;
2162 if (!tab)
2163 return;
2164
2165 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2166 kfunc_desc_cmp_by_imm, NULL);
2167 }
2168
bpf_prog_has_kfunc_call(const struct bpf_prog * prog)2169 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2170 {
2171 return !!prog->aux->kfunc_tab;
2172 }
2173
2174 const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)2175 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2176 const struct bpf_insn *insn)
2177 {
2178 const struct bpf_kfunc_desc desc = {
2179 .imm = insn->imm,
2180 };
2181 const struct bpf_kfunc_desc *res;
2182 struct bpf_kfunc_desc_tab *tab;
2183
2184 tab = prog->aux->kfunc_tab;
2185 res = bsearch(&desc, tab->descs, tab->nr_descs,
2186 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2187
2188 return res ? &res->func_model : NULL;
2189 }
2190
add_subprog_and_kfunc(struct bpf_verifier_env * env)2191 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2192 {
2193 struct bpf_subprog_info *subprog = env->subprog_info;
2194 struct bpf_insn *insn = env->prog->insnsi;
2195 int i, ret, insn_cnt = env->prog->len;
2196
2197 /* Add entry function. */
2198 ret = add_subprog(env, 0);
2199 if (ret)
2200 return ret;
2201
2202 for (i = 0; i < insn_cnt; i++, insn++) {
2203 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2204 !bpf_pseudo_kfunc_call(insn))
2205 continue;
2206
2207 if (!env->bpf_capable) {
2208 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2209 return -EPERM;
2210 }
2211
2212 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2213 ret = add_subprog(env, i + insn->imm + 1);
2214 else
2215 ret = add_kfunc_call(env, insn->imm, insn->off);
2216
2217 if (ret < 0)
2218 return ret;
2219 }
2220
2221 /* Add a fake 'exit' subprog which could simplify subprog iteration
2222 * logic. 'subprog_cnt' should not be increased.
2223 */
2224 subprog[env->subprog_cnt].start = insn_cnt;
2225
2226 if (env->log.level & BPF_LOG_LEVEL2)
2227 for (i = 0; i < env->subprog_cnt; i++)
2228 verbose(env, "func#%d @%d\n", i, subprog[i].start);
2229
2230 return 0;
2231 }
2232
check_subprogs(struct bpf_verifier_env * env)2233 static int check_subprogs(struct bpf_verifier_env *env)
2234 {
2235 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2236 struct bpf_subprog_info *subprog = env->subprog_info;
2237 struct bpf_insn *insn = env->prog->insnsi;
2238 int insn_cnt = env->prog->len;
2239
2240 /* now check that all jumps are within the same subprog */
2241 subprog_start = subprog[cur_subprog].start;
2242 subprog_end = subprog[cur_subprog + 1].start;
2243 for (i = 0; i < insn_cnt; i++) {
2244 u8 code = insn[i].code;
2245
2246 if (code == (BPF_JMP | BPF_CALL) &&
2247 insn[i].imm == BPF_FUNC_tail_call &&
2248 insn[i].src_reg != BPF_PSEUDO_CALL)
2249 subprog[cur_subprog].has_tail_call = true;
2250 if (BPF_CLASS(code) == BPF_LD &&
2251 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2252 subprog[cur_subprog].has_ld_abs = true;
2253 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2254 goto next;
2255 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2256 goto next;
2257 off = i + insn[i].off + 1;
2258 if (off < subprog_start || off >= subprog_end) {
2259 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2260 return -EINVAL;
2261 }
2262 next:
2263 if (i == subprog_end - 1) {
2264 /* to avoid fall-through from one subprog into another
2265 * the last insn of the subprog should be either exit
2266 * or unconditional jump back
2267 */
2268 if (code != (BPF_JMP | BPF_EXIT) &&
2269 code != (BPF_JMP | BPF_JA)) {
2270 verbose(env, "last insn is not an exit or jmp\n");
2271 return -EINVAL;
2272 }
2273 subprog_start = subprog_end;
2274 cur_subprog++;
2275 if (cur_subprog < env->subprog_cnt)
2276 subprog_end = subprog[cur_subprog + 1].start;
2277 }
2278 }
2279 return 0;
2280 }
2281
2282 /* Parentage chain of this register (or stack slot) should take care of all
2283 * issues like callee-saved registers, stack slot allocation time, etc.
2284 */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)2285 static int mark_reg_read(struct bpf_verifier_env *env,
2286 const struct bpf_reg_state *state,
2287 struct bpf_reg_state *parent, u8 flag)
2288 {
2289 bool writes = parent == state->parent; /* Observe write marks */
2290 int cnt = 0;
2291
2292 while (parent) {
2293 /* if read wasn't screened by an earlier write ... */
2294 if (writes && state->live & REG_LIVE_WRITTEN)
2295 break;
2296 if (parent->live & REG_LIVE_DONE) {
2297 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2298 reg_type_str(env, parent->type),
2299 parent->var_off.value, parent->off);
2300 return -EFAULT;
2301 }
2302 /* The first condition is more likely to be true than the
2303 * second, checked it first.
2304 */
2305 if ((parent->live & REG_LIVE_READ) == flag ||
2306 parent->live & REG_LIVE_READ64)
2307 /* The parentage chain never changes and
2308 * this parent was already marked as LIVE_READ.
2309 * There is no need to keep walking the chain again and
2310 * keep re-marking all parents as LIVE_READ.
2311 * This case happens when the same register is read
2312 * multiple times without writes into it in-between.
2313 * Also, if parent has the stronger REG_LIVE_READ64 set,
2314 * then no need to set the weak REG_LIVE_READ32.
2315 */
2316 break;
2317 /* ... then we depend on parent's value */
2318 parent->live |= flag;
2319 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2320 if (flag == REG_LIVE_READ64)
2321 parent->live &= ~REG_LIVE_READ32;
2322 state = parent;
2323 parent = state->parent;
2324 writes = true;
2325 cnt++;
2326 }
2327
2328 if (env->longest_mark_read_walk < cnt)
2329 env->longest_mark_read_walk = cnt;
2330 return 0;
2331 }
2332
2333 /* This function is supposed to be used by the following 32-bit optimization
2334 * code only. It returns TRUE if the source or destination register operates
2335 * on 64-bit, otherwise return FALSE.
2336 */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)2337 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2338 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2339 {
2340 u8 code, class, op;
2341
2342 code = insn->code;
2343 class = BPF_CLASS(code);
2344 op = BPF_OP(code);
2345 if (class == BPF_JMP) {
2346 /* BPF_EXIT for "main" will reach here. Return TRUE
2347 * conservatively.
2348 */
2349 if (op == BPF_EXIT)
2350 return true;
2351 if (op == BPF_CALL) {
2352 /* BPF to BPF call will reach here because of marking
2353 * caller saved clobber with DST_OP_NO_MARK for which we
2354 * don't care the register def because they are anyway
2355 * marked as NOT_INIT already.
2356 */
2357 if (insn->src_reg == BPF_PSEUDO_CALL)
2358 return false;
2359 /* Helper call will reach here because of arg type
2360 * check, conservatively return TRUE.
2361 */
2362 if (t == SRC_OP)
2363 return true;
2364
2365 return false;
2366 }
2367 }
2368
2369 if (class == BPF_ALU64 || class == BPF_JMP ||
2370 /* BPF_END always use BPF_ALU class. */
2371 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2372 return true;
2373
2374 if (class == BPF_ALU || class == BPF_JMP32)
2375 return false;
2376
2377 if (class == BPF_LDX) {
2378 if (t != SRC_OP)
2379 return BPF_SIZE(code) == BPF_DW;
2380 /* LDX source must be ptr. */
2381 return true;
2382 }
2383
2384 if (class == BPF_STX) {
2385 /* BPF_STX (including atomic variants) has multiple source
2386 * operands, one of which is a ptr. Check whether the caller is
2387 * asking about it.
2388 */
2389 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2390 return true;
2391 return BPF_SIZE(code) == BPF_DW;
2392 }
2393
2394 if (class == BPF_LD) {
2395 u8 mode = BPF_MODE(code);
2396
2397 /* LD_IMM64 */
2398 if (mode == BPF_IMM)
2399 return true;
2400
2401 /* Both LD_IND and LD_ABS return 32-bit data. */
2402 if (t != SRC_OP)
2403 return false;
2404
2405 /* Implicit ctx ptr. */
2406 if (regno == BPF_REG_6)
2407 return true;
2408
2409 /* Explicit source could be any width. */
2410 return true;
2411 }
2412
2413 if (class == BPF_ST)
2414 /* The only source register for BPF_ST is a ptr. */
2415 return true;
2416
2417 /* Conservatively return true at default. */
2418 return true;
2419 }
2420
2421 /* Return the regno defined by the insn, or -1. */
insn_def_regno(const struct bpf_insn * insn)2422 static int insn_def_regno(const struct bpf_insn *insn)
2423 {
2424 switch (BPF_CLASS(insn->code)) {
2425 case BPF_JMP:
2426 case BPF_JMP32:
2427 case BPF_ST:
2428 return -1;
2429 case BPF_STX:
2430 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2431 (insn->imm & BPF_FETCH)) {
2432 if (insn->imm == BPF_CMPXCHG)
2433 return BPF_REG_0;
2434 else
2435 return insn->src_reg;
2436 } else {
2437 return -1;
2438 }
2439 default:
2440 return insn->dst_reg;
2441 }
2442 }
2443
2444 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)2445 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2446 {
2447 int dst_reg = insn_def_regno(insn);
2448
2449 if (dst_reg == -1)
2450 return false;
2451
2452 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2453 }
2454
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)2455 static void mark_insn_zext(struct bpf_verifier_env *env,
2456 struct bpf_reg_state *reg)
2457 {
2458 s32 def_idx = reg->subreg_def;
2459
2460 if (def_idx == DEF_NOT_SUBREG)
2461 return;
2462
2463 env->insn_aux_data[def_idx - 1].zext_dst = true;
2464 /* The dst will be zero extended, so won't be sub-register anymore. */
2465 reg->subreg_def = DEF_NOT_SUBREG;
2466 }
2467
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)2468 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2469 enum reg_arg_type t)
2470 {
2471 struct bpf_verifier_state *vstate = env->cur_state;
2472 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2473 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2474 struct bpf_reg_state *reg, *regs = state->regs;
2475 bool rw64;
2476
2477 if (regno >= MAX_BPF_REG) {
2478 verbose(env, "R%d is invalid\n", regno);
2479 return -EINVAL;
2480 }
2481
2482 mark_reg_scratched(env, regno);
2483
2484 reg = ®s[regno];
2485 rw64 = is_reg64(env, insn, regno, reg, t);
2486 if (t == SRC_OP) {
2487 /* check whether register used as source operand can be read */
2488 if (reg->type == NOT_INIT) {
2489 verbose(env, "R%d !read_ok\n", regno);
2490 return -EACCES;
2491 }
2492 /* We don't need to worry about FP liveness because it's read-only */
2493 if (regno == BPF_REG_FP)
2494 return 0;
2495
2496 if (rw64)
2497 mark_insn_zext(env, reg);
2498
2499 return mark_reg_read(env, reg, reg->parent,
2500 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2501 } else {
2502 /* check whether register used as dest operand can be written to */
2503 if (regno == BPF_REG_FP) {
2504 verbose(env, "frame pointer is read only\n");
2505 return -EACCES;
2506 }
2507 reg->live |= REG_LIVE_WRITTEN;
2508 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2509 if (t == DST_OP)
2510 mark_reg_unknown(env, regs, regno);
2511 }
2512 return 0;
2513 }
2514
2515 /* 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)2516 static int push_jmp_history(struct bpf_verifier_env *env,
2517 struct bpf_verifier_state *cur)
2518 {
2519 u32 cnt = cur->jmp_history_cnt;
2520 struct bpf_idx_pair *p;
2521 size_t alloc_size;
2522
2523 cnt++;
2524 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
2525 p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
2526 if (!p)
2527 return -ENOMEM;
2528 p[cnt - 1].idx = env->insn_idx;
2529 p[cnt - 1].prev_idx = env->prev_insn_idx;
2530 cur->jmp_history = p;
2531 cur->jmp_history_cnt = cnt;
2532 return 0;
2533 }
2534
2535 /* Backtrack one insn at a time. If idx is not at the top of recorded
2536 * history then previous instruction came from straight line execution.
2537 * Return -ENOENT if we exhausted all instructions within given state.
2538 *
2539 * It's legal to have a bit of a looping with the same starting and ending
2540 * insn index within the same state, e.g.: 3->4->5->3, so just because current
2541 * instruction index is the same as state's first_idx doesn't mean we are
2542 * done. If there is still some jump history left, we should keep going. We
2543 * need to take into account that we might have a jump history between given
2544 * state's parent and itself, due to checkpointing. In this case, we'll have
2545 * history entry recording a jump from last instruction of parent state and
2546 * first instruction of given state.
2547 */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)2548 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2549 u32 *history)
2550 {
2551 u32 cnt = *history;
2552
2553 if (i == st->first_insn_idx) {
2554 if (cnt == 0)
2555 return -ENOENT;
2556 if (cnt == 1 && st->jmp_history[0].idx == i)
2557 return -ENOENT;
2558 }
2559
2560 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2561 i = st->jmp_history[cnt - 1].prev_idx;
2562 (*history)--;
2563 } else {
2564 i--;
2565 }
2566 return i;
2567 }
2568
disasm_kfunc_name(void * data,const struct bpf_insn * insn)2569 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2570 {
2571 const struct btf_type *func;
2572 struct btf *desc_btf;
2573
2574 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2575 return NULL;
2576
2577 desc_btf = find_kfunc_desc_btf(data, insn->off);
2578 if (IS_ERR(desc_btf))
2579 return "<error>";
2580
2581 func = btf_type_by_id(desc_btf, insn->imm);
2582 return btf_name_by_offset(desc_btf, func->name_off);
2583 }
2584
2585 /* For given verifier state backtrack_insn() is called from the last insn to
2586 * the first insn. Its purpose is to compute a bitmask of registers and
2587 * stack slots that needs precision in the parent verifier state.
2588 */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)2589 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2590 u32 *reg_mask, u64 *stack_mask)
2591 {
2592 const struct bpf_insn_cbs cbs = {
2593 .cb_call = disasm_kfunc_name,
2594 .cb_print = verbose,
2595 .private_data = env,
2596 };
2597 struct bpf_insn *insn = env->prog->insnsi + idx;
2598 u8 class = BPF_CLASS(insn->code);
2599 u8 opcode = BPF_OP(insn->code);
2600 u8 mode = BPF_MODE(insn->code);
2601 u32 dreg = 1u << insn->dst_reg;
2602 u32 sreg = 1u << insn->src_reg;
2603 u32 spi;
2604
2605 if (insn->code == 0)
2606 return 0;
2607 if (env->log.level & BPF_LOG_LEVEL2) {
2608 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2609 verbose(env, "%d: ", idx);
2610 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2611 }
2612
2613 if (class == BPF_ALU || class == BPF_ALU64) {
2614 if (!(*reg_mask & dreg))
2615 return 0;
2616 if (opcode == BPF_END || opcode == BPF_NEG) {
2617 /* sreg is reserved and unused
2618 * dreg still need precision before this insn
2619 */
2620 return 0;
2621 } else if (opcode == BPF_MOV) {
2622 if (BPF_SRC(insn->code) == BPF_X) {
2623 /* dreg = sreg
2624 * dreg needs precision after this insn
2625 * sreg needs precision before this insn
2626 */
2627 *reg_mask &= ~dreg;
2628 *reg_mask |= sreg;
2629 } else {
2630 /* dreg = K
2631 * dreg needs precision after this insn.
2632 * Corresponding register is already marked
2633 * as precise=true in this verifier state.
2634 * No further markings in parent are necessary
2635 */
2636 *reg_mask &= ~dreg;
2637 }
2638 } else {
2639 if (BPF_SRC(insn->code) == BPF_X) {
2640 /* dreg += sreg
2641 * both dreg and sreg need precision
2642 * before this insn
2643 */
2644 *reg_mask |= sreg;
2645 } /* else dreg += K
2646 * dreg still needs precision before this insn
2647 */
2648 }
2649 } else if (class == BPF_LDX) {
2650 if (!(*reg_mask & dreg))
2651 return 0;
2652 *reg_mask &= ~dreg;
2653
2654 /* scalars can only be spilled into stack w/o losing precision.
2655 * Load from any other memory can be zero extended.
2656 * The desire to keep that precision is already indicated
2657 * by 'precise' mark in corresponding register of this state.
2658 * No further tracking necessary.
2659 */
2660 if (insn->src_reg != BPF_REG_FP)
2661 return 0;
2662
2663 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2664 * that [fp - off] slot contains scalar that needs to be
2665 * tracked with precision
2666 */
2667 spi = (-insn->off - 1) / BPF_REG_SIZE;
2668 if (spi >= 64) {
2669 verbose(env, "BUG spi %d\n", spi);
2670 WARN_ONCE(1, "verifier backtracking bug");
2671 return -EFAULT;
2672 }
2673 *stack_mask |= 1ull << spi;
2674 } else if (class == BPF_STX || class == BPF_ST) {
2675 if (*reg_mask & dreg)
2676 /* stx & st shouldn't be using _scalar_ dst_reg
2677 * to access memory. It means backtracking
2678 * encountered a case of pointer subtraction.
2679 */
2680 return -ENOTSUPP;
2681 /* scalars can only be spilled into stack */
2682 if (insn->dst_reg != BPF_REG_FP)
2683 return 0;
2684 spi = (-insn->off - 1) / BPF_REG_SIZE;
2685 if (spi >= 64) {
2686 verbose(env, "BUG spi %d\n", spi);
2687 WARN_ONCE(1, "verifier backtracking bug");
2688 return -EFAULT;
2689 }
2690 if (!(*stack_mask & (1ull << spi)))
2691 return 0;
2692 *stack_mask &= ~(1ull << spi);
2693 if (class == BPF_STX)
2694 *reg_mask |= sreg;
2695 } else if (class == BPF_JMP || class == BPF_JMP32) {
2696 if (opcode == BPF_CALL) {
2697 if (insn->src_reg == BPF_PSEUDO_CALL)
2698 return -ENOTSUPP;
2699 /* kfunc with imm==0 is invalid and fixup_kfunc_call will
2700 * catch this error later. Make backtracking conservative
2701 * with ENOTSUPP.
2702 */
2703 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
2704 return -ENOTSUPP;
2705 /* BPF helpers that invoke callback subprogs are
2706 * equivalent to BPF_PSEUDO_CALL above
2707 */
2708 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm))
2709 return -ENOTSUPP;
2710 /* regular helper call sets R0 */
2711 *reg_mask &= ~1;
2712 if (*reg_mask & 0x3f) {
2713 /* if backtracing was looking for registers R1-R5
2714 * they should have been found already.
2715 */
2716 verbose(env, "BUG regs %x\n", *reg_mask);
2717 WARN_ONCE(1, "verifier backtracking bug");
2718 return -EFAULT;
2719 }
2720 } else if (opcode == BPF_EXIT) {
2721 return -ENOTSUPP;
2722 } else if (BPF_SRC(insn->code) == BPF_X) {
2723 if (!(*reg_mask & (dreg | sreg)))
2724 return 0;
2725 /* dreg <cond> sreg
2726 * Both dreg and sreg need precision before
2727 * this insn. If only sreg was marked precise
2728 * before it would be equally necessary to
2729 * propagate it to dreg.
2730 */
2731 *reg_mask |= (sreg | dreg);
2732 /* else dreg <cond> K
2733 * Only dreg still needs precision before
2734 * this insn, so for the K-based conditional
2735 * there is nothing new to be marked.
2736 */
2737 }
2738 } else if (class == BPF_LD) {
2739 if (!(*reg_mask & dreg))
2740 return 0;
2741 *reg_mask &= ~dreg;
2742 /* It's ld_imm64 or ld_abs or ld_ind.
2743 * For ld_imm64 no further tracking of precision
2744 * into parent is necessary
2745 */
2746 if (mode == BPF_IND || mode == BPF_ABS)
2747 /* to be analyzed */
2748 return -ENOTSUPP;
2749 }
2750 return 0;
2751 }
2752
2753 /* the scalar precision tracking algorithm:
2754 * . at the start all registers have precise=false.
2755 * . scalar ranges are tracked as normal through alu and jmp insns.
2756 * . once precise value of the scalar register is used in:
2757 * . ptr + scalar alu
2758 * . if (scalar cond K|scalar)
2759 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2760 * backtrack through the verifier states and mark all registers and
2761 * stack slots with spilled constants that these scalar regisers
2762 * should be precise.
2763 * . during state pruning two registers (or spilled stack slots)
2764 * are equivalent if both are not precise.
2765 *
2766 * Note the verifier cannot simply walk register parentage chain,
2767 * since many different registers and stack slots could have been
2768 * used to compute single precise scalar.
2769 *
2770 * The approach of starting with precise=true for all registers and then
2771 * backtrack to mark a register as not precise when the verifier detects
2772 * that program doesn't care about specific value (e.g., when helper
2773 * takes register as ARG_ANYTHING parameter) is not safe.
2774 *
2775 * It's ok to walk single parentage chain of the verifier states.
2776 * It's possible that this backtracking will go all the way till 1st insn.
2777 * All other branches will be explored for needing precision later.
2778 *
2779 * The backtracking needs to deal with cases like:
2780 * 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)
2781 * r9 -= r8
2782 * r5 = r9
2783 * if r5 > 0x79f goto pc+7
2784 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2785 * r5 += 1
2786 * ...
2787 * call bpf_perf_event_output#25
2788 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2789 *
2790 * and this case:
2791 * r6 = 1
2792 * call foo // uses callee's r6 inside to compute r0
2793 * r0 += r6
2794 * if r0 == 0 goto
2795 *
2796 * to track above reg_mask/stack_mask needs to be independent for each frame.
2797 *
2798 * Also if parent's curframe > frame where backtracking started,
2799 * the verifier need to mark registers in both frames, otherwise callees
2800 * may incorrectly prune callers. This is similar to
2801 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2802 *
2803 * For now backtracking falls back into conservative marking.
2804 */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2805 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2806 struct bpf_verifier_state *st)
2807 {
2808 struct bpf_func_state *func;
2809 struct bpf_reg_state *reg;
2810 int i, j;
2811
2812 /* big hammer: mark all scalars precise in this path.
2813 * pop_stack may still get !precise scalars.
2814 * We also skip current state and go straight to first parent state,
2815 * because precision markings in current non-checkpointed state are
2816 * not needed. See why in the comment in __mark_chain_precision below.
2817 */
2818 for (st = st->parent; st; st = st->parent) {
2819 for (i = 0; i <= st->curframe; i++) {
2820 func = st->frame[i];
2821 for (j = 0; j < BPF_REG_FP; j++) {
2822 reg = &func->regs[j];
2823 if (reg->type != SCALAR_VALUE)
2824 continue;
2825 reg->precise = true;
2826 }
2827 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2828 if (!is_spilled_reg(&func->stack[j]))
2829 continue;
2830 reg = &func->stack[j].spilled_ptr;
2831 if (reg->type != SCALAR_VALUE)
2832 continue;
2833 reg->precise = true;
2834 }
2835 }
2836 }
2837 }
2838
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2839 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2840 {
2841 struct bpf_func_state *func;
2842 struct bpf_reg_state *reg;
2843 int i, j;
2844
2845 for (i = 0; i <= st->curframe; i++) {
2846 func = st->frame[i];
2847 for (j = 0; j < BPF_REG_FP; j++) {
2848 reg = &func->regs[j];
2849 if (reg->type != SCALAR_VALUE)
2850 continue;
2851 reg->precise = false;
2852 }
2853 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2854 if (!is_spilled_reg(&func->stack[j]))
2855 continue;
2856 reg = &func->stack[j].spilled_ptr;
2857 if (reg->type != SCALAR_VALUE)
2858 continue;
2859 reg->precise = false;
2860 }
2861 }
2862 }
2863
2864 /*
2865 * __mark_chain_precision() backtracks BPF program instruction sequence and
2866 * chain of verifier states making sure that register *regno* (if regno >= 0)
2867 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2868 * SCALARS, as well as any other registers and slots that contribute to
2869 * a tracked state of given registers/stack slots, depending on specific BPF
2870 * assembly instructions (see backtrack_insns() for exact instruction handling
2871 * logic). This backtracking relies on recorded jmp_history and is able to
2872 * traverse entire chain of parent states. This process ends only when all the
2873 * necessary registers/slots and their transitive dependencies are marked as
2874 * precise.
2875 *
2876 * One important and subtle aspect is that precise marks *do not matter* in
2877 * the currently verified state (current state). It is important to understand
2878 * why this is the case.
2879 *
2880 * First, note that current state is the state that is not yet "checkpointed",
2881 * i.e., it is not yet put into env->explored_states, and it has no children
2882 * states as well. It's ephemeral, and can end up either a) being discarded if
2883 * compatible explored state is found at some point or BPF_EXIT instruction is
2884 * reached or b) checkpointed and put into env->explored_states, branching out
2885 * into one or more children states.
2886 *
2887 * In the former case, precise markings in current state are completely
2888 * ignored by state comparison code (see regsafe() for details). Only
2889 * checkpointed ("old") state precise markings are important, and if old
2890 * state's register/slot is precise, regsafe() assumes current state's
2891 * register/slot as precise and checks value ranges exactly and precisely. If
2892 * states turn out to be compatible, current state's necessary precise
2893 * markings and any required parent states' precise markings are enforced
2894 * after the fact with propagate_precision() logic, after the fact. But it's
2895 * important to realize that in this case, even after marking current state
2896 * registers/slots as precise, we immediately discard current state. So what
2897 * actually matters is any of the precise markings propagated into current
2898 * state's parent states, which are always checkpointed (due to b) case above).
2899 * As such, for scenario a) it doesn't matter if current state has precise
2900 * markings set or not.
2901 *
2902 * Now, for the scenario b), checkpointing and forking into child(ren)
2903 * state(s). Note that before current state gets to checkpointing step, any
2904 * processed instruction always assumes precise SCALAR register/slot
2905 * knowledge: if precise value or range is useful to prune jump branch, BPF
2906 * verifier takes this opportunity enthusiastically. Similarly, when
2907 * register's value is used to calculate offset or memory address, exact
2908 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2909 * what we mentioned above about state comparison ignoring precise markings
2910 * during state comparison, BPF verifier ignores and also assumes precise
2911 * markings *at will* during instruction verification process. But as verifier
2912 * assumes precision, it also propagates any precision dependencies across
2913 * parent states, which are not yet finalized, so can be further restricted
2914 * based on new knowledge gained from restrictions enforced by their children
2915 * states. This is so that once those parent states are finalized, i.e., when
2916 * they have no more active children state, state comparison logic in
2917 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2918 * required for correctness.
2919 *
2920 * To build a bit more intuition, note also that once a state is checkpointed,
2921 * the path we took to get to that state is not important. This is crucial
2922 * property for state pruning. When state is checkpointed and finalized at
2923 * some instruction index, it can be correctly and safely used to "short
2924 * circuit" any *compatible* state that reaches exactly the same instruction
2925 * index. I.e., if we jumped to that instruction from a completely different
2926 * code path than original finalized state was derived from, it doesn't
2927 * matter, current state can be discarded because from that instruction
2928 * forward having a compatible state will ensure we will safely reach the
2929 * exit. States describe preconditions for further exploration, but completely
2930 * forget the history of how we got here.
2931 *
2932 * This also means that even if we needed precise SCALAR range to get to
2933 * finalized state, but from that point forward *that same* SCALAR register is
2934 * never used in a precise context (i.e., it's precise value is not needed for
2935 * correctness), it's correct and safe to mark such register as "imprecise"
2936 * (i.e., precise marking set to false). This is what we rely on when we do
2937 * not set precise marking in current state. If no child state requires
2938 * precision for any given SCALAR register, it's safe to dictate that it can
2939 * be imprecise. If any child state does require this register to be precise,
2940 * we'll mark it precise later retroactively during precise markings
2941 * propagation from child state to parent states.
2942 *
2943 * Skipping precise marking setting in current state is a mild version of
2944 * relying on the above observation. But we can utilize this property even
2945 * more aggressively by proactively forgetting any precise marking in the
2946 * current state (which we inherited from the parent state), right before we
2947 * checkpoint it and branch off into new child state. This is done by
2948 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2949 * finalized states which help in short circuiting more future states.
2950 */
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2951 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2952 int spi)
2953 {
2954 struct bpf_verifier_state *st = env->cur_state;
2955 int first_idx = st->first_insn_idx;
2956 int last_idx = env->insn_idx;
2957 struct bpf_func_state *func;
2958 struct bpf_reg_state *reg;
2959 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2960 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2961 bool skip_first = true;
2962 bool new_marks = false;
2963 int i, err;
2964
2965 if (!env->bpf_capable)
2966 return 0;
2967
2968 /* Do sanity checks against current state of register and/or stack
2969 * slot, but don't set precise flag in current state, as precision
2970 * tracking in the current state is unnecessary.
2971 */
2972 func = st->frame[frame];
2973 if (regno >= 0) {
2974 reg = &func->regs[regno];
2975 if (reg->type != SCALAR_VALUE) {
2976 WARN_ONCE(1, "backtracing misuse");
2977 return -EFAULT;
2978 }
2979 new_marks = true;
2980 }
2981
2982 while (spi >= 0) {
2983 if (!is_spilled_reg(&func->stack[spi])) {
2984 stack_mask = 0;
2985 break;
2986 }
2987 reg = &func->stack[spi].spilled_ptr;
2988 if (reg->type != SCALAR_VALUE) {
2989 stack_mask = 0;
2990 break;
2991 }
2992 new_marks = true;
2993 break;
2994 }
2995
2996 if (!new_marks)
2997 return 0;
2998 if (!reg_mask && !stack_mask)
2999 return 0;
3000
3001 for (;;) {
3002 DECLARE_BITMAP(mask, 64);
3003 u32 history = st->jmp_history_cnt;
3004
3005 if (env->log.level & BPF_LOG_LEVEL2)
3006 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
3007
3008 if (last_idx < 0) {
3009 /* we are at the entry into subprog, which
3010 * is expected for global funcs, but only if
3011 * requested precise registers are R1-R5
3012 * (which are global func's input arguments)
3013 */
3014 if (st->curframe == 0 &&
3015 st->frame[0]->subprogno > 0 &&
3016 st->frame[0]->callsite == BPF_MAIN_FUNC &&
3017 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
3018 bitmap_from_u64(mask, reg_mask);
3019 for_each_set_bit(i, mask, 32) {
3020 reg = &st->frame[0]->regs[i];
3021 if (reg->type != SCALAR_VALUE) {
3022 reg_mask &= ~(1u << i);
3023 continue;
3024 }
3025 reg->precise = true;
3026 }
3027 return 0;
3028 }
3029
3030 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
3031 st->frame[0]->subprogno, reg_mask, stack_mask);
3032 WARN_ONCE(1, "verifier backtracking bug");
3033 return -EFAULT;
3034 }
3035
3036 for (i = last_idx;;) {
3037 if (skip_first) {
3038 err = 0;
3039 skip_first = false;
3040 } else {
3041 err = backtrack_insn(env, i, ®_mask, &stack_mask);
3042 }
3043 if (err == -ENOTSUPP) {
3044 mark_all_scalars_precise(env, st);
3045 return 0;
3046 } else if (err) {
3047 return err;
3048 }
3049 if (!reg_mask && !stack_mask)
3050 /* Found assignment(s) into tracked register in this state.
3051 * Since this state is already marked, just return.
3052 * Nothing to be tracked further in the parent state.
3053 */
3054 return 0;
3055 i = get_prev_insn_idx(st, i, &history);
3056 if (i == -ENOENT)
3057 break;
3058 if (i >= env->prog->len) {
3059 /* This can happen if backtracking reached insn 0
3060 * and there are still reg_mask or stack_mask
3061 * to backtrack.
3062 * It means the backtracking missed the spot where
3063 * particular register was initialized with a constant.
3064 */
3065 verbose(env, "BUG backtracking idx %d\n", i);
3066 WARN_ONCE(1, "verifier backtracking bug");
3067 return -EFAULT;
3068 }
3069 }
3070 st = st->parent;
3071 if (!st)
3072 break;
3073
3074 new_marks = false;
3075 func = st->frame[frame];
3076 bitmap_from_u64(mask, reg_mask);
3077 for_each_set_bit(i, mask, 32) {
3078 reg = &func->regs[i];
3079 if (reg->type != SCALAR_VALUE) {
3080 reg_mask &= ~(1u << i);
3081 continue;
3082 }
3083 if (!reg->precise)
3084 new_marks = true;
3085 reg->precise = true;
3086 }
3087
3088 bitmap_from_u64(mask, stack_mask);
3089 for_each_set_bit(i, mask, 64) {
3090 if (i >= func->allocated_stack / BPF_REG_SIZE) {
3091 /* the sequence of instructions:
3092 * 2: (bf) r3 = r10
3093 * 3: (7b) *(u64 *)(r3 -8) = r0
3094 * 4: (79) r4 = *(u64 *)(r10 -8)
3095 * doesn't contain jmps. It's backtracked
3096 * as a single block.
3097 * During backtracking insn 3 is not recognized as
3098 * stack access, so at the end of backtracking
3099 * stack slot fp-8 is still marked in stack_mask.
3100 * However the parent state may not have accessed
3101 * fp-8 and it's "unallocated" stack space.
3102 * In such case fallback to conservative.
3103 */
3104 mark_all_scalars_precise(env, st);
3105 return 0;
3106 }
3107
3108 if (!is_spilled_reg(&func->stack[i])) {
3109 stack_mask &= ~(1ull << i);
3110 continue;
3111 }
3112 reg = &func->stack[i].spilled_ptr;
3113 if (reg->type != SCALAR_VALUE) {
3114 stack_mask &= ~(1ull << i);
3115 continue;
3116 }
3117 if (!reg->precise)
3118 new_marks = true;
3119 reg->precise = true;
3120 }
3121 if (env->log.level & BPF_LOG_LEVEL2) {
3122 verbose(env, "parent %s regs=%x stack=%llx marks:",
3123 new_marks ? "didn't have" : "already had",
3124 reg_mask, stack_mask);
3125 print_verifier_state(env, func, true);
3126 }
3127
3128 if (!reg_mask && !stack_mask)
3129 break;
3130 if (!new_marks)
3131 break;
3132
3133 last_idx = st->last_insn_idx;
3134 first_idx = st->first_insn_idx;
3135 }
3136 return 0;
3137 }
3138
mark_chain_precision(struct bpf_verifier_env * env,int regno)3139 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
3140 {
3141 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
3142 }
3143
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)3144 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
3145 {
3146 return __mark_chain_precision(env, frame, regno, -1);
3147 }
3148
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)3149 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
3150 {
3151 return __mark_chain_precision(env, frame, -1, spi);
3152 }
3153
is_spillable_regtype(enum bpf_reg_type type)3154 static bool is_spillable_regtype(enum bpf_reg_type type)
3155 {
3156 switch (base_type(type)) {
3157 case PTR_TO_MAP_VALUE:
3158 case PTR_TO_STACK:
3159 case PTR_TO_CTX:
3160 case PTR_TO_PACKET:
3161 case PTR_TO_PACKET_META:
3162 case PTR_TO_PACKET_END:
3163 case PTR_TO_FLOW_KEYS:
3164 case CONST_PTR_TO_MAP:
3165 case PTR_TO_SOCKET:
3166 case PTR_TO_SOCK_COMMON:
3167 case PTR_TO_TCP_SOCK:
3168 case PTR_TO_XDP_SOCK:
3169 case PTR_TO_BTF_ID:
3170 case PTR_TO_BUF:
3171 case PTR_TO_MEM:
3172 case PTR_TO_FUNC:
3173 case PTR_TO_MAP_KEY:
3174 return true;
3175 default:
3176 return false;
3177 }
3178 }
3179
3180 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)3181 static bool register_is_null(struct bpf_reg_state *reg)
3182 {
3183 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
3184 }
3185
register_is_const(struct bpf_reg_state * reg)3186 static bool register_is_const(struct bpf_reg_state *reg)
3187 {
3188 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
3189 }
3190
__is_scalar_unbounded(struct bpf_reg_state * reg)3191 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
3192 {
3193 return tnum_is_unknown(reg->var_off) &&
3194 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
3195 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
3196 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
3197 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
3198 }
3199
register_is_bounded(struct bpf_reg_state * reg)3200 static bool register_is_bounded(struct bpf_reg_state *reg)
3201 {
3202 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
3203 }
3204
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)3205 static bool __is_pointer_value(bool allow_ptr_leaks,
3206 const struct bpf_reg_state *reg)
3207 {
3208 if (allow_ptr_leaks)
3209 return false;
3210
3211 return reg->type != SCALAR_VALUE;
3212 }
3213
3214 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)3215 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
3216 {
3217 struct bpf_reg_state *parent = dst->parent;
3218 enum bpf_reg_liveness live = dst->live;
3219
3220 *dst = *src;
3221 dst->parent = parent;
3222 dst->live = live;
3223 }
3224
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)3225 static void save_register_state(struct bpf_func_state *state,
3226 int spi, struct bpf_reg_state *reg,
3227 int size)
3228 {
3229 int i;
3230
3231 copy_register_state(&state->stack[spi].spilled_ptr, reg);
3232 if (size == BPF_REG_SIZE)
3233 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3234
3235 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
3236 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
3237
3238 /* size < 8 bytes spill */
3239 for (; i; i--)
3240 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
3241 }
3242
is_bpf_st_mem(struct bpf_insn * insn)3243 static bool is_bpf_st_mem(struct bpf_insn *insn)
3244 {
3245 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
3246 }
3247
3248 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
3249 * stack boundary and alignment are checked in check_mem_access()
3250 */
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)3251 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
3252 /* stack frame we're writing to */
3253 struct bpf_func_state *state,
3254 int off, int size, int value_regno,
3255 int insn_idx)
3256 {
3257 struct bpf_func_state *cur; /* state of the current function */
3258 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
3259 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
3260 struct bpf_reg_state *reg = NULL;
3261 u32 dst_reg = insn->dst_reg;
3262
3263 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
3264 if (err)
3265 return err;
3266 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
3267 * so it's aligned access and [off, off + size) are within stack limits
3268 */
3269 if (!env->allow_ptr_leaks &&
3270 is_spilled_reg(&state->stack[spi]) &&
3271 size != BPF_REG_SIZE) {
3272 verbose(env, "attempt to corrupt spilled pointer on stack\n");
3273 return -EACCES;
3274 }
3275
3276 cur = env->cur_state->frame[env->cur_state->curframe];
3277 if (value_regno >= 0)
3278 reg = &cur->regs[value_regno];
3279 if (!env->bypass_spec_v4) {
3280 bool sanitize = reg && is_spillable_regtype(reg->type);
3281
3282 for (i = 0; i < size; i++) {
3283 u8 type = state->stack[spi].slot_type[i];
3284
3285 if (type != STACK_MISC && type != STACK_ZERO) {
3286 sanitize = true;
3287 break;
3288 }
3289 }
3290
3291 if (sanitize)
3292 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
3293 }
3294
3295 mark_stack_slot_scratched(env, spi);
3296 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
3297 !register_is_null(reg) && env->bpf_capable) {
3298 if (dst_reg != BPF_REG_FP) {
3299 /* The backtracking logic can only recognize explicit
3300 * stack slot address like [fp - 8]. Other spill of
3301 * scalar via different register has to be conservative.
3302 * Backtrack from here and mark all registers as precise
3303 * that contributed into 'reg' being a constant.
3304 */
3305 err = mark_chain_precision(env, value_regno);
3306 if (err)
3307 return err;
3308 }
3309 save_register_state(state, spi, reg, size);
3310 /* Break the relation on a narrowing spill. */
3311 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
3312 state->stack[spi].spilled_ptr.id = 0;
3313 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
3314 insn->imm != 0 && env->bpf_capable) {
3315 struct bpf_reg_state fake_reg = {};
3316
3317 __mark_reg_known(&fake_reg, insn->imm);
3318 fake_reg.type = SCALAR_VALUE;
3319 save_register_state(state, spi, &fake_reg, size);
3320 } else if (reg && is_spillable_regtype(reg->type)) {
3321 /* register containing pointer is being spilled into stack */
3322 if (size != BPF_REG_SIZE) {
3323 verbose_linfo(env, insn_idx, "; ");
3324 verbose(env, "invalid size of register spill\n");
3325 return -EACCES;
3326 }
3327 if (state != cur && reg->type == PTR_TO_STACK) {
3328 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
3329 return -EINVAL;
3330 }
3331 save_register_state(state, spi, reg, size);
3332 } else {
3333 u8 type = STACK_MISC;
3334
3335 /* regular write of data into stack destroys any spilled ptr */
3336 state->stack[spi].spilled_ptr.type = NOT_INIT;
3337 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
3338 if (is_spilled_reg(&state->stack[spi]))
3339 for (i = 0; i < BPF_REG_SIZE; i++)
3340 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
3341
3342 /* only mark the slot as written if all 8 bytes were written
3343 * otherwise read propagation may incorrectly stop too soon
3344 * when stack slots are partially written.
3345 * This heuristic means that read propagation will be
3346 * conservative, since it will add reg_live_read marks
3347 * to stack slots all the way to first state when programs
3348 * writes+reads less than 8 bytes
3349 */
3350 if (size == BPF_REG_SIZE)
3351 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
3352
3353 /* when we zero initialize stack slots mark them as such */
3354 if ((reg && register_is_null(reg)) ||
3355 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
3356 /* backtracking doesn't work for STACK_ZERO yet. */
3357 err = mark_chain_precision(env, value_regno);
3358 if (err)
3359 return err;
3360 type = STACK_ZERO;
3361 }
3362
3363 /* Mark slots affected by this stack write. */
3364 for (i = 0; i < size; i++)
3365 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
3366 type;
3367 }
3368 return 0;
3369 }
3370
3371 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
3372 * known to contain a variable offset.
3373 * This function checks whether the write is permitted and conservatively
3374 * tracks the effects of the write, considering that each stack slot in the
3375 * dynamic range is potentially written to.
3376 *
3377 * 'off' includes 'regno->off'.
3378 * 'value_regno' can be -1, meaning that an unknown value is being written to
3379 * the stack.
3380 *
3381 * Spilled pointers in range are not marked as written because we don't know
3382 * what's going to be actually written. This means that read propagation for
3383 * future reads cannot be terminated by this write.
3384 *
3385 * For privileged programs, uninitialized stack slots are considered
3386 * initialized by this write (even though we don't know exactly what offsets
3387 * are going to be written to). The idea is that we don't want the verifier to
3388 * reject future reads that access slots written to through variable offsets.
3389 */
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)3390 static int check_stack_write_var_off(struct bpf_verifier_env *env,
3391 /* func where register points to */
3392 struct bpf_func_state *state,
3393 int ptr_regno, int off, int size,
3394 int value_regno, int insn_idx)
3395 {
3396 struct bpf_func_state *cur; /* state of the current function */
3397 int min_off, max_off;
3398 int i, err;
3399 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3400 bool writing_zero = false;
3401 /* set if the fact that we're writing a zero is used to let any
3402 * stack slots remain STACK_ZERO
3403 */
3404 bool zero_used = false;
3405
3406 cur = env->cur_state->frame[env->cur_state->curframe];
3407 ptr_reg = &cur->regs[ptr_regno];
3408 min_off = ptr_reg->smin_value + off;
3409 max_off = ptr_reg->smax_value + off + size;
3410 if (value_regno >= 0)
3411 value_reg = &cur->regs[value_regno];
3412 if (value_reg && register_is_null(value_reg))
3413 writing_zero = true;
3414
3415 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
3416 if (err)
3417 return err;
3418
3419
3420 /* Variable offset writes destroy any spilled pointers in range. */
3421 for (i = min_off; i < max_off; i++) {
3422 u8 new_type, *stype;
3423 int slot, spi;
3424
3425 slot = -i - 1;
3426 spi = slot / BPF_REG_SIZE;
3427 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3428 mark_stack_slot_scratched(env, spi);
3429
3430 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
3431 /* Reject the write if range we may write to has not
3432 * been initialized beforehand. If we didn't reject
3433 * here, the ptr status would be erased below (even
3434 * though not all slots are actually overwritten),
3435 * possibly opening the door to leaks.
3436 *
3437 * We do however catch STACK_INVALID case below, and
3438 * only allow reading possibly uninitialized memory
3439 * later for CAP_PERFMON, as the write may not happen to
3440 * that slot.
3441 */
3442 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3443 insn_idx, i);
3444 return -EINVAL;
3445 }
3446
3447 /* Erase all spilled pointers. */
3448 state->stack[spi].spilled_ptr.type = NOT_INIT;
3449
3450 /* Update the slot type. */
3451 new_type = STACK_MISC;
3452 if (writing_zero && *stype == STACK_ZERO) {
3453 new_type = STACK_ZERO;
3454 zero_used = true;
3455 }
3456 /* If the slot is STACK_INVALID, we check whether it's OK to
3457 * pretend that it will be initialized by this write. The slot
3458 * might not actually be written to, and so if we mark it as
3459 * initialized future reads might leak uninitialized memory.
3460 * For privileged programs, we will accept such reads to slots
3461 * that may or may not be written because, if we're reject
3462 * them, the error would be too confusing.
3463 */
3464 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3465 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3466 insn_idx, i);
3467 return -EINVAL;
3468 }
3469 *stype = new_type;
3470 }
3471 if (zero_used) {
3472 /* backtracking doesn't work for STACK_ZERO yet. */
3473 err = mark_chain_precision(env, value_regno);
3474 if (err)
3475 return err;
3476 }
3477 return 0;
3478 }
3479
3480 /* When register 'dst_regno' is assigned some values from stack[min_off,
3481 * max_off), we set the register's type according to the types of the
3482 * respective stack slots. If all the stack values are known to be zeros, then
3483 * so is the destination reg. Otherwise, the register is considered to be
3484 * SCALAR. This function does not deal with register filling; the caller must
3485 * ensure that all spilled registers in the stack range have been marked as
3486 * read.
3487 */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)3488 static void mark_reg_stack_read(struct bpf_verifier_env *env,
3489 /* func where src register points to */
3490 struct bpf_func_state *ptr_state,
3491 int min_off, int max_off, int dst_regno)
3492 {
3493 struct bpf_verifier_state *vstate = env->cur_state;
3494 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3495 int i, slot, spi;
3496 u8 *stype;
3497 int zeros = 0;
3498
3499 for (i = min_off; i < max_off; i++) {
3500 slot = -i - 1;
3501 spi = slot / BPF_REG_SIZE;
3502 stype = ptr_state->stack[spi].slot_type;
3503 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3504 break;
3505 zeros++;
3506 }
3507 if (zeros == max_off - min_off) {
3508 /* any access_size read into register is zero extended,
3509 * so the whole register == const_zero
3510 */
3511 __mark_reg_const_zero(&state->regs[dst_regno]);
3512 /* backtracking doesn't support STACK_ZERO yet,
3513 * so mark it precise here, so that later
3514 * backtracking can stop here.
3515 * Backtracking may not need this if this register
3516 * doesn't participate in pointer adjustment.
3517 * Forward propagation of precise flag is not
3518 * necessary either. This mark is only to stop
3519 * backtracking. Any register that contributed
3520 * to const 0 was marked precise before spill.
3521 */
3522 state->regs[dst_regno].precise = true;
3523 } else {
3524 /* have read misc data from the stack */
3525 mark_reg_unknown(env, state->regs, dst_regno);
3526 }
3527 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3528 }
3529
3530 /* Read the stack at 'off' and put the results into the register indicated by
3531 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3532 * spilled reg.
3533 *
3534 * 'dst_regno' can be -1, meaning that the read value is not going to a
3535 * register.
3536 *
3537 * The access is assumed to be within the current stack bounds.
3538 */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)3539 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3540 /* func where src register points to */
3541 struct bpf_func_state *reg_state,
3542 int off, int size, int dst_regno)
3543 {
3544 struct bpf_verifier_state *vstate = env->cur_state;
3545 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3546 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
3547 struct bpf_reg_state *reg;
3548 u8 *stype, type;
3549
3550 stype = reg_state->stack[spi].slot_type;
3551 reg = ®_state->stack[spi].spilled_ptr;
3552
3553 if (is_spilled_reg(®_state->stack[spi])) {
3554 u8 spill_size = 1;
3555
3556 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3557 spill_size++;
3558
3559 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
3560 if (reg->type != SCALAR_VALUE) {
3561 verbose_linfo(env, env->insn_idx, "; ");
3562 verbose(env, "invalid size of register fill\n");
3563 return -EACCES;
3564 }
3565
3566 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3567 if (dst_regno < 0)
3568 return 0;
3569
3570 if (!(off % BPF_REG_SIZE) && size == spill_size) {
3571 /* The earlier check_reg_arg() has decided the
3572 * subreg_def for this insn. Save it first.
3573 */
3574 s32 subreg_def = state->regs[dst_regno].subreg_def;
3575
3576 copy_register_state(&state->regs[dst_regno], reg);
3577 state->regs[dst_regno].subreg_def = subreg_def;
3578 } else {
3579 for (i = 0; i < size; i++) {
3580 type = stype[(slot - i) % BPF_REG_SIZE];
3581 if (type == STACK_SPILL)
3582 continue;
3583 if (type == STACK_MISC)
3584 continue;
3585 verbose(env, "invalid read from stack off %d+%d size %d\n",
3586 off, i, size);
3587 return -EACCES;
3588 }
3589 mark_reg_unknown(env, state->regs, dst_regno);
3590 }
3591 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3592 return 0;
3593 }
3594
3595 if (dst_regno >= 0) {
3596 /* restore register state from stack */
3597 copy_register_state(&state->regs[dst_regno], reg);
3598 /* mark reg as written since spilled pointer state likely
3599 * has its liveness marks cleared by is_state_visited()
3600 * which resets stack/reg liveness for state transitions
3601 */
3602 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3603 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
3604 /* If dst_regno==-1, the caller is asking us whether
3605 * it is acceptable to use this value as a SCALAR_VALUE
3606 * (e.g. for XADD).
3607 * We must not allow unprivileged callers to do that
3608 * with spilled pointers.
3609 */
3610 verbose(env, "leaking pointer from stack off %d\n",
3611 off);
3612 return -EACCES;
3613 }
3614 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3615 } else {
3616 for (i = 0; i < size; i++) {
3617 type = stype[(slot - i) % BPF_REG_SIZE];
3618 if (type == STACK_MISC)
3619 continue;
3620 if (type == STACK_ZERO)
3621 continue;
3622 verbose(env, "invalid read from stack off %d+%d size %d\n",
3623 off, i, size);
3624 return -EACCES;
3625 }
3626 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
3627 if (dst_regno >= 0)
3628 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
3629 }
3630 return 0;
3631 }
3632
3633 enum bpf_access_src {
3634 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3635 ACCESS_HELPER = 2, /* the access is performed by a helper */
3636 };
3637
3638 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3639 int regno, int off, int access_size,
3640 bool zero_size_allowed,
3641 enum bpf_access_src type,
3642 struct bpf_call_arg_meta *meta);
3643
reg_state(struct bpf_verifier_env * env,int regno)3644 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3645 {
3646 return cur_regs(env) + regno;
3647 }
3648
3649 /* Read the stack at 'ptr_regno + off' and put the result into the register
3650 * 'dst_regno'.
3651 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3652 * but not its variable offset.
3653 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3654 *
3655 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3656 * filling registers (i.e. reads of spilled register cannot be detected when
3657 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3658 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3659 * offset; for a fixed offset check_stack_read_fixed_off should be used
3660 * instead.
3661 */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3662 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3663 int ptr_regno, int off, int size, int dst_regno)
3664 {
3665 /* The state of the source register. */
3666 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3667 struct bpf_func_state *ptr_state = func(env, reg);
3668 int err;
3669 int min_off, max_off;
3670
3671 /* Note that we pass a NULL meta, so raw access will not be permitted.
3672 */
3673 err = check_stack_range_initialized(env, ptr_regno, off, size,
3674 false, ACCESS_DIRECT, NULL);
3675 if (err)
3676 return err;
3677
3678 min_off = reg->smin_value + off;
3679 max_off = reg->smax_value + off;
3680 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3681 return 0;
3682 }
3683
3684 /* check_stack_read dispatches to check_stack_read_fixed_off or
3685 * check_stack_read_var_off.
3686 *
3687 * The caller must ensure that the offset falls within the allocated stack
3688 * bounds.
3689 *
3690 * 'dst_regno' is a register which will receive the value from the stack. It
3691 * can be -1, meaning that the read value is not going to a register.
3692 */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)3693 static int check_stack_read(struct bpf_verifier_env *env,
3694 int ptr_regno, int off, int size,
3695 int dst_regno)
3696 {
3697 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3698 struct bpf_func_state *state = func(env, reg);
3699 int err;
3700 /* Some accesses are only permitted with a static offset. */
3701 bool var_off = !tnum_is_const(reg->var_off);
3702
3703 /* The offset is required to be static when reads don't go to a
3704 * register, in order to not leak pointers (see
3705 * check_stack_read_fixed_off).
3706 */
3707 if (dst_regno < 0 && var_off) {
3708 char tn_buf[48];
3709
3710 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3711 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3712 tn_buf, off, size);
3713 return -EACCES;
3714 }
3715 /* Variable offset is prohibited for unprivileged mode for simplicity
3716 * since it requires corresponding support in Spectre masking for stack
3717 * ALU. See also retrieve_ptr_limit(). The check in
3718 * check_stack_access_for_ptr_arithmetic() called by
3719 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
3720 * with variable offsets, therefore no check is required here. Further,
3721 * just checking it here would be insufficient as speculative stack
3722 * writes could still lead to unsafe speculative behaviour.
3723 */
3724 if (!var_off) {
3725 off += reg->var_off.value;
3726 err = check_stack_read_fixed_off(env, state, off, size,
3727 dst_regno);
3728 } else {
3729 /* Variable offset stack reads need more conservative handling
3730 * than fixed offset ones. Note that dst_regno >= 0 on this
3731 * branch.
3732 */
3733 err = check_stack_read_var_off(env, ptr_regno, off, size,
3734 dst_regno);
3735 }
3736 return err;
3737 }
3738
3739
3740 /* check_stack_write dispatches to check_stack_write_fixed_off or
3741 * check_stack_write_var_off.
3742 *
3743 * 'ptr_regno' is the register used as a pointer into the stack.
3744 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3745 * 'value_regno' is the register whose value we're writing to the stack. It can
3746 * be -1, meaning that we're not writing from a register.
3747 *
3748 * The caller must ensure that the offset falls within the maximum stack size.
3749 */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)3750 static int check_stack_write(struct bpf_verifier_env *env,
3751 int ptr_regno, int off, int size,
3752 int value_regno, int insn_idx)
3753 {
3754 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3755 struct bpf_func_state *state = func(env, reg);
3756 int err;
3757
3758 if (tnum_is_const(reg->var_off)) {
3759 off += reg->var_off.value;
3760 err = check_stack_write_fixed_off(env, state, off, size,
3761 value_regno, insn_idx);
3762 } else {
3763 /* Variable offset stack reads need more conservative handling
3764 * than fixed offset ones.
3765 */
3766 err = check_stack_write_var_off(env, state,
3767 ptr_regno, off, size,
3768 value_regno, insn_idx);
3769 }
3770 return err;
3771 }
3772
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)3773 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3774 int off, int size, enum bpf_access_type type)
3775 {
3776 struct bpf_reg_state *regs = cur_regs(env);
3777 struct bpf_map *map = regs[regno].map_ptr;
3778 u32 cap = bpf_map_flags_to_cap(map);
3779
3780 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3781 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3782 map->value_size, off, size);
3783 return -EACCES;
3784 }
3785
3786 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3787 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3788 map->value_size, off, size);
3789 return -EACCES;
3790 }
3791
3792 return 0;
3793 }
3794
3795 /* 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)3796 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3797 int off, int size, u32 mem_size,
3798 bool zero_size_allowed)
3799 {
3800 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3801 struct bpf_reg_state *reg;
3802
3803 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3804 return 0;
3805
3806 reg = &cur_regs(env)[regno];
3807 switch (reg->type) {
3808 case PTR_TO_MAP_KEY:
3809 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3810 mem_size, off, size);
3811 break;
3812 case PTR_TO_MAP_VALUE:
3813 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3814 mem_size, off, size);
3815 break;
3816 case PTR_TO_PACKET:
3817 case PTR_TO_PACKET_META:
3818 case PTR_TO_PACKET_END:
3819 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3820 off, size, regno, reg->id, off, mem_size);
3821 break;
3822 case PTR_TO_MEM:
3823 default:
3824 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3825 mem_size, off, size);
3826 }
3827
3828 return -EACCES;
3829 }
3830
3831 /* 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)3832 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3833 int off, int size, u32 mem_size,
3834 bool zero_size_allowed)
3835 {
3836 struct bpf_verifier_state *vstate = env->cur_state;
3837 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3838 struct bpf_reg_state *reg = &state->regs[regno];
3839 int err;
3840
3841 /* We may have adjusted the register pointing to memory region, so we
3842 * need to try adding each of min_value and max_value to off
3843 * to make sure our theoretical access will be safe.
3844 *
3845 * The minimum value is only important with signed
3846 * comparisons where we can't assume the floor of a
3847 * value is 0. If we are using signed variables for our
3848 * index'es we need to make sure that whatever we use
3849 * will have a set floor within our range.
3850 */
3851 if (reg->smin_value < 0 &&
3852 (reg->smin_value == S64_MIN ||
3853 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3854 reg->smin_value + off < 0)) {
3855 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3856 regno);
3857 return -EACCES;
3858 }
3859 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3860 mem_size, zero_size_allowed);
3861 if (err) {
3862 verbose(env, "R%d min value is outside of the allowed memory range\n",
3863 regno);
3864 return err;
3865 }
3866
3867 /* If we haven't set a max value then we need to bail since we can't be
3868 * sure we won't do bad things.
3869 * If reg->umax_value + off could overflow, treat that as unbounded too.
3870 */
3871 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3872 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3873 regno);
3874 return -EACCES;
3875 }
3876 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3877 mem_size, zero_size_allowed);
3878 if (err) {
3879 verbose(env, "R%d max value is outside of the allowed memory range\n",
3880 regno);
3881 return err;
3882 }
3883
3884 return 0;
3885 }
3886
__check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,bool fixed_off_ok)3887 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
3888 const struct bpf_reg_state *reg, int regno,
3889 bool fixed_off_ok)
3890 {
3891 /* Access to this pointer-typed register or passing it to a helper
3892 * is only allowed in its original, unmodified form.
3893 */
3894
3895 if (reg->off < 0) {
3896 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
3897 reg_type_str(env, reg->type), regno, reg->off);
3898 return -EACCES;
3899 }
3900
3901 if (!fixed_off_ok && reg->off) {
3902 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
3903 reg_type_str(env, reg->type), regno, reg->off);
3904 return -EACCES;
3905 }
3906
3907 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3908 char tn_buf[48];
3909
3910 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3911 verbose(env, "variable %s access var_off=%s disallowed\n",
3912 reg_type_str(env, reg->type), tn_buf);
3913 return -EACCES;
3914 }
3915
3916 return 0;
3917 }
3918
check_ptr_off_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3919 int check_ptr_off_reg(struct bpf_verifier_env *env,
3920 const struct bpf_reg_state *reg, int regno)
3921 {
3922 return __check_ptr_off_reg(env, reg, regno, false);
3923 }
3924
map_kptr_match_type(struct bpf_verifier_env * env,struct bpf_map_value_off_desc * off_desc,struct bpf_reg_state * reg,u32 regno)3925 static int map_kptr_match_type(struct bpf_verifier_env *env,
3926 struct bpf_map_value_off_desc *off_desc,
3927 struct bpf_reg_state *reg, u32 regno)
3928 {
3929 const char *targ_name = kernel_type_name(off_desc->kptr.btf, off_desc->kptr.btf_id);
3930 int perm_flags = PTR_MAYBE_NULL;
3931 const char *reg_name = "";
3932
3933 /* Only unreferenced case accepts untrusted pointers */
3934 if (off_desc->type == BPF_KPTR_UNREF)
3935 perm_flags |= PTR_UNTRUSTED;
3936
3937 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
3938 goto bad_type;
3939
3940 if (!btf_is_kernel(reg->btf)) {
3941 verbose(env, "R%d must point to kernel BTF\n", regno);
3942 return -EINVAL;
3943 }
3944 /* We need to verify reg->type and reg->btf, before accessing reg->btf */
3945 reg_name = kernel_type_name(reg->btf, reg->btf_id);
3946
3947 /* For ref_ptr case, release function check should ensure we get one
3948 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
3949 * normal store of unreferenced kptr, we must ensure var_off is zero.
3950 * Since ref_ptr cannot be accessed directly by BPF insns, checks for
3951 * reg->off and reg->ref_obj_id are not needed here.
3952 */
3953 if (__check_ptr_off_reg(env, reg, regno, true))
3954 return -EACCES;
3955
3956 /* A full type match is needed, as BTF can be vmlinux or module BTF, and
3957 * we also need to take into account the reg->off.
3958 *
3959 * We want to support cases like:
3960 *
3961 * struct foo {
3962 * struct bar br;
3963 * struct baz bz;
3964 * };
3965 *
3966 * struct foo *v;
3967 * v = func(); // PTR_TO_BTF_ID
3968 * val->foo = v; // reg->off is zero, btf and btf_id match type
3969 * val->bar = &v->br; // reg->off is still zero, but we need to retry with
3970 * // first member type of struct after comparison fails
3971 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
3972 * // to match type
3973 *
3974 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
3975 * is zero. We must also ensure that btf_struct_ids_match does not walk
3976 * the struct to match type against first member of struct, i.e. reject
3977 * second case from above. Hence, when type is BPF_KPTR_REF, we set
3978 * strict mode to true for type match.
3979 */
3980 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
3981 off_desc->kptr.btf, off_desc->kptr.btf_id,
3982 off_desc->type == BPF_KPTR_REF))
3983 goto bad_type;
3984 return 0;
3985 bad_type:
3986 verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
3987 reg_type_str(env, reg->type), reg_name);
3988 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
3989 if (off_desc->type == BPF_KPTR_UNREF)
3990 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
3991 targ_name);
3992 else
3993 verbose(env, "\n");
3994 return -EINVAL;
3995 }
3996
check_map_kptr_access(struct bpf_verifier_env * env,u32 regno,int value_regno,int insn_idx,struct bpf_map_value_off_desc * off_desc)3997 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
3998 int value_regno, int insn_idx,
3999 struct bpf_map_value_off_desc *off_desc)
4000 {
4001 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4002 int class = BPF_CLASS(insn->code);
4003 struct bpf_reg_state *val_reg;
4004
4005 /* Things we already checked for in check_map_access and caller:
4006 * - Reject cases where variable offset may touch kptr
4007 * - size of access (must be BPF_DW)
4008 * - tnum_is_const(reg->var_off)
4009 * - off_desc->offset == off + reg->var_off.value
4010 */
4011 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
4012 if (BPF_MODE(insn->code) != BPF_MEM) {
4013 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
4014 return -EACCES;
4015 }
4016
4017 /* We only allow loading referenced kptr, since it will be marked as
4018 * untrusted, similar to unreferenced kptr.
4019 */
4020 if (class != BPF_LDX && off_desc->type == BPF_KPTR_REF) {
4021 verbose(env, "store to referenced kptr disallowed\n");
4022 return -EACCES;
4023 }
4024
4025 if (class == BPF_LDX) {
4026 val_reg = reg_state(env, value_regno);
4027 /* We can simply mark the value_regno receiving the pointer
4028 * value from map as PTR_TO_BTF_ID, with the correct type.
4029 */
4030 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, off_desc->kptr.btf,
4031 off_desc->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED);
4032 /* For mark_ptr_or_null_reg */
4033 val_reg->id = ++env->id_gen;
4034 } else if (class == BPF_STX) {
4035 val_reg = reg_state(env, value_regno);
4036 if (!register_is_null(val_reg) &&
4037 map_kptr_match_type(env, off_desc, val_reg, value_regno))
4038 return -EACCES;
4039 } else if (class == BPF_ST) {
4040 if (insn->imm) {
4041 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
4042 off_desc->offset);
4043 return -EACCES;
4044 }
4045 } else {
4046 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
4047 return -EACCES;
4048 }
4049 return 0;
4050 }
4051
4052 /* 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)4053 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
4054 int off, int size, bool zero_size_allowed,
4055 enum bpf_access_src src)
4056 {
4057 struct bpf_verifier_state *vstate = env->cur_state;
4058 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4059 struct bpf_reg_state *reg = &state->regs[regno];
4060 struct bpf_map *map = reg->map_ptr;
4061 int err;
4062
4063 err = check_mem_region_access(env, regno, off, size, map->value_size,
4064 zero_size_allowed);
4065 if (err)
4066 return err;
4067
4068 if (map_value_has_spin_lock(map)) {
4069 u32 lock = map->spin_lock_off;
4070
4071 /* if any part of struct bpf_spin_lock can be touched by
4072 * load/store reject this program.
4073 * To check that [x1, x2) overlaps with [y1, y2)
4074 * it is sufficient to check x1 < y2 && y1 < x2.
4075 */
4076 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
4077 lock < reg->umax_value + off + size) {
4078 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
4079 return -EACCES;
4080 }
4081 }
4082 if (map_value_has_timer(map)) {
4083 u32 t = map->timer_off;
4084
4085 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
4086 t < reg->umax_value + off + size) {
4087 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
4088 return -EACCES;
4089 }
4090 }
4091 if (map_value_has_kptrs(map)) {
4092 struct bpf_map_value_off *tab = map->kptr_off_tab;
4093 int i;
4094
4095 for (i = 0; i < tab->nr_off; i++) {
4096 u32 p = tab->off[i].offset;
4097
4098 if (reg->smin_value + off < p + sizeof(u64) &&
4099 p < reg->umax_value + off + size) {
4100 if (src != ACCESS_DIRECT) {
4101 verbose(env, "kptr cannot be accessed indirectly by helper\n");
4102 return -EACCES;
4103 }
4104 if (!tnum_is_const(reg->var_off)) {
4105 verbose(env, "kptr access cannot have variable offset\n");
4106 return -EACCES;
4107 }
4108 if (p != off + reg->var_off.value) {
4109 verbose(env, "kptr access misaligned expected=%u off=%llu\n",
4110 p, off + reg->var_off.value);
4111 return -EACCES;
4112 }
4113 if (size != bpf_size_to_bytes(BPF_DW)) {
4114 verbose(env, "kptr access size must be BPF_DW\n");
4115 return -EACCES;
4116 }
4117 break;
4118 }
4119 }
4120 }
4121 return err;
4122 }
4123
4124 #define MAX_PACKET_OFF 0xffff
4125
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)4126 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
4127 const struct bpf_call_arg_meta *meta,
4128 enum bpf_access_type t)
4129 {
4130 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
4131
4132 switch (prog_type) {
4133 /* Program types only with direct read access go here! */
4134 case BPF_PROG_TYPE_LWT_IN:
4135 case BPF_PROG_TYPE_LWT_OUT:
4136 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
4137 case BPF_PROG_TYPE_SK_REUSEPORT:
4138 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4139 case BPF_PROG_TYPE_CGROUP_SKB:
4140 if (t == BPF_WRITE)
4141 return false;
4142 fallthrough;
4143
4144 /* Program types with direct read + write access go here! */
4145 case BPF_PROG_TYPE_SCHED_CLS:
4146 case BPF_PROG_TYPE_SCHED_ACT:
4147 case BPF_PROG_TYPE_XDP:
4148 case BPF_PROG_TYPE_LWT_XMIT:
4149 case BPF_PROG_TYPE_SK_SKB:
4150 case BPF_PROG_TYPE_SK_MSG:
4151 if (meta)
4152 return meta->pkt_access;
4153
4154 env->seen_direct_write = true;
4155 return true;
4156
4157 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4158 if (t == BPF_WRITE)
4159 env->seen_direct_write = true;
4160
4161 return true;
4162
4163 default:
4164 return false;
4165 }
4166 }
4167
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)4168 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
4169 int size, bool zero_size_allowed)
4170 {
4171 struct bpf_reg_state *regs = cur_regs(env);
4172 struct bpf_reg_state *reg = ®s[regno];
4173 int err;
4174
4175 /* We may have added a variable offset to the packet pointer; but any
4176 * reg->range we have comes after that. We are only checking the fixed
4177 * offset.
4178 */
4179
4180 /* We don't allow negative numbers, because we aren't tracking enough
4181 * detail to prove they're safe.
4182 */
4183 if (reg->smin_value < 0) {
4184 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4185 regno);
4186 return -EACCES;
4187 }
4188
4189 err = reg->range < 0 ? -EINVAL :
4190 __check_mem_access(env, regno, off, size, reg->range,
4191 zero_size_allowed);
4192 if (err) {
4193 verbose(env, "R%d offset is outside of the packet\n", regno);
4194 return err;
4195 }
4196
4197 /* __check_mem_access has made sure "off + size - 1" is within u16.
4198 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
4199 * otherwise find_good_pkt_pointers would have refused to set range info
4200 * that __check_mem_access would have rejected this pkt access.
4201 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
4202 */
4203 env->prog->aux->max_pkt_offset =
4204 max_t(u32, env->prog->aux->max_pkt_offset,
4205 off + reg->umax_value + size - 1);
4206
4207 return err;
4208 }
4209
4210 /* 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)4211 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
4212 enum bpf_access_type t, enum bpf_reg_type *reg_type,
4213 struct btf **btf, u32 *btf_id)
4214 {
4215 struct bpf_insn_access_aux info = {
4216 .reg_type = *reg_type,
4217 .log = &env->log,
4218 };
4219
4220 if (env->ops->is_valid_access &&
4221 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
4222 /* A non zero info.ctx_field_size indicates that this field is a
4223 * candidate for later verifier transformation to load the whole
4224 * field and then apply a mask when accessed with a narrower
4225 * access than actual ctx access size. A zero info.ctx_field_size
4226 * will only allow for whole field access and rejects any other
4227 * type of narrower access.
4228 */
4229 *reg_type = info.reg_type;
4230
4231 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
4232 *btf = info.btf;
4233 *btf_id = info.btf_id;
4234 } else {
4235 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
4236 }
4237 /* remember the offset of last byte accessed in ctx */
4238 if (env->prog->aux->max_ctx_offset < off + size)
4239 env->prog->aux->max_ctx_offset = off + size;
4240 return 0;
4241 }
4242
4243 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
4244 return -EACCES;
4245 }
4246
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)4247 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
4248 int size)
4249 {
4250 if (size < 0 || off < 0 ||
4251 (u64)off + size > sizeof(struct bpf_flow_keys)) {
4252 verbose(env, "invalid access to flow keys off=%d size=%d\n",
4253 off, size);
4254 return -EACCES;
4255 }
4256 return 0;
4257 }
4258
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)4259 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
4260 u32 regno, int off, int size,
4261 enum bpf_access_type t)
4262 {
4263 struct bpf_reg_state *regs = cur_regs(env);
4264 struct bpf_reg_state *reg = ®s[regno];
4265 struct bpf_insn_access_aux info = {};
4266 bool valid;
4267
4268 if (reg->smin_value < 0) {
4269 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4270 regno);
4271 return -EACCES;
4272 }
4273
4274 switch (reg->type) {
4275 case PTR_TO_SOCK_COMMON:
4276 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
4277 break;
4278 case PTR_TO_SOCKET:
4279 valid = bpf_sock_is_valid_access(off, size, t, &info);
4280 break;
4281 case PTR_TO_TCP_SOCK:
4282 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
4283 break;
4284 case PTR_TO_XDP_SOCK:
4285 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
4286 break;
4287 default:
4288 valid = false;
4289 }
4290
4291
4292 if (valid) {
4293 env->insn_aux_data[insn_idx].ctx_field_size =
4294 info.ctx_field_size;
4295 return 0;
4296 }
4297
4298 verbose(env, "R%d invalid %s access off=%d size=%d\n",
4299 regno, reg_type_str(env, reg->type), off, size);
4300
4301 return -EACCES;
4302 }
4303
is_pointer_value(struct bpf_verifier_env * env,int regno)4304 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
4305 {
4306 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4307 }
4308
is_ctx_reg(struct bpf_verifier_env * env,int regno)4309 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
4310 {
4311 const struct bpf_reg_state *reg = reg_state(env, regno);
4312
4313 return reg->type == PTR_TO_CTX;
4314 }
4315
is_sk_reg(struct bpf_verifier_env * env,int regno)4316 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
4317 {
4318 const struct bpf_reg_state *reg = reg_state(env, regno);
4319
4320 return type_is_sk_pointer(reg->type);
4321 }
4322
is_pkt_reg(struct bpf_verifier_env * env,int regno)4323 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
4324 {
4325 const struct bpf_reg_state *reg = reg_state(env, regno);
4326
4327 return type_is_pkt_pointer(reg->type);
4328 }
4329
is_flow_key_reg(struct bpf_verifier_env * env,int regno)4330 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
4331 {
4332 const struct bpf_reg_state *reg = reg_state(env, regno);
4333
4334 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
4335 return reg->type == PTR_TO_FLOW_KEYS;
4336 }
4337
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)4338 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
4339 const struct bpf_reg_state *reg,
4340 int off, int size, bool strict)
4341 {
4342 struct tnum reg_off;
4343 int ip_align;
4344
4345 /* Byte size accesses are always allowed. */
4346 if (!strict || size == 1)
4347 return 0;
4348
4349 /* For platforms that do not have a Kconfig enabling
4350 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
4351 * NET_IP_ALIGN is universally set to '2'. And on platforms
4352 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
4353 * to this code only in strict mode where we want to emulate
4354 * the NET_IP_ALIGN==2 checking. Therefore use an
4355 * unconditional IP align value of '2'.
4356 */
4357 ip_align = 2;
4358
4359 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
4360 if (!tnum_is_aligned(reg_off, size)) {
4361 char tn_buf[48];
4362
4363 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4364 verbose(env,
4365 "misaligned packet access off %d+%s+%d+%d size %d\n",
4366 ip_align, tn_buf, reg->off, off, size);
4367 return -EACCES;
4368 }
4369
4370 return 0;
4371 }
4372
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)4373 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
4374 const struct bpf_reg_state *reg,
4375 const char *pointer_desc,
4376 int off, int size, bool strict)
4377 {
4378 struct tnum reg_off;
4379
4380 /* Byte size accesses are always allowed. */
4381 if (!strict || size == 1)
4382 return 0;
4383
4384 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
4385 if (!tnum_is_aligned(reg_off, size)) {
4386 char tn_buf[48];
4387
4388 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4389 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
4390 pointer_desc, tn_buf, reg->off, off, size);
4391 return -EACCES;
4392 }
4393
4394 return 0;
4395 }
4396
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)4397 static int check_ptr_alignment(struct bpf_verifier_env *env,
4398 const struct bpf_reg_state *reg, int off,
4399 int size, bool strict_alignment_once)
4400 {
4401 bool strict = env->strict_alignment || strict_alignment_once;
4402 const char *pointer_desc = "";
4403
4404 switch (reg->type) {
4405 case PTR_TO_PACKET:
4406 case PTR_TO_PACKET_META:
4407 /* Special case, because of NET_IP_ALIGN. Given metadata sits
4408 * right in front, treat it the very same way.
4409 */
4410 return check_pkt_ptr_alignment(env, reg, off, size, strict);
4411 case PTR_TO_FLOW_KEYS:
4412 pointer_desc = "flow keys ";
4413 break;
4414 case PTR_TO_MAP_KEY:
4415 pointer_desc = "key ";
4416 break;
4417 case PTR_TO_MAP_VALUE:
4418 pointer_desc = "value ";
4419 break;
4420 case PTR_TO_CTX:
4421 pointer_desc = "context ";
4422 break;
4423 case PTR_TO_STACK:
4424 pointer_desc = "stack ";
4425 /* The stack spill tracking logic in check_stack_write_fixed_off()
4426 * and check_stack_read_fixed_off() relies on stack accesses being
4427 * aligned.
4428 */
4429 strict = true;
4430 break;
4431 case PTR_TO_SOCKET:
4432 pointer_desc = "sock ";
4433 break;
4434 case PTR_TO_SOCK_COMMON:
4435 pointer_desc = "sock_common ";
4436 break;
4437 case PTR_TO_TCP_SOCK:
4438 pointer_desc = "tcp_sock ";
4439 break;
4440 case PTR_TO_XDP_SOCK:
4441 pointer_desc = "xdp_sock ";
4442 break;
4443 default:
4444 break;
4445 }
4446 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
4447 strict);
4448 }
4449
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)4450 static int update_stack_depth(struct bpf_verifier_env *env,
4451 const struct bpf_func_state *func,
4452 int off)
4453 {
4454 u16 stack = env->subprog_info[func->subprogno].stack_depth;
4455
4456 if (stack >= -off)
4457 return 0;
4458
4459 /* update known max for given subprogram */
4460 env->subprog_info[func->subprogno].stack_depth = -off;
4461 return 0;
4462 }
4463
4464 /* starting from main bpf function walk all instructions of the function
4465 * and recursively walk all callees that given function can call.
4466 * Ignore jump and exit insns.
4467 * Since recursion is prevented by check_cfg() this algorithm
4468 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
4469 */
check_max_stack_depth_subprog(struct bpf_verifier_env * env,int idx)4470 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
4471 {
4472 struct bpf_subprog_info *subprog = env->subprog_info;
4473 struct bpf_insn *insn = env->prog->insnsi;
4474 int depth = 0, frame = 0, i, subprog_end;
4475 bool tail_call_reachable = false;
4476 int ret_insn[MAX_CALL_FRAMES];
4477 int ret_prog[MAX_CALL_FRAMES];
4478 int j;
4479
4480 i = subprog[idx].start;
4481 process_func:
4482 /* protect against potential stack overflow that might happen when
4483 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
4484 * depth for such case down to 256 so that the worst case scenario
4485 * would result in 8k stack size (32 which is tailcall limit * 256 =
4486 * 8k).
4487 *
4488 * To get the idea what might happen, see an example:
4489 * func1 -> sub rsp, 128
4490 * subfunc1 -> sub rsp, 256
4491 * tailcall1 -> add rsp, 256
4492 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
4493 * subfunc2 -> sub rsp, 64
4494 * subfunc22 -> sub rsp, 128
4495 * tailcall2 -> add rsp, 128
4496 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
4497 *
4498 * tailcall will unwind the current stack frame but it will not get rid
4499 * of caller's stack as shown on the example above.
4500 */
4501 if (idx && subprog[idx].has_tail_call && depth >= 256) {
4502 verbose(env,
4503 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
4504 depth);
4505 return -EACCES;
4506 }
4507 /* round up to 32-bytes, since this is granularity
4508 * of interpreter stack size
4509 */
4510 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4511 if (depth > MAX_BPF_STACK) {
4512 verbose(env, "combined stack size of %d calls is %d. Too large\n",
4513 frame + 1, depth);
4514 return -EACCES;
4515 }
4516 continue_func:
4517 subprog_end = subprog[idx + 1].start;
4518 for (; i < subprog_end; i++) {
4519 int next_insn, sidx;
4520
4521 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
4522 continue;
4523 /* remember insn and function to return to */
4524 ret_insn[frame] = i + 1;
4525 ret_prog[frame] = idx;
4526
4527 /* find the callee */
4528 next_insn = i + insn[i].imm + 1;
4529 sidx = find_subprog(env, next_insn);
4530 if (sidx < 0) {
4531 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4532 next_insn);
4533 return -EFAULT;
4534 }
4535 if (subprog[sidx].is_async_cb) {
4536 if (subprog[sidx].has_tail_call) {
4537 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
4538 return -EFAULT;
4539 }
4540 /* async callbacks don't increase bpf prog stack size unless called directly */
4541 if (!bpf_pseudo_call(insn + i))
4542 continue;
4543 }
4544 i = next_insn;
4545 idx = sidx;
4546
4547 if (subprog[idx].has_tail_call)
4548 tail_call_reachable = true;
4549
4550 frame++;
4551 if (frame >= MAX_CALL_FRAMES) {
4552 verbose(env, "the call stack of %d frames is too deep !\n",
4553 frame);
4554 return -E2BIG;
4555 }
4556 goto process_func;
4557 }
4558 /* if tail call got detected across bpf2bpf calls then mark each of the
4559 * currently present subprog frames as tail call reachable subprogs;
4560 * this info will be utilized by JIT so that we will be preserving the
4561 * tail call counter throughout bpf2bpf calls combined with tailcalls
4562 */
4563 if (tail_call_reachable)
4564 for (j = 0; j < frame; j++)
4565 subprog[ret_prog[j]].tail_call_reachable = true;
4566 if (subprog[0].tail_call_reachable)
4567 env->prog->aux->tail_call_reachable = true;
4568
4569 /* end of for() loop means the last insn of the 'subprog'
4570 * was reached. Doesn't matter whether it was JA or EXIT
4571 */
4572 if (frame == 0)
4573 return 0;
4574 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
4575 frame--;
4576 i = ret_insn[frame];
4577 idx = ret_prog[frame];
4578 goto continue_func;
4579 }
4580
check_max_stack_depth(struct bpf_verifier_env * env)4581 static int check_max_stack_depth(struct bpf_verifier_env *env)
4582 {
4583 struct bpf_subprog_info *si = env->subprog_info;
4584 int ret;
4585
4586 for (int i = 0; i < env->subprog_cnt; i++) {
4587 if (!i || si[i].is_async_cb) {
4588 ret = check_max_stack_depth_subprog(env, i);
4589 if (ret < 0)
4590 return ret;
4591 }
4592 continue;
4593 }
4594 return 0;
4595 }
4596
4597 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)4598 static int get_callee_stack_depth(struct bpf_verifier_env *env,
4599 const struct bpf_insn *insn, int idx)
4600 {
4601 int start = idx + insn->imm + 1, subprog;
4602
4603 subprog = find_subprog(env, start);
4604 if (subprog < 0) {
4605 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
4606 start);
4607 return -EFAULT;
4608 }
4609 return env->subprog_info[subprog].stack_depth;
4610 }
4611 #endif
4612
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)4613 static int __check_buffer_access(struct bpf_verifier_env *env,
4614 const char *buf_info,
4615 const struct bpf_reg_state *reg,
4616 int regno, int off, int size)
4617 {
4618 if (off < 0) {
4619 verbose(env,
4620 "R%d invalid %s buffer access: off=%d, size=%d\n",
4621 regno, buf_info, off, size);
4622 return -EACCES;
4623 }
4624 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4625 char tn_buf[48];
4626
4627 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4628 verbose(env,
4629 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
4630 regno, off, tn_buf);
4631 return -EACCES;
4632 }
4633
4634 return 0;
4635 }
4636
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)4637 static int check_tp_buffer_access(struct bpf_verifier_env *env,
4638 const struct bpf_reg_state *reg,
4639 int regno, int off, int size)
4640 {
4641 int err;
4642
4643 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4644 if (err)
4645 return err;
4646
4647 if (off + size > env->prog->aux->max_tp_access)
4648 env->prog->aux->max_tp_access = off + size;
4649
4650 return 0;
4651 }
4652
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)4653 static int check_buffer_access(struct bpf_verifier_env *env,
4654 const struct bpf_reg_state *reg,
4655 int regno, int off, int size,
4656 bool zero_size_allowed,
4657 u32 *max_access)
4658 {
4659 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
4660 int err;
4661
4662 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4663 if (err)
4664 return err;
4665
4666 if (off + size > *max_access)
4667 *max_access = off + size;
4668
4669 return 0;
4670 }
4671
4672 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)4673 static void zext_32_to_64(struct bpf_reg_state *reg)
4674 {
4675 reg->var_off = tnum_subreg(reg->var_off);
4676 __reg_assign_32_into_64(reg);
4677 }
4678
4679 /* truncate register to smaller size (in bytes)
4680 * must be called with size < BPF_REG_SIZE
4681 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)4682 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4683 {
4684 u64 mask;
4685
4686 /* clear high bits in bit representation */
4687 reg->var_off = tnum_cast(reg->var_off, size);
4688
4689 /* fix arithmetic bounds */
4690 mask = ((u64)1 << (size * 8)) - 1;
4691 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4692 reg->umin_value &= mask;
4693 reg->umax_value &= mask;
4694 } else {
4695 reg->umin_value = 0;
4696 reg->umax_value = mask;
4697 }
4698 reg->smin_value = reg->umin_value;
4699 reg->smax_value = reg->umax_value;
4700
4701 /* If size is smaller than 32bit register the 32bit register
4702 * values are also truncated so we push 64-bit bounds into
4703 * 32-bit bounds. Above were truncated < 32-bits already.
4704 */
4705 if (size >= 4)
4706 return;
4707 __reg_combine_64_into_32(reg);
4708 }
4709
bpf_map_is_rdonly(const struct bpf_map * map)4710 static bool bpf_map_is_rdonly(const struct bpf_map *map)
4711 {
4712 /* A map is considered read-only if the following condition are true:
4713 *
4714 * 1) BPF program side cannot change any of the map content. The
4715 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4716 * and was set at map creation time.
4717 * 2) The map value(s) have been initialized from user space by a
4718 * loader and then "frozen", such that no new map update/delete
4719 * operations from syscall side are possible for the rest of
4720 * the map's lifetime from that point onwards.
4721 * 3) Any parallel/pending map update/delete operations from syscall
4722 * side have been completed. Only after that point, it's safe to
4723 * assume that map value(s) are immutable.
4724 */
4725 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4726 READ_ONCE(map->frozen) &&
4727 !bpf_map_write_active(map);
4728 }
4729
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)4730 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4731 {
4732 void *ptr;
4733 u64 addr;
4734 int err;
4735
4736 err = map->ops->map_direct_value_addr(map, &addr, off);
4737 if (err)
4738 return err;
4739 ptr = (void *)(long)addr + off;
4740
4741 switch (size) {
4742 case sizeof(u8):
4743 *val = (u64)*(u8 *)ptr;
4744 break;
4745 case sizeof(u16):
4746 *val = (u64)*(u16 *)ptr;
4747 break;
4748 case sizeof(u32):
4749 *val = (u64)*(u32 *)ptr;
4750 break;
4751 case sizeof(u64):
4752 *val = *(u64 *)ptr;
4753 break;
4754 default:
4755 return -EINVAL;
4756 }
4757 return 0;
4758 }
4759
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)4760 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4761 struct bpf_reg_state *regs,
4762 int regno, int off, int size,
4763 enum bpf_access_type atype,
4764 int value_regno)
4765 {
4766 struct bpf_reg_state *reg = regs + regno;
4767 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4768 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
4769 enum bpf_type_flag flag = 0;
4770 u32 btf_id;
4771 int ret;
4772
4773 if (off < 0) {
4774 verbose(env,
4775 "R%d is ptr_%s invalid negative access: off=%d\n",
4776 regno, tname, off);
4777 return -EACCES;
4778 }
4779 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4780 char tn_buf[48];
4781
4782 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4783 verbose(env,
4784 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4785 regno, tname, off, tn_buf);
4786 return -EACCES;
4787 }
4788
4789 if (reg->type & MEM_USER) {
4790 verbose(env,
4791 "R%d is ptr_%s access user memory: off=%d\n",
4792 regno, tname, off);
4793 return -EACCES;
4794 }
4795
4796 if (reg->type & MEM_PERCPU) {
4797 verbose(env,
4798 "R%d is ptr_%s access percpu memory: off=%d\n",
4799 regno, tname, off);
4800 return -EACCES;
4801 }
4802
4803 if (env->ops->btf_struct_access) {
4804 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4805 off, size, atype, &btf_id, &flag);
4806 } else {
4807 if (atype != BPF_READ) {
4808 verbose(env, "only read is supported\n");
4809 return -EACCES;
4810 }
4811
4812 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4813 atype, &btf_id, &flag);
4814 }
4815
4816 if (ret < 0)
4817 return ret;
4818
4819 /* If this is an untrusted pointer, all pointers formed by walking it
4820 * also inherit the untrusted flag.
4821 */
4822 if (type_flag(reg->type) & PTR_UNTRUSTED)
4823 flag |= PTR_UNTRUSTED;
4824
4825 if (atype == BPF_READ && value_regno >= 0)
4826 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
4827
4828 return 0;
4829 }
4830
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)4831 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4832 struct bpf_reg_state *regs,
4833 int regno, int off, int size,
4834 enum bpf_access_type atype,
4835 int value_regno)
4836 {
4837 struct bpf_reg_state *reg = regs + regno;
4838 struct bpf_map *map = reg->map_ptr;
4839 enum bpf_type_flag flag = 0;
4840 const struct btf_type *t;
4841 const char *tname;
4842 u32 btf_id;
4843 int ret;
4844
4845 if (!btf_vmlinux) {
4846 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4847 return -ENOTSUPP;
4848 }
4849
4850 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4851 verbose(env, "map_ptr access not supported for map type %d\n",
4852 map->map_type);
4853 return -ENOTSUPP;
4854 }
4855
4856 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4857 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4858
4859 if (!env->allow_ptr_to_map_access) {
4860 verbose(env,
4861 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4862 tname);
4863 return -EPERM;
4864 }
4865
4866 if (off < 0) {
4867 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4868 regno, tname, off);
4869 return -EACCES;
4870 }
4871
4872 if (atype != BPF_READ) {
4873 verbose(env, "only read from %s is supported\n", tname);
4874 return -EACCES;
4875 }
4876
4877 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id, &flag);
4878 if (ret < 0)
4879 return ret;
4880
4881 if (value_regno >= 0)
4882 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
4883
4884 return 0;
4885 }
4886
4887 /* Check that the stack access at the given offset is within bounds. The
4888 * maximum valid offset is -1.
4889 *
4890 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4891 * -state->allocated_stack for reads.
4892 */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)4893 static int check_stack_slot_within_bounds(int off,
4894 struct bpf_func_state *state,
4895 enum bpf_access_type t)
4896 {
4897 int min_valid_off;
4898
4899 if (t == BPF_WRITE)
4900 min_valid_off = -MAX_BPF_STACK;
4901 else
4902 min_valid_off = -state->allocated_stack;
4903
4904 if (off < min_valid_off || off > -1)
4905 return -EACCES;
4906 return 0;
4907 }
4908
4909 /* Check that the stack access at 'regno + off' falls within the maximum stack
4910 * bounds.
4911 *
4912 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4913 */
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)4914 static int check_stack_access_within_bounds(
4915 struct bpf_verifier_env *env,
4916 int regno, int off, int access_size,
4917 enum bpf_access_src src, enum bpf_access_type type)
4918 {
4919 struct bpf_reg_state *regs = cur_regs(env);
4920 struct bpf_reg_state *reg = regs + regno;
4921 struct bpf_func_state *state = func(env, reg);
4922 int min_off, max_off;
4923 int err;
4924 char *err_extra;
4925
4926 if (src == ACCESS_HELPER)
4927 /* We don't know if helpers are reading or writing (or both). */
4928 err_extra = " indirect access to";
4929 else if (type == BPF_READ)
4930 err_extra = " read from";
4931 else
4932 err_extra = " write to";
4933
4934 if (tnum_is_const(reg->var_off)) {
4935 min_off = reg->var_off.value + off;
4936 max_off = min_off + access_size;
4937 } else {
4938 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4939 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4940 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4941 err_extra, regno);
4942 return -EACCES;
4943 }
4944 min_off = reg->smin_value + off;
4945 max_off = reg->smax_value + off + access_size;
4946 }
4947
4948 err = check_stack_slot_within_bounds(min_off, state, type);
4949 if (!err && max_off > 0)
4950 err = -EINVAL; /* out of stack access into non-negative offsets */
4951
4952 if (err) {
4953 if (tnum_is_const(reg->var_off)) {
4954 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4955 err_extra, regno, off, access_size);
4956 } else {
4957 char tn_buf[48];
4958
4959 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4960 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4961 err_extra, regno, tn_buf, access_size);
4962 }
4963 }
4964 return err;
4965 }
4966
4967 /* check whether memory at (regno + off) is accessible for t = (read | write)
4968 * if t==write, value_regno is a register which value is stored into memory
4969 * if t==read, value_regno is a register which will receive the value from memory
4970 * if t==write && value_regno==-1, some unknown value is stored into memory
4971 * if t==read && value_regno==-1, don't care what we read from memory
4972 */
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)4973 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4974 int off, int bpf_size, enum bpf_access_type t,
4975 int value_regno, bool strict_alignment_once)
4976 {
4977 struct bpf_reg_state *regs = cur_regs(env);
4978 struct bpf_reg_state *reg = regs + regno;
4979 struct bpf_func_state *state;
4980 int size, err = 0;
4981
4982 size = bpf_size_to_bytes(bpf_size);
4983 if (size < 0)
4984 return size;
4985
4986 /* alignment checks will add in reg->off themselves */
4987 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4988 if (err)
4989 return err;
4990
4991 /* for access checks, reg->off is just part of off */
4992 off += reg->off;
4993
4994 if (reg->type == PTR_TO_MAP_KEY) {
4995 if (t == BPF_WRITE) {
4996 verbose(env, "write to change key R%d not allowed\n", regno);
4997 return -EACCES;
4998 }
4999
5000 err = check_mem_region_access(env, regno, off, size,
5001 reg->map_ptr->key_size, false);
5002 if (err)
5003 return err;
5004 if (value_regno >= 0)
5005 mark_reg_unknown(env, regs, value_regno);
5006 } else if (reg->type == PTR_TO_MAP_VALUE) {
5007 struct bpf_map_value_off_desc *kptr_off_desc = NULL;
5008
5009 if (t == BPF_WRITE && value_regno >= 0 &&
5010 is_pointer_value(env, value_regno)) {
5011 verbose(env, "R%d leaks addr into map\n", value_regno);
5012 return -EACCES;
5013 }
5014 err = check_map_access_type(env, regno, off, size, t);
5015 if (err)
5016 return err;
5017 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
5018 if (err)
5019 return err;
5020 if (tnum_is_const(reg->var_off))
5021 kptr_off_desc = bpf_map_kptr_off_contains(reg->map_ptr,
5022 off + reg->var_off.value);
5023 if (kptr_off_desc) {
5024 err = check_map_kptr_access(env, regno, value_regno, insn_idx,
5025 kptr_off_desc);
5026 } else if (t == BPF_READ && value_regno >= 0) {
5027 struct bpf_map *map = reg->map_ptr;
5028
5029 /* if map is read-only, track its contents as scalars */
5030 if (tnum_is_const(reg->var_off) &&
5031 bpf_map_is_rdonly(map) &&
5032 map->ops->map_direct_value_addr) {
5033 int map_off = off + reg->var_off.value;
5034 u64 val = 0;
5035
5036 err = bpf_map_direct_read(map, map_off, size,
5037 &val);
5038 if (err)
5039 return err;
5040
5041 regs[value_regno].type = SCALAR_VALUE;
5042 __mark_reg_known(®s[value_regno], val);
5043 } else {
5044 mark_reg_unknown(env, regs, value_regno);
5045 }
5046 }
5047 } else if (base_type(reg->type) == PTR_TO_MEM) {
5048 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5049
5050 if (type_may_be_null(reg->type)) {
5051 verbose(env, "R%d invalid mem access '%s'\n", regno,
5052 reg_type_str(env, reg->type));
5053 return -EACCES;
5054 }
5055
5056 if (t == BPF_WRITE && rdonly_mem) {
5057 verbose(env, "R%d cannot write into %s\n",
5058 regno, reg_type_str(env, reg->type));
5059 return -EACCES;
5060 }
5061
5062 if (t == BPF_WRITE && value_regno >= 0 &&
5063 is_pointer_value(env, value_regno)) {
5064 verbose(env, "R%d leaks addr into mem\n", value_regno);
5065 return -EACCES;
5066 }
5067
5068 err = check_mem_region_access(env, regno, off, size,
5069 reg->mem_size, false);
5070 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
5071 mark_reg_unknown(env, regs, value_regno);
5072 } else if (reg->type == PTR_TO_CTX) {
5073 enum bpf_reg_type reg_type = SCALAR_VALUE;
5074 struct btf *btf = NULL;
5075 u32 btf_id = 0;
5076
5077 if (t == BPF_WRITE && value_regno >= 0 &&
5078 is_pointer_value(env, value_regno)) {
5079 verbose(env, "R%d leaks addr into ctx\n", value_regno);
5080 return -EACCES;
5081 }
5082
5083 err = check_ptr_off_reg(env, reg, regno);
5084 if (err < 0)
5085 return err;
5086
5087 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf,
5088 &btf_id);
5089 if (err)
5090 verbose_linfo(env, insn_idx, "; ");
5091 if (!err && t == BPF_READ && value_regno >= 0) {
5092 /* ctx access returns either a scalar, or a
5093 * PTR_TO_PACKET[_META,_END]. In the latter
5094 * case, we know the offset is zero.
5095 */
5096 if (reg_type == SCALAR_VALUE) {
5097 mark_reg_unknown(env, regs, value_regno);
5098 } else {
5099 mark_reg_known_zero(env, regs,
5100 value_regno);
5101 if (type_may_be_null(reg_type))
5102 regs[value_regno].id = ++env->id_gen;
5103 /* A load of ctx field could have different
5104 * actual load size with the one encoded in the
5105 * insn. When the dst is PTR, it is for sure not
5106 * a sub-register.
5107 */
5108 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
5109 if (base_type(reg_type) == PTR_TO_BTF_ID) {
5110 regs[value_regno].btf = btf;
5111 regs[value_regno].btf_id = btf_id;
5112 }
5113 }
5114 regs[value_regno].type = reg_type;
5115 }
5116
5117 } else if (reg->type == PTR_TO_STACK) {
5118 /* Basic bounds checks. */
5119 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
5120 if (err)
5121 return err;
5122
5123 state = func(env, reg);
5124 err = update_stack_depth(env, state, off);
5125 if (err)
5126 return err;
5127
5128 if (t == BPF_READ)
5129 err = check_stack_read(env, regno, off, size,
5130 value_regno);
5131 else
5132 err = check_stack_write(env, regno, off, size,
5133 value_regno, insn_idx);
5134 } else if (reg_is_pkt_pointer(reg)) {
5135 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
5136 verbose(env, "cannot write into packet\n");
5137 return -EACCES;
5138 }
5139 if (t == BPF_WRITE && value_regno >= 0 &&
5140 is_pointer_value(env, value_regno)) {
5141 verbose(env, "R%d leaks addr into packet\n",
5142 value_regno);
5143 return -EACCES;
5144 }
5145 err = check_packet_access(env, regno, off, size, false);
5146 if (!err && t == BPF_READ && value_regno >= 0)
5147 mark_reg_unknown(env, regs, value_regno);
5148 } else if (reg->type == PTR_TO_FLOW_KEYS) {
5149 if (t == BPF_WRITE && value_regno >= 0 &&
5150 is_pointer_value(env, value_regno)) {
5151 verbose(env, "R%d leaks addr into flow keys\n",
5152 value_regno);
5153 return -EACCES;
5154 }
5155
5156 err = check_flow_keys_access(env, off, size);
5157 if (!err && t == BPF_READ && value_regno >= 0)
5158 mark_reg_unknown(env, regs, value_regno);
5159 } else if (type_is_sk_pointer(reg->type)) {
5160 if (t == BPF_WRITE) {
5161 verbose(env, "R%d cannot write into %s\n",
5162 regno, reg_type_str(env, reg->type));
5163 return -EACCES;
5164 }
5165 err = check_sock_access(env, insn_idx, regno, off, size, t);
5166 if (!err && value_regno >= 0)
5167 mark_reg_unknown(env, regs, value_regno);
5168 } else if (reg->type == PTR_TO_TP_BUFFER) {
5169 err = check_tp_buffer_access(env, reg, regno, off, size);
5170 if (!err && t == BPF_READ && value_regno >= 0)
5171 mark_reg_unknown(env, regs, value_regno);
5172 } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
5173 !type_may_be_null(reg->type)) {
5174 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
5175 value_regno);
5176 } else if (reg->type == CONST_PTR_TO_MAP) {
5177 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
5178 value_regno);
5179 } else if (base_type(reg->type) == PTR_TO_BUF) {
5180 bool rdonly_mem = type_is_rdonly_mem(reg->type);
5181 u32 *max_access;
5182
5183 if (rdonly_mem) {
5184 if (t == BPF_WRITE) {
5185 verbose(env, "R%d cannot write into %s\n",
5186 regno, reg_type_str(env, reg->type));
5187 return -EACCES;
5188 }
5189 max_access = &env->prog->aux->max_rdonly_access;
5190 } else {
5191 max_access = &env->prog->aux->max_rdwr_access;
5192 }
5193
5194 err = check_buffer_access(env, reg, regno, off, size, false,
5195 max_access);
5196
5197 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
5198 mark_reg_unknown(env, regs, value_regno);
5199 } else {
5200 verbose(env, "R%d invalid mem access '%s'\n", regno,
5201 reg_type_str(env, reg->type));
5202 return -EACCES;
5203 }
5204
5205 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
5206 regs[value_regno].type == SCALAR_VALUE) {
5207 /* b/h/w load zero-extends, mark upper bits as known 0 */
5208 coerce_reg_to_size(®s[value_regno], size);
5209 }
5210 return err;
5211 }
5212
check_atomic(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)5213 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
5214 {
5215 int load_reg;
5216 int err;
5217
5218 switch (insn->imm) {
5219 case BPF_ADD:
5220 case BPF_ADD | BPF_FETCH:
5221 case BPF_AND:
5222 case BPF_AND | BPF_FETCH:
5223 case BPF_OR:
5224 case BPF_OR | BPF_FETCH:
5225 case BPF_XOR:
5226 case BPF_XOR | BPF_FETCH:
5227 case BPF_XCHG:
5228 case BPF_CMPXCHG:
5229 break;
5230 default:
5231 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
5232 return -EINVAL;
5233 }
5234
5235 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
5236 verbose(env, "invalid atomic operand size\n");
5237 return -EINVAL;
5238 }
5239
5240 /* check src1 operand */
5241 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5242 if (err)
5243 return err;
5244
5245 /* check src2 operand */
5246 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5247 if (err)
5248 return err;
5249
5250 if (insn->imm == BPF_CMPXCHG) {
5251 /* Check comparison of R0 with memory location */
5252 const u32 aux_reg = BPF_REG_0;
5253
5254 err = check_reg_arg(env, aux_reg, SRC_OP);
5255 if (err)
5256 return err;
5257
5258 if (is_pointer_value(env, aux_reg)) {
5259 verbose(env, "R%d leaks addr into mem\n", aux_reg);
5260 return -EACCES;
5261 }
5262 }
5263
5264 if (is_pointer_value(env, insn->src_reg)) {
5265 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
5266 return -EACCES;
5267 }
5268
5269 if (is_ctx_reg(env, insn->dst_reg) ||
5270 is_pkt_reg(env, insn->dst_reg) ||
5271 is_flow_key_reg(env, insn->dst_reg) ||
5272 is_sk_reg(env, insn->dst_reg)) {
5273 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
5274 insn->dst_reg,
5275 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
5276 return -EACCES;
5277 }
5278
5279 if (insn->imm & BPF_FETCH) {
5280 if (insn->imm == BPF_CMPXCHG)
5281 load_reg = BPF_REG_0;
5282 else
5283 load_reg = insn->src_reg;
5284
5285 /* check and record load of old value */
5286 err = check_reg_arg(env, load_reg, DST_OP);
5287 if (err)
5288 return err;
5289 } else {
5290 /* This instruction accesses a memory location but doesn't
5291 * actually load it into a register.
5292 */
5293 load_reg = -1;
5294 }
5295
5296 /* Check whether we can read the memory, with second call for fetch
5297 * case to simulate the register fill.
5298 */
5299 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5300 BPF_SIZE(insn->code), BPF_READ, -1, true);
5301 if (!err && load_reg >= 0)
5302 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5303 BPF_SIZE(insn->code), BPF_READ, load_reg,
5304 true);
5305 if (err)
5306 return err;
5307
5308 /* Check whether we can write into the same memory. */
5309 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
5310 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
5311 if (err)
5312 return err;
5313
5314 return 0;
5315 }
5316
5317 /* When register 'regno' is used to read the stack (either directly or through
5318 * a helper function) make sure that it's within stack boundary and, depending
5319 * on the access type, that all elements of the stack are initialized.
5320 *
5321 * 'off' includes 'regno->off', but not its dynamic part (if any).
5322 *
5323 * All registers that have been spilled on the stack in the slots within the
5324 * read offsets are marked as read.
5325 */
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)5326 static int check_stack_range_initialized(
5327 struct bpf_verifier_env *env, int regno, int off,
5328 int access_size, bool zero_size_allowed,
5329 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
5330 {
5331 struct bpf_reg_state *reg = reg_state(env, regno);
5332 struct bpf_func_state *state = func(env, reg);
5333 int err, min_off, max_off, i, j, slot, spi;
5334 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
5335 enum bpf_access_type bounds_check_type;
5336 /* Some accesses can write anything into the stack, others are
5337 * read-only.
5338 */
5339 bool clobber = false;
5340
5341 if (access_size == 0 && !zero_size_allowed) {
5342 verbose(env, "invalid zero-sized read\n");
5343 return -EACCES;
5344 }
5345
5346 if (type == ACCESS_HELPER) {
5347 /* The bounds checks for writes are more permissive than for
5348 * reads. However, if raw_mode is not set, we'll do extra
5349 * checks below.
5350 */
5351 bounds_check_type = BPF_WRITE;
5352 clobber = true;
5353 } else {
5354 bounds_check_type = BPF_READ;
5355 }
5356 err = check_stack_access_within_bounds(env, regno, off, access_size,
5357 type, bounds_check_type);
5358 if (err)
5359 return err;
5360
5361
5362 if (tnum_is_const(reg->var_off)) {
5363 min_off = max_off = reg->var_off.value + off;
5364 } else {
5365 /* Variable offset is prohibited for unprivileged mode for
5366 * simplicity since it requires corresponding support in
5367 * Spectre masking for stack ALU.
5368 * See also retrieve_ptr_limit().
5369 */
5370 if (!env->bypass_spec_v1) {
5371 char tn_buf[48];
5372
5373 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5374 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
5375 regno, err_extra, tn_buf);
5376 return -EACCES;
5377 }
5378 /* Only initialized buffer on stack is allowed to be accessed
5379 * with variable offset. With uninitialized buffer it's hard to
5380 * guarantee that whole memory is marked as initialized on
5381 * helper return since specific bounds are unknown what may
5382 * cause uninitialized stack leaking.
5383 */
5384 if (meta && meta->raw_mode)
5385 meta = NULL;
5386
5387 min_off = reg->smin_value + off;
5388 max_off = reg->smax_value + off;
5389 }
5390
5391 if (meta && meta->raw_mode) {
5392 meta->access_size = access_size;
5393 meta->regno = regno;
5394 return 0;
5395 }
5396
5397 for (i = min_off; i < max_off + access_size; i++) {
5398 u8 *stype;
5399
5400 slot = -i - 1;
5401 spi = slot / BPF_REG_SIZE;
5402 if (state->allocated_stack <= slot)
5403 goto err;
5404 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
5405 if (*stype == STACK_MISC)
5406 goto mark;
5407 if (*stype == STACK_ZERO) {
5408 if (clobber) {
5409 /* helper can write anything into the stack */
5410 *stype = STACK_MISC;
5411 }
5412 goto mark;
5413 }
5414
5415 if (is_spilled_reg(&state->stack[spi]) &&
5416 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
5417 env->allow_ptr_leaks)) {
5418 if (clobber) {
5419 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
5420 for (j = 0; j < BPF_REG_SIZE; j++)
5421 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
5422 }
5423 goto mark;
5424 }
5425
5426 err:
5427 if (tnum_is_const(reg->var_off)) {
5428 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
5429 err_extra, regno, min_off, i - min_off, access_size);
5430 } else {
5431 char tn_buf[48];
5432
5433 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5434 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
5435 err_extra, regno, tn_buf, i - min_off, access_size);
5436 }
5437 return -EACCES;
5438 mark:
5439 /* reading any byte out of 8-byte 'spill_slot' will cause
5440 * the whole slot to be marked as 'read'
5441 */
5442 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5443 state->stack[spi].spilled_ptr.parent,
5444 REG_LIVE_READ64);
5445 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
5446 * be sure that whether stack slot is written to or not. Hence,
5447 * we must still conservatively propagate reads upwards even if
5448 * helper may write to the entire memory range.
5449 */
5450 }
5451 return update_stack_depth(env, state, min_off);
5452 }
5453
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)5454 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
5455 int access_size, bool zero_size_allowed,
5456 struct bpf_call_arg_meta *meta)
5457 {
5458 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5459 u32 *max_access;
5460
5461 switch (base_type(reg->type)) {
5462 case PTR_TO_PACKET:
5463 case PTR_TO_PACKET_META:
5464 return check_packet_access(env, regno, reg->off, access_size,
5465 zero_size_allowed);
5466 case PTR_TO_MAP_KEY:
5467 if (meta && meta->raw_mode) {
5468 verbose(env, "R%d cannot write into %s\n", regno,
5469 reg_type_str(env, reg->type));
5470 return -EACCES;
5471 }
5472 return check_mem_region_access(env, regno, reg->off, access_size,
5473 reg->map_ptr->key_size, false);
5474 case PTR_TO_MAP_VALUE:
5475 if (check_map_access_type(env, regno, reg->off, access_size,
5476 meta && meta->raw_mode ? BPF_WRITE :
5477 BPF_READ))
5478 return -EACCES;
5479 return check_map_access(env, regno, reg->off, access_size,
5480 zero_size_allowed, ACCESS_HELPER);
5481 case PTR_TO_MEM:
5482 if (type_is_rdonly_mem(reg->type)) {
5483 if (meta && meta->raw_mode) {
5484 verbose(env, "R%d cannot write into %s\n", regno,
5485 reg_type_str(env, reg->type));
5486 return -EACCES;
5487 }
5488 }
5489 return check_mem_region_access(env, regno, reg->off,
5490 access_size, reg->mem_size,
5491 zero_size_allowed);
5492 case PTR_TO_BUF:
5493 if (type_is_rdonly_mem(reg->type)) {
5494 if (meta && meta->raw_mode) {
5495 verbose(env, "R%d cannot write into %s\n", regno,
5496 reg_type_str(env, reg->type));
5497 return -EACCES;
5498 }
5499
5500 max_access = &env->prog->aux->max_rdonly_access;
5501 } else {
5502 max_access = &env->prog->aux->max_rdwr_access;
5503 }
5504 return check_buffer_access(env, reg, regno, reg->off,
5505 access_size, zero_size_allowed,
5506 max_access);
5507 case PTR_TO_STACK:
5508 return check_stack_range_initialized(
5509 env,
5510 regno, reg->off, access_size,
5511 zero_size_allowed, ACCESS_HELPER, meta);
5512 case PTR_TO_CTX:
5513 /* in case the function doesn't know how to access the context,
5514 * (because we are in a program of type SYSCALL for example), we
5515 * can not statically check its size.
5516 * Dynamically check it now.
5517 */
5518 if (!env->ops->convert_ctx_access) {
5519 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
5520 int offset = access_size - 1;
5521
5522 /* Allow zero-byte read from PTR_TO_CTX */
5523 if (access_size == 0)
5524 return zero_size_allowed ? 0 : -EACCES;
5525
5526 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
5527 atype, -1, false);
5528 }
5529
5530 fallthrough;
5531 default: /* scalar_value or invalid ptr */
5532 /* Allow zero-byte read from NULL, regardless of pointer type */
5533 if (zero_size_allowed && access_size == 0 &&
5534 register_is_null(reg))
5535 return 0;
5536
5537 verbose(env, "R%d type=%s ", regno,
5538 reg_type_str(env, reg->type));
5539 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
5540 return -EACCES;
5541 }
5542 }
5543
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)5544 static int check_mem_size_reg(struct bpf_verifier_env *env,
5545 struct bpf_reg_state *reg, u32 regno,
5546 bool zero_size_allowed,
5547 struct bpf_call_arg_meta *meta)
5548 {
5549 int err;
5550
5551 /* This is used to refine r0 return value bounds for helpers
5552 * that enforce this value as an upper bound on return values.
5553 * See do_refine_retval_range() for helpers that can refine
5554 * the return value. C type of helper is u32 so we pull register
5555 * bound from umax_value however, if negative verifier errors
5556 * out. Only upper bounds can be learned because retval is an
5557 * int type and negative retvals are allowed.
5558 */
5559 meta->msize_max_value = reg->umax_value;
5560
5561 /* The register is SCALAR_VALUE; the access check
5562 * happens using its boundaries.
5563 */
5564 if (!tnum_is_const(reg->var_off))
5565 /* For unprivileged variable accesses, disable raw
5566 * mode so that the program is required to
5567 * initialize all the memory that the helper could
5568 * just partially fill up.
5569 */
5570 meta = NULL;
5571
5572 if (reg->smin_value < 0) {
5573 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5574 regno);
5575 return -EACCES;
5576 }
5577
5578 if (reg->umin_value == 0) {
5579 err = check_helper_mem_access(env, regno - 1, 0,
5580 zero_size_allowed,
5581 meta);
5582 if (err)
5583 return err;
5584 }
5585
5586 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5587 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5588 regno);
5589 return -EACCES;
5590 }
5591 err = check_helper_mem_access(env, regno - 1,
5592 reg->umax_value,
5593 zero_size_allowed, meta);
5594 if (!err)
5595 err = mark_chain_precision(env, regno);
5596 return err;
5597 }
5598
check_mem_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno,u32 mem_size)5599 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5600 u32 regno, u32 mem_size)
5601 {
5602 bool may_be_null = type_may_be_null(reg->type);
5603 struct bpf_reg_state saved_reg;
5604 struct bpf_call_arg_meta meta;
5605 int err;
5606
5607 if (register_is_null(reg))
5608 return 0;
5609
5610 memset(&meta, 0, sizeof(meta));
5611 /* Assuming that the register contains a value check if the memory
5612 * access is safe. Temporarily save and restore the register's state as
5613 * the conversion shouldn't be visible to a caller.
5614 */
5615 if (may_be_null) {
5616 saved_reg = *reg;
5617 mark_ptr_not_null_reg(reg);
5618 }
5619
5620 err = check_helper_mem_access(env, regno, mem_size, true, &meta);
5621 /* Check access for BPF_WRITE */
5622 meta.raw_mode = true;
5623 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
5624
5625 if (may_be_null)
5626 *reg = saved_reg;
5627
5628 return err;
5629 }
5630
check_kfunc_mem_size_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,u32 regno)5631 int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
5632 u32 regno)
5633 {
5634 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
5635 bool may_be_null = type_may_be_null(mem_reg->type);
5636 struct bpf_reg_state saved_reg;
5637 struct bpf_call_arg_meta meta;
5638 int err;
5639
5640 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
5641
5642 memset(&meta, 0, sizeof(meta));
5643
5644 if (may_be_null) {
5645 saved_reg = *mem_reg;
5646 mark_ptr_not_null_reg(mem_reg);
5647 }
5648
5649 err = check_mem_size_reg(env, reg, regno, true, &meta);
5650 /* Check access for BPF_WRITE */
5651 meta.raw_mode = true;
5652 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
5653
5654 if (may_be_null)
5655 *mem_reg = saved_reg;
5656 return err;
5657 }
5658
5659 /* Implementation details:
5660 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
5661 * Two bpf_map_lookups (even with the same key) will have different reg->id.
5662 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
5663 * value_or_null->value transition, since the verifier only cares about
5664 * the range of access to valid map value pointer and doesn't care about actual
5665 * address of the map element.
5666 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
5667 * reg->id > 0 after value_or_null->value transition. By doing so
5668 * two bpf_map_lookups will be considered two different pointers that
5669 * point to different bpf_spin_locks.
5670 * The verifier allows taking only one bpf_spin_lock at a time to avoid
5671 * dead-locks.
5672 * Since only one bpf_spin_lock is allowed the checks are simpler than
5673 * reg_is_refcounted() logic. The verifier needs to remember only
5674 * one spin_lock instead of array of acquired_refs.
5675 * cur_state->active_spin_lock remembers which map value element got locked
5676 * and clears it after bpf_spin_unlock.
5677 */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)5678 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
5679 bool is_lock)
5680 {
5681 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5682 struct bpf_verifier_state *cur = env->cur_state;
5683 bool is_const = tnum_is_const(reg->var_off);
5684 struct bpf_map *map = reg->map_ptr;
5685 u64 val = reg->var_off.value;
5686
5687 if (!is_const) {
5688 verbose(env,
5689 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
5690 regno);
5691 return -EINVAL;
5692 }
5693 if (!map->btf) {
5694 verbose(env,
5695 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
5696 map->name);
5697 return -EINVAL;
5698 }
5699 if (!map_value_has_spin_lock(map)) {
5700 if (map->spin_lock_off == -E2BIG)
5701 verbose(env,
5702 "map '%s' has more than one 'struct bpf_spin_lock'\n",
5703 map->name);
5704 else if (map->spin_lock_off == -ENOENT)
5705 verbose(env,
5706 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
5707 map->name);
5708 else
5709 verbose(env,
5710 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
5711 map->name);
5712 return -EINVAL;
5713 }
5714 if (map->spin_lock_off != val + reg->off) {
5715 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
5716 val + reg->off);
5717 return -EINVAL;
5718 }
5719 if (is_lock) {
5720 if (cur->active_spin_lock) {
5721 verbose(env,
5722 "Locking two bpf_spin_locks are not allowed\n");
5723 return -EINVAL;
5724 }
5725 cur->active_spin_lock = reg->id;
5726 } else {
5727 if (!cur->active_spin_lock) {
5728 verbose(env, "bpf_spin_unlock without taking a lock\n");
5729 return -EINVAL;
5730 }
5731 if (cur->active_spin_lock != reg->id) {
5732 verbose(env, "bpf_spin_unlock of different lock\n");
5733 return -EINVAL;
5734 }
5735 cur->active_spin_lock = 0;
5736 }
5737 return 0;
5738 }
5739
process_timer_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)5740 static int process_timer_func(struct bpf_verifier_env *env, int regno,
5741 struct bpf_call_arg_meta *meta)
5742 {
5743 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5744 bool is_const = tnum_is_const(reg->var_off);
5745 struct bpf_map *map = reg->map_ptr;
5746 u64 val = reg->var_off.value;
5747
5748 if (!is_const) {
5749 verbose(env,
5750 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
5751 regno);
5752 return -EINVAL;
5753 }
5754 if (!map->btf) {
5755 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
5756 map->name);
5757 return -EINVAL;
5758 }
5759 if (!map_value_has_timer(map)) {
5760 if (map->timer_off == -E2BIG)
5761 verbose(env,
5762 "map '%s' has more than one 'struct bpf_timer'\n",
5763 map->name);
5764 else if (map->timer_off == -ENOENT)
5765 verbose(env,
5766 "map '%s' doesn't have 'struct bpf_timer'\n",
5767 map->name);
5768 else
5769 verbose(env,
5770 "map '%s' is not a struct type or bpf_timer is mangled\n",
5771 map->name);
5772 return -EINVAL;
5773 }
5774 if (map->timer_off != val + reg->off) {
5775 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5776 val + reg->off, map->timer_off);
5777 return -EINVAL;
5778 }
5779 if (meta->map_ptr) {
5780 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5781 return -EFAULT;
5782 }
5783 meta->map_uid = reg->map_uid;
5784 meta->map_ptr = map;
5785 return 0;
5786 }
5787
process_kptr_func(struct bpf_verifier_env * env,int regno,struct bpf_call_arg_meta * meta)5788 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
5789 struct bpf_call_arg_meta *meta)
5790 {
5791 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
5792 struct bpf_map_value_off_desc *off_desc;
5793 struct bpf_map *map_ptr = reg->map_ptr;
5794 u32 kptr_off;
5795 int ret;
5796
5797 if (!tnum_is_const(reg->var_off)) {
5798 verbose(env,
5799 "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
5800 regno);
5801 return -EINVAL;
5802 }
5803 if (!map_ptr->btf) {
5804 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
5805 map_ptr->name);
5806 return -EINVAL;
5807 }
5808 if (!map_value_has_kptrs(map_ptr)) {
5809 ret = PTR_ERR_OR_ZERO(map_ptr->kptr_off_tab);
5810 if (ret == -E2BIG)
5811 verbose(env, "map '%s' has more than %d kptr\n", map_ptr->name,
5812 BPF_MAP_VALUE_OFF_MAX);
5813 else if (ret == -EEXIST)
5814 verbose(env, "map '%s' has repeating kptr BTF tags\n", map_ptr->name);
5815 else
5816 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
5817 return -EINVAL;
5818 }
5819
5820 meta->map_ptr = map_ptr;
5821 kptr_off = reg->off + reg->var_off.value;
5822 off_desc = bpf_map_kptr_off_contains(map_ptr, kptr_off);
5823 if (!off_desc) {
5824 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
5825 return -EACCES;
5826 }
5827 if (off_desc->type != BPF_KPTR_REF) {
5828 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
5829 return -EACCES;
5830 }
5831 meta->kptr_off_desc = off_desc;
5832 return 0;
5833 }
5834
arg_type_is_mem_size(enum bpf_arg_type type)5835 static bool arg_type_is_mem_size(enum bpf_arg_type type)
5836 {
5837 return type == ARG_CONST_SIZE ||
5838 type == ARG_CONST_SIZE_OR_ZERO;
5839 }
5840
arg_type_is_release(enum bpf_arg_type type)5841 static bool arg_type_is_release(enum bpf_arg_type type)
5842 {
5843 return type & OBJ_RELEASE;
5844 }
5845
arg_type_is_dynptr(enum bpf_arg_type type)5846 static bool arg_type_is_dynptr(enum bpf_arg_type type)
5847 {
5848 return base_type(type) == ARG_PTR_TO_DYNPTR;
5849 }
5850
int_ptr_type_to_size(enum bpf_arg_type type)5851 static int int_ptr_type_to_size(enum bpf_arg_type type)
5852 {
5853 if (type == ARG_PTR_TO_INT)
5854 return sizeof(u32);
5855 else if (type == ARG_PTR_TO_LONG)
5856 return sizeof(u64);
5857
5858 return -EINVAL;
5859 }
5860
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)5861 static int resolve_map_arg_type(struct bpf_verifier_env *env,
5862 const struct bpf_call_arg_meta *meta,
5863 enum bpf_arg_type *arg_type)
5864 {
5865 if (!meta->map_ptr) {
5866 /* kernel subsystem misconfigured verifier */
5867 verbose(env, "invalid map_ptr to access map->type\n");
5868 return -EACCES;
5869 }
5870
5871 switch (meta->map_ptr->map_type) {
5872 case BPF_MAP_TYPE_SOCKMAP:
5873 case BPF_MAP_TYPE_SOCKHASH:
5874 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
5875 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
5876 } else {
5877 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5878 return -EINVAL;
5879 }
5880 break;
5881 case BPF_MAP_TYPE_BLOOM_FILTER:
5882 if (meta->func_id == BPF_FUNC_map_peek_elem)
5883 *arg_type = ARG_PTR_TO_MAP_VALUE;
5884 break;
5885 default:
5886 break;
5887 }
5888 return 0;
5889 }
5890
5891 struct bpf_reg_types {
5892 const enum bpf_reg_type types[10];
5893 u32 *btf_id;
5894 };
5895
5896 static const struct bpf_reg_types map_key_value_types = {
5897 .types = {
5898 PTR_TO_STACK,
5899 PTR_TO_PACKET,
5900 PTR_TO_PACKET_META,
5901 PTR_TO_MAP_KEY,
5902 PTR_TO_MAP_VALUE,
5903 },
5904 };
5905
5906 static const struct bpf_reg_types sock_types = {
5907 .types = {
5908 PTR_TO_SOCK_COMMON,
5909 PTR_TO_SOCKET,
5910 PTR_TO_TCP_SOCK,
5911 PTR_TO_XDP_SOCK,
5912 },
5913 };
5914
5915 #ifdef CONFIG_NET
5916 static const struct bpf_reg_types btf_id_sock_common_types = {
5917 .types = {
5918 PTR_TO_SOCK_COMMON,
5919 PTR_TO_SOCKET,
5920 PTR_TO_TCP_SOCK,
5921 PTR_TO_XDP_SOCK,
5922 PTR_TO_BTF_ID,
5923 },
5924 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5925 };
5926 #endif
5927
5928 static const struct bpf_reg_types mem_types = {
5929 .types = {
5930 PTR_TO_STACK,
5931 PTR_TO_PACKET,
5932 PTR_TO_PACKET_META,
5933 PTR_TO_MAP_KEY,
5934 PTR_TO_MAP_VALUE,
5935 PTR_TO_MEM,
5936 PTR_TO_MEM | MEM_ALLOC,
5937 PTR_TO_BUF,
5938 },
5939 };
5940
5941 static const struct bpf_reg_types int_ptr_types = {
5942 .types = {
5943 PTR_TO_STACK,
5944 PTR_TO_PACKET,
5945 PTR_TO_PACKET_META,
5946 PTR_TO_MAP_KEY,
5947 PTR_TO_MAP_VALUE,
5948 },
5949 };
5950
5951 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5952 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5953 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5954 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM | MEM_ALLOC } };
5955 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5956 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5957 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
5958 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_BTF_ID | MEM_PERCPU } };
5959 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5960 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
5961 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
5962 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
5963 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
5964 static const struct bpf_reg_types dynptr_types = {
5965 .types = {
5966 PTR_TO_STACK,
5967 PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL,
5968 }
5969 };
5970
5971 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
5972 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5973 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5974 [ARG_CONST_SIZE] = &scalar_types,
5975 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5976 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5977 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5978 [ARG_PTR_TO_CTX] = &context_types,
5979 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
5980 #ifdef CONFIG_NET
5981 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
5982 #endif
5983 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5984 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5985 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5986 [ARG_PTR_TO_MEM] = &mem_types,
5987 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5988 [ARG_PTR_TO_INT] = &int_ptr_types,
5989 [ARG_PTR_TO_LONG] = &int_ptr_types,
5990 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
5991 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5992 [ARG_PTR_TO_STACK] = &stack_ptr_types,
5993 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
5994 [ARG_PTR_TO_TIMER] = &timer_types,
5995 [ARG_PTR_TO_KPTR] = &kptr_types,
5996 [ARG_PTR_TO_DYNPTR] = &dynptr_types,
5997 };
5998
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)5999 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
6000 enum bpf_arg_type arg_type,
6001 const u32 *arg_btf_id,
6002 struct bpf_call_arg_meta *meta)
6003 {
6004 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6005 enum bpf_reg_type expected, type = reg->type;
6006 const struct bpf_reg_types *compatible;
6007 int i, j;
6008
6009 compatible = compatible_reg_types[base_type(arg_type)];
6010 if (!compatible) {
6011 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
6012 return -EFAULT;
6013 }
6014
6015 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
6016 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
6017 *
6018 * Same for MAYBE_NULL:
6019 *
6020 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
6021 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
6022 *
6023 * Therefore we fold these flags depending on the arg_type before comparison.
6024 */
6025 if (arg_type & MEM_RDONLY)
6026 type &= ~MEM_RDONLY;
6027 if (arg_type & PTR_MAYBE_NULL)
6028 type &= ~PTR_MAYBE_NULL;
6029
6030 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
6031 expected = compatible->types[i];
6032 if (expected == NOT_INIT)
6033 break;
6034
6035 if (type == expected)
6036 goto found;
6037 }
6038
6039 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
6040 for (j = 0; j + 1 < i; j++)
6041 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
6042 verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
6043 return -EACCES;
6044
6045 found:
6046 if (reg->type == PTR_TO_BTF_ID) {
6047 /* For bpf_sk_release, it needs to match against first member
6048 * 'struct sock_common', hence make an exception for it. This
6049 * allows bpf_sk_release to work for multiple socket types.
6050 */
6051 bool strict_type_match = arg_type_is_release(arg_type) &&
6052 meta->func_id != BPF_FUNC_sk_release;
6053
6054 if (!arg_btf_id) {
6055 if (!compatible->btf_id) {
6056 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
6057 return -EFAULT;
6058 }
6059 arg_btf_id = compatible->btf_id;
6060 }
6061
6062 if (meta->func_id == BPF_FUNC_kptr_xchg) {
6063 if (map_kptr_match_type(env, meta->kptr_off_desc, reg, regno))
6064 return -EACCES;
6065 } else {
6066 if (arg_btf_id == BPF_PTR_POISON) {
6067 verbose(env, "verifier internal error:");
6068 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
6069 regno);
6070 return -EACCES;
6071 }
6072
6073 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
6074 btf_vmlinux, *arg_btf_id,
6075 strict_type_match)) {
6076 verbose(env, "R%d is of type %s but %s is expected\n",
6077 regno, kernel_type_name(reg->btf, reg->btf_id),
6078 kernel_type_name(btf_vmlinux, *arg_btf_id));
6079 return -EACCES;
6080 }
6081 }
6082 }
6083
6084 return 0;
6085 }
6086
check_func_arg_reg_off(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,enum bpf_arg_type arg_type)6087 int check_func_arg_reg_off(struct bpf_verifier_env *env,
6088 const struct bpf_reg_state *reg, int regno,
6089 enum bpf_arg_type arg_type)
6090 {
6091 enum bpf_reg_type type = reg->type;
6092 bool fixed_off_ok = false;
6093
6094 switch ((u32)type) {
6095 /* Pointer types where reg offset is explicitly allowed: */
6096 case PTR_TO_STACK:
6097 if (arg_type_is_dynptr(arg_type) && reg->off % BPF_REG_SIZE) {
6098 verbose(env, "cannot pass in dynptr at an offset\n");
6099 return -EINVAL;
6100 }
6101 fallthrough;
6102 case PTR_TO_PACKET:
6103 case PTR_TO_PACKET_META:
6104 case PTR_TO_MAP_KEY:
6105 case PTR_TO_MAP_VALUE:
6106 case PTR_TO_MEM:
6107 case PTR_TO_MEM | MEM_RDONLY:
6108 case PTR_TO_MEM | MEM_ALLOC:
6109 case PTR_TO_BUF:
6110 case PTR_TO_BUF | MEM_RDONLY:
6111 case SCALAR_VALUE:
6112 /* Some of the argument types nevertheless require a
6113 * zero register offset.
6114 */
6115 if (base_type(arg_type) != ARG_PTR_TO_ALLOC_MEM)
6116 return 0;
6117 break;
6118 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
6119 * fixed offset.
6120 */
6121 case PTR_TO_BTF_ID:
6122 /* When referenced PTR_TO_BTF_ID is passed to release function,
6123 * it's fixed offset must be 0. In the other cases, fixed offset
6124 * can be non-zero.
6125 */
6126 if (arg_type_is_release(arg_type) && reg->off) {
6127 verbose(env, "R%d must have zero offset when passed to release func\n",
6128 regno);
6129 return -EINVAL;
6130 }
6131 /* For arg is release pointer, fixed_off_ok must be false, but
6132 * we already checked and rejected reg->off != 0 above, so set
6133 * to true to allow fixed offset for all other cases.
6134 */
6135 fixed_off_ok = true;
6136 break;
6137 default:
6138 break;
6139 }
6140 return __check_ptr_off_reg(env, reg, regno, fixed_off_ok);
6141 }
6142
stack_slot_get_id(struct bpf_verifier_env * env,struct bpf_reg_state * reg)6143 static u32 stack_slot_get_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
6144 {
6145 struct bpf_func_state *state = func(env, reg);
6146 int spi = get_spi(reg->off);
6147
6148 return state->stack[spi].spilled_ptr.id;
6149 }
6150
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)6151 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
6152 struct bpf_call_arg_meta *meta,
6153 const struct bpf_func_proto *fn)
6154 {
6155 u32 regno = BPF_REG_1 + arg;
6156 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
6157 enum bpf_arg_type arg_type = fn->arg_type[arg];
6158 enum bpf_reg_type type = reg->type;
6159 u32 *arg_btf_id = NULL;
6160 int err = 0;
6161
6162 if (arg_type == ARG_DONTCARE)
6163 return 0;
6164
6165 err = check_reg_arg(env, regno, SRC_OP);
6166 if (err)
6167 return err;
6168
6169 if (arg_type == ARG_ANYTHING) {
6170 if (is_pointer_value(env, regno)) {
6171 verbose(env, "R%d leaks addr into helper function\n",
6172 regno);
6173 return -EACCES;
6174 }
6175 return 0;
6176 }
6177
6178 if (type_is_pkt_pointer(type) &&
6179 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
6180 verbose(env, "helper access to the packet is not allowed\n");
6181 return -EACCES;
6182 }
6183
6184 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
6185 err = resolve_map_arg_type(env, meta, &arg_type);
6186 if (err)
6187 return err;
6188 }
6189
6190 if (register_is_null(reg) && type_may_be_null(arg_type))
6191 /* A NULL register has a SCALAR_VALUE type, so skip
6192 * type checking.
6193 */
6194 goto skip_type_check;
6195
6196 /* arg_btf_id and arg_size are in a union. */
6197 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID)
6198 arg_btf_id = fn->arg_btf_id[arg];
6199
6200 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
6201 if (err)
6202 return err;
6203
6204 err = check_func_arg_reg_off(env, reg, regno, arg_type);
6205 if (err)
6206 return err;
6207
6208 skip_type_check:
6209 if (arg_type_is_release(arg_type)) {
6210 if (arg_type_is_dynptr(arg_type)) {
6211 struct bpf_func_state *state = func(env, reg);
6212 int spi = get_spi(reg->off);
6213
6214 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) ||
6215 !state->stack[spi].spilled_ptr.id) {
6216 verbose(env, "arg %d is an unacquired reference\n", regno);
6217 return -EINVAL;
6218 }
6219 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
6220 verbose(env, "R%d must be referenced when passed to release function\n",
6221 regno);
6222 return -EINVAL;
6223 }
6224 if (meta->release_regno) {
6225 verbose(env, "verifier internal error: more than one release argument\n");
6226 return -EFAULT;
6227 }
6228 meta->release_regno = regno;
6229 }
6230
6231 if (reg->ref_obj_id) {
6232 if (meta->ref_obj_id) {
6233 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
6234 regno, reg->ref_obj_id,
6235 meta->ref_obj_id);
6236 return -EFAULT;
6237 }
6238 meta->ref_obj_id = reg->ref_obj_id;
6239 }
6240
6241 switch (base_type(arg_type)) {
6242 case ARG_CONST_MAP_PTR:
6243 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
6244 if (meta->map_ptr) {
6245 /* Use map_uid (which is unique id of inner map) to reject:
6246 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
6247 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
6248 * if (inner_map1 && inner_map2) {
6249 * timer = bpf_map_lookup_elem(inner_map1);
6250 * if (timer)
6251 * // mismatch would have been allowed
6252 * bpf_timer_init(timer, inner_map2);
6253 * }
6254 *
6255 * Comparing map_ptr is enough to distinguish normal and outer maps.
6256 */
6257 if (meta->map_ptr != reg->map_ptr ||
6258 meta->map_uid != reg->map_uid) {
6259 verbose(env,
6260 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
6261 meta->map_uid, reg->map_uid);
6262 return -EINVAL;
6263 }
6264 }
6265 meta->map_ptr = reg->map_ptr;
6266 meta->map_uid = reg->map_uid;
6267 break;
6268 case ARG_PTR_TO_MAP_KEY:
6269 /* bpf_map_xxx(..., map_ptr, ..., key) call:
6270 * check that [key, key + map->key_size) are within
6271 * stack limits and initialized
6272 */
6273 if (!meta->map_ptr) {
6274 /* in function declaration map_ptr must come before
6275 * map_key, so that it's verified and known before
6276 * we have to check map_key here. Otherwise it means
6277 * that kernel subsystem misconfigured verifier
6278 */
6279 verbose(env, "invalid map_ptr to access map->key\n");
6280 return -EACCES;
6281 }
6282 err = check_helper_mem_access(env, regno,
6283 meta->map_ptr->key_size, false,
6284 NULL);
6285 break;
6286 case ARG_PTR_TO_MAP_VALUE:
6287 if (type_may_be_null(arg_type) && register_is_null(reg))
6288 return 0;
6289
6290 /* bpf_map_xxx(..., map_ptr, ..., value) call:
6291 * check [value, value + map->value_size) validity
6292 */
6293 if (!meta->map_ptr) {
6294 /* kernel subsystem misconfigured verifier */
6295 verbose(env, "invalid map_ptr to access map->value\n");
6296 return -EACCES;
6297 }
6298 meta->raw_mode = arg_type & MEM_UNINIT;
6299 err = check_helper_mem_access(env, regno,
6300 meta->map_ptr->value_size, false,
6301 meta);
6302 break;
6303 case ARG_PTR_TO_PERCPU_BTF_ID:
6304 if (!reg->btf_id) {
6305 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
6306 return -EACCES;
6307 }
6308 meta->ret_btf = reg->btf;
6309 meta->ret_btf_id = reg->btf_id;
6310 break;
6311 case ARG_PTR_TO_SPIN_LOCK:
6312 if (meta->func_id == BPF_FUNC_spin_lock) {
6313 if (process_spin_lock(env, regno, true))
6314 return -EACCES;
6315 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
6316 if (process_spin_lock(env, regno, false))
6317 return -EACCES;
6318 } else {
6319 verbose(env, "verifier internal error\n");
6320 return -EFAULT;
6321 }
6322 break;
6323 case ARG_PTR_TO_TIMER:
6324 if (process_timer_func(env, regno, meta))
6325 return -EACCES;
6326 break;
6327 case ARG_PTR_TO_FUNC:
6328 meta->subprogno = reg->subprogno;
6329 break;
6330 case ARG_PTR_TO_MEM:
6331 /* The access to this pointer is only checked when we hit the
6332 * next is_mem_size argument below.
6333 */
6334 meta->raw_mode = arg_type & MEM_UNINIT;
6335 if (arg_type & MEM_FIXED_SIZE) {
6336 err = check_helper_mem_access(env, regno,
6337 fn->arg_size[arg], false,
6338 meta);
6339 }
6340 break;
6341 case ARG_CONST_SIZE:
6342 err = check_mem_size_reg(env, reg, regno, false, meta);
6343 break;
6344 case ARG_CONST_SIZE_OR_ZERO:
6345 err = check_mem_size_reg(env, reg, regno, true, meta);
6346 break;
6347 case ARG_PTR_TO_DYNPTR:
6348 /* We only need to check for initialized / uninitialized helper
6349 * dynptr args if the dynptr is not PTR_TO_DYNPTR, as the
6350 * assumption is that if it is, that a helper function
6351 * initialized the dynptr on behalf of the BPF program.
6352 */
6353 if (base_type(reg->type) == PTR_TO_DYNPTR)
6354 break;
6355 if (arg_type & MEM_UNINIT) {
6356 if (!is_dynptr_reg_valid_uninit(env, reg)) {
6357 verbose(env, "Dynptr has to be an uninitialized dynptr\n");
6358 return -EINVAL;
6359 }
6360
6361 /* We only support one dynptr being uninitialized at the moment,
6362 * which is sufficient for the helper functions we have right now.
6363 */
6364 if (meta->uninit_dynptr_regno) {
6365 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n");
6366 return -EFAULT;
6367 }
6368
6369 meta->uninit_dynptr_regno = regno;
6370 } else if (!is_dynptr_reg_valid_init(env, reg)) {
6371 verbose(env,
6372 "Expected an initialized dynptr as arg #%d\n",
6373 arg + 1);
6374 return -EINVAL;
6375 } else if (!is_dynptr_type_expected(env, reg, arg_type)) {
6376 const char *err_extra = "";
6377
6378 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
6379 case DYNPTR_TYPE_LOCAL:
6380 err_extra = "local";
6381 break;
6382 case DYNPTR_TYPE_RINGBUF:
6383 err_extra = "ringbuf";
6384 break;
6385 default:
6386 err_extra = "<unknown>";
6387 break;
6388 }
6389 verbose(env,
6390 "Expected a dynptr of type %s as arg #%d\n",
6391 err_extra, arg + 1);
6392 return -EINVAL;
6393 }
6394 break;
6395 case ARG_CONST_ALLOC_SIZE_OR_ZERO:
6396 if (!tnum_is_const(reg->var_off)) {
6397 verbose(env, "R%d is not a known constant'\n",
6398 regno);
6399 return -EACCES;
6400 }
6401 meta->mem_size = reg->var_off.value;
6402 err = mark_chain_precision(env, regno);
6403 if (err)
6404 return err;
6405 break;
6406 case ARG_PTR_TO_INT:
6407 case ARG_PTR_TO_LONG:
6408 {
6409 int size = int_ptr_type_to_size(arg_type);
6410
6411 err = check_helper_mem_access(env, regno, size, false, meta);
6412 if (err)
6413 return err;
6414 err = check_ptr_alignment(env, reg, 0, size, true);
6415 break;
6416 }
6417 case ARG_PTR_TO_CONST_STR:
6418 {
6419 struct bpf_map *map = reg->map_ptr;
6420 int map_off;
6421 u64 map_addr;
6422 char *str_ptr;
6423
6424 if (!bpf_map_is_rdonly(map)) {
6425 verbose(env, "R%d does not point to a readonly map'\n", regno);
6426 return -EACCES;
6427 }
6428
6429 if (!tnum_is_const(reg->var_off)) {
6430 verbose(env, "R%d is not a constant address'\n", regno);
6431 return -EACCES;
6432 }
6433
6434 if (!map->ops->map_direct_value_addr) {
6435 verbose(env, "no direct value access support for this map type\n");
6436 return -EACCES;
6437 }
6438
6439 err = check_map_access(env, regno, reg->off,
6440 map->value_size - reg->off, false,
6441 ACCESS_HELPER);
6442 if (err)
6443 return err;
6444
6445 map_off = reg->off + reg->var_off.value;
6446 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
6447 if (err) {
6448 verbose(env, "direct value access on string failed\n");
6449 return err;
6450 }
6451
6452 str_ptr = (char *)(long)(map_addr);
6453 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
6454 verbose(env, "string is not zero-terminated\n");
6455 return -EINVAL;
6456 }
6457 break;
6458 }
6459 case ARG_PTR_TO_KPTR:
6460 if (process_kptr_func(env, regno, meta))
6461 return -EACCES;
6462 break;
6463 }
6464
6465 return err;
6466 }
6467
may_update_sockmap(struct bpf_verifier_env * env,int func_id)6468 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
6469 {
6470 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6471 enum bpf_prog_type type = resolve_prog_type(env->prog);
6472
6473 if (func_id != BPF_FUNC_map_update_elem)
6474 return false;
6475
6476 /* It's not possible to get access to a locked struct sock in these
6477 * contexts, so updating is safe.
6478 */
6479 switch (type) {
6480 case BPF_PROG_TYPE_TRACING:
6481 if (eatype == BPF_TRACE_ITER)
6482 return true;
6483 break;
6484 case BPF_PROG_TYPE_SOCKET_FILTER:
6485 case BPF_PROG_TYPE_SCHED_CLS:
6486 case BPF_PROG_TYPE_SCHED_ACT:
6487 case BPF_PROG_TYPE_XDP:
6488 case BPF_PROG_TYPE_SK_REUSEPORT:
6489 case BPF_PROG_TYPE_FLOW_DISSECTOR:
6490 case BPF_PROG_TYPE_SK_LOOKUP:
6491 return true;
6492 default:
6493 break;
6494 }
6495
6496 verbose(env, "cannot update sockmap in this context\n");
6497 return false;
6498 }
6499
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)6500 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
6501 {
6502 return env->prog->jit_requested &&
6503 bpf_jit_supports_subprog_tailcalls();
6504 }
6505
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)6506 static int check_map_func_compatibility(struct bpf_verifier_env *env,
6507 struct bpf_map *map, int func_id)
6508 {
6509 if (!map)
6510 return 0;
6511
6512 /* We need a two way check, first is from map perspective ... */
6513 switch (map->map_type) {
6514 case BPF_MAP_TYPE_PROG_ARRAY:
6515 if (func_id != BPF_FUNC_tail_call)
6516 goto error;
6517 break;
6518 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
6519 if (func_id != BPF_FUNC_perf_event_read &&
6520 func_id != BPF_FUNC_perf_event_output &&
6521 func_id != BPF_FUNC_skb_output &&
6522 func_id != BPF_FUNC_perf_event_read_value &&
6523 func_id != BPF_FUNC_xdp_output)
6524 goto error;
6525 break;
6526 case BPF_MAP_TYPE_RINGBUF:
6527 if (func_id != BPF_FUNC_ringbuf_output &&
6528 func_id != BPF_FUNC_ringbuf_reserve &&
6529 func_id != BPF_FUNC_ringbuf_query &&
6530 func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
6531 func_id != BPF_FUNC_ringbuf_submit_dynptr &&
6532 func_id != BPF_FUNC_ringbuf_discard_dynptr)
6533 goto error;
6534 break;
6535 case BPF_MAP_TYPE_USER_RINGBUF:
6536 if (func_id != BPF_FUNC_user_ringbuf_drain)
6537 goto error;
6538 break;
6539 case BPF_MAP_TYPE_STACK_TRACE:
6540 if (func_id != BPF_FUNC_get_stackid)
6541 goto error;
6542 break;
6543 case BPF_MAP_TYPE_CGROUP_ARRAY:
6544 if (func_id != BPF_FUNC_skb_under_cgroup &&
6545 func_id != BPF_FUNC_current_task_under_cgroup)
6546 goto error;
6547 break;
6548 case BPF_MAP_TYPE_CGROUP_STORAGE:
6549 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
6550 if (func_id != BPF_FUNC_get_local_storage)
6551 goto error;
6552 break;
6553 case BPF_MAP_TYPE_DEVMAP:
6554 case BPF_MAP_TYPE_DEVMAP_HASH:
6555 if (func_id != BPF_FUNC_redirect_map &&
6556 func_id != BPF_FUNC_map_lookup_elem)
6557 goto error;
6558 break;
6559 /* Restrict bpf side of cpumap and xskmap, open when use-cases
6560 * appear.
6561 */
6562 case BPF_MAP_TYPE_CPUMAP:
6563 if (func_id != BPF_FUNC_redirect_map)
6564 goto error;
6565 break;
6566 case BPF_MAP_TYPE_XSKMAP:
6567 if (func_id != BPF_FUNC_redirect_map &&
6568 func_id != BPF_FUNC_map_lookup_elem)
6569 goto error;
6570 break;
6571 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
6572 case BPF_MAP_TYPE_HASH_OF_MAPS:
6573 if (func_id != BPF_FUNC_map_lookup_elem)
6574 goto error;
6575 break;
6576 case BPF_MAP_TYPE_SOCKMAP:
6577 if (func_id != BPF_FUNC_sk_redirect_map &&
6578 func_id != BPF_FUNC_sock_map_update &&
6579 func_id != BPF_FUNC_map_delete_elem &&
6580 func_id != BPF_FUNC_msg_redirect_map &&
6581 func_id != BPF_FUNC_sk_select_reuseport &&
6582 func_id != BPF_FUNC_map_lookup_elem &&
6583 !may_update_sockmap(env, func_id))
6584 goto error;
6585 break;
6586 case BPF_MAP_TYPE_SOCKHASH:
6587 if (func_id != BPF_FUNC_sk_redirect_hash &&
6588 func_id != BPF_FUNC_sock_hash_update &&
6589 func_id != BPF_FUNC_map_delete_elem &&
6590 func_id != BPF_FUNC_msg_redirect_hash &&
6591 func_id != BPF_FUNC_sk_select_reuseport &&
6592 func_id != BPF_FUNC_map_lookup_elem &&
6593 !may_update_sockmap(env, func_id))
6594 goto error;
6595 break;
6596 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
6597 if (func_id != BPF_FUNC_sk_select_reuseport)
6598 goto error;
6599 break;
6600 case BPF_MAP_TYPE_QUEUE:
6601 case BPF_MAP_TYPE_STACK:
6602 if (func_id != BPF_FUNC_map_peek_elem &&
6603 func_id != BPF_FUNC_map_pop_elem &&
6604 func_id != BPF_FUNC_map_push_elem)
6605 goto error;
6606 break;
6607 case BPF_MAP_TYPE_SK_STORAGE:
6608 if (func_id != BPF_FUNC_sk_storage_get &&
6609 func_id != BPF_FUNC_sk_storage_delete)
6610 goto error;
6611 break;
6612 case BPF_MAP_TYPE_INODE_STORAGE:
6613 if (func_id != BPF_FUNC_inode_storage_get &&
6614 func_id != BPF_FUNC_inode_storage_delete)
6615 goto error;
6616 break;
6617 case BPF_MAP_TYPE_TASK_STORAGE:
6618 if (func_id != BPF_FUNC_task_storage_get &&
6619 func_id != BPF_FUNC_task_storage_delete)
6620 goto error;
6621 break;
6622 case BPF_MAP_TYPE_BLOOM_FILTER:
6623 if (func_id != BPF_FUNC_map_peek_elem &&
6624 func_id != BPF_FUNC_map_push_elem)
6625 goto error;
6626 break;
6627 default:
6628 break;
6629 }
6630
6631 /* ... and second from the function itself. */
6632 switch (func_id) {
6633 case BPF_FUNC_tail_call:
6634 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
6635 goto error;
6636 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
6637 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
6638 return -EINVAL;
6639 }
6640 break;
6641 case BPF_FUNC_perf_event_read:
6642 case BPF_FUNC_perf_event_output:
6643 case BPF_FUNC_perf_event_read_value:
6644 case BPF_FUNC_skb_output:
6645 case BPF_FUNC_xdp_output:
6646 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
6647 goto error;
6648 break;
6649 case BPF_FUNC_ringbuf_output:
6650 case BPF_FUNC_ringbuf_reserve:
6651 case BPF_FUNC_ringbuf_query:
6652 case BPF_FUNC_ringbuf_reserve_dynptr:
6653 case BPF_FUNC_ringbuf_submit_dynptr:
6654 case BPF_FUNC_ringbuf_discard_dynptr:
6655 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
6656 goto error;
6657 break;
6658 case BPF_FUNC_user_ringbuf_drain:
6659 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
6660 goto error;
6661 break;
6662 case BPF_FUNC_get_stackid:
6663 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
6664 goto error;
6665 break;
6666 case BPF_FUNC_current_task_under_cgroup:
6667 case BPF_FUNC_skb_under_cgroup:
6668 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
6669 goto error;
6670 break;
6671 case BPF_FUNC_redirect_map:
6672 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6673 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
6674 map->map_type != BPF_MAP_TYPE_CPUMAP &&
6675 map->map_type != BPF_MAP_TYPE_XSKMAP)
6676 goto error;
6677 break;
6678 case BPF_FUNC_sk_redirect_map:
6679 case BPF_FUNC_msg_redirect_map:
6680 case BPF_FUNC_sock_map_update:
6681 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
6682 goto error;
6683 break;
6684 case BPF_FUNC_sk_redirect_hash:
6685 case BPF_FUNC_msg_redirect_hash:
6686 case BPF_FUNC_sock_hash_update:
6687 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
6688 goto error;
6689 break;
6690 case BPF_FUNC_get_local_storage:
6691 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
6692 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
6693 goto error;
6694 break;
6695 case BPF_FUNC_sk_select_reuseport:
6696 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
6697 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
6698 map->map_type != BPF_MAP_TYPE_SOCKHASH)
6699 goto error;
6700 break;
6701 case BPF_FUNC_map_pop_elem:
6702 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6703 map->map_type != BPF_MAP_TYPE_STACK)
6704 goto error;
6705 break;
6706 case BPF_FUNC_map_peek_elem:
6707 case BPF_FUNC_map_push_elem:
6708 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
6709 map->map_type != BPF_MAP_TYPE_STACK &&
6710 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
6711 goto error;
6712 break;
6713 case BPF_FUNC_map_lookup_percpu_elem:
6714 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
6715 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
6716 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
6717 goto error;
6718 break;
6719 case BPF_FUNC_sk_storage_get:
6720 case BPF_FUNC_sk_storage_delete:
6721 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
6722 goto error;
6723 break;
6724 case BPF_FUNC_inode_storage_get:
6725 case BPF_FUNC_inode_storage_delete:
6726 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
6727 goto error;
6728 break;
6729 case BPF_FUNC_task_storage_get:
6730 case BPF_FUNC_task_storage_delete:
6731 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
6732 goto error;
6733 break;
6734 default:
6735 break;
6736 }
6737
6738 return 0;
6739 error:
6740 verbose(env, "cannot pass map_type %d into func %s#%d\n",
6741 map->map_type, func_id_name(func_id), func_id);
6742 return -EINVAL;
6743 }
6744
check_raw_mode_ok(const struct bpf_func_proto * fn)6745 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
6746 {
6747 int count = 0;
6748
6749 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
6750 count++;
6751 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
6752 count++;
6753 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
6754 count++;
6755 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
6756 count++;
6757 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
6758 count++;
6759
6760 /* We only support one arg being in raw mode at the moment,
6761 * which is sufficient for the helper functions we have
6762 * right now.
6763 */
6764 return count <= 1;
6765 }
6766
check_args_pair_invalid(const struct bpf_func_proto * fn,int arg)6767 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
6768 {
6769 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
6770 bool has_size = fn->arg_size[arg] != 0;
6771 bool is_next_size = false;
6772
6773 if (arg + 1 < ARRAY_SIZE(fn->arg_type))
6774 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
6775
6776 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
6777 return is_next_size;
6778
6779 return has_size == is_next_size || is_next_size == is_fixed;
6780 }
6781
check_arg_pair_ok(const struct bpf_func_proto * fn)6782 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
6783 {
6784 /* bpf_xxx(..., buf, len) call will access 'len'
6785 * bytes from memory 'buf'. Both arg types need
6786 * to be paired, so make sure there's no buggy
6787 * helper function specification.
6788 */
6789 if (arg_type_is_mem_size(fn->arg1_type) ||
6790 check_args_pair_invalid(fn, 0) ||
6791 check_args_pair_invalid(fn, 1) ||
6792 check_args_pair_invalid(fn, 2) ||
6793 check_args_pair_invalid(fn, 3) ||
6794 check_args_pair_invalid(fn, 4))
6795 return false;
6796
6797 return true;
6798 }
6799
check_btf_id_ok(const struct bpf_func_proto * fn)6800 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
6801 {
6802 int i;
6803
6804 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
6805 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
6806 return false;
6807
6808 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
6809 /* arg_btf_id and arg_size are in a union. */
6810 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
6811 !(fn->arg_type[i] & MEM_FIXED_SIZE)))
6812 return false;
6813 }
6814
6815 return true;
6816 }
6817
check_func_proto(const struct bpf_func_proto * fn,int func_id)6818 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
6819 {
6820 return check_raw_mode_ok(fn) &&
6821 check_arg_pair_ok(fn) &&
6822 check_btf_id_ok(fn) ? 0 : -EINVAL;
6823 }
6824
6825 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
6826 * are now invalid, so turn them into unknown SCALAR_VALUE.
6827 */
clear_all_pkt_pointers(struct bpf_verifier_env * env)6828 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
6829 {
6830 struct bpf_func_state *state;
6831 struct bpf_reg_state *reg;
6832
6833 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6834 if (reg_is_pkt_pointer_any(reg))
6835 __mark_reg_unknown(env, reg);
6836 }));
6837 }
6838
6839 enum {
6840 AT_PKT_END = -1,
6841 BEYOND_PKT_END = -2,
6842 };
6843
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)6844 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
6845 {
6846 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6847 struct bpf_reg_state *reg = &state->regs[regn];
6848
6849 if (reg->type != PTR_TO_PACKET)
6850 /* PTR_TO_PACKET_META is not supported yet */
6851 return;
6852
6853 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
6854 * How far beyond pkt_end it goes is unknown.
6855 * if (!range_open) it's the case of pkt >= pkt_end
6856 * if (range_open) it's the case of pkt > pkt_end
6857 * hence this pointer is at least 1 byte bigger than pkt_end
6858 */
6859 if (range_open)
6860 reg->range = BEYOND_PKT_END;
6861 else
6862 reg->range = AT_PKT_END;
6863 }
6864
6865 /* The pointer with the specified id has released its reference to kernel
6866 * resources. Identify all copies of the same pointer and clear the reference.
6867 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)6868 static int release_reference(struct bpf_verifier_env *env,
6869 int ref_obj_id)
6870 {
6871 struct bpf_func_state *state;
6872 struct bpf_reg_state *reg;
6873 int err;
6874
6875 err = release_reference_state(cur_func(env), ref_obj_id);
6876 if (err)
6877 return err;
6878
6879 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
6880 if (reg->ref_obj_id == ref_obj_id) {
6881 if (!env->allow_ptr_leaks)
6882 __mark_reg_not_init(env, reg);
6883 else
6884 __mark_reg_unknown(env, reg);
6885 }
6886 }));
6887
6888 return 0;
6889 }
6890
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)6891 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
6892 struct bpf_reg_state *regs)
6893 {
6894 int i;
6895
6896 /* after the call registers r0 - r5 were scratched */
6897 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6898 mark_reg_not_init(env, regs, caller_saved[i]);
6899 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6900 }
6901 }
6902
6903 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
6904 struct bpf_func_state *caller,
6905 struct bpf_func_state *callee,
6906 int insn_idx);
6907
6908 static int set_callee_state(struct bpf_verifier_env *env,
6909 struct bpf_func_state *caller,
6910 struct bpf_func_state *callee, int insn_idx);
6911
__check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx,int subprog,set_callee_state_fn set_callee_state_cb)6912 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6913 int *insn_idx, int subprog,
6914 set_callee_state_fn set_callee_state_cb)
6915 {
6916 struct bpf_verifier_state *state = env->cur_state;
6917 struct bpf_func_info_aux *func_info_aux;
6918 struct bpf_func_state *caller, *callee;
6919 int err;
6920 bool is_global = false;
6921
6922 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
6923 verbose(env, "the call stack of %d frames is too deep\n",
6924 state->curframe + 2);
6925 return -E2BIG;
6926 }
6927
6928 caller = state->frame[state->curframe];
6929 if (state->frame[state->curframe + 1]) {
6930 verbose(env, "verifier bug. Frame %d already allocated\n",
6931 state->curframe + 1);
6932 return -EFAULT;
6933 }
6934
6935 func_info_aux = env->prog->aux->func_info_aux;
6936 if (func_info_aux)
6937 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6938 err = btf_check_subprog_call(env, subprog, caller->regs);
6939 if (err == -EFAULT)
6940 return err;
6941 if (is_global) {
6942 if (err) {
6943 verbose(env, "Caller passes invalid args into func#%d\n",
6944 subprog);
6945 return err;
6946 } else {
6947 if (env->log.level & BPF_LOG_LEVEL)
6948 verbose(env,
6949 "Func#%d is global and valid. Skipping.\n",
6950 subprog);
6951 clear_caller_saved_regs(env, caller->regs);
6952
6953 /* All global functions return a 64-bit SCALAR_VALUE */
6954 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6955 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6956
6957 /* continue with next insn after call */
6958 return 0;
6959 }
6960 }
6961
6962 /* set_callee_state is used for direct subprog calls, but we are
6963 * interested in validating only BPF helpers that can call subprogs as
6964 * callbacks
6965 */
6966 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) {
6967 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n",
6968 func_id_name(insn->imm), insn->imm);
6969 return -EFAULT;
6970 }
6971
6972 if (insn->code == (BPF_JMP | BPF_CALL) &&
6973 insn->src_reg == 0 &&
6974 insn->imm == BPF_FUNC_timer_set_callback) {
6975 struct bpf_verifier_state *async_cb;
6976
6977 /* there is no real recursion here. timer callbacks are async */
6978 env->subprog_info[subprog].is_async_cb = true;
6979 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6980 *insn_idx, subprog);
6981 if (!async_cb)
6982 return -EFAULT;
6983 callee = async_cb->frame[0];
6984 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6985
6986 /* Convert bpf_timer_set_callback() args into timer callback args */
6987 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6988 if (err)
6989 return err;
6990
6991 clear_caller_saved_regs(env, caller->regs);
6992 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6993 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6994 /* continue with next insn after call */
6995 return 0;
6996 }
6997
6998 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6999 if (!callee)
7000 return -ENOMEM;
7001 state->frame[state->curframe + 1] = callee;
7002
7003 /* callee cannot access r0, r6 - r9 for reading and has to write
7004 * into its own stack before reading from it.
7005 * callee can read/write into caller's stack
7006 */
7007 init_func_state(env, callee,
7008 /* remember the callsite, it will be used by bpf_exit */
7009 *insn_idx /* callsite */,
7010 state->curframe + 1 /* frameno within this callchain */,
7011 subprog /* subprog number within this prog */);
7012
7013 /* Transfer references to the callee */
7014 err = copy_reference_state(callee, caller);
7015 if (err)
7016 goto err_out;
7017
7018 err = set_callee_state_cb(env, caller, callee, *insn_idx);
7019 if (err)
7020 goto err_out;
7021
7022 clear_caller_saved_regs(env, caller->regs);
7023
7024 /* only increment it after check_reg_arg() finished */
7025 state->curframe++;
7026
7027 /* and go analyze first insn of the callee */
7028 *insn_idx = env->subprog_info[subprog].start - 1;
7029
7030 if (env->log.level & BPF_LOG_LEVEL) {
7031 verbose(env, "caller:\n");
7032 print_verifier_state(env, caller, true);
7033 verbose(env, "callee:\n");
7034 print_verifier_state(env, callee, true);
7035 }
7036 return 0;
7037
7038 err_out:
7039 free_func_state(callee);
7040 state->frame[state->curframe + 1] = NULL;
7041 return err;
7042 }
7043
map_set_for_each_callback_args(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee)7044 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
7045 struct bpf_func_state *caller,
7046 struct bpf_func_state *callee)
7047 {
7048 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
7049 * void *callback_ctx, u64 flags);
7050 * callback_fn(struct bpf_map *map, void *key, void *value,
7051 * void *callback_ctx);
7052 */
7053 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7054
7055 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7056 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7057 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7058
7059 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7060 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7061 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
7062
7063 /* pointer to stack or null */
7064 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
7065
7066 /* unused */
7067 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7068 return 0;
7069 }
7070
set_callee_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7071 static int set_callee_state(struct bpf_verifier_env *env,
7072 struct bpf_func_state *caller,
7073 struct bpf_func_state *callee, int insn_idx)
7074 {
7075 int i;
7076
7077 /* copy r1 - r5 args that callee can access. The copy includes parent
7078 * pointers, which connects us up to the liveness chain
7079 */
7080 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
7081 callee->regs[i] = caller->regs[i];
7082 return 0;
7083 }
7084
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)7085 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7086 int *insn_idx)
7087 {
7088 int subprog, target_insn;
7089
7090 target_insn = *insn_idx + insn->imm + 1;
7091 subprog = find_subprog(env, target_insn);
7092 if (subprog < 0) {
7093 verbose(env, "verifier bug. No program starts at insn %d\n",
7094 target_insn);
7095 return -EFAULT;
7096 }
7097
7098 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
7099 }
7100
set_map_elem_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7101 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
7102 struct bpf_func_state *caller,
7103 struct bpf_func_state *callee,
7104 int insn_idx)
7105 {
7106 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
7107 struct bpf_map *map;
7108 int err;
7109
7110 if (bpf_map_ptr_poisoned(insn_aux)) {
7111 verbose(env, "tail_call abusing map_ptr\n");
7112 return -EINVAL;
7113 }
7114
7115 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
7116 if (!map->ops->map_set_for_each_callback_args ||
7117 !map->ops->map_for_each_callback) {
7118 verbose(env, "callback function not allowed for map\n");
7119 return -ENOTSUPP;
7120 }
7121
7122 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
7123 if (err)
7124 return err;
7125
7126 callee->in_callback_fn = true;
7127 callee->callback_ret_range = tnum_range(0, 1);
7128 return 0;
7129 }
7130
set_loop_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7131 static int set_loop_callback_state(struct bpf_verifier_env *env,
7132 struct bpf_func_state *caller,
7133 struct bpf_func_state *callee,
7134 int insn_idx)
7135 {
7136 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
7137 * u64 flags);
7138 * callback_fn(u32 index, void *callback_ctx);
7139 */
7140 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
7141 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7142
7143 /* unused */
7144 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7145 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7146 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7147
7148 callee->in_callback_fn = true;
7149 callee->callback_ret_range = tnum_range(0, 1);
7150 return 0;
7151 }
7152
set_timer_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7153 static int set_timer_callback_state(struct bpf_verifier_env *env,
7154 struct bpf_func_state *caller,
7155 struct bpf_func_state *callee,
7156 int insn_idx)
7157 {
7158 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
7159
7160 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
7161 * callback_fn(struct bpf_map *map, void *key, void *value);
7162 */
7163 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
7164 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7165 callee->regs[BPF_REG_1].map_ptr = map_ptr;
7166
7167 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
7168 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7169 callee->regs[BPF_REG_2].map_ptr = map_ptr;
7170
7171 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
7172 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
7173 callee->regs[BPF_REG_3].map_ptr = map_ptr;
7174
7175 /* unused */
7176 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7177 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7178 callee->in_async_callback_fn = true;
7179 callee->callback_ret_range = tnum_range(0, 1);
7180 return 0;
7181 }
7182
set_find_vma_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7183 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
7184 struct bpf_func_state *caller,
7185 struct bpf_func_state *callee,
7186 int insn_idx)
7187 {
7188 /* bpf_find_vma(struct task_struct *task, u64 addr,
7189 * void *callback_fn, void *callback_ctx, u64 flags)
7190 * (callback_fn)(struct task_struct *task,
7191 * struct vm_area_struct *vma, void *callback_ctx);
7192 */
7193 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
7194
7195 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
7196 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
7197 callee->regs[BPF_REG_2].btf = btf_vmlinux;
7198 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
7199
7200 /* pointer to stack or null */
7201 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
7202
7203 /* unused */
7204 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7205 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7206 callee->in_callback_fn = true;
7207 callee->callback_ret_range = tnum_range(0, 1);
7208 return 0;
7209 }
7210
set_user_ringbuf_callback_state(struct bpf_verifier_env * env,struct bpf_func_state * caller,struct bpf_func_state * callee,int insn_idx)7211 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
7212 struct bpf_func_state *caller,
7213 struct bpf_func_state *callee,
7214 int insn_idx)
7215 {
7216 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
7217 * callback_ctx, u64 flags);
7218 * callback_fn(struct bpf_dynptr_t* dynptr, void *callback_ctx);
7219 */
7220 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
7221 callee->regs[BPF_REG_1].type = PTR_TO_DYNPTR | DYNPTR_TYPE_LOCAL;
7222 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
7223 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
7224
7225 /* unused */
7226 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
7227 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
7228 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
7229
7230 callee->in_callback_fn = true;
7231 callee->callback_ret_range = tnum_range(0, 1);
7232 return 0;
7233 }
7234
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)7235 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
7236 {
7237 struct bpf_verifier_state *state = env->cur_state;
7238 struct bpf_func_state *caller, *callee;
7239 struct bpf_reg_state *r0;
7240 int err;
7241
7242 callee = state->frame[state->curframe];
7243 r0 = &callee->regs[BPF_REG_0];
7244 if (r0->type == PTR_TO_STACK) {
7245 /* technically it's ok to return caller's stack pointer
7246 * (or caller's caller's pointer) back to the caller,
7247 * since these pointers are valid. Only current stack
7248 * pointer will be invalid as soon as function exits,
7249 * but let's be conservative
7250 */
7251 verbose(env, "cannot return stack pointer to the caller\n");
7252 return -EINVAL;
7253 }
7254
7255 caller = state->frame[state->curframe - 1];
7256 if (callee->in_callback_fn) {
7257 /* enforce R0 return value range [0, 1]. */
7258 struct tnum range = callee->callback_ret_range;
7259
7260 if (r0->type != SCALAR_VALUE) {
7261 verbose(env, "R0 not a scalar value\n");
7262 return -EACCES;
7263 }
7264
7265 /* we are going to rely on register's precise value */
7266 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
7267 err = err ?: mark_chain_precision(env, BPF_REG_0);
7268 if (err)
7269 return err;
7270
7271 if (!tnum_in(range, r0->var_off)) {
7272 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
7273 return -EINVAL;
7274 }
7275 } else {
7276 /* return to the caller whatever r0 had in the callee */
7277 caller->regs[BPF_REG_0] = *r0;
7278 }
7279
7280 /* callback_fn frame should have released its own additions to parent's
7281 * reference state at this point, or check_reference_leak would
7282 * complain, hence it must be the same as the caller. There is no need
7283 * to copy it back.
7284 */
7285 if (!callee->in_callback_fn) {
7286 /* Transfer references to the caller */
7287 err = copy_reference_state(caller, callee);
7288 if (err)
7289 return err;
7290 }
7291
7292 *insn_idx = callee->callsite + 1;
7293 if (env->log.level & BPF_LOG_LEVEL) {
7294 verbose(env, "returning from callee:\n");
7295 print_verifier_state(env, callee, true);
7296 verbose(env, "to caller at %d:\n", *insn_idx);
7297 print_verifier_state(env, caller, true);
7298 }
7299 /* clear everything in the callee */
7300 free_func_state(callee);
7301 state->frame[state->curframe--] = NULL;
7302 return 0;
7303 }
7304
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)7305 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
7306 int func_id,
7307 struct bpf_call_arg_meta *meta)
7308 {
7309 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
7310
7311 if (ret_type != RET_INTEGER ||
7312 (func_id != BPF_FUNC_get_stack &&
7313 func_id != BPF_FUNC_get_task_stack &&
7314 func_id != BPF_FUNC_probe_read_str &&
7315 func_id != BPF_FUNC_probe_read_kernel_str &&
7316 func_id != BPF_FUNC_probe_read_user_str))
7317 return;
7318
7319 ret_reg->smax_value = meta->msize_max_value;
7320 ret_reg->s32_max_value = meta->msize_max_value;
7321 ret_reg->smin_value = -MAX_ERRNO;
7322 ret_reg->s32_min_value = -MAX_ERRNO;
7323 reg_bounds_sync(ret_reg);
7324 }
7325
7326 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)7327 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7328 int func_id, int insn_idx)
7329 {
7330 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7331 struct bpf_map *map = meta->map_ptr;
7332
7333 if (func_id != BPF_FUNC_tail_call &&
7334 func_id != BPF_FUNC_map_lookup_elem &&
7335 func_id != BPF_FUNC_map_update_elem &&
7336 func_id != BPF_FUNC_map_delete_elem &&
7337 func_id != BPF_FUNC_map_push_elem &&
7338 func_id != BPF_FUNC_map_pop_elem &&
7339 func_id != BPF_FUNC_map_peek_elem &&
7340 func_id != BPF_FUNC_for_each_map_elem &&
7341 func_id != BPF_FUNC_redirect_map &&
7342 func_id != BPF_FUNC_map_lookup_percpu_elem)
7343 return 0;
7344
7345 if (map == NULL) {
7346 verbose(env, "kernel subsystem misconfigured verifier\n");
7347 return -EINVAL;
7348 }
7349
7350 /* In case of read-only, some additional restrictions
7351 * need to be applied in order to prevent altering the
7352 * state of the map from program side.
7353 */
7354 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
7355 (func_id == BPF_FUNC_map_delete_elem ||
7356 func_id == BPF_FUNC_map_update_elem ||
7357 func_id == BPF_FUNC_map_push_elem ||
7358 func_id == BPF_FUNC_map_pop_elem)) {
7359 verbose(env, "write into map forbidden\n");
7360 return -EACCES;
7361 }
7362
7363 if (!BPF_MAP_PTR(aux->map_ptr_state))
7364 bpf_map_ptr_store(aux, meta->map_ptr,
7365 !meta->map_ptr->bypass_spec_v1);
7366 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
7367 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
7368 !meta->map_ptr->bypass_spec_v1);
7369 return 0;
7370 }
7371
7372 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)7373 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
7374 int func_id, int insn_idx)
7375 {
7376 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
7377 struct bpf_reg_state *regs = cur_regs(env), *reg;
7378 struct bpf_map *map = meta->map_ptr;
7379 u64 val, max;
7380 int err;
7381
7382 if (func_id != BPF_FUNC_tail_call)
7383 return 0;
7384 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
7385 verbose(env, "kernel subsystem misconfigured verifier\n");
7386 return -EINVAL;
7387 }
7388
7389 reg = ®s[BPF_REG_3];
7390 val = reg->var_off.value;
7391 max = map->max_entries;
7392
7393 if (!(register_is_const(reg) && val < max)) {
7394 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7395 return 0;
7396 }
7397
7398 err = mark_chain_precision(env, BPF_REG_3);
7399 if (err)
7400 return err;
7401 if (bpf_map_key_unseen(aux))
7402 bpf_map_key_store(aux, val);
7403 else if (!bpf_map_key_poisoned(aux) &&
7404 bpf_map_key_immediate(aux) != val)
7405 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
7406 return 0;
7407 }
7408
check_reference_leak(struct bpf_verifier_env * env)7409 static int check_reference_leak(struct bpf_verifier_env *env)
7410 {
7411 struct bpf_func_state *state = cur_func(env);
7412 bool refs_lingering = false;
7413 int i;
7414
7415 if (state->frameno && !state->in_callback_fn)
7416 return 0;
7417
7418 for (i = 0; i < state->acquired_refs; i++) {
7419 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
7420 continue;
7421 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
7422 state->refs[i].id, state->refs[i].insn_idx);
7423 refs_lingering = true;
7424 }
7425 return refs_lingering ? -EINVAL : 0;
7426 }
7427
check_bpf_snprintf_call(struct bpf_verifier_env * env,struct bpf_reg_state * regs)7428 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
7429 struct bpf_reg_state *regs)
7430 {
7431 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3];
7432 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5];
7433 struct bpf_map *fmt_map = fmt_reg->map_ptr;
7434 struct bpf_bprintf_data data = {};
7435 int err, fmt_map_off, num_args;
7436 u64 fmt_addr;
7437 char *fmt;
7438
7439 /* data must be an array of u64 */
7440 if (data_len_reg->var_off.value % 8)
7441 return -EINVAL;
7442 num_args = data_len_reg->var_off.value / 8;
7443
7444 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
7445 * and map_direct_value_addr is set.
7446 */
7447 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
7448 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
7449 fmt_map_off);
7450 if (err) {
7451 verbose(env, "verifier bug\n");
7452 return -EFAULT;
7453 }
7454 fmt = (char *)(long)fmt_addr + fmt_map_off;
7455
7456 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
7457 * can focus on validating the format specifiers.
7458 */
7459 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
7460 if (err < 0)
7461 verbose(env, "Invalid format string\n");
7462
7463 return err;
7464 }
7465
check_get_func_ip(struct bpf_verifier_env * env)7466 static int check_get_func_ip(struct bpf_verifier_env *env)
7467 {
7468 enum bpf_prog_type type = resolve_prog_type(env->prog);
7469 int func_id = BPF_FUNC_get_func_ip;
7470
7471 if (type == BPF_PROG_TYPE_TRACING) {
7472 if (!bpf_prog_has_trampoline(env->prog)) {
7473 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
7474 func_id_name(func_id), func_id);
7475 return -ENOTSUPP;
7476 }
7477 return 0;
7478 } else if (type == BPF_PROG_TYPE_KPROBE) {
7479 return 0;
7480 }
7481
7482 verbose(env, "func %s#%d not supported for program type %d\n",
7483 func_id_name(func_id), func_id, type);
7484 return -ENOTSUPP;
7485 }
7486
cur_aux(struct bpf_verifier_env * env)7487 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
7488 {
7489 return &env->insn_aux_data[env->insn_idx];
7490 }
7491
loop_flag_is_zero(struct bpf_verifier_env * env)7492 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
7493 {
7494 struct bpf_reg_state *regs = cur_regs(env);
7495 struct bpf_reg_state *reg = ®s[BPF_REG_4];
7496 bool reg_is_null = register_is_null(reg);
7497
7498 if (reg_is_null)
7499 mark_chain_precision(env, BPF_REG_4);
7500
7501 return reg_is_null;
7502 }
7503
update_loop_inline_state(struct bpf_verifier_env * env,u32 subprogno)7504 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
7505 {
7506 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
7507
7508 if (!state->initialized) {
7509 state->initialized = 1;
7510 state->fit_for_inline = loop_flag_is_zero(env);
7511 state->callback_subprogno = subprogno;
7512 return;
7513 }
7514
7515 if (!state->fit_for_inline)
7516 return;
7517
7518 state->fit_for_inline = (loop_flag_is_zero(env) &&
7519 state->callback_subprogno == subprogno);
7520 }
7521
check_helper_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)7522 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7523 int *insn_idx_p)
7524 {
7525 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
7526 const struct bpf_func_proto *fn = NULL;
7527 enum bpf_return_type ret_type;
7528 enum bpf_type_flag ret_flag;
7529 struct bpf_reg_state *regs;
7530 struct bpf_call_arg_meta meta;
7531 int insn_idx = *insn_idx_p;
7532 bool changes_data;
7533 int i, err, func_id;
7534
7535 /* find function prototype */
7536 func_id = insn->imm;
7537 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
7538 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
7539 func_id);
7540 return -EINVAL;
7541 }
7542
7543 if (env->ops->get_func_proto)
7544 fn = env->ops->get_func_proto(func_id, env->prog);
7545 if (!fn) {
7546 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
7547 func_id);
7548 return -EINVAL;
7549 }
7550
7551 /* eBPF programs must be GPL compatible to use GPL-ed functions */
7552 if (!env->prog->gpl_compatible && fn->gpl_only) {
7553 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
7554 return -EINVAL;
7555 }
7556
7557 if (fn->allowed && !fn->allowed(env->prog)) {
7558 verbose(env, "helper call is not allowed in probe\n");
7559 return -EINVAL;
7560 }
7561
7562 /* With LD_ABS/IND some JITs save/restore skb from r1. */
7563 changes_data = bpf_helper_changes_pkt_data(fn->func);
7564 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
7565 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
7566 func_id_name(func_id), func_id);
7567 return -EINVAL;
7568 }
7569
7570 memset(&meta, 0, sizeof(meta));
7571 meta.pkt_access = fn->pkt_access;
7572
7573 err = check_func_proto(fn, func_id);
7574 if (err) {
7575 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
7576 func_id_name(func_id), func_id);
7577 return err;
7578 }
7579
7580 meta.func_id = func_id;
7581 /* check args */
7582 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7583 err = check_func_arg(env, i, &meta, fn);
7584 if (err)
7585 return err;
7586 }
7587
7588 err = record_func_map(env, &meta, func_id, insn_idx);
7589 if (err)
7590 return err;
7591
7592 err = record_func_key(env, &meta, func_id, insn_idx);
7593 if (err)
7594 return err;
7595
7596 /* Mark slots with STACK_MISC in case of raw mode, stack offset
7597 * is inferred from register state.
7598 */
7599 for (i = 0; i < meta.access_size; i++) {
7600 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
7601 BPF_WRITE, -1, false);
7602 if (err)
7603 return err;
7604 }
7605
7606 regs = cur_regs(env);
7607
7608 if (meta.uninit_dynptr_regno) {
7609 /* we write BPF_DW bits (8 bytes) at a time */
7610 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7611 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno,
7612 i, BPF_DW, BPF_WRITE, -1, false);
7613 if (err)
7614 return err;
7615 }
7616
7617 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno],
7618 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1],
7619 insn_idx);
7620 if (err)
7621 return err;
7622 }
7623
7624 if (meta.release_regno) {
7625 err = -EINVAL;
7626 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1]))
7627 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]);
7628 else if (meta.ref_obj_id)
7629 err = release_reference(env, meta.ref_obj_id);
7630 /* meta.ref_obj_id can only be 0 if register that is meant to be
7631 * released is NULL, which must be > R0.
7632 */
7633 else if (register_is_null(®s[meta.release_regno]))
7634 err = 0;
7635 if (err) {
7636 verbose(env, "func %s#%d reference has not been acquired before\n",
7637 func_id_name(func_id), func_id);
7638 return err;
7639 }
7640 }
7641
7642 switch (func_id) {
7643 case BPF_FUNC_tail_call:
7644 err = check_reference_leak(env);
7645 if (err) {
7646 verbose(env, "tail_call would lead to reference leak\n");
7647 return err;
7648 }
7649 break;
7650 case BPF_FUNC_get_local_storage:
7651 /* check that flags argument in get_local_storage(map, flags) is 0,
7652 * this is required because get_local_storage() can't return an error.
7653 */
7654 if (!register_is_null(®s[BPF_REG_2])) {
7655 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
7656 return -EINVAL;
7657 }
7658 break;
7659 case BPF_FUNC_for_each_map_elem:
7660 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7661 set_map_elem_callback_state);
7662 break;
7663 case BPF_FUNC_timer_set_callback:
7664 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7665 set_timer_callback_state);
7666 break;
7667 case BPF_FUNC_find_vma:
7668 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7669 set_find_vma_callback_state);
7670 break;
7671 case BPF_FUNC_snprintf:
7672 err = check_bpf_snprintf_call(env, regs);
7673 break;
7674 case BPF_FUNC_loop:
7675 update_loop_inline_state(env, meta.subprogno);
7676 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7677 set_loop_callback_state);
7678 break;
7679 case BPF_FUNC_dynptr_from_mem:
7680 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
7681 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
7682 reg_type_str(env, regs[BPF_REG_1].type));
7683 return -EACCES;
7684 }
7685 break;
7686 case BPF_FUNC_set_retval:
7687 if (prog_type == BPF_PROG_TYPE_LSM &&
7688 env->prog->expected_attach_type == BPF_LSM_CGROUP) {
7689 if (!env->prog->aux->attach_func_proto->type) {
7690 /* Make sure programs that attach to void
7691 * hooks don't try to modify return value.
7692 */
7693 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
7694 return -EINVAL;
7695 }
7696 }
7697 break;
7698 case BPF_FUNC_dynptr_data:
7699 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
7700 if (arg_type_is_dynptr(fn->arg_type[i])) {
7701 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i];
7702
7703 if (meta.ref_obj_id) {
7704 verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
7705 return -EFAULT;
7706 }
7707
7708 if (base_type(reg->type) != PTR_TO_DYNPTR)
7709 /* Find the id of the dynptr we're
7710 * tracking the reference of
7711 */
7712 meta.ref_obj_id = stack_slot_get_id(env, reg);
7713 break;
7714 }
7715 }
7716 if (i == MAX_BPF_FUNC_REG_ARGS) {
7717 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n");
7718 return -EFAULT;
7719 }
7720 break;
7721 case BPF_FUNC_user_ringbuf_drain:
7722 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
7723 set_user_ringbuf_callback_state);
7724 break;
7725 }
7726
7727 if (err)
7728 return err;
7729
7730 /* reset caller saved regs */
7731 for (i = 0; i < CALLER_SAVED_REGS; i++) {
7732 mark_reg_not_init(env, regs, caller_saved[i]);
7733 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
7734 }
7735
7736 /* helper call returns 64-bit value. */
7737 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
7738
7739 /* update return register (already marked as written above) */
7740 ret_type = fn->ret_type;
7741 ret_flag = type_flag(ret_type);
7742
7743 switch (base_type(ret_type)) {
7744 case RET_INTEGER:
7745 /* sets type to SCALAR_VALUE */
7746 mark_reg_unknown(env, regs, BPF_REG_0);
7747 break;
7748 case RET_VOID:
7749 regs[BPF_REG_0].type = NOT_INIT;
7750 break;
7751 case RET_PTR_TO_MAP_VALUE:
7752 /* There is no offset yet applied, variable or fixed */
7753 mark_reg_known_zero(env, regs, BPF_REG_0);
7754 /* remember map_ptr, so that check_map_access()
7755 * can check 'value_size' boundary of memory access
7756 * to map element returned from bpf_map_lookup_elem()
7757 */
7758 if (meta.map_ptr == NULL) {
7759 verbose(env,
7760 "kernel subsystem misconfigured verifier\n");
7761 return -EINVAL;
7762 }
7763 regs[BPF_REG_0].map_ptr = meta.map_ptr;
7764 regs[BPF_REG_0].map_uid = meta.map_uid;
7765 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
7766 if (!type_may_be_null(ret_type) &&
7767 map_value_has_spin_lock(meta.map_ptr)) {
7768 regs[BPF_REG_0].id = ++env->id_gen;
7769 }
7770 break;
7771 case RET_PTR_TO_SOCKET:
7772 mark_reg_known_zero(env, regs, BPF_REG_0);
7773 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
7774 break;
7775 case RET_PTR_TO_SOCK_COMMON:
7776 mark_reg_known_zero(env, regs, BPF_REG_0);
7777 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
7778 break;
7779 case RET_PTR_TO_TCP_SOCK:
7780 mark_reg_known_zero(env, regs, BPF_REG_0);
7781 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
7782 break;
7783 case RET_PTR_TO_ALLOC_MEM:
7784 mark_reg_known_zero(env, regs, BPF_REG_0);
7785 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7786 regs[BPF_REG_0].mem_size = meta.mem_size;
7787 break;
7788 case RET_PTR_TO_MEM_OR_BTF_ID:
7789 {
7790 const struct btf_type *t;
7791
7792 mark_reg_known_zero(env, regs, BPF_REG_0);
7793 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
7794 if (!btf_type_is_struct(t)) {
7795 u32 tsize;
7796 const struct btf_type *ret;
7797 const char *tname;
7798
7799 /* resolve the type size of ksym. */
7800 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
7801 if (IS_ERR(ret)) {
7802 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
7803 verbose(env, "unable to resolve the size of type '%s': %ld\n",
7804 tname, PTR_ERR(ret));
7805 return -EINVAL;
7806 }
7807 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
7808 regs[BPF_REG_0].mem_size = tsize;
7809 } else {
7810 /* MEM_RDONLY may be carried from ret_flag, but it
7811 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
7812 * it will confuse the check of PTR_TO_BTF_ID in
7813 * check_mem_access().
7814 */
7815 ret_flag &= ~MEM_RDONLY;
7816
7817 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7818 regs[BPF_REG_0].btf = meta.ret_btf;
7819 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
7820 }
7821 break;
7822 }
7823 case RET_PTR_TO_BTF_ID:
7824 {
7825 struct btf *ret_btf;
7826 int ret_btf_id;
7827
7828 mark_reg_known_zero(env, regs, BPF_REG_0);
7829 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
7830 if (func_id == BPF_FUNC_kptr_xchg) {
7831 ret_btf = meta.kptr_off_desc->kptr.btf;
7832 ret_btf_id = meta.kptr_off_desc->kptr.btf_id;
7833 } else {
7834 if (fn->ret_btf_id == BPF_PTR_POISON) {
7835 verbose(env, "verifier internal error:");
7836 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
7837 func_id_name(func_id));
7838 return -EINVAL;
7839 }
7840 ret_btf = btf_vmlinux;
7841 ret_btf_id = *fn->ret_btf_id;
7842 }
7843 if (ret_btf_id == 0) {
7844 verbose(env, "invalid return type %u of func %s#%d\n",
7845 base_type(ret_type), func_id_name(func_id),
7846 func_id);
7847 return -EINVAL;
7848 }
7849 regs[BPF_REG_0].btf = ret_btf;
7850 regs[BPF_REG_0].btf_id = ret_btf_id;
7851 break;
7852 }
7853 default:
7854 verbose(env, "unknown return type %u of func %s#%d\n",
7855 base_type(ret_type), func_id_name(func_id), func_id);
7856 return -EINVAL;
7857 }
7858
7859 if (type_may_be_null(regs[BPF_REG_0].type))
7860 regs[BPF_REG_0].id = ++env->id_gen;
7861
7862 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
7863 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
7864 func_id_name(func_id), func_id);
7865 return -EFAULT;
7866 }
7867
7868 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
7869 /* For release_reference() */
7870 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
7871 } else if (is_acquire_function(func_id, meta.map_ptr)) {
7872 int id = acquire_reference_state(env, insn_idx);
7873
7874 if (id < 0)
7875 return id;
7876 /* For mark_ptr_or_null_reg() */
7877 regs[BPF_REG_0].id = id;
7878 /* For release_reference() */
7879 regs[BPF_REG_0].ref_obj_id = id;
7880 }
7881
7882 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
7883
7884 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
7885 if (err)
7886 return err;
7887
7888 if ((func_id == BPF_FUNC_get_stack ||
7889 func_id == BPF_FUNC_get_task_stack) &&
7890 !env->prog->has_callchain_buf) {
7891 const char *err_str;
7892
7893 #ifdef CONFIG_PERF_EVENTS
7894 err = get_callchain_buffers(sysctl_perf_event_max_stack);
7895 err_str = "cannot get callchain buffer for func %s#%d\n";
7896 #else
7897 err = -ENOTSUPP;
7898 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
7899 #endif
7900 if (err) {
7901 verbose(env, err_str, func_id_name(func_id), func_id);
7902 return err;
7903 }
7904
7905 env->prog->has_callchain_buf = true;
7906 }
7907
7908 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
7909 env->prog->call_get_stack = true;
7910
7911 if (func_id == BPF_FUNC_get_func_ip) {
7912 if (check_get_func_ip(env))
7913 return -ENOTSUPP;
7914 env->prog->call_get_func_ip = true;
7915 }
7916
7917 if (changes_data)
7918 clear_all_pkt_pointers(env);
7919 return 0;
7920 }
7921
7922 /* mark_btf_func_reg_size() is used when the reg size is determined by
7923 * the BTF func_proto's return value size and argument.
7924 */
mark_btf_func_reg_size(struct bpf_verifier_env * env,u32 regno,size_t reg_size)7925 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
7926 size_t reg_size)
7927 {
7928 struct bpf_reg_state *reg = &cur_regs(env)[regno];
7929
7930 if (regno == BPF_REG_0) {
7931 /* Function return value */
7932 reg->live |= REG_LIVE_WRITTEN;
7933 reg->subreg_def = reg_size == sizeof(u64) ?
7934 DEF_NOT_SUBREG : env->insn_idx + 1;
7935 } else {
7936 /* Function argument */
7937 if (reg_size == sizeof(u64)) {
7938 mark_insn_zext(env, reg);
7939 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
7940 } else {
7941 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
7942 }
7943 }
7944 }
7945
check_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx_p)7946 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
7947 int *insn_idx_p)
7948 {
7949 const struct btf_type *t, *func, *func_proto, *ptr_type;
7950 struct bpf_reg_state *regs = cur_regs(env);
7951 struct bpf_kfunc_arg_meta meta = { 0 };
7952 const char *func_name, *ptr_type_name;
7953 u32 i, nargs, func_id, ptr_type_id;
7954 int err, insn_idx = *insn_idx_p;
7955 const struct btf_param *args;
7956 struct btf *desc_btf;
7957 u32 *kfunc_flags;
7958 bool acq;
7959
7960 /* skip for now, but return error when we find this in fixup_kfunc_call */
7961 if (!insn->imm)
7962 return 0;
7963
7964 desc_btf = find_kfunc_desc_btf(env, insn->off);
7965 if (IS_ERR(desc_btf))
7966 return PTR_ERR(desc_btf);
7967
7968 func_id = insn->imm;
7969 func = btf_type_by_id(desc_btf, func_id);
7970 func_name = btf_name_by_offset(desc_btf, func->name_off);
7971 func_proto = btf_type_by_id(desc_btf, func->type);
7972
7973 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id);
7974 if (!kfunc_flags) {
7975 verbose(env, "calling kernel function %s is not allowed\n",
7976 func_name);
7977 return -EACCES;
7978 }
7979 if (*kfunc_flags & KF_DESTRUCTIVE && !capable(CAP_SYS_BOOT)) {
7980 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capabilities\n");
7981 return -EACCES;
7982 }
7983
7984 acq = *kfunc_flags & KF_ACQUIRE;
7985
7986 meta.flags = *kfunc_flags;
7987
7988 /* Check the arguments */
7989 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs, &meta);
7990 if (err < 0)
7991 return err;
7992 /* In case of release function, we get register number of refcounted
7993 * PTR_TO_BTF_ID back from btf_check_kfunc_arg_match, do the release now
7994 */
7995 if (err) {
7996 err = release_reference(env, regs[err].ref_obj_id);
7997 if (err) {
7998 verbose(env, "kfunc %s#%d reference has not been acquired before\n",
7999 func_name, func_id);
8000 return err;
8001 }
8002 }
8003
8004 for (i = 0; i < CALLER_SAVED_REGS; i++)
8005 mark_reg_not_init(env, regs, caller_saved[i]);
8006
8007 /* Check return type */
8008 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
8009
8010 if (acq && !btf_type_is_struct_ptr(desc_btf, t)) {
8011 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
8012 return -EINVAL;
8013 }
8014
8015 if (btf_type_is_scalar(t)) {
8016 mark_reg_unknown(env, regs, BPF_REG_0);
8017 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
8018 } else if (btf_type_is_ptr(t)) {
8019 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
8020 &ptr_type_id);
8021 if (!btf_type_is_struct(ptr_type)) {
8022 if (!meta.r0_size) {
8023 ptr_type_name = btf_name_by_offset(desc_btf,
8024 ptr_type->name_off);
8025 verbose(env,
8026 "kernel function %s returns pointer type %s %s is not supported\n",
8027 func_name,
8028 btf_type_str(ptr_type),
8029 ptr_type_name);
8030 return -EINVAL;
8031 }
8032
8033 mark_reg_known_zero(env, regs, BPF_REG_0);
8034 regs[BPF_REG_0].type = PTR_TO_MEM;
8035 regs[BPF_REG_0].mem_size = meta.r0_size;
8036
8037 if (meta.r0_rdonly)
8038 regs[BPF_REG_0].type |= MEM_RDONLY;
8039
8040 /* Ensures we don't access the memory after a release_reference() */
8041 if (meta.ref_obj_id)
8042 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
8043 } else {
8044 mark_reg_known_zero(env, regs, BPF_REG_0);
8045 regs[BPF_REG_0].btf = desc_btf;
8046 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
8047 regs[BPF_REG_0].btf_id = ptr_type_id;
8048 }
8049 if (*kfunc_flags & KF_RET_NULL) {
8050 regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
8051 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
8052 regs[BPF_REG_0].id = ++env->id_gen;
8053 }
8054 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
8055 if (acq) {
8056 int id = acquire_reference_state(env, insn_idx);
8057
8058 if (id < 0)
8059 return id;
8060 regs[BPF_REG_0].id = id;
8061 regs[BPF_REG_0].ref_obj_id = id;
8062 }
8063 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
8064
8065 nargs = btf_type_vlen(func_proto);
8066 args = (const struct btf_param *)(func_proto + 1);
8067 for (i = 0; i < nargs; i++) {
8068 u32 regno = i + 1;
8069
8070 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
8071 if (btf_type_is_ptr(t))
8072 mark_btf_func_reg_size(env, regno, sizeof(void *));
8073 else
8074 /* scalar. ensured by btf_check_kfunc_arg_match() */
8075 mark_btf_func_reg_size(env, regno, t->size);
8076 }
8077
8078 return 0;
8079 }
8080
signed_add_overflows(s64 a,s64 b)8081 static bool signed_add_overflows(s64 a, s64 b)
8082 {
8083 /* Do the add in u64, where overflow is well-defined */
8084 s64 res = (s64)((u64)a + (u64)b);
8085
8086 if (b < 0)
8087 return res > a;
8088 return res < a;
8089 }
8090
signed_add32_overflows(s32 a,s32 b)8091 static bool signed_add32_overflows(s32 a, s32 b)
8092 {
8093 /* Do the add in u32, where overflow is well-defined */
8094 s32 res = (s32)((u32)a + (u32)b);
8095
8096 if (b < 0)
8097 return res > a;
8098 return res < a;
8099 }
8100
signed_sub_overflows(s64 a,s64 b)8101 static bool signed_sub_overflows(s64 a, s64 b)
8102 {
8103 /* Do the sub in u64, where overflow is well-defined */
8104 s64 res = (s64)((u64)a - (u64)b);
8105
8106 if (b < 0)
8107 return res < a;
8108 return res > a;
8109 }
8110
signed_sub32_overflows(s32 a,s32 b)8111 static bool signed_sub32_overflows(s32 a, s32 b)
8112 {
8113 /* Do the sub in u32, where overflow is well-defined */
8114 s32 res = (s32)((u32)a - (u32)b);
8115
8116 if (b < 0)
8117 return res < a;
8118 return res > a;
8119 }
8120
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)8121 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
8122 const struct bpf_reg_state *reg,
8123 enum bpf_reg_type type)
8124 {
8125 bool known = tnum_is_const(reg->var_off);
8126 s64 val = reg->var_off.value;
8127 s64 smin = reg->smin_value;
8128
8129 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
8130 verbose(env, "math between %s pointer and %lld is not allowed\n",
8131 reg_type_str(env, type), val);
8132 return false;
8133 }
8134
8135 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
8136 verbose(env, "%s pointer offset %d is not allowed\n",
8137 reg_type_str(env, type), reg->off);
8138 return false;
8139 }
8140
8141 if (smin == S64_MIN) {
8142 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
8143 reg_type_str(env, type));
8144 return false;
8145 }
8146
8147 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
8148 verbose(env, "value %lld makes %s pointer be out of bounds\n",
8149 smin, reg_type_str(env, type));
8150 return false;
8151 }
8152
8153 return true;
8154 }
8155
8156 enum {
8157 REASON_BOUNDS = -1,
8158 REASON_TYPE = -2,
8159 REASON_PATHS = -3,
8160 REASON_LIMIT = -4,
8161 REASON_STACK = -5,
8162 };
8163
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)8164 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
8165 u32 *alu_limit, bool mask_to_left)
8166 {
8167 u32 max = 0, ptr_limit = 0;
8168
8169 switch (ptr_reg->type) {
8170 case PTR_TO_STACK:
8171 /* Offset 0 is out-of-bounds, but acceptable start for the
8172 * left direction, see BPF_REG_FP. Also, unknown scalar
8173 * offset where we would need to deal with min/max bounds is
8174 * currently prohibited for unprivileged.
8175 */
8176 max = MAX_BPF_STACK + mask_to_left;
8177 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
8178 break;
8179 case PTR_TO_MAP_VALUE:
8180 max = ptr_reg->map_ptr->value_size;
8181 ptr_limit = (mask_to_left ?
8182 ptr_reg->smin_value :
8183 ptr_reg->umax_value) + ptr_reg->off;
8184 break;
8185 default:
8186 return REASON_TYPE;
8187 }
8188
8189 if (ptr_limit >= max)
8190 return REASON_LIMIT;
8191 *alu_limit = ptr_limit;
8192 return 0;
8193 }
8194
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)8195 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
8196 const struct bpf_insn *insn)
8197 {
8198 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
8199 }
8200
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)8201 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
8202 u32 alu_state, u32 alu_limit)
8203 {
8204 /* If we arrived here from different branches with different
8205 * state or limits to sanitize, then this won't work.
8206 */
8207 if (aux->alu_state &&
8208 (aux->alu_state != alu_state ||
8209 aux->alu_limit != alu_limit))
8210 return REASON_PATHS;
8211
8212 /* Corresponding fixup done in do_misc_fixups(). */
8213 aux->alu_state = alu_state;
8214 aux->alu_limit = alu_limit;
8215 return 0;
8216 }
8217
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)8218 static int sanitize_val_alu(struct bpf_verifier_env *env,
8219 struct bpf_insn *insn)
8220 {
8221 struct bpf_insn_aux_data *aux = cur_aux(env);
8222
8223 if (can_skip_alu_sanitation(env, insn))
8224 return 0;
8225
8226 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
8227 }
8228
sanitize_needed(u8 opcode)8229 static bool sanitize_needed(u8 opcode)
8230 {
8231 return opcode == BPF_ADD || opcode == BPF_SUB;
8232 }
8233
8234 struct bpf_sanitize_info {
8235 struct bpf_insn_aux_data aux;
8236 bool mask_to_left;
8237 };
8238
8239 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)8240 sanitize_speculative_path(struct bpf_verifier_env *env,
8241 const struct bpf_insn *insn,
8242 u32 next_idx, u32 curr_idx)
8243 {
8244 struct bpf_verifier_state *branch;
8245 struct bpf_reg_state *regs;
8246
8247 branch = push_stack(env, next_idx, curr_idx, true);
8248 if (branch && insn) {
8249 regs = branch->frame[branch->curframe]->regs;
8250 if (BPF_SRC(insn->code) == BPF_K) {
8251 mark_reg_unknown(env, regs, insn->dst_reg);
8252 } else if (BPF_SRC(insn->code) == BPF_X) {
8253 mark_reg_unknown(env, regs, insn->dst_reg);
8254 mark_reg_unknown(env, regs, insn->src_reg);
8255 }
8256 }
8257 return branch;
8258 }
8259
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)8260 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
8261 struct bpf_insn *insn,
8262 const struct bpf_reg_state *ptr_reg,
8263 const struct bpf_reg_state *off_reg,
8264 struct bpf_reg_state *dst_reg,
8265 struct bpf_sanitize_info *info,
8266 const bool commit_window)
8267 {
8268 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
8269 struct bpf_verifier_state *vstate = env->cur_state;
8270 bool off_is_imm = tnum_is_const(off_reg->var_off);
8271 bool off_is_neg = off_reg->smin_value < 0;
8272 bool ptr_is_dst_reg = ptr_reg == dst_reg;
8273 u8 opcode = BPF_OP(insn->code);
8274 u32 alu_state, alu_limit;
8275 struct bpf_reg_state tmp;
8276 bool ret;
8277 int err;
8278
8279 if (can_skip_alu_sanitation(env, insn))
8280 return 0;
8281
8282 /* We already marked aux for masking from non-speculative
8283 * paths, thus we got here in the first place. We only care
8284 * to explore bad access from here.
8285 */
8286 if (vstate->speculative)
8287 goto do_sim;
8288
8289 if (!commit_window) {
8290 if (!tnum_is_const(off_reg->var_off) &&
8291 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
8292 return REASON_BOUNDS;
8293
8294 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
8295 (opcode == BPF_SUB && !off_is_neg);
8296 }
8297
8298 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
8299 if (err < 0)
8300 return err;
8301
8302 if (commit_window) {
8303 /* In commit phase we narrow the masking window based on
8304 * the observed pointer move after the simulated operation.
8305 */
8306 alu_state = info->aux.alu_state;
8307 alu_limit = abs(info->aux.alu_limit - alu_limit);
8308 } else {
8309 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
8310 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
8311 alu_state |= ptr_is_dst_reg ?
8312 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
8313
8314 /* Limit pruning on unknown scalars to enable deep search for
8315 * potential masking differences from other program paths.
8316 */
8317 if (!off_is_imm)
8318 env->explore_alu_limits = true;
8319 }
8320
8321 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
8322 if (err < 0)
8323 return err;
8324 do_sim:
8325 /* If we're in commit phase, we're done here given we already
8326 * pushed the truncated dst_reg into the speculative verification
8327 * stack.
8328 *
8329 * Also, when register is a known constant, we rewrite register-based
8330 * operation to immediate-based, and thus do not need masking (and as
8331 * a consequence, do not need to simulate the zero-truncation either).
8332 */
8333 if (commit_window || off_is_imm)
8334 return 0;
8335
8336 /* Simulate and find potential out-of-bounds access under
8337 * speculative execution from truncation as a result of
8338 * masking when off was not within expected range. If off
8339 * sits in dst, then we temporarily need to move ptr there
8340 * to simulate dst (== 0) +/-= ptr. Needed, for example,
8341 * for cases where we use K-based arithmetic in one direction
8342 * and truncated reg-based in the other in order to explore
8343 * bad access.
8344 */
8345 if (!ptr_is_dst_reg) {
8346 tmp = *dst_reg;
8347 copy_register_state(dst_reg, ptr_reg);
8348 }
8349 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
8350 env->insn_idx);
8351 if (!ptr_is_dst_reg && ret)
8352 *dst_reg = tmp;
8353 return !ret ? REASON_STACK : 0;
8354 }
8355
sanitize_mark_insn_seen(struct bpf_verifier_env * env)8356 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
8357 {
8358 struct bpf_verifier_state *vstate = env->cur_state;
8359
8360 /* If we simulate paths under speculation, we don't update the
8361 * insn as 'seen' such that when we verify unreachable paths in
8362 * the non-speculative domain, sanitize_dead_code() can still
8363 * rewrite/sanitize them.
8364 */
8365 if (!vstate->speculative)
8366 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
8367 }
8368
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)8369 static int sanitize_err(struct bpf_verifier_env *env,
8370 const struct bpf_insn *insn, int reason,
8371 const struct bpf_reg_state *off_reg,
8372 const struct bpf_reg_state *dst_reg)
8373 {
8374 static const char *err = "pointer arithmetic with it prohibited for !root";
8375 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
8376 u32 dst = insn->dst_reg, src = insn->src_reg;
8377
8378 switch (reason) {
8379 case REASON_BOUNDS:
8380 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
8381 off_reg == dst_reg ? dst : src, err);
8382 break;
8383 case REASON_TYPE:
8384 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
8385 off_reg == dst_reg ? src : dst, err);
8386 break;
8387 case REASON_PATHS:
8388 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
8389 dst, op, err);
8390 break;
8391 case REASON_LIMIT:
8392 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
8393 dst, op, err);
8394 break;
8395 case REASON_STACK:
8396 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
8397 dst, err);
8398 break;
8399 default:
8400 verbose(env, "verifier internal error: unknown reason (%d)\n",
8401 reason);
8402 break;
8403 }
8404
8405 return -EACCES;
8406 }
8407
8408 /* check that stack access falls within stack limits and that 'reg' doesn't
8409 * have a variable offset.
8410 *
8411 * Variable offset is prohibited for unprivileged mode for simplicity since it
8412 * requires corresponding support in Spectre masking for stack ALU. See also
8413 * retrieve_ptr_limit().
8414 *
8415 *
8416 * 'off' includes 'reg->off'.
8417 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)8418 static int check_stack_access_for_ptr_arithmetic(
8419 struct bpf_verifier_env *env,
8420 int regno,
8421 const struct bpf_reg_state *reg,
8422 int off)
8423 {
8424 if (!tnum_is_const(reg->var_off)) {
8425 char tn_buf[48];
8426
8427 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8428 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
8429 regno, tn_buf, off);
8430 return -EACCES;
8431 }
8432
8433 if (off >= 0 || off < -MAX_BPF_STACK) {
8434 verbose(env, "R%d stack pointer arithmetic goes out of range, "
8435 "prohibited for !root; off=%d\n", regno, off);
8436 return -EACCES;
8437 }
8438
8439 return 0;
8440 }
8441
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)8442 static int sanitize_check_bounds(struct bpf_verifier_env *env,
8443 const struct bpf_insn *insn,
8444 const struct bpf_reg_state *dst_reg)
8445 {
8446 u32 dst = insn->dst_reg;
8447
8448 /* For unprivileged we require that resulting offset must be in bounds
8449 * in order to be able to sanitize access later on.
8450 */
8451 if (env->bypass_spec_v1)
8452 return 0;
8453
8454 switch (dst_reg->type) {
8455 case PTR_TO_STACK:
8456 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
8457 dst_reg->off + dst_reg->var_off.value))
8458 return -EACCES;
8459 break;
8460 case PTR_TO_MAP_VALUE:
8461 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
8462 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
8463 "prohibited for !root\n", dst);
8464 return -EACCES;
8465 }
8466 break;
8467 default:
8468 break;
8469 }
8470
8471 return 0;
8472 }
8473
8474 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
8475 * Caller should also handle BPF_MOV case separately.
8476 * If we return -EACCES, caller may want to try again treating pointer as a
8477 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
8478 */
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)8479 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
8480 struct bpf_insn *insn,
8481 const struct bpf_reg_state *ptr_reg,
8482 const struct bpf_reg_state *off_reg)
8483 {
8484 struct bpf_verifier_state *vstate = env->cur_state;
8485 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8486 struct bpf_reg_state *regs = state->regs, *dst_reg;
8487 bool known = tnum_is_const(off_reg->var_off);
8488 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
8489 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
8490 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
8491 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
8492 struct bpf_sanitize_info info = {};
8493 u8 opcode = BPF_OP(insn->code);
8494 u32 dst = insn->dst_reg;
8495 int ret;
8496
8497 dst_reg = ®s[dst];
8498
8499 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
8500 smin_val > smax_val || umin_val > umax_val) {
8501 /* Taint dst register if offset had invalid bounds derived from
8502 * e.g. dead branches.
8503 */
8504 __mark_reg_unknown(env, dst_reg);
8505 return 0;
8506 }
8507
8508 if (BPF_CLASS(insn->code) != BPF_ALU64) {
8509 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
8510 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
8511 __mark_reg_unknown(env, dst_reg);
8512 return 0;
8513 }
8514
8515 verbose(env,
8516 "R%d 32-bit pointer arithmetic prohibited\n",
8517 dst);
8518 return -EACCES;
8519 }
8520
8521 if (ptr_reg->type & PTR_MAYBE_NULL) {
8522 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
8523 dst, reg_type_str(env, ptr_reg->type));
8524 return -EACCES;
8525 }
8526
8527 switch (base_type(ptr_reg->type)) {
8528 case PTR_TO_FLOW_KEYS:
8529 if (known)
8530 break;
8531 fallthrough;
8532 case CONST_PTR_TO_MAP:
8533 /* smin_val represents the known value */
8534 if (known && smin_val == 0 && opcode == BPF_ADD)
8535 break;
8536 fallthrough;
8537 case PTR_TO_PACKET_END:
8538 case PTR_TO_SOCKET:
8539 case PTR_TO_SOCK_COMMON:
8540 case PTR_TO_TCP_SOCK:
8541 case PTR_TO_XDP_SOCK:
8542 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
8543 dst, reg_type_str(env, ptr_reg->type));
8544 return -EACCES;
8545 default:
8546 break;
8547 }
8548
8549 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
8550 * The id may be overwritten later if we create a new variable offset.
8551 */
8552 dst_reg->type = ptr_reg->type;
8553 dst_reg->id = ptr_reg->id;
8554
8555 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
8556 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
8557 return -EINVAL;
8558
8559 /* pointer types do not carry 32-bit bounds at the moment. */
8560 __mark_reg32_unbounded(dst_reg);
8561
8562 if (sanitize_needed(opcode)) {
8563 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
8564 &info, false);
8565 if (ret < 0)
8566 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8567 }
8568
8569 switch (opcode) {
8570 case BPF_ADD:
8571 /* We can take a fixed offset as long as it doesn't overflow
8572 * the s32 'off' field
8573 */
8574 if (known && (ptr_reg->off + smin_val ==
8575 (s64)(s32)(ptr_reg->off + smin_val))) {
8576 /* pointer += K. Accumulate it into fixed offset */
8577 dst_reg->smin_value = smin_ptr;
8578 dst_reg->smax_value = smax_ptr;
8579 dst_reg->umin_value = umin_ptr;
8580 dst_reg->umax_value = umax_ptr;
8581 dst_reg->var_off = ptr_reg->var_off;
8582 dst_reg->off = ptr_reg->off + smin_val;
8583 dst_reg->raw = ptr_reg->raw;
8584 break;
8585 }
8586 /* A new variable offset is created. Note that off_reg->off
8587 * == 0, since it's a scalar.
8588 * dst_reg gets the pointer type and since some positive
8589 * integer value was added to the pointer, give it a new 'id'
8590 * if it's a PTR_TO_PACKET.
8591 * this creates a new 'base' pointer, off_reg (variable) gets
8592 * added into the variable offset, and we copy the fixed offset
8593 * from ptr_reg.
8594 */
8595 if (signed_add_overflows(smin_ptr, smin_val) ||
8596 signed_add_overflows(smax_ptr, smax_val)) {
8597 dst_reg->smin_value = S64_MIN;
8598 dst_reg->smax_value = S64_MAX;
8599 } else {
8600 dst_reg->smin_value = smin_ptr + smin_val;
8601 dst_reg->smax_value = smax_ptr + smax_val;
8602 }
8603 if (umin_ptr + umin_val < umin_ptr ||
8604 umax_ptr + umax_val < umax_ptr) {
8605 dst_reg->umin_value = 0;
8606 dst_reg->umax_value = U64_MAX;
8607 } else {
8608 dst_reg->umin_value = umin_ptr + umin_val;
8609 dst_reg->umax_value = umax_ptr + umax_val;
8610 }
8611 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
8612 dst_reg->off = ptr_reg->off;
8613 dst_reg->raw = ptr_reg->raw;
8614 if (reg_is_pkt_pointer(ptr_reg)) {
8615 dst_reg->id = ++env->id_gen;
8616 /* something was added to pkt_ptr, set range to zero */
8617 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8618 }
8619 break;
8620 case BPF_SUB:
8621 if (dst_reg == off_reg) {
8622 /* scalar -= pointer. Creates an unknown scalar */
8623 verbose(env, "R%d tried to subtract pointer from scalar\n",
8624 dst);
8625 return -EACCES;
8626 }
8627 /* We don't allow subtraction from FP, because (according to
8628 * test_verifier.c test "invalid fp arithmetic", JITs might not
8629 * be able to deal with it.
8630 */
8631 if (ptr_reg->type == PTR_TO_STACK) {
8632 verbose(env, "R%d subtraction from stack pointer prohibited\n",
8633 dst);
8634 return -EACCES;
8635 }
8636 if (known && (ptr_reg->off - smin_val ==
8637 (s64)(s32)(ptr_reg->off - smin_val))) {
8638 /* pointer -= K. Subtract it from fixed offset */
8639 dst_reg->smin_value = smin_ptr;
8640 dst_reg->smax_value = smax_ptr;
8641 dst_reg->umin_value = umin_ptr;
8642 dst_reg->umax_value = umax_ptr;
8643 dst_reg->var_off = ptr_reg->var_off;
8644 dst_reg->id = ptr_reg->id;
8645 dst_reg->off = ptr_reg->off - smin_val;
8646 dst_reg->raw = ptr_reg->raw;
8647 break;
8648 }
8649 /* A new variable offset is created. If the subtrahend is known
8650 * nonnegative, then any reg->range we had before is still good.
8651 */
8652 if (signed_sub_overflows(smin_ptr, smax_val) ||
8653 signed_sub_overflows(smax_ptr, smin_val)) {
8654 /* Overflow possible, we know nothing */
8655 dst_reg->smin_value = S64_MIN;
8656 dst_reg->smax_value = S64_MAX;
8657 } else {
8658 dst_reg->smin_value = smin_ptr - smax_val;
8659 dst_reg->smax_value = smax_ptr - smin_val;
8660 }
8661 if (umin_ptr < umax_val) {
8662 /* Overflow possible, we know nothing */
8663 dst_reg->umin_value = 0;
8664 dst_reg->umax_value = U64_MAX;
8665 } else {
8666 /* Cannot overflow (as long as bounds are consistent) */
8667 dst_reg->umin_value = umin_ptr - umax_val;
8668 dst_reg->umax_value = umax_ptr - umin_val;
8669 }
8670 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
8671 dst_reg->off = ptr_reg->off;
8672 dst_reg->raw = ptr_reg->raw;
8673 if (reg_is_pkt_pointer(ptr_reg)) {
8674 dst_reg->id = ++env->id_gen;
8675 /* something was added to pkt_ptr, set range to zero */
8676 if (smin_val < 0)
8677 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
8678 }
8679 break;
8680 case BPF_AND:
8681 case BPF_OR:
8682 case BPF_XOR:
8683 /* bitwise ops on pointers are troublesome, prohibit. */
8684 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
8685 dst, bpf_alu_string[opcode >> 4]);
8686 return -EACCES;
8687 default:
8688 /* other operators (e.g. MUL,LSH) produce non-pointer results */
8689 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
8690 dst, bpf_alu_string[opcode >> 4]);
8691 return -EACCES;
8692 }
8693
8694 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
8695 return -EINVAL;
8696 reg_bounds_sync(dst_reg);
8697 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
8698 return -EACCES;
8699 if (sanitize_needed(opcode)) {
8700 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
8701 &info, true);
8702 if (ret < 0)
8703 return sanitize_err(env, insn, ret, off_reg, dst_reg);
8704 }
8705
8706 return 0;
8707 }
8708
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8709 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
8710 struct bpf_reg_state *src_reg)
8711 {
8712 s32 smin_val = src_reg->s32_min_value;
8713 s32 smax_val = src_reg->s32_max_value;
8714 u32 umin_val = src_reg->u32_min_value;
8715 u32 umax_val = src_reg->u32_max_value;
8716
8717 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
8718 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
8719 dst_reg->s32_min_value = S32_MIN;
8720 dst_reg->s32_max_value = S32_MAX;
8721 } else {
8722 dst_reg->s32_min_value += smin_val;
8723 dst_reg->s32_max_value += smax_val;
8724 }
8725 if (dst_reg->u32_min_value + umin_val < umin_val ||
8726 dst_reg->u32_max_value + umax_val < umax_val) {
8727 dst_reg->u32_min_value = 0;
8728 dst_reg->u32_max_value = U32_MAX;
8729 } else {
8730 dst_reg->u32_min_value += umin_val;
8731 dst_reg->u32_max_value += umax_val;
8732 }
8733 }
8734
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8735 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
8736 struct bpf_reg_state *src_reg)
8737 {
8738 s64 smin_val = src_reg->smin_value;
8739 s64 smax_val = src_reg->smax_value;
8740 u64 umin_val = src_reg->umin_value;
8741 u64 umax_val = src_reg->umax_value;
8742
8743 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
8744 signed_add_overflows(dst_reg->smax_value, smax_val)) {
8745 dst_reg->smin_value = S64_MIN;
8746 dst_reg->smax_value = S64_MAX;
8747 } else {
8748 dst_reg->smin_value += smin_val;
8749 dst_reg->smax_value += smax_val;
8750 }
8751 if (dst_reg->umin_value + umin_val < umin_val ||
8752 dst_reg->umax_value + umax_val < umax_val) {
8753 dst_reg->umin_value = 0;
8754 dst_reg->umax_value = U64_MAX;
8755 } else {
8756 dst_reg->umin_value += umin_val;
8757 dst_reg->umax_value += umax_val;
8758 }
8759 }
8760
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8761 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
8762 struct bpf_reg_state *src_reg)
8763 {
8764 s32 smin_val = src_reg->s32_min_value;
8765 s32 smax_val = src_reg->s32_max_value;
8766 u32 umin_val = src_reg->u32_min_value;
8767 u32 umax_val = src_reg->u32_max_value;
8768
8769 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
8770 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
8771 /* Overflow possible, we know nothing */
8772 dst_reg->s32_min_value = S32_MIN;
8773 dst_reg->s32_max_value = S32_MAX;
8774 } else {
8775 dst_reg->s32_min_value -= smax_val;
8776 dst_reg->s32_max_value -= smin_val;
8777 }
8778 if (dst_reg->u32_min_value < umax_val) {
8779 /* Overflow possible, we know nothing */
8780 dst_reg->u32_min_value = 0;
8781 dst_reg->u32_max_value = U32_MAX;
8782 } else {
8783 /* Cannot overflow (as long as bounds are consistent) */
8784 dst_reg->u32_min_value -= umax_val;
8785 dst_reg->u32_max_value -= umin_val;
8786 }
8787 }
8788
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8789 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
8790 struct bpf_reg_state *src_reg)
8791 {
8792 s64 smin_val = src_reg->smin_value;
8793 s64 smax_val = src_reg->smax_value;
8794 u64 umin_val = src_reg->umin_value;
8795 u64 umax_val = src_reg->umax_value;
8796
8797 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
8798 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
8799 /* Overflow possible, we know nothing */
8800 dst_reg->smin_value = S64_MIN;
8801 dst_reg->smax_value = S64_MAX;
8802 } else {
8803 dst_reg->smin_value -= smax_val;
8804 dst_reg->smax_value -= smin_val;
8805 }
8806 if (dst_reg->umin_value < umax_val) {
8807 /* Overflow possible, we know nothing */
8808 dst_reg->umin_value = 0;
8809 dst_reg->umax_value = U64_MAX;
8810 } else {
8811 /* Cannot overflow (as long as bounds are consistent) */
8812 dst_reg->umin_value -= umax_val;
8813 dst_reg->umax_value -= umin_val;
8814 }
8815 }
8816
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8817 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
8818 struct bpf_reg_state *src_reg)
8819 {
8820 s32 smin_val = src_reg->s32_min_value;
8821 u32 umin_val = src_reg->u32_min_value;
8822 u32 umax_val = src_reg->u32_max_value;
8823
8824 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
8825 /* Ain't nobody got time to multiply that sign */
8826 __mark_reg32_unbounded(dst_reg);
8827 return;
8828 }
8829 /* Both values are positive, so we can work with unsigned and
8830 * copy the result to signed (unless it exceeds S32_MAX).
8831 */
8832 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
8833 /* Potential overflow, we know nothing */
8834 __mark_reg32_unbounded(dst_reg);
8835 return;
8836 }
8837 dst_reg->u32_min_value *= umin_val;
8838 dst_reg->u32_max_value *= umax_val;
8839 if (dst_reg->u32_max_value > S32_MAX) {
8840 /* Overflow possible, we know nothing */
8841 dst_reg->s32_min_value = S32_MIN;
8842 dst_reg->s32_max_value = S32_MAX;
8843 } else {
8844 dst_reg->s32_min_value = dst_reg->u32_min_value;
8845 dst_reg->s32_max_value = dst_reg->u32_max_value;
8846 }
8847 }
8848
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8849 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
8850 struct bpf_reg_state *src_reg)
8851 {
8852 s64 smin_val = src_reg->smin_value;
8853 u64 umin_val = src_reg->umin_value;
8854 u64 umax_val = src_reg->umax_value;
8855
8856 if (smin_val < 0 || dst_reg->smin_value < 0) {
8857 /* Ain't nobody got time to multiply that sign */
8858 __mark_reg64_unbounded(dst_reg);
8859 return;
8860 }
8861 /* Both values are positive, so we can work with unsigned and
8862 * copy the result to signed (unless it exceeds S64_MAX).
8863 */
8864 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
8865 /* Potential overflow, we know nothing */
8866 __mark_reg64_unbounded(dst_reg);
8867 return;
8868 }
8869 dst_reg->umin_value *= umin_val;
8870 dst_reg->umax_value *= umax_val;
8871 if (dst_reg->umax_value > S64_MAX) {
8872 /* Overflow possible, we know nothing */
8873 dst_reg->smin_value = S64_MIN;
8874 dst_reg->smax_value = S64_MAX;
8875 } else {
8876 dst_reg->smin_value = dst_reg->umin_value;
8877 dst_reg->smax_value = dst_reg->umax_value;
8878 }
8879 }
8880
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8881 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
8882 struct bpf_reg_state *src_reg)
8883 {
8884 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8885 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8886 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8887 s32 smin_val = src_reg->s32_min_value;
8888 u32 umax_val = src_reg->u32_max_value;
8889
8890 if (src_known && dst_known) {
8891 __mark_reg32_known(dst_reg, var32_off.value);
8892 return;
8893 }
8894
8895 /* We get our minimum from the var_off, since that's inherently
8896 * bitwise. Our maximum is the minimum of the operands' maxima.
8897 */
8898 dst_reg->u32_min_value = var32_off.value;
8899 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
8900 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8901 /* Lose signed bounds when ANDing negative numbers,
8902 * ain't nobody got time for that.
8903 */
8904 dst_reg->s32_min_value = S32_MIN;
8905 dst_reg->s32_max_value = S32_MAX;
8906 } else {
8907 /* ANDing two positives gives a positive, so safe to
8908 * cast result into s64.
8909 */
8910 dst_reg->s32_min_value = dst_reg->u32_min_value;
8911 dst_reg->s32_max_value = dst_reg->u32_max_value;
8912 }
8913 }
8914
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8915 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
8916 struct bpf_reg_state *src_reg)
8917 {
8918 bool src_known = tnum_is_const(src_reg->var_off);
8919 bool dst_known = tnum_is_const(dst_reg->var_off);
8920 s64 smin_val = src_reg->smin_value;
8921 u64 umax_val = src_reg->umax_value;
8922
8923 if (src_known && dst_known) {
8924 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8925 return;
8926 }
8927
8928 /* We get our minimum from the var_off, since that's inherently
8929 * bitwise. Our maximum is the minimum of the operands' maxima.
8930 */
8931 dst_reg->umin_value = dst_reg->var_off.value;
8932 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
8933 if (dst_reg->smin_value < 0 || smin_val < 0) {
8934 /* Lose signed bounds when ANDing negative numbers,
8935 * ain't nobody got time for that.
8936 */
8937 dst_reg->smin_value = S64_MIN;
8938 dst_reg->smax_value = S64_MAX;
8939 } else {
8940 /* ANDing two positives gives a positive, so safe to
8941 * cast result into s64.
8942 */
8943 dst_reg->smin_value = dst_reg->umin_value;
8944 dst_reg->smax_value = dst_reg->umax_value;
8945 }
8946 /* We may learn something more from the var_off */
8947 __update_reg_bounds(dst_reg);
8948 }
8949
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8950 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
8951 struct bpf_reg_state *src_reg)
8952 {
8953 bool src_known = tnum_subreg_is_const(src_reg->var_off);
8954 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
8955 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
8956 s32 smin_val = src_reg->s32_min_value;
8957 u32 umin_val = src_reg->u32_min_value;
8958
8959 if (src_known && dst_known) {
8960 __mark_reg32_known(dst_reg, var32_off.value);
8961 return;
8962 }
8963
8964 /* We get our maximum from the var_off, and our minimum is the
8965 * maximum of the operands' minima
8966 */
8967 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
8968 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
8969 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
8970 /* Lose signed bounds when ORing negative numbers,
8971 * ain't nobody got time for that.
8972 */
8973 dst_reg->s32_min_value = S32_MIN;
8974 dst_reg->s32_max_value = S32_MAX;
8975 } else {
8976 /* ORing two positives gives a positive, so safe to
8977 * cast result into s64.
8978 */
8979 dst_reg->s32_min_value = dst_reg->u32_min_value;
8980 dst_reg->s32_max_value = dst_reg->u32_max_value;
8981 }
8982 }
8983
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)8984 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
8985 struct bpf_reg_state *src_reg)
8986 {
8987 bool src_known = tnum_is_const(src_reg->var_off);
8988 bool dst_known = tnum_is_const(dst_reg->var_off);
8989 s64 smin_val = src_reg->smin_value;
8990 u64 umin_val = src_reg->umin_value;
8991
8992 if (src_known && dst_known) {
8993 __mark_reg_known(dst_reg, dst_reg->var_off.value);
8994 return;
8995 }
8996
8997 /* We get our maximum from the var_off, and our minimum is the
8998 * maximum of the operands' minima
8999 */
9000 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
9001 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9002 if (dst_reg->smin_value < 0 || smin_val < 0) {
9003 /* Lose signed bounds when ORing negative numbers,
9004 * ain't nobody got time for that.
9005 */
9006 dst_reg->smin_value = S64_MIN;
9007 dst_reg->smax_value = S64_MAX;
9008 } else {
9009 /* ORing two positives gives a positive, so safe to
9010 * cast result into s64.
9011 */
9012 dst_reg->smin_value = dst_reg->umin_value;
9013 dst_reg->smax_value = dst_reg->umax_value;
9014 }
9015 /* We may learn something more from the var_off */
9016 __update_reg_bounds(dst_reg);
9017 }
9018
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9019 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
9020 struct bpf_reg_state *src_reg)
9021 {
9022 bool src_known = tnum_subreg_is_const(src_reg->var_off);
9023 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
9024 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
9025 s32 smin_val = src_reg->s32_min_value;
9026
9027 if (src_known && dst_known) {
9028 __mark_reg32_known(dst_reg, var32_off.value);
9029 return;
9030 }
9031
9032 /* We get both minimum and maximum from the var32_off. */
9033 dst_reg->u32_min_value = var32_off.value;
9034 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
9035
9036 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
9037 /* XORing two positive sign numbers gives a positive,
9038 * so safe to cast u32 result into s32.
9039 */
9040 dst_reg->s32_min_value = dst_reg->u32_min_value;
9041 dst_reg->s32_max_value = dst_reg->u32_max_value;
9042 } else {
9043 dst_reg->s32_min_value = S32_MIN;
9044 dst_reg->s32_max_value = S32_MAX;
9045 }
9046 }
9047
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9048 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
9049 struct bpf_reg_state *src_reg)
9050 {
9051 bool src_known = tnum_is_const(src_reg->var_off);
9052 bool dst_known = tnum_is_const(dst_reg->var_off);
9053 s64 smin_val = src_reg->smin_value;
9054
9055 if (src_known && dst_known) {
9056 /* dst_reg->var_off.value has been updated earlier */
9057 __mark_reg_known(dst_reg, dst_reg->var_off.value);
9058 return;
9059 }
9060
9061 /* We get both minimum and maximum from the var_off. */
9062 dst_reg->umin_value = dst_reg->var_off.value;
9063 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
9064
9065 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
9066 /* XORing two positive sign numbers gives a positive,
9067 * so safe to cast u64 result into s64.
9068 */
9069 dst_reg->smin_value = dst_reg->umin_value;
9070 dst_reg->smax_value = dst_reg->umax_value;
9071 } else {
9072 dst_reg->smin_value = S64_MIN;
9073 dst_reg->smax_value = S64_MAX;
9074 }
9075
9076 __update_reg_bounds(dst_reg);
9077 }
9078
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)9079 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
9080 u64 umin_val, u64 umax_val)
9081 {
9082 /* We lose all sign bit information (except what we can pick
9083 * up from var_off)
9084 */
9085 dst_reg->s32_min_value = S32_MIN;
9086 dst_reg->s32_max_value = S32_MAX;
9087 /* If we might shift our top bit out, then we know nothing */
9088 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
9089 dst_reg->u32_min_value = 0;
9090 dst_reg->u32_max_value = U32_MAX;
9091 } else {
9092 dst_reg->u32_min_value <<= umin_val;
9093 dst_reg->u32_max_value <<= umax_val;
9094 }
9095 }
9096
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9097 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
9098 struct bpf_reg_state *src_reg)
9099 {
9100 u32 umax_val = src_reg->u32_max_value;
9101 u32 umin_val = src_reg->u32_min_value;
9102 /* u32 alu operation will zext upper bits */
9103 struct tnum subreg = tnum_subreg(dst_reg->var_off);
9104
9105 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
9106 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
9107 /* Not required but being careful mark reg64 bounds as unknown so
9108 * that we are forced to pick them up from tnum and zext later and
9109 * if some path skips this step we are still safe.
9110 */
9111 __mark_reg64_unbounded(dst_reg);
9112 __update_reg32_bounds(dst_reg);
9113 }
9114
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)9115 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
9116 u64 umin_val, u64 umax_val)
9117 {
9118 /* Special case <<32 because it is a common compiler pattern to sign
9119 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
9120 * positive we know this shift will also be positive so we can track
9121 * bounds correctly. Otherwise we lose all sign bit information except
9122 * what we can pick up from var_off. Perhaps we can generalize this
9123 * later to shifts of any length.
9124 */
9125 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
9126 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
9127 else
9128 dst_reg->smax_value = S64_MAX;
9129
9130 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
9131 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
9132 else
9133 dst_reg->smin_value = S64_MIN;
9134
9135 /* If we might shift our top bit out, then we know nothing */
9136 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
9137 dst_reg->umin_value = 0;
9138 dst_reg->umax_value = U64_MAX;
9139 } else {
9140 dst_reg->umin_value <<= umin_val;
9141 dst_reg->umax_value <<= umax_val;
9142 }
9143 }
9144
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9145 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
9146 struct bpf_reg_state *src_reg)
9147 {
9148 u64 umax_val = src_reg->umax_value;
9149 u64 umin_val = src_reg->umin_value;
9150
9151 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
9152 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
9153 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
9154
9155 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
9156 /* We may learn something more from the var_off */
9157 __update_reg_bounds(dst_reg);
9158 }
9159
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9160 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
9161 struct bpf_reg_state *src_reg)
9162 {
9163 struct tnum subreg = tnum_subreg(dst_reg->var_off);
9164 u32 umax_val = src_reg->u32_max_value;
9165 u32 umin_val = src_reg->u32_min_value;
9166
9167 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
9168 * be negative, then either:
9169 * 1) src_reg might be zero, so the sign bit of the result is
9170 * unknown, so we lose our signed bounds
9171 * 2) it's known negative, thus the unsigned bounds capture the
9172 * signed bounds
9173 * 3) the signed bounds cross zero, so they tell us nothing
9174 * about the result
9175 * If the value in dst_reg is known nonnegative, then again the
9176 * unsigned bounds capture the signed bounds.
9177 * Thus, in all cases it suffices to blow away our signed bounds
9178 * and rely on inferring new ones from the unsigned bounds and
9179 * var_off of the result.
9180 */
9181 dst_reg->s32_min_value = S32_MIN;
9182 dst_reg->s32_max_value = S32_MAX;
9183
9184 dst_reg->var_off = tnum_rshift(subreg, umin_val);
9185 dst_reg->u32_min_value >>= umax_val;
9186 dst_reg->u32_max_value >>= umin_val;
9187
9188 __mark_reg64_unbounded(dst_reg);
9189 __update_reg32_bounds(dst_reg);
9190 }
9191
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9192 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
9193 struct bpf_reg_state *src_reg)
9194 {
9195 u64 umax_val = src_reg->umax_value;
9196 u64 umin_val = src_reg->umin_value;
9197
9198 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
9199 * be negative, then either:
9200 * 1) src_reg might be zero, so the sign bit of the result is
9201 * unknown, so we lose our signed bounds
9202 * 2) it's known negative, thus the unsigned bounds capture the
9203 * signed bounds
9204 * 3) the signed bounds cross zero, so they tell us nothing
9205 * about the result
9206 * If the value in dst_reg is known nonnegative, then again the
9207 * unsigned bounds capture the signed bounds.
9208 * Thus, in all cases it suffices to blow away our signed bounds
9209 * and rely on inferring new ones from the unsigned bounds and
9210 * var_off of the result.
9211 */
9212 dst_reg->smin_value = S64_MIN;
9213 dst_reg->smax_value = S64_MAX;
9214 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
9215 dst_reg->umin_value >>= umax_val;
9216 dst_reg->umax_value >>= umin_val;
9217
9218 /* Its not easy to operate on alu32 bounds here because it depends
9219 * on bits being shifted in. Take easy way out and mark unbounded
9220 * so we can recalculate later from tnum.
9221 */
9222 __mark_reg32_unbounded(dst_reg);
9223 __update_reg_bounds(dst_reg);
9224 }
9225
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9226 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
9227 struct bpf_reg_state *src_reg)
9228 {
9229 u64 umin_val = src_reg->u32_min_value;
9230
9231 /* Upon reaching here, src_known is true and
9232 * umax_val is equal to umin_val.
9233 */
9234 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
9235 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
9236
9237 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
9238
9239 /* blow away the dst_reg umin_value/umax_value and rely on
9240 * dst_reg var_off to refine the result.
9241 */
9242 dst_reg->u32_min_value = 0;
9243 dst_reg->u32_max_value = U32_MAX;
9244
9245 __mark_reg64_unbounded(dst_reg);
9246 __update_reg32_bounds(dst_reg);
9247 }
9248
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)9249 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
9250 struct bpf_reg_state *src_reg)
9251 {
9252 u64 umin_val = src_reg->umin_value;
9253
9254 /* Upon reaching here, src_known is true and umax_val is equal
9255 * to umin_val.
9256 */
9257 dst_reg->smin_value >>= umin_val;
9258 dst_reg->smax_value >>= umin_val;
9259
9260 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
9261
9262 /* blow away the dst_reg umin_value/umax_value and rely on
9263 * dst_reg var_off to refine the result.
9264 */
9265 dst_reg->umin_value = 0;
9266 dst_reg->umax_value = U64_MAX;
9267
9268 /* Its not easy to operate on alu32 bounds here because it depends
9269 * on bits being shifted in from upper 32-bits. Take easy way out
9270 * and mark unbounded so we can recalculate later from tnum.
9271 */
9272 __mark_reg32_unbounded(dst_reg);
9273 __update_reg_bounds(dst_reg);
9274 }
9275
9276 /* WARNING: This function does calculations on 64-bit values, but the actual
9277 * execution may occur on 32-bit values. Therefore, things like bitshifts
9278 * need extra checks in the 32-bit case.
9279 */
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)9280 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
9281 struct bpf_insn *insn,
9282 struct bpf_reg_state *dst_reg,
9283 struct bpf_reg_state src_reg)
9284 {
9285 struct bpf_reg_state *regs = cur_regs(env);
9286 u8 opcode = BPF_OP(insn->code);
9287 bool src_known;
9288 s64 smin_val, smax_val;
9289 u64 umin_val, umax_val;
9290 s32 s32_min_val, s32_max_val;
9291 u32 u32_min_val, u32_max_val;
9292 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
9293 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
9294 int ret;
9295
9296 smin_val = src_reg.smin_value;
9297 smax_val = src_reg.smax_value;
9298 umin_val = src_reg.umin_value;
9299 umax_val = src_reg.umax_value;
9300
9301 s32_min_val = src_reg.s32_min_value;
9302 s32_max_val = src_reg.s32_max_value;
9303 u32_min_val = src_reg.u32_min_value;
9304 u32_max_val = src_reg.u32_max_value;
9305
9306 if (alu32) {
9307 src_known = tnum_subreg_is_const(src_reg.var_off);
9308 if ((src_known &&
9309 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
9310 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
9311 /* Taint dst register if offset had invalid bounds
9312 * derived from e.g. dead branches.
9313 */
9314 __mark_reg_unknown(env, dst_reg);
9315 return 0;
9316 }
9317 } else {
9318 src_known = tnum_is_const(src_reg.var_off);
9319 if ((src_known &&
9320 (smin_val != smax_val || umin_val != umax_val)) ||
9321 smin_val > smax_val || umin_val > umax_val) {
9322 /* Taint dst register if offset had invalid bounds
9323 * derived from e.g. dead branches.
9324 */
9325 __mark_reg_unknown(env, dst_reg);
9326 return 0;
9327 }
9328 }
9329
9330 if (!src_known &&
9331 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
9332 __mark_reg_unknown(env, dst_reg);
9333 return 0;
9334 }
9335
9336 if (sanitize_needed(opcode)) {
9337 ret = sanitize_val_alu(env, insn);
9338 if (ret < 0)
9339 return sanitize_err(env, insn, ret, NULL, NULL);
9340 }
9341
9342 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
9343 * There are two classes of instructions: The first class we track both
9344 * alu32 and alu64 sign/unsigned bounds independently this provides the
9345 * greatest amount of precision when alu operations are mixed with jmp32
9346 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
9347 * and BPF_OR. This is possible because these ops have fairly easy to
9348 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
9349 * See alu32 verifier tests for examples. The second class of
9350 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
9351 * with regards to tracking sign/unsigned bounds because the bits may
9352 * cross subreg boundaries in the alu64 case. When this happens we mark
9353 * the reg unbounded in the subreg bound space and use the resulting
9354 * tnum to calculate an approximation of the sign/unsigned bounds.
9355 */
9356 switch (opcode) {
9357 case BPF_ADD:
9358 scalar32_min_max_add(dst_reg, &src_reg);
9359 scalar_min_max_add(dst_reg, &src_reg);
9360 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
9361 break;
9362 case BPF_SUB:
9363 scalar32_min_max_sub(dst_reg, &src_reg);
9364 scalar_min_max_sub(dst_reg, &src_reg);
9365 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
9366 break;
9367 case BPF_MUL:
9368 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
9369 scalar32_min_max_mul(dst_reg, &src_reg);
9370 scalar_min_max_mul(dst_reg, &src_reg);
9371 break;
9372 case BPF_AND:
9373 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
9374 scalar32_min_max_and(dst_reg, &src_reg);
9375 scalar_min_max_and(dst_reg, &src_reg);
9376 break;
9377 case BPF_OR:
9378 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
9379 scalar32_min_max_or(dst_reg, &src_reg);
9380 scalar_min_max_or(dst_reg, &src_reg);
9381 break;
9382 case BPF_XOR:
9383 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
9384 scalar32_min_max_xor(dst_reg, &src_reg);
9385 scalar_min_max_xor(dst_reg, &src_reg);
9386 break;
9387 case BPF_LSH:
9388 if (umax_val >= insn_bitness) {
9389 /* Shifts greater than 31 or 63 are undefined.
9390 * This includes shifts by a negative number.
9391 */
9392 mark_reg_unknown(env, regs, insn->dst_reg);
9393 break;
9394 }
9395 if (alu32)
9396 scalar32_min_max_lsh(dst_reg, &src_reg);
9397 else
9398 scalar_min_max_lsh(dst_reg, &src_reg);
9399 break;
9400 case BPF_RSH:
9401 if (umax_val >= insn_bitness) {
9402 /* Shifts greater than 31 or 63 are undefined.
9403 * This includes shifts by a negative number.
9404 */
9405 mark_reg_unknown(env, regs, insn->dst_reg);
9406 break;
9407 }
9408 if (alu32)
9409 scalar32_min_max_rsh(dst_reg, &src_reg);
9410 else
9411 scalar_min_max_rsh(dst_reg, &src_reg);
9412 break;
9413 case BPF_ARSH:
9414 if (umax_val >= insn_bitness) {
9415 /* Shifts greater than 31 or 63 are undefined.
9416 * This includes shifts by a negative number.
9417 */
9418 mark_reg_unknown(env, regs, insn->dst_reg);
9419 break;
9420 }
9421 if (alu32)
9422 scalar32_min_max_arsh(dst_reg, &src_reg);
9423 else
9424 scalar_min_max_arsh(dst_reg, &src_reg);
9425 break;
9426 default:
9427 mark_reg_unknown(env, regs, insn->dst_reg);
9428 break;
9429 }
9430
9431 /* ALU32 ops are zero extended into 64bit register */
9432 if (alu32)
9433 zext_32_to_64(dst_reg);
9434 reg_bounds_sync(dst_reg);
9435 return 0;
9436 }
9437
9438 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
9439 * and var_off.
9440 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)9441 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
9442 struct bpf_insn *insn)
9443 {
9444 struct bpf_verifier_state *vstate = env->cur_state;
9445 struct bpf_func_state *state = vstate->frame[vstate->curframe];
9446 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
9447 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
9448 u8 opcode = BPF_OP(insn->code);
9449 int err;
9450
9451 dst_reg = ®s[insn->dst_reg];
9452 src_reg = NULL;
9453 if (dst_reg->type != SCALAR_VALUE)
9454 ptr_reg = dst_reg;
9455 else
9456 /* Make sure ID is cleared otherwise dst_reg min/max could be
9457 * incorrectly propagated into other registers by find_equal_scalars()
9458 */
9459 dst_reg->id = 0;
9460 if (BPF_SRC(insn->code) == BPF_X) {
9461 src_reg = ®s[insn->src_reg];
9462 if (src_reg->type != SCALAR_VALUE) {
9463 if (dst_reg->type != SCALAR_VALUE) {
9464 /* Combining two pointers by any ALU op yields
9465 * an arbitrary scalar. Disallow all math except
9466 * pointer subtraction
9467 */
9468 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
9469 mark_reg_unknown(env, regs, insn->dst_reg);
9470 return 0;
9471 }
9472 verbose(env, "R%d pointer %s pointer prohibited\n",
9473 insn->dst_reg,
9474 bpf_alu_string[opcode >> 4]);
9475 return -EACCES;
9476 } else {
9477 /* scalar += pointer
9478 * This is legal, but we have to reverse our
9479 * src/dest handling in computing the range
9480 */
9481 err = mark_chain_precision(env, insn->dst_reg);
9482 if (err)
9483 return err;
9484 return adjust_ptr_min_max_vals(env, insn,
9485 src_reg, dst_reg);
9486 }
9487 } else if (ptr_reg) {
9488 /* pointer += scalar */
9489 err = mark_chain_precision(env, insn->src_reg);
9490 if (err)
9491 return err;
9492 return adjust_ptr_min_max_vals(env, insn,
9493 dst_reg, src_reg);
9494 } else if (dst_reg->precise) {
9495 /* if dst_reg is precise, src_reg should be precise as well */
9496 err = mark_chain_precision(env, insn->src_reg);
9497 if (err)
9498 return err;
9499 }
9500 } else {
9501 /* Pretend the src is a reg with a known value, since we only
9502 * need to be able to read from this state.
9503 */
9504 off_reg.type = SCALAR_VALUE;
9505 __mark_reg_known(&off_reg, insn->imm);
9506 src_reg = &off_reg;
9507 if (ptr_reg) /* pointer += K */
9508 return adjust_ptr_min_max_vals(env, insn,
9509 ptr_reg, src_reg);
9510 }
9511
9512 /* Got here implies adding two SCALAR_VALUEs */
9513 if (WARN_ON_ONCE(ptr_reg)) {
9514 print_verifier_state(env, state, true);
9515 verbose(env, "verifier internal error: unexpected ptr_reg\n");
9516 return -EINVAL;
9517 }
9518 if (WARN_ON(!src_reg)) {
9519 print_verifier_state(env, state, true);
9520 verbose(env, "verifier internal error: no src_reg\n");
9521 return -EINVAL;
9522 }
9523 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
9524 }
9525
9526 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)9527 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
9528 {
9529 struct bpf_reg_state *regs = cur_regs(env);
9530 u8 opcode = BPF_OP(insn->code);
9531 int err;
9532
9533 if (opcode == BPF_END || opcode == BPF_NEG) {
9534 if (opcode == BPF_NEG) {
9535 if (BPF_SRC(insn->code) != BPF_K ||
9536 insn->src_reg != BPF_REG_0 ||
9537 insn->off != 0 || insn->imm != 0) {
9538 verbose(env, "BPF_NEG uses reserved fields\n");
9539 return -EINVAL;
9540 }
9541 } else {
9542 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
9543 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
9544 BPF_CLASS(insn->code) == BPF_ALU64) {
9545 verbose(env, "BPF_END uses reserved fields\n");
9546 return -EINVAL;
9547 }
9548 }
9549
9550 /* check src operand */
9551 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9552 if (err)
9553 return err;
9554
9555 if (is_pointer_value(env, insn->dst_reg)) {
9556 verbose(env, "R%d pointer arithmetic prohibited\n",
9557 insn->dst_reg);
9558 return -EACCES;
9559 }
9560
9561 /* check dest operand */
9562 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9563 if (err)
9564 return err;
9565
9566 } else if (opcode == BPF_MOV) {
9567
9568 if (BPF_SRC(insn->code) == BPF_X) {
9569 if (insn->imm != 0 || insn->off != 0) {
9570 verbose(env, "BPF_MOV uses reserved fields\n");
9571 return -EINVAL;
9572 }
9573
9574 /* check src operand */
9575 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9576 if (err)
9577 return err;
9578 } else {
9579 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9580 verbose(env, "BPF_MOV uses reserved fields\n");
9581 return -EINVAL;
9582 }
9583 }
9584
9585 /* check dest operand, mark as required later */
9586 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9587 if (err)
9588 return err;
9589
9590 if (BPF_SRC(insn->code) == BPF_X) {
9591 struct bpf_reg_state *src_reg = regs + insn->src_reg;
9592 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
9593
9594 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9595 /* case: R1 = R2
9596 * copy register state to dest reg
9597 */
9598 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
9599 /* Assign src and dst registers the same ID
9600 * that will be used by find_equal_scalars()
9601 * to propagate min/max range.
9602 */
9603 src_reg->id = ++env->id_gen;
9604 copy_register_state(dst_reg, src_reg);
9605 dst_reg->live |= REG_LIVE_WRITTEN;
9606 dst_reg->subreg_def = DEF_NOT_SUBREG;
9607 } else {
9608 /* R1 = (u32) R2 */
9609 if (is_pointer_value(env, insn->src_reg)) {
9610 verbose(env,
9611 "R%d partial copy of pointer\n",
9612 insn->src_reg);
9613 return -EACCES;
9614 } else if (src_reg->type == SCALAR_VALUE) {
9615 copy_register_state(dst_reg, src_reg);
9616 /* Make sure ID is cleared otherwise
9617 * dst_reg min/max could be incorrectly
9618 * propagated into src_reg by find_equal_scalars()
9619 */
9620 dst_reg->id = 0;
9621 dst_reg->live |= REG_LIVE_WRITTEN;
9622 dst_reg->subreg_def = env->insn_idx + 1;
9623 } else {
9624 mark_reg_unknown(env, regs,
9625 insn->dst_reg);
9626 }
9627 zext_32_to_64(dst_reg);
9628 reg_bounds_sync(dst_reg);
9629 }
9630 } else {
9631 /* case: R = imm
9632 * remember the value we stored into this reg
9633 */
9634 /* clear any state __mark_reg_known doesn't set */
9635 mark_reg_unknown(env, regs, insn->dst_reg);
9636 regs[insn->dst_reg].type = SCALAR_VALUE;
9637 if (BPF_CLASS(insn->code) == BPF_ALU64) {
9638 __mark_reg_known(regs + insn->dst_reg,
9639 insn->imm);
9640 } else {
9641 __mark_reg_known(regs + insn->dst_reg,
9642 (u32)insn->imm);
9643 }
9644 }
9645
9646 } else if (opcode > BPF_END) {
9647 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
9648 return -EINVAL;
9649
9650 } else { /* all other ALU ops: and, sub, xor, add, ... */
9651
9652 if (BPF_SRC(insn->code) == BPF_X) {
9653 if (insn->imm != 0 || insn->off != 0) {
9654 verbose(env, "BPF_ALU uses reserved fields\n");
9655 return -EINVAL;
9656 }
9657 /* check src1 operand */
9658 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9659 if (err)
9660 return err;
9661 } else {
9662 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
9663 verbose(env, "BPF_ALU uses reserved fields\n");
9664 return -EINVAL;
9665 }
9666 }
9667
9668 /* check src2 operand */
9669 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9670 if (err)
9671 return err;
9672
9673 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
9674 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
9675 verbose(env, "div by zero\n");
9676 return -EINVAL;
9677 }
9678
9679 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
9680 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
9681 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
9682
9683 if (insn->imm < 0 || insn->imm >= size) {
9684 verbose(env, "invalid shift %d\n", insn->imm);
9685 return -EINVAL;
9686 }
9687 }
9688
9689 /* check dest operand */
9690 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9691 if (err)
9692 return err;
9693
9694 return adjust_reg_min_max_vals(env, insn);
9695 }
9696
9697 return 0;
9698 }
9699
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)9700 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
9701 struct bpf_reg_state *dst_reg,
9702 enum bpf_reg_type type,
9703 bool range_right_open)
9704 {
9705 struct bpf_func_state *state;
9706 struct bpf_reg_state *reg;
9707 int new_range;
9708
9709 if (dst_reg->off < 0 ||
9710 (dst_reg->off == 0 && range_right_open))
9711 /* This doesn't give us any range */
9712 return;
9713
9714 if (dst_reg->umax_value > MAX_PACKET_OFF ||
9715 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
9716 /* Risk of overflow. For instance, ptr + (1<<63) may be less
9717 * than pkt_end, but that's because it's also less than pkt.
9718 */
9719 return;
9720
9721 new_range = dst_reg->off;
9722 if (range_right_open)
9723 new_range++;
9724
9725 /* Examples for register markings:
9726 *
9727 * pkt_data in dst register:
9728 *
9729 * r2 = r3;
9730 * r2 += 8;
9731 * if (r2 > pkt_end) goto <handle exception>
9732 * <access okay>
9733 *
9734 * r2 = r3;
9735 * r2 += 8;
9736 * if (r2 < pkt_end) goto <access okay>
9737 * <handle exception>
9738 *
9739 * Where:
9740 * r2 == dst_reg, pkt_end == src_reg
9741 * r2=pkt(id=n,off=8,r=0)
9742 * r3=pkt(id=n,off=0,r=0)
9743 *
9744 * pkt_data in src register:
9745 *
9746 * r2 = r3;
9747 * r2 += 8;
9748 * if (pkt_end >= r2) goto <access okay>
9749 * <handle exception>
9750 *
9751 * r2 = r3;
9752 * r2 += 8;
9753 * if (pkt_end <= r2) goto <handle exception>
9754 * <access okay>
9755 *
9756 * Where:
9757 * pkt_end == dst_reg, r2 == src_reg
9758 * r2=pkt(id=n,off=8,r=0)
9759 * r3=pkt(id=n,off=0,r=0)
9760 *
9761 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
9762 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
9763 * and [r3, r3 + 8-1) respectively is safe to access depending on
9764 * the check.
9765 */
9766
9767 /* If our ids match, then we must have the same max_value. And we
9768 * don't care about the other reg's fixed offset, since if it's too big
9769 * the range won't allow anything.
9770 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
9771 */
9772 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
9773 if (reg->type == type && reg->id == dst_reg->id)
9774 /* keep the maximum range already checked */
9775 reg->range = max(reg->range, new_range);
9776 }));
9777 }
9778
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)9779 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
9780 {
9781 struct tnum subreg = tnum_subreg(reg->var_off);
9782 s32 sval = (s32)val;
9783
9784 switch (opcode) {
9785 case BPF_JEQ:
9786 if (tnum_is_const(subreg))
9787 return !!tnum_equals_const(subreg, val);
9788 break;
9789 case BPF_JNE:
9790 if (tnum_is_const(subreg))
9791 return !tnum_equals_const(subreg, val);
9792 break;
9793 case BPF_JSET:
9794 if ((~subreg.mask & subreg.value) & val)
9795 return 1;
9796 if (!((subreg.mask | subreg.value) & val))
9797 return 0;
9798 break;
9799 case BPF_JGT:
9800 if (reg->u32_min_value > val)
9801 return 1;
9802 else if (reg->u32_max_value <= val)
9803 return 0;
9804 break;
9805 case BPF_JSGT:
9806 if (reg->s32_min_value > sval)
9807 return 1;
9808 else if (reg->s32_max_value <= sval)
9809 return 0;
9810 break;
9811 case BPF_JLT:
9812 if (reg->u32_max_value < val)
9813 return 1;
9814 else if (reg->u32_min_value >= val)
9815 return 0;
9816 break;
9817 case BPF_JSLT:
9818 if (reg->s32_max_value < sval)
9819 return 1;
9820 else if (reg->s32_min_value >= sval)
9821 return 0;
9822 break;
9823 case BPF_JGE:
9824 if (reg->u32_min_value >= val)
9825 return 1;
9826 else if (reg->u32_max_value < val)
9827 return 0;
9828 break;
9829 case BPF_JSGE:
9830 if (reg->s32_min_value >= sval)
9831 return 1;
9832 else if (reg->s32_max_value < sval)
9833 return 0;
9834 break;
9835 case BPF_JLE:
9836 if (reg->u32_max_value <= val)
9837 return 1;
9838 else if (reg->u32_min_value > val)
9839 return 0;
9840 break;
9841 case BPF_JSLE:
9842 if (reg->s32_max_value <= sval)
9843 return 1;
9844 else if (reg->s32_min_value > sval)
9845 return 0;
9846 break;
9847 }
9848
9849 return -1;
9850 }
9851
9852
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)9853 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
9854 {
9855 s64 sval = (s64)val;
9856
9857 switch (opcode) {
9858 case BPF_JEQ:
9859 if (tnum_is_const(reg->var_off))
9860 return !!tnum_equals_const(reg->var_off, val);
9861 break;
9862 case BPF_JNE:
9863 if (tnum_is_const(reg->var_off))
9864 return !tnum_equals_const(reg->var_off, val);
9865 break;
9866 case BPF_JSET:
9867 if ((~reg->var_off.mask & reg->var_off.value) & val)
9868 return 1;
9869 if (!((reg->var_off.mask | reg->var_off.value) & val))
9870 return 0;
9871 break;
9872 case BPF_JGT:
9873 if (reg->umin_value > val)
9874 return 1;
9875 else if (reg->umax_value <= val)
9876 return 0;
9877 break;
9878 case BPF_JSGT:
9879 if (reg->smin_value > sval)
9880 return 1;
9881 else if (reg->smax_value <= sval)
9882 return 0;
9883 break;
9884 case BPF_JLT:
9885 if (reg->umax_value < val)
9886 return 1;
9887 else if (reg->umin_value >= val)
9888 return 0;
9889 break;
9890 case BPF_JSLT:
9891 if (reg->smax_value < sval)
9892 return 1;
9893 else if (reg->smin_value >= sval)
9894 return 0;
9895 break;
9896 case BPF_JGE:
9897 if (reg->umin_value >= val)
9898 return 1;
9899 else if (reg->umax_value < val)
9900 return 0;
9901 break;
9902 case BPF_JSGE:
9903 if (reg->smin_value >= sval)
9904 return 1;
9905 else if (reg->smax_value < sval)
9906 return 0;
9907 break;
9908 case BPF_JLE:
9909 if (reg->umax_value <= val)
9910 return 1;
9911 else if (reg->umin_value > val)
9912 return 0;
9913 break;
9914 case BPF_JSLE:
9915 if (reg->smax_value <= sval)
9916 return 1;
9917 else if (reg->smin_value > sval)
9918 return 0;
9919 break;
9920 }
9921
9922 return -1;
9923 }
9924
9925 /* compute branch direction of the expression "if (reg opcode val) goto target;"
9926 * and return:
9927 * 1 - branch will be taken and "goto target" will be executed
9928 * 0 - branch will not be taken and fall-through to next insn
9929 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
9930 * range [0,10]
9931 */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)9932 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
9933 bool is_jmp32)
9934 {
9935 if (__is_pointer_value(false, reg)) {
9936 if (!reg_type_not_null(reg->type))
9937 return -1;
9938
9939 /* If pointer is valid tests against zero will fail so we can
9940 * use this to direct branch taken.
9941 */
9942 if (val != 0)
9943 return -1;
9944
9945 switch (opcode) {
9946 case BPF_JEQ:
9947 return 0;
9948 case BPF_JNE:
9949 return 1;
9950 default:
9951 return -1;
9952 }
9953 }
9954
9955 if (is_jmp32)
9956 return is_branch32_taken(reg, val, opcode);
9957 return is_branch64_taken(reg, val, opcode);
9958 }
9959
flip_opcode(u32 opcode)9960 static int flip_opcode(u32 opcode)
9961 {
9962 /* How can we transform "a <op> b" into "b <op> a"? */
9963 static const u8 opcode_flip[16] = {
9964 /* these stay the same */
9965 [BPF_JEQ >> 4] = BPF_JEQ,
9966 [BPF_JNE >> 4] = BPF_JNE,
9967 [BPF_JSET >> 4] = BPF_JSET,
9968 /* these swap "lesser" and "greater" (L and G in the opcodes) */
9969 [BPF_JGE >> 4] = BPF_JLE,
9970 [BPF_JGT >> 4] = BPF_JLT,
9971 [BPF_JLE >> 4] = BPF_JGE,
9972 [BPF_JLT >> 4] = BPF_JGT,
9973 [BPF_JSGE >> 4] = BPF_JSLE,
9974 [BPF_JSGT >> 4] = BPF_JSLT,
9975 [BPF_JSLE >> 4] = BPF_JSGE,
9976 [BPF_JSLT >> 4] = BPF_JSGT
9977 };
9978 return opcode_flip[opcode >> 4];
9979 }
9980
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)9981 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
9982 struct bpf_reg_state *src_reg,
9983 u8 opcode)
9984 {
9985 struct bpf_reg_state *pkt;
9986
9987 if (src_reg->type == PTR_TO_PACKET_END) {
9988 pkt = dst_reg;
9989 } else if (dst_reg->type == PTR_TO_PACKET_END) {
9990 pkt = src_reg;
9991 opcode = flip_opcode(opcode);
9992 } else {
9993 return -1;
9994 }
9995
9996 if (pkt->range >= 0)
9997 return -1;
9998
9999 switch (opcode) {
10000 case BPF_JLE:
10001 /* pkt <= pkt_end */
10002 fallthrough;
10003 case BPF_JGT:
10004 /* pkt > pkt_end */
10005 if (pkt->range == BEYOND_PKT_END)
10006 /* pkt has at last one extra byte beyond pkt_end */
10007 return opcode == BPF_JGT;
10008 break;
10009 case BPF_JLT:
10010 /* pkt < pkt_end */
10011 fallthrough;
10012 case BPF_JGE:
10013 /* pkt >= pkt_end */
10014 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
10015 return opcode == BPF_JGE;
10016 break;
10017 }
10018 return -1;
10019 }
10020
10021 /* Adjusts the register min/max values in the case that the dst_reg is the
10022 * variable register that we are working on, and src_reg is a constant or we're
10023 * simply doing a BPF_K check.
10024 * In JEQ/JNE cases we also adjust the var_off values.
10025 */
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)10026 static void reg_set_min_max(struct bpf_reg_state *true_reg,
10027 struct bpf_reg_state *false_reg,
10028 u64 val, u32 val32,
10029 u8 opcode, bool is_jmp32)
10030 {
10031 struct tnum false_32off = tnum_subreg(false_reg->var_off);
10032 struct tnum false_64off = false_reg->var_off;
10033 struct tnum true_32off = tnum_subreg(true_reg->var_off);
10034 struct tnum true_64off = true_reg->var_off;
10035 s64 sval = (s64)val;
10036 s32 sval32 = (s32)val32;
10037
10038 /* If the dst_reg is a pointer, we can't learn anything about its
10039 * variable offset from the compare (unless src_reg were a pointer into
10040 * the same object, but we don't bother with that.
10041 * Since false_reg and true_reg have the same type by construction, we
10042 * only need to check one of them for pointerness.
10043 */
10044 if (__is_pointer_value(false, false_reg))
10045 return;
10046
10047 switch (opcode) {
10048 /* JEQ/JNE comparison doesn't change the register equivalence.
10049 *
10050 * r1 = r2;
10051 * if (r1 == 42) goto label;
10052 * ...
10053 * label: // here both r1 and r2 are known to be 42.
10054 *
10055 * Hence when marking register as known preserve it's ID.
10056 */
10057 case BPF_JEQ:
10058 if (is_jmp32) {
10059 __mark_reg32_known(true_reg, val32);
10060 true_32off = tnum_subreg(true_reg->var_off);
10061 } else {
10062 ___mark_reg_known(true_reg, val);
10063 true_64off = true_reg->var_off;
10064 }
10065 break;
10066 case BPF_JNE:
10067 if (is_jmp32) {
10068 __mark_reg32_known(false_reg, val32);
10069 false_32off = tnum_subreg(false_reg->var_off);
10070 } else {
10071 ___mark_reg_known(false_reg, val);
10072 false_64off = false_reg->var_off;
10073 }
10074 break;
10075 case BPF_JSET:
10076 if (is_jmp32) {
10077 false_32off = tnum_and(false_32off, tnum_const(~val32));
10078 if (is_power_of_2(val32))
10079 true_32off = tnum_or(true_32off,
10080 tnum_const(val32));
10081 } else {
10082 false_64off = tnum_and(false_64off, tnum_const(~val));
10083 if (is_power_of_2(val))
10084 true_64off = tnum_or(true_64off,
10085 tnum_const(val));
10086 }
10087 break;
10088 case BPF_JGE:
10089 case BPF_JGT:
10090 {
10091 if (is_jmp32) {
10092 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
10093 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
10094
10095 false_reg->u32_max_value = min(false_reg->u32_max_value,
10096 false_umax);
10097 true_reg->u32_min_value = max(true_reg->u32_min_value,
10098 true_umin);
10099 } else {
10100 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
10101 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
10102
10103 false_reg->umax_value = min(false_reg->umax_value, false_umax);
10104 true_reg->umin_value = max(true_reg->umin_value, true_umin);
10105 }
10106 break;
10107 }
10108 case BPF_JSGE:
10109 case BPF_JSGT:
10110 {
10111 if (is_jmp32) {
10112 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
10113 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
10114
10115 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
10116 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
10117 } else {
10118 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
10119 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
10120
10121 false_reg->smax_value = min(false_reg->smax_value, false_smax);
10122 true_reg->smin_value = max(true_reg->smin_value, true_smin);
10123 }
10124 break;
10125 }
10126 case BPF_JLE:
10127 case BPF_JLT:
10128 {
10129 if (is_jmp32) {
10130 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
10131 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
10132
10133 false_reg->u32_min_value = max(false_reg->u32_min_value,
10134 false_umin);
10135 true_reg->u32_max_value = min(true_reg->u32_max_value,
10136 true_umax);
10137 } else {
10138 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
10139 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
10140
10141 false_reg->umin_value = max(false_reg->umin_value, false_umin);
10142 true_reg->umax_value = min(true_reg->umax_value, true_umax);
10143 }
10144 break;
10145 }
10146 case BPF_JSLE:
10147 case BPF_JSLT:
10148 {
10149 if (is_jmp32) {
10150 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
10151 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
10152
10153 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
10154 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
10155 } else {
10156 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
10157 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
10158
10159 false_reg->smin_value = max(false_reg->smin_value, false_smin);
10160 true_reg->smax_value = min(true_reg->smax_value, true_smax);
10161 }
10162 break;
10163 }
10164 default:
10165 return;
10166 }
10167
10168 if (is_jmp32) {
10169 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
10170 tnum_subreg(false_32off));
10171 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
10172 tnum_subreg(true_32off));
10173 __reg_combine_32_into_64(false_reg);
10174 __reg_combine_32_into_64(true_reg);
10175 } else {
10176 false_reg->var_off = false_64off;
10177 true_reg->var_off = true_64off;
10178 __reg_combine_64_into_32(false_reg);
10179 __reg_combine_64_into_32(true_reg);
10180 }
10181 }
10182
10183 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
10184 * the variable reg.
10185 */
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)10186 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
10187 struct bpf_reg_state *false_reg,
10188 u64 val, u32 val32,
10189 u8 opcode, bool is_jmp32)
10190 {
10191 opcode = flip_opcode(opcode);
10192 /* This uses zero as "not present in table"; luckily the zero opcode,
10193 * BPF_JA, can't get here.
10194 */
10195 if (opcode)
10196 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
10197 }
10198
10199 /* 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)10200 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
10201 struct bpf_reg_state *dst_reg)
10202 {
10203 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
10204 dst_reg->umin_value);
10205 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
10206 dst_reg->umax_value);
10207 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
10208 dst_reg->smin_value);
10209 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
10210 dst_reg->smax_value);
10211 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
10212 dst_reg->var_off);
10213 reg_bounds_sync(src_reg);
10214 reg_bounds_sync(dst_reg);
10215 }
10216
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)10217 static void reg_combine_min_max(struct bpf_reg_state *true_src,
10218 struct bpf_reg_state *true_dst,
10219 struct bpf_reg_state *false_src,
10220 struct bpf_reg_state *false_dst,
10221 u8 opcode)
10222 {
10223 switch (opcode) {
10224 case BPF_JEQ:
10225 __reg_combine_min_max(true_src, true_dst);
10226 break;
10227 case BPF_JNE:
10228 __reg_combine_min_max(false_src, false_dst);
10229 break;
10230 }
10231 }
10232
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)10233 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
10234 struct bpf_reg_state *reg, u32 id,
10235 bool is_null)
10236 {
10237 if (type_may_be_null(reg->type) && reg->id == id &&
10238 !WARN_ON_ONCE(!reg->id)) {
10239 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
10240 !tnum_equals_const(reg->var_off, 0) ||
10241 reg->off)) {
10242 /* Old offset (both fixed and variable parts) should
10243 * have been known-zero, because we don't allow pointer
10244 * arithmetic on pointers that might be NULL. If we
10245 * see this happening, don't convert the register.
10246 */
10247 return;
10248 }
10249 if (is_null) {
10250 reg->type = SCALAR_VALUE;
10251 /* We don't need id and ref_obj_id from this point
10252 * onwards anymore, thus we should better reset it,
10253 * so that state pruning has chances to take effect.
10254 */
10255 reg->id = 0;
10256 reg->ref_obj_id = 0;
10257
10258 return;
10259 }
10260
10261 mark_ptr_not_null_reg(reg);
10262
10263 if (!reg_may_point_to_spin_lock(reg)) {
10264 /* For not-NULL ptr, reg->ref_obj_id will be reset
10265 * in release_reference().
10266 *
10267 * reg->id is still used by spin_lock ptr. Other
10268 * than spin_lock ptr type, reg->id can be reset.
10269 */
10270 reg->id = 0;
10271 }
10272 }
10273 }
10274
10275 /* The logic is similar to find_good_pkt_pointers(), both could eventually
10276 * be folded together at some point.
10277 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)10278 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
10279 bool is_null)
10280 {
10281 struct bpf_func_state *state = vstate->frame[vstate->curframe];
10282 struct bpf_reg_state *regs = state->regs, *reg;
10283 u32 ref_obj_id = regs[regno].ref_obj_id;
10284 u32 id = regs[regno].id;
10285
10286 if (ref_obj_id && ref_obj_id == id && is_null)
10287 /* regs[regno] is in the " == NULL" branch.
10288 * No one could have freed the reference state before
10289 * doing the NULL check.
10290 */
10291 WARN_ON_ONCE(release_reference_state(state, id));
10292
10293 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10294 mark_ptr_or_null_reg(state, reg, id, is_null);
10295 }));
10296 }
10297
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)10298 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
10299 struct bpf_reg_state *dst_reg,
10300 struct bpf_reg_state *src_reg,
10301 struct bpf_verifier_state *this_branch,
10302 struct bpf_verifier_state *other_branch)
10303 {
10304 if (BPF_SRC(insn->code) != BPF_X)
10305 return false;
10306
10307 /* Pointers are always 64-bit. */
10308 if (BPF_CLASS(insn->code) == BPF_JMP32)
10309 return false;
10310
10311 switch (BPF_OP(insn->code)) {
10312 case BPF_JGT:
10313 if ((dst_reg->type == PTR_TO_PACKET &&
10314 src_reg->type == PTR_TO_PACKET_END) ||
10315 (dst_reg->type == PTR_TO_PACKET_META &&
10316 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10317 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
10318 find_good_pkt_pointers(this_branch, dst_reg,
10319 dst_reg->type, false);
10320 mark_pkt_end(other_branch, insn->dst_reg, true);
10321 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10322 src_reg->type == PTR_TO_PACKET) ||
10323 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10324 src_reg->type == PTR_TO_PACKET_META)) {
10325 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
10326 find_good_pkt_pointers(other_branch, src_reg,
10327 src_reg->type, true);
10328 mark_pkt_end(this_branch, insn->src_reg, false);
10329 } else {
10330 return false;
10331 }
10332 break;
10333 case BPF_JLT:
10334 if ((dst_reg->type == PTR_TO_PACKET &&
10335 src_reg->type == PTR_TO_PACKET_END) ||
10336 (dst_reg->type == PTR_TO_PACKET_META &&
10337 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10338 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
10339 find_good_pkt_pointers(other_branch, dst_reg,
10340 dst_reg->type, true);
10341 mark_pkt_end(this_branch, insn->dst_reg, false);
10342 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10343 src_reg->type == PTR_TO_PACKET) ||
10344 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10345 src_reg->type == PTR_TO_PACKET_META)) {
10346 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
10347 find_good_pkt_pointers(this_branch, src_reg,
10348 src_reg->type, false);
10349 mark_pkt_end(other_branch, insn->src_reg, true);
10350 } else {
10351 return false;
10352 }
10353 break;
10354 case BPF_JGE:
10355 if ((dst_reg->type == PTR_TO_PACKET &&
10356 src_reg->type == PTR_TO_PACKET_END) ||
10357 (dst_reg->type == PTR_TO_PACKET_META &&
10358 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10359 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
10360 find_good_pkt_pointers(this_branch, dst_reg,
10361 dst_reg->type, true);
10362 mark_pkt_end(other_branch, insn->dst_reg, false);
10363 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10364 src_reg->type == PTR_TO_PACKET) ||
10365 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10366 src_reg->type == PTR_TO_PACKET_META)) {
10367 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
10368 find_good_pkt_pointers(other_branch, src_reg,
10369 src_reg->type, false);
10370 mark_pkt_end(this_branch, insn->src_reg, true);
10371 } else {
10372 return false;
10373 }
10374 break;
10375 case BPF_JLE:
10376 if ((dst_reg->type == PTR_TO_PACKET &&
10377 src_reg->type == PTR_TO_PACKET_END) ||
10378 (dst_reg->type == PTR_TO_PACKET_META &&
10379 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
10380 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
10381 find_good_pkt_pointers(other_branch, dst_reg,
10382 dst_reg->type, false);
10383 mark_pkt_end(this_branch, insn->dst_reg, true);
10384 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
10385 src_reg->type == PTR_TO_PACKET) ||
10386 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
10387 src_reg->type == PTR_TO_PACKET_META)) {
10388 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
10389 find_good_pkt_pointers(this_branch, src_reg,
10390 src_reg->type, true);
10391 mark_pkt_end(other_branch, insn->src_reg, false);
10392 } else {
10393 return false;
10394 }
10395 break;
10396 default:
10397 return false;
10398 }
10399
10400 return true;
10401 }
10402
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)10403 static void find_equal_scalars(struct bpf_verifier_state *vstate,
10404 struct bpf_reg_state *known_reg)
10405 {
10406 struct bpf_func_state *state;
10407 struct bpf_reg_state *reg;
10408
10409 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
10410 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
10411 copy_register_state(reg, known_reg);
10412 }));
10413 }
10414
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)10415 static int check_cond_jmp_op(struct bpf_verifier_env *env,
10416 struct bpf_insn *insn, int *insn_idx)
10417 {
10418 struct bpf_verifier_state *this_branch = env->cur_state;
10419 struct bpf_verifier_state *other_branch;
10420 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
10421 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
10422 u8 opcode = BPF_OP(insn->code);
10423 bool is_jmp32;
10424 int pred = -1;
10425 int err;
10426
10427 /* Only conditional jumps are expected to reach here. */
10428 if (opcode == BPF_JA || opcode > BPF_JSLE) {
10429 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
10430 return -EINVAL;
10431 }
10432
10433 /* check src2 operand */
10434 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10435 if (err)
10436 return err;
10437
10438 dst_reg = ®s[insn->dst_reg];
10439 if (BPF_SRC(insn->code) == BPF_X) {
10440 if (insn->imm != 0) {
10441 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10442 return -EINVAL;
10443 }
10444
10445 /* check src1 operand */
10446 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10447 if (err)
10448 return err;
10449
10450 src_reg = ®s[insn->src_reg];
10451 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
10452 is_pointer_value(env, insn->src_reg)) {
10453 verbose(env, "R%d pointer comparison prohibited\n",
10454 insn->src_reg);
10455 return -EACCES;
10456 }
10457 } else {
10458 if (insn->src_reg != BPF_REG_0) {
10459 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
10460 return -EINVAL;
10461 }
10462 }
10463
10464 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
10465
10466 if (BPF_SRC(insn->code) == BPF_K) {
10467 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
10468 } else if (src_reg->type == SCALAR_VALUE &&
10469 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
10470 pred = is_branch_taken(dst_reg,
10471 tnum_subreg(src_reg->var_off).value,
10472 opcode,
10473 is_jmp32);
10474 } else if (src_reg->type == SCALAR_VALUE &&
10475 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
10476 pred = is_branch_taken(dst_reg,
10477 src_reg->var_off.value,
10478 opcode,
10479 is_jmp32);
10480 } else if (reg_is_pkt_pointer_any(dst_reg) &&
10481 reg_is_pkt_pointer_any(src_reg) &&
10482 !is_jmp32) {
10483 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
10484 }
10485
10486 if (pred >= 0) {
10487 /* If we get here with a dst_reg pointer type it is because
10488 * above is_branch_taken() special cased the 0 comparison.
10489 */
10490 if (!__is_pointer_value(false, dst_reg))
10491 err = mark_chain_precision(env, insn->dst_reg);
10492 if (BPF_SRC(insn->code) == BPF_X && !err &&
10493 !__is_pointer_value(false, src_reg))
10494 err = mark_chain_precision(env, insn->src_reg);
10495 if (err)
10496 return err;
10497 }
10498
10499 if (pred == 1) {
10500 /* Only follow the goto, ignore fall-through. If needed, push
10501 * the fall-through branch for simulation under speculative
10502 * execution.
10503 */
10504 if (!env->bypass_spec_v1 &&
10505 !sanitize_speculative_path(env, insn, *insn_idx + 1,
10506 *insn_idx))
10507 return -EFAULT;
10508 if (env->log.level & BPF_LOG_LEVEL)
10509 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10510 *insn_idx += insn->off;
10511 return 0;
10512 } else if (pred == 0) {
10513 /* Only follow the fall-through branch, since that's where the
10514 * program will go. If needed, push the goto branch for
10515 * simulation under speculative execution.
10516 */
10517 if (!env->bypass_spec_v1 &&
10518 !sanitize_speculative_path(env, insn,
10519 *insn_idx + insn->off + 1,
10520 *insn_idx))
10521 return -EFAULT;
10522 if (env->log.level & BPF_LOG_LEVEL)
10523 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10524 return 0;
10525 }
10526
10527 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
10528 false);
10529 if (!other_branch)
10530 return -EFAULT;
10531 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
10532
10533 /* detect if we are comparing against a constant value so we can adjust
10534 * our min/max values for our dst register.
10535 * this is only legit if both are scalars (or pointers to the same
10536 * object, I suppose, but we don't support that right now), because
10537 * otherwise the different base pointers mean the offsets aren't
10538 * comparable.
10539 */
10540 if (BPF_SRC(insn->code) == BPF_X) {
10541 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
10542
10543 if (dst_reg->type == SCALAR_VALUE &&
10544 src_reg->type == SCALAR_VALUE) {
10545 if (tnum_is_const(src_reg->var_off) ||
10546 (is_jmp32 &&
10547 tnum_is_const(tnum_subreg(src_reg->var_off))))
10548 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10549 dst_reg,
10550 src_reg->var_off.value,
10551 tnum_subreg(src_reg->var_off).value,
10552 opcode, is_jmp32);
10553 else if (tnum_is_const(dst_reg->var_off) ||
10554 (is_jmp32 &&
10555 tnum_is_const(tnum_subreg(dst_reg->var_off))))
10556 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
10557 src_reg,
10558 dst_reg->var_off.value,
10559 tnum_subreg(dst_reg->var_off).value,
10560 opcode, is_jmp32);
10561 else if (!is_jmp32 &&
10562 (opcode == BPF_JEQ || opcode == BPF_JNE))
10563 /* Comparing for equality, we can combine knowledge */
10564 reg_combine_min_max(&other_branch_regs[insn->src_reg],
10565 &other_branch_regs[insn->dst_reg],
10566 src_reg, dst_reg, opcode);
10567 if (src_reg->id &&
10568 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
10569 find_equal_scalars(this_branch, src_reg);
10570 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
10571 }
10572
10573 }
10574 } else if (dst_reg->type == SCALAR_VALUE) {
10575 reg_set_min_max(&other_branch_regs[insn->dst_reg],
10576 dst_reg, insn->imm, (u32)insn->imm,
10577 opcode, is_jmp32);
10578 }
10579
10580 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
10581 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
10582 find_equal_scalars(this_branch, dst_reg);
10583 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
10584 }
10585
10586 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
10587 * NOTE: these optimizations below are related with pointer comparison
10588 * which will never be JMP32.
10589 */
10590 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
10591 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
10592 type_may_be_null(dst_reg->type)) {
10593 /* Mark all identical registers in each branch as either
10594 * safe or unknown depending R == 0 or R != 0 conditional.
10595 */
10596 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
10597 opcode == BPF_JNE);
10598 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
10599 opcode == BPF_JEQ);
10600 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
10601 this_branch, other_branch) &&
10602 is_pointer_value(env, insn->dst_reg)) {
10603 verbose(env, "R%d pointer comparison prohibited\n",
10604 insn->dst_reg);
10605 return -EACCES;
10606 }
10607 if (env->log.level & BPF_LOG_LEVEL)
10608 print_insn_state(env, this_branch->frame[this_branch->curframe]);
10609 return 0;
10610 }
10611
10612 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)10613 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
10614 {
10615 struct bpf_insn_aux_data *aux = cur_aux(env);
10616 struct bpf_reg_state *regs = cur_regs(env);
10617 struct bpf_reg_state *dst_reg;
10618 struct bpf_map *map;
10619 int err;
10620
10621 if (BPF_SIZE(insn->code) != BPF_DW) {
10622 verbose(env, "invalid BPF_LD_IMM insn\n");
10623 return -EINVAL;
10624 }
10625 if (insn->off != 0) {
10626 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
10627 return -EINVAL;
10628 }
10629
10630 err = check_reg_arg(env, insn->dst_reg, DST_OP);
10631 if (err)
10632 return err;
10633
10634 dst_reg = ®s[insn->dst_reg];
10635 if (insn->src_reg == 0) {
10636 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
10637
10638 dst_reg->type = SCALAR_VALUE;
10639 __mark_reg_known(®s[insn->dst_reg], imm);
10640 return 0;
10641 }
10642
10643 /* All special src_reg cases are listed below. From this point onwards
10644 * we either succeed and assign a corresponding dst_reg->type after
10645 * zeroing the offset, or fail and reject the program.
10646 */
10647 mark_reg_known_zero(env, regs, insn->dst_reg);
10648
10649 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
10650 dst_reg->type = aux->btf_var.reg_type;
10651 switch (base_type(dst_reg->type)) {
10652 case PTR_TO_MEM:
10653 dst_reg->mem_size = aux->btf_var.mem_size;
10654 break;
10655 case PTR_TO_BTF_ID:
10656 dst_reg->btf = aux->btf_var.btf;
10657 dst_reg->btf_id = aux->btf_var.btf_id;
10658 break;
10659 default:
10660 verbose(env, "bpf verifier is misconfigured\n");
10661 return -EFAULT;
10662 }
10663 return 0;
10664 }
10665
10666 if (insn->src_reg == BPF_PSEUDO_FUNC) {
10667 struct bpf_prog_aux *aux = env->prog->aux;
10668 u32 subprogno = find_subprog(env,
10669 env->insn_idx + insn->imm + 1);
10670
10671 if (!aux->func_info) {
10672 verbose(env, "missing btf func_info\n");
10673 return -EINVAL;
10674 }
10675 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
10676 verbose(env, "callback function not static\n");
10677 return -EINVAL;
10678 }
10679
10680 dst_reg->type = PTR_TO_FUNC;
10681 dst_reg->subprogno = subprogno;
10682 return 0;
10683 }
10684
10685 map = env->used_maps[aux->map_index];
10686 dst_reg->map_ptr = map;
10687
10688 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
10689 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
10690 dst_reg->type = PTR_TO_MAP_VALUE;
10691 dst_reg->off = aux->map_off;
10692 if (map_value_has_spin_lock(map))
10693 dst_reg->id = ++env->id_gen;
10694 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
10695 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
10696 dst_reg->type = CONST_PTR_TO_MAP;
10697 } else {
10698 verbose(env, "bpf verifier is misconfigured\n");
10699 return -EINVAL;
10700 }
10701
10702 return 0;
10703 }
10704
may_access_skb(enum bpf_prog_type type)10705 static bool may_access_skb(enum bpf_prog_type type)
10706 {
10707 switch (type) {
10708 case BPF_PROG_TYPE_SOCKET_FILTER:
10709 case BPF_PROG_TYPE_SCHED_CLS:
10710 case BPF_PROG_TYPE_SCHED_ACT:
10711 return true;
10712 default:
10713 return false;
10714 }
10715 }
10716
10717 /* verify safety of LD_ABS|LD_IND instructions:
10718 * - they can only appear in the programs where ctx == skb
10719 * - since they are wrappers of function calls, they scratch R1-R5 registers,
10720 * preserve R6-R9, and store return value into R0
10721 *
10722 * Implicit input:
10723 * ctx == skb == R6 == CTX
10724 *
10725 * Explicit input:
10726 * SRC == any register
10727 * IMM == 32-bit immediate
10728 *
10729 * Output:
10730 * R0 - 8/16/32-bit skb data converted to cpu endianness
10731 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)10732 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
10733 {
10734 struct bpf_reg_state *regs = cur_regs(env);
10735 static const int ctx_reg = BPF_REG_6;
10736 u8 mode = BPF_MODE(insn->code);
10737 int i, err;
10738
10739 if (!may_access_skb(resolve_prog_type(env->prog))) {
10740 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
10741 return -EINVAL;
10742 }
10743
10744 if (!env->ops->gen_ld_abs) {
10745 verbose(env, "bpf verifier is misconfigured\n");
10746 return -EINVAL;
10747 }
10748
10749 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
10750 BPF_SIZE(insn->code) == BPF_DW ||
10751 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
10752 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
10753 return -EINVAL;
10754 }
10755
10756 /* check whether implicit source operand (register R6) is readable */
10757 err = check_reg_arg(env, ctx_reg, SRC_OP);
10758 if (err)
10759 return err;
10760
10761 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
10762 * gen_ld_abs() may terminate the program at runtime, leading to
10763 * reference leak.
10764 */
10765 err = check_reference_leak(env);
10766 if (err) {
10767 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
10768 return err;
10769 }
10770
10771 if (env->cur_state->active_spin_lock) {
10772 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
10773 return -EINVAL;
10774 }
10775
10776 if (regs[ctx_reg].type != PTR_TO_CTX) {
10777 verbose(env,
10778 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
10779 return -EINVAL;
10780 }
10781
10782 if (mode == BPF_IND) {
10783 /* check explicit source operand */
10784 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10785 if (err)
10786 return err;
10787 }
10788
10789 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg);
10790 if (err < 0)
10791 return err;
10792
10793 /* reset caller saved regs to unreadable */
10794 for (i = 0; i < CALLER_SAVED_REGS; i++) {
10795 mark_reg_not_init(env, regs, caller_saved[i]);
10796 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10797 }
10798
10799 /* mark destination R0 register as readable, since it contains
10800 * the value fetched from the packet.
10801 * Already marked as written above.
10802 */
10803 mark_reg_unknown(env, regs, BPF_REG_0);
10804 /* ld_abs load up to 32-bit skb data. */
10805 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
10806 return 0;
10807 }
10808
check_return_code(struct bpf_verifier_env * env)10809 static int check_return_code(struct bpf_verifier_env *env)
10810 {
10811 struct tnum enforce_attach_type_range = tnum_unknown;
10812 const struct bpf_prog *prog = env->prog;
10813 struct bpf_reg_state *reg;
10814 struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
10815 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10816 int err;
10817 struct bpf_func_state *frame = env->cur_state->frame[0];
10818 const bool is_subprog = frame->subprogno;
10819
10820 /* LSM and struct_ops func-ptr's return type could be "void" */
10821 if (!is_subprog) {
10822 switch (prog_type) {
10823 case BPF_PROG_TYPE_LSM:
10824 if (prog->expected_attach_type == BPF_LSM_CGROUP)
10825 /* See below, can be 0 or 0-1 depending on hook. */
10826 break;
10827 fallthrough;
10828 case BPF_PROG_TYPE_STRUCT_OPS:
10829 if (!prog->aux->attach_func_proto->type)
10830 return 0;
10831 break;
10832 default:
10833 break;
10834 }
10835 }
10836
10837 /* eBPF calling convention is such that R0 is used
10838 * to return the value from eBPF program.
10839 * Make sure that it's readable at this time
10840 * of bpf_exit, which means that program wrote
10841 * something into it earlier
10842 */
10843 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
10844 if (err)
10845 return err;
10846
10847 if (is_pointer_value(env, BPF_REG_0)) {
10848 verbose(env, "R0 leaks addr as return value\n");
10849 return -EACCES;
10850 }
10851
10852 reg = cur_regs(env) + BPF_REG_0;
10853
10854 if (frame->in_async_callback_fn) {
10855 /* enforce return zero from async callbacks like timer */
10856 if (reg->type != SCALAR_VALUE) {
10857 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
10858 reg_type_str(env, reg->type));
10859 return -EINVAL;
10860 }
10861
10862 if (!tnum_in(const_0, reg->var_off)) {
10863 verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
10864 return -EINVAL;
10865 }
10866 return 0;
10867 }
10868
10869 if (is_subprog) {
10870 if (reg->type != SCALAR_VALUE) {
10871 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
10872 reg_type_str(env, reg->type));
10873 return -EINVAL;
10874 }
10875 return 0;
10876 }
10877
10878 switch (prog_type) {
10879 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10880 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
10881 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
10882 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
10883 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
10884 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
10885 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
10886 range = tnum_range(1, 1);
10887 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
10888 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
10889 range = tnum_range(0, 3);
10890 break;
10891 case BPF_PROG_TYPE_CGROUP_SKB:
10892 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
10893 range = tnum_range(0, 3);
10894 enforce_attach_type_range = tnum_range(2, 3);
10895 }
10896 break;
10897 case BPF_PROG_TYPE_CGROUP_SOCK:
10898 case BPF_PROG_TYPE_SOCK_OPS:
10899 case BPF_PROG_TYPE_CGROUP_DEVICE:
10900 case BPF_PROG_TYPE_CGROUP_SYSCTL:
10901 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10902 break;
10903 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10904 if (!env->prog->aux->attach_btf_id)
10905 return 0;
10906 range = tnum_const(0);
10907 break;
10908 case BPF_PROG_TYPE_TRACING:
10909 switch (env->prog->expected_attach_type) {
10910 case BPF_TRACE_FENTRY:
10911 case BPF_TRACE_FEXIT:
10912 range = tnum_const(0);
10913 break;
10914 case BPF_TRACE_RAW_TP:
10915 case BPF_MODIFY_RETURN:
10916 return 0;
10917 case BPF_TRACE_ITER:
10918 break;
10919 default:
10920 return -ENOTSUPP;
10921 }
10922 break;
10923 case BPF_PROG_TYPE_SK_LOOKUP:
10924 range = tnum_range(SK_DROP, SK_PASS);
10925 break;
10926
10927 case BPF_PROG_TYPE_LSM:
10928 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
10929 /* Regular BPF_PROG_TYPE_LSM programs can return
10930 * any value.
10931 */
10932 return 0;
10933 }
10934 if (!env->prog->aux->attach_func_proto->type) {
10935 /* Make sure programs that attach to void
10936 * hooks don't try to modify return value.
10937 */
10938 range = tnum_range(1, 1);
10939 }
10940 break;
10941
10942 case BPF_PROG_TYPE_EXT:
10943 /* freplace program can return anything as its return value
10944 * depends on the to-be-replaced kernel func or bpf program.
10945 */
10946 default:
10947 return 0;
10948 }
10949
10950 if (reg->type != SCALAR_VALUE) {
10951 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
10952 reg_type_str(env, reg->type));
10953 return -EINVAL;
10954 }
10955
10956 if (!tnum_in(range, reg->var_off)) {
10957 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
10958 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
10959 prog_type == BPF_PROG_TYPE_LSM &&
10960 !prog->aux->attach_func_proto->type)
10961 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10962 return -EINVAL;
10963 }
10964
10965 if (!tnum_is_unknown(enforce_attach_type_range) &&
10966 tnum_in(enforce_attach_type_range, reg->var_off))
10967 env->prog->enforce_expected_attach_type = 1;
10968 return 0;
10969 }
10970
10971 /* non-recursive DFS pseudo code
10972 * 1 procedure DFS-iterative(G,v):
10973 * 2 label v as discovered
10974 * 3 let S be a stack
10975 * 4 S.push(v)
10976 * 5 while S is not empty
10977 * 6 t <- S.pop()
10978 * 7 if t is what we're looking for:
10979 * 8 return t
10980 * 9 for all edges e in G.adjacentEdges(t) do
10981 * 10 if edge e is already labelled
10982 * 11 continue with the next edge
10983 * 12 w <- G.adjacentVertex(t,e)
10984 * 13 if vertex w is not discovered and not explored
10985 * 14 label e as tree-edge
10986 * 15 label w as discovered
10987 * 16 S.push(w)
10988 * 17 continue at 5
10989 * 18 else if vertex w is discovered
10990 * 19 label e as back-edge
10991 * 20 else
10992 * 21 // vertex w is explored
10993 * 22 label e as forward- or cross-edge
10994 * 23 label t as explored
10995 * 24 S.pop()
10996 *
10997 * convention:
10998 * 0x10 - discovered
10999 * 0x11 - discovered and fall-through edge labelled
11000 * 0x12 - discovered and fall-through and branch edges labelled
11001 * 0x20 - explored
11002 */
11003
11004 enum {
11005 DISCOVERED = 0x10,
11006 EXPLORED = 0x20,
11007 FALLTHROUGH = 1,
11008 BRANCH = 2,
11009 };
11010
state_htab_size(struct bpf_verifier_env * env)11011 static u32 state_htab_size(struct bpf_verifier_env *env)
11012 {
11013 return env->prog->len;
11014 }
11015
explored_state(struct bpf_verifier_env * env,int idx)11016 static struct bpf_verifier_state_list **explored_state(
11017 struct bpf_verifier_env *env,
11018 int idx)
11019 {
11020 struct bpf_verifier_state *cur = env->cur_state;
11021 struct bpf_func_state *state = cur->frame[cur->curframe];
11022
11023 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
11024 }
11025
init_explored_state(struct bpf_verifier_env * env,int idx)11026 static void init_explored_state(struct bpf_verifier_env *env, int idx)
11027 {
11028 env->insn_aux_data[idx].prune_point = true;
11029 }
11030
11031 enum {
11032 DONE_EXPLORING = 0,
11033 KEEP_EXPLORING = 1,
11034 };
11035
11036 /* t, w, e - match pseudo-code above:
11037 * t - index of current instruction
11038 * w - next instruction
11039 * e - edge
11040 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)11041 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
11042 bool loop_ok)
11043 {
11044 int *insn_stack = env->cfg.insn_stack;
11045 int *insn_state = env->cfg.insn_state;
11046
11047 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
11048 return DONE_EXPLORING;
11049
11050 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
11051 return DONE_EXPLORING;
11052
11053 if (w < 0 || w >= env->prog->len) {
11054 verbose_linfo(env, t, "%d: ", t);
11055 verbose(env, "jump out of range from insn %d to %d\n", t, w);
11056 return -EINVAL;
11057 }
11058
11059 if (e == BRANCH)
11060 /* mark branch target for state pruning */
11061 init_explored_state(env, w);
11062
11063 if (insn_state[w] == 0) {
11064 /* tree-edge */
11065 insn_state[t] = DISCOVERED | e;
11066 insn_state[w] = DISCOVERED;
11067 if (env->cfg.cur_stack >= env->prog->len)
11068 return -E2BIG;
11069 insn_stack[env->cfg.cur_stack++] = w;
11070 return KEEP_EXPLORING;
11071 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
11072 if (loop_ok && env->bpf_capable)
11073 return DONE_EXPLORING;
11074 verbose_linfo(env, t, "%d: ", t);
11075 verbose_linfo(env, w, "%d: ", w);
11076 verbose(env, "back-edge from insn %d to %d\n", t, w);
11077 return -EINVAL;
11078 } else if (insn_state[w] == EXPLORED) {
11079 /* forward- or cross-edge */
11080 insn_state[t] = DISCOVERED | e;
11081 } else {
11082 verbose(env, "insn state internal bug\n");
11083 return -EFAULT;
11084 }
11085 return DONE_EXPLORING;
11086 }
11087
visit_func_call_insn(int t,int insn_cnt,struct bpf_insn * insns,struct bpf_verifier_env * env,bool visit_callee)11088 static int visit_func_call_insn(int t, int insn_cnt,
11089 struct bpf_insn *insns,
11090 struct bpf_verifier_env *env,
11091 bool visit_callee)
11092 {
11093 int ret;
11094
11095 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
11096 if (ret)
11097 return ret;
11098
11099 if (t + 1 < insn_cnt)
11100 init_explored_state(env, t + 1);
11101 if (visit_callee) {
11102 init_explored_state(env, t);
11103 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
11104 /* It's ok to allow recursion from CFG point of
11105 * view. __check_func_call() will do the actual
11106 * check.
11107 */
11108 bpf_pseudo_func(insns + t));
11109 }
11110 return ret;
11111 }
11112
11113 /* Visits the instruction at index t and returns one of the following:
11114 * < 0 - an error occurred
11115 * DONE_EXPLORING - the instruction was fully explored
11116 * KEEP_EXPLORING - there is still work to be done before it is fully explored
11117 */
visit_insn(int t,int insn_cnt,struct bpf_verifier_env * env)11118 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
11119 {
11120 struct bpf_insn *insns = env->prog->insnsi;
11121 int ret;
11122
11123 if (bpf_pseudo_func(insns + t))
11124 return visit_func_call_insn(t, insn_cnt, insns, env, true);
11125
11126 /* All non-branch instructions have a single fall-through edge. */
11127 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
11128 BPF_CLASS(insns[t].code) != BPF_JMP32)
11129 return push_insn(t, t + 1, FALLTHROUGH, env, false);
11130
11131 switch (BPF_OP(insns[t].code)) {
11132 case BPF_EXIT:
11133 return DONE_EXPLORING;
11134
11135 case BPF_CALL:
11136 if (insns[t].imm == BPF_FUNC_timer_set_callback)
11137 /* Mark this call insn to trigger is_state_visited() check
11138 * before call itself is processed by __check_func_call().
11139 * Otherwise new async state will be pushed for further
11140 * exploration.
11141 */
11142 init_explored_state(env, t);
11143 return visit_func_call_insn(t, insn_cnt, insns, env,
11144 insns[t].src_reg == BPF_PSEUDO_CALL);
11145
11146 case BPF_JA:
11147 if (BPF_SRC(insns[t].code) != BPF_K)
11148 return -EINVAL;
11149
11150 /* unconditional jump with single edge */
11151 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
11152 true);
11153 if (ret)
11154 return ret;
11155
11156 /* unconditional jmp is not a good pruning point,
11157 * but it's marked, since backtracking needs
11158 * to record jmp history in is_state_visited().
11159 */
11160 init_explored_state(env, t + insns[t].off + 1);
11161 /* tell verifier to check for equivalent states
11162 * after every call and jump
11163 */
11164 if (t + 1 < insn_cnt)
11165 init_explored_state(env, t + 1);
11166
11167 return ret;
11168
11169 default:
11170 /* conditional jump with two edges */
11171 init_explored_state(env, t);
11172 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
11173 if (ret)
11174 return ret;
11175
11176 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
11177 }
11178 }
11179
11180 /* non-recursive depth-first-search to detect loops in BPF program
11181 * loop == back-edge in directed graph
11182 */
check_cfg(struct bpf_verifier_env * env)11183 static int check_cfg(struct bpf_verifier_env *env)
11184 {
11185 int insn_cnt = env->prog->len;
11186 int *insn_stack, *insn_state;
11187 int ret = 0;
11188 int i;
11189
11190 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11191 if (!insn_state)
11192 return -ENOMEM;
11193
11194 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
11195 if (!insn_stack) {
11196 kvfree(insn_state);
11197 return -ENOMEM;
11198 }
11199
11200 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
11201 insn_stack[0] = 0; /* 0 is the first instruction */
11202 env->cfg.cur_stack = 1;
11203
11204 while (env->cfg.cur_stack > 0) {
11205 int t = insn_stack[env->cfg.cur_stack - 1];
11206
11207 ret = visit_insn(t, insn_cnt, env);
11208 switch (ret) {
11209 case DONE_EXPLORING:
11210 insn_state[t] = EXPLORED;
11211 env->cfg.cur_stack--;
11212 break;
11213 case KEEP_EXPLORING:
11214 break;
11215 default:
11216 if (ret > 0) {
11217 verbose(env, "visit_insn internal bug\n");
11218 ret = -EFAULT;
11219 }
11220 goto err_free;
11221 }
11222 }
11223
11224 if (env->cfg.cur_stack < 0) {
11225 verbose(env, "pop stack internal bug\n");
11226 ret = -EFAULT;
11227 goto err_free;
11228 }
11229
11230 for (i = 0; i < insn_cnt; i++) {
11231 if (insn_state[i] != EXPLORED) {
11232 verbose(env, "unreachable insn %d\n", i);
11233 ret = -EINVAL;
11234 goto err_free;
11235 }
11236 }
11237 ret = 0; /* cfg looks good */
11238
11239 err_free:
11240 kvfree(insn_state);
11241 kvfree(insn_stack);
11242 env->cfg.insn_state = env->cfg.insn_stack = NULL;
11243 return ret;
11244 }
11245
check_abnormal_return(struct bpf_verifier_env * env)11246 static int check_abnormal_return(struct bpf_verifier_env *env)
11247 {
11248 int i;
11249
11250 for (i = 1; i < env->subprog_cnt; i++) {
11251 if (env->subprog_info[i].has_ld_abs) {
11252 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
11253 return -EINVAL;
11254 }
11255 if (env->subprog_info[i].has_tail_call) {
11256 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
11257 return -EINVAL;
11258 }
11259 }
11260 return 0;
11261 }
11262
11263 /* The minimum supported BTF func info size */
11264 #define MIN_BPF_FUNCINFO_SIZE 8
11265 #define MAX_FUNCINFO_REC_SIZE 252
11266
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11267 static int check_btf_func(struct bpf_verifier_env *env,
11268 const union bpf_attr *attr,
11269 bpfptr_t uattr)
11270 {
11271 const struct btf_type *type, *func_proto, *ret_type;
11272 u32 i, nfuncs, urec_size, min_size;
11273 u32 krec_size = sizeof(struct bpf_func_info);
11274 struct bpf_func_info *krecord;
11275 struct bpf_func_info_aux *info_aux = NULL;
11276 struct bpf_prog *prog;
11277 const struct btf *btf;
11278 bpfptr_t urecord;
11279 u32 prev_offset = 0;
11280 bool scalar_return;
11281 int ret = -ENOMEM;
11282
11283 nfuncs = attr->func_info_cnt;
11284 if (!nfuncs) {
11285 if (check_abnormal_return(env))
11286 return -EINVAL;
11287 return 0;
11288 }
11289
11290 if (nfuncs != env->subprog_cnt) {
11291 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
11292 return -EINVAL;
11293 }
11294
11295 urec_size = attr->func_info_rec_size;
11296 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
11297 urec_size > MAX_FUNCINFO_REC_SIZE ||
11298 urec_size % sizeof(u32)) {
11299 verbose(env, "invalid func info rec size %u\n", urec_size);
11300 return -EINVAL;
11301 }
11302
11303 prog = env->prog;
11304 btf = prog->aux->btf;
11305
11306 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
11307 min_size = min_t(u32, krec_size, urec_size);
11308
11309 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
11310 if (!krecord)
11311 return -ENOMEM;
11312 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
11313 if (!info_aux)
11314 goto err_free;
11315
11316 for (i = 0; i < nfuncs; i++) {
11317 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
11318 if (ret) {
11319 if (ret == -E2BIG) {
11320 verbose(env, "nonzero tailing record in func info");
11321 /* set the size kernel expects so loader can zero
11322 * out the rest of the record.
11323 */
11324 if (copy_to_bpfptr_offset(uattr,
11325 offsetof(union bpf_attr, func_info_rec_size),
11326 &min_size, sizeof(min_size)))
11327 ret = -EFAULT;
11328 }
11329 goto err_free;
11330 }
11331
11332 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
11333 ret = -EFAULT;
11334 goto err_free;
11335 }
11336
11337 /* check insn_off */
11338 ret = -EINVAL;
11339 if (i == 0) {
11340 if (krecord[i].insn_off) {
11341 verbose(env,
11342 "nonzero insn_off %u for the first func info record",
11343 krecord[i].insn_off);
11344 goto err_free;
11345 }
11346 } else if (krecord[i].insn_off <= prev_offset) {
11347 verbose(env,
11348 "same or smaller insn offset (%u) than previous func info record (%u)",
11349 krecord[i].insn_off, prev_offset);
11350 goto err_free;
11351 }
11352
11353 if (env->subprog_info[i].start != krecord[i].insn_off) {
11354 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
11355 goto err_free;
11356 }
11357
11358 /* check type_id */
11359 type = btf_type_by_id(btf, krecord[i].type_id);
11360 if (!type || !btf_type_is_func(type)) {
11361 verbose(env, "invalid type id %d in func info",
11362 krecord[i].type_id);
11363 goto err_free;
11364 }
11365 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
11366
11367 func_proto = btf_type_by_id(btf, type->type);
11368 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
11369 /* btf_func_check() already verified it during BTF load */
11370 goto err_free;
11371 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
11372 scalar_return =
11373 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
11374 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
11375 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
11376 goto err_free;
11377 }
11378 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
11379 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
11380 goto err_free;
11381 }
11382
11383 prev_offset = krecord[i].insn_off;
11384 bpfptr_add(&urecord, urec_size);
11385 }
11386
11387 prog->aux->func_info = krecord;
11388 prog->aux->func_info_cnt = nfuncs;
11389 prog->aux->func_info_aux = info_aux;
11390 return 0;
11391
11392 err_free:
11393 kvfree(krecord);
11394 kfree(info_aux);
11395 return ret;
11396 }
11397
adjust_btf_func(struct bpf_verifier_env * env)11398 static void adjust_btf_func(struct bpf_verifier_env *env)
11399 {
11400 struct bpf_prog_aux *aux = env->prog->aux;
11401 int i;
11402
11403 if (!aux->func_info)
11404 return;
11405
11406 for (i = 0; i < env->subprog_cnt; i++)
11407 aux->func_info[i].insn_off = env->subprog_info[i].start;
11408 }
11409
11410 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col)
11411 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
11412
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11413 static int check_btf_line(struct bpf_verifier_env *env,
11414 const union bpf_attr *attr,
11415 bpfptr_t uattr)
11416 {
11417 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
11418 struct bpf_subprog_info *sub;
11419 struct bpf_line_info *linfo;
11420 struct bpf_prog *prog;
11421 const struct btf *btf;
11422 bpfptr_t ulinfo;
11423 int err;
11424
11425 nr_linfo = attr->line_info_cnt;
11426 if (!nr_linfo)
11427 return 0;
11428 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
11429 return -EINVAL;
11430
11431 rec_size = attr->line_info_rec_size;
11432 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
11433 rec_size > MAX_LINEINFO_REC_SIZE ||
11434 rec_size & (sizeof(u32) - 1))
11435 return -EINVAL;
11436
11437 /* Need to zero it in case the userspace may
11438 * pass in a smaller bpf_line_info object.
11439 */
11440 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
11441 GFP_KERNEL | __GFP_NOWARN);
11442 if (!linfo)
11443 return -ENOMEM;
11444
11445 prog = env->prog;
11446 btf = prog->aux->btf;
11447
11448 s = 0;
11449 sub = env->subprog_info;
11450 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
11451 expected_size = sizeof(struct bpf_line_info);
11452 ncopy = min_t(u32, expected_size, rec_size);
11453 for (i = 0; i < nr_linfo; i++) {
11454 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
11455 if (err) {
11456 if (err == -E2BIG) {
11457 verbose(env, "nonzero tailing record in line_info");
11458 if (copy_to_bpfptr_offset(uattr,
11459 offsetof(union bpf_attr, line_info_rec_size),
11460 &expected_size, sizeof(expected_size)))
11461 err = -EFAULT;
11462 }
11463 goto err_free;
11464 }
11465
11466 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
11467 err = -EFAULT;
11468 goto err_free;
11469 }
11470
11471 /*
11472 * Check insn_off to ensure
11473 * 1) strictly increasing AND
11474 * 2) bounded by prog->len
11475 *
11476 * The linfo[0].insn_off == 0 check logically falls into
11477 * the later "missing bpf_line_info for func..." case
11478 * because the first linfo[0].insn_off must be the
11479 * first sub also and the first sub must have
11480 * subprog_info[0].start == 0.
11481 */
11482 if ((i && linfo[i].insn_off <= prev_offset) ||
11483 linfo[i].insn_off >= prog->len) {
11484 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
11485 i, linfo[i].insn_off, prev_offset,
11486 prog->len);
11487 err = -EINVAL;
11488 goto err_free;
11489 }
11490
11491 if (!prog->insnsi[linfo[i].insn_off].code) {
11492 verbose(env,
11493 "Invalid insn code at line_info[%u].insn_off\n",
11494 i);
11495 err = -EINVAL;
11496 goto err_free;
11497 }
11498
11499 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
11500 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
11501 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
11502 err = -EINVAL;
11503 goto err_free;
11504 }
11505
11506 if (s != env->subprog_cnt) {
11507 if (linfo[i].insn_off == sub[s].start) {
11508 sub[s].linfo_idx = i;
11509 s++;
11510 } else if (sub[s].start < linfo[i].insn_off) {
11511 verbose(env, "missing bpf_line_info for func#%u\n", s);
11512 err = -EINVAL;
11513 goto err_free;
11514 }
11515 }
11516
11517 prev_offset = linfo[i].insn_off;
11518 bpfptr_add(&ulinfo, rec_size);
11519 }
11520
11521 if (s != env->subprog_cnt) {
11522 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
11523 env->subprog_cnt - s, s);
11524 err = -EINVAL;
11525 goto err_free;
11526 }
11527
11528 prog->aux->linfo = linfo;
11529 prog->aux->nr_linfo = nr_linfo;
11530
11531 return 0;
11532
11533 err_free:
11534 kvfree(linfo);
11535 return err;
11536 }
11537
11538 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
11539 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
11540
check_core_relo(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11541 static int check_core_relo(struct bpf_verifier_env *env,
11542 const union bpf_attr *attr,
11543 bpfptr_t uattr)
11544 {
11545 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
11546 struct bpf_core_relo core_relo = {};
11547 struct bpf_prog *prog = env->prog;
11548 const struct btf *btf = prog->aux->btf;
11549 struct bpf_core_ctx ctx = {
11550 .log = &env->log,
11551 .btf = btf,
11552 };
11553 bpfptr_t u_core_relo;
11554 int err;
11555
11556 nr_core_relo = attr->core_relo_cnt;
11557 if (!nr_core_relo)
11558 return 0;
11559 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
11560 return -EINVAL;
11561
11562 rec_size = attr->core_relo_rec_size;
11563 if (rec_size < MIN_CORE_RELO_SIZE ||
11564 rec_size > MAX_CORE_RELO_SIZE ||
11565 rec_size % sizeof(u32))
11566 return -EINVAL;
11567
11568 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
11569 expected_size = sizeof(struct bpf_core_relo);
11570 ncopy = min_t(u32, expected_size, rec_size);
11571
11572 /* Unlike func_info and line_info, copy and apply each CO-RE
11573 * relocation record one at a time.
11574 */
11575 for (i = 0; i < nr_core_relo; i++) {
11576 /* future proofing when sizeof(bpf_core_relo) changes */
11577 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
11578 if (err) {
11579 if (err == -E2BIG) {
11580 verbose(env, "nonzero tailing record in core_relo");
11581 if (copy_to_bpfptr_offset(uattr,
11582 offsetof(union bpf_attr, core_relo_rec_size),
11583 &expected_size, sizeof(expected_size)))
11584 err = -EFAULT;
11585 }
11586 break;
11587 }
11588
11589 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
11590 err = -EFAULT;
11591 break;
11592 }
11593
11594 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
11595 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
11596 i, core_relo.insn_off, prog->len);
11597 err = -EINVAL;
11598 break;
11599 }
11600
11601 err = bpf_core_apply(&ctx, &core_relo, i,
11602 &prog->insnsi[core_relo.insn_off / 8]);
11603 if (err)
11604 break;
11605 bpfptr_add(&u_core_relo, rec_size);
11606 }
11607 return err;
11608 }
11609
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,bpfptr_t uattr)11610 static int check_btf_info(struct bpf_verifier_env *env,
11611 const union bpf_attr *attr,
11612 bpfptr_t uattr)
11613 {
11614 struct btf *btf;
11615 int err;
11616
11617 if (!attr->func_info_cnt && !attr->line_info_cnt) {
11618 if (check_abnormal_return(env))
11619 return -EINVAL;
11620 return 0;
11621 }
11622
11623 btf = btf_get_by_fd(attr->prog_btf_fd);
11624 if (IS_ERR(btf))
11625 return PTR_ERR(btf);
11626 if (btf_is_kernel(btf)) {
11627 btf_put(btf);
11628 return -EACCES;
11629 }
11630 env->prog->aux->btf = btf;
11631
11632 err = check_btf_func(env, attr, uattr);
11633 if (err)
11634 return err;
11635
11636 err = check_btf_line(env, attr, uattr);
11637 if (err)
11638 return err;
11639
11640 err = check_core_relo(env, attr, uattr);
11641 if (err)
11642 return err;
11643
11644 return 0;
11645 }
11646
11647 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)11648 static bool range_within(struct bpf_reg_state *old,
11649 struct bpf_reg_state *cur)
11650 {
11651 return old->umin_value <= cur->umin_value &&
11652 old->umax_value >= cur->umax_value &&
11653 old->smin_value <= cur->smin_value &&
11654 old->smax_value >= cur->smax_value &&
11655 old->u32_min_value <= cur->u32_min_value &&
11656 old->u32_max_value >= cur->u32_max_value &&
11657 old->s32_min_value <= cur->s32_min_value &&
11658 old->s32_max_value >= cur->s32_max_value;
11659 }
11660
11661 /* If in the old state two registers had the same id, then they need to have
11662 * the same id in the new state as well. But that id could be different from
11663 * the old state, so we need to track the mapping from old to new ids.
11664 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
11665 * regs with old id 5 must also have new id 9 for the new state to be safe. But
11666 * regs with a different old id could still have new id 9, we don't care about
11667 * that.
11668 * So we look through our idmap to see if this old id has been seen before. If
11669 * so, we require the new id to match; otherwise, we add the id pair to the map.
11670 */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)11671 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
11672 {
11673 unsigned int i;
11674
11675 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
11676 if (!idmap[i].old) {
11677 /* Reached an empty slot; haven't seen this id before */
11678 idmap[i].old = old_id;
11679 idmap[i].cur = cur_id;
11680 return true;
11681 }
11682 if (idmap[i].old == old_id)
11683 return idmap[i].cur == cur_id;
11684 }
11685 /* We ran out of idmap slots, which should be impossible */
11686 WARN_ON_ONCE(1);
11687 return false;
11688 }
11689
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)11690 static void clean_func_state(struct bpf_verifier_env *env,
11691 struct bpf_func_state *st)
11692 {
11693 enum bpf_reg_liveness live;
11694 int i, j;
11695
11696 for (i = 0; i < BPF_REG_FP; i++) {
11697 live = st->regs[i].live;
11698 /* liveness must not touch this register anymore */
11699 st->regs[i].live |= REG_LIVE_DONE;
11700 if (!(live & REG_LIVE_READ))
11701 /* since the register is unused, clear its state
11702 * to make further comparison simpler
11703 */
11704 __mark_reg_not_init(env, &st->regs[i]);
11705 }
11706
11707 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
11708 live = st->stack[i].spilled_ptr.live;
11709 /* liveness must not touch this stack slot anymore */
11710 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
11711 if (!(live & REG_LIVE_READ)) {
11712 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
11713 for (j = 0; j < BPF_REG_SIZE; j++)
11714 st->stack[i].slot_type[j] = STACK_INVALID;
11715 }
11716 }
11717 }
11718
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)11719 static void clean_verifier_state(struct bpf_verifier_env *env,
11720 struct bpf_verifier_state *st)
11721 {
11722 int i;
11723
11724 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
11725 /* all regs in this state in all frames were already marked */
11726 return;
11727
11728 for (i = 0; i <= st->curframe; i++)
11729 clean_func_state(env, st->frame[i]);
11730 }
11731
11732 /* the parentage chains form a tree.
11733 * the verifier states are added to state lists at given insn and
11734 * pushed into state stack for future exploration.
11735 * when the verifier reaches bpf_exit insn some of the verifer states
11736 * stored in the state lists have their final liveness state already,
11737 * but a lot of states will get revised from liveness point of view when
11738 * the verifier explores other branches.
11739 * Example:
11740 * 1: r0 = 1
11741 * 2: if r1 == 100 goto pc+1
11742 * 3: r0 = 2
11743 * 4: exit
11744 * when the verifier reaches exit insn the register r0 in the state list of
11745 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
11746 * of insn 2 and goes exploring further. At the insn 4 it will walk the
11747 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
11748 *
11749 * Since the verifier pushes the branch states as it sees them while exploring
11750 * the program the condition of walking the branch instruction for the second
11751 * time means that all states below this branch were already explored and
11752 * their final liveness marks are already propagated.
11753 * Hence when the verifier completes the search of state list in is_state_visited()
11754 * we can call this clean_live_states() function to mark all liveness states
11755 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
11756 * will not be used.
11757 * This function also clears the registers and stack for states that !READ
11758 * to simplify state merging.
11759 *
11760 * Important note here that walking the same branch instruction in the callee
11761 * doesn't meant that the states are DONE. The verifier has to compare
11762 * the callsites
11763 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)11764 static void clean_live_states(struct bpf_verifier_env *env, int insn,
11765 struct bpf_verifier_state *cur)
11766 {
11767 struct bpf_verifier_state_list *sl;
11768 int i;
11769
11770 sl = *explored_state(env, insn);
11771 while (sl) {
11772 if (sl->state.branches)
11773 goto next;
11774 if (sl->state.insn_idx != insn ||
11775 sl->state.curframe != cur->curframe)
11776 goto next;
11777 for (i = 0; i <= cur->curframe; i++)
11778 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
11779 goto next;
11780 clean_verifier_state(env, &sl->state);
11781 next:
11782 sl = sl->next;
11783 }
11784 }
11785
11786 /* 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_id_pair * idmap)11787 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
11788 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
11789 {
11790 bool equal;
11791
11792 if (!(rold->live & REG_LIVE_READ))
11793 /* explored state didn't use this */
11794 return true;
11795
11796 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
11797
11798 if (rold->type == PTR_TO_STACK)
11799 /* two stack pointers are equal only if they're pointing to
11800 * the same stack frame, since fp-8 in foo != fp-8 in bar
11801 */
11802 return equal && rold->frameno == rcur->frameno;
11803
11804 if (equal)
11805 return true;
11806
11807 if (rold->type == NOT_INIT)
11808 /* explored state can't have used this */
11809 return true;
11810 if (rcur->type == NOT_INIT)
11811 return false;
11812 switch (base_type(rold->type)) {
11813 case SCALAR_VALUE:
11814 if (env->explore_alu_limits)
11815 return false;
11816 if (rcur->type == SCALAR_VALUE) {
11817 if (!rold->precise)
11818 return true;
11819 /* new val must satisfy old val knowledge */
11820 return range_within(rold, rcur) &&
11821 tnum_in(rold->var_off, rcur->var_off);
11822 } else {
11823 /* We're trying to use a pointer in place of a scalar.
11824 * Even if the scalar was unbounded, this could lead to
11825 * pointer leaks because scalars are allowed to leak
11826 * while pointers are not. We could make this safe in
11827 * special cases if root is calling us, but it's
11828 * probably not worth the hassle.
11829 */
11830 return false;
11831 }
11832 case PTR_TO_MAP_KEY:
11833 case PTR_TO_MAP_VALUE:
11834 /* a PTR_TO_MAP_VALUE could be safe to use as a
11835 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
11836 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
11837 * checked, doing so could have affected others with the same
11838 * id, and we can't check for that because we lost the id when
11839 * we converted to a PTR_TO_MAP_VALUE.
11840 */
11841 if (type_may_be_null(rold->type)) {
11842 if (!type_may_be_null(rcur->type))
11843 return false;
11844 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
11845 return false;
11846 /* Check our ids match any regs they're supposed to */
11847 return check_ids(rold->id, rcur->id, idmap);
11848 }
11849
11850 /* If the new min/max/var_off satisfy the old ones and
11851 * everything else matches, we are OK.
11852 * 'id' is not compared, since it's only used for maps with
11853 * bpf_spin_lock inside map element and in such cases if
11854 * the rest of the prog is valid for one map element then
11855 * it's valid for all map elements regardless of the key
11856 * used in bpf_map_lookup()
11857 */
11858 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
11859 range_within(rold, rcur) &&
11860 tnum_in(rold->var_off, rcur->var_off);
11861 case PTR_TO_PACKET_META:
11862 case PTR_TO_PACKET:
11863 if (rcur->type != rold->type)
11864 return false;
11865 /* We must have at least as much range as the old ptr
11866 * did, so that any accesses which were safe before are
11867 * still safe. This is true even if old range < old off,
11868 * since someone could have accessed through (ptr - k), or
11869 * even done ptr -= k in a register, to get a safe access.
11870 */
11871 if (rold->range > rcur->range)
11872 return false;
11873 /* If the offsets don't match, we can't trust our alignment;
11874 * nor can we be sure that we won't fall out of range.
11875 */
11876 if (rold->off != rcur->off)
11877 return false;
11878 /* id relations must be preserved */
11879 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
11880 return false;
11881 /* new val must satisfy old val knowledge */
11882 return range_within(rold, rcur) &&
11883 tnum_in(rold->var_off, rcur->var_off);
11884 case PTR_TO_CTX:
11885 case CONST_PTR_TO_MAP:
11886 case PTR_TO_PACKET_END:
11887 case PTR_TO_FLOW_KEYS:
11888 case PTR_TO_SOCKET:
11889 case PTR_TO_SOCK_COMMON:
11890 case PTR_TO_TCP_SOCK:
11891 case PTR_TO_XDP_SOCK:
11892 /* Only valid matches are exact, which memcmp() above
11893 * would have accepted
11894 */
11895 default:
11896 /* Don't know what's going on, just say it's not safe */
11897 return false;
11898 }
11899
11900 /* Shouldn't get here; if we do, say it's not safe */
11901 WARN_ON_ONCE(1);
11902 return false;
11903 }
11904
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)11905 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
11906 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
11907 {
11908 int i, spi;
11909
11910 /* walk slots of the explored stack and ignore any additional
11911 * slots in the current stack, since explored(safe) state
11912 * didn't use them
11913 */
11914 for (i = 0; i < old->allocated_stack; i++) {
11915 spi = i / BPF_REG_SIZE;
11916
11917 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
11918 i += BPF_REG_SIZE - 1;
11919 /* explored state didn't use this */
11920 continue;
11921 }
11922
11923 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
11924 continue;
11925
11926 /* explored stack has more populated slots than current stack
11927 * and these slots were used
11928 */
11929 if (i >= cur->allocated_stack)
11930 return false;
11931
11932 /* if old state was safe with misc data in the stack
11933 * it will be safe with zero-initialized stack.
11934 * The opposite is not true
11935 */
11936 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
11937 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
11938 continue;
11939 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
11940 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
11941 /* Ex: old explored (safe) state has STACK_SPILL in
11942 * this stack slot, but current has STACK_MISC ->
11943 * this verifier states are not equivalent,
11944 * return false to continue verification of this path
11945 */
11946 return false;
11947 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
11948 continue;
11949 if (!is_spilled_reg(&old->stack[spi]))
11950 continue;
11951 if (!regsafe(env, &old->stack[spi].spilled_ptr,
11952 &cur->stack[spi].spilled_ptr, idmap))
11953 /* when explored and current stack slot are both storing
11954 * spilled registers, check that stored pointers types
11955 * are the same as well.
11956 * Ex: explored safe path could have stored
11957 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
11958 * but current path has stored:
11959 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
11960 * such verifier states are not equivalent.
11961 * return false to continue verification of this path
11962 */
11963 return false;
11964 }
11965 return true;
11966 }
11967
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)11968 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
11969 {
11970 if (old->acquired_refs != cur->acquired_refs)
11971 return false;
11972 return !memcmp(old->refs, cur->refs,
11973 sizeof(*old->refs) * old->acquired_refs);
11974 }
11975
11976 /* compare two verifier states
11977 *
11978 * all states stored in state_list are known to be valid, since
11979 * verifier reached 'bpf_exit' instruction through them
11980 *
11981 * this function is called when verifier exploring different branches of
11982 * execution popped from the state stack. If it sees an old state that has
11983 * more strict register state and more strict stack state then this execution
11984 * branch doesn't need to be explored further, since verifier already
11985 * concluded that more strict state leads to valid finish.
11986 *
11987 * Therefore two states are equivalent if register state is more conservative
11988 * and explored stack state is more conservative than the current one.
11989 * Example:
11990 * explored current
11991 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
11992 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
11993 *
11994 * In other words if current stack state (one being explored) has more
11995 * valid slots than old one that already passed validation, it means
11996 * the verifier can stop exploring and conclude that current state is valid too
11997 *
11998 * Similarly with registers. If explored state has register type as invalid
11999 * whereas register type in current state is meaningful, it means that
12000 * the current state will reach 'bpf_exit' instruction safely
12001 */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)12002 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
12003 struct bpf_func_state *cur)
12004 {
12005 int i;
12006
12007 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
12008 for (i = 0; i < MAX_BPF_REG; i++)
12009 if (!regsafe(env, &old->regs[i], &cur->regs[i],
12010 env->idmap_scratch))
12011 return false;
12012
12013 if (!stacksafe(env, old, cur, env->idmap_scratch))
12014 return false;
12015
12016 if (!refsafe(old, cur))
12017 return false;
12018
12019 return true;
12020 }
12021
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)12022 static bool states_equal(struct bpf_verifier_env *env,
12023 struct bpf_verifier_state *old,
12024 struct bpf_verifier_state *cur)
12025 {
12026 int i;
12027
12028 if (old->curframe != cur->curframe)
12029 return false;
12030
12031 /* Verification state from speculative execution simulation
12032 * must never prune a non-speculative execution one.
12033 */
12034 if (old->speculative && !cur->speculative)
12035 return false;
12036
12037 if (old->active_spin_lock != cur->active_spin_lock)
12038 return false;
12039
12040 /* for states to be equal callsites have to be the same
12041 * and all frame states need to be equivalent
12042 */
12043 for (i = 0; i <= old->curframe; i++) {
12044 if (old->frame[i]->callsite != cur->frame[i]->callsite)
12045 return false;
12046 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
12047 return false;
12048 }
12049 return true;
12050 }
12051
12052 /* Return 0 if no propagation happened. Return negative error code if error
12053 * happened. Otherwise, return the propagated bit.
12054 */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)12055 static int propagate_liveness_reg(struct bpf_verifier_env *env,
12056 struct bpf_reg_state *reg,
12057 struct bpf_reg_state *parent_reg)
12058 {
12059 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
12060 u8 flag = reg->live & REG_LIVE_READ;
12061 int err;
12062
12063 /* When comes here, read flags of PARENT_REG or REG could be any of
12064 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
12065 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
12066 */
12067 if (parent_flag == REG_LIVE_READ64 ||
12068 /* Or if there is no read flag from REG. */
12069 !flag ||
12070 /* Or if the read flag from REG is the same as PARENT_REG. */
12071 parent_flag == flag)
12072 return 0;
12073
12074 err = mark_reg_read(env, reg, parent_reg, flag);
12075 if (err)
12076 return err;
12077
12078 return flag;
12079 }
12080
12081 /* A write screens off any subsequent reads; but write marks come from the
12082 * straight-line code between a state and its parent. When we arrive at an
12083 * equivalent state (jump target or such) we didn't arrive by the straight-line
12084 * code, so read marks in the state must propagate to the parent regardless
12085 * of the state's write marks. That's what 'parent == state->parent' comparison
12086 * in mark_reg_read() is for.
12087 */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)12088 static int propagate_liveness(struct bpf_verifier_env *env,
12089 const struct bpf_verifier_state *vstate,
12090 struct bpf_verifier_state *vparent)
12091 {
12092 struct bpf_reg_state *state_reg, *parent_reg;
12093 struct bpf_func_state *state, *parent;
12094 int i, frame, err = 0;
12095
12096 if (vparent->curframe != vstate->curframe) {
12097 WARN(1, "propagate_live: parent frame %d current frame %d\n",
12098 vparent->curframe, vstate->curframe);
12099 return -EFAULT;
12100 }
12101 /* Propagate read liveness of registers... */
12102 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
12103 for (frame = 0; frame <= vstate->curframe; frame++) {
12104 parent = vparent->frame[frame];
12105 state = vstate->frame[frame];
12106 parent_reg = parent->regs;
12107 state_reg = state->regs;
12108 /* We don't need to worry about FP liveness, it's read-only */
12109 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
12110 err = propagate_liveness_reg(env, &state_reg[i],
12111 &parent_reg[i]);
12112 if (err < 0)
12113 return err;
12114 if (err == REG_LIVE_READ64)
12115 mark_insn_zext(env, &parent_reg[i]);
12116 }
12117
12118 /* Propagate stack slots. */
12119 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
12120 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
12121 parent_reg = &parent->stack[i].spilled_ptr;
12122 state_reg = &state->stack[i].spilled_ptr;
12123 err = propagate_liveness_reg(env, state_reg,
12124 parent_reg);
12125 if (err < 0)
12126 return err;
12127 }
12128 }
12129 return 0;
12130 }
12131
12132 /* find precise scalars in the previous equivalent state and
12133 * propagate them into the current state
12134 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)12135 static int propagate_precision(struct bpf_verifier_env *env,
12136 const struct bpf_verifier_state *old)
12137 {
12138 struct bpf_reg_state *state_reg;
12139 struct bpf_func_state *state;
12140 int i, err = 0, fr;
12141
12142 for (fr = old->curframe; fr >= 0; fr--) {
12143 state = old->frame[fr];
12144 state_reg = state->regs;
12145 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
12146 if (state_reg->type != SCALAR_VALUE ||
12147 !state_reg->precise ||
12148 !(state_reg->live & REG_LIVE_READ))
12149 continue;
12150 if (env->log.level & BPF_LOG_LEVEL2)
12151 verbose(env, "frame %d: propagating r%d\n", fr, i);
12152 err = mark_chain_precision_frame(env, fr, i);
12153 if (err < 0)
12154 return err;
12155 }
12156
12157 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
12158 if (!is_spilled_reg(&state->stack[i]))
12159 continue;
12160 state_reg = &state->stack[i].spilled_ptr;
12161 if (state_reg->type != SCALAR_VALUE ||
12162 !state_reg->precise ||
12163 !(state_reg->live & REG_LIVE_READ))
12164 continue;
12165 if (env->log.level & BPF_LOG_LEVEL2)
12166 verbose(env, "frame %d: propagating fp%d\n",
12167 fr, (-i - 1) * BPF_REG_SIZE);
12168 err = mark_chain_precision_stack_frame(env, fr, i);
12169 if (err < 0)
12170 return err;
12171 }
12172 }
12173 return 0;
12174 }
12175
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)12176 static bool states_maybe_looping(struct bpf_verifier_state *old,
12177 struct bpf_verifier_state *cur)
12178 {
12179 struct bpf_func_state *fold, *fcur;
12180 int i, fr = cur->curframe;
12181
12182 if (old->curframe != fr)
12183 return false;
12184
12185 fold = old->frame[fr];
12186 fcur = cur->frame[fr];
12187 for (i = 0; i < MAX_BPF_REG; i++)
12188 if (memcmp(&fold->regs[i], &fcur->regs[i],
12189 offsetof(struct bpf_reg_state, parent)))
12190 return false;
12191 return true;
12192 }
12193
12194
is_state_visited(struct bpf_verifier_env * env,int insn_idx)12195 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
12196 {
12197 struct bpf_verifier_state_list *new_sl;
12198 struct bpf_verifier_state_list *sl, **pprev;
12199 struct bpf_verifier_state *cur = env->cur_state, *new;
12200 int i, j, err, states_cnt = 0;
12201 bool add_new_state = env->test_state_freq ? true : false;
12202
12203 cur->last_insn_idx = env->prev_insn_idx;
12204 if (!env->insn_aux_data[insn_idx].prune_point)
12205 /* this 'insn_idx' instruction wasn't marked, so we will not
12206 * be doing state search here
12207 */
12208 return 0;
12209
12210 /* bpf progs typically have pruning point every 4 instructions
12211 * http://vger.kernel.org/bpfconf2019.html#session-1
12212 * Do not add new state for future pruning if the verifier hasn't seen
12213 * at least 2 jumps and at least 8 instructions.
12214 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
12215 * In tests that amounts to up to 50% reduction into total verifier
12216 * memory consumption and 20% verifier time speedup.
12217 */
12218 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
12219 env->insn_processed - env->prev_insn_processed >= 8)
12220 add_new_state = true;
12221
12222 pprev = explored_state(env, insn_idx);
12223 sl = *pprev;
12224
12225 clean_live_states(env, insn_idx, cur);
12226
12227 while (sl) {
12228 states_cnt++;
12229 if (sl->state.insn_idx != insn_idx)
12230 goto next;
12231
12232 if (sl->state.branches) {
12233 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
12234
12235 if (frame->in_async_callback_fn &&
12236 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
12237 /* Different async_entry_cnt means that the verifier is
12238 * processing another entry into async callback.
12239 * Seeing the same state is not an indication of infinite
12240 * loop or infinite recursion.
12241 * But finding the same state doesn't mean that it's safe
12242 * to stop processing the current state. The previous state
12243 * hasn't yet reached bpf_exit, since state.branches > 0.
12244 * Checking in_async_callback_fn alone is not enough either.
12245 * Since the verifier still needs to catch infinite loops
12246 * inside async callbacks.
12247 */
12248 } else if (states_maybe_looping(&sl->state, cur) &&
12249 states_equal(env, &sl->state, cur)) {
12250 verbose_linfo(env, insn_idx, "; ");
12251 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
12252 return -EINVAL;
12253 }
12254 /* if the verifier is processing a loop, avoid adding new state
12255 * too often, since different loop iterations have distinct
12256 * states and may not help future pruning.
12257 * This threshold shouldn't be too low to make sure that
12258 * a loop with large bound will be rejected quickly.
12259 * The most abusive loop will be:
12260 * r1 += 1
12261 * if r1 < 1000000 goto pc-2
12262 * 1M insn_procssed limit / 100 == 10k peak states.
12263 * This threshold shouldn't be too high either, since states
12264 * at the end of the loop are likely to be useful in pruning.
12265 */
12266 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
12267 env->insn_processed - env->prev_insn_processed < 100)
12268 add_new_state = false;
12269 goto miss;
12270 }
12271 if (states_equal(env, &sl->state, cur)) {
12272 sl->hit_cnt++;
12273 /* reached equivalent register/stack state,
12274 * prune the search.
12275 * Registers read by the continuation are read by us.
12276 * If we have any write marks in env->cur_state, they
12277 * will prevent corresponding reads in the continuation
12278 * from reaching our parent (an explored_state). Our
12279 * own state will get the read marks recorded, but
12280 * they'll be immediately forgotten as we're pruning
12281 * this state and will pop a new one.
12282 */
12283 err = propagate_liveness(env, &sl->state, cur);
12284
12285 /* if previous state reached the exit with precision and
12286 * current state is equivalent to it (except precsion marks)
12287 * the precision needs to be propagated back in
12288 * the current state.
12289 */
12290 err = err ? : push_jmp_history(env, cur);
12291 err = err ? : propagate_precision(env, &sl->state);
12292 if (err)
12293 return err;
12294 return 1;
12295 }
12296 miss:
12297 /* when new state is not going to be added do not increase miss count.
12298 * Otherwise several loop iterations will remove the state
12299 * recorded earlier. The goal of these heuristics is to have
12300 * states from some iterations of the loop (some in the beginning
12301 * and some at the end) to help pruning.
12302 */
12303 if (add_new_state)
12304 sl->miss_cnt++;
12305 /* heuristic to determine whether this state is beneficial
12306 * to keep checking from state equivalence point of view.
12307 * Higher numbers increase max_states_per_insn and verification time,
12308 * but do not meaningfully decrease insn_processed.
12309 */
12310 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
12311 /* the state is unlikely to be useful. Remove it to
12312 * speed up verification
12313 */
12314 *pprev = sl->next;
12315 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
12316 u32 br = sl->state.branches;
12317
12318 WARN_ONCE(br,
12319 "BUG live_done but branches_to_explore %d\n",
12320 br);
12321 free_verifier_state(&sl->state, false);
12322 kfree(sl);
12323 env->peak_states--;
12324 } else {
12325 /* cannot free this state, since parentage chain may
12326 * walk it later. Add it for free_list instead to
12327 * be freed at the end of verification
12328 */
12329 sl->next = env->free_list;
12330 env->free_list = sl;
12331 }
12332 sl = *pprev;
12333 continue;
12334 }
12335 next:
12336 pprev = &sl->next;
12337 sl = *pprev;
12338 }
12339
12340 if (env->max_states_per_insn < states_cnt)
12341 env->max_states_per_insn = states_cnt;
12342
12343 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
12344 return push_jmp_history(env, cur);
12345
12346 if (!add_new_state)
12347 return push_jmp_history(env, cur);
12348
12349 /* There were no equivalent states, remember the current one.
12350 * Technically the current state is not proven to be safe yet,
12351 * but it will either reach outer most bpf_exit (which means it's safe)
12352 * or it will be rejected. When there are no loops the verifier won't be
12353 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
12354 * again on the way to bpf_exit.
12355 * When looping the sl->state.branches will be > 0 and this state
12356 * will not be considered for equivalence until branches == 0.
12357 */
12358 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
12359 if (!new_sl)
12360 return -ENOMEM;
12361 env->total_states++;
12362 env->peak_states++;
12363 env->prev_jmps_processed = env->jmps_processed;
12364 env->prev_insn_processed = env->insn_processed;
12365
12366 /* forget precise markings we inherited, see __mark_chain_precision */
12367 if (env->bpf_capable)
12368 mark_all_scalars_imprecise(env, cur);
12369
12370 /* add new state to the head of linked list */
12371 new = &new_sl->state;
12372 err = copy_verifier_state(new, cur);
12373 if (err) {
12374 free_verifier_state(new, false);
12375 kfree(new_sl);
12376 return err;
12377 }
12378 new->insn_idx = insn_idx;
12379 WARN_ONCE(new->branches != 1,
12380 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
12381
12382 cur->parent = new;
12383 cur->first_insn_idx = insn_idx;
12384 clear_jmp_history(cur);
12385 new_sl->next = *explored_state(env, insn_idx);
12386 *explored_state(env, insn_idx) = new_sl;
12387 /* connect new state to parentage chain. Current frame needs all
12388 * registers connected. Only r6 - r9 of the callers are alive (pushed
12389 * to the stack implicitly by JITs) so in callers' frames connect just
12390 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
12391 * the state of the call instruction (with WRITTEN set), and r0 comes
12392 * from callee with its full parentage chain, anyway.
12393 */
12394 /* clear write marks in current state: the writes we did are not writes
12395 * our child did, so they don't screen off its reads from us.
12396 * (There are no read marks in current state, because reads always mark
12397 * their parent and current state never has children yet. Only
12398 * explored_states can get read marks.)
12399 */
12400 for (j = 0; j <= cur->curframe; j++) {
12401 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
12402 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
12403 for (i = 0; i < BPF_REG_FP; i++)
12404 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
12405 }
12406
12407 /* all stack frames are accessible from callee, clear them all */
12408 for (j = 0; j <= cur->curframe; j++) {
12409 struct bpf_func_state *frame = cur->frame[j];
12410 struct bpf_func_state *newframe = new->frame[j];
12411
12412 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
12413 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
12414 frame->stack[i].spilled_ptr.parent =
12415 &newframe->stack[i].spilled_ptr;
12416 }
12417 }
12418 return 0;
12419 }
12420
12421 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)12422 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
12423 {
12424 switch (base_type(type)) {
12425 case PTR_TO_CTX:
12426 case PTR_TO_SOCKET:
12427 case PTR_TO_SOCK_COMMON:
12428 case PTR_TO_TCP_SOCK:
12429 case PTR_TO_XDP_SOCK:
12430 case PTR_TO_BTF_ID:
12431 return false;
12432 default:
12433 return true;
12434 }
12435 }
12436
12437 /* If an instruction was previously used with particular pointer types, then we
12438 * need to be careful to avoid cases such as the below, where it may be ok
12439 * for one branch accessing the pointer, but not ok for the other branch:
12440 *
12441 * R1 = sock_ptr
12442 * goto X;
12443 * ...
12444 * R1 = some_other_valid_ptr;
12445 * goto X;
12446 * ...
12447 * R2 = *(u32 *)(R1 + 0);
12448 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)12449 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
12450 {
12451 return src != prev && (!reg_type_mismatch_ok(src) ||
12452 !reg_type_mismatch_ok(prev));
12453 }
12454
do_check(struct bpf_verifier_env * env)12455 static int do_check(struct bpf_verifier_env *env)
12456 {
12457 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
12458 struct bpf_verifier_state *state = env->cur_state;
12459 struct bpf_insn *insns = env->prog->insnsi;
12460 struct bpf_reg_state *regs;
12461 int insn_cnt = env->prog->len;
12462 bool do_print_state = false;
12463 int prev_insn_idx = -1;
12464
12465 for (;;) {
12466 struct bpf_insn *insn;
12467 u8 class;
12468 int err;
12469
12470 env->prev_insn_idx = prev_insn_idx;
12471 if (env->insn_idx >= insn_cnt) {
12472 verbose(env, "invalid insn idx %d insn_cnt %d\n",
12473 env->insn_idx, insn_cnt);
12474 return -EFAULT;
12475 }
12476
12477 insn = &insns[env->insn_idx];
12478 class = BPF_CLASS(insn->code);
12479
12480 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
12481 verbose(env,
12482 "BPF program is too large. Processed %d insn\n",
12483 env->insn_processed);
12484 return -E2BIG;
12485 }
12486
12487 err = is_state_visited(env, env->insn_idx);
12488 if (err < 0)
12489 return err;
12490 if (err == 1) {
12491 /* found equivalent state, can prune the search */
12492 if (env->log.level & BPF_LOG_LEVEL) {
12493 if (do_print_state)
12494 verbose(env, "\nfrom %d to %d%s: safe\n",
12495 env->prev_insn_idx, env->insn_idx,
12496 env->cur_state->speculative ?
12497 " (speculative execution)" : "");
12498 else
12499 verbose(env, "%d: safe\n", env->insn_idx);
12500 }
12501 goto process_bpf_exit;
12502 }
12503
12504 if (signal_pending(current))
12505 return -EAGAIN;
12506
12507 if (need_resched())
12508 cond_resched();
12509
12510 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
12511 verbose(env, "\nfrom %d to %d%s:",
12512 env->prev_insn_idx, env->insn_idx,
12513 env->cur_state->speculative ?
12514 " (speculative execution)" : "");
12515 print_verifier_state(env, state->frame[state->curframe], true);
12516 do_print_state = false;
12517 }
12518
12519 if (env->log.level & BPF_LOG_LEVEL) {
12520 const struct bpf_insn_cbs cbs = {
12521 .cb_call = disasm_kfunc_name,
12522 .cb_print = verbose,
12523 .private_data = env,
12524 };
12525
12526 if (verifier_state_scratched(env))
12527 print_insn_state(env, state->frame[state->curframe]);
12528
12529 verbose_linfo(env, env->insn_idx, "; ");
12530 env->prev_log_len = env->log.len_used;
12531 verbose(env, "%d: ", env->insn_idx);
12532 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
12533 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
12534 env->prev_log_len = env->log.len_used;
12535 }
12536
12537 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12538 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
12539 env->prev_insn_idx);
12540 if (err)
12541 return err;
12542 }
12543
12544 regs = cur_regs(env);
12545 sanitize_mark_insn_seen(env);
12546 prev_insn_idx = env->insn_idx;
12547
12548 if (class == BPF_ALU || class == BPF_ALU64) {
12549 err = check_alu_op(env, insn);
12550 if (err)
12551 return err;
12552
12553 } else if (class == BPF_LDX) {
12554 enum bpf_reg_type *prev_src_type, src_reg_type;
12555
12556 /* check for reserved fields is already done */
12557
12558 /* check src operand */
12559 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12560 if (err)
12561 return err;
12562
12563 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
12564 if (err)
12565 return err;
12566
12567 src_reg_type = regs[insn->src_reg].type;
12568
12569 /* check that memory (src_reg + off) is readable,
12570 * the state of dst_reg will be updated by this func
12571 */
12572 err = check_mem_access(env, env->insn_idx, insn->src_reg,
12573 insn->off, BPF_SIZE(insn->code),
12574 BPF_READ, insn->dst_reg, false);
12575 if (err)
12576 return err;
12577
12578 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12579
12580 if (*prev_src_type == NOT_INIT) {
12581 /* saw a valid insn
12582 * dst_reg = *(u32 *)(src_reg + off)
12583 * save type to validate intersecting paths
12584 */
12585 *prev_src_type = src_reg_type;
12586
12587 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
12588 /* ABuser program is trying to use the same insn
12589 * dst_reg = *(u32*) (src_reg + off)
12590 * with different pointer types:
12591 * src_reg == ctx in one branch and
12592 * src_reg == stack|map in some other branch.
12593 * Reject it.
12594 */
12595 verbose(env, "same insn cannot be used with different pointers\n");
12596 return -EINVAL;
12597 }
12598
12599 } else if (class == BPF_STX) {
12600 enum bpf_reg_type *prev_dst_type, dst_reg_type;
12601
12602 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
12603 err = check_atomic(env, env->insn_idx, insn);
12604 if (err)
12605 return err;
12606 env->insn_idx++;
12607 continue;
12608 }
12609
12610 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
12611 verbose(env, "BPF_STX uses reserved fields\n");
12612 return -EINVAL;
12613 }
12614
12615 /* check src1 operand */
12616 err = check_reg_arg(env, insn->src_reg, SRC_OP);
12617 if (err)
12618 return err;
12619 /* check src2 operand */
12620 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12621 if (err)
12622 return err;
12623
12624 dst_reg_type = regs[insn->dst_reg].type;
12625
12626 /* check that memory (dst_reg + off) is writeable */
12627 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12628 insn->off, BPF_SIZE(insn->code),
12629 BPF_WRITE, insn->src_reg, false);
12630 if (err)
12631 return err;
12632
12633 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
12634
12635 if (*prev_dst_type == NOT_INIT) {
12636 *prev_dst_type = dst_reg_type;
12637 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
12638 verbose(env, "same insn cannot be used with different pointers\n");
12639 return -EINVAL;
12640 }
12641
12642 } else if (class == BPF_ST) {
12643 if (BPF_MODE(insn->code) != BPF_MEM ||
12644 insn->src_reg != BPF_REG_0) {
12645 verbose(env, "BPF_ST uses reserved fields\n");
12646 return -EINVAL;
12647 }
12648 /* check src operand */
12649 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
12650 if (err)
12651 return err;
12652
12653 if (is_ctx_reg(env, insn->dst_reg)) {
12654 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
12655 insn->dst_reg,
12656 reg_type_str(env, reg_state(env, insn->dst_reg)->type));
12657 return -EACCES;
12658 }
12659
12660 /* check that memory (dst_reg + off) is writeable */
12661 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
12662 insn->off, BPF_SIZE(insn->code),
12663 BPF_WRITE, -1, false);
12664 if (err)
12665 return err;
12666
12667 } else if (class == BPF_JMP || class == BPF_JMP32) {
12668 u8 opcode = BPF_OP(insn->code);
12669
12670 env->jmps_processed++;
12671 if (opcode == BPF_CALL) {
12672 if (BPF_SRC(insn->code) != BPF_K ||
12673 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
12674 && insn->off != 0) ||
12675 (insn->src_reg != BPF_REG_0 &&
12676 insn->src_reg != BPF_PSEUDO_CALL &&
12677 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
12678 insn->dst_reg != BPF_REG_0 ||
12679 class == BPF_JMP32) {
12680 verbose(env, "BPF_CALL uses reserved fields\n");
12681 return -EINVAL;
12682 }
12683
12684 if (env->cur_state->active_spin_lock &&
12685 (insn->src_reg == BPF_PSEUDO_CALL ||
12686 insn->imm != BPF_FUNC_spin_unlock)) {
12687 verbose(env, "function calls are not allowed while holding a lock\n");
12688 return -EINVAL;
12689 }
12690 if (insn->src_reg == BPF_PSEUDO_CALL)
12691 err = check_func_call(env, insn, &env->insn_idx);
12692 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
12693 err = check_kfunc_call(env, insn, &env->insn_idx);
12694 else
12695 err = check_helper_call(env, insn, &env->insn_idx);
12696 if (err)
12697 return err;
12698 } else if (opcode == BPF_JA) {
12699 if (BPF_SRC(insn->code) != BPF_K ||
12700 insn->imm != 0 ||
12701 insn->src_reg != BPF_REG_0 ||
12702 insn->dst_reg != BPF_REG_0 ||
12703 class == BPF_JMP32) {
12704 verbose(env, "BPF_JA uses reserved fields\n");
12705 return -EINVAL;
12706 }
12707
12708 env->insn_idx += insn->off + 1;
12709 continue;
12710
12711 } else if (opcode == BPF_EXIT) {
12712 if (BPF_SRC(insn->code) != BPF_K ||
12713 insn->imm != 0 ||
12714 insn->src_reg != BPF_REG_0 ||
12715 insn->dst_reg != BPF_REG_0 ||
12716 class == BPF_JMP32) {
12717 verbose(env, "BPF_EXIT uses reserved fields\n");
12718 return -EINVAL;
12719 }
12720
12721 if (env->cur_state->active_spin_lock) {
12722 verbose(env, "bpf_spin_unlock is missing\n");
12723 return -EINVAL;
12724 }
12725
12726 /* We must do check_reference_leak here before
12727 * prepare_func_exit to handle the case when
12728 * state->curframe > 0, it may be a callback
12729 * function, for which reference_state must
12730 * match caller reference state when it exits.
12731 */
12732 err = check_reference_leak(env);
12733 if (err)
12734 return err;
12735
12736 if (state->curframe) {
12737 /* exit from nested function */
12738 err = prepare_func_exit(env, &env->insn_idx);
12739 if (err)
12740 return err;
12741 do_print_state = true;
12742 continue;
12743 }
12744
12745 err = check_return_code(env);
12746 if (err)
12747 return err;
12748 process_bpf_exit:
12749 mark_verifier_state_scratched(env);
12750 update_branch_counts(env, env->cur_state);
12751 err = pop_stack(env, &prev_insn_idx,
12752 &env->insn_idx, pop_log);
12753 if (err < 0) {
12754 if (err != -ENOENT)
12755 return err;
12756 break;
12757 } else {
12758 do_print_state = true;
12759 continue;
12760 }
12761 } else {
12762 err = check_cond_jmp_op(env, insn, &env->insn_idx);
12763 if (err)
12764 return err;
12765 }
12766 } else if (class == BPF_LD) {
12767 u8 mode = BPF_MODE(insn->code);
12768
12769 if (mode == BPF_ABS || mode == BPF_IND) {
12770 err = check_ld_abs(env, insn);
12771 if (err)
12772 return err;
12773
12774 } else if (mode == BPF_IMM) {
12775 err = check_ld_imm(env, insn);
12776 if (err)
12777 return err;
12778
12779 env->insn_idx++;
12780 sanitize_mark_insn_seen(env);
12781 } else {
12782 verbose(env, "invalid BPF_LD mode\n");
12783 return -EINVAL;
12784 }
12785 } else {
12786 verbose(env, "unknown insn class %d\n", class);
12787 return -EINVAL;
12788 }
12789
12790 env->insn_idx++;
12791 }
12792
12793 return 0;
12794 }
12795
find_btf_percpu_datasec(struct btf * btf)12796 static int find_btf_percpu_datasec(struct btf *btf)
12797 {
12798 const struct btf_type *t;
12799 const char *tname;
12800 int i, n;
12801
12802 /*
12803 * Both vmlinux and module each have their own ".data..percpu"
12804 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
12805 * types to look at only module's own BTF types.
12806 */
12807 n = btf_nr_types(btf);
12808 if (btf_is_module(btf))
12809 i = btf_nr_types(btf_vmlinux);
12810 else
12811 i = 1;
12812
12813 for(; i < n; i++) {
12814 t = btf_type_by_id(btf, i);
12815 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
12816 continue;
12817
12818 tname = btf_name_by_offset(btf, t->name_off);
12819 if (!strcmp(tname, ".data..percpu"))
12820 return i;
12821 }
12822
12823 return -ENOENT;
12824 }
12825
12826 /* 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)12827 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
12828 struct bpf_insn *insn,
12829 struct bpf_insn_aux_data *aux)
12830 {
12831 const struct btf_var_secinfo *vsi;
12832 const struct btf_type *datasec;
12833 struct btf_mod_pair *btf_mod;
12834 const struct btf_type *t;
12835 const char *sym_name;
12836 bool percpu = false;
12837 u32 type, id = insn->imm;
12838 struct btf *btf;
12839 s32 datasec_id;
12840 u64 addr;
12841 int i, btf_fd, err;
12842
12843 btf_fd = insn[1].imm;
12844 if (btf_fd) {
12845 btf = btf_get_by_fd(btf_fd);
12846 if (IS_ERR(btf)) {
12847 verbose(env, "invalid module BTF object FD specified.\n");
12848 return -EINVAL;
12849 }
12850 } else {
12851 if (!btf_vmlinux) {
12852 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
12853 return -EINVAL;
12854 }
12855 btf = btf_vmlinux;
12856 btf_get(btf);
12857 }
12858
12859 t = btf_type_by_id(btf, id);
12860 if (!t) {
12861 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
12862 err = -ENOENT;
12863 goto err_put;
12864 }
12865
12866 if (!btf_type_is_var(t)) {
12867 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
12868 err = -EINVAL;
12869 goto err_put;
12870 }
12871
12872 sym_name = btf_name_by_offset(btf, t->name_off);
12873 addr = kallsyms_lookup_name(sym_name);
12874 if (!addr) {
12875 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
12876 sym_name);
12877 err = -ENOENT;
12878 goto err_put;
12879 }
12880
12881 datasec_id = find_btf_percpu_datasec(btf);
12882 if (datasec_id > 0) {
12883 datasec = btf_type_by_id(btf, datasec_id);
12884 for_each_vsi(i, datasec, vsi) {
12885 if (vsi->type == id) {
12886 percpu = true;
12887 break;
12888 }
12889 }
12890 }
12891
12892 insn[0].imm = (u32)addr;
12893 insn[1].imm = addr >> 32;
12894
12895 type = t->type;
12896 t = btf_type_skip_modifiers(btf, type, NULL);
12897 if (percpu) {
12898 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
12899 aux->btf_var.btf = btf;
12900 aux->btf_var.btf_id = type;
12901 } else if (!btf_type_is_struct(t)) {
12902 const struct btf_type *ret;
12903 const char *tname;
12904 u32 tsize;
12905
12906 /* resolve the type size of ksym. */
12907 ret = btf_resolve_size(btf, t, &tsize);
12908 if (IS_ERR(ret)) {
12909 tname = btf_name_by_offset(btf, t->name_off);
12910 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
12911 tname, PTR_ERR(ret));
12912 err = -EINVAL;
12913 goto err_put;
12914 }
12915 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
12916 aux->btf_var.mem_size = tsize;
12917 } else {
12918 aux->btf_var.reg_type = PTR_TO_BTF_ID;
12919 aux->btf_var.btf = btf;
12920 aux->btf_var.btf_id = type;
12921 }
12922
12923 /* check whether we recorded this BTF (and maybe module) already */
12924 for (i = 0; i < env->used_btf_cnt; i++) {
12925 if (env->used_btfs[i].btf == btf) {
12926 btf_put(btf);
12927 return 0;
12928 }
12929 }
12930
12931 if (env->used_btf_cnt >= MAX_USED_BTFS) {
12932 err = -E2BIG;
12933 goto err_put;
12934 }
12935
12936 btf_mod = &env->used_btfs[env->used_btf_cnt];
12937 btf_mod->btf = btf;
12938 btf_mod->module = NULL;
12939
12940 /* if we reference variables from kernel module, bump its refcount */
12941 if (btf_is_module(btf)) {
12942 btf_mod->module = btf_try_get_module(btf);
12943 if (!btf_mod->module) {
12944 err = -ENXIO;
12945 goto err_put;
12946 }
12947 }
12948
12949 env->used_btf_cnt++;
12950
12951 return 0;
12952 err_put:
12953 btf_put(btf);
12954 return err;
12955 }
12956
is_tracing_prog_type(enum bpf_prog_type type)12957 static bool is_tracing_prog_type(enum bpf_prog_type type)
12958 {
12959 switch (type) {
12960 case BPF_PROG_TYPE_KPROBE:
12961 case BPF_PROG_TYPE_TRACEPOINT:
12962 case BPF_PROG_TYPE_PERF_EVENT:
12963 case BPF_PROG_TYPE_RAW_TRACEPOINT:
12964 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
12965 return true;
12966 default:
12967 return false;
12968 }
12969 }
12970
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)12971 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
12972 struct bpf_map *map,
12973 struct bpf_prog *prog)
12974
12975 {
12976 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12977
12978 if (map_value_has_spin_lock(map)) {
12979 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
12980 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
12981 return -EINVAL;
12982 }
12983
12984 if (is_tracing_prog_type(prog_type)) {
12985 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
12986 return -EINVAL;
12987 }
12988
12989 if (prog->aux->sleepable) {
12990 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
12991 return -EINVAL;
12992 }
12993 }
12994
12995 if (map_value_has_timer(map)) {
12996 if (is_tracing_prog_type(prog_type)) {
12997 verbose(env, "tracing progs cannot use bpf_timer yet\n");
12998 return -EINVAL;
12999 }
13000 }
13001
13002 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
13003 !bpf_offload_prog_map_match(prog, map)) {
13004 verbose(env, "offload device mismatch between prog and map\n");
13005 return -EINVAL;
13006 }
13007
13008 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
13009 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
13010 return -EINVAL;
13011 }
13012
13013 if (prog->aux->sleepable)
13014 switch (map->map_type) {
13015 case BPF_MAP_TYPE_HASH:
13016 case BPF_MAP_TYPE_LRU_HASH:
13017 case BPF_MAP_TYPE_ARRAY:
13018 case BPF_MAP_TYPE_PERCPU_HASH:
13019 case BPF_MAP_TYPE_PERCPU_ARRAY:
13020 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
13021 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
13022 case BPF_MAP_TYPE_HASH_OF_MAPS:
13023 case BPF_MAP_TYPE_RINGBUF:
13024 case BPF_MAP_TYPE_USER_RINGBUF:
13025 case BPF_MAP_TYPE_INODE_STORAGE:
13026 case BPF_MAP_TYPE_SK_STORAGE:
13027 case BPF_MAP_TYPE_TASK_STORAGE:
13028 break;
13029 default:
13030 verbose(env,
13031 "Sleepable programs can only use array, hash, and ringbuf maps\n");
13032 return -EINVAL;
13033 }
13034
13035 return 0;
13036 }
13037
bpf_map_is_cgroup_storage(struct bpf_map * map)13038 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
13039 {
13040 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
13041 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
13042 }
13043
13044 /* find and rewrite pseudo imm in ld_imm64 instructions:
13045 *
13046 * 1. if it accesses map FD, replace it with actual map pointer.
13047 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
13048 *
13049 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
13050 */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)13051 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
13052 {
13053 struct bpf_insn *insn = env->prog->insnsi;
13054 int insn_cnt = env->prog->len;
13055 int i, j, err;
13056
13057 err = bpf_prog_calc_tag(env->prog);
13058 if (err)
13059 return err;
13060
13061 for (i = 0; i < insn_cnt; i++, insn++) {
13062 if (BPF_CLASS(insn->code) == BPF_LDX &&
13063 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
13064 verbose(env, "BPF_LDX uses reserved fields\n");
13065 return -EINVAL;
13066 }
13067
13068 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
13069 struct bpf_insn_aux_data *aux;
13070 struct bpf_map *map;
13071 struct fd f;
13072 u64 addr;
13073 u32 fd;
13074
13075 if (i == insn_cnt - 1 || insn[1].code != 0 ||
13076 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
13077 insn[1].off != 0) {
13078 verbose(env, "invalid bpf_ld_imm64 insn\n");
13079 return -EINVAL;
13080 }
13081
13082 if (insn[0].src_reg == 0)
13083 /* valid generic load 64-bit imm */
13084 goto next_insn;
13085
13086 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
13087 aux = &env->insn_aux_data[i];
13088 err = check_pseudo_btf_id(env, insn, aux);
13089 if (err)
13090 return err;
13091 goto next_insn;
13092 }
13093
13094 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
13095 aux = &env->insn_aux_data[i];
13096 aux->ptr_type = PTR_TO_FUNC;
13097 goto next_insn;
13098 }
13099
13100 /* In final convert_pseudo_ld_imm64() step, this is
13101 * converted into regular 64-bit imm load insn.
13102 */
13103 switch (insn[0].src_reg) {
13104 case BPF_PSEUDO_MAP_VALUE:
13105 case BPF_PSEUDO_MAP_IDX_VALUE:
13106 break;
13107 case BPF_PSEUDO_MAP_FD:
13108 case BPF_PSEUDO_MAP_IDX:
13109 if (insn[1].imm == 0)
13110 break;
13111 fallthrough;
13112 default:
13113 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
13114 return -EINVAL;
13115 }
13116
13117 switch (insn[0].src_reg) {
13118 case BPF_PSEUDO_MAP_IDX_VALUE:
13119 case BPF_PSEUDO_MAP_IDX:
13120 if (bpfptr_is_null(env->fd_array)) {
13121 verbose(env, "fd_idx without fd_array is invalid\n");
13122 return -EPROTO;
13123 }
13124 if (copy_from_bpfptr_offset(&fd, env->fd_array,
13125 insn[0].imm * sizeof(fd),
13126 sizeof(fd)))
13127 return -EFAULT;
13128 break;
13129 default:
13130 fd = insn[0].imm;
13131 break;
13132 }
13133
13134 f = fdget(fd);
13135 map = __bpf_map_get(f);
13136 if (IS_ERR(map)) {
13137 verbose(env, "fd %d is not pointing to valid bpf_map\n",
13138 insn[0].imm);
13139 return PTR_ERR(map);
13140 }
13141
13142 err = check_map_prog_compatibility(env, map, env->prog);
13143 if (err) {
13144 fdput(f);
13145 return err;
13146 }
13147
13148 aux = &env->insn_aux_data[i];
13149 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
13150 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
13151 addr = (unsigned long)map;
13152 } else {
13153 u32 off = insn[1].imm;
13154
13155 if (off >= BPF_MAX_VAR_OFF) {
13156 verbose(env, "direct value offset of %u is not allowed\n", off);
13157 fdput(f);
13158 return -EINVAL;
13159 }
13160
13161 if (!map->ops->map_direct_value_addr) {
13162 verbose(env, "no direct value access support for this map type\n");
13163 fdput(f);
13164 return -EINVAL;
13165 }
13166
13167 err = map->ops->map_direct_value_addr(map, &addr, off);
13168 if (err) {
13169 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
13170 map->value_size, off);
13171 fdput(f);
13172 return err;
13173 }
13174
13175 aux->map_off = off;
13176 addr += off;
13177 }
13178
13179 insn[0].imm = (u32)addr;
13180 insn[1].imm = addr >> 32;
13181
13182 /* check whether we recorded this map already */
13183 for (j = 0; j < env->used_map_cnt; j++) {
13184 if (env->used_maps[j] == map) {
13185 aux->map_index = j;
13186 fdput(f);
13187 goto next_insn;
13188 }
13189 }
13190
13191 if (env->used_map_cnt >= MAX_USED_MAPS) {
13192 fdput(f);
13193 return -E2BIG;
13194 }
13195
13196 /* hold the map. If the program is rejected by verifier,
13197 * the map will be released by release_maps() or it
13198 * will be used by the valid program until it's unloaded
13199 * and all maps are released in free_used_maps()
13200 */
13201 bpf_map_inc(map);
13202
13203 aux->map_index = env->used_map_cnt;
13204 env->used_maps[env->used_map_cnt++] = map;
13205
13206 if (bpf_map_is_cgroup_storage(map) &&
13207 bpf_cgroup_storage_assign(env->prog->aux, map)) {
13208 verbose(env, "only one cgroup storage of each type is allowed\n");
13209 fdput(f);
13210 return -EBUSY;
13211 }
13212
13213 fdput(f);
13214 next_insn:
13215 insn++;
13216 i++;
13217 continue;
13218 }
13219
13220 /* Basic sanity check before we invest more work here. */
13221 if (!bpf_opcode_in_insntable(insn->code)) {
13222 verbose(env, "unknown opcode %02x\n", insn->code);
13223 return -EINVAL;
13224 }
13225 }
13226
13227 /* now all pseudo BPF_LD_IMM64 instructions load valid
13228 * 'struct bpf_map *' into a register instead of user map_fd.
13229 * These pointers will be used later by verifier to validate map access.
13230 */
13231 return 0;
13232 }
13233
13234 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)13235 static void release_maps(struct bpf_verifier_env *env)
13236 {
13237 __bpf_free_used_maps(env->prog->aux, env->used_maps,
13238 env->used_map_cnt);
13239 }
13240
13241 /* drop refcnt of maps used by the rejected program */
release_btfs(struct bpf_verifier_env * env)13242 static void release_btfs(struct bpf_verifier_env *env)
13243 {
13244 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
13245 env->used_btf_cnt);
13246 }
13247
13248 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)13249 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
13250 {
13251 struct bpf_insn *insn = env->prog->insnsi;
13252 int insn_cnt = env->prog->len;
13253 int i;
13254
13255 for (i = 0; i < insn_cnt; i++, insn++) {
13256 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
13257 continue;
13258 if (insn->src_reg == BPF_PSEUDO_FUNC)
13259 continue;
13260 insn->src_reg = 0;
13261 }
13262 }
13263
13264 /* single env->prog->insni[off] instruction was replaced with the range
13265 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
13266 * [0, off) and [off, end) to new locations, so the patched range stays zero
13267 */
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)13268 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
13269 struct bpf_insn_aux_data *new_data,
13270 struct bpf_prog *new_prog, u32 off, u32 cnt)
13271 {
13272 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
13273 struct bpf_insn *insn = new_prog->insnsi;
13274 u32 old_seen = old_data[off].seen;
13275 u32 prog_len;
13276 int i;
13277
13278 /* aux info at OFF always needs adjustment, no matter fast path
13279 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
13280 * original insn at old prog.
13281 */
13282 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
13283
13284 if (cnt == 1)
13285 return;
13286 prog_len = new_prog->len;
13287
13288 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
13289 memcpy(new_data + off + cnt - 1, old_data + off,
13290 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
13291 for (i = off; i < off + cnt - 1; i++) {
13292 /* Expand insni[off]'s seen count to the patched range. */
13293 new_data[i].seen = old_seen;
13294 new_data[i].zext_dst = insn_has_def32(env, insn + i);
13295 }
13296 env->insn_aux_data = new_data;
13297 vfree(old_data);
13298 }
13299
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)13300 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
13301 {
13302 int i;
13303
13304 if (len == 1)
13305 return;
13306 /* NOTE: fake 'exit' subprog should be updated as well. */
13307 for (i = 0; i <= env->subprog_cnt; i++) {
13308 if (env->subprog_info[i].start <= off)
13309 continue;
13310 env->subprog_info[i].start += len - 1;
13311 }
13312 }
13313
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)13314 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
13315 {
13316 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
13317 int i, sz = prog->aux->size_poke_tab;
13318 struct bpf_jit_poke_descriptor *desc;
13319
13320 for (i = 0; i < sz; i++) {
13321 desc = &tab[i];
13322 if (desc->insn_idx <= off)
13323 continue;
13324 desc->insn_idx += len - 1;
13325 }
13326 }
13327
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)13328 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
13329 const struct bpf_insn *patch, u32 len)
13330 {
13331 struct bpf_prog *new_prog;
13332 struct bpf_insn_aux_data *new_data = NULL;
13333
13334 if (len > 1) {
13335 new_data = vzalloc(array_size(env->prog->len + len - 1,
13336 sizeof(struct bpf_insn_aux_data)));
13337 if (!new_data)
13338 return NULL;
13339 }
13340
13341 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
13342 if (IS_ERR(new_prog)) {
13343 if (PTR_ERR(new_prog) == -ERANGE)
13344 verbose(env,
13345 "insn %d cannot be patched due to 16-bit range\n",
13346 env->insn_aux_data[off].orig_idx);
13347 vfree(new_data);
13348 return NULL;
13349 }
13350 adjust_insn_aux_data(env, new_data, new_prog, off, len);
13351 adjust_subprog_starts(env, off, len);
13352 adjust_poke_descs(new_prog, off, len);
13353 return new_prog;
13354 }
13355
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)13356 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
13357 u32 off, u32 cnt)
13358 {
13359 int i, j;
13360
13361 /* find first prog starting at or after off (first to remove) */
13362 for (i = 0; i < env->subprog_cnt; i++)
13363 if (env->subprog_info[i].start >= off)
13364 break;
13365 /* find first prog starting at or after off + cnt (first to stay) */
13366 for (j = i; j < env->subprog_cnt; j++)
13367 if (env->subprog_info[j].start >= off + cnt)
13368 break;
13369 /* if j doesn't start exactly at off + cnt, we are just removing
13370 * the front of previous prog
13371 */
13372 if (env->subprog_info[j].start != off + cnt)
13373 j--;
13374
13375 if (j > i) {
13376 struct bpf_prog_aux *aux = env->prog->aux;
13377 int move;
13378
13379 /* move fake 'exit' subprog as well */
13380 move = env->subprog_cnt + 1 - j;
13381
13382 memmove(env->subprog_info + i,
13383 env->subprog_info + j,
13384 sizeof(*env->subprog_info) * move);
13385 env->subprog_cnt -= j - i;
13386
13387 /* remove func_info */
13388 if (aux->func_info) {
13389 move = aux->func_info_cnt - j;
13390
13391 memmove(aux->func_info + i,
13392 aux->func_info + j,
13393 sizeof(*aux->func_info) * move);
13394 aux->func_info_cnt -= j - i;
13395 /* func_info->insn_off is set after all code rewrites,
13396 * in adjust_btf_func() - no need to adjust
13397 */
13398 }
13399 } else {
13400 /* convert i from "first prog to remove" to "first to adjust" */
13401 if (env->subprog_info[i].start == off)
13402 i++;
13403 }
13404
13405 /* update fake 'exit' subprog as well */
13406 for (; i <= env->subprog_cnt; i++)
13407 env->subprog_info[i].start -= cnt;
13408
13409 return 0;
13410 }
13411
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)13412 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
13413 u32 cnt)
13414 {
13415 struct bpf_prog *prog = env->prog;
13416 u32 i, l_off, l_cnt, nr_linfo;
13417 struct bpf_line_info *linfo;
13418
13419 nr_linfo = prog->aux->nr_linfo;
13420 if (!nr_linfo)
13421 return 0;
13422
13423 linfo = prog->aux->linfo;
13424
13425 /* find first line info to remove, count lines to be removed */
13426 for (i = 0; i < nr_linfo; i++)
13427 if (linfo[i].insn_off >= off)
13428 break;
13429
13430 l_off = i;
13431 l_cnt = 0;
13432 for (; i < nr_linfo; i++)
13433 if (linfo[i].insn_off < off + cnt)
13434 l_cnt++;
13435 else
13436 break;
13437
13438 /* First live insn doesn't match first live linfo, it needs to "inherit"
13439 * last removed linfo. prog is already modified, so prog->len == off
13440 * means no live instructions after (tail of the program was removed).
13441 */
13442 if (prog->len != off && l_cnt &&
13443 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
13444 l_cnt--;
13445 linfo[--i].insn_off = off + cnt;
13446 }
13447
13448 /* remove the line info which refer to the removed instructions */
13449 if (l_cnt) {
13450 memmove(linfo + l_off, linfo + i,
13451 sizeof(*linfo) * (nr_linfo - i));
13452
13453 prog->aux->nr_linfo -= l_cnt;
13454 nr_linfo = prog->aux->nr_linfo;
13455 }
13456
13457 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
13458 for (i = l_off; i < nr_linfo; i++)
13459 linfo[i].insn_off -= cnt;
13460
13461 /* fix up all subprogs (incl. 'exit') which start >= off */
13462 for (i = 0; i <= env->subprog_cnt; i++)
13463 if (env->subprog_info[i].linfo_idx > l_off) {
13464 /* program may have started in the removed region but
13465 * may not be fully removed
13466 */
13467 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
13468 env->subprog_info[i].linfo_idx -= l_cnt;
13469 else
13470 env->subprog_info[i].linfo_idx = l_off;
13471 }
13472
13473 return 0;
13474 }
13475
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)13476 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
13477 {
13478 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13479 unsigned int orig_prog_len = env->prog->len;
13480 int err;
13481
13482 if (bpf_prog_is_dev_bound(env->prog->aux))
13483 bpf_prog_offload_remove_insns(env, off, cnt);
13484
13485 err = bpf_remove_insns(env->prog, off, cnt);
13486 if (err)
13487 return err;
13488
13489 err = adjust_subprog_starts_after_remove(env, off, cnt);
13490 if (err)
13491 return err;
13492
13493 err = bpf_adj_linfo_after_remove(env, off, cnt);
13494 if (err)
13495 return err;
13496
13497 memmove(aux_data + off, aux_data + off + cnt,
13498 sizeof(*aux_data) * (orig_prog_len - off - cnt));
13499
13500 return 0;
13501 }
13502
13503 /* The verifier does more data flow analysis than llvm and will not
13504 * explore branches that are dead at run time. Malicious programs can
13505 * have dead code too. Therefore replace all dead at-run-time code
13506 * with 'ja -1'.
13507 *
13508 * Just nops are not optimal, e.g. if they would sit at the end of the
13509 * program and through another bug we would manage to jump there, then
13510 * we'd execute beyond program memory otherwise. Returning exception
13511 * code also wouldn't work since we can have subprogs where the dead
13512 * code could be located.
13513 */
sanitize_dead_code(struct bpf_verifier_env * env)13514 static void sanitize_dead_code(struct bpf_verifier_env *env)
13515 {
13516 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13517 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
13518 struct bpf_insn *insn = env->prog->insnsi;
13519 const int insn_cnt = env->prog->len;
13520 int i;
13521
13522 for (i = 0; i < insn_cnt; i++) {
13523 if (aux_data[i].seen)
13524 continue;
13525 memcpy(insn + i, &trap, sizeof(trap));
13526 aux_data[i].zext_dst = false;
13527 }
13528 }
13529
insn_is_cond_jump(u8 code)13530 static bool insn_is_cond_jump(u8 code)
13531 {
13532 u8 op;
13533
13534 if (BPF_CLASS(code) == BPF_JMP32)
13535 return true;
13536
13537 if (BPF_CLASS(code) != BPF_JMP)
13538 return false;
13539
13540 op = BPF_OP(code);
13541 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
13542 }
13543
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)13544 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
13545 {
13546 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13547 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13548 struct bpf_insn *insn = env->prog->insnsi;
13549 const int insn_cnt = env->prog->len;
13550 int i;
13551
13552 for (i = 0; i < insn_cnt; i++, insn++) {
13553 if (!insn_is_cond_jump(insn->code))
13554 continue;
13555
13556 if (!aux_data[i + 1].seen)
13557 ja.off = insn->off;
13558 else if (!aux_data[i + 1 + insn->off].seen)
13559 ja.off = 0;
13560 else
13561 continue;
13562
13563 if (bpf_prog_is_dev_bound(env->prog->aux))
13564 bpf_prog_offload_replace_insn(env, i, &ja);
13565
13566 memcpy(insn, &ja, sizeof(ja));
13567 }
13568 }
13569
opt_remove_dead_code(struct bpf_verifier_env * env)13570 static int opt_remove_dead_code(struct bpf_verifier_env *env)
13571 {
13572 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
13573 int insn_cnt = env->prog->len;
13574 int i, err;
13575
13576 for (i = 0; i < insn_cnt; i++) {
13577 int j;
13578
13579 j = 0;
13580 while (i + j < insn_cnt && !aux_data[i + j].seen)
13581 j++;
13582 if (!j)
13583 continue;
13584
13585 err = verifier_remove_insns(env, i, j);
13586 if (err)
13587 return err;
13588 insn_cnt = env->prog->len;
13589 }
13590
13591 return 0;
13592 }
13593
opt_remove_nops(struct bpf_verifier_env * env)13594 static int opt_remove_nops(struct bpf_verifier_env *env)
13595 {
13596 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
13597 struct bpf_insn *insn = env->prog->insnsi;
13598 int insn_cnt = env->prog->len;
13599 int i, err;
13600
13601 for (i = 0; i < insn_cnt; i++) {
13602 if (memcmp(&insn[i], &ja, sizeof(ja)))
13603 continue;
13604
13605 err = verifier_remove_insns(env, i, 1);
13606 if (err)
13607 return err;
13608 insn_cnt--;
13609 i--;
13610 }
13611
13612 return 0;
13613 }
13614
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)13615 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
13616 const union bpf_attr *attr)
13617 {
13618 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
13619 struct bpf_insn_aux_data *aux = env->insn_aux_data;
13620 int i, patch_len, delta = 0, len = env->prog->len;
13621 struct bpf_insn *insns = env->prog->insnsi;
13622 struct bpf_prog *new_prog;
13623 bool rnd_hi32;
13624
13625 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
13626 zext_patch[1] = BPF_ZEXT_REG(0);
13627 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
13628 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
13629 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
13630 for (i = 0; i < len; i++) {
13631 int adj_idx = i + delta;
13632 struct bpf_insn insn;
13633 int load_reg;
13634
13635 insn = insns[adj_idx];
13636 load_reg = insn_def_regno(&insn);
13637 if (!aux[adj_idx].zext_dst) {
13638 u8 code, class;
13639 u32 imm_rnd;
13640
13641 if (!rnd_hi32)
13642 continue;
13643
13644 code = insn.code;
13645 class = BPF_CLASS(code);
13646 if (load_reg == -1)
13647 continue;
13648
13649 /* NOTE: arg "reg" (the fourth one) is only used for
13650 * BPF_STX + SRC_OP, so it is safe to pass NULL
13651 * here.
13652 */
13653 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
13654 if (class == BPF_LD &&
13655 BPF_MODE(code) == BPF_IMM)
13656 i++;
13657 continue;
13658 }
13659
13660 /* ctx load could be transformed into wider load. */
13661 if (class == BPF_LDX &&
13662 aux[adj_idx].ptr_type == PTR_TO_CTX)
13663 continue;
13664
13665 imm_rnd = get_random_u32();
13666 rnd_hi32_patch[0] = insn;
13667 rnd_hi32_patch[1].imm = imm_rnd;
13668 rnd_hi32_patch[3].dst_reg = load_reg;
13669 patch = rnd_hi32_patch;
13670 patch_len = 4;
13671 goto apply_patch_buffer;
13672 }
13673
13674 /* Add in an zero-extend instruction if a) the JIT has requested
13675 * it or b) it's a CMPXCHG.
13676 *
13677 * The latter is because: BPF_CMPXCHG always loads a value into
13678 * R0, therefore always zero-extends. However some archs'
13679 * equivalent instruction only does this load when the
13680 * comparison is successful. This detail of CMPXCHG is
13681 * orthogonal to the general zero-extension behaviour of the
13682 * CPU, so it's treated independently of bpf_jit_needs_zext.
13683 */
13684 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
13685 continue;
13686
13687 /* Zero-extension is done by the caller. */
13688 if (bpf_pseudo_kfunc_call(&insn))
13689 continue;
13690
13691 if (WARN_ON(load_reg == -1)) {
13692 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
13693 return -EFAULT;
13694 }
13695
13696 zext_patch[0] = insn;
13697 zext_patch[1].dst_reg = load_reg;
13698 zext_patch[1].src_reg = load_reg;
13699 patch = zext_patch;
13700 patch_len = 2;
13701 apply_patch_buffer:
13702 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
13703 if (!new_prog)
13704 return -ENOMEM;
13705 env->prog = new_prog;
13706 insns = new_prog->insnsi;
13707 aux = env->insn_aux_data;
13708 delta += patch_len - 1;
13709 }
13710
13711 return 0;
13712 }
13713
13714 /* convert load instructions that access fields of a context type into a
13715 * sequence of instructions that access fields of the underlying structure:
13716 * struct __sk_buff -> struct sk_buff
13717 * struct bpf_sock_ops -> struct sock
13718 */
convert_ctx_accesses(struct bpf_verifier_env * env)13719 static int convert_ctx_accesses(struct bpf_verifier_env *env)
13720 {
13721 const struct bpf_verifier_ops *ops = env->ops;
13722 int i, cnt, size, ctx_field_size, delta = 0;
13723 const int insn_cnt = env->prog->len;
13724 struct bpf_insn insn_buf[16], *insn;
13725 u32 target_size, size_default, off;
13726 struct bpf_prog *new_prog;
13727 enum bpf_access_type type;
13728 bool is_narrower_load;
13729
13730 if (ops->gen_prologue || env->seen_direct_write) {
13731 if (!ops->gen_prologue) {
13732 verbose(env, "bpf verifier is misconfigured\n");
13733 return -EINVAL;
13734 }
13735 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
13736 env->prog);
13737 if (cnt >= ARRAY_SIZE(insn_buf)) {
13738 verbose(env, "bpf verifier is misconfigured\n");
13739 return -EINVAL;
13740 } else if (cnt) {
13741 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
13742 if (!new_prog)
13743 return -ENOMEM;
13744
13745 env->prog = new_prog;
13746 delta += cnt - 1;
13747 }
13748 }
13749
13750 if (bpf_prog_is_dev_bound(env->prog->aux))
13751 return 0;
13752
13753 insn = env->prog->insnsi + delta;
13754
13755 for (i = 0; i < insn_cnt; i++, insn++) {
13756 bpf_convert_ctx_access_t convert_ctx_access;
13757 bool ctx_access;
13758
13759 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
13760 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
13761 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
13762 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
13763 type = BPF_READ;
13764 ctx_access = true;
13765 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
13766 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
13767 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
13768 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
13769 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
13770 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
13771 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
13772 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
13773 type = BPF_WRITE;
13774 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
13775 } else {
13776 continue;
13777 }
13778
13779 if (type == BPF_WRITE &&
13780 env->insn_aux_data[i + delta].sanitize_stack_spill) {
13781 struct bpf_insn patch[] = {
13782 *insn,
13783 BPF_ST_NOSPEC(),
13784 };
13785
13786 cnt = ARRAY_SIZE(patch);
13787 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
13788 if (!new_prog)
13789 return -ENOMEM;
13790
13791 delta += cnt - 1;
13792 env->prog = new_prog;
13793 insn = new_prog->insnsi + i + delta;
13794 continue;
13795 }
13796
13797 if (!ctx_access)
13798 continue;
13799
13800 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
13801 case PTR_TO_CTX:
13802 if (!ops->convert_ctx_access)
13803 continue;
13804 convert_ctx_access = ops->convert_ctx_access;
13805 break;
13806 case PTR_TO_SOCKET:
13807 case PTR_TO_SOCK_COMMON:
13808 convert_ctx_access = bpf_sock_convert_ctx_access;
13809 break;
13810 case PTR_TO_TCP_SOCK:
13811 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
13812 break;
13813 case PTR_TO_XDP_SOCK:
13814 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
13815 break;
13816 case PTR_TO_BTF_ID:
13817 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
13818 if (type == BPF_READ) {
13819 insn->code = BPF_LDX | BPF_PROBE_MEM |
13820 BPF_SIZE((insn)->code);
13821 env->prog->aux->num_exentries++;
13822 }
13823 continue;
13824 default:
13825 continue;
13826 }
13827
13828 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
13829 size = BPF_LDST_BYTES(insn);
13830
13831 /* If the read access is a narrower load of the field,
13832 * convert to a 4/8-byte load, to minimum program type specific
13833 * convert_ctx_access changes. If conversion is successful,
13834 * we will apply proper mask to the result.
13835 */
13836 is_narrower_load = size < ctx_field_size;
13837 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
13838 off = insn->off;
13839 if (is_narrower_load) {
13840 u8 size_code;
13841
13842 if (type == BPF_WRITE) {
13843 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
13844 return -EINVAL;
13845 }
13846
13847 size_code = BPF_H;
13848 if (ctx_field_size == 4)
13849 size_code = BPF_W;
13850 else if (ctx_field_size == 8)
13851 size_code = BPF_DW;
13852
13853 insn->off = off & ~(size_default - 1);
13854 insn->code = BPF_LDX | BPF_MEM | size_code;
13855 }
13856
13857 target_size = 0;
13858 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
13859 &target_size);
13860 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
13861 (ctx_field_size && !target_size)) {
13862 verbose(env, "bpf verifier is misconfigured\n");
13863 return -EINVAL;
13864 }
13865
13866 if (is_narrower_load && size < target_size) {
13867 u8 shift = bpf_ctx_narrow_access_offset(
13868 off, size, size_default) * 8;
13869 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
13870 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
13871 return -EINVAL;
13872 }
13873 if (ctx_field_size <= 4) {
13874 if (shift)
13875 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
13876 insn->dst_reg,
13877 shift);
13878 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13879 (1 << size * 8) - 1);
13880 } else {
13881 if (shift)
13882 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
13883 insn->dst_reg,
13884 shift);
13885 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
13886 (1ULL << size * 8) - 1);
13887 }
13888 }
13889
13890 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13891 if (!new_prog)
13892 return -ENOMEM;
13893
13894 delta += cnt - 1;
13895
13896 /* keep walking new program and skip insns we just inserted */
13897 env->prog = new_prog;
13898 insn = new_prog->insnsi + i + delta;
13899 }
13900
13901 return 0;
13902 }
13903
jit_subprogs(struct bpf_verifier_env * env)13904 static int jit_subprogs(struct bpf_verifier_env *env)
13905 {
13906 struct bpf_prog *prog = env->prog, **func, *tmp;
13907 int i, j, subprog_start, subprog_end = 0, len, subprog;
13908 struct bpf_map *map_ptr;
13909 struct bpf_insn *insn;
13910 void *old_bpf_func;
13911 int err, num_exentries;
13912
13913 if (env->subprog_cnt <= 1)
13914 return 0;
13915
13916 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
13917 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
13918 continue;
13919
13920 /* Upon error here we cannot fall back to interpreter but
13921 * need a hard reject of the program. Thus -EFAULT is
13922 * propagated in any case.
13923 */
13924 subprog = find_subprog(env, i + insn->imm + 1);
13925 if (subprog < 0) {
13926 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
13927 i + insn->imm + 1);
13928 return -EFAULT;
13929 }
13930 /* temporarily remember subprog id inside insn instead of
13931 * aux_data, since next loop will split up all insns into funcs
13932 */
13933 insn->off = subprog;
13934 /* remember original imm in case JIT fails and fallback
13935 * to interpreter will be needed
13936 */
13937 env->insn_aux_data[i].call_imm = insn->imm;
13938 /* point imm to __bpf_call_base+1 from JITs point of view */
13939 insn->imm = 1;
13940 if (bpf_pseudo_func(insn))
13941 /* jit (e.g. x86_64) may emit fewer instructions
13942 * if it learns a u32 imm is the same as a u64 imm.
13943 * Force a non zero here.
13944 */
13945 insn[1].imm = 1;
13946 }
13947
13948 err = bpf_prog_alloc_jited_linfo(prog);
13949 if (err)
13950 goto out_undo_insn;
13951
13952 err = -ENOMEM;
13953 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
13954 if (!func)
13955 goto out_undo_insn;
13956
13957 for (i = 0; i < env->subprog_cnt; i++) {
13958 subprog_start = subprog_end;
13959 subprog_end = env->subprog_info[i + 1].start;
13960
13961 len = subprog_end - subprog_start;
13962 /* bpf_prog_run() doesn't call subprogs directly,
13963 * hence main prog stats include the runtime of subprogs.
13964 * subprogs don't have IDs and not reachable via prog_get_next_id
13965 * func[i]->stats will never be accessed and stays NULL
13966 */
13967 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
13968 if (!func[i])
13969 goto out_free;
13970 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
13971 len * sizeof(struct bpf_insn));
13972 func[i]->type = prog->type;
13973 func[i]->len = len;
13974 if (bpf_prog_calc_tag(func[i]))
13975 goto out_free;
13976 func[i]->is_func = 1;
13977 func[i]->aux->func_idx = i;
13978 /* Below members will be freed only at prog->aux */
13979 func[i]->aux->btf = prog->aux->btf;
13980 func[i]->aux->func_info = prog->aux->func_info;
13981 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
13982 func[i]->aux->poke_tab = prog->aux->poke_tab;
13983 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
13984
13985 for (j = 0; j < prog->aux->size_poke_tab; j++) {
13986 struct bpf_jit_poke_descriptor *poke;
13987
13988 poke = &prog->aux->poke_tab[j];
13989 if (poke->insn_idx < subprog_end &&
13990 poke->insn_idx >= subprog_start)
13991 poke->aux = func[i]->aux;
13992 }
13993
13994 func[i]->aux->name[0] = 'F';
13995 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
13996 func[i]->jit_requested = 1;
13997 func[i]->blinding_requested = prog->blinding_requested;
13998 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
13999 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
14000 func[i]->aux->linfo = prog->aux->linfo;
14001 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
14002 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
14003 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
14004 num_exentries = 0;
14005 insn = func[i]->insnsi;
14006 for (j = 0; j < func[i]->len; j++, insn++) {
14007 if (BPF_CLASS(insn->code) == BPF_LDX &&
14008 BPF_MODE(insn->code) == BPF_PROBE_MEM)
14009 num_exentries++;
14010 }
14011 func[i]->aux->num_exentries = num_exentries;
14012 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
14013 func[i] = bpf_int_jit_compile(func[i]);
14014 if (!func[i]->jited) {
14015 err = -ENOTSUPP;
14016 goto out_free;
14017 }
14018 cond_resched();
14019 }
14020
14021 /* at this point all bpf functions were successfully JITed
14022 * now populate all bpf_calls with correct addresses and
14023 * run last pass of JIT
14024 */
14025 for (i = 0; i < env->subprog_cnt; i++) {
14026 insn = func[i]->insnsi;
14027 for (j = 0; j < func[i]->len; j++, insn++) {
14028 if (bpf_pseudo_func(insn)) {
14029 subprog = insn->off;
14030 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
14031 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
14032 continue;
14033 }
14034 if (!bpf_pseudo_call(insn))
14035 continue;
14036 subprog = insn->off;
14037 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
14038 }
14039
14040 /* we use the aux data to keep a list of the start addresses
14041 * of the JITed images for each function in the program
14042 *
14043 * for some architectures, such as powerpc64, the imm field
14044 * might not be large enough to hold the offset of the start
14045 * address of the callee's JITed image from __bpf_call_base
14046 *
14047 * in such cases, we can lookup the start address of a callee
14048 * by using its subprog id, available from the off field of
14049 * the call instruction, as an index for this list
14050 */
14051 func[i]->aux->func = func;
14052 func[i]->aux->func_cnt = env->subprog_cnt;
14053 }
14054 for (i = 0; i < env->subprog_cnt; i++) {
14055 old_bpf_func = func[i]->bpf_func;
14056 tmp = bpf_int_jit_compile(func[i]);
14057 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
14058 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
14059 err = -ENOTSUPP;
14060 goto out_free;
14061 }
14062 cond_resched();
14063 }
14064
14065 /* finally lock prog and jit images for all functions and
14066 * populate kallsysm. Begin at the first subprogram, since
14067 * bpf_prog_load will add the kallsyms for the main program.
14068 */
14069 for (i = 1; i < env->subprog_cnt; i++) {
14070 bpf_prog_lock_ro(func[i]);
14071 bpf_prog_kallsyms_add(func[i]);
14072 }
14073
14074 /* Last step: make now unused interpreter insns from main
14075 * prog consistent for later dump requests, so they can
14076 * later look the same as if they were interpreted only.
14077 */
14078 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
14079 if (bpf_pseudo_func(insn)) {
14080 insn[0].imm = env->insn_aux_data[i].call_imm;
14081 insn[1].imm = insn->off;
14082 insn->off = 0;
14083 continue;
14084 }
14085 if (!bpf_pseudo_call(insn))
14086 continue;
14087 insn->off = env->insn_aux_data[i].call_imm;
14088 subprog = find_subprog(env, i + insn->off + 1);
14089 insn->imm = subprog;
14090 }
14091
14092 prog->jited = 1;
14093 prog->bpf_func = func[0]->bpf_func;
14094 prog->jited_len = func[0]->jited_len;
14095 prog->aux->extable = func[0]->aux->extable;
14096 prog->aux->num_exentries = func[0]->aux->num_exentries;
14097 prog->aux->func = func;
14098 prog->aux->func_cnt = env->subprog_cnt;
14099 bpf_prog_jit_attempt_done(prog);
14100 return 0;
14101 out_free:
14102 /* We failed JIT'ing, so at this point we need to unregister poke
14103 * descriptors from subprogs, so that kernel is not attempting to
14104 * patch it anymore as we're freeing the subprog JIT memory.
14105 */
14106 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14107 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14108 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
14109 }
14110 /* At this point we're guaranteed that poke descriptors are not
14111 * live anymore. We can just unlink its descriptor table as it's
14112 * released with the main prog.
14113 */
14114 for (i = 0; i < env->subprog_cnt; i++) {
14115 if (!func[i])
14116 continue;
14117 func[i]->aux->poke_tab = NULL;
14118 bpf_jit_free(func[i]);
14119 }
14120 kfree(func);
14121 out_undo_insn:
14122 /* cleanup main prog to be interpreted */
14123 prog->jit_requested = 0;
14124 prog->blinding_requested = 0;
14125 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
14126 if (!bpf_pseudo_call(insn))
14127 continue;
14128 insn->off = 0;
14129 insn->imm = env->insn_aux_data[i].call_imm;
14130 }
14131 bpf_prog_jit_attempt_done(prog);
14132 return err;
14133 }
14134
fixup_call_args(struct bpf_verifier_env * env)14135 static int fixup_call_args(struct bpf_verifier_env *env)
14136 {
14137 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
14138 struct bpf_prog *prog = env->prog;
14139 struct bpf_insn *insn = prog->insnsi;
14140 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
14141 int i, depth;
14142 #endif
14143 int err = 0;
14144
14145 if (env->prog->jit_requested &&
14146 !bpf_prog_is_dev_bound(env->prog->aux)) {
14147 err = jit_subprogs(env);
14148 if (err == 0)
14149 return 0;
14150 if (err == -EFAULT)
14151 return err;
14152 }
14153 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
14154 if (has_kfunc_call) {
14155 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
14156 return -EINVAL;
14157 }
14158 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
14159 /* When JIT fails the progs with bpf2bpf calls and tail_calls
14160 * have to be rejected, since interpreter doesn't support them yet.
14161 */
14162 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
14163 return -EINVAL;
14164 }
14165 for (i = 0; i < prog->len; i++, insn++) {
14166 if (bpf_pseudo_func(insn)) {
14167 /* When JIT fails the progs with callback calls
14168 * have to be rejected, since interpreter doesn't support them yet.
14169 */
14170 verbose(env, "callbacks are not allowed in non-JITed programs\n");
14171 return -EINVAL;
14172 }
14173
14174 if (!bpf_pseudo_call(insn))
14175 continue;
14176 depth = get_callee_stack_depth(env, insn, i);
14177 if (depth < 0)
14178 return depth;
14179 bpf_patch_call_args(insn, depth);
14180 }
14181 err = 0;
14182 #endif
14183 return err;
14184 }
14185
fixup_kfunc_call(struct bpf_verifier_env * env,struct bpf_insn * insn)14186 static int fixup_kfunc_call(struct bpf_verifier_env *env,
14187 struct bpf_insn *insn)
14188 {
14189 const struct bpf_kfunc_desc *desc;
14190
14191 if (!insn->imm) {
14192 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
14193 return -EINVAL;
14194 }
14195
14196 /* insn->imm has the btf func_id. Replace it with
14197 * an address (relative to __bpf_base_call).
14198 */
14199 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
14200 if (!desc) {
14201 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
14202 insn->imm);
14203 return -EFAULT;
14204 }
14205
14206 insn->imm = desc->imm;
14207
14208 return 0;
14209 }
14210
14211 /* Do various post-verification rewrites in a single program pass.
14212 * These rewrites simplify JIT and interpreter implementations.
14213 */
do_misc_fixups(struct bpf_verifier_env * env)14214 static int do_misc_fixups(struct bpf_verifier_env *env)
14215 {
14216 struct bpf_prog *prog = env->prog;
14217 enum bpf_attach_type eatype = prog->expected_attach_type;
14218 enum bpf_prog_type prog_type = resolve_prog_type(prog);
14219 struct bpf_insn *insn = prog->insnsi;
14220 const struct bpf_func_proto *fn;
14221 const int insn_cnt = prog->len;
14222 const struct bpf_map_ops *ops;
14223 struct bpf_insn_aux_data *aux;
14224 struct bpf_insn insn_buf[16];
14225 struct bpf_prog *new_prog;
14226 struct bpf_map *map_ptr;
14227 int i, ret, cnt, delta = 0;
14228
14229 for (i = 0; i < insn_cnt; i++, insn++) {
14230 /* Make divide-by-zero exceptions impossible. */
14231 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
14232 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
14233 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
14234 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
14235 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
14236 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
14237 struct bpf_insn *patchlet;
14238 struct bpf_insn chk_and_div[] = {
14239 /* [R,W]x div 0 -> 0 */
14240 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14241 BPF_JNE | BPF_K, insn->src_reg,
14242 0, 2, 0),
14243 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
14244 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14245 *insn,
14246 };
14247 struct bpf_insn chk_and_mod[] = {
14248 /* [R,W]x mod 0 -> [R,W]x */
14249 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
14250 BPF_JEQ | BPF_K, insn->src_reg,
14251 0, 1 + (is64 ? 0 : 1), 0),
14252 *insn,
14253 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
14254 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
14255 };
14256
14257 patchlet = isdiv ? chk_and_div : chk_and_mod;
14258 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
14259 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
14260
14261 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
14262 if (!new_prog)
14263 return -ENOMEM;
14264
14265 delta += cnt - 1;
14266 env->prog = prog = new_prog;
14267 insn = new_prog->insnsi + i + delta;
14268 continue;
14269 }
14270
14271 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
14272 if (BPF_CLASS(insn->code) == BPF_LD &&
14273 (BPF_MODE(insn->code) == BPF_ABS ||
14274 BPF_MODE(insn->code) == BPF_IND)) {
14275 cnt = env->ops->gen_ld_abs(insn, insn_buf);
14276 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14277 verbose(env, "bpf verifier is misconfigured\n");
14278 return -EINVAL;
14279 }
14280
14281 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14282 if (!new_prog)
14283 return -ENOMEM;
14284
14285 delta += cnt - 1;
14286 env->prog = prog = new_prog;
14287 insn = new_prog->insnsi + i + delta;
14288 continue;
14289 }
14290
14291 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
14292 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
14293 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
14294 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
14295 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
14296 struct bpf_insn *patch = &insn_buf[0];
14297 bool issrc, isneg, isimm;
14298 u32 off_reg;
14299
14300 aux = &env->insn_aux_data[i + delta];
14301 if (!aux->alu_state ||
14302 aux->alu_state == BPF_ALU_NON_POINTER)
14303 continue;
14304
14305 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
14306 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
14307 BPF_ALU_SANITIZE_SRC;
14308 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
14309
14310 off_reg = issrc ? insn->src_reg : insn->dst_reg;
14311 if (isimm) {
14312 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14313 } else {
14314 if (isneg)
14315 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14316 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
14317 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
14318 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
14319 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
14320 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
14321 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
14322 }
14323 if (!issrc)
14324 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
14325 insn->src_reg = BPF_REG_AX;
14326 if (isneg)
14327 insn->code = insn->code == code_add ?
14328 code_sub : code_add;
14329 *patch++ = *insn;
14330 if (issrc && isneg && !isimm)
14331 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
14332 cnt = patch - insn_buf;
14333
14334 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14335 if (!new_prog)
14336 return -ENOMEM;
14337
14338 delta += cnt - 1;
14339 env->prog = prog = new_prog;
14340 insn = new_prog->insnsi + i + delta;
14341 continue;
14342 }
14343
14344 if (insn->code != (BPF_JMP | BPF_CALL))
14345 continue;
14346 if (insn->src_reg == BPF_PSEUDO_CALL)
14347 continue;
14348 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14349 ret = fixup_kfunc_call(env, insn);
14350 if (ret)
14351 return ret;
14352 continue;
14353 }
14354
14355 if (insn->imm == BPF_FUNC_get_route_realm)
14356 prog->dst_needed = 1;
14357 if (insn->imm == BPF_FUNC_get_prandom_u32)
14358 bpf_user_rnd_init_once();
14359 if (insn->imm == BPF_FUNC_override_return)
14360 prog->kprobe_override = 1;
14361 if (insn->imm == BPF_FUNC_tail_call) {
14362 /* If we tail call into other programs, we
14363 * cannot make any assumptions since they can
14364 * be replaced dynamically during runtime in
14365 * the program array.
14366 */
14367 prog->cb_access = 1;
14368 if (!allow_tail_call_in_subprogs(env))
14369 prog->aux->stack_depth = MAX_BPF_STACK;
14370 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
14371
14372 /* mark bpf_tail_call as different opcode to avoid
14373 * conditional branch in the interpreter for every normal
14374 * call and to prevent accidental JITing by JIT compiler
14375 * that doesn't support bpf_tail_call yet
14376 */
14377 insn->imm = 0;
14378 insn->code = BPF_JMP | BPF_TAIL_CALL;
14379
14380 aux = &env->insn_aux_data[i + delta];
14381 if (env->bpf_capable && !prog->blinding_requested &&
14382 prog->jit_requested &&
14383 !bpf_map_key_poisoned(aux) &&
14384 !bpf_map_ptr_poisoned(aux) &&
14385 !bpf_map_ptr_unpriv(aux)) {
14386 struct bpf_jit_poke_descriptor desc = {
14387 .reason = BPF_POKE_REASON_TAIL_CALL,
14388 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
14389 .tail_call.key = bpf_map_key_immediate(aux),
14390 .insn_idx = i + delta,
14391 };
14392
14393 ret = bpf_jit_add_poke_descriptor(prog, &desc);
14394 if (ret < 0) {
14395 verbose(env, "adding tail call poke descriptor failed\n");
14396 return ret;
14397 }
14398
14399 insn->imm = ret + 1;
14400 continue;
14401 }
14402
14403 if (!bpf_map_ptr_unpriv(aux))
14404 continue;
14405
14406 /* instead of changing every JIT dealing with tail_call
14407 * emit two extra insns:
14408 * if (index >= max_entries) goto out;
14409 * index &= array->index_mask;
14410 * to avoid out-of-bounds cpu speculation
14411 */
14412 if (bpf_map_ptr_poisoned(aux)) {
14413 verbose(env, "tail_call abusing map_ptr\n");
14414 return -EINVAL;
14415 }
14416
14417 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14418 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
14419 map_ptr->max_entries, 2);
14420 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
14421 container_of(map_ptr,
14422 struct bpf_array,
14423 map)->index_mask);
14424 insn_buf[2] = *insn;
14425 cnt = 3;
14426 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14427 if (!new_prog)
14428 return -ENOMEM;
14429
14430 delta += cnt - 1;
14431 env->prog = prog = new_prog;
14432 insn = new_prog->insnsi + i + delta;
14433 continue;
14434 }
14435
14436 if (insn->imm == BPF_FUNC_timer_set_callback) {
14437 /* The verifier will process callback_fn as many times as necessary
14438 * with different maps and the register states prepared by
14439 * set_timer_callback_state will be accurate.
14440 *
14441 * The following use case is valid:
14442 * map1 is shared by prog1, prog2, prog3.
14443 * prog1 calls bpf_timer_init for some map1 elements
14444 * prog2 calls bpf_timer_set_callback for some map1 elements.
14445 * Those that were not bpf_timer_init-ed will return -EINVAL.
14446 * prog3 calls bpf_timer_start for some map1 elements.
14447 * Those that were not both bpf_timer_init-ed and
14448 * bpf_timer_set_callback-ed will return -EINVAL.
14449 */
14450 struct bpf_insn ld_addrs[2] = {
14451 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
14452 };
14453
14454 insn_buf[0] = ld_addrs[0];
14455 insn_buf[1] = ld_addrs[1];
14456 insn_buf[2] = *insn;
14457 cnt = 3;
14458
14459 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14460 if (!new_prog)
14461 return -ENOMEM;
14462
14463 delta += cnt - 1;
14464 env->prog = prog = new_prog;
14465 insn = new_prog->insnsi + i + delta;
14466 goto patch_call_imm;
14467 }
14468
14469 if (insn->imm == BPF_FUNC_task_storage_get ||
14470 insn->imm == BPF_FUNC_sk_storage_get ||
14471 insn->imm == BPF_FUNC_inode_storage_get) {
14472 if (env->prog->aux->sleepable)
14473 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
14474 else
14475 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
14476 insn_buf[1] = *insn;
14477 cnt = 2;
14478
14479 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14480 if (!new_prog)
14481 return -ENOMEM;
14482
14483 delta += cnt - 1;
14484 env->prog = prog = new_prog;
14485 insn = new_prog->insnsi + i + delta;
14486 goto patch_call_imm;
14487 }
14488
14489 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
14490 * and other inlining handlers are currently limited to 64 bit
14491 * only.
14492 */
14493 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14494 (insn->imm == BPF_FUNC_map_lookup_elem ||
14495 insn->imm == BPF_FUNC_map_update_elem ||
14496 insn->imm == BPF_FUNC_map_delete_elem ||
14497 insn->imm == BPF_FUNC_map_push_elem ||
14498 insn->imm == BPF_FUNC_map_pop_elem ||
14499 insn->imm == BPF_FUNC_map_peek_elem ||
14500 insn->imm == BPF_FUNC_redirect_map ||
14501 insn->imm == BPF_FUNC_for_each_map_elem ||
14502 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
14503 aux = &env->insn_aux_data[i + delta];
14504 if (bpf_map_ptr_poisoned(aux))
14505 goto patch_call_imm;
14506
14507 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
14508 ops = map_ptr->ops;
14509 if (insn->imm == BPF_FUNC_map_lookup_elem &&
14510 ops->map_gen_lookup) {
14511 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
14512 if (cnt == -EOPNOTSUPP)
14513 goto patch_map_ops_generic;
14514 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
14515 verbose(env, "bpf verifier is misconfigured\n");
14516 return -EINVAL;
14517 }
14518
14519 new_prog = bpf_patch_insn_data(env, i + delta,
14520 insn_buf, cnt);
14521 if (!new_prog)
14522 return -ENOMEM;
14523
14524 delta += cnt - 1;
14525 env->prog = prog = new_prog;
14526 insn = new_prog->insnsi + i + delta;
14527 continue;
14528 }
14529
14530 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
14531 (void *(*)(struct bpf_map *map, void *key))NULL));
14532 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
14533 (int (*)(struct bpf_map *map, void *key))NULL));
14534 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
14535 (int (*)(struct bpf_map *map, void *key, void *value,
14536 u64 flags))NULL));
14537 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
14538 (int (*)(struct bpf_map *map, void *value,
14539 u64 flags))NULL));
14540 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
14541 (int (*)(struct bpf_map *map, void *value))NULL));
14542 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
14543 (int (*)(struct bpf_map *map, void *value))NULL));
14544 BUILD_BUG_ON(!__same_type(ops->map_redirect,
14545 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
14546 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
14547 (int (*)(struct bpf_map *map,
14548 bpf_callback_t callback_fn,
14549 void *callback_ctx,
14550 u64 flags))NULL));
14551 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
14552 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
14553
14554 patch_map_ops_generic:
14555 switch (insn->imm) {
14556 case BPF_FUNC_map_lookup_elem:
14557 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
14558 continue;
14559 case BPF_FUNC_map_update_elem:
14560 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
14561 continue;
14562 case BPF_FUNC_map_delete_elem:
14563 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
14564 continue;
14565 case BPF_FUNC_map_push_elem:
14566 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
14567 continue;
14568 case BPF_FUNC_map_pop_elem:
14569 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
14570 continue;
14571 case BPF_FUNC_map_peek_elem:
14572 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
14573 continue;
14574 case BPF_FUNC_redirect_map:
14575 insn->imm = BPF_CALL_IMM(ops->map_redirect);
14576 continue;
14577 case BPF_FUNC_for_each_map_elem:
14578 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
14579 continue;
14580 case BPF_FUNC_map_lookup_percpu_elem:
14581 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
14582 continue;
14583 }
14584
14585 goto patch_call_imm;
14586 }
14587
14588 /* Implement bpf_jiffies64 inline. */
14589 if (prog->jit_requested && BITS_PER_LONG == 64 &&
14590 insn->imm == BPF_FUNC_jiffies64) {
14591 struct bpf_insn ld_jiffies_addr[2] = {
14592 BPF_LD_IMM64(BPF_REG_0,
14593 (unsigned long)&jiffies),
14594 };
14595
14596 insn_buf[0] = ld_jiffies_addr[0];
14597 insn_buf[1] = ld_jiffies_addr[1];
14598 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
14599 BPF_REG_0, 0);
14600 cnt = 3;
14601
14602 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
14603 cnt);
14604 if (!new_prog)
14605 return -ENOMEM;
14606
14607 delta += cnt - 1;
14608 env->prog = prog = new_prog;
14609 insn = new_prog->insnsi + i + delta;
14610 continue;
14611 }
14612
14613 /* Implement bpf_get_func_arg inline. */
14614 if (prog_type == BPF_PROG_TYPE_TRACING &&
14615 insn->imm == BPF_FUNC_get_func_arg) {
14616 /* Load nr_args from ctx - 8 */
14617 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14618 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
14619 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
14620 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
14621 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
14622 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14623 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
14624 insn_buf[7] = BPF_JMP_A(1);
14625 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
14626 cnt = 9;
14627
14628 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14629 if (!new_prog)
14630 return -ENOMEM;
14631
14632 delta += cnt - 1;
14633 env->prog = prog = new_prog;
14634 insn = new_prog->insnsi + i + delta;
14635 continue;
14636 }
14637
14638 /* Implement bpf_get_func_ret inline. */
14639 if (prog_type == BPF_PROG_TYPE_TRACING &&
14640 insn->imm == BPF_FUNC_get_func_ret) {
14641 if (eatype == BPF_TRACE_FEXIT ||
14642 eatype == BPF_MODIFY_RETURN) {
14643 /* Load nr_args from ctx - 8 */
14644 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14645 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
14646 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
14647 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
14648 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
14649 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
14650 cnt = 6;
14651 } else {
14652 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
14653 cnt = 1;
14654 }
14655
14656 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
14657 if (!new_prog)
14658 return -ENOMEM;
14659
14660 delta += cnt - 1;
14661 env->prog = prog = new_prog;
14662 insn = new_prog->insnsi + i + delta;
14663 continue;
14664 }
14665
14666 /* Implement get_func_arg_cnt inline. */
14667 if (prog_type == BPF_PROG_TYPE_TRACING &&
14668 insn->imm == BPF_FUNC_get_func_arg_cnt) {
14669 /* Load nr_args from ctx - 8 */
14670 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
14671
14672 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14673 if (!new_prog)
14674 return -ENOMEM;
14675
14676 env->prog = prog = new_prog;
14677 insn = new_prog->insnsi + i + delta;
14678 continue;
14679 }
14680
14681 /* Implement bpf_get_func_ip inline. */
14682 if (prog_type == BPF_PROG_TYPE_TRACING &&
14683 insn->imm == BPF_FUNC_get_func_ip) {
14684 /* Load IP address from ctx - 16 */
14685 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
14686
14687 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
14688 if (!new_prog)
14689 return -ENOMEM;
14690
14691 env->prog = prog = new_prog;
14692 insn = new_prog->insnsi + i + delta;
14693 continue;
14694 }
14695
14696 patch_call_imm:
14697 fn = env->ops->get_func_proto(insn->imm, env->prog);
14698 /* all functions that have prototype and verifier allowed
14699 * programs to call them, must be real in-kernel functions
14700 */
14701 if (!fn->func) {
14702 verbose(env,
14703 "kernel subsystem misconfigured func %s#%d\n",
14704 func_id_name(insn->imm), insn->imm);
14705 return -EFAULT;
14706 }
14707 insn->imm = fn->func - __bpf_call_base;
14708 }
14709
14710 /* Since poke tab is now finalized, publish aux to tracker. */
14711 for (i = 0; i < prog->aux->size_poke_tab; i++) {
14712 map_ptr = prog->aux->poke_tab[i].tail_call.map;
14713 if (!map_ptr->ops->map_poke_track ||
14714 !map_ptr->ops->map_poke_untrack ||
14715 !map_ptr->ops->map_poke_run) {
14716 verbose(env, "bpf verifier is misconfigured\n");
14717 return -EINVAL;
14718 }
14719
14720 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
14721 if (ret < 0) {
14722 verbose(env, "tracking tail call prog failed\n");
14723 return ret;
14724 }
14725 }
14726
14727 sort_kfunc_descs_by_imm(env->prog);
14728
14729 return 0;
14730 }
14731
inline_bpf_loop(struct bpf_verifier_env * env,int position,s32 stack_base,u32 callback_subprogno,u32 * cnt)14732 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
14733 int position,
14734 s32 stack_base,
14735 u32 callback_subprogno,
14736 u32 *cnt)
14737 {
14738 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
14739 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
14740 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
14741 int reg_loop_max = BPF_REG_6;
14742 int reg_loop_cnt = BPF_REG_7;
14743 int reg_loop_ctx = BPF_REG_8;
14744
14745 struct bpf_prog *new_prog;
14746 u32 callback_start;
14747 u32 call_insn_offset;
14748 s32 callback_offset;
14749
14750 /* This represents an inlined version of bpf_iter.c:bpf_loop,
14751 * be careful to modify this code in sync.
14752 */
14753 struct bpf_insn insn_buf[] = {
14754 /* Return error and jump to the end of the patch if
14755 * expected number of iterations is too big.
14756 */
14757 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
14758 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
14759 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
14760 /* spill R6, R7, R8 to use these as loop vars */
14761 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
14762 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
14763 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
14764 /* initialize loop vars */
14765 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
14766 BPF_MOV32_IMM(reg_loop_cnt, 0),
14767 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
14768 /* loop header,
14769 * if reg_loop_cnt >= reg_loop_max skip the loop body
14770 */
14771 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
14772 /* callback call,
14773 * correct callback offset would be set after patching
14774 */
14775 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
14776 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
14777 BPF_CALL_REL(0),
14778 /* increment loop counter */
14779 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
14780 /* jump to loop header if callback returned 0 */
14781 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
14782 /* return value of bpf_loop,
14783 * set R0 to the number of iterations
14784 */
14785 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
14786 /* restore original values of R6, R7, R8 */
14787 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
14788 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
14789 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
14790 };
14791
14792 *cnt = ARRAY_SIZE(insn_buf);
14793 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
14794 if (!new_prog)
14795 return new_prog;
14796
14797 /* callback start is known only after patching */
14798 callback_start = env->subprog_info[callback_subprogno].start;
14799 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
14800 call_insn_offset = position + 12;
14801 callback_offset = callback_start - call_insn_offset - 1;
14802 new_prog->insnsi[call_insn_offset].imm = callback_offset;
14803
14804 return new_prog;
14805 }
14806
is_bpf_loop_call(struct bpf_insn * insn)14807 static bool is_bpf_loop_call(struct bpf_insn *insn)
14808 {
14809 return insn->code == (BPF_JMP | BPF_CALL) &&
14810 insn->src_reg == 0 &&
14811 insn->imm == BPF_FUNC_loop;
14812 }
14813
14814 /* For all sub-programs in the program (including main) check
14815 * insn_aux_data to see if there are bpf_loop calls that require
14816 * inlining. If such calls are found the calls are replaced with a
14817 * sequence of instructions produced by `inline_bpf_loop` function and
14818 * subprog stack_depth is increased by the size of 3 registers.
14819 * This stack space is used to spill values of the R6, R7, R8. These
14820 * registers are used to store the loop bound, counter and context
14821 * variables.
14822 */
optimize_bpf_loop(struct bpf_verifier_env * env)14823 static int optimize_bpf_loop(struct bpf_verifier_env *env)
14824 {
14825 struct bpf_subprog_info *subprogs = env->subprog_info;
14826 int i, cur_subprog = 0, cnt, delta = 0;
14827 struct bpf_insn *insn = env->prog->insnsi;
14828 int insn_cnt = env->prog->len;
14829 u16 stack_depth = subprogs[cur_subprog].stack_depth;
14830 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14831 u16 stack_depth_extra = 0;
14832
14833 for (i = 0; i < insn_cnt; i++, insn++) {
14834 struct bpf_loop_inline_state *inline_state =
14835 &env->insn_aux_data[i + delta].loop_inline_state;
14836
14837 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
14838 struct bpf_prog *new_prog;
14839
14840 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
14841 new_prog = inline_bpf_loop(env,
14842 i + delta,
14843 -(stack_depth + stack_depth_extra),
14844 inline_state->callback_subprogno,
14845 &cnt);
14846 if (!new_prog)
14847 return -ENOMEM;
14848
14849 delta += cnt - 1;
14850 env->prog = new_prog;
14851 insn = new_prog->insnsi + i + delta;
14852 }
14853
14854 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
14855 subprogs[cur_subprog].stack_depth += stack_depth_extra;
14856 cur_subprog++;
14857 stack_depth = subprogs[cur_subprog].stack_depth;
14858 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
14859 stack_depth_extra = 0;
14860 }
14861 }
14862
14863 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
14864
14865 return 0;
14866 }
14867
free_states(struct bpf_verifier_env * env)14868 static void free_states(struct bpf_verifier_env *env)
14869 {
14870 struct bpf_verifier_state_list *sl, *sln;
14871 int i;
14872
14873 sl = env->free_list;
14874 while (sl) {
14875 sln = sl->next;
14876 free_verifier_state(&sl->state, false);
14877 kfree(sl);
14878 sl = sln;
14879 }
14880 env->free_list = NULL;
14881
14882 if (!env->explored_states)
14883 return;
14884
14885 for (i = 0; i < state_htab_size(env); i++) {
14886 sl = env->explored_states[i];
14887
14888 while (sl) {
14889 sln = sl->next;
14890 free_verifier_state(&sl->state, false);
14891 kfree(sl);
14892 sl = sln;
14893 }
14894 env->explored_states[i] = NULL;
14895 }
14896 }
14897
do_check_common(struct bpf_verifier_env * env,int subprog)14898 static int do_check_common(struct bpf_verifier_env *env, int subprog)
14899 {
14900 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
14901 struct bpf_verifier_state *state;
14902 struct bpf_reg_state *regs;
14903 int ret, i;
14904
14905 env->prev_linfo = NULL;
14906 env->pass_cnt++;
14907
14908 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
14909 if (!state)
14910 return -ENOMEM;
14911 state->curframe = 0;
14912 state->speculative = false;
14913 state->branches = 1;
14914 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
14915 if (!state->frame[0]) {
14916 kfree(state);
14917 return -ENOMEM;
14918 }
14919 env->cur_state = state;
14920 init_func_state(env, state->frame[0],
14921 BPF_MAIN_FUNC /* callsite */,
14922 0 /* frameno */,
14923 subprog);
14924 state->first_insn_idx = env->subprog_info[subprog].start;
14925 state->last_insn_idx = -1;
14926
14927 regs = state->frame[state->curframe]->regs;
14928 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
14929 ret = btf_prepare_func_args(env, subprog, regs);
14930 if (ret)
14931 goto out;
14932 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
14933 if (regs[i].type == PTR_TO_CTX)
14934 mark_reg_known_zero(env, regs, i);
14935 else if (regs[i].type == SCALAR_VALUE)
14936 mark_reg_unknown(env, regs, i);
14937 else if (base_type(regs[i].type) == PTR_TO_MEM) {
14938 const u32 mem_size = regs[i].mem_size;
14939
14940 mark_reg_known_zero(env, regs, i);
14941 regs[i].mem_size = mem_size;
14942 regs[i].id = ++env->id_gen;
14943 }
14944 }
14945 } else {
14946 /* 1st arg to a function */
14947 regs[BPF_REG_1].type = PTR_TO_CTX;
14948 mark_reg_known_zero(env, regs, BPF_REG_1);
14949 ret = btf_check_subprog_arg_match(env, subprog, regs);
14950 if (ret == -EFAULT)
14951 /* unlikely verifier bug. abort.
14952 * ret == 0 and ret < 0 are sadly acceptable for
14953 * main() function due to backward compatibility.
14954 * Like socket filter program may be written as:
14955 * int bpf_prog(struct pt_regs *ctx)
14956 * and never dereference that ctx in the program.
14957 * 'struct pt_regs' is a type mismatch for socket
14958 * filter that should be using 'struct __sk_buff'.
14959 */
14960 goto out;
14961 }
14962
14963 ret = do_check(env);
14964 out:
14965 /* check for NULL is necessary, since cur_state can be freed inside
14966 * do_check() under memory pressure.
14967 */
14968 if (env->cur_state) {
14969 free_verifier_state(env->cur_state, true);
14970 env->cur_state = NULL;
14971 }
14972 while (!pop_stack(env, NULL, NULL, false));
14973 if (!ret && pop_log)
14974 bpf_vlog_reset(&env->log, 0);
14975 free_states(env);
14976 return ret;
14977 }
14978
14979 /* Verify all global functions in a BPF program one by one based on their BTF.
14980 * All global functions must pass verification. Otherwise the whole program is rejected.
14981 * Consider:
14982 * int bar(int);
14983 * int foo(int f)
14984 * {
14985 * return bar(f);
14986 * }
14987 * int bar(int b)
14988 * {
14989 * ...
14990 * }
14991 * foo() will be verified first for R1=any_scalar_value. During verification it
14992 * will be assumed that bar() already verified successfully and call to bar()
14993 * from foo() will be checked for type match only. Later bar() will be verified
14994 * independently to check that it's safe for R1=any_scalar_value.
14995 */
do_check_subprogs(struct bpf_verifier_env * env)14996 static int do_check_subprogs(struct bpf_verifier_env *env)
14997 {
14998 struct bpf_prog_aux *aux = env->prog->aux;
14999 int i, ret;
15000
15001 if (!aux->func_info)
15002 return 0;
15003
15004 for (i = 1; i < env->subprog_cnt; i++) {
15005 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
15006 continue;
15007 env->insn_idx = env->subprog_info[i].start;
15008 WARN_ON_ONCE(env->insn_idx == 0);
15009 ret = do_check_common(env, i);
15010 if (ret) {
15011 return ret;
15012 } else if (env->log.level & BPF_LOG_LEVEL) {
15013 verbose(env,
15014 "Func#%d is safe for any args that match its prototype\n",
15015 i);
15016 }
15017 }
15018 return 0;
15019 }
15020
do_check_main(struct bpf_verifier_env * env)15021 static int do_check_main(struct bpf_verifier_env *env)
15022 {
15023 int ret;
15024
15025 env->insn_idx = 0;
15026 ret = do_check_common(env, 0);
15027 if (!ret)
15028 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
15029 return ret;
15030 }
15031
15032
print_verification_stats(struct bpf_verifier_env * env)15033 static void print_verification_stats(struct bpf_verifier_env *env)
15034 {
15035 int i;
15036
15037 if (env->log.level & BPF_LOG_STATS) {
15038 verbose(env, "verification time %lld usec\n",
15039 div_u64(env->verification_time, 1000));
15040 verbose(env, "stack depth ");
15041 for (i = 0; i < env->subprog_cnt; i++) {
15042 u32 depth = env->subprog_info[i].stack_depth;
15043
15044 verbose(env, "%d", depth);
15045 if (i + 1 < env->subprog_cnt)
15046 verbose(env, "+");
15047 }
15048 verbose(env, "\n");
15049 }
15050 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
15051 "total_states %d peak_states %d mark_read %d\n",
15052 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
15053 env->max_states_per_insn, env->total_states,
15054 env->peak_states, env->longest_mark_read_walk);
15055 }
15056
check_struct_ops_btf_id(struct bpf_verifier_env * env)15057 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
15058 {
15059 const struct btf_type *t, *func_proto;
15060 const struct bpf_struct_ops *st_ops;
15061 const struct btf_member *member;
15062 struct bpf_prog *prog = env->prog;
15063 u32 btf_id, member_idx;
15064 const char *mname;
15065
15066 if (!prog->gpl_compatible) {
15067 verbose(env, "struct ops programs must have a GPL compatible license\n");
15068 return -EINVAL;
15069 }
15070
15071 btf_id = prog->aux->attach_btf_id;
15072 st_ops = bpf_struct_ops_find(btf_id);
15073 if (!st_ops) {
15074 verbose(env, "attach_btf_id %u is not a supported struct\n",
15075 btf_id);
15076 return -ENOTSUPP;
15077 }
15078
15079 t = st_ops->type;
15080 member_idx = prog->expected_attach_type;
15081 if (member_idx >= btf_type_vlen(t)) {
15082 verbose(env, "attach to invalid member idx %u of struct %s\n",
15083 member_idx, st_ops->name);
15084 return -EINVAL;
15085 }
15086
15087 member = &btf_type_member(t)[member_idx];
15088 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
15089 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
15090 NULL);
15091 if (!func_proto) {
15092 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
15093 mname, member_idx, st_ops->name);
15094 return -EINVAL;
15095 }
15096
15097 if (st_ops->check_member) {
15098 int err = st_ops->check_member(t, member);
15099
15100 if (err) {
15101 verbose(env, "attach to unsupported member %s of struct %s\n",
15102 mname, st_ops->name);
15103 return err;
15104 }
15105 }
15106
15107 prog->aux->attach_func_proto = func_proto;
15108 prog->aux->attach_func_name = mname;
15109 env->ops = st_ops->verifier_ops;
15110
15111 return 0;
15112 }
15113 #define SECURITY_PREFIX "security_"
15114
check_attach_modify_return(unsigned long addr,const char * func_name)15115 static int check_attach_modify_return(unsigned long addr, const char *func_name)
15116 {
15117 if (within_error_injection_list(addr) ||
15118 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
15119 return 0;
15120
15121 return -EINVAL;
15122 }
15123
15124 /* list of non-sleepable functions that are otherwise on
15125 * ALLOW_ERROR_INJECTION list
15126 */
15127 BTF_SET_START(btf_non_sleepable_error_inject)
15128 /* Three functions below can be called from sleepable and non-sleepable context.
15129 * Assume non-sleepable from bpf safety point of view.
15130 */
BTF_ID(func,__filemap_add_folio)15131 BTF_ID(func, __filemap_add_folio)
15132 BTF_ID(func, should_fail_alloc_page)
15133 BTF_ID(func, should_failslab)
15134 BTF_SET_END(btf_non_sleepable_error_inject)
15135
15136 static int check_non_sleepable_error_inject(u32 btf_id)
15137 {
15138 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
15139 }
15140
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)15141 int bpf_check_attach_target(struct bpf_verifier_log *log,
15142 const struct bpf_prog *prog,
15143 const struct bpf_prog *tgt_prog,
15144 u32 btf_id,
15145 struct bpf_attach_target_info *tgt_info)
15146 {
15147 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
15148 const char prefix[] = "btf_trace_";
15149 int ret = 0, subprog = -1, i;
15150 const struct btf_type *t;
15151 bool conservative = true;
15152 const char *tname;
15153 struct btf *btf;
15154 long addr = 0;
15155
15156 if (!btf_id) {
15157 bpf_log(log, "Tracing programs must provide btf_id\n");
15158 return -EINVAL;
15159 }
15160 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
15161 if (!btf) {
15162 bpf_log(log,
15163 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
15164 return -EINVAL;
15165 }
15166 t = btf_type_by_id(btf, btf_id);
15167 if (!t) {
15168 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
15169 return -EINVAL;
15170 }
15171 tname = btf_name_by_offset(btf, t->name_off);
15172 if (!tname) {
15173 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
15174 return -EINVAL;
15175 }
15176 if (tgt_prog) {
15177 struct bpf_prog_aux *aux = tgt_prog->aux;
15178
15179 for (i = 0; i < aux->func_info_cnt; i++)
15180 if (aux->func_info[i].type_id == btf_id) {
15181 subprog = i;
15182 break;
15183 }
15184 if (subprog == -1) {
15185 bpf_log(log, "Subprog %s doesn't exist\n", tname);
15186 return -EINVAL;
15187 }
15188 conservative = aux->func_info_aux[subprog].unreliable;
15189 if (prog_extension) {
15190 if (conservative) {
15191 bpf_log(log,
15192 "Cannot replace static functions\n");
15193 return -EINVAL;
15194 }
15195 if (!prog->jit_requested) {
15196 bpf_log(log,
15197 "Extension programs should be JITed\n");
15198 return -EINVAL;
15199 }
15200 }
15201 if (!tgt_prog->jited) {
15202 bpf_log(log, "Can attach to only JITed progs\n");
15203 return -EINVAL;
15204 }
15205 if (tgt_prog->type == prog->type) {
15206 /* Cannot fentry/fexit another fentry/fexit program.
15207 * Cannot attach program extension to another extension.
15208 * It's ok to attach fentry/fexit to extension program.
15209 */
15210 bpf_log(log, "Cannot recursively attach\n");
15211 return -EINVAL;
15212 }
15213 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
15214 prog_extension &&
15215 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
15216 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
15217 /* Program extensions can extend all program types
15218 * except fentry/fexit. The reason is the following.
15219 * The fentry/fexit programs are used for performance
15220 * analysis, stats and can be attached to any program
15221 * type except themselves. When extension program is
15222 * replacing XDP function it is necessary to allow
15223 * performance analysis of all functions. Both original
15224 * XDP program and its program extension. Hence
15225 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
15226 * allowed. If extending of fentry/fexit was allowed it
15227 * would be possible to create long call chain
15228 * fentry->extension->fentry->extension beyond
15229 * reasonable stack size. Hence extending fentry is not
15230 * allowed.
15231 */
15232 bpf_log(log, "Cannot extend fentry/fexit\n");
15233 return -EINVAL;
15234 }
15235 } else {
15236 if (prog_extension) {
15237 bpf_log(log, "Cannot replace kernel functions\n");
15238 return -EINVAL;
15239 }
15240 }
15241
15242 switch (prog->expected_attach_type) {
15243 case BPF_TRACE_RAW_TP:
15244 if (tgt_prog) {
15245 bpf_log(log,
15246 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
15247 return -EINVAL;
15248 }
15249 if (!btf_type_is_typedef(t)) {
15250 bpf_log(log, "attach_btf_id %u is not a typedef\n",
15251 btf_id);
15252 return -EINVAL;
15253 }
15254 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
15255 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
15256 btf_id, tname);
15257 return -EINVAL;
15258 }
15259 tname += sizeof(prefix) - 1;
15260 t = btf_type_by_id(btf, t->type);
15261 if (!btf_type_is_ptr(t))
15262 /* should never happen in valid vmlinux build */
15263 return -EINVAL;
15264 t = btf_type_by_id(btf, t->type);
15265 if (!btf_type_is_func_proto(t))
15266 /* should never happen in valid vmlinux build */
15267 return -EINVAL;
15268
15269 break;
15270 case BPF_TRACE_ITER:
15271 if (!btf_type_is_func(t)) {
15272 bpf_log(log, "attach_btf_id %u is not a function\n",
15273 btf_id);
15274 return -EINVAL;
15275 }
15276 t = btf_type_by_id(btf, t->type);
15277 if (!btf_type_is_func_proto(t))
15278 return -EINVAL;
15279 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15280 if (ret)
15281 return ret;
15282 break;
15283 default:
15284 if (!prog_extension)
15285 return -EINVAL;
15286 fallthrough;
15287 case BPF_MODIFY_RETURN:
15288 case BPF_LSM_MAC:
15289 case BPF_LSM_CGROUP:
15290 case BPF_TRACE_FENTRY:
15291 case BPF_TRACE_FEXIT:
15292 if (!btf_type_is_func(t)) {
15293 bpf_log(log, "attach_btf_id %u is not a function\n",
15294 btf_id);
15295 return -EINVAL;
15296 }
15297 if (prog_extension &&
15298 btf_check_type_match(log, prog, btf, t))
15299 return -EINVAL;
15300 t = btf_type_by_id(btf, t->type);
15301 if (!btf_type_is_func_proto(t))
15302 return -EINVAL;
15303
15304 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
15305 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
15306 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
15307 return -EINVAL;
15308
15309 if (tgt_prog && conservative)
15310 t = NULL;
15311
15312 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
15313 if (ret < 0)
15314 return ret;
15315
15316 if (tgt_prog) {
15317 if (subprog == 0)
15318 addr = (long) tgt_prog->bpf_func;
15319 else
15320 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
15321 } else {
15322 addr = kallsyms_lookup_name(tname);
15323 if (!addr) {
15324 bpf_log(log,
15325 "The address of function %s cannot be found\n",
15326 tname);
15327 return -ENOENT;
15328 }
15329 }
15330
15331 if (prog->aux->sleepable) {
15332 ret = -EINVAL;
15333 switch (prog->type) {
15334 case BPF_PROG_TYPE_TRACING:
15335 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
15336 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
15337 */
15338 if (!check_non_sleepable_error_inject(btf_id) &&
15339 within_error_injection_list(addr))
15340 ret = 0;
15341 break;
15342 case BPF_PROG_TYPE_LSM:
15343 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
15344 * Only some of them are sleepable.
15345 */
15346 if (bpf_lsm_is_sleepable_hook(btf_id))
15347 ret = 0;
15348 break;
15349 default:
15350 break;
15351 }
15352 if (ret) {
15353 bpf_log(log, "%s is not sleepable\n", tname);
15354 return ret;
15355 }
15356 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
15357 if (tgt_prog) {
15358 bpf_log(log, "can't modify return codes of BPF programs\n");
15359 return -EINVAL;
15360 }
15361 ret = check_attach_modify_return(addr, tname);
15362 if (ret) {
15363 bpf_log(log, "%s() is not modifiable\n", tname);
15364 return ret;
15365 }
15366 }
15367
15368 break;
15369 }
15370 tgt_info->tgt_addr = addr;
15371 tgt_info->tgt_name = tname;
15372 tgt_info->tgt_type = t;
15373 return 0;
15374 }
15375
BTF_SET_START(btf_id_deny)15376 BTF_SET_START(btf_id_deny)
15377 BTF_ID_UNUSED
15378 #ifdef CONFIG_SMP
15379 BTF_ID(func, migrate_disable)
15380 BTF_ID(func, migrate_enable)
15381 #endif
15382 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
15383 BTF_ID(func, rcu_read_unlock_strict)
15384 #endif
15385 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
15386 BTF_ID(func, preempt_count_add)
15387 BTF_ID(func, preempt_count_sub)
15388 #endif
15389 BTF_SET_END(btf_id_deny)
15390
15391 static int check_attach_btf_id(struct bpf_verifier_env *env)
15392 {
15393 struct bpf_prog *prog = env->prog;
15394 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
15395 struct bpf_attach_target_info tgt_info = {};
15396 u32 btf_id = prog->aux->attach_btf_id;
15397 struct bpf_trampoline *tr;
15398 int ret;
15399 u64 key;
15400
15401 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
15402 if (prog->aux->sleepable)
15403 /* attach_btf_id checked to be zero already */
15404 return 0;
15405 verbose(env, "Syscall programs can only be sleepable\n");
15406 return -EINVAL;
15407 }
15408
15409 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
15410 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) {
15411 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n");
15412 return -EINVAL;
15413 }
15414
15415 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
15416 return check_struct_ops_btf_id(env);
15417
15418 if (prog->type != BPF_PROG_TYPE_TRACING &&
15419 prog->type != BPF_PROG_TYPE_LSM &&
15420 prog->type != BPF_PROG_TYPE_EXT)
15421 return 0;
15422
15423 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
15424 if (ret)
15425 return ret;
15426
15427 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
15428 /* to make freplace equivalent to their targets, they need to
15429 * inherit env->ops and expected_attach_type for the rest of the
15430 * verification
15431 */
15432 env->ops = bpf_verifier_ops[tgt_prog->type];
15433 prog->expected_attach_type = tgt_prog->expected_attach_type;
15434 }
15435
15436 /* store info about the attachment target that will be used later */
15437 prog->aux->attach_func_proto = tgt_info.tgt_type;
15438 prog->aux->attach_func_name = tgt_info.tgt_name;
15439
15440 if (tgt_prog) {
15441 prog->aux->saved_dst_prog_type = tgt_prog->type;
15442 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
15443 }
15444
15445 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
15446 prog->aux->attach_btf_trace = true;
15447 return 0;
15448 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
15449 if (!bpf_iter_prog_supported(prog))
15450 return -EINVAL;
15451 return 0;
15452 }
15453
15454 if (prog->type == BPF_PROG_TYPE_LSM) {
15455 ret = bpf_lsm_verify_prog(&env->log, prog);
15456 if (ret < 0)
15457 return ret;
15458 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
15459 btf_id_set_contains(&btf_id_deny, btf_id)) {
15460 return -EINVAL;
15461 }
15462
15463 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
15464 tr = bpf_trampoline_get(key, &tgt_info);
15465 if (!tr)
15466 return -ENOMEM;
15467
15468 if (tgt_prog && tgt_prog->aux->tail_call_reachable)
15469 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
15470
15471 prog->aux->dst_trampoline = tr;
15472 return 0;
15473 }
15474
bpf_get_btf_vmlinux(void)15475 struct btf *bpf_get_btf_vmlinux(void)
15476 {
15477 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
15478 mutex_lock(&bpf_verifier_lock);
15479 if (!btf_vmlinux)
15480 btf_vmlinux = btf_parse_vmlinux();
15481 mutex_unlock(&bpf_verifier_lock);
15482 }
15483 return btf_vmlinux;
15484 }
15485
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,bpfptr_t uattr)15486 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
15487 {
15488 u64 start_time = ktime_get_ns();
15489 struct bpf_verifier_env *env;
15490 struct bpf_verifier_log *log;
15491 int i, len, ret = -EINVAL;
15492 bool is_priv;
15493
15494 /* no program is valid */
15495 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
15496 return -EINVAL;
15497
15498 /* 'struct bpf_verifier_env' can be global, but since it's not small,
15499 * allocate/free it every time bpf_check() is called
15500 */
15501 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
15502 if (!env)
15503 return -ENOMEM;
15504 log = &env->log;
15505
15506 len = (*prog)->len;
15507 env->insn_aux_data =
15508 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
15509 ret = -ENOMEM;
15510 if (!env->insn_aux_data)
15511 goto err_free_env;
15512 for (i = 0; i < len; i++)
15513 env->insn_aux_data[i].orig_idx = i;
15514 env->prog = *prog;
15515 env->ops = bpf_verifier_ops[env->prog->type];
15516 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
15517 is_priv = bpf_capable();
15518
15519 bpf_get_btf_vmlinux();
15520
15521 /* grab the mutex to protect few globals used by verifier */
15522 if (!is_priv)
15523 mutex_lock(&bpf_verifier_lock);
15524
15525 if (attr->log_level || attr->log_buf || attr->log_size) {
15526 /* user requested verbose verifier output
15527 * and supplied buffer to store the verification trace
15528 */
15529 log->level = attr->log_level;
15530 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
15531 log->len_total = attr->log_size;
15532
15533 /* log attributes have to be sane */
15534 if (!bpf_verifier_log_attr_valid(log)) {
15535 ret = -EINVAL;
15536 goto err_unlock;
15537 }
15538 }
15539
15540 mark_verifier_state_clean(env);
15541
15542 if (IS_ERR(btf_vmlinux)) {
15543 /* Either gcc or pahole or kernel are broken. */
15544 verbose(env, "in-kernel BTF is malformed\n");
15545 ret = PTR_ERR(btf_vmlinux);
15546 goto skip_full_check;
15547 }
15548
15549 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
15550 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
15551 env->strict_alignment = true;
15552 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
15553 env->strict_alignment = false;
15554
15555 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
15556 env->allow_uninit_stack = bpf_allow_uninit_stack();
15557 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
15558 env->bypass_spec_v1 = bpf_bypass_spec_v1();
15559 env->bypass_spec_v4 = bpf_bypass_spec_v4();
15560 env->bpf_capable = bpf_capable();
15561
15562 if (is_priv)
15563 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
15564
15565 env->explored_states = kvcalloc(state_htab_size(env),
15566 sizeof(struct bpf_verifier_state_list *),
15567 GFP_USER);
15568 ret = -ENOMEM;
15569 if (!env->explored_states)
15570 goto skip_full_check;
15571
15572 ret = add_subprog_and_kfunc(env);
15573 if (ret < 0)
15574 goto skip_full_check;
15575
15576 ret = check_subprogs(env);
15577 if (ret < 0)
15578 goto skip_full_check;
15579
15580 ret = check_btf_info(env, attr, uattr);
15581 if (ret < 0)
15582 goto skip_full_check;
15583
15584 ret = check_attach_btf_id(env);
15585 if (ret)
15586 goto skip_full_check;
15587
15588 ret = resolve_pseudo_ldimm64(env);
15589 if (ret < 0)
15590 goto skip_full_check;
15591
15592 if (bpf_prog_is_dev_bound(env->prog->aux)) {
15593 ret = bpf_prog_offload_verifier_prep(env->prog);
15594 if (ret)
15595 goto skip_full_check;
15596 }
15597
15598 ret = check_cfg(env);
15599 if (ret < 0)
15600 goto skip_full_check;
15601
15602 ret = do_check_subprogs(env);
15603 ret = ret ?: do_check_main(env);
15604
15605 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
15606 ret = bpf_prog_offload_finalize(env);
15607
15608 skip_full_check:
15609 kvfree(env->explored_states);
15610
15611 if (ret == 0)
15612 ret = check_max_stack_depth(env);
15613
15614 /* instruction rewrites happen after this point */
15615 if (ret == 0)
15616 ret = optimize_bpf_loop(env);
15617
15618 if (is_priv) {
15619 if (ret == 0)
15620 opt_hard_wire_dead_code_branches(env);
15621 if (ret == 0)
15622 ret = opt_remove_dead_code(env);
15623 if (ret == 0)
15624 ret = opt_remove_nops(env);
15625 } else {
15626 if (ret == 0)
15627 sanitize_dead_code(env);
15628 }
15629
15630 if (ret == 0)
15631 /* program is valid, convert *(u32*)(ctx + off) accesses */
15632 ret = convert_ctx_accesses(env);
15633
15634 if (ret == 0)
15635 ret = do_misc_fixups(env);
15636
15637 /* do 32-bit optimization after insn patching has done so those patched
15638 * insns could be handled correctly.
15639 */
15640 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
15641 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
15642 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
15643 : false;
15644 }
15645
15646 if (ret == 0)
15647 ret = fixup_call_args(env);
15648
15649 env->verification_time = ktime_get_ns() - start_time;
15650 print_verification_stats(env);
15651 env->prog->aux->verified_insns = env->insn_processed;
15652
15653 if (log->level && bpf_verifier_log_full(log))
15654 ret = -ENOSPC;
15655 if (log->level && !log->ubuf) {
15656 ret = -EFAULT;
15657 goto err_release_maps;
15658 }
15659
15660 if (ret)
15661 goto err_release_maps;
15662
15663 if (env->used_map_cnt) {
15664 /* if program passed verifier, update used_maps in bpf_prog_info */
15665 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
15666 sizeof(env->used_maps[0]),
15667 GFP_KERNEL);
15668
15669 if (!env->prog->aux->used_maps) {
15670 ret = -ENOMEM;
15671 goto err_release_maps;
15672 }
15673
15674 memcpy(env->prog->aux->used_maps, env->used_maps,
15675 sizeof(env->used_maps[0]) * env->used_map_cnt);
15676 env->prog->aux->used_map_cnt = env->used_map_cnt;
15677 }
15678 if (env->used_btf_cnt) {
15679 /* if program passed verifier, update used_btfs in bpf_prog_aux */
15680 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
15681 sizeof(env->used_btfs[0]),
15682 GFP_KERNEL);
15683 if (!env->prog->aux->used_btfs) {
15684 ret = -ENOMEM;
15685 goto err_release_maps;
15686 }
15687
15688 memcpy(env->prog->aux->used_btfs, env->used_btfs,
15689 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
15690 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
15691 }
15692 if (env->used_map_cnt || env->used_btf_cnt) {
15693 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
15694 * bpf_ld_imm64 instructions
15695 */
15696 convert_pseudo_ld_imm64(env);
15697 }
15698
15699 adjust_btf_func(env);
15700
15701 err_release_maps:
15702 if (!env->prog->aux->used_maps)
15703 /* if we didn't copy map pointers into bpf_prog_info, release
15704 * them now. Otherwise free_used_maps() will release them.
15705 */
15706 release_maps(env);
15707 if (!env->prog->aux->used_btfs)
15708 release_btfs(env);
15709
15710 /* extension progs temporarily inherit the attach_type of their targets
15711 for verification purposes, so set it back to zero before returning
15712 */
15713 if (env->prog->type == BPF_PROG_TYPE_EXT)
15714 env->prog->expected_attach_type = 0;
15715
15716 *prog = env->prog;
15717 err_unlock:
15718 if (!is_priv)
15719 mutex_unlock(&bpf_verifier_lock);
15720 vfree(env->insn_aux_data);
15721 err_free_env:
15722 kfree(env);
15723 return ret;
15724 }
15725