]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - kernel/bpf/verifier.c
watch_queue: Free the page array when watch_queue is dismantled
[mirror_ubuntu-jammy-kernel.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3 * Copyright (c) 2016 Facebook
4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5 */
6 #include <uapi/linux/btf.h>
7 #include <linux/kernel.h>
8 #include <linux/types.h>
9 #include <linux/slab.h>
10 #include <linux/bpf.h>
11 #include <linux/btf.h>
12 #include <linux/bpf_verifier.h>
13 #include <linux/filter.h>
14 #include <net/netlink.h>
15 #include <linux/file.h>
16 #include <linux/vmalloc.h>
17 #include <linux/stringify.h>
18 #include <linux/bsearch.h>
19 #include <linux/sort.h>
20 #include <linux/perf_event.h>
21 #include <linux/ctype.h>
22 #include <linux/error-injection.h>
23 #include <linux/bpf_lsm.h>
24 #include <linux/btf_ids.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #define BPF_LINK_TYPE(_id, _name)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 #undef BPF_LINK_TYPE
37 };
38
39 /* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all paths through the program, the length of the
51 * analysis is limited to 64k insn, which may be hit even if total number of
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
79 * Most of the time the registers have SCALAR_VALUE type, which
80 * means the register has some value, but it's not a valid pointer.
81 * (like pointer plus pointer becomes SCALAR_VALUE type)
82 *
83 * When verifier sees load or store instructions the type of base register
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns either pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
162 */
163
164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
165 struct bpf_verifier_stack_elem {
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
170 struct bpf_verifier_state st;
171 int insn_idx;
172 int prev_insn_idx;
173 struct bpf_verifier_stack_elem *next;
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
176 };
177
178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
179 #define BPF_COMPLEXITY_LIMIT_STATES 64
180
181 #define BPF_MAP_KEY_POISON (1ULL << 63)
182 #define BPF_MAP_KEY_SEEN (1ULL << 62)
183
184 #define BPF_MAP_PTR_UNPRIV 1UL
185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190 {
191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
192 }
193
194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195 {
196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
197 }
198
199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201 {
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206 }
207
208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209 {
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211 }
212
213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214 {
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216 }
217
218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219 {
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221 }
222
223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224 {
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
229 }
230
231 static bool bpf_pseudo_call(const struct bpf_insn *insn)
232 {
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
235 }
236
237 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238 {
239 return insn->code == (BPF_JMP | BPF_CALL) &&
240 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241 }
242
243 static bool bpf_pseudo_func(const struct bpf_insn *insn)
244 {
245 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 insn->src_reg == BPF_PSEUDO_FUNC;
247 }
248
249 struct bpf_call_arg_meta {
250 struct bpf_map *map_ptr;
251 bool raw_mode;
252 bool pkt_access;
253 int regno;
254 int access_size;
255 int mem_size;
256 u64 msize_max_value;
257 int ref_obj_id;
258 int map_uid;
259 int func_id;
260 struct btf *btf;
261 u32 btf_id;
262 struct btf *ret_btf;
263 u32 ret_btf_id;
264 u32 subprogno;
265 };
266
267 struct btf *btf_vmlinux;
268
269 static DEFINE_MUTEX(bpf_verifier_lock);
270
271 static const struct bpf_line_info *
272 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
273 {
274 const struct bpf_line_info *linfo;
275 const struct bpf_prog *prog;
276 u32 i, nr_linfo;
277
278 prog = env->prog;
279 nr_linfo = prog->aux->nr_linfo;
280
281 if (!nr_linfo || insn_off >= prog->len)
282 return NULL;
283
284 linfo = prog->aux->linfo;
285 for (i = 1; i < nr_linfo; i++)
286 if (insn_off < linfo[i].insn_off)
287 break;
288
289 return &linfo[i - 1];
290 }
291
292 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
293 va_list args)
294 {
295 unsigned int n;
296
297 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
298
299 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
300 "verifier log line truncated - local buffer too short\n");
301
302 n = min(log->len_total - log->len_used - 1, n);
303 log->kbuf[n] = '\0';
304
305 if (log->level == BPF_LOG_KERNEL) {
306 pr_err("BPF:%s\n", log->kbuf);
307 return;
308 }
309 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
310 log->len_used += n;
311 else
312 log->ubuf = NULL;
313 }
314
315 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
316 {
317 char zero = 0;
318
319 if (!bpf_verifier_log_needed(log))
320 return;
321
322 log->len_used = new_pos;
323 if (put_user(zero, log->ubuf + new_pos))
324 log->ubuf = NULL;
325 }
326
327 /* log_level controls verbosity level of eBPF verifier.
328 * bpf_verifier_log_write() is used to dump the verification trace to the log,
329 * so the user can figure out what's wrong with the program
330 */
331 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
332 const char *fmt, ...)
333 {
334 va_list args;
335
336 if (!bpf_verifier_log_needed(&env->log))
337 return;
338
339 va_start(args, fmt);
340 bpf_verifier_vlog(&env->log, fmt, args);
341 va_end(args);
342 }
343 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
344
345 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
346 {
347 struct bpf_verifier_env *env = private_data;
348 va_list args;
349
350 if (!bpf_verifier_log_needed(&env->log))
351 return;
352
353 va_start(args, fmt);
354 bpf_verifier_vlog(&env->log, fmt, args);
355 va_end(args);
356 }
357
358 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
359 const char *fmt, ...)
360 {
361 va_list args;
362
363 if (!bpf_verifier_log_needed(log))
364 return;
365
366 va_start(args, fmt);
367 bpf_verifier_vlog(log, fmt, args);
368 va_end(args);
369 }
370
371 static const char *ltrim(const char *s)
372 {
373 while (isspace(*s))
374 s++;
375
376 return s;
377 }
378
379 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
380 u32 insn_off,
381 const char *prefix_fmt, ...)
382 {
383 const struct bpf_line_info *linfo;
384
385 if (!bpf_verifier_log_needed(&env->log))
386 return;
387
388 linfo = find_linfo(env, insn_off);
389 if (!linfo || linfo == env->prev_linfo)
390 return;
391
392 if (prefix_fmt) {
393 va_list args;
394
395 va_start(args, prefix_fmt);
396 bpf_verifier_vlog(&env->log, prefix_fmt, args);
397 va_end(args);
398 }
399
400 verbose(env, "%s\n",
401 ltrim(btf_name_by_offset(env->prog->aux->btf,
402 linfo->line_off)));
403
404 env->prev_linfo = linfo;
405 }
406
407 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
408 struct bpf_reg_state *reg,
409 struct tnum *range, const char *ctx,
410 const char *reg_name)
411 {
412 char tn_buf[48];
413
414 verbose(env, "At %s the register %s ", ctx, reg_name);
415 if (!tnum_is_unknown(reg->var_off)) {
416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
417 verbose(env, "has value %s", tn_buf);
418 } else {
419 verbose(env, "has unknown scalar value");
420 }
421 tnum_strn(tn_buf, sizeof(tn_buf), *range);
422 verbose(env, " should have been in %s\n", tn_buf);
423 }
424
425 static bool type_is_pkt_pointer(enum bpf_reg_type type)
426 {
427 return type == PTR_TO_PACKET ||
428 type == PTR_TO_PACKET_META;
429 }
430
431 static bool type_is_sk_pointer(enum bpf_reg_type type)
432 {
433 return type == PTR_TO_SOCKET ||
434 type == PTR_TO_SOCK_COMMON ||
435 type == PTR_TO_TCP_SOCK ||
436 type == PTR_TO_XDP_SOCK;
437 }
438
439 static bool reg_type_not_null(enum bpf_reg_type type)
440 {
441 return type == PTR_TO_SOCKET ||
442 type == PTR_TO_TCP_SOCK ||
443 type == PTR_TO_MAP_VALUE ||
444 type == PTR_TO_MAP_KEY ||
445 type == PTR_TO_SOCK_COMMON;
446 }
447
448 static bool reg_type_may_be_null(enum bpf_reg_type type)
449 {
450 return type == PTR_TO_MAP_VALUE_OR_NULL ||
451 type == PTR_TO_SOCKET_OR_NULL ||
452 type == PTR_TO_SOCK_COMMON_OR_NULL ||
453 type == PTR_TO_TCP_SOCK_OR_NULL ||
454 type == PTR_TO_BTF_ID_OR_NULL ||
455 type == PTR_TO_MEM_OR_NULL ||
456 type == PTR_TO_RDONLY_BUF_OR_NULL ||
457 type == PTR_TO_RDWR_BUF_OR_NULL;
458 }
459
460 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
461 {
462 return reg->type == PTR_TO_MAP_VALUE &&
463 map_value_has_spin_lock(reg->map_ptr);
464 }
465
466 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
467 {
468 return type == PTR_TO_SOCKET ||
469 type == PTR_TO_SOCKET_OR_NULL ||
470 type == PTR_TO_TCP_SOCK ||
471 type == PTR_TO_TCP_SOCK_OR_NULL ||
472 type == PTR_TO_MEM ||
473 type == PTR_TO_MEM_OR_NULL;
474 }
475
476 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
477 {
478 return type == ARG_PTR_TO_SOCK_COMMON;
479 }
480
481 static bool arg_type_may_be_null(enum bpf_arg_type type)
482 {
483 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
484 type == ARG_PTR_TO_MEM_OR_NULL ||
485 type == ARG_PTR_TO_CTX_OR_NULL ||
486 type == ARG_PTR_TO_SOCKET_OR_NULL ||
487 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
488 type == ARG_PTR_TO_STACK_OR_NULL;
489 }
490
491 /* Determine whether the function releases some resources allocated by another
492 * function call. The first reference type argument will be assumed to be
493 * released by release_reference().
494 */
495 static bool is_release_function(enum bpf_func_id func_id)
496 {
497 return func_id == BPF_FUNC_sk_release ||
498 func_id == BPF_FUNC_ringbuf_submit ||
499 func_id == BPF_FUNC_ringbuf_discard;
500 }
501
502 static bool may_be_acquire_function(enum bpf_func_id func_id)
503 {
504 return func_id == BPF_FUNC_sk_lookup_tcp ||
505 func_id == BPF_FUNC_sk_lookup_udp ||
506 func_id == BPF_FUNC_skc_lookup_tcp ||
507 func_id == BPF_FUNC_map_lookup_elem ||
508 func_id == BPF_FUNC_ringbuf_reserve;
509 }
510
511 static bool is_acquire_function(enum bpf_func_id func_id,
512 const struct bpf_map *map)
513 {
514 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
515
516 if (func_id == BPF_FUNC_sk_lookup_tcp ||
517 func_id == BPF_FUNC_sk_lookup_udp ||
518 func_id == BPF_FUNC_skc_lookup_tcp ||
519 func_id == BPF_FUNC_ringbuf_reserve)
520 return true;
521
522 if (func_id == BPF_FUNC_map_lookup_elem &&
523 (map_type == BPF_MAP_TYPE_SOCKMAP ||
524 map_type == BPF_MAP_TYPE_SOCKHASH))
525 return true;
526
527 return false;
528 }
529
530 static bool is_ptr_cast_function(enum bpf_func_id func_id)
531 {
532 return func_id == BPF_FUNC_tcp_sock ||
533 func_id == BPF_FUNC_sk_fullsock ||
534 func_id == BPF_FUNC_skc_to_tcp_sock ||
535 func_id == BPF_FUNC_skc_to_tcp6_sock ||
536 func_id == BPF_FUNC_skc_to_udp6_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
538 func_id == BPF_FUNC_skc_to_tcp_request_sock;
539 }
540
541 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
542 {
543 return BPF_CLASS(insn->code) == BPF_STX &&
544 BPF_MODE(insn->code) == BPF_ATOMIC &&
545 insn->imm == BPF_CMPXCHG;
546 }
547
548 /* string representation of 'enum bpf_reg_type' */
549 static const char * const reg_type_str[] = {
550 [NOT_INIT] = "?",
551 [SCALAR_VALUE] = "inv",
552 [PTR_TO_CTX] = "ctx",
553 [CONST_PTR_TO_MAP] = "map_ptr",
554 [PTR_TO_MAP_VALUE] = "map_value",
555 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
556 [PTR_TO_STACK] = "fp",
557 [PTR_TO_PACKET] = "pkt",
558 [PTR_TO_PACKET_META] = "pkt_meta",
559 [PTR_TO_PACKET_END] = "pkt_end",
560 [PTR_TO_FLOW_KEYS] = "flow_keys",
561 [PTR_TO_SOCKET] = "sock",
562 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
563 [PTR_TO_SOCK_COMMON] = "sock_common",
564 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
565 [PTR_TO_TCP_SOCK] = "tcp_sock",
566 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
567 [PTR_TO_TP_BUFFER] = "tp_buffer",
568 [PTR_TO_XDP_SOCK] = "xdp_sock",
569 [PTR_TO_BTF_ID] = "ptr_",
570 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
571 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
572 [PTR_TO_MEM] = "mem",
573 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
574 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
575 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
576 [PTR_TO_RDWR_BUF] = "rdwr_buf",
577 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
578 [PTR_TO_FUNC] = "func",
579 [PTR_TO_MAP_KEY] = "map_key",
580 };
581
582 static char slot_type_char[] = {
583 [STACK_INVALID] = '?',
584 [STACK_SPILL] = 'r',
585 [STACK_MISC] = 'm',
586 [STACK_ZERO] = '0',
587 };
588
589 static void print_liveness(struct bpf_verifier_env *env,
590 enum bpf_reg_liveness live)
591 {
592 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
593 verbose(env, "_");
594 if (live & REG_LIVE_READ)
595 verbose(env, "r");
596 if (live & REG_LIVE_WRITTEN)
597 verbose(env, "w");
598 if (live & REG_LIVE_DONE)
599 verbose(env, "D");
600 }
601
602 static struct bpf_func_state *func(struct bpf_verifier_env *env,
603 const struct bpf_reg_state *reg)
604 {
605 struct bpf_verifier_state *cur = env->cur_state;
606
607 return cur->frame[reg->frameno];
608 }
609
610 static const char *kernel_type_name(const struct btf* btf, u32 id)
611 {
612 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
613 }
614
615 static void print_verifier_state(struct bpf_verifier_env *env,
616 const struct bpf_func_state *state)
617 {
618 const struct bpf_reg_state *reg;
619 enum bpf_reg_type t;
620 int i;
621
622 if (state->frameno)
623 verbose(env, " frame%d:", state->frameno);
624 for (i = 0; i < MAX_BPF_REG; i++) {
625 reg = &state->regs[i];
626 t = reg->type;
627 if (t == NOT_INIT)
628 continue;
629 verbose(env, " R%d", i);
630 print_liveness(env, reg->live);
631 verbose(env, "=%s", reg_type_str[t]);
632 if (t == SCALAR_VALUE && reg->precise)
633 verbose(env, "P");
634 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
635 tnum_is_const(reg->var_off)) {
636 /* reg->off should be 0 for SCALAR_VALUE */
637 verbose(env, "%lld", reg->var_off.value + reg->off);
638 } else {
639 if (t == PTR_TO_BTF_ID ||
640 t == PTR_TO_BTF_ID_OR_NULL ||
641 t == PTR_TO_PERCPU_BTF_ID)
642 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
643 verbose(env, "(id=%d", reg->id);
644 if (reg_type_may_be_refcounted_or_null(t))
645 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
646 if (t != SCALAR_VALUE)
647 verbose(env, ",off=%d", reg->off);
648 if (type_is_pkt_pointer(t))
649 verbose(env, ",r=%d", reg->range);
650 else if (t == CONST_PTR_TO_MAP ||
651 t == PTR_TO_MAP_KEY ||
652 t == PTR_TO_MAP_VALUE ||
653 t == PTR_TO_MAP_VALUE_OR_NULL)
654 verbose(env, ",ks=%d,vs=%d",
655 reg->map_ptr->key_size,
656 reg->map_ptr->value_size);
657 if (tnum_is_const(reg->var_off)) {
658 /* Typically an immediate SCALAR_VALUE, but
659 * could be a pointer whose offset is too big
660 * for reg->off
661 */
662 verbose(env, ",imm=%llx", reg->var_off.value);
663 } else {
664 if (reg->smin_value != reg->umin_value &&
665 reg->smin_value != S64_MIN)
666 verbose(env, ",smin_value=%lld",
667 (long long)reg->smin_value);
668 if (reg->smax_value != reg->umax_value &&
669 reg->smax_value != S64_MAX)
670 verbose(env, ",smax_value=%lld",
671 (long long)reg->smax_value);
672 if (reg->umin_value != 0)
673 verbose(env, ",umin_value=%llu",
674 (unsigned long long)reg->umin_value);
675 if (reg->umax_value != U64_MAX)
676 verbose(env, ",umax_value=%llu",
677 (unsigned long long)reg->umax_value);
678 if (!tnum_is_unknown(reg->var_off)) {
679 char tn_buf[48];
680
681 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
682 verbose(env, ",var_off=%s", tn_buf);
683 }
684 if (reg->s32_min_value != reg->smin_value &&
685 reg->s32_min_value != S32_MIN)
686 verbose(env, ",s32_min_value=%d",
687 (int)(reg->s32_min_value));
688 if (reg->s32_max_value != reg->smax_value &&
689 reg->s32_max_value != S32_MAX)
690 verbose(env, ",s32_max_value=%d",
691 (int)(reg->s32_max_value));
692 if (reg->u32_min_value != reg->umin_value &&
693 reg->u32_min_value != U32_MIN)
694 verbose(env, ",u32_min_value=%d",
695 (int)(reg->u32_min_value));
696 if (reg->u32_max_value != reg->umax_value &&
697 reg->u32_max_value != U32_MAX)
698 verbose(env, ",u32_max_value=%d",
699 (int)(reg->u32_max_value));
700 }
701 verbose(env, ")");
702 }
703 }
704 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
705 char types_buf[BPF_REG_SIZE + 1];
706 bool valid = false;
707 int j;
708
709 for (j = 0; j < BPF_REG_SIZE; j++) {
710 if (state->stack[i].slot_type[j] != STACK_INVALID)
711 valid = true;
712 types_buf[j] = slot_type_char[
713 state->stack[i].slot_type[j]];
714 }
715 types_buf[BPF_REG_SIZE] = 0;
716 if (!valid)
717 continue;
718 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
719 print_liveness(env, state->stack[i].spilled_ptr.live);
720 if (state->stack[i].slot_type[0] == STACK_SPILL) {
721 reg = &state->stack[i].spilled_ptr;
722 t = reg->type;
723 verbose(env, "=%s", reg_type_str[t]);
724 if (t == SCALAR_VALUE && reg->precise)
725 verbose(env, "P");
726 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
727 verbose(env, "%lld", reg->var_off.value + reg->off);
728 } else {
729 verbose(env, "=%s", types_buf);
730 }
731 }
732 if (state->acquired_refs && state->refs[0].id) {
733 verbose(env, " refs=%d", state->refs[0].id);
734 for (i = 1; i < state->acquired_refs; i++)
735 if (state->refs[i].id)
736 verbose(env, ",%d", state->refs[i].id);
737 }
738 if (state->in_callback_fn)
739 verbose(env, " cb");
740 if (state->in_async_callback_fn)
741 verbose(env, " async_cb");
742 verbose(env, "\n");
743 }
744
745 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
746 * small to hold src. This is different from krealloc since we don't want to preserve
747 * the contents of dst.
748 *
749 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
750 * not be allocated.
751 */
752 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
753 {
754 size_t bytes;
755
756 if (ZERO_OR_NULL_PTR(src))
757 goto out;
758
759 if (unlikely(check_mul_overflow(n, size, &bytes)))
760 return NULL;
761
762 if (ksize(dst) < bytes) {
763 kfree(dst);
764 dst = kmalloc_track_caller(bytes, flags);
765 if (!dst)
766 return NULL;
767 }
768
769 memcpy(dst, src, bytes);
770 out:
771 return dst ? dst : ZERO_SIZE_PTR;
772 }
773
774 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
775 * small to hold new_n items. new items are zeroed out if the array grows.
776 *
777 * Contrary to krealloc_array, does not free arr if new_n is zero.
778 */
779 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
780 {
781 if (!new_n || old_n == new_n)
782 goto out;
783
784 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
785 if (!arr)
786 return NULL;
787
788 if (new_n > old_n)
789 memset(arr + old_n * size, 0, (new_n - old_n) * size);
790
791 out:
792 return arr ? arr : ZERO_SIZE_PTR;
793 }
794
795 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
796 {
797 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
798 sizeof(struct bpf_reference_state), GFP_KERNEL);
799 if (!dst->refs)
800 return -ENOMEM;
801
802 dst->acquired_refs = src->acquired_refs;
803 return 0;
804 }
805
806 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
807 {
808 size_t n = src->allocated_stack / BPF_REG_SIZE;
809
810 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
811 GFP_KERNEL);
812 if (!dst->stack)
813 return -ENOMEM;
814
815 dst->allocated_stack = src->allocated_stack;
816 return 0;
817 }
818
819 static int resize_reference_state(struct bpf_func_state *state, size_t n)
820 {
821 state->refs = realloc_array(state->refs, state->acquired_refs, n,
822 sizeof(struct bpf_reference_state));
823 if (!state->refs)
824 return -ENOMEM;
825
826 state->acquired_refs = n;
827 return 0;
828 }
829
830 static int grow_stack_state(struct bpf_func_state *state, int size)
831 {
832 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
833
834 if (old_n >= n)
835 return 0;
836
837 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
838 if (!state->stack)
839 return -ENOMEM;
840
841 state->allocated_stack = size;
842 return 0;
843 }
844
845 /* Acquire a pointer id from the env and update the state->refs to include
846 * this new pointer reference.
847 * On success, returns a valid pointer id to associate with the register
848 * On failure, returns a negative errno.
849 */
850 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
851 {
852 struct bpf_func_state *state = cur_func(env);
853 int new_ofs = state->acquired_refs;
854 int id, err;
855
856 err = resize_reference_state(state, state->acquired_refs + 1);
857 if (err)
858 return err;
859 id = ++env->id_gen;
860 state->refs[new_ofs].id = id;
861 state->refs[new_ofs].insn_idx = insn_idx;
862
863 return id;
864 }
865
866 /* release function corresponding to acquire_reference_state(). Idempotent. */
867 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
868 {
869 int i, last_idx;
870
871 last_idx = state->acquired_refs - 1;
872 for (i = 0; i < state->acquired_refs; i++) {
873 if (state->refs[i].id == ptr_id) {
874 if (last_idx && i != last_idx)
875 memcpy(&state->refs[i], &state->refs[last_idx],
876 sizeof(*state->refs));
877 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
878 state->acquired_refs--;
879 return 0;
880 }
881 }
882 return -EINVAL;
883 }
884
885 static void free_func_state(struct bpf_func_state *state)
886 {
887 if (!state)
888 return;
889 kfree(state->refs);
890 kfree(state->stack);
891 kfree(state);
892 }
893
894 static void clear_jmp_history(struct bpf_verifier_state *state)
895 {
896 kfree(state->jmp_history);
897 state->jmp_history = NULL;
898 state->jmp_history_cnt = 0;
899 }
900
901 static void free_verifier_state(struct bpf_verifier_state *state,
902 bool free_self)
903 {
904 int i;
905
906 for (i = 0; i <= state->curframe; i++) {
907 free_func_state(state->frame[i]);
908 state->frame[i] = NULL;
909 }
910 clear_jmp_history(state);
911 if (free_self)
912 kfree(state);
913 }
914
915 /* copy verifier state from src to dst growing dst stack space
916 * when necessary to accommodate larger src stack
917 */
918 static int copy_func_state(struct bpf_func_state *dst,
919 const struct bpf_func_state *src)
920 {
921 int err;
922
923 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
924 err = copy_reference_state(dst, src);
925 if (err)
926 return err;
927 return copy_stack_state(dst, src);
928 }
929
930 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
931 const struct bpf_verifier_state *src)
932 {
933 struct bpf_func_state *dst;
934 int i, err;
935
936 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
937 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
938 GFP_USER);
939 if (!dst_state->jmp_history)
940 return -ENOMEM;
941 dst_state->jmp_history_cnt = src->jmp_history_cnt;
942
943 /* if dst has more stack frames then src frame, free them */
944 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
945 free_func_state(dst_state->frame[i]);
946 dst_state->frame[i] = NULL;
947 }
948 dst_state->speculative = src->speculative;
949 dst_state->curframe = src->curframe;
950 dst_state->active_spin_lock = src->active_spin_lock;
951 dst_state->branches = src->branches;
952 dst_state->parent = src->parent;
953 dst_state->first_insn_idx = src->first_insn_idx;
954 dst_state->last_insn_idx = src->last_insn_idx;
955 for (i = 0; i <= src->curframe; i++) {
956 dst = dst_state->frame[i];
957 if (!dst) {
958 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
959 if (!dst)
960 return -ENOMEM;
961 dst_state->frame[i] = dst;
962 }
963 err = copy_func_state(dst, src->frame[i]);
964 if (err)
965 return err;
966 }
967 return 0;
968 }
969
970 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
971 {
972 while (st) {
973 u32 br = --st->branches;
974
975 /* WARN_ON(br > 1) technically makes sense here,
976 * but see comment in push_stack(), hence:
977 */
978 WARN_ONCE((int)br < 0,
979 "BUG update_branch_counts:branches_to_explore=%d\n",
980 br);
981 if (br)
982 break;
983 st = st->parent;
984 }
985 }
986
987 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
988 int *insn_idx, bool pop_log)
989 {
990 struct bpf_verifier_state *cur = env->cur_state;
991 struct bpf_verifier_stack_elem *elem, *head = env->head;
992 int err;
993
994 if (env->head == NULL)
995 return -ENOENT;
996
997 if (cur) {
998 err = copy_verifier_state(cur, &head->st);
999 if (err)
1000 return err;
1001 }
1002 if (pop_log)
1003 bpf_vlog_reset(&env->log, head->log_pos);
1004 if (insn_idx)
1005 *insn_idx = head->insn_idx;
1006 if (prev_insn_idx)
1007 *prev_insn_idx = head->prev_insn_idx;
1008 elem = head->next;
1009 free_verifier_state(&head->st, false);
1010 kfree(head);
1011 env->head = elem;
1012 env->stack_size--;
1013 return 0;
1014 }
1015
1016 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1017 int insn_idx, int prev_insn_idx,
1018 bool speculative)
1019 {
1020 struct bpf_verifier_state *cur = env->cur_state;
1021 struct bpf_verifier_stack_elem *elem;
1022 int err;
1023
1024 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1025 if (!elem)
1026 goto err;
1027
1028 elem->insn_idx = insn_idx;
1029 elem->prev_insn_idx = prev_insn_idx;
1030 elem->next = env->head;
1031 elem->log_pos = env->log.len_used;
1032 env->head = elem;
1033 env->stack_size++;
1034 err = copy_verifier_state(&elem->st, cur);
1035 if (err)
1036 goto err;
1037 elem->st.speculative |= speculative;
1038 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1039 verbose(env, "The sequence of %d jumps is too complex.\n",
1040 env->stack_size);
1041 goto err;
1042 }
1043 if (elem->st.parent) {
1044 ++elem->st.parent->branches;
1045 /* WARN_ON(branches > 2) technically makes sense here,
1046 * but
1047 * 1. speculative states will bump 'branches' for non-branch
1048 * instructions
1049 * 2. is_state_visited() heuristics may decide not to create
1050 * a new state for a sequence of branches and all such current
1051 * and cloned states will be pointing to a single parent state
1052 * which might have large 'branches' count.
1053 */
1054 }
1055 return &elem->st;
1056 err:
1057 free_verifier_state(env->cur_state, true);
1058 env->cur_state = NULL;
1059 /* pop all elements and return */
1060 while (!pop_stack(env, NULL, NULL, false));
1061 return NULL;
1062 }
1063
1064 #define CALLER_SAVED_REGS 6
1065 static const int caller_saved[CALLER_SAVED_REGS] = {
1066 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1067 };
1068
1069 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1070 struct bpf_reg_state *reg);
1071
1072 /* This helper doesn't clear reg->id */
1073 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1074 {
1075 reg->var_off = tnum_const(imm);
1076 reg->smin_value = (s64)imm;
1077 reg->smax_value = (s64)imm;
1078 reg->umin_value = imm;
1079 reg->umax_value = imm;
1080
1081 reg->s32_min_value = (s32)imm;
1082 reg->s32_max_value = (s32)imm;
1083 reg->u32_min_value = (u32)imm;
1084 reg->u32_max_value = (u32)imm;
1085 }
1086
1087 /* Mark the unknown part of a register (variable offset or scalar value) as
1088 * known to have the value @imm.
1089 */
1090 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1091 {
1092 /* Clear id, off, and union(map_ptr, range) */
1093 memset(((u8 *)reg) + sizeof(reg->type), 0,
1094 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1095 ___mark_reg_known(reg, imm);
1096 }
1097
1098 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1099 {
1100 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1101 reg->s32_min_value = (s32)imm;
1102 reg->s32_max_value = (s32)imm;
1103 reg->u32_min_value = (u32)imm;
1104 reg->u32_max_value = (u32)imm;
1105 }
1106
1107 /* Mark the 'variable offset' part of a register as zero. This should be
1108 * used only on registers holding a pointer type.
1109 */
1110 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1111 {
1112 __mark_reg_known(reg, 0);
1113 }
1114
1115 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1116 {
1117 __mark_reg_known(reg, 0);
1118 reg->type = SCALAR_VALUE;
1119 }
1120
1121 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1122 struct bpf_reg_state *regs, u32 regno)
1123 {
1124 if (WARN_ON(regno >= MAX_BPF_REG)) {
1125 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1126 /* Something bad happened, let's kill all regs */
1127 for (regno = 0; regno < MAX_BPF_REG; regno++)
1128 __mark_reg_not_init(env, regs + regno);
1129 return;
1130 }
1131 __mark_reg_known_zero(regs + regno);
1132 }
1133
1134 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1135 {
1136 switch (reg->type) {
1137 case PTR_TO_MAP_VALUE_OR_NULL: {
1138 const struct bpf_map *map = reg->map_ptr;
1139
1140 if (map->inner_map_meta) {
1141 reg->type = CONST_PTR_TO_MAP;
1142 reg->map_ptr = map->inner_map_meta;
1143 /* transfer reg's id which is unique for every map_lookup_elem
1144 * as UID of the inner map.
1145 */
1146 if (map_value_has_timer(map->inner_map_meta))
1147 reg->map_uid = reg->id;
1148 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1149 reg->type = PTR_TO_XDP_SOCK;
1150 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1151 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1152 reg->type = PTR_TO_SOCKET;
1153 } else {
1154 reg->type = PTR_TO_MAP_VALUE;
1155 }
1156 break;
1157 }
1158 case PTR_TO_SOCKET_OR_NULL:
1159 reg->type = PTR_TO_SOCKET;
1160 break;
1161 case PTR_TO_SOCK_COMMON_OR_NULL:
1162 reg->type = PTR_TO_SOCK_COMMON;
1163 break;
1164 case PTR_TO_TCP_SOCK_OR_NULL:
1165 reg->type = PTR_TO_TCP_SOCK;
1166 break;
1167 case PTR_TO_BTF_ID_OR_NULL:
1168 reg->type = PTR_TO_BTF_ID;
1169 break;
1170 case PTR_TO_MEM_OR_NULL:
1171 reg->type = PTR_TO_MEM;
1172 break;
1173 case PTR_TO_RDONLY_BUF_OR_NULL:
1174 reg->type = PTR_TO_RDONLY_BUF;
1175 break;
1176 case PTR_TO_RDWR_BUF_OR_NULL:
1177 reg->type = PTR_TO_RDWR_BUF;
1178 break;
1179 default:
1180 WARN_ONCE(1, "unknown nullable register type");
1181 }
1182 }
1183
1184 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1185 {
1186 return type_is_pkt_pointer(reg->type);
1187 }
1188
1189 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1190 {
1191 return reg_is_pkt_pointer(reg) ||
1192 reg->type == PTR_TO_PACKET_END;
1193 }
1194
1195 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1196 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1197 enum bpf_reg_type which)
1198 {
1199 /* The register can already have a range from prior markings.
1200 * This is fine as long as it hasn't been advanced from its
1201 * origin.
1202 */
1203 return reg->type == which &&
1204 reg->id == 0 &&
1205 reg->off == 0 &&
1206 tnum_equals_const(reg->var_off, 0);
1207 }
1208
1209 /* Reset the min/max bounds of a register */
1210 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1211 {
1212 reg->smin_value = S64_MIN;
1213 reg->smax_value = S64_MAX;
1214 reg->umin_value = 0;
1215 reg->umax_value = U64_MAX;
1216
1217 reg->s32_min_value = S32_MIN;
1218 reg->s32_max_value = S32_MAX;
1219 reg->u32_min_value = 0;
1220 reg->u32_max_value = U32_MAX;
1221 }
1222
1223 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1224 {
1225 reg->smin_value = S64_MIN;
1226 reg->smax_value = S64_MAX;
1227 reg->umin_value = 0;
1228 reg->umax_value = U64_MAX;
1229 }
1230
1231 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1232 {
1233 reg->s32_min_value = S32_MIN;
1234 reg->s32_max_value = S32_MAX;
1235 reg->u32_min_value = 0;
1236 reg->u32_max_value = U32_MAX;
1237 }
1238
1239 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1240 {
1241 struct tnum var32_off = tnum_subreg(reg->var_off);
1242
1243 /* min signed is max(sign bit) | min(other bits) */
1244 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1245 var32_off.value | (var32_off.mask & S32_MIN));
1246 /* max signed is min(sign bit) | max(other bits) */
1247 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1248 var32_off.value | (var32_off.mask & S32_MAX));
1249 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1250 reg->u32_max_value = min(reg->u32_max_value,
1251 (u32)(var32_off.value | var32_off.mask));
1252 }
1253
1254 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1255 {
1256 /* min signed is max(sign bit) | min(other bits) */
1257 reg->smin_value = max_t(s64, reg->smin_value,
1258 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1259 /* max signed is min(sign bit) | max(other bits) */
1260 reg->smax_value = min_t(s64, reg->smax_value,
1261 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1262 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1263 reg->umax_value = min(reg->umax_value,
1264 reg->var_off.value | reg->var_off.mask);
1265 }
1266
1267 static void __update_reg_bounds(struct bpf_reg_state *reg)
1268 {
1269 __update_reg32_bounds(reg);
1270 __update_reg64_bounds(reg);
1271 }
1272
1273 /* Uses signed min/max values to inform unsigned, and vice-versa */
1274 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1275 {
1276 /* Learn sign from signed bounds.
1277 * If we cannot cross the sign boundary, then signed and unsigned bounds
1278 * are the same, so combine. This works even in the negative case, e.g.
1279 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1280 */
1281 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1282 reg->s32_min_value = reg->u32_min_value =
1283 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1284 reg->s32_max_value = reg->u32_max_value =
1285 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1286 return;
1287 }
1288 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1289 * boundary, so we must be careful.
1290 */
1291 if ((s32)reg->u32_max_value >= 0) {
1292 /* Positive. We can't learn anything from the smin, but smax
1293 * is positive, hence safe.
1294 */
1295 reg->s32_min_value = reg->u32_min_value;
1296 reg->s32_max_value = reg->u32_max_value =
1297 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1298 } else if ((s32)reg->u32_min_value < 0) {
1299 /* Negative. We can't learn anything from the smax, but smin
1300 * is negative, hence safe.
1301 */
1302 reg->s32_min_value = reg->u32_min_value =
1303 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1304 reg->s32_max_value = reg->u32_max_value;
1305 }
1306 }
1307
1308 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1309 {
1310 /* Learn sign from signed bounds.
1311 * If we cannot cross the sign boundary, then signed and unsigned bounds
1312 * are the same, so combine. This works even in the negative case, e.g.
1313 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1314 */
1315 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1316 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1317 reg->umin_value);
1318 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1319 reg->umax_value);
1320 return;
1321 }
1322 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1323 * boundary, so we must be careful.
1324 */
1325 if ((s64)reg->umax_value >= 0) {
1326 /* Positive. We can't learn anything from the smin, but smax
1327 * is positive, hence safe.
1328 */
1329 reg->smin_value = reg->umin_value;
1330 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1331 reg->umax_value);
1332 } else if ((s64)reg->umin_value < 0) {
1333 /* Negative. We can't learn anything from the smax, but smin
1334 * is negative, hence safe.
1335 */
1336 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1337 reg->umin_value);
1338 reg->smax_value = reg->umax_value;
1339 }
1340 }
1341
1342 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1343 {
1344 __reg32_deduce_bounds(reg);
1345 __reg64_deduce_bounds(reg);
1346 }
1347
1348 /* Attempts to improve var_off based on unsigned min/max information */
1349 static void __reg_bound_offset(struct bpf_reg_state *reg)
1350 {
1351 struct tnum var64_off = tnum_intersect(reg->var_off,
1352 tnum_range(reg->umin_value,
1353 reg->umax_value));
1354 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1355 tnum_range(reg->u32_min_value,
1356 reg->u32_max_value));
1357
1358 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1359 }
1360
1361 static bool __reg32_bound_s64(s32 a)
1362 {
1363 return a >= 0 && a <= S32_MAX;
1364 }
1365
1366 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1367 {
1368 reg->umin_value = reg->u32_min_value;
1369 reg->umax_value = reg->u32_max_value;
1370
1371 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1372 * be positive otherwise set to worse case bounds and refine later
1373 * from tnum.
1374 */
1375 if (__reg32_bound_s64(reg->s32_min_value) &&
1376 __reg32_bound_s64(reg->s32_max_value)) {
1377 reg->smin_value = reg->s32_min_value;
1378 reg->smax_value = reg->s32_max_value;
1379 } else {
1380 reg->smin_value = 0;
1381 reg->smax_value = U32_MAX;
1382 }
1383 }
1384
1385 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1386 {
1387 /* special case when 64-bit register has upper 32-bit register
1388 * zeroed. Typically happens after zext or <<32, >>32 sequence
1389 * allowing us to use 32-bit bounds directly,
1390 */
1391 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1392 __reg_assign_32_into_64(reg);
1393 } else {
1394 /* Otherwise the best we can do is push lower 32bit known and
1395 * unknown bits into register (var_off set from jmp logic)
1396 * then learn as much as possible from the 64-bit tnum
1397 * known and unknown bits. The previous smin/smax bounds are
1398 * invalid here because of jmp32 compare so mark them unknown
1399 * so they do not impact tnum bounds calculation.
1400 */
1401 __mark_reg64_unbounded(reg);
1402 __update_reg_bounds(reg);
1403 }
1404
1405 /* Intersecting with the old var_off might have improved our bounds
1406 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1407 * then new var_off is (0; 0x7f...fc) which improves our umax.
1408 */
1409 __reg_deduce_bounds(reg);
1410 __reg_bound_offset(reg);
1411 __update_reg_bounds(reg);
1412 }
1413
1414 static bool __reg64_bound_s32(s64 a)
1415 {
1416 return a >= S32_MIN && a <= S32_MAX;
1417 }
1418
1419 static bool __reg64_bound_u32(u64 a)
1420 {
1421 return a >= U32_MIN && a <= U32_MAX;
1422 }
1423
1424 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1425 {
1426 __mark_reg32_unbounded(reg);
1427
1428 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1429 reg->s32_min_value = (s32)reg->smin_value;
1430 reg->s32_max_value = (s32)reg->smax_value;
1431 }
1432 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1433 reg->u32_min_value = (u32)reg->umin_value;
1434 reg->u32_max_value = (u32)reg->umax_value;
1435 }
1436
1437 /* Intersecting with the old var_off might have improved our bounds
1438 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1439 * then new var_off is (0; 0x7f...fc) which improves our umax.
1440 */
1441 __reg_deduce_bounds(reg);
1442 __reg_bound_offset(reg);
1443 __update_reg_bounds(reg);
1444 }
1445
1446 /* Mark a register as having a completely unknown (scalar) value. */
1447 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1448 struct bpf_reg_state *reg)
1449 {
1450 /*
1451 * Clear type, id, off, and union(map_ptr, range) and
1452 * padding between 'type' and union
1453 */
1454 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1455 reg->type = SCALAR_VALUE;
1456 reg->var_off = tnum_unknown;
1457 reg->frameno = 0;
1458 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1459 __mark_reg_unbounded(reg);
1460 }
1461
1462 static void mark_reg_unknown(struct bpf_verifier_env *env,
1463 struct bpf_reg_state *regs, u32 regno)
1464 {
1465 if (WARN_ON(regno >= MAX_BPF_REG)) {
1466 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1467 /* Something bad happened, let's kill all regs except FP */
1468 for (regno = 0; regno < BPF_REG_FP; regno++)
1469 __mark_reg_not_init(env, regs + regno);
1470 return;
1471 }
1472 __mark_reg_unknown(env, regs + regno);
1473 }
1474
1475 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1476 struct bpf_reg_state *reg)
1477 {
1478 __mark_reg_unknown(env, reg);
1479 reg->type = NOT_INIT;
1480 }
1481
1482 static void mark_reg_not_init(struct bpf_verifier_env *env,
1483 struct bpf_reg_state *regs, u32 regno)
1484 {
1485 if (WARN_ON(regno >= MAX_BPF_REG)) {
1486 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1487 /* Something bad happened, let's kill all regs except FP */
1488 for (regno = 0; regno < BPF_REG_FP; regno++)
1489 __mark_reg_not_init(env, regs + regno);
1490 return;
1491 }
1492 __mark_reg_not_init(env, regs + regno);
1493 }
1494
1495 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1496 struct bpf_reg_state *regs, u32 regno,
1497 enum bpf_reg_type reg_type,
1498 struct btf *btf, u32 btf_id)
1499 {
1500 if (reg_type == SCALAR_VALUE) {
1501 mark_reg_unknown(env, regs, regno);
1502 return;
1503 }
1504 mark_reg_known_zero(env, regs, regno);
1505 regs[regno].type = PTR_TO_BTF_ID;
1506 regs[regno].btf = btf;
1507 regs[regno].btf_id = btf_id;
1508 }
1509
1510 #define DEF_NOT_SUBREG (0)
1511 static void init_reg_state(struct bpf_verifier_env *env,
1512 struct bpf_func_state *state)
1513 {
1514 struct bpf_reg_state *regs = state->regs;
1515 int i;
1516
1517 for (i = 0; i < MAX_BPF_REG; i++) {
1518 mark_reg_not_init(env, regs, i);
1519 regs[i].live = REG_LIVE_NONE;
1520 regs[i].parent = NULL;
1521 regs[i].subreg_def = DEF_NOT_SUBREG;
1522 }
1523
1524 /* frame pointer */
1525 regs[BPF_REG_FP].type = PTR_TO_STACK;
1526 mark_reg_known_zero(env, regs, BPF_REG_FP);
1527 regs[BPF_REG_FP].frameno = state->frameno;
1528 }
1529
1530 #define BPF_MAIN_FUNC (-1)
1531 static void init_func_state(struct bpf_verifier_env *env,
1532 struct bpf_func_state *state,
1533 int callsite, int frameno, int subprogno)
1534 {
1535 state->callsite = callsite;
1536 state->frameno = frameno;
1537 state->subprogno = subprogno;
1538 init_reg_state(env, state);
1539 }
1540
1541 /* Similar to push_stack(), but for async callbacks */
1542 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1543 int insn_idx, int prev_insn_idx,
1544 int subprog)
1545 {
1546 struct bpf_verifier_stack_elem *elem;
1547 struct bpf_func_state *frame;
1548
1549 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1550 if (!elem)
1551 goto err;
1552
1553 elem->insn_idx = insn_idx;
1554 elem->prev_insn_idx = prev_insn_idx;
1555 elem->next = env->head;
1556 elem->log_pos = env->log.len_used;
1557 env->head = elem;
1558 env->stack_size++;
1559 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1560 verbose(env,
1561 "The sequence of %d jumps is too complex for async cb.\n",
1562 env->stack_size);
1563 goto err;
1564 }
1565 /* Unlike push_stack() do not copy_verifier_state().
1566 * The caller state doesn't matter.
1567 * This is async callback. It starts in a fresh stack.
1568 * Initialize it similar to do_check_common().
1569 */
1570 elem->st.branches = 1;
1571 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1572 if (!frame)
1573 goto err;
1574 init_func_state(env, frame,
1575 BPF_MAIN_FUNC /* callsite */,
1576 0 /* frameno within this callchain */,
1577 subprog /* subprog number within this prog */);
1578 elem->st.frame[0] = frame;
1579 return &elem->st;
1580 err:
1581 free_verifier_state(env->cur_state, true);
1582 env->cur_state = NULL;
1583 /* pop all elements and return */
1584 while (!pop_stack(env, NULL, NULL, false));
1585 return NULL;
1586 }
1587
1588
1589 enum reg_arg_type {
1590 SRC_OP, /* register is used as source operand */
1591 DST_OP, /* register is used as destination operand */
1592 DST_OP_NO_MARK /* same as above, check only, don't mark */
1593 };
1594
1595 static int cmp_subprogs(const void *a, const void *b)
1596 {
1597 return ((struct bpf_subprog_info *)a)->start -
1598 ((struct bpf_subprog_info *)b)->start;
1599 }
1600
1601 static int find_subprog(struct bpf_verifier_env *env, int off)
1602 {
1603 struct bpf_subprog_info *p;
1604
1605 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1606 sizeof(env->subprog_info[0]), cmp_subprogs);
1607 if (!p)
1608 return -ENOENT;
1609 return p - env->subprog_info;
1610
1611 }
1612
1613 static int add_subprog(struct bpf_verifier_env *env, int off)
1614 {
1615 int insn_cnt = env->prog->len;
1616 int ret;
1617
1618 if (off >= insn_cnt || off < 0) {
1619 verbose(env, "call to invalid destination\n");
1620 return -EINVAL;
1621 }
1622 ret = find_subprog(env, off);
1623 if (ret >= 0)
1624 return ret;
1625 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1626 verbose(env, "too many subprograms\n");
1627 return -E2BIG;
1628 }
1629 /* determine subprog starts. The end is one before the next starts */
1630 env->subprog_info[env->subprog_cnt++].start = off;
1631 sort(env->subprog_info, env->subprog_cnt,
1632 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1633 return env->subprog_cnt - 1;
1634 }
1635
1636 struct bpf_kfunc_desc {
1637 struct btf_func_model func_model;
1638 u32 func_id;
1639 s32 imm;
1640 };
1641
1642 #define MAX_KFUNC_DESCS 256
1643 struct bpf_kfunc_desc_tab {
1644 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1645 u32 nr_descs;
1646 };
1647
1648 static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1649 {
1650 const struct bpf_kfunc_desc *d0 = a;
1651 const struct bpf_kfunc_desc *d1 = b;
1652
1653 /* func_id is not greater than BTF_MAX_TYPE */
1654 return d0->func_id - d1->func_id;
1655 }
1656
1657 static const struct bpf_kfunc_desc *
1658 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1659 {
1660 struct bpf_kfunc_desc desc = {
1661 .func_id = func_id,
1662 };
1663 struct bpf_kfunc_desc_tab *tab;
1664
1665 tab = prog->aux->kfunc_tab;
1666 return bsearch(&desc, tab->descs, tab->nr_descs,
1667 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1668 }
1669
1670 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1671 {
1672 const struct btf_type *func, *func_proto;
1673 struct bpf_kfunc_desc_tab *tab;
1674 struct bpf_prog_aux *prog_aux;
1675 struct bpf_kfunc_desc *desc;
1676 const char *func_name;
1677 unsigned long addr;
1678 int err;
1679
1680 prog_aux = env->prog->aux;
1681 tab = prog_aux->kfunc_tab;
1682 if (!tab) {
1683 if (!btf_vmlinux) {
1684 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1685 return -ENOTSUPP;
1686 }
1687
1688 if (!env->prog->jit_requested) {
1689 verbose(env, "JIT is required for calling kernel function\n");
1690 return -ENOTSUPP;
1691 }
1692
1693 if (!bpf_jit_supports_kfunc_call()) {
1694 verbose(env, "JIT does not support calling kernel function\n");
1695 return -ENOTSUPP;
1696 }
1697
1698 if (!env->prog->gpl_compatible) {
1699 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1700 return -EINVAL;
1701 }
1702
1703 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1704 if (!tab)
1705 return -ENOMEM;
1706 prog_aux->kfunc_tab = tab;
1707 }
1708
1709 if (find_kfunc_desc(env->prog, func_id))
1710 return 0;
1711
1712 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1713 verbose(env, "too many different kernel function calls\n");
1714 return -E2BIG;
1715 }
1716
1717 func = btf_type_by_id(btf_vmlinux, func_id);
1718 if (!func || !btf_type_is_func(func)) {
1719 verbose(env, "kernel btf_id %u is not a function\n",
1720 func_id);
1721 return -EINVAL;
1722 }
1723 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1724 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1725 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1726 func_id);
1727 return -EINVAL;
1728 }
1729
1730 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1731 addr = kallsyms_lookup_name(func_name);
1732 if (!addr) {
1733 verbose(env, "cannot find address for kernel function %s\n",
1734 func_name);
1735 return -EINVAL;
1736 }
1737
1738 desc = &tab->descs[tab->nr_descs++];
1739 desc->func_id = func_id;
1740 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1741 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1742 func_proto, func_name,
1743 &desc->func_model);
1744 if (!err)
1745 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1746 kfunc_desc_cmp_by_id, NULL);
1747 return err;
1748 }
1749
1750 static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1751 {
1752 const struct bpf_kfunc_desc *d0 = a;
1753 const struct bpf_kfunc_desc *d1 = b;
1754
1755 if (d0->imm > d1->imm)
1756 return 1;
1757 else if (d0->imm < d1->imm)
1758 return -1;
1759 return 0;
1760 }
1761
1762 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1763 {
1764 struct bpf_kfunc_desc_tab *tab;
1765
1766 tab = prog->aux->kfunc_tab;
1767 if (!tab)
1768 return;
1769
1770 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1771 kfunc_desc_cmp_by_imm, NULL);
1772 }
1773
1774 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1775 {
1776 return !!prog->aux->kfunc_tab;
1777 }
1778
1779 const struct btf_func_model *
1780 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1781 const struct bpf_insn *insn)
1782 {
1783 const struct bpf_kfunc_desc desc = {
1784 .imm = insn->imm,
1785 };
1786 const struct bpf_kfunc_desc *res;
1787 struct bpf_kfunc_desc_tab *tab;
1788
1789 tab = prog->aux->kfunc_tab;
1790 res = bsearch(&desc, tab->descs, tab->nr_descs,
1791 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1792
1793 return res ? &res->func_model : NULL;
1794 }
1795
1796 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1797 {
1798 struct bpf_subprog_info *subprog = env->subprog_info;
1799 struct bpf_insn *insn = env->prog->insnsi;
1800 int i, ret, insn_cnt = env->prog->len;
1801
1802 /* Add entry function. */
1803 ret = add_subprog(env, 0);
1804 if (ret)
1805 return ret;
1806
1807 for (i = 0; i < insn_cnt; i++, insn++) {
1808 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1809 !bpf_pseudo_kfunc_call(insn))
1810 continue;
1811
1812 if (!env->bpf_capable) {
1813 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1814 return -EPERM;
1815 }
1816
1817 if (bpf_pseudo_func(insn)) {
1818 ret = add_subprog(env, i + insn->imm + 1);
1819 if (ret >= 0)
1820 /* remember subprog */
1821 insn[1].imm = ret;
1822 } else if (bpf_pseudo_call(insn)) {
1823 ret = add_subprog(env, i + insn->imm + 1);
1824 } else {
1825 ret = add_kfunc_call(env, insn->imm);
1826 }
1827
1828 if (ret < 0)
1829 return ret;
1830 }
1831
1832 /* Add a fake 'exit' subprog which could simplify subprog iteration
1833 * logic. 'subprog_cnt' should not be increased.
1834 */
1835 subprog[env->subprog_cnt].start = insn_cnt;
1836
1837 if (env->log.level & BPF_LOG_LEVEL2)
1838 for (i = 0; i < env->subprog_cnt; i++)
1839 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1840
1841 return 0;
1842 }
1843
1844 static int check_subprogs(struct bpf_verifier_env *env)
1845 {
1846 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1847 struct bpf_subprog_info *subprog = env->subprog_info;
1848 struct bpf_insn *insn = env->prog->insnsi;
1849 int insn_cnt = env->prog->len;
1850
1851 /* now check that all jumps are within the same subprog */
1852 subprog_start = subprog[cur_subprog].start;
1853 subprog_end = subprog[cur_subprog + 1].start;
1854 for (i = 0; i < insn_cnt; i++) {
1855 u8 code = insn[i].code;
1856
1857 if (code == (BPF_JMP | BPF_CALL) &&
1858 insn[i].imm == BPF_FUNC_tail_call &&
1859 insn[i].src_reg != BPF_PSEUDO_CALL)
1860 subprog[cur_subprog].has_tail_call = true;
1861 if (BPF_CLASS(code) == BPF_LD &&
1862 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1863 subprog[cur_subprog].has_ld_abs = true;
1864 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1865 goto next;
1866 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1867 goto next;
1868 off = i + insn[i].off + 1;
1869 if (off < subprog_start || off >= subprog_end) {
1870 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1871 return -EINVAL;
1872 }
1873 next:
1874 if (i == subprog_end - 1) {
1875 /* to avoid fall-through from one subprog into another
1876 * the last insn of the subprog should be either exit
1877 * or unconditional jump back
1878 */
1879 if (code != (BPF_JMP | BPF_EXIT) &&
1880 code != (BPF_JMP | BPF_JA)) {
1881 verbose(env, "last insn is not an exit or jmp\n");
1882 return -EINVAL;
1883 }
1884 subprog_start = subprog_end;
1885 cur_subprog++;
1886 if (cur_subprog < env->subprog_cnt)
1887 subprog_end = subprog[cur_subprog + 1].start;
1888 }
1889 }
1890 return 0;
1891 }
1892
1893 /* Parentage chain of this register (or stack slot) should take care of all
1894 * issues like callee-saved registers, stack slot allocation time, etc.
1895 */
1896 static int mark_reg_read(struct bpf_verifier_env *env,
1897 const struct bpf_reg_state *state,
1898 struct bpf_reg_state *parent, u8 flag)
1899 {
1900 bool writes = parent == state->parent; /* Observe write marks */
1901 int cnt = 0;
1902
1903 while (parent) {
1904 /* if read wasn't screened by an earlier write ... */
1905 if (writes && state->live & REG_LIVE_WRITTEN)
1906 break;
1907 if (parent->live & REG_LIVE_DONE) {
1908 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1909 reg_type_str[parent->type],
1910 parent->var_off.value, parent->off);
1911 return -EFAULT;
1912 }
1913 /* The first condition is more likely to be true than the
1914 * second, checked it first.
1915 */
1916 if ((parent->live & REG_LIVE_READ) == flag ||
1917 parent->live & REG_LIVE_READ64)
1918 /* The parentage chain never changes and
1919 * this parent was already marked as LIVE_READ.
1920 * There is no need to keep walking the chain again and
1921 * keep re-marking all parents as LIVE_READ.
1922 * This case happens when the same register is read
1923 * multiple times without writes into it in-between.
1924 * Also, if parent has the stronger REG_LIVE_READ64 set,
1925 * then no need to set the weak REG_LIVE_READ32.
1926 */
1927 break;
1928 /* ... then we depend on parent's value */
1929 parent->live |= flag;
1930 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1931 if (flag == REG_LIVE_READ64)
1932 parent->live &= ~REG_LIVE_READ32;
1933 state = parent;
1934 parent = state->parent;
1935 writes = true;
1936 cnt++;
1937 }
1938
1939 if (env->longest_mark_read_walk < cnt)
1940 env->longest_mark_read_walk = cnt;
1941 return 0;
1942 }
1943
1944 /* This function is supposed to be used by the following 32-bit optimization
1945 * code only. It returns TRUE if the source or destination register operates
1946 * on 64-bit, otherwise return FALSE.
1947 */
1948 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1949 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1950 {
1951 u8 code, class, op;
1952
1953 code = insn->code;
1954 class = BPF_CLASS(code);
1955 op = BPF_OP(code);
1956 if (class == BPF_JMP) {
1957 /* BPF_EXIT for "main" will reach here. Return TRUE
1958 * conservatively.
1959 */
1960 if (op == BPF_EXIT)
1961 return true;
1962 if (op == BPF_CALL) {
1963 /* BPF to BPF call will reach here because of marking
1964 * caller saved clobber with DST_OP_NO_MARK for which we
1965 * don't care the register def because they are anyway
1966 * marked as NOT_INIT already.
1967 */
1968 if (insn->src_reg == BPF_PSEUDO_CALL)
1969 return false;
1970 /* Helper call will reach here because of arg type
1971 * check, conservatively return TRUE.
1972 */
1973 if (t == SRC_OP)
1974 return true;
1975
1976 return false;
1977 }
1978 }
1979
1980 if (class == BPF_ALU64 || class == BPF_JMP ||
1981 /* BPF_END always use BPF_ALU class. */
1982 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1983 return true;
1984
1985 if (class == BPF_ALU || class == BPF_JMP32)
1986 return false;
1987
1988 if (class == BPF_LDX) {
1989 if (t != SRC_OP)
1990 return BPF_SIZE(code) == BPF_DW;
1991 /* LDX source must be ptr. */
1992 return true;
1993 }
1994
1995 if (class == BPF_STX) {
1996 /* BPF_STX (including atomic variants) has multiple source
1997 * operands, one of which is a ptr. Check whether the caller is
1998 * asking about it.
1999 */
2000 if (t == SRC_OP && reg->type != SCALAR_VALUE)
2001 return true;
2002 return BPF_SIZE(code) == BPF_DW;
2003 }
2004
2005 if (class == BPF_LD) {
2006 u8 mode = BPF_MODE(code);
2007
2008 /* LD_IMM64 */
2009 if (mode == BPF_IMM)
2010 return true;
2011
2012 /* Both LD_IND and LD_ABS return 32-bit data. */
2013 if (t != SRC_OP)
2014 return false;
2015
2016 /* Implicit ctx ptr. */
2017 if (regno == BPF_REG_6)
2018 return true;
2019
2020 /* Explicit source could be any width. */
2021 return true;
2022 }
2023
2024 if (class == BPF_ST)
2025 /* The only source register for BPF_ST is a ptr. */
2026 return true;
2027
2028 /* Conservatively return true at default. */
2029 return true;
2030 }
2031
2032 /* Return the regno defined by the insn, or -1. */
2033 static int insn_def_regno(const struct bpf_insn *insn)
2034 {
2035 switch (BPF_CLASS(insn->code)) {
2036 case BPF_JMP:
2037 case BPF_JMP32:
2038 case BPF_ST:
2039 return -1;
2040 case BPF_STX:
2041 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2042 (insn->imm & BPF_FETCH)) {
2043 if (insn->imm == BPF_CMPXCHG)
2044 return BPF_REG_0;
2045 else
2046 return insn->src_reg;
2047 } else {
2048 return -1;
2049 }
2050 default:
2051 return insn->dst_reg;
2052 }
2053 }
2054
2055 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
2056 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2057 {
2058 int dst_reg = insn_def_regno(insn);
2059
2060 if (dst_reg == -1)
2061 return false;
2062
2063 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
2064 }
2065
2066 static void mark_insn_zext(struct bpf_verifier_env *env,
2067 struct bpf_reg_state *reg)
2068 {
2069 s32 def_idx = reg->subreg_def;
2070
2071 if (def_idx == DEF_NOT_SUBREG)
2072 return;
2073
2074 env->insn_aux_data[def_idx - 1].zext_dst = true;
2075 /* The dst will be zero extended, so won't be sub-register anymore. */
2076 reg->subreg_def = DEF_NOT_SUBREG;
2077 }
2078
2079 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
2080 enum reg_arg_type t)
2081 {
2082 struct bpf_verifier_state *vstate = env->cur_state;
2083 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2084 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
2085 struct bpf_reg_state *reg, *regs = state->regs;
2086 bool rw64;
2087
2088 if (regno >= MAX_BPF_REG) {
2089 verbose(env, "R%d is invalid\n", regno);
2090 return -EINVAL;
2091 }
2092
2093 reg = &regs[regno];
2094 rw64 = is_reg64(env, insn, regno, reg, t);
2095 if (t == SRC_OP) {
2096 /* check whether register used as source operand can be read */
2097 if (reg->type == NOT_INIT) {
2098 verbose(env, "R%d !read_ok\n", regno);
2099 return -EACCES;
2100 }
2101 /* We don't need to worry about FP liveness because it's read-only */
2102 if (regno == BPF_REG_FP)
2103 return 0;
2104
2105 if (rw64)
2106 mark_insn_zext(env, reg);
2107
2108 return mark_reg_read(env, reg, reg->parent,
2109 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
2110 } else {
2111 /* check whether register used as dest operand can be written to */
2112 if (regno == BPF_REG_FP) {
2113 verbose(env, "frame pointer is read only\n");
2114 return -EACCES;
2115 }
2116 reg->live |= REG_LIVE_WRITTEN;
2117 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
2118 if (t == DST_OP)
2119 mark_reg_unknown(env, regs, regno);
2120 }
2121 return 0;
2122 }
2123
2124 /* for any branch, call, exit record the history of jmps in the given state */
2125 static int push_jmp_history(struct bpf_verifier_env *env,
2126 struct bpf_verifier_state *cur)
2127 {
2128 u32 cnt = cur->jmp_history_cnt;
2129 struct bpf_idx_pair *p;
2130
2131 cnt++;
2132 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2133 if (!p)
2134 return -ENOMEM;
2135 p[cnt - 1].idx = env->insn_idx;
2136 p[cnt - 1].prev_idx = env->prev_insn_idx;
2137 cur->jmp_history = p;
2138 cur->jmp_history_cnt = cnt;
2139 return 0;
2140 }
2141
2142 /* Backtrack one insn at a time. If idx is not at the top of recorded
2143 * history then previous instruction came from straight line execution.
2144 */
2145 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2146 u32 *history)
2147 {
2148 u32 cnt = *history;
2149
2150 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2151 i = st->jmp_history[cnt - 1].prev_idx;
2152 (*history)--;
2153 } else {
2154 i--;
2155 }
2156 return i;
2157 }
2158
2159 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2160 {
2161 const struct btf_type *func;
2162
2163 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2164 return NULL;
2165
2166 func = btf_type_by_id(btf_vmlinux, insn->imm);
2167 return btf_name_by_offset(btf_vmlinux, func->name_off);
2168 }
2169
2170 /* For given verifier state backtrack_insn() is called from the last insn to
2171 * the first insn. Its purpose is to compute a bitmask of registers and
2172 * stack slots that needs precision in the parent verifier state.
2173 */
2174 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2175 u32 *reg_mask, u64 *stack_mask)
2176 {
2177 const struct bpf_insn_cbs cbs = {
2178 .cb_call = disasm_kfunc_name,
2179 .cb_print = verbose,
2180 .private_data = env,
2181 };
2182 struct bpf_insn *insn = env->prog->insnsi + idx;
2183 u8 class = BPF_CLASS(insn->code);
2184 u8 opcode = BPF_OP(insn->code);
2185 u8 mode = BPF_MODE(insn->code);
2186 u32 dreg = 1u << insn->dst_reg;
2187 u32 sreg = 1u << insn->src_reg;
2188 u32 spi;
2189
2190 if (insn->code == 0)
2191 return 0;
2192 if (env->log.level & BPF_LOG_LEVEL) {
2193 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2194 verbose(env, "%d: ", idx);
2195 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2196 }
2197
2198 if (class == BPF_ALU || class == BPF_ALU64) {
2199 if (!(*reg_mask & dreg))
2200 return 0;
2201 if (opcode == BPF_MOV) {
2202 if (BPF_SRC(insn->code) == BPF_X) {
2203 /* dreg = sreg
2204 * dreg needs precision after this insn
2205 * sreg needs precision before this insn
2206 */
2207 *reg_mask &= ~dreg;
2208 *reg_mask |= sreg;
2209 } else {
2210 /* dreg = K
2211 * dreg needs precision after this insn.
2212 * Corresponding register is already marked
2213 * as precise=true in this verifier state.
2214 * No further markings in parent are necessary
2215 */
2216 *reg_mask &= ~dreg;
2217 }
2218 } else {
2219 if (BPF_SRC(insn->code) == BPF_X) {
2220 /* dreg += sreg
2221 * both dreg and sreg need precision
2222 * before this insn
2223 */
2224 *reg_mask |= sreg;
2225 } /* else dreg += K
2226 * dreg still needs precision before this insn
2227 */
2228 }
2229 } else if (class == BPF_LDX) {
2230 if (!(*reg_mask & dreg))
2231 return 0;
2232 *reg_mask &= ~dreg;
2233
2234 /* scalars can only be spilled into stack w/o losing precision.
2235 * Load from any other memory can be zero extended.
2236 * The desire to keep that precision is already indicated
2237 * by 'precise' mark in corresponding register of this state.
2238 * No further tracking necessary.
2239 */
2240 if (insn->src_reg != BPF_REG_FP)
2241 return 0;
2242 if (BPF_SIZE(insn->code) != BPF_DW)
2243 return 0;
2244
2245 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2246 * that [fp - off] slot contains scalar that needs to be
2247 * tracked with precision
2248 */
2249 spi = (-insn->off - 1) / BPF_REG_SIZE;
2250 if (spi >= 64) {
2251 verbose(env, "BUG spi %d\n", spi);
2252 WARN_ONCE(1, "verifier backtracking bug");
2253 return -EFAULT;
2254 }
2255 *stack_mask |= 1ull << spi;
2256 } else if (class == BPF_STX || class == BPF_ST) {
2257 if (*reg_mask & dreg)
2258 /* stx & st shouldn't be using _scalar_ dst_reg
2259 * to access memory. It means backtracking
2260 * encountered a case of pointer subtraction.
2261 */
2262 return -ENOTSUPP;
2263 /* scalars can only be spilled into stack */
2264 if (insn->dst_reg != BPF_REG_FP)
2265 return 0;
2266 if (BPF_SIZE(insn->code) != BPF_DW)
2267 return 0;
2268 spi = (-insn->off - 1) / BPF_REG_SIZE;
2269 if (spi >= 64) {
2270 verbose(env, "BUG spi %d\n", spi);
2271 WARN_ONCE(1, "verifier backtracking bug");
2272 return -EFAULT;
2273 }
2274 if (!(*stack_mask & (1ull << spi)))
2275 return 0;
2276 *stack_mask &= ~(1ull << spi);
2277 if (class == BPF_STX)
2278 *reg_mask |= sreg;
2279 } else if (class == BPF_JMP || class == BPF_JMP32) {
2280 if (opcode == BPF_CALL) {
2281 if (insn->src_reg == BPF_PSEUDO_CALL)
2282 return -ENOTSUPP;
2283 /* regular helper call sets R0 */
2284 *reg_mask &= ~1;
2285 if (*reg_mask & 0x3f) {
2286 /* if backtracing was looking for registers R1-R5
2287 * they should have been found already.
2288 */
2289 verbose(env, "BUG regs %x\n", *reg_mask);
2290 WARN_ONCE(1, "verifier backtracking bug");
2291 return -EFAULT;
2292 }
2293 } else if (opcode == BPF_EXIT) {
2294 return -ENOTSUPP;
2295 }
2296 } else if (class == BPF_LD) {
2297 if (!(*reg_mask & dreg))
2298 return 0;
2299 *reg_mask &= ~dreg;
2300 /* It's ld_imm64 or ld_abs or ld_ind.
2301 * For ld_imm64 no further tracking of precision
2302 * into parent is necessary
2303 */
2304 if (mode == BPF_IND || mode == BPF_ABS)
2305 /* to be analyzed */
2306 return -ENOTSUPP;
2307 }
2308 return 0;
2309 }
2310
2311 /* the scalar precision tracking algorithm:
2312 * . at the start all registers have precise=false.
2313 * . scalar ranges are tracked as normal through alu and jmp insns.
2314 * . once precise value of the scalar register is used in:
2315 * . ptr + scalar alu
2316 * . if (scalar cond K|scalar)
2317 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2318 * backtrack through the verifier states and mark all registers and
2319 * stack slots with spilled constants that these scalar regisers
2320 * should be precise.
2321 * . during state pruning two registers (or spilled stack slots)
2322 * are equivalent if both are not precise.
2323 *
2324 * Note the verifier cannot simply walk register parentage chain,
2325 * since many different registers and stack slots could have been
2326 * used to compute single precise scalar.
2327 *
2328 * The approach of starting with precise=true for all registers and then
2329 * backtrack to mark a register as not precise when the verifier detects
2330 * that program doesn't care about specific value (e.g., when helper
2331 * takes register as ARG_ANYTHING parameter) is not safe.
2332 *
2333 * It's ok to walk single parentage chain of the verifier states.
2334 * It's possible that this backtracking will go all the way till 1st insn.
2335 * All other branches will be explored for needing precision later.
2336 *
2337 * The backtracking needs to deal with cases like:
2338 * 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)
2339 * r9 -= r8
2340 * r5 = r9
2341 * if r5 > 0x79f goto pc+7
2342 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2343 * r5 += 1
2344 * ...
2345 * call bpf_perf_event_output#25
2346 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2347 *
2348 * and this case:
2349 * r6 = 1
2350 * call foo // uses callee's r6 inside to compute r0
2351 * r0 += r6
2352 * if r0 == 0 goto
2353 *
2354 * to track above reg_mask/stack_mask needs to be independent for each frame.
2355 *
2356 * Also if parent's curframe > frame where backtracking started,
2357 * the verifier need to mark registers in both frames, otherwise callees
2358 * may incorrectly prune callers. This is similar to
2359 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2360 *
2361 * For now backtracking falls back into conservative marking.
2362 */
2363 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2364 struct bpf_verifier_state *st)
2365 {
2366 struct bpf_func_state *func;
2367 struct bpf_reg_state *reg;
2368 int i, j;
2369
2370 /* big hammer: mark all scalars precise in this path.
2371 * pop_stack may still get !precise scalars.
2372 */
2373 for (; st; st = st->parent)
2374 for (i = 0; i <= st->curframe; i++) {
2375 func = st->frame[i];
2376 for (j = 0; j < BPF_REG_FP; j++) {
2377 reg = &func->regs[j];
2378 if (reg->type != SCALAR_VALUE)
2379 continue;
2380 reg->precise = true;
2381 }
2382 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2383 if (func->stack[j].slot_type[0] != STACK_SPILL)
2384 continue;
2385 reg = &func->stack[j].spilled_ptr;
2386 if (reg->type != SCALAR_VALUE)
2387 continue;
2388 reg->precise = true;
2389 }
2390 }
2391 }
2392
2393 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2394 int spi)
2395 {
2396 struct bpf_verifier_state *st = env->cur_state;
2397 int first_idx = st->first_insn_idx;
2398 int last_idx = env->insn_idx;
2399 struct bpf_func_state *func;
2400 struct bpf_reg_state *reg;
2401 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2402 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2403 bool skip_first = true;
2404 bool new_marks = false;
2405 int i, err;
2406
2407 if (!env->bpf_capable)
2408 return 0;
2409
2410 func = st->frame[st->curframe];
2411 if (regno >= 0) {
2412 reg = &func->regs[regno];
2413 if (reg->type != SCALAR_VALUE) {
2414 WARN_ONCE(1, "backtracing misuse");
2415 return -EFAULT;
2416 }
2417 if (!reg->precise)
2418 new_marks = true;
2419 else
2420 reg_mask = 0;
2421 reg->precise = true;
2422 }
2423
2424 while (spi >= 0) {
2425 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2426 stack_mask = 0;
2427 break;
2428 }
2429 reg = &func->stack[spi].spilled_ptr;
2430 if (reg->type != SCALAR_VALUE) {
2431 stack_mask = 0;
2432 break;
2433 }
2434 if (!reg->precise)
2435 new_marks = true;
2436 else
2437 stack_mask = 0;
2438 reg->precise = true;
2439 break;
2440 }
2441
2442 if (!new_marks)
2443 return 0;
2444 if (!reg_mask && !stack_mask)
2445 return 0;
2446 for (;;) {
2447 DECLARE_BITMAP(mask, 64);
2448 u32 history = st->jmp_history_cnt;
2449
2450 if (env->log.level & BPF_LOG_LEVEL)
2451 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2452 for (i = last_idx;;) {
2453 if (skip_first) {
2454 err = 0;
2455 skip_first = false;
2456 } else {
2457 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2458 }
2459 if (err == -ENOTSUPP) {
2460 mark_all_scalars_precise(env, st);
2461 return 0;
2462 } else if (err) {
2463 return err;
2464 }
2465 if (!reg_mask && !stack_mask)
2466 /* Found assignment(s) into tracked register in this state.
2467 * Since this state is already marked, just return.
2468 * Nothing to be tracked further in the parent state.
2469 */
2470 return 0;
2471 if (i == first_idx)
2472 break;
2473 i = get_prev_insn_idx(st, i, &history);
2474 if (i >= env->prog->len) {
2475 /* This can happen if backtracking reached insn 0
2476 * and there are still reg_mask or stack_mask
2477 * to backtrack.
2478 * It means the backtracking missed the spot where
2479 * particular register was initialized with a constant.
2480 */
2481 verbose(env, "BUG backtracking idx %d\n", i);
2482 WARN_ONCE(1, "verifier backtracking bug");
2483 return -EFAULT;
2484 }
2485 }
2486 st = st->parent;
2487 if (!st)
2488 break;
2489
2490 new_marks = false;
2491 func = st->frame[st->curframe];
2492 bitmap_from_u64(mask, reg_mask);
2493 for_each_set_bit(i, mask, 32) {
2494 reg = &func->regs[i];
2495 if (reg->type != SCALAR_VALUE) {
2496 reg_mask &= ~(1u << i);
2497 continue;
2498 }
2499 if (!reg->precise)
2500 new_marks = true;
2501 reg->precise = true;
2502 }
2503
2504 bitmap_from_u64(mask, stack_mask);
2505 for_each_set_bit(i, mask, 64) {
2506 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2507 /* the sequence of instructions:
2508 * 2: (bf) r3 = r10
2509 * 3: (7b) *(u64 *)(r3 -8) = r0
2510 * 4: (79) r4 = *(u64 *)(r10 -8)
2511 * doesn't contain jmps. It's backtracked
2512 * as a single block.
2513 * During backtracking insn 3 is not recognized as
2514 * stack access, so at the end of backtracking
2515 * stack slot fp-8 is still marked in stack_mask.
2516 * However the parent state may not have accessed
2517 * fp-8 and it's "unallocated" stack space.
2518 * In such case fallback to conservative.
2519 */
2520 mark_all_scalars_precise(env, st);
2521 return 0;
2522 }
2523
2524 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2525 stack_mask &= ~(1ull << i);
2526 continue;
2527 }
2528 reg = &func->stack[i].spilled_ptr;
2529 if (reg->type != SCALAR_VALUE) {
2530 stack_mask &= ~(1ull << i);
2531 continue;
2532 }
2533 if (!reg->precise)
2534 new_marks = true;
2535 reg->precise = true;
2536 }
2537 if (env->log.level & BPF_LOG_LEVEL) {
2538 print_verifier_state(env, func);
2539 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2540 new_marks ? "didn't have" : "already had",
2541 reg_mask, stack_mask);
2542 }
2543
2544 if (!reg_mask && !stack_mask)
2545 break;
2546 if (!new_marks)
2547 break;
2548
2549 last_idx = st->last_insn_idx;
2550 first_idx = st->first_insn_idx;
2551 }
2552 return 0;
2553 }
2554
2555 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2556 {
2557 return __mark_chain_precision(env, regno, -1);
2558 }
2559
2560 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2561 {
2562 return __mark_chain_precision(env, -1, spi);
2563 }
2564
2565 static bool is_spillable_regtype(enum bpf_reg_type type)
2566 {
2567 switch (type) {
2568 case PTR_TO_MAP_VALUE:
2569 case PTR_TO_MAP_VALUE_OR_NULL:
2570 case PTR_TO_STACK:
2571 case PTR_TO_CTX:
2572 case PTR_TO_PACKET:
2573 case PTR_TO_PACKET_META:
2574 case PTR_TO_PACKET_END:
2575 case PTR_TO_FLOW_KEYS:
2576 case CONST_PTR_TO_MAP:
2577 case PTR_TO_SOCKET:
2578 case PTR_TO_SOCKET_OR_NULL:
2579 case PTR_TO_SOCK_COMMON:
2580 case PTR_TO_SOCK_COMMON_OR_NULL:
2581 case PTR_TO_TCP_SOCK:
2582 case PTR_TO_TCP_SOCK_OR_NULL:
2583 case PTR_TO_XDP_SOCK:
2584 case PTR_TO_BTF_ID:
2585 case PTR_TO_BTF_ID_OR_NULL:
2586 case PTR_TO_RDONLY_BUF:
2587 case PTR_TO_RDONLY_BUF_OR_NULL:
2588 case PTR_TO_RDWR_BUF:
2589 case PTR_TO_RDWR_BUF_OR_NULL:
2590 case PTR_TO_PERCPU_BTF_ID:
2591 case PTR_TO_MEM:
2592 case PTR_TO_MEM_OR_NULL:
2593 case PTR_TO_FUNC:
2594 case PTR_TO_MAP_KEY:
2595 return true;
2596 default:
2597 return false;
2598 }
2599 }
2600
2601 /* Does this register contain a constant zero? */
2602 static bool register_is_null(struct bpf_reg_state *reg)
2603 {
2604 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2605 }
2606
2607 static bool register_is_const(struct bpf_reg_state *reg)
2608 {
2609 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2610 }
2611
2612 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2613 {
2614 return tnum_is_unknown(reg->var_off) &&
2615 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2616 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2617 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2618 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2619 }
2620
2621 static bool register_is_bounded(struct bpf_reg_state *reg)
2622 {
2623 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2624 }
2625
2626 static bool __is_pointer_value(bool allow_ptr_leaks,
2627 const struct bpf_reg_state *reg)
2628 {
2629 if (allow_ptr_leaks)
2630 return false;
2631
2632 return reg->type != SCALAR_VALUE;
2633 }
2634
2635 static void save_register_state(struct bpf_func_state *state,
2636 int spi, struct bpf_reg_state *reg)
2637 {
2638 int i;
2639
2640 state->stack[spi].spilled_ptr = *reg;
2641 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2642
2643 for (i = 0; i < BPF_REG_SIZE; i++)
2644 state->stack[spi].slot_type[i] = STACK_SPILL;
2645 }
2646
2647 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2648 * stack boundary and alignment are checked in check_mem_access()
2649 */
2650 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2651 /* stack frame we're writing to */
2652 struct bpf_func_state *state,
2653 int off, int size, int value_regno,
2654 int insn_idx)
2655 {
2656 struct bpf_func_state *cur; /* state of the current function */
2657 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2658 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2659 struct bpf_reg_state *reg = NULL;
2660
2661 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
2662 if (err)
2663 return err;
2664 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2665 * so it's aligned access and [off, off + size) are within stack limits
2666 */
2667 if (!env->allow_ptr_leaks &&
2668 state->stack[spi].slot_type[0] == STACK_SPILL &&
2669 size != BPF_REG_SIZE) {
2670 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2671 return -EACCES;
2672 }
2673
2674 cur = env->cur_state->frame[env->cur_state->curframe];
2675 if (value_regno >= 0)
2676 reg = &cur->regs[value_regno];
2677 if (!env->bypass_spec_v4) {
2678 bool sanitize = reg && is_spillable_regtype(reg->type);
2679
2680 for (i = 0; i < size; i++) {
2681 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2682 sanitize = true;
2683 break;
2684 }
2685 }
2686
2687 if (sanitize)
2688 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2689 }
2690
2691 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2692 !register_is_null(reg) && env->bpf_capable) {
2693 if (dst_reg != BPF_REG_FP) {
2694 /* The backtracking logic can only recognize explicit
2695 * stack slot address like [fp - 8]. Other spill of
2696 * scalar via different register has to be conservative.
2697 * Backtrack from here and mark all registers as precise
2698 * that contributed into 'reg' being a constant.
2699 */
2700 err = mark_chain_precision(env, value_regno);
2701 if (err)
2702 return err;
2703 }
2704 save_register_state(state, spi, reg);
2705 } else if (reg && is_spillable_regtype(reg->type)) {
2706 /* register containing pointer is being spilled into stack */
2707 if (size != BPF_REG_SIZE) {
2708 verbose_linfo(env, insn_idx, "; ");
2709 verbose(env, "invalid size of register spill\n");
2710 return -EACCES;
2711 }
2712 if (state != cur && reg->type == PTR_TO_STACK) {
2713 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2714 return -EINVAL;
2715 }
2716 save_register_state(state, spi, reg);
2717 } else {
2718 u8 type = STACK_MISC;
2719
2720 /* regular write of data into stack destroys any spilled ptr */
2721 state->stack[spi].spilled_ptr.type = NOT_INIT;
2722 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2723 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2724 for (i = 0; i < BPF_REG_SIZE; i++)
2725 state->stack[spi].slot_type[i] = STACK_MISC;
2726
2727 /* only mark the slot as written if all 8 bytes were written
2728 * otherwise read propagation may incorrectly stop too soon
2729 * when stack slots are partially written.
2730 * This heuristic means that read propagation will be
2731 * conservative, since it will add reg_live_read marks
2732 * to stack slots all the way to first state when programs
2733 * writes+reads less than 8 bytes
2734 */
2735 if (size == BPF_REG_SIZE)
2736 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2737
2738 /* when we zero initialize stack slots mark them as such */
2739 if (reg && register_is_null(reg)) {
2740 /* backtracking doesn't work for STACK_ZERO yet. */
2741 err = mark_chain_precision(env, value_regno);
2742 if (err)
2743 return err;
2744 type = STACK_ZERO;
2745 }
2746
2747 /* Mark slots affected by this stack write. */
2748 for (i = 0; i < size; i++)
2749 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2750 type;
2751 }
2752 return 0;
2753 }
2754
2755 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2756 * known to contain a variable offset.
2757 * This function checks whether the write is permitted and conservatively
2758 * tracks the effects of the write, considering that each stack slot in the
2759 * dynamic range is potentially written to.
2760 *
2761 * 'off' includes 'regno->off'.
2762 * 'value_regno' can be -1, meaning that an unknown value is being written to
2763 * the stack.
2764 *
2765 * Spilled pointers in range are not marked as written because we don't know
2766 * what's going to be actually written. This means that read propagation for
2767 * future reads cannot be terminated by this write.
2768 *
2769 * For privileged programs, uninitialized stack slots are considered
2770 * initialized by this write (even though we don't know exactly what offsets
2771 * are going to be written to). The idea is that we don't want the verifier to
2772 * reject future reads that access slots written to through variable offsets.
2773 */
2774 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2775 /* func where register points to */
2776 struct bpf_func_state *state,
2777 int ptr_regno, int off, int size,
2778 int value_regno, int insn_idx)
2779 {
2780 struct bpf_func_state *cur; /* state of the current function */
2781 int min_off, max_off;
2782 int i, err;
2783 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2784 bool writing_zero = false;
2785 /* set if the fact that we're writing a zero is used to let any
2786 * stack slots remain STACK_ZERO
2787 */
2788 bool zero_used = false;
2789
2790 cur = env->cur_state->frame[env->cur_state->curframe];
2791 ptr_reg = &cur->regs[ptr_regno];
2792 min_off = ptr_reg->smin_value + off;
2793 max_off = ptr_reg->smax_value + off + size;
2794 if (value_regno >= 0)
2795 value_reg = &cur->regs[value_regno];
2796 if (value_reg && register_is_null(value_reg))
2797 writing_zero = true;
2798
2799 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
2800 if (err)
2801 return err;
2802
2803
2804 /* Variable offset writes destroy any spilled pointers in range. */
2805 for (i = min_off; i < max_off; i++) {
2806 u8 new_type, *stype;
2807 int slot, spi;
2808
2809 slot = -i - 1;
2810 spi = slot / BPF_REG_SIZE;
2811 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2812
2813 if (!env->allow_ptr_leaks
2814 && *stype != NOT_INIT
2815 && *stype != SCALAR_VALUE) {
2816 /* Reject the write if there's are spilled pointers in
2817 * range. If we didn't reject here, the ptr status
2818 * would be erased below (even though not all slots are
2819 * actually overwritten), possibly opening the door to
2820 * leaks.
2821 */
2822 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2823 insn_idx, i);
2824 return -EINVAL;
2825 }
2826
2827 /* Erase all spilled pointers. */
2828 state->stack[spi].spilled_ptr.type = NOT_INIT;
2829
2830 /* Update the slot type. */
2831 new_type = STACK_MISC;
2832 if (writing_zero && *stype == STACK_ZERO) {
2833 new_type = STACK_ZERO;
2834 zero_used = true;
2835 }
2836 /* If the slot is STACK_INVALID, we check whether it's OK to
2837 * pretend that it will be initialized by this write. The slot
2838 * might not actually be written to, and so if we mark it as
2839 * initialized future reads might leak uninitialized memory.
2840 * For privileged programs, we will accept such reads to slots
2841 * that may or may not be written because, if we're reject
2842 * them, the error would be too confusing.
2843 */
2844 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2845 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2846 insn_idx, i);
2847 return -EINVAL;
2848 }
2849 *stype = new_type;
2850 }
2851 if (zero_used) {
2852 /* backtracking doesn't work for STACK_ZERO yet. */
2853 err = mark_chain_precision(env, value_regno);
2854 if (err)
2855 return err;
2856 }
2857 return 0;
2858 }
2859
2860 /* When register 'dst_regno' is assigned some values from stack[min_off,
2861 * max_off), we set the register's type according to the types of the
2862 * respective stack slots. If all the stack values are known to be zeros, then
2863 * so is the destination reg. Otherwise, the register is considered to be
2864 * SCALAR. This function does not deal with register filling; the caller must
2865 * ensure that all spilled registers in the stack range have been marked as
2866 * read.
2867 */
2868 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2869 /* func where src register points to */
2870 struct bpf_func_state *ptr_state,
2871 int min_off, int max_off, int dst_regno)
2872 {
2873 struct bpf_verifier_state *vstate = env->cur_state;
2874 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2875 int i, slot, spi;
2876 u8 *stype;
2877 int zeros = 0;
2878
2879 for (i = min_off; i < max_off; i++) {
2880 slot = -i - 1;
2881 spi = slot / BPF_REG_SIZE;
2882 stype = ptr_state->stack[spi].slot_type;
2883 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2884 break;
2885 zeros++;
2886 }
2887 if (zeros == max_off - min_off) {
2888 /* any access_size read into register is zero extended,
2889 * so the whole register == const_zero
2890 */
2891 __mark_reg_const_zero(&state->regs[dst_regno]);
2892 /* backtracking doesn't support STACK_ZERO yet,
2893 * so mark it precise here, so that later
2894 * backtracking can stop here.
2895 * Backtracking may not need this if this register
2896 * doesn't participate in pointer adjustment.
2897 * Forward propagation of precise flag is not
2898 * necessary either. This mark is only to stop
2899 * backtracking. Any register that contributed
2900 * to const 0 was marked precise before spill.
2901 */
2902 state->regs[dst_regno].precise = true;
2903 } else {
2904 /* have read misc data from the stack */
2905 mark_reg_unknown(env, state->regs, dst_regno);
2906 }
2907 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2908 }
2909
2910 /* Read the stack at 'off' and put the results into the register indicated by
2911 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2912 * spilled reg.
2913 *
2914 * 'dst_regno' can be -1, meaning that the read value is not going to a
2915 * register.
2916 *
2917 * The access is assumed to be within the current stack bounds.
2918 */
2919 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2920 /* func where src register points to */
2921 struct bpf_func_state *reg_state,
2922 int off, int size, int dst_regno)
2923 {
2924 struct bpf_verifier_state *vstate = env->cur_state;
2925 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2926 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2927 struct bpf_reg_state *reg;
2928 u8 *stype;
2929
2930 stype = reg_state->stack[spi].slot_type;
2931 reg = &reg_state->stack[spi].spilled_ptr;
2932
2933 if (stype[0] == STACK_SPILL) {
2934 if (size != BPF_REG_SIZE) {
2935 if (reg->type != SCALAR_VALUE) {
2936 verbose_linfo(env, env->insn_idx, "; ");
2937 verbose(env, "invalid size of register fill\n");
2938 return -EACCES;
2939 }
2940 if (dst_regno >= 0) {
2941 mark_reg_unknown(env, state->regs, dst_regno);
2942 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2943 }
2944 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2945 return 0;
2946 }
2947 for (i = 1; i < BPF_REG_SIZE; i++) {
2948 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2949 verbose(env, "corrupted spill memory\n");
2950 return -EACCES;
2951 }
2952 }
2953
2954 if (dst_regno >= 0) {
2955 /* restore register state from stack */
2956 state->regs[dst_regno] = *reg;
2957 /* mark reg as written since spilled pointer state likely
2958 * has its liveness marks cleared by is_state_visited()
2959 * which resets stack/reg liveness for state transitions
2960 */
2961 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2962 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2963 /* If dst_regno==-1, the caller is asking us whether
2964 * it is acceptable to use this value as a SCALAR_VALUE
2965 * (e.g. for XADD).
2966 * We must not allow unprivileged callers to do that
2967 * with spilled pointers.
2968 */
2969 verbose(env, "leaking pointer from stack off %d\n",
2970 off);
2971 return -EACCES;
2972 }
2973 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2974 } else {
2975 u8 type;
2976
2977 for (i = 0; i < size; i++) {
2978 type = stype[(slot - i) % BPF_REG_SIZE];
2979 if (type == STACK_MISC)
2980 continue;
2981 if (type == STACK_ZERO)
2982 continue;
2983 verbose(env, "invalid read from stack off %d+%d size %d\n",
2984 off, i, size);
2985 return -EACCES;
2986 }
2987 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2988 if (dst_regno >= 0)
2989 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2990 }
2991 return 0;
2992 }
2993
2994 enum stack_access_src {
2995 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2996 ACCESS_HELPER = 2, /* the access is performed by a helper */
2997 };
2998
2999 static int check_stack_range_initialized(struct bpf_verifier_env *env,
3000 int regno, int off, int access_size,
3001 bool zero_size_allowed,
3002 enum stack_access_src type,
3003 struct bpf_call_arg_meta *meta);
3004
3005 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
3006 {
3007 return cur_regs(env) + regno;
3008 }
3009
3010 /* Read the stack at 'ptr_regno + off' and put the result into the register
3011 * 'dst_regno'.
3012 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3013 * but not its variable offset.
3014 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3015 *
3016 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3017 * filling registers (i.e. reads of spilled register cannot be detected when
3018 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3019 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3020 * offset; for a fixed offset check_stack_read_fixed_off should be used
3021 * instead.
3022 */
3023 static int check_stack_read_var_off(struct bpf_verifier_env *env,
3024 int ptr_regno, int off, int size, int dst_regno)
3025 {
3026 /* The state of the source register. */
3027 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3028 struct bpf_func_state *ptr_state = func(env, reg);
3029 int err;
3030 int min_off, max_off;
3031
3032 /* Note that we pass a NULL meta, so raw access will not be permitted.
3033 */
3034 err = check_stack_range_initialized(env, ptr_regno, off, size,
3035 false, ACCESS_DIRECT, NULL);
3036 if (err)
3037 return err;
3038
3039 min_off = reg->smin_value + off;
3040 max_off = reg->smax_value + off;
3041 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3042 return 0;
3043 }
3044
3045 /* check_stack_read dispatches to check_stack_read_fixed_off or
3046 * check_stack_read_var_off.
3047 *
3048 * The caller must ensure that the offset falls within the allocated stack
3049 * bounds.
3050 *
3051 * 'dst_regno' is a register which will receive the value from the stack. It
3052 * can be -1, meaning that the read value is not going to a register.
3053 */
3054 static int check_stack_read(struct bpf_verifier_env *env,
3055 int ptr_regno, int off, int size,
3056 int dst_regno)
3057 {
3058 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3059 struct bpf_func_state *state = func(env, reg);
3060 int err;
3061 /* Some accesses are only permitted with a static offset. */
3062 bool var_off = !tnum_is_const(reg->var_off);
3063
3064 /* The offset is required to be static when reads don't go to a
3065 * register, in order to not leak pointers (see
3066 * check_stack_read_fixed_off).
3067 */
3068 if (dst_regno < 0 && var_off) {
3069 char tn_buf[48];
3070
3071 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3072 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
3073 tn_buf, off, size);
3074 return -EACCES;
3075 }
3076 /* Variable offset is prohibited for unprivileged mode for simplicity
3077 * since it requires corresponding support in Spectre masking for stack
3078 * ALU. See also retrieve_ptr_limit().
3079 */
3080 if (!env->bypass_spec_v1 && var_off) {
3081 char tn_buf[48];
3082
3083 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3084 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3085 ptr_regno, tn_buf);
3086 return -EACCES;
3087 }
3088
3089 if (!var_off) {
3090 off += reg->var_off.value;
3091 err = check_stack_read_fixed_off(env, state, off, size,
3092 dst_regno);
3093 } else {
3094 /* Variable offset stack reads need more conservative handling
3095 * than fixed offset ones. Note that dst_regno >= 0 on this
3096 * branch.
3097 */
3098 err = check_stack_read_var_off(env, ptr_regno, off, size,
3099 dst_regno);
3100 }
3101 return err;
3102 }
3103
3104
3105 /* check_stack_write dispatches to check_stack_write_fixed_off or
3106 * check_stack_write_var_off.
3107 *
3108 * 'ptr_regno' is the register used as a pointer into the stack.
3109 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3110 * 'value_regno' is the register whose value we're writing to the stack. It can
3111 * be -1, meaning that we're not writing from a register.
3112 *
3113 * The caller must ensure that the offset falls within the maximum stack size.
3114 */
3115 static int check_stack_write(struct bpf_verifier_env *env,
3116 int ptr_regno, int off, int size,
3117 int value_regno, int insn_idx)
3118 {
3119 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3120 struct bpf_func_state *state = func(env, reg);
3121 int err;
3122
3123 if (tnum_is_const(reg->var_off)) {
3124 off += reg->var_off.value;
3125 err = check_stack_write_fixed_off(env, state, off, size,
3126 value_regno, insn_idx);
3127 } else {
3128 /* Variable offset stack reads need more conservative handling
3129 * than fixed offset ones.
3130 */
3131 err = check_stack_write_var_off(env, state,
3132 ptr_regno, off, size,
3133 value_regno, insn_idx);
3134 }
3135 return err;
3136 }
3137
3138 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3139 int off, int size, enum bpf_access_type type)
3140 {
3141 struct bpf_reg_state *regs = cur_regs(env);
3142 struct bpf_map *map = regs[regno].map_ptr;
3143 u32 cap = bpf_map_flags_to_cap(map);
3144
3145 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3146 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3147 map->value_size, off, size);
3148 return -EACCES;
3149 }
3150
3151 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3152 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3153 map->value_size, off, size);
3154 return -EACCES;
3155 }
3156
3157 return 0;
3158 }
3159
3160 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3161 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3162 int off, int size, u32 mem_size,
3163 bool zero_size_allowed)
3164 {
3165 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3166 struct bpf_reg_state *reg;
3167
3168 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3169 return 0;
3170
3171 reg = &cur_regs(env)[regno];
3172 switch (reg->type) {
3173 case PTR_TO_MAP_KEY:
3174 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3175 mem_size, off, size);
3176 break;
3177 case PTR_TO_MAP_VALUE:
3178 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3179 mem_size, off, size);
3180 break;
3181 case PTR_TO_PACKET:
3182 case PTR_TO_PACKET_META:
3183 case PTR_TO_PACKET_END:
3184 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3185 off, size, regno, reg->id, off, mem_size);
3186 break;
3187 case PTR_TO_MEM:
3188 default:
3189 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3190 mem_size, off, size);
3191 }
3192
3193 return -EACCES;
3194 }
3195
3196 /* check read/write into a memory region with possible variable offset */
3197 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3198 int off, int size, u32 mem_size,
3199 bool zero_size_allowed)
3200 {
3201 struct bpf_verifier_state *vstate = env->cur_state;
3202 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3203 struct bpf_reg_state *reg = &state->regs[regno];
3204 int err;
3205
3206 /* We may have adjusted the register pointing to memory region, so we
3207 * need to try adding each of min_value and max_value to off
3208 * to make sure our theoretical access will be safe.
3209 */
3210 if (env->log.level & BPF_LOG_LEVEL)
3211 print_verifier_state(env, state);
3212
3213 /* The minimum value is only important with signed
3214 * comparisons where we can't assume the floor of a
3215 * value is 0. If we are using signed variables for our
3216 * index'es we need to make sure that whatever we use
3217 * will have a set floor within our range.
3218 */
3219 if (reg->smin_value < 0 &&
3220 (reg->smin_value == S64_MIN ||
3221 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3222 reg->smin_value + off < 0)) {
3223 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3224 regno);
3225 return -EACCES;
3226 }
3227 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3228 mem_size, zero_size_allowed);
3229 if (err) {
3230 verbose(env, "R%d min value is outside of the allowed memory range\n",
3231 regno);
3232 return err;
3233 }
3234
3235 /* If we haven't set a max value then we need to bail since we can't be
3236 * sure we won't do bad things.
3237 * If reg->umax_value + off could overflow, treat that as unbounded too.
3238 */
3239 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3240 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3241 regno);
3242 return -EACCES;
3243 }
3244 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3245 mem_size, zero_size_allowed);
3246 if (err) {
3247 verbose(env, "R%d max value is outside of the allowed memory range\n",
3248 regno);
3249 return err;
3250 }
3251
3252 return 0;
3253 }
3254
3255 /* check read/write into a map element with possible variable offset */
3256 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3257 int off, int size, bool zero_size_allowed)
3258 {
3259 struct bpf_verifier_state *vstate = env->cur_state;
3260 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3261 struct bpf_reg_state *reg = &state->regs[regno];
3262 struct bpf_map *map = reg->map_ptr;
3263 int err;
3264
3265 err = check_mem_region_access(env, regno, off, size, map->value_size,
3266 zero_size_allowed);
3267 if (err)
3268 return err;
3269
3270 if (map_value_has_spin_lock(map)) {
3271 u32 lock = map->spin_lock_off;
3272
3273 /* if any part of struct bpf_spin_lock can be touched by
3274 * load/store reject this program.
3275 * To check that [x1, x2) overlaps with [y1, y2)
3276 * it is sufficient to check x1 < y2 && y1 < x2.
3277 */
3278 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3279 lock < reg->umax_value + off + size) {
3280 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3281 return -EACCES;
3282 }
3283 }
3284 if (map_value_has_timer(map)) {
3285 u32 t = map->timer_off;
3286
3287 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3288 t < reg->umax_value + off + size) {
3289 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3290 return -EACCES;
3291 }
3292 }
3293 return err;
3294 }
3295
3296 #define MAX_PACKET_OFF 0xffff
3297
3298 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3299 {
3300 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3301 }
3302
3303 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3304 const struct bpf_call_arg_meta *meta,
3305 enum bpf_access_type t)
3306 {
3307 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3308
3309 switch (prog_type) {
3310 /* Program types only with direct read access go here! */
3311 case BPF_PROG_TYPE_LWT_IN:
3312 case BPF_PROG_TYPE_LWT_OUT:
3313 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3314 case BPF_PROG_TYPE_SK_REUSEPORT:
3315 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3316 case BPF_PROG_TYPE_CGROUP_SKB:
3317 if (t == BPF_WRITE)
3318 return false;
3319 fallthrough;
3320
3321 /* Program types with direct read + write access go here! */
3322 case BPF_PROG_TYPE_SCHED_CLS:
3323 case BPF_PROG_TYPE_SCHED_ACT:
3324 case BPF_PROG_TYPE_XDP:
3325 case BPF_PROG_TYPE_LWT_XMIT:
3326 case BPF_PROG_TYPE_SK_SKB:
3327 case BPF_PROG_TYPE_SK_MSG:
3328 if (meta)
3329 return meta->pkt_access;
3330
3331 env->seen_direct_write = true;
3332 return true;
3333
3334 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3335 if (t == BPF_WRITE)
3336 env->seen_direct_write = true;
3337
3338 return true;
3339
3340 default:
3341 return false;
3342 }
3343 }
3344
3345 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3346 int size, bool zero_size_allowed)
3347 {
3348 struct bpf_reg_state *regs = cur_regs(env);
3349 struct bpf_reg_state *reg = &regs[regno];
3350 int err;
3351
3352 /* We may have added a variable offset to the packet pointer; but any
3353 * reg->range we have comes after that. We are only checking the fixed
3354 * offset.
3355 */
3356
3357 /* We don't allow negative numbers, because we aren't tracking enough
3358 * detail to prove they're safe.
3359 */
3360 if (reg->smin_value < 0) {
3361 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3362 regno);
3363 return -EACCES;
3364 }
3365
3366 err = reg->range < 0 ? -EINVAL :
3367 __check_mem_access(env, regno, off, size, reg->range,
3368 zero_size_allowed);
3369 if (err) {
3370 verbose(env, "R%d offset is outside of the packet\n", regno);
3371 return err;
3372 }
3373
3374 /* __check_mem_access has made sure "off + size - 1" is within u16.
3375 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3376 * otherwise find_good_pkt_pointers would have refused to set range info
3377 * that __check_mem_access would have rejected this pkt access.
3378 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3379 */
3380 env->prog->aux->max_pkt_offset =
3381 max_t(u32, env->prog->aux->max_pkt_offset,
3382 off + reg->umax_value + size - 1);
3383
3384 return err;
3385 }
3386
3387 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3388 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3389 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3390 struct btf **btf, u32 *btf_id)
3391 {
3392 struct bpf_insn_access_aux info = {
3393 .reg_type = *reg_type,
3394 .log = &env->log,
3395 };
3396
3397 if (env->ops->is_valid_access &&
3398 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3399 /* A non zero info.ctx_field_size indicates that this field is a
3400 * candidate for later verifier transformation to load the whole
3401 * field and then apply a mask when accessed with a narrower
3402 * access than actual ctx access size. A zero info.ctx_field_size
3403 * will only allow for whole field access and rejects any other
3404 * type of narrower access.
3405 */
3406 *reg_type = info.reg_type;
3407
3408 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3409 *btf = info.btf;
3410 *btf_id = info.btf_id;
3411 } else {
3412 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3413 }
3414 /* remember the offset of last byte accessed in ctx */
3415 if (env->prog->aux->max_ctx_offset < off + size)
3416 env->prog->aux->max_ctx_offset = off + size;
3417 return 0;
3418 }
3419
3420 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3421 return -EACCES;
3422 }
3423
3424 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3425 int size)
3426 {
3427 if (size < 0 || off < 0 ||
3428 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3429 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3430 off, size);
3431 return -EACCES;
3432 }
3433 return 0;
3434 }
3435
3436 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3437 u32 regno, int off, int size,
3438 enum bpf_access_type t)
3439 {
3440 struct bpf_reg_state *regs = cur_regs(env);
3441 struct bpf_reg_state *reg = &regs[regno];
3442 struct bpf_insn_access_aux info = {};
3443 bool valid;
3444
3445 if (reg->smin_value < 0) {
3446 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3447 regno);
3448 return -EACCES;
3449 }
3450
3451 switch (reg->type) {
3452 case PTR_TO_SOCK_COMMON:
3453 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3454 break;
3455 case PTR_TO_SOCKET:
3456 valid = bpf_sock_is_valid_access(off, size, t, &info);
3457 break;
3458 case PTR_TO_TCP_SOCK:
3459 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3460 break;
3461 case PTR_TO_XDP_SOCK:
3462 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3463 break;
3464 default:
3465 valid = false;
3466 }
3467
3468
3469 if (valid) {
3470 env->insn_aux_data[insn_idx].ctx_field_size =
3471 info.ctx_field_size;
3472 return 0;
3473 }
3474
3475 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3476 regno, reg_type_str[reg->type], off, size);
3477
3478 return -EACCES;
3479 }
3480
3481 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3482 {
3483 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3484 }
3485
3486 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3487 {
3488 const struct bpf_reg_state *reg = reg_state(env, regno);
3489
3490 return reg->type == PTR_TO_CTX;
3491 }
3492
3493 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3494 {
3495 const struct bpf_reg_state *reg = reg_state(env, regno);
3496
3497 return type_is_sk_pointer(reg->type);
3498 }
3499
3500 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3501 {
3502 const struct bpf_reg_state *reg = reg_state(env, regno);
3503
3504 return type_is_pkt_pointer(reg->type);
3505 }
3506
3507 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3508 {
3509 const struct bpf_reg_state *reg = reg_state(env, regno);
3510
3511 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3512 return reg->type == PTR_TO_FLOW_KEYS;
3513 }
3514
3515 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3516 const struct bpf_reg_state *reg,
3517 int off, int size, bool strict)
3518 {
3519 struct tnum reg_off;
3520 int ip_align;
3521
3522 /* Byte size accesses are always allowed. */
3523 if (!strict || size == 1)
3524 return 0;
3525
3526 /* For platforms that do not have a Kconfig enabling
3527 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3528 * NET_IP_ALIGN is universally set to '2'. And on platforms
3529 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3530 * to this code only in strict mode where we want to emulate
3531 * the NET_IP_ALIGN==2 checking. Therefore use an
3532 * unconditional IP align value of '2'.
3533 */
3534 ip_align = 2;
3535
3536 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3537 if (!tnum_is_aligned(reg_off, size)) {
3538 char tn_buf[48];
3539
3540 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3541 verbose(env,
3542 "misaligned packet access off %d+%s+%d+%d size %d\n",
3543 ip_align, tn_buf, reg->off, off, size);
3544 return -EACCES;
3545 }
3546
3547 return 0;
3548 }
3549
3550 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3551 const struct bpf_reg_state *reg,
3552 const char *pointer_desc,
3553 int off, int size, bool strict)
3554 {
3555 struct tnum reg_off;
3556
3557 /* Byte size accesses are always allowed. */
3558 if (!strict || size == 1)
3559 return 0;
3560
3561 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3562 if (!tnum_is_aligned(reg_off, size)) {
3563 char tn_buf[48];
3564
3565 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3566 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3567 pointer_desc, tn_buf, reg->off, off, size);
3568 return -EACCES;
3569 }
3570
3571 return 0;
3572 }
3573
3574 static int check_ptr_alignment(struct bpf_verifier_env *env,
3575 const struct bpf_reg_state *reg, int off,
3576 int size, bool strict_alignment_once)
3577 {
3578 bool strict = env->strict_alignment || strict_alignment_once;
3579 const char *pointer_desc = "";
3580
3581 switch (reg->type) {
3582 case PTR_TO_PACKET:
3583 case PTR_TO_PACKET_META:
3584 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3585 * right in front, treat it the very same way.
3586 */
3587 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3588 case PTR_TO_FLOW_KEYS:
3589 pointer_desc = "flow keys ";
3590 break;
3591 case PTR_TO_MAP_KEY:
3592 pointer_desc = "key ";
3593 break;
3594 case PTR_TO_MAP_VALUE:
3595 pointer_desc = "value ";
3596 break;
3597 case PTR_TO_CTX:
3598 pointer_desc = "context ";
3599 break;
3600 case PTR_TO_STACK:
3601 pointer_desc = "stack ";
3602 /* The stack spill tracking logic in check_stack_write_fixed_off()
3603 * and check_stack_read_fixed_off() relies on stack accesses being
3604 * aligned.
3605 */
3606 strict = true;
3607 break;
3608 case PTR_TO_SOCKET:
3609 pointer_desc = "sock ";
3610 break;
3611 case PTR_TO_SOCK_COMMON:
3612 pointer_desc = "sock_common ";
3613 break;
3614 case PTR_TO_TCP_SOCK:
3615 pointer_desc = "tcp_sock ";
3616 break;
3617 case PTR_TO_XDP_SOCK:
3618 pointer_desc = "xdp_sock ";
3619 break;
3620 default:
3621 break;
3622 }
3623 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3624 strict);
3625 }
3626
3627 static int update_stack_depth(struct bpf_verifier_env *env,
3628 const struct bpf_func_state *func,
3629 int off)
3630 {
3631 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3632
3633 if (stack >= -off)
3634 return 0;
3635
3636 /* update known max for given subprogram */
3637 env->subprog_info[func->subprogno].stack_depth = -off;
3638 return 0;
3639 }
3640
3641 /* starting from main bpf function walk all instructions of the function
3642 * and recursively walk all callees that given function can call.
3643 * Ignore jump and exit insns.
3644 * Since recursion is prevented by check_cfg() this algorithm
3645 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3646 */
3647 static int check_max_stack_depth(struct bpf_verifier_env *env)
3648 {
3649 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3650 struct bpf_subprog_info *subprog = env->subprog_info;
3651 struct bpf_insn *insn = env->prog->insnsi;
3652 bool tail_call_reachable = false;
3653 int ret_insn[MAX_CALL_FRAMES];
3654 int ret_prog[MAX_CALL_FRAMES];
3655 int j;
3656
3657 process_func:
3658 /* protect against potential stack overflow that might happen when
3659 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3660 * depth for such case down to 256 so that the worst case scenario
3661 * would result in 8k stack size (32 which is tailcall limit * 256 =
3662 * 8k).
3663 *
3664 * To get the idea what might happen, see an example:
3665 * func1 -> sub rsp, 128
3666 * subfunc1 -> sub rsp, 256
3667 * tailcall1 -> add rsp, 256
3668 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3669 * subfunc2 -> sub rsp, 64
3670 * subfunc22 -> sub rsp, 128
3671 * tailcall2 -> add rsp, 128
3672 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3673 *
3674 * tailcall will unwind the current stack frame but it will not get rid
3675 * of caller's stack as shown on the example above.
3676 */
3677 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3678 verbose(env,
3679 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3680 depth);
3681 return -EACCES;
3682 }
3683 /* round up to 32-bytes, since this is granularity
3684 * of interpreter stack size
3685 */
3686 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3687 if (depth > MAX_BPF_STACK) {
3688 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3689 frame + 1, depth);
3690 return -EACCES;
3691 }
3692 continue_func:
3693 subprog_end = subprog[idx + 1].start;
3694 for (; i < subprog_end; i++) {
3695 int next_insn;
3696
3697 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
3698 continue;
3699 /* remember insn and function to return to */
3700 ret_insn[frame] = i + 1;
3701 ret_prog[frame] = idx;
3702
3703 /* find the callee */
3704 next_insn = i + insn[i].imm + 1;
3705 idx = find_subprog(env, next_insn);
3706 if (idx < 0) {
3707 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3708 next_insn);
3709 return -EFAULT;
3710 }
3711 if (subprog[idx].is_async_cb) {
3712 if (subprog[idx].has_tail_call) {
3713 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3714 return -EFAULT;
3715 }
3716 /* async callbacks don't increase bpf prog stack size */
3717 continue;
3718 }
3719 i = next_insn;
3720
3721 if (subprog[idx].has_tail_call)
3722 tail_call_reachable = true;
3723
3724 frame++;
3725 if (frame >= MAX_CALL_FRAMES) {
3726 verbose(env, "the call stack of %d frames is too deep !\n",
3727 frame);
3728 return -E2BIG;
3729 }
3730 goto process_func;
3731 }
3732 /* if tail call got detected across bpf2bpf calls then mark each of the
3733 * currently present subprog frames as tail call reachable subprogs;
3734 * this info will be utilized by JIT so that we will be preserving the
3735 * tail call counter throughout bpf2bpf calls combined with tailcalls
3736 */
3737 if (tail_call_reachable)
3738 for (j = 0; j < frame; j++)
3739 subprog[ret_prog[j]].tail_call_reachable = true;
3740 if (subprog[0].tail_call_reachable)
3741 env->prog->aux->tail_call_reachable = true;
3742
3743 /* end of for() loop means the last insn of the 'subprog'
3744 * was reached. Doesn't matter whether it was JA or EXIT
3745 */
3746 if (frame == 0)
3747 return 0;
3748 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3749 frame--;
3750 i = ret_insn[frame];
3751 idx = ret_prog[frame];
3752 goto continue_func;
3753 }
3754
3755 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3756 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3757 const struct bpf_insn *insn, int idx)
3758 {
3759 int start = idx + insn->imm + 1, subprog;
3760
3761 subprog = find_subprog(env, start);
3762 if (subprog < 0) {
3763 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3764 start);
3765 return -EFAULT;
3766 }
3767 return env->subprog_info[subprog].stack_depth;
3768 }
3769 #endif
3770
3771 int check_ctx_reg(struct bpf_verifier_env *env,
3772 const struct bpf_reg_state *reg, int regno)
3773 {
3774 /* Access to ctx or passing it to a helper is only allowed in
3775 * its original, unmodified form.
3776 */
3777
3778 if (reg->off) {
3779 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3780 regno, reg->off);
3781 return -EACCES;
3782 }
3783
3784 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3785 char tn_buf[48];
3786
3787 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3788 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3789 return -EACCES;
3790 }
3791
3792 return 0;
3793 }
3794
3795 static int __check_buffer_access(struct bpf_verifier_env *env,
3796 const char *buf_info,
3797 const struct bpf_reg_state *reg,
3798 int regno, int off, int size)
3799 {
3800 if (off < 0) {
3801 verbose(env,
3802 "R%d invalid %s buffer access: off=%d, size=%d\n",
3803 regno, buf_info, off, size);
3804 return -EACCES;
3805 }
3806 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3807 char tn_buf[48];
3808
3809 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3810 verbose(env,
3811 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3812 regno, off, tn_buf);
3813 return -EACCES;
3814 }
3815
3816 return 0;
3817 }
3818
3819 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3820 const struct bpf_reg_state *reg,
3821 int regno, int off, int size)
3822 {
3823 int err;
3824
3825 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3826 if (err)
3827 return err;
3828
3829 if (off + size > env->prog->aux->max_tp_access)
3830 env->prog->aux->max_tp_access = off + size;
3831
3832 return 0;
3833 }
3834
3835 static int check_buffer_access(struct bpf_verifier_env *env,
3836 const struct bpf_reg_state *reg,
3837 int regno, int off, int size,
3838 bool zero_size_allowed,
3839 const char *buf_info,
3840 u32 *max_access)
3841 {
3842 int err;
3843
3844 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3845 if (err)
3846 return err;
3847
3848 if (off + size > *max_access)
3849 *max_access = off + size;
3850
3851 return 0;
3852 }
3853
3854 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3855 static void zext_32_to_64(struct bpf_reg_state *reg)
3856 {
3857 reg->var_off = tnum_subreg(reg->var_off);
3858 __reg_assign_32_into_64(reg);
3859 }
3860
3861 /* truncate register to smaller size (in bytes)
3862 * must be called with size < BPF_REG_SIZE
3863 */
3864 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3865 {
3866 u64 mask;
3867
3868 /* clear high bits in bit representation */
3869 reg->var_off = tnum_cast(reg->var_off, size);
3870
3871 /* fix arithmetic bounds */
3872 mask = ((u64)1 << (size * 8)) - 1;
3873 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3874 reg->umin_value &= mask;
3875 reg->umax_value &= mask;
3876 } else {
3877 reg->umin_value = 0;
3878 reg->umax_value = mask;
3879 }
3880 reg->smin_value = reg->umin_value;
3881 reg->smax_value = reg->umax_value;
3882
3883 /* If size is smaller than 32bit register the 32bit register
3884 * values are also truncated so we push 64-bit bounds into
3885 * 32-bit bounds. Above were truncated < 32-bits already.
3886 */
3887 if (size >= 4)
3888 return;
3889 __reg_combine_64_into_32(reg);
3890 }
3891
3892 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3893 {
3894 /* A map is considered read-only if the following condition are true:
3895 *
3896 * 1) BPF program side cannot change any of the map content. The
3897 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3898 * and was set at map creation time.
3899 * 2) The map value(s) have been initialized from user space by a
3900 * loader and then "frozen", such that no new map update/delete
3901 * operations from syscall side are possible for the rest of
3902 * the map's lifetime from that point onwards.
3903 * 3) Any parallel/pending map update/delete operations from syscall
3904 * side have been completed. Only after that point, it's safe to
3905 * assume that map value(s) are immutable.
3906 */
3907 return (map->map_flags & BPF_F_RDONLY_PROG) &&
3908 READ_ONCE(map->frozen) &&
3909 !bpf_map_write_active(map);
3910 }
3911
3912 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3913 {
3914 void *ptr;
3915 u64 addr;
3916 int err;
3917
3918 err = map->ops->map_direct_value_addr(map, &addr, off);
3919 if (err)
3920 return err;
3921 ptr = (void *)(long)addr + off;
3922
3923 switch (size) {
3924 case sizeof(u8):
3925 *val = (u64)*(u8 *)ptr;
3926 break;
3927 case sizeof(u16):
3928 *val = (u64)*(u16 *)ptr;
3929 break;
3930 case sizeof(u32):
3931 *val = (u64)*(u32 *)ptr;
3932 break;
3933 case sizeof(u64):
3934 *val = *(u64 *)ptr;
3935 break;
3936 default:
3937 return -EINVAL;
3938 }
3939 return 0;
3940 }
3941
3942 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3943 struct bpf_reg_state *regs,
3944 int regno, int off, int size,
3945 enum bpf_access_type atype,
3946 int value_regno)
3947 {
3948 struct bpf_reg_state *reg = regs + regno;
3949 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3950 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3951 u32 btf_id;
3952 int ret;
3953
3954 if (off < 0) {
3955 verbose(env,
3956 "R%d is ptr_%s invalid negative access: off=%d\n",
3957 regno, tname, off);
3958 return -EACCES;
3959 }
3960 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3961 char tn_buf[48];
3962
3963 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3964 verbose(env,
3965 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3966 regno, tname, off, tn_buf);
3967 return -EACCES;
3968 }
3969
3970 if (env->ops->btf_struct_access) {
3971 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3972 off, size, atype, &btf_id);
3973 } else {
3974 if (atype != BPF_READ) {
3975 verbose(env, "only read is supported\n");
3976 return -EACCES;
3977 }
3978
3979 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3980 atype, &btf_id);
3981 }
3982
3983 if (ret < 0)
3984 return ret;
3985
3986 if (atype == BPF_READ && value_regno >= 0)
3987 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3988
3989 return 0;
3990 }
3991
3992 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3993 struct bpf_reg_state *regs,
3994 int regno, int off, int size,
3995 enum bpf_access_type atype,
3996 int value_regno)
3997 {
3998 struct bpf_reg_state *reg = regs + regno;
3999 struct bpf_map *map = reg->map_ptr;
4000 const struct btf_type *t;
4001 const char *tname;
4002 u32 btf_id;
4003 int ret;
4004
4005 if (!btf_vmlinux) {
4006 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4007 return -ENOTSUPP;
4008 }
4009
4010 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4011 verbose(env, "map_ptr access not supported for map type %d\n",
4012 map->map_type);
4013 return -ENOTSUPP;
4014 }
4015
4016 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4017 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4018
4019 if (!env->allow_ptr_to_map_access) {
4020 verbose(env,
4021 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4022 tname);
4023 return -EPERM;
4024 }
4025
4026 if (off < 0) {
4027 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4028 regno, tname, off);
4029 return -EACCES;
4030 }
4031
4032 if (atype != BPF_READ) {
4033 verbose(env, "only read from %s is supported\n", tname);
4034 return -EACCES;
4035 }
4036
4037 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
4038 if (ret < 0)
4039 return ret;
4040
4041 if (value_regno >= 0)
4042 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
4043
4044 return 0;
4045 }
4046
4047 /* Check that the stack access at the given offset is within bounds. The
4048 * maximum valid offset is -1.
4049 *
4050 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4051 * -state->allocated_stack for reads.
4052 */
4053 static int check_stack_slot_within_bounds(int off,
4054 struct bpf_func_state *state,
4055 enum bpf_access_type t)
4056 {
4057 int min_valid_off;
4058
4059 if (t == BPF_WRITE)
4060 min_valid_off = -MAX_BPF_STACK;
4061 else
4062 min_valid_off = -state->allocated_stack;
4063
4064 if (off < min_valid_off || off > -1)
4065 return -EACCES;
4066 return 0;
4067 }
4068
4069 /* Check that the stack access at 'regno + off' falls within the maximum stack
4070 * bounds.
4071 *
4072 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4073 */
4074 static int check_stack_access_within_bounds(
4075 struct bpf_verifier_env *env,
4076 int regno, int off, int access_size,
4077 enum stack_access_src src, enum bpf_access_type type)
4078 {
4079 struct bpf_reg_state *regs = cur_regs(env);
4080 struct bpf_reg_state *reg = regs + regno;
4081 struct bpf_func_state *state = func(env, reg);
4082 int min_off, max_off;
4083 int err;
4084 char *err_extra;
4085
4086 if (src == ACCESS_HELPER)
4087 /* We don't know if helpers are reading or writing (or both). */
4088 err_extra = " indirect access to";
4089 else if (type == BPF_READ)
4090 err_extra = " read from";
4091 else
4092 err_extra = " write to";
4093
4094 if (tnum_is_const(reg->var_off)) {
4095 min_off = reg->var_off.value + off;
4096 if (access_size > 0)
4097 max_off = min_off + access_size - 1;
4098 else
4099 max_off = min_off;
4100 } else {
4101 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4102 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4103 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4104 err_extra, regno);
4105 return -EACCES;
4106 }
4107 min_off = reg->smin_value + off;
4108 if (access_size > 0)
4109 max_off = reg->smax_value + off + access_size - 1;
4110 else
4111 max_off = min_off;
4112 }
4113
4114 err = check_stack_slot_within_bounds(min_off, state, type);
4115 if (!err)
4116 err = check_stack_slot_within_bounds(max_off, state, type);
4117
4118 if (err) {
4119 if (tnum_is_const(reg->var_off)) {
4120 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4121 err_extra, regno, off, access_size);
4122 } else {
4123 char tn_buf[48];
4124
4125 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4126 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4127 err_extra, regno, tn_buf, access_size);
4128 }
4129 }
4130 return err;
4131 }
4132
4133 /* check whether memory at (regno + off) is accessible for t = (read | write)
4134 * if t==write, value_regno is a register which value is stored into memory
4135 * if t==read, value_regno is a register which will receive the value from memory
4136 * if t==write && value_regno==-1, some unknown value is stored into memory
4137 * if t==read && value_regno==-1, don't care what we read from memory
4138 */
4139 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4140 int off, int bpf_size, enum bpf_access_type t,
4141 int value_regno, bool strict_alignment_once)
4142 {
4143 struct bpf_reg_state *regs = cur_regs(env);
4144 struct bpf_reg_state *reg = regs + regno;
4145 struct bpf_func_state *state;
4146 int size, err = 0;
4147
4148 size = bpf_size_to_bytes(bpf_size);
4149 if (size < 0)
4150 return size;
4151
4152 /* alignment checks will add in reg->off themselves */
4153 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
4154 if (err)
4155 return err;
4156
4157 /* for access checks, reg->off is just part of off */
4158 off += reg->off;
4159
4160 if (reg->type == PTR_TO_MAP_KEY) {
4161 if (t == BPF_WRITE) {
4162 verbose(env, "write to change key R%d not allowed\n", regno);
4163 return -EACCES;
4164 }
4165
4166 err = check_mem_region_access(env, regno, off, size,
4167 reg->map_ptr->key_size, false);
4168 if (err)
4169 return err;
4170 if (value_regno >= 0)
4171 mark_reg_unknown(env, regs, value_regno);
4172 } else if (reg->type == PTR_TO_MAP_VALUE) {
4173 if (t == BPF_WRITE && value_regno >= 0 &&
4174 is_pointer_value(env, value_regno)) {
4175 verbose(env, "R%d leaks addr into map\n", value_regno);
4176 return -EACCES;
4177 }
4178 err = check_map_access_type(env, regno, off, size, t);
4179 if (err)
4180 return err;
4181 err = check_map_access(env, regno, off, size, false);
4182 if (!err && t == BPF_READ && value_regno >= 0) {
4183 struct bpf_map *map = reg->map_ptr;
4184
4185 /* if map is read-only, track its contents as scalars */
4186 if (tnum_is_const(reg->var_off) &&
4187 bpf_map_is_rdonly(map) &&
4188 map->ops->map_direct_value_addr) {
4189 int map_off = off + reg->var_off.value;
4190 u64 val = 0;
4191
4192 err = bpf_map_direct_read(map, map_off, size,
4193 &val);
4194 if (err)
4195 return err;
4196
4197 regs[value_regno].type = SCALAR_VALUE;
4198 __mark_reg_known(&regs[value_regno], val);
4199 } else {
4200 mark_reg_unknown(env, regs, value_regno);
4201 }
4202 }
4203 } else if (reg->type == PTR_TO_MEM) {
4204 if (t == BPF_WRITE && value_regno >= 0 &&
4205 is_pointer_value(env, value_regno)) {
4206 verbose(env, "R%d leaks addr into mem\n", value_regno);
4207 return -EACCES;
4208 }
4209 err = check_mem_region_access(env, regno, off, size,
4210 reg->mem_size, false);
4211 if (!err && t == BPF_READ && value_regno >= 0)
4212 mark_reg_unknown(env, regs, value_regno);
4213 } else if (reg->type == PTR_TO_CTX) {
4214 enum bpf_reg_type reg_type = SCALAR_VALUE;
4215 struct btf *btf = NULL;
4216 u32 btf_id = 0;
4217
4218 if (t == BPF_WRITE && value_regno >= 0 &&
4219 is_pointer_value(env, value_regno)) {
4220 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4221 return -EACCES;
4222 }
4223
4224 err = check_ctx_reg(env, reg, regno);
4225 if (err < 0)
4226 return err;
4227
4228 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
4229 if (err)
4230 verbose_linfo(env, insn_idx, "; ");
4231 if (!err && t == BPF_READ && value_regno >= 0) {
4232 /* ctx access returns either a scalar, or a
4233 * PTR_TO_PACKET[_META,_END]. In the latter
4234 * case, we know the offset is zero.
4235 */
4236 if (reg_type == SCALAR_VALUE) {
4237 mark_reg_unknown(env, regs, value_regno);
4238 } else {
4239 mark_reg_known_zero(env, regs,
4240 value_regno);
4241 if (reg_type_may_be_null(reg_type))
4242 regs[value_regno].id = ++env->id_gen;
4243 /* A load of ctx field could have different
4244 * actual load size with the one encoded in the
4245 * insn. When the dst is PTR, it is for sure not
4246 * a sub-register.
4247 */
4248 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4249 if (reg_type == PTR_TO_BTF_ID ||
4250 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4251 regs[value_regno].btf = btf;
4252 regs[value_regno].btf_id = btf_id;
4253 }
4254 }
4255 regs[value_regno].type = reg_type;
4256 }
4257
4258 } else if (reg->type == PTR_TO_STACK) {
4259 /* Basic bounds checks. */
4260 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4261 if (err)
4262 return err;
4263
4264 state = func(env, reg);
4265 err = update_stack_depth(env, state, off);
4266 if (err)
4267 return err;
4268
4269 if (t == BPF_READ)
4270 err = check_stack_read(env, regno, off, size,
4271 value_regno);
4272 else
4273 err = check_stack_write(env, regno, off, size,
4274 value_regno, insn_idx);
4275 } else if (reg_is_pkt_pointer(reg)) {
4276 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4277 verbose(env, "cannot write into packet\n");
4278 return -EACCES;
4279 }
4280 if (t == BPF_WRITE && value_regno >= 0 &&
4281 is_pointer_value(env, value_regno)) {
4282 verbose(env, "R%d leaks addr into packet\n",
4283 value_regno);
4284 return -EACCES;
4285 }
4286 err = check_packet_access(env, regno, off, size, false);
4287 if (!err && t == BPF_READ && value_regno >= 0)
4288 mark_reg_unknown(env, regs, value_regno);
4289 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4290 if (t == BPF_WRITE && value_regno >= 0 &&
4291 is_pointer_value(env, value_regno)) {
4292 verbose(env, "R%d leaks addr into flow keys\n",
4293 value_regno);
4294 return -EACCES;
4295 }
4296
4297 err = check_flow_keys_access(env, off, size);
4298 if (!err && t == BPF_READ && value_regno >= 0)
4299 mark_reg_unknown(env, regs, value_regno);
4300 } else if (type_is_sk_pointer(reg->type)) {
4301 if (t == BPF_WRITE) {
4302 verbose(env, "R%d cannot write into %s\n",
4303 regno, reg_type_str[reg->type]);
4304 return -EACCES;
4305 }
4306 err = check_sock_access(env, insn_idx, regno, off, size, t);
4307 if (!err && value_regno >= 0)
4308 mark_reg_unknown(env, regs, value_regno);
4309 } else if (reg->type == PTR_TO_TP_BUFFER) {
4310 err = check_tp_buffer_access(env, reg, regno, off, size);
4311 if (!err && t == BPF_READ && value_regno >= 0)
4312 mark_reg_unknown(env, regs, value_regno);
4313 } else if (reg->type == PTR_TO_BTF_ID) {
4314 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4315 value_regno);
4316 } else if (reg->type == CONST_PTR_TO_MAP) {
4317 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4318 value_regno);
4319 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4320 if (t == BPF_WRITE) {
4321 verbose(env, "R%d cannot write into %s\n",
4322 regno, reg_type_str[reg->type]);
4323 return -EACCES;
4324 }
4325 err = check_buffer_access(env, reg, regno, off, size, false,
4326 "rdonly",
4327 &env->prog->aux->max_rdonly_access);
4328 if (!err && value_regno >= 0)
4329 mark_reg_unknown(env, regs, value_regno);
4330 } else if (reg->type == PTR_TO_RDWR_BUF) {
4331 err = check_buffer_access(env, reg, regno, off, size, false,
4332 "rdwr",
4333 &env->prog->aux->max_rdwr_access);
4334 if (!err && t == BPF_READ && value_regno >= 0)
4335 mark_reg_unknown(env, regs, value_regno);
4336 } else {
4337 verbose(env, "R%d invalid mem access '%s'\n", regno,
4338 reg_type_str[reg->type]);
4339 return -EACCES;
4340 }
4341
4342 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4343 regs[value_regno].type == SCALAR_VALUE) {
4344 /* b/h/w load zero-extends, mark upper bits as known 0 */
4345 coerce_reg_to_size(&regs[value_regno], size);
4346 }
4347 return err;
4348 }
4349
4350 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4351 {
4352 int load_reg;
4353 int err;
4354
4355 switch (insn->imm) {
4356 case BPF_ADD:
4357 case BPF_ADD | BPF_FETCH:
4358 case BPF_AND:
4359 case BPF_AND | BPF_FETCH:
4360 case BPF_OR:
4361 case BPF_OR | BPF_FETCH:
4362 case BPF_XOR:
4363 case BPF_XOR | BPF_FETCH:
4364 case BPF_XCHG:
4365 case BPF_CMPXCHG:
4366 break;
4367 default:
4368 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4369 return -EINVAL;
4370 }
4371
4372 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4373 verbose(env, "invalid atomic operand size\n");
4374 return -EINVAL;
4375 }
4376
4377 /* check src1 operand */
4378 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4379 if (err)
4380 return err;
4381
4382 /* check src2 operand */
4383 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4384 if (err)
4385 return err;
4386
4387 if (insn->imm == BPF_CMPXCHG) {
4388 /* Check comparison of R0 with memory location */
4389 const u32 aux_reg = BPF_REG_0;
4390
4391 err = check_reg_arg(env, aux_reg, SRC_OP);
4392 if (err)
4393 return err;
4394
4395 if (is_pointer_value(env, aux_reg)) {
4396 verbose(env, "R%d leaks addr into mem\n", aux_reg);
4397 return -EACCES;
4398 }
4399 }
4400
4401 if (is_pointer_value(env, insn->src_reg)) {
4402 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4403 return -EACCES;
4404 }
4405
4406 if (is_ctx_reg(env, insn->dst_reg) ||
4407 is_pkt_reg(env, insn->dst_reg) ||
4408 is_flow_key_reg(env, insn->dst_reg) ||
4409 is_sk_reg(env, insn->dst_reg)) {
4410 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
4411 insn->dst_reg,
4412 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4413 return -EACCES;
4414 }
4415
4416 if (insn->imm & BPF_FETCH) {
4417 if (insn->imm == BPF_CMPXCHG)
4418 load_reg = BPF_REG_0;
4419 else
4420 load_reg = insn->src_reg;
4421
4422 /* check and record load of old value */
4423 err = check_reg_arg(env, load_reg, DST_OP);
4424 if (err)
4425 return err;
4426 } else {
4427 /* This instruction accesses a memory location but doesn't
4428 * actually load it into a register.
4429 */
4430 load_reg = -1;
4431 }
4432
4433 /* Check whether we can read the memory, with second call for fetch
4434 * case to simulate the register fill.
4435 */
4436 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4437 BPF_SIZE(insn->code), BPF_READ, -1, true);
4438 if (!err && load_reg >= 0)
4439 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4440 BPF_SIZE(insn->code), BPF_READ, load_reg,
4441 true);
4442 if (err)
4443 return err;
4444
4445 /* Check whether we can write into the same memory. */
4446 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4447 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4448 if (err)
4449 return err;
4450
4451 return 0;
4452 }
4453
4454 /* When register 'regno' is used to read the stack (either directly or through
4455 * a helper function) make sure that it's within stack boundary and, depending
4456 * on the access type, that all elements of the stack are initialized.
4457 *
4458 * 'off' includes 'regno->off', but not its dynamic part (if any).
4459 *
4460 * All registers that have been spilled on the stack in the slots within the
4461 * read offsets are marked as read.
4462 */
4463 static int check_stack_range_initialized(
4464 struct bpf_verifier_env *env, int regno, int off,
4465 int access_size, bool zero_size_allowed,
4466 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4467 {
4468 struct bpf_reg_state *reg = reg_state(env, regno);
4469 struct bpf_func_state *state = func(env, reg);
4470 int err, min_off, max_off, i, j, slot, spi;
4471 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4472 enum bpf_access_type bounds_check_type;
4473 /* Some accesses can write anything into the stack, others are
4474 * read-only.
4475 */
4476 bool clobber = false;
4477
4478 if (access_size == 0 && !zero_size_allowed) {
4479 verbose(env, "invalid zero-sized read\n");
4480 return -EACCES;
4481 }
4482
4483 if (type == ACCESS_HELPER) {
4484 /* The bounds checks for writes are more permissive than for
4485 * reads. However, if raw_mode is not set, we'll do extra
4486 * checks below.
4487 */
4488 bounds_check_type = BPF_WRITE;
4489 clobber = true;
4490 } else {
4491 bounds_check_type = BPF_READ;
4492 }
4493 err = check_stack_access_within_bounds(env, regno, off, access_size,
4494 type, bounds_check_type);
4495 if (err)
4496 return err;
4497
4498
4499 if (tnum_is_const(reg->var_off)) {
4500 min_off = max_off = reg->var_off.value + off;
4501 } else {
4502 /* Variable offset is prohibited for unprivileged mode for
4503 * simplicity since it requires corresponding support in
4504 * Spectre masking for stack ALU.
4505 * See also retrieve_ptr_limit().
4506 */
4507 if (!env->bypass_spec_v1) {
4508 char tn_buf[48];
4509
4510 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4511 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4512 regno, err_extra, tn_buf);
4513 return -EACCES;
4514 }
4515 /* Only initialized buffer on stack is allowed to be accessed
4516 * with variable offset. With uninitialized buffer it's hard to
4517 * guarantee that whole memory is marked as initialized on
4518 * helper return since specific bounds are unknown what may
4519 * cause uninitialized stack leaking.
4520 */
4521 if (meta && meta->raw_mode)
4522 meta = NULL;
4523
4524 min_off = reg->smin_value + off;
4525 max_off = reg->smax_value + off;
4526 }
4527
4528 if (meta && meta->raw_mode) {
4529 meta->access_size = access_size;
4530 meta->regno = regno;
4531 return 0;
4532 }
4533
4534 for (i = min_off; i < max_off + access_size; i++) {
4535 u8 *stype;
4536
4537 slot = -i - 1;
4538 spi = slot / BPF_REG_SIZE;
4539 if (state->allocated_stack <= slot)
4540 goto err;
4541 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4542 if (*stype == STACK_MISC)
4543 goto mark;
4544 if (*stype == STACK_ZERO) {
4545 if (clobber) {
4546 /* helper can write anything into the stack */
4547 *stype = STACK_MISC;
4548 }
4549 goto mark;
4550 }
4551
4552 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4553 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4554 goto mark;
4555
4556 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4557 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4558 env->allow_ptr_leaks)) {
4559 if (clobber) {
4560 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4561 for (j = 0; j < BPF_REG_SIZE; j++)
4562 state->stack[spi].slot_type[j] = STACK_MISC;
4563 }
4564 goto mark;
4565 }
4566
4567 err:
4568 if (tnum_is_const(reg->var_off)) {
4569 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4570 err_extra, regno, min_off, i - min_off, access_size);
4571 } else {
4572 char tn_buf[48];
4573
4574 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4575 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4576 err_extra, regno, tn_buf, i - min_off, access_size);
4577 }
4578 return -EACCES;
4579 mark:
4580 /* reading any byte out of 8-byte 'spill_slot' will cause
4581 * the whole slot to be marked as 'read'
4582 */
4583 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4584 state->stack[spi].spilled_ptr.parent,
4585 REG_LIVE_READ64);
4586 }
4587 return update_stack_depth(env, state, min_off);
4588 }
4589
4590 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4591 int access_size, bool zero_size_allowed,
4592 struct bpf_call_arg_meta *meta)
4593 {
4594 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4595
4596 switch (reg->type) {
4597 case PTR_TO_PACKET:
4598 case PTR_TO_PACKET_META:
4599 return check_packet_access(env, regno, reg->off, access_size,
4600 zero_size_allowed);
4601 case PTR_TO_MAP_KEY:
4602 return check_mem_region_access(env, regno, reg->off, access_size,
4603 reg->map_ptr->key_size, false);
4604 case PTR_TO_MAP_VALUE:
4605 if (check_map_access_type(env, regno, reg->off, access_size,
4606 meta && meta->raw_mode ? BPF_WRITE :
4607 BPF_READ))
4608 return -EACCES;
4609 return check_map_access(env, regno, reg->off, access_size,
4610 zero_size_allowed);
4611 case PTR_TO_MEM:
4612 return check_mem_region_access(env, regno, reg->off,
4613 access_size, reg->mem_size,
4614 zero_size_allowed);
4615 case PTR_TO_RDONLY_BUF:
4616 if (meta && meta->raw_mode)
4617 return -EACCES;
4618 return check_buffer_access(env, reg, regno, reg->off,
4619 access_size, zero_size_allowed,
4620 "rdonly",
4621 &env->prog->aux->max_rdonly_access);
4622 case PTR_TO_RDWR_BUF:
4623 return check_buffer_access(env, reg, regno, reg->off,
4624 access_size, zero_size_allowed,
4625 "rdwr",
4626 &env->prog->aux->max_rdwr_access);
4627 case PTR_TO_STACK:
4628 return check_stack_range_initialized(
4629 env,
4630 regno, reg->off, access_size,
4631 zero_size_allowed, ACCESS_HELPER, meta);
4632 default: /* scalar_value or invalid ptr */
4633 /* Allow zero-byte read from NULL, regardless of pointer type */
4634 if (zero_size_allowed && access_size == 0 &&
4635 register_is_null(reg))
4636 return 0;
4637
4638 verbose(env, "R%d type=%s expected=%s\n", regno,
4639 reg_type_str[reg->type],
4640 reg_type_str[PTR_TO_STACK]);
4641 return -EACCES;
4642 }
4643 }
4644
4645 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4646 u32 regno, u32 mem_size)
4647 {
4648 if (register_is_null(reg))
4649 return 0;
4650
4651 if (reg_type_may_be_null(reg->type)) {
4652 /* Assuming that the register contains a value check if the memory
4653 * access is safe. Temporarily save and restore the register's state as
4654 * the conversion shouldn't be visible to a caller.
4655 */
4656 const struct bpf_reg_state saved_reg = *reg;
4657 int rv;
4658
4659 mark_ptr_not_null_reg(reg);
4660 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4661 *reg = saved_reg;
4662 return rv;
4663 }
4664
4665 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4666 }
4667
4668 /* Implementation details:
4669 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4670 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4671 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4672 * value_or_null->value transition, since the verifier only cares about
4673 * the range of access to valid map value pointer and doesn't care about actual
4674 * address of the map element.
4675 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4676 * reg->id > 0 after value_or_null->value transition. By doing so
4677 * two bpf_map_lookups will be considered two different pointers that
4678 * point to different bpf_spin_locks.
4679 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4680 * dead-locks.
4681 * Since only one bpf_spin_lock is allowed the checks are simpler than
4682 * reg_is_refcounted() logic. The verifier needs to remember only
4683 * one spin_lock instead of array of acquired_refs.
4684 * cur_state->active_spin_lock remembers which map value element got locked
4685 * and clears it after bpf_spin_unlock.
4686 */
4687 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4688 bool is_lock)
4689 {
4690 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4691 struct bpf_verifier_state *cur = env->cur_state;
4692 bool is_const = tnum_is_const(reg->var_off);
4693 struct bpf_map *map = reg->map_ptr;
4694 u64 val = reg->var_off.value;
4695
4696 if (!is_const) {
4697 verbose(env,
4698 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4699 regno);
4700 return -EINVAL;
4701 }
4702 if (!map->btf) {
4703 verbose(env,
4704 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4705 map->name);
4706 return -EINVAL;
4707 }
4708 if (!map_value_has_spin_lock(map)) {
4709 if (map->spin_lock_off == -E2BIG)
4710 verbose(env,
4711 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4712 map->name);
4713 else if (map->spin_lock_off == -ENOENT)
4714 verbose(env,
4715 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4716 map->name);
4717 else
4718 verbose(env,
4719 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4720 map->name);
4721 return -EINVAL;
4722 }
4723 if (map->spin_lock_off != val + reg->off) {
4724 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4725 val + reg->off);
4726 return -EINVAL;
4727 }
4728 if (is_lock) {
4729 if (cur->active_spin_lock) {
4730 verbose(env,
4731 "Locking two bpf_spin_locks are not allowed\n");
4732 return -EINVAL;
4733 }
4734 cur->active_spin_lock = reg->id;
4735 } else {
4736 if (!cur->active_spin_lock) {
4737 verbose(env, "bpf_spin_unlock without taking a lock\n");
4738 return -EINVAL;
4739 }
4740 if (cur->active_spin_lock != reg->id) {
4741 verbose(env, "bpf_spin_unlock of different lock\n");
4742 return -EINVAL;
4743 }
4744 cur->active_spin_lock = 0;
4745 }
4746 return 0;
4747 }
4748
4749 static int process_timer_func(struct bpf_verifier_env *env, int regno,
4750 struct bpf_call_arg_meta *meta)
4751 {
4752 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4753 bool is_const = tnum_is_const(reg->var_off);
4754 struct bpf_map *map = reg->map_ptr;
4755 u64 val = reg->var_off.value;
4756
4757 if (!is_const) {
4758 verbose(env,
4759 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4760 regno);
4761 return -EINVAL;
4762 }
4763 if (!map->btf) {
4764 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4765 map->name);
4766 return -EINVAL;
4767 }
4768 if (!map_value_has_timer(map)) {
4769 if (map->timer_off == -E2BIG)
4770 verbose(env,
4771 "map '%s' has more than one 'struct bpf_timer'\n",
4772 map->name);
4773 else if (map->timer_off == -ENOENT)
4774 verbose(env,
4775 "map '%s' doesn't have 'struct bpf_timer'\n",
4776 map->name);
4777 else
4778 verbose(env,
4779 "map '%s' is not a struct type or bpf_timer is mangled\n",
4780 map->name);
4781 return -EINVAL;
4782 }
4783 if (map->timer_off != val + reg->off) {
4784 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
4785 val + reg->off, map->timer_off);
4786 return -EINVAL;
4787 }
4788 if (meta->map_ptr) {
4789 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
4790 return -EFAULT;
4791 }
4792 meta->map_uid = reg->map_uid;
4793 meta->map_ptr = map;
4794 return 0;
4795 }
4796
4797 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4798 {
4799 return type == ARG_PTR_TO_MEM ||
4800 type == ARG_PTR_TO_MEM_OR_NULL ||
4801 type == ARG_PTR_TO_UNINIT_MEM;
4802 }
4803
4804 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4805 {
4806 return type == ARG_CONST_SIZE ||
4807 type == ARG_CONST_SIZE_OR_ZERO;
4808 }
4809
4810 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4811 {
4812 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4813 }
4814
4815 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4816 {
4817 return type == ARG_PTR_TO_INT ||
4818 type == ARG_PTR_TO_LONG;
4819 }
4820
4821 static int int_ptr_type_to_size(enum bpf_arg_type type)
4822 {
4823 if (type == ARG_PTR_TO_INT)
4824 return sizeof(u32);
4825 else if (type == ARG_PTR_TO_LONG)
4826 return sizeof(u64);
4827
4828 return -EINVAL;
4829 }
4830
4831 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4832 const struct bpf_call_arg_meta *meta,
4833 enum bpf_arg_type *arg_type)
4834 {
4835 if (!meta->map_ptr) {
4836 /* kernel subsystem misconfigured verifier */
4837 verbose(env, "invalid map_ptr to access map->type\n");
4838 return -EACCES;
4839 }
4840
4841 switch (meta->map_ptr->map_type) {
4842 case BPF_MAP_TYPE_SOCKMAP:
4843 case BPF_MAP_TYPE_SOCKHASH:
4844 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4845 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4846 } else {
4847 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4848 return -EINVAL;
4849 }
4850 break;
4851
4852 default:
4853 break;
4854 }
4855 return 0;
4856 }
4857
4858 struct bpf_reg_types {
4859 const enum bpf_reg_type types[10];
4860 u32 *btf_id;
4861 };
4862
4863 static const struct bpf_reg_types map_key_value_types = {
4864 .types = {
4865 PTR_TO_STACK,
4866 PTR_TO_PACKET,
4867 PTR_TO_PACKET_META,
4868 PTR_TO_MAP_KEY,
4869 PTR_TO_MAP_VALUE,
4870 },
4871 };
4872
4873 static const struct bpf_reg_types sock_types = {
4874 .types = {
4875 PTR_TO_SOCK_COMMON,
4876 PTR_TO_SOCKET,
4877 PTR_TO_TCP_SOCK,
4878 PTR_TO_XDP_SOCK,
4879 },
4880 };
4881
4882 #ifdef CONFIG_NET
4883 static const struct bpf_reg_types btf_id_sock_common_types = {
4884 .types = {
4885 PTR_TO_SOCK_COMMON,
4886 PTR_TO_SOCKET,
4887 PTR_TO_TCP_SOCK,
4888 PTR_TO_XDP_SOCK,
4889 PTR_TO_BTF_ID,
4890 },
4891 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4892 };
4893 #endif
4894
4895 static const struct bpf_reg_types mem_types = {
4896 .types = {
4897 PTR_TO_STACK,
4898 PTR_TO_PACKET,
4899 PTR_TO_PACKET_META,
4900 PTR_TO_MAP_KEY,
4901 PTR_TO_MAP_VALUE,
4902 PTR_TO_MEM,
4903 PTR_TO_RDONLY_BUF,
4904 PTR_TO_RDWR_BUF,
4905 },
4906 };
4907
4908 static const struct bpf_reg_types int_ptr_types = {
4909 .types = {
4910 PTR_TO_STACK,
4911 PTR_TO_PACKET,
4912 PTR_TO_PACKET_META,
4913 PTR_TO_MAP_KEY,
4914 PTR_TO_MAP_VALUE,
4915 },
4916 };
4917
4918 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4919 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4920 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4921 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4922 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4923 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4924 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4925 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4926 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4927 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
4928 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
4929 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
4930
4931 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4932 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4933 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4934 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4935 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4936 [ARG_CONST_SIZE] = &scalar_types,
4937 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4938 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4939 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4940 [ARG_PTR_TO_CTX] = &context_types,
4941 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4942 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4943 #ifdef CONFIG_NET
4944 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4945 #endif
4946 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4947 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4948 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4949 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4950 [ARG_PTR_TO_MEM] = &mem_types,
4951 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4952 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4953 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4954 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4955 [ARG_PTR_TO_INT] = &int_ptr_types,
4956 [ARG_PTR_TO_LONG] = &int_ptr_types,
4957 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4958 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4959 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
4960 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
4961 [ARG_PTR_TO_TIMER] = &timer_types,
4962 };
4963
4964 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4965 enum bpf_arg_type arg_type,
4966 const u32 *arg_btf_id)
4967 {
4968 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4969 enum bpf_reg_type expected, type = reg->type;
4970 const struct bpf_reg_types *compatible;
4971 int i, j;
4972
4973 compatible = compatible_reg_types[arg_type];
4974 if (!compatible) {
4975 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4976 return -EFAULT;
4977 }
4978
4979 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4980 expected = compatible->types[i];
4981 if (expected == NOT_INIT)
4982 break;
4983
4984 if (type == expected)
4985 goto found;
4986 }
4987
4988 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4989 for (j = 0; j + 1 < i; j++)
4990 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4991 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4992 return -EACCES;
4993
4994 found:
4995 if (type == PTR_TO_BTF_ID) {
4996 if (!arg_btf_id) {
4997 if (!compatible->btf_id) {
4998 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4999 return -EFAULT;
5000 }
5001 arg_btf_id = compatible->btf_id;
5002 }
5003
5004 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5005 btf_vmlinux, *arg_btf_id)) {
5006 verbose(env, "R%d is of type %s but %s is expected\n",
5007 regno, kernel_type_name(reg->btf, reg->btf_id),
5008 kernel_type_name(btf_vmlinux, *arg_btf_id));
5009 return -EACCES;
5010 }
5011
5012 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5013 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5014 regno);
5015 return -EACCES;
5016 }
5017 }
5018
5019 return 0;
5020 }
5021
5022 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5023 struct bpf_call_arg_meta *meta,
5024 const struct bpf_func_proto *fn)
5025 {
5026 u32 regno = BPF_REG_1 + arg;
5027 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5028 enum bpf_arg_type arg_type = fn->arg_type[arg];
5029 enum bpf_reg_type type = reg->type;
5030 int err = 0;
5031
5032 if (arg_type == ARG_DONTCARE)
5033 return 0;
5034
5035 err = check_reg_arg(env, regno, SRC_OP);
5036 if (err)
5037 return err;
5038
5039 if (arg_type == ARG_ANYTHING) {
5040 if (is_pointer_value(env, regno)) {
5041 verbose(env, "R%d leaks addr into helper function\n",
5042 regno);
5043 return -EACCES;
5044 }
5045 return 0;
5046 }
5047
5048 if (type_is_pkt_pointer(type) &&
5049 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
5050 verbose(env, "helper access to the packet is not allowed\n");
5051 return -EACCES;
5052 }
5053
5054 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5055 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5056 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5057 err = resolve_map_arg_type(env, meta, &arg_type);
5058 if (err)
5059 return err;
5060 }
5061
5062 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5063 /* A NULL register has a SCALAR_VALUE type, so skip
5064 * type checking.
5065 */
5066 goto skip_type_check;
5067
5068 /* We already checked for NULL above */
5069 if (arg_type == ARG_PTR_TO_ALLOC_MEM) {
5070 if (reg->off != 0 || !tnum_is_const(reg->var_off)) {
5071 verbose(env, "helper wants pointer to allocated memory\n");
5072 return -EACCES;
5073 }
5074 }
5075
5076 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
5077 if (err)
5078 return err;
5079
5080 if (type == PTR_TO_CTX) {
5081 err = check_ctx_reg(env, reg, regno);
5082 if (err < 0)
5083 return err;
5084 }
5085
5086 skip_type_check:
5087 if (reg->ref_obj_id) {
5088 if (meta->ref_obj_id) {
5089 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5090 regno, reg->ref_obj_id,
5091 meta->ref_obj_id);
5092 return -EFAULT;
5093 }
5094 meta->ref_obj_id = reg->ref_obj_id;
5095 }
5096
5097 if (arg_type == ARG_CONST_MAP_PTR) {
5098 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
5099 if (meta->map_ptr) {
5100 /* Use map_uid (which is unique id of inner map) to reject:
5101 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5102 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5103 * if (inner_map1 && inner_map2) {
5104 * timer = bpf_map_lookup_elem(inner_map1);
5105 * if (timer)
5106 * // mismatch would have been allowed
5107 * bpf_timer_init(timer, inner_map2);
5108 * }
5109 *
5110 * Comparing map_ptr is enough to distinguish normal and outer maps.
5111 */
5112 if (meta->map_ptr != reg->map_ptr ||
5113 meta->map_uid != reg->map_uid) {
5114 verbose(env,
5115 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5116 meta->map_uid, reg->map_uid);
5117 return -EINVAL;
5118 }
5119 }
5120 meta->map_ptr = reg->map_ptr;
5121 meta->map_uid = reg->map_uid;
5122 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5123 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5124 * check that [key, key + map->key_size) are within
5125 * stack limits and initialized
5126 */
5127 if (!meta->map_ptr) {
5128 /* in function declaration map_ptr must come before
5129 * map_key, so that it's verified and known before
5130 * we have to check map_key here. Otherwise it means
5131 * that kernel subsystem misconfigured verifier
5132 */
5133 verbose(env, "invalid map_ptr to access map->key\n");
5134 return -EACCES;
5135 }
5136 err = check_helper_mem_access(env, regno,
5137 meta->map_ptr->key_size, false,
5138 NULL);
5139 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5140 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5141 !register_is_null(reg)) ||
5142 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
5143 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5144 * check [value, value + map->value_size) validity
5145 */
5146 if (!meta->map_ptr) {
5147 /* kernel subsystem misconfigured verifier */
5148 verbose(env, "invalid map_ptr to access map->value\n");
5149 return -EACCES;
5150 }
5151 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
5152 err = check_helper_mem_access(env, regno,
5153 meta->map_ptr->value_size, false,
5154 meta);
5155 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5156 if (!reg->btf_id) {
5157 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5158 return -EACCES;
5159 }
5160 meta->ret_btf = reg->btf;
5161 meta->ret_btf_id = reg->btf_id;
5162 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5163 if (meta->func_id == BPF_FUNC_spin_lock) {
5164 if (process_spin_lock(env, regno, true))
5165 return -EACCES;
5166 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5167 if (process_spin_lock(env, regno, false))
5168 return -EACCES;
5169 } else {
5170 verbose(env, "verifier internal error\n");
5171 return -EFAULT;
5172 }
5173 } else if (arg_type == ARG_PTR_TO_TIMER) {
5174 if (process_timer_func(env, regno, meta))
5175 return -EACCES;
5176 } else if (arg_type == ARG_PTR_TO_FUNC) {
5177 meta->subprogno = reg->subprogno;
5178 } else if (arg_type_is_mem_ptr(arg_type)) {
5179 /* The access to this pointer is only checked when we hit the
5180 * next is_mem_size argument below.
5181 */
5182 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
5183 } else if (arg_type_is_mem_size(arg_type)) {
5184 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
5185
5186 /* This is used to refine r0 return value bounds for helpers
5187 * that enforce this value as an upper bound on return values.
5188 * See do_refine_retval_range() for helpers that can refine
5189 * the return value. C type of helper is u32 so we pull register
5190 * bound from umax_value however, if negative verifier errors
5191 * out. Only upper bounds can be learned because retval is an
5192 * int type and negative retvals are allowed.
5193 */
5194 meta->msize_max_value = reg->umax_value;
5195
5196 /* The register is SCALAR_VALUE; the access check
5197 * happens using its boundaries.
5198 */
5199 if (!tnum_is_const(reg->var_off))
5200 /* For unprivileged variable accesses, disable raw
5201 * mode so that the program is required to
5202 * initialize all the memory that the helper could
5203 * just partially fill up.
5204 */
5205 meta = NULL;
5206
5207 if (reg->smin_value < 0) {
5208 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
5209 regno);
5210 return -EACCES;
5211 }
5212
5213 if (reg->umin_value == 0) {
5214 err = check_helper_mem_access(env, regno - 1, 0,
5215 zero_size_allowed,
5216 meta);
5217 if (err)
5218 return err;
5219 }
5220
5221 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
5222 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
5223 regno);
5224 return -EACCES;
5225 }
5226 err = check_helper_mem_access(env, regno - 1,
5227 reg->umax_value,
5228 zero_size_allowed, meta);
5229 if (!err)
5230 err = mark_chain_precision(env, regno);
5231 } else if (arg_type_is_alloc_size(arg_type)) {
5232 if (!tnum_is_const(reg->var_off)) {
5233 verbose(env, "R%d is not a known constant'\n",
5234 regno);
5235 return -EACCES;
5236 }
5237 meta->mem_size = reg->var_off.value;
5238 } else if (arg_type_is_int_ptr(arg_type)) {
5239 int size = int_ptr_type_to_size(arg_type);
5240
5241 err = check_helper_mem_access(env, regno, size, false, meta);
5242 if (err)
5243 return err;
5244 err = check_ptr_alignment(env, reg, 0, size, true);
5245 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5246 struct bpf_map *map = reg->map_ptr;
5247 int map_off;
5248 u64 map_addr;
5249 char *str_ptr;
5250
5251 if (!bpf_map_is_rdonly(map)) {
5252 verbose(env, "R%d does not point to a readonly map'\n", regno);
5253 return -EACCES;
5254 }
5255
5256 if (!tnum_is_const(reg->var_off)) {
5257 verbose(env, "R%d is not a constant address'\n", regno);
5258 return -EACCES;
5259 }
5260
5261 if (!map->ops->map_direct_value_addr) {
5262 verbose(env, "no direct value access support for this map type\n");
5263 return -EACCES;
5264 }
5265
5266 err = check_map_access(env, regno, reg->off,
5267 map->value_size - reg->off, false);
5268 if (err)
5269 return err;
5270
5271 map_off = reg->off + reg->var_off.value;
5272 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5273 if (err) {
5274 verbose(env, "direct value access on string failed\n");
5275 return err;
5276 }
5277
5278 str_ptr = (char *)(long)(map_addr);
5279 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5280 verbose(env, "string is not zero-terminated\n");
5281 return -EINVAL;
5282 }
5283 }
5284
5285 return err;
5286 }
5287
5288 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5289 {
5290 enum bpf_attach_type eatype = env->prog->expected_attach_type;
5291 enum bpf_prog_type type = resolve_prog_type(env->prog);
5292
5293 if (func_id != BPF_FUNC_map_update_elem)
5294 return false;
5295
5296 /* It's not possible to get access to a locked struct sock in these
5297 * contexts, so updating is safe.
5298 */
5299 switch (type) {
5300 case BPF_PROG_TYPE_TRACING:
5301 if (eatype == BPF_TRACE_ITER)
5302 return true;
5303 break;
5304 case BPF_PROG_TYPE_SOCKET_FILTER:
5305 case BPF_PROG_TYPE_SCHED_CLS:
5306 case BPF_PROG_TYPE_SCHED_ACT:
5307 case BPF_PROG_TYPE_XDP:
5308 case BPF_PROG_TYPE_SK_REUSEPORT:
5309 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5310 case BPF_PROG_TYPE_SK_LOOKUP:
5311 return true;
5312 default:
5313 break;
5314 }
5315
5316 verbose(env, "cannot update sockmap in this context\n");
5317 return false;
5318 }
5319
5320 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5321 {
5322 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5323 }
5324
5325 static int check_map_func_compatibility(struct bpf_verifier_env *env,
5326 struct bpf_map *map, int func_id)
5327 {
5328 if (!map)
5329 return 0;
5330
5331 /* We need a two way check, first is from map perspective ... */
5332 switch (map->map_type) {
5333 case BPF_MAP_TYPE_PROG_ARRAY:
5334 if (func_id != BPF_FUNC_tail_call)
5335 goto error;
5336 break;
5337 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5338 if (func_id != BPF_FUNC_perf_event_read &&
5339 func_id != BPF_FUNC_perf_event_output &&
5340 func_id != BPF_FUNC_skb_output &&
5341 func_id != BPF_FUNC_perf_event_read_value &&
5342 func_id != BPF_FUNC_xdp_output)
5343 goto error;
5344 break;
5345 case BPF_MAP_TYPE_RINGBUF:
5346 if (func_id != BPF_FUNC_ringbuf_output &&
5347 func_id != BPF_FUNC_ringbuf_reserve &&
5348 func_id != BPF_FUNC_ringbuf_query)
5349 goto error;
5350 break;
5351 case BPF_MAP_TYPE_STACK_TRACE:
5352 if (func_id != BPF_FUNC_get_stackid)
5353 goto error;
5354 break;
5355 case BPF_MAP_TYPE_CGROUP_ARRAY:
5356 if (func_id != BPF_FUNC_skb_under_cgroup &&
5357 func_id != BPF_FUNC_current_task_under_cgroup)
5358 goto error;
5359 break;
5360 case BPF_MAP_TYPE_CGROUP_STORAGE:
5361 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
5362 if (func_id != BPF_FUNC_get_local_storage)
5363 goto error;
5364 break;
5365 case BPF_MAP_TYPE_DEVMAP:
5366 case BPF_MAP_TYPE_DEVMAP_HASH:
5367 if (func_id != BPF_FUNC_redirect_map &&
5368 func_id != BPF_FUNC_map_lookup_elem)
5369 goto error;
5370 break;
5371 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5372 * appear.
5373 */
5374 case BPF_MAP_TYPE_CPUMAP:
5375 if (func_id != BPF_FUNC_redirect_map)
5376 goto error;
5377 break;
5378 case BPF_MAP_TYPE_XSKMAP:
5379 if (func_id != BPF_FUNC_redirect_map &&
5380 func_id != BPF_FUNC_map_lookup_elem)
5381 goto error;
5382 break;
5383 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
5384 case BPF_MAP_TYPE_HASH_OF_MAPS:
5385 if (func_id != BPF_FUNC_map_lookup_elem)
5386 goto error;
5387 break;
5388 case BPF_MAP_TYPE_SOCKMAP:
5389 if (func_id != BPF_FUNC_sk_redirect_map &&
5390 func_id != BPF_FUNC_sock_map_update &&
5391 func_id != BPF_FUNC_map_delete_elem &&
5392 func_id != BPF_FUNC_msg_redirect_map &&
5393 func_id != BPF_FUNC_sk_select_reuseport &&
5394 func_id != BPF_FUNC_map_lookup_elem &&
5395 !may_update_sockmap(env, func_id))
5396 goto error;
5397 break;
5398 case BPF_MAP_TYPE_SOCKHASH:
5399 if (func_id != BPF_FUNC_sk_redirect_hash &&
5400 func_id != BPF_FUNC_sock_hash_update &&
5401 func_id != BPF_FUNC_map_delete_elem &&
5402 func_id != BPF_FUNC_msg_redirect_hash &&
5403 func_id != BPF_FUNC_sk_select_reuseport &&
5404 func_id != BPF_FUNC_map_lookup_elem &&
5405 !may_update_sockmap(env, func_id))
5406 goto error;
5407 break;
5408 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5409 if (func_id != BPF_FUNC_sk_select_reuseport)
5410 goto error;
5411 break;
5412 case BPF_MAP_TYPE_QUEUE:
5413 case BPF_MAP_TYPE_STACK:
5414 if (func_id != BPF_FUNC_map_peek_elem &&
5415 func_id != BPF_FUNC_map_pop_elem &&
5416 func_id != BPF_FUNC_map_push_elem)
5417 goto error;
5418 break;
5419 case BPF_MAP_TYPE_SK_STORAGE:
5420 if (func_id != BPF_FUNC_sk_storage_get &&
5421 func_id != BPF_FUNC_sk_storage_delete)
5422 goto error;
5423 break;
5424 case BPF_MAP_TYPE_INODE_STORAGE:
5425 if (func_id != BPF_FUNC_inode_storage_get &&
5426 func_id != BPF_FUNC_inode_storage_delete)
5427 goto error;
5428 break;
5429 case BPF_MAP_TYPE_TASK_STORAGE:
5430 if (func_id != BPF_FUNC_task_storage_get &&
5431 func_id != BPF_FUNC_task_storage_delete)
5432 goto error;
5433 break;
5434 default:
5435 break;
5436 }
5437
5438 /* ... and second from the function itself. */
5439 switch (func_id) {
5440 case BPF_FUNC_tail_call:
5441 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5442 goto error;
5443 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5444 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5445 return -EINVAL;
5446 }
5447 break;
5448 case BPF_FUNC_perf_event_read:
5449 case BPF_FUNC_perf_event_output:
5450 case BPF_FUNC_perf_event_read_value:
5451 case BPF_FUNC_skb_output:
5452 case BPF_FUNC_xdp_output:
5453 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5454 goto error;
5455 break;
5456 case BPF_FUNC_ringbuf_output:
5457 case BPF_FUNC_ringbuf_reserve:
5458 case BPF_FUNC_ringbuf_query:
5459 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5460 goto error;
5461 break;
5462 case BPF_FUNC_get_stackid:
5463 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5464 goto error;
5465 break;
5466 case BPF_FUNC_current_task_under_cgroup:
5467 case BPF_FUNC_skb_under_cgroup:
5468 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5469 goto error;
5470 break;
5471 case BPF_FUNC_redirect_map:
5472 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5473 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5474 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5475 map->map_type != BPF_MAP_TYPE_XSKMAP)
5476 goto error;
5477 break;
5478 case BPF_FUNC_sk_redirect_map:
5479 case BPF_FUNC_msg_redirect_map:
5480 case BPF_FUNC_sock_map_update:
5481 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5482 goto error;
5483 break;
5484 case BPF_FUNC_sk_redirect_hash:
5485 case BPF_FUNC_msg_redirect_hash:
5486 case BPF_FUNC_sock_hash_update:
5487 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5488 goto error;
5489 break;
5490 case BPF_FUNC_get_local_storage:
5491 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5492 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5493 goto error;
5494 break;
5495 case BPF_FUNC_sk_select_reuseport:
5496 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5497 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5498 map->map_type != BPF_MAP_TYPE_SOCKHASH)
5499 goto error;
5500 break;
5501 case BPF_FUNC_map_peek_elem:
5502 case BPF_FUNC_map_pop_elem:
5503 case BPF_FUNC_map_push_elem:
5504 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5505 map->map_type != BPF_MAP_TYPE_STACK)
5506 goto error;
5507 break;
5508 case BPF_FUNC_sk_storage_get:
5509 case BPF_FUNC_sk_storage_delete:
5510 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5511 goto error;
5512 break;
5513 case BPF_FUNC_inode_storage_get:
5514 case BPF_FUNC_inode_storage_delete:
5515 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5516 goto error;
5517 break;
5518 case BPF_FUNC_task_storage_get:
5519 case BPF_FUNC_task_storage_delete:
5520 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5521 goto error;
5522 break;
5523 default:
5524 break;
5525 }
5526
5527 return 0;
5528 error:
5529 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5530 map->map_type, func_id_name(func_id), func_id);
5531 return -EINVAL;
5532 }
5533
5534 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5535 {
5536 int count = 0;
5537
5538 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5539 count++;
5540 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5541 count++;
5542 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5543 count++;
5544 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5545 count++;
5546 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5547 count++;
5548
5549 /* We only support one arg being in raw mode at the moment,
5550 * which is sufficient for the helper functions we have
5551 * right now.
5552 */
5553 return count <= 1;
5554 }
5555
5556 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5557 enum bpf_arg_type arg_next)
5558 {
5559 return (arg_type_is_mem_ptr(arg_curr) &&
5560 !arg_type_is_mem_size(arg_next)) ||
5561 (!arg_type_is_mem_ptr(arg_curr) &&
5562 arg_type_is_mem_size(arg_next));
5563 }
5564
5565 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5566 {
5567 /* bpf_xxx(..., buf, len) call will access 'len'
5568 * bytes from memory 'buf'. Both arg types need
5569 * to be paired, so make sure there's no buggy
5570 * helper function specification.
5571 */
5572 if (arg_type_is_mem_size(fn->arg1_type) ||
5573 arg_type_is_mem_ptr(fn->arg5_type) ||
5574 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5575 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5576 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5577 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5578 return false;
5579
5580 return true;
5581 }
5582
5583 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5584 {
5585 int count = 0;
5586
5587 if (arg_type_may_be_refcounted(fn->arg1_type))
5588 count++;
5589 if (arg_type_may_be_refcounted(fn->arg2_type))
5590 count++;
5591 if (arg_type_may_be_refcounted(fn->arg3_type))
5592 count++;
5593 if (arg_type_may_be_refcounted(fn->arg4_type))
5594 count++;
5595 if (arg_type_may_be_refcounted(fn->arg5_type))
5596 count++;
5597
5598 /* A reference acquiring function cannot acquire
5599 * another refcounted ptr.
5600 */
5601 if (may_be_acquire_function(func_id) && count)
5602 return false;
5603
5604 /* We only support one arg being unreferenced at the moment,
5605 * which is sufficient for the helper functions we have right now.
5606 */
5607 return count <= 1;
5608 }
5609
5610 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5611 {
5612 int i;
5613
5614 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5615 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5616 return false;
5617
5618 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5619 return false;
5620 }
5621
5622 return true;
5623 }
5624
5625 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5626 {
5627 return check_raw_mode_ok(fn) &&
5628 check_arg_pair_ok(fn) &&
5629 check_btf_id_ok(fn) &&
5630 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5631 }
5632
5633 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5634 * are now invalid, so turn them into unknown SCALAR_VALUE.
5635 */
5636 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5637 struct bpf_func_state *state)
5638 {
5639 struct bpf_reg_state *regs = state->regs, *reg;
5640 int i;
5641
5642 for (i = 0; i < MAX_BPF_REG; i++)
5643 if (reg_is_pkt_pointer_any(&regs[i]))
5644 mark_reg_unknown(env, regs, i);
5645
5646 bpf_for_each_spilled_reg(i, state, reg) {
5647 if (!reg)
5648 continue;
5649 if (reg_is_pkt_pointer_any(reg))
5650 __mark_reg_unknown(env, reg);
5651 }
5652 }
5653
5654 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5655 {
5656 struct bpf_verifier_state *vstate = env->cur_state;
5657 int i;
5658
5659 for (i = 0; i <= vstate->curframe; i++)
5660 __clear_all_pkt_pointers(env, vstate->frame[i]);
5661 }
5662
5663 enum {
5664 AT_PKT_END = -1,
5665 BEYOND_PKT_END = -2,
5666 };
5667
5668 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5669 {
5670 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5671 struct bpf_reg_state *reg = &state->regs[regn];
5672
5673 if (reg->type != PTR_TO_PACKET)
5674 /* PTR_TO_PACKET_META is not supported yet */
5675 return;
5676
5677 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5678 * How far beyond pkt_end it goes is unknown.
5679 * if (!range_open) it's the case of pkt >= pkt_end
5680 * if (range_open) it's the case of pkt > pkt_end
5681 * hence this pointer is at least 1 byte bigger than pkt_end
5682 */
5683 if (range_open)
5684 reg->range = BEYOND_PKT_END;
5685 else
5686 reg->range = AT_PKT_END;
5687 }
5688
5689 static void release_reg_references(struct bpf_verifier_env *env,
5690 struct bpf_func_state *state,
5691 int ref_obj_id)
5692 {
5693 struct bpf_reg_state *regs = state->regs, *reg;
5694 int i;
5695
5696 for (i = 0; i < MAX_BPF_REG; i++)
5697 if (regs[i].ref_obj_id == ref_obj_id)
5698 mark_reg_unknown(env, regs, i);
5699
5700 bpf_for_each_spilled_reg(i, state, reg) {
5701 if (!reg)
5702 continue;
5703 if (reg->ref_obj_id == ref_obj_id)
5704 __mark_reg_unknown(env, reg);
5705 }
5706 }
5707
5708 /* The pointer with the specified id has released its reference to kernel
5709 * resources. Identify all copies of the same pointer and clear the reference.
5710 */
5711 static int release_reference(struct bpf_verifier_env *env,
5712 int ref_obj_id)
5713 {
5714 struct bpf_verifier_state *vstate = env->cur_state;
5715 int err;
5716 int i;
5717
5718 err = release_reference_state(cur_func(env), ref_obj_id);
5719 if (err)
5720 return err;
5721
5722 for (i = 0; i <= vstate->curframe; i++)
5723 release_reg_references(env, vstate->frame[i], ref_obj_id);
5724
5725 return 0;
5726 }
5727
5728 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5729 struct bpf_reg_state *regs)
5730 {
5731 int i;
5732
5733 /* after the call registers r0 - r5 were scratched */
5734 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5735 mark_reg_not_init(env, regs, caller_saved[i]);
5736 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5737 }
5738 }
5739
5740 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5741 struct bpf_func_state *caller,
5742 struct bpf_func_state *callee,
5743 int insn_idx);
5744
5745 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5746 int *insn_idx, int subprog,
5747 set_callee_state_fn set_callee_state_cb)
5748 {
5749 struct bpf_verifier_state *state = env->cur_state;
5750 struct bpf_func_info_aux *func_info_aux;
5751 struct bpf_func_state *caller, *callee;
5752 int err;
5753 bool is_global = false;
5754
5755 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5756 verbose(env, "the call stack of %d frames is too deep\n",
5757 state->curframe + 2);
5758 return -E2BIG;
5759 }
5760
5761 caller = state->frame[state->curframe];
5762 if (state->frame[state->curframe + 1]) {
5763 verbose(env, "verifier bug. Frame %d already allocated\n",
5764 state->curframe + 1);
5765 return -EFAULT;
5766 }
5767
5768 func_info_aux = env->prog->aux->func_info_aux;
5769 if (func_info_aux)
5770 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5771 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
5772 if (err == -EFAULT)
5773 return err;
5774 if (is_global) {
5775 if (err) {
5776 verbose(env, "Caller passes invalid args into func#%d\n",
5777 subprog);
5778 return err;
5779 } else {
5780 if (env->log.level & BPF_LOG_LEVEL)
5781 verbose(env,
5782 "Func#%d is global and valid. Skipping.\n",
5783 subprog);
5784 clear_caller_saved_regs(env, caller->regs);
5785
5786 /* All global functions return a 64-bit SCALAR_VALUE */
5787 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5788 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5789
5790 /* continue with next insn after call */
5791 return 0;
5792 }
5793 }
5794
5795 if (insn->code == (BPF_JMP | BPF_CALL) &&
5796 insn->src_reg == 0 &&
5797 insn->imm == BPF_FUNC_timer_set_callback) {
5798 struct bpf_verifier_state *async_cb;
5799
5800 /* there is no real recursion here. timer callbacks are async */
5801 env->subprog_info[subprog].is_async_cb = true;
5802 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
5803 *insn_idx, subprog);
5804 if (!async_cb)
5805 return -EFAULT;
5806 callee = async_cb->frame[0];
5807 callee->async_entry_cnt = caller->async_entry_cnt + 1;
5808
5809 /* Convert bpf_timer_set_callback() args into timer callback args */
5810 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5811 if (err)
5812 return err;
5813
5814 clear_caller_saved_regs(env, caller->regs);
5815 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5816 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5817 /* continue with next insn after call */
5818 return 0;
5819 }
5820
5821 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5822 if (!callee)
5823 return -ENOMEM;
5824 state->frame[state->curframe + 1] = callee;
5825
5826 /* callee cannot access r0, r6 - r9 for reading and has to write
5827 * into its own stack before reading from it.
5828 * callee can read/write into caller's stack
5829 */
5830 init_func_state(env, callee,
5831 /* remember the callsite, it will be used by bpf_exit */
5832 *insn_idx /* callsite */,
5833 state->curframe + 1 /* frameno within this callchain */,
5834 subprog /* subprog number within this prog */);
5835
5836 /* Transfer references to the callee */
5837 err = copy_reference_state(callee, caller);
5838 if (err)
5839 return err;
5840
5841 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5842 if (err)
5843 return err;
5844
5845 clear_caller_saved_regs(env, caller->regs);
5846
5847 /* only increment it after check_reg_arg() finished */
5848 state->curframe++;
5849
5850 /* and go analyze first insn of the callee */
5851 *insn_idx = env->subprog_info[subprog].start - 1;
5852
5853 if (env->log.level & BPF_LOG_LEVEL) {
5854 verbose(env, "caller:\n");
5855 print_verifier_state(env, caller);
5856 verbose(env, "callee:\n");
5857 print_verifier_state(env, callee);
5858 }
5859 return 0;
5860 }
5861
5862 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5863 struct bpf_func_state *caller,
5864 struct bpf_func_state *callee)
5865 {
5866 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5867 * void *callback_ctx, u64 flags);
5868 * callback_fn(struct bpf_map *map, void *key, void *value,
5869 * void *callback_ctx);
5870 */
5871 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5872
5873 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5874 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5875 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5876
5877 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5878 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5879 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5880
5881 /* pointer to stack or null */
5882 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5883
5884 /* unused */
5885 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5886 return 0;
5887 }
5888
5889 static int set_callee_state(struct bpf_verifier_env *env,
5890 struct bpf_func_state *caller,
5891 struct bpf_func_state *callee, int insn_idx)
5892 {
5893 int i;
5894
5895 /* copy r1 - r5 args that callee can access. The copy includes parent
5896 * pointers, which connects us up to the liveness chain
5897 */
5898 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5899 callee->regs[i] = caller->regs[i];
5900 return 0;
5901 }
5902
5903 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5904 int *insn_idx)
5905 {
5906 int subprog, target_insn;
5907
5908 target_insn = *insn_idx + insn->imm + 1;
5909 subprog = find_subprog(env, target_insn);
5910 if (subprog < 0) {
5911 verbose(env, "verifier bug. No program starts at insn %d\n",
5912 target_insn);
5913 return -EFAULT;
5914 }
5915
5916 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5917 }
5918
5919 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5920 struct bpf_func_state *caller,
5921 struct bpf_func_state *callee,
5922 int insn_idx)
5923 {
5924 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5925 struct bpf_map *map;
5926 int err;
5927
5928 if (bpf_map_ptr_poisoned(insn_aux)) {
5929 verbose(env, "tail_call abusing map_ptr\n");
5930 return -EINVAL;
5931 }
5932
5933 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5934 if (!map->ops->map_set_for_each_callback_args ||
5935 !map->ops->map_for_each_callback) {
5936 verbose(env, "callback function not allowed for map\n");
5937 return -ENOTSUPP;
5938 }
5939
5940 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5941 if (err)
5942 return err;
5943
5944 callee->in_callback_fn = true;
5945 return 0;
5946 }
5947
5948 static int set_timer_callback_state(struct bpf_verifier_env *env,
5949 struct bpf_func_state *caller,
5950 struct bpf_func_state *callee,
5951 int insn_idx)
5952 {
5953 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
5954
5955 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
5956 * callback_fn(struct bpf_map *map, void *key, void *value);
5957 */
5958 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
5959 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
5960 callee->regs[BPF_REG_1].map_ptr = map_ptr;
5961
5962 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5963 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5964 callee->regs[BPF_REG_2].map_ptr = map_ptr;
5965
5966 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5967 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5968 callee->regs[BPF_REG_3].map_ptr = map_ptr;
5969
5970 /* unused */
5971 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
5972 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5973 callee->in_async_callback_fn = true;
5974 return 0;
5975 }
5976
5977 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5978 {
5979 struct bpf_verifier_state *state = env->cur_state;
5980 struct bpf_func_state *caller, *callee;
5981 struct bpf_reg_state *r0;
5982 int err;
5983
5984 callee = state->frame[state->curframe];
5985 r0 = &callee->regs[BPF_REG_0];
5986 if (r0->type == PTR_TO_STACK) {
5987 /* technically it's ok to return caller's stack pointer
5988 * (or caller's caller's pointer) back to the caller,
5989 * since these pointers are valid. Only current stack
5990 * pointer will be invalid as soon as function exits,
5991 * but let's be conservative
5992 */
5993 verbose(env, "cannot return stack pointer to the caller\n");
5994 return -EINVAL;
5995 }
5996
5997 state->curframe--;
5998 caller = state->frame[state->curframe];
5999 if (callee->in_callback_fn) {
6000 /* enforce R0 return value range [0, 1]. */
6001 struct tnum range = tnum_range(0, 1);
6002
6003 if (r0->type != SCALAR_VALUE) {
6004 verbose(env, "R0 not a scalar value\n");
6005 return -EACCES;
6006 }
6007 if (!tnum_in(range, r0->var_off)) {
6008 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6009 return -EINVAL;
6010 }
6011 } else {
6012 /* return to the caller whatever r0 had in the callee */
6013 caller->regs[BPF_REG_0] = *r0;
6014 }
6015
6016 /* Transfer references to the caller */
6017 err = copy_reference_state(caller, callee);
6018 if (err)
6019 return err;
6020
6021 *insn_idx = callee->callsite + 1;
6022 if (env->log.level & BPF_LOG_LEVEL) {
6023 verbose(env, "returning from callee:\n");
6024 print_verifier_state(env, callee);
6025 verbose(env, "to caller at %d:\n", *insn_idx);
6026 print_verifier_state(env, caller);
6027 }
6028 /* clear everything in the callee */
6029 free_func_state(callee);
6030 state->frame[state->curframe + 1] = NULL;
6031 return 0;
6032 }
6033
6034 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6035 int func_id,
6036 struct bpf_call_arg_meta *meta)
6037 {
6038 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6039
6040 if (ret_type != RET_INTEGER ||
6041 (func_id != BPF_FUNC_get_stack &&
6042 func_id != BPF_FUNC_get_task_stack &&
6043 func_id != BPF_FUNC_probe_read_str &&
6044 func_id != BPF_FUNC_probe_read_kernel_str &&
6045 func_id != BPF_FUNC_probe_read_user_str))
6046 return;
6047
6048 ret_reg->smax_value = meta->msize_max_value;
6049 ret_reg->s32_max_value = meta->msize_max_value;
6050 ret_reg->smin_value = -MAX_ERRNO;
6051 ret_reg->s32_min_value = -MAX_ERRNO;
6052 __reg_deduce_bounds(ret_reg);
6053 __reg_bound_offset(ret_reg);
6054 __update_reg_bounds(ret_reg);
6055 }
6056
6057 static int
6058 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6059 int func_id, int insn_idx)
6060 {
6061 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6062 struct bpf_map *map = meta->map_ptr;
6063
6064 if (func_id != BPF_FUNC_tail_call &&
6065 func_id != BPF_FUNC_map_lookup_elem &&
6066 func_id != BPF_FUNC_map_update_elem &&
6067 func_id != BPF_FUNC_map_delete_elem &&
6068 func_id != BPF_FUNC_map_push_elem &&
6069 func_id != BPF_FUNC_map_pop_elem &&
6070 func_id != BPF_FUNC_map_peek_elem &&
6071 func_id != BPF_FUNC_for_each_map_elem &&
6072 func_id != BPF_FUNC_redirect_map)
6073 return 0;
6074
6075 if (map == NULL) {
6076 verbose(env, "kernel subsystem misconfigured verifier\n");
6077 return -EINVAL;
6078 }
6079
6080 /* In case of read-only, some additional restrictions
6081 * need to be applied in order to prevent altering the
6082 * state of the map from program side.
6083 */
6084 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6085 (func_id == BPF_FUNC_map_delete_elem ||
6086 func_id == BPF_FUNC_map_update_elem ||
6087 func_id == BPF_FUNC_map_push_elem ||
6088 func_id == BPF_FUNC_map_pop_elem)) {
6089 verbose(env, "write into map forbidden\n");
6090 return -EACCES;
6091 }
6092
6093 if (!BPF_MAP_PTR(aux->map_ptr_state))
6094 bpf_map_ptr_store(aux, meta->map_ptr,
6095 !meta->map_ptr->bypass_spec_v1);
6096 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
6097 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
6098 !meta->map_ptr->bypass_spec_v1);
6099 return 0;
6100 }
6101
6102 static int
6103 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6104 int func_id, int insn_idx)
6105 {
6106 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6107 struct bpf_reg_state *regs = cur_regs(env), *reg;
6108 struct bpf_map *map = meta->map_ptr;
6109 struct tnum range;
6110 u64 val;
6111 int err;
6112
6113 if (func_id != BPF_FUNC_tail_call)
6114 return 0;
6115 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6116 verbose(env, "kernel subsystem misconfigured verifier\n");
6117 return -EINVAL;
6118 }
6119
6120 range = tnum_range(0, map->max_entries - 1);
6121 reg = &regs[BPF_REG_3];
6122
6123 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6124 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6125 return 0;
6126 }
6127
6128 err = mark_chain_precision(env, BPF_REG_3);
6129 if (err)
6130 return err;
6131
6132 val = reg->var_off.value;
6133 if (bpf_map_key_unseen(aux))
6134 bpf_map_key_store(aux, val);
6135 else if (!bpf_map_key_poisoned(aux) &&
6136 bpf_map_key_immediate(aux) != val)
6137 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6138 return 0;
6139 }
6140
6141 static int check_reference_leak(struct bpf_verifier_env *env)
6142 {
6143 struct bpf_func_state *state = cur_func(env);
6144 int i;
6145
6146 for (i = 0; i < state->acquired_refs; i++) {
6147 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6148 state->refs[i].id, state->refs[i].insn_idx);
6149 }
6150 return state->acquired_refs ? -EINVAL : 0;
6151 }
6152
6153 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6154 struct bpf_reg_state *regs)
6155 {
6156 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6157 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6158 struct bpf_map *fmt_map = fmt_reg->map_ptr;
6159 int err, fmt_map_off, num_args;
6160 u64 fmt_addr;
6161 char *fmt;
6162
6163 /* data must be an array of u64 */
6164 if (data_len_reg->var_off.value % 8)
6165 return -EINVAL;
6166 num_args = data_len_reg->var_off.value / 8;
6167
6168 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6169 * and map_direct_value_addr is set.
6170 */
6171 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6172 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6173 fmt_map_off);
6174 if (err) {
6175 verbose(env, "verifier bug\n");
6176 return -EFAULT;
6177 }
6178 fmt = (char *)(long)fmt_addr + fmt_map_off;
6179
6180 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6181 * can focus on validating the format specifiers.
6182 */
6183 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
6184 if (err < 0)
6185 verbose(env, "Invalid format string\n");
6186
6187 return err;
6188 }
6189
6190 static int check_get_func_ip(struct bpf_verifier_env *env)
6191 {
6192 enum bpf_attach_type eatype = env->prog->expected_attach_type;
6193 enum bpf_prog_type type = resolve_prog_type(env->prog);
6194 int func_id = BPF_FUNC_get_func_ip;
6195
6196 if (type == BPF_PROG_TYPE_TRACING) {
6197 if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT &&
6198 eatype != BPF_MODIFY_RETURN) {
6199 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6200 func_id_name(func_id), func_id);
6201 return -ENOTSUPP;
6202 }
6203 return 0;
6204 } else if (type == BPF_PROG_TYPE_KPROBE) {
6205 return 0;
6206 }
6207
6208 verbose(env, "func %s#%d not supported for program type %d\n",
6209 func_id_name(func_id), func_id, type);
6210 return -ENOTSUPP;
6211 }
6212
6213 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6214 int *insn_idx_p)
6215 {
6216 const struct bpf_func_proto *fn = NULL;
6217 struct bpf_reg_state *regs;
6218 struct bpf_call_arg_meta meta;
6219 int insn_idx = *insn_idx_p;
6220 bool changes_data;
6221 int i, err, func_id;
6222
6223 /* find function prototype */
6224 func_id = insn->imm;
6225 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
6226 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6227 func_id);
6228 return -EINVAL;
6229 }
6230
6231 if (env->ops->get_func_proto)
6232 fn = env->ops->get_func_proto(func_id, env->prog);
6233 if (!fn) {
6234 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6235 func_id);
6236 return -EINVAL;
6237 }
6238
6239 /* eBPF programs must be GPL compatible to use GPL-ed functions */
6240 if (!env->prog->gpl_compatible && fn->gpl_only) {
6241 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
6242 return -EINVAL;
6243 }
6244
6245 if (fn->allowed && !fn->allowed(env->prog)) {
6246 verbose(env, "helper call is not allowed in probe\n");
6247 return -EINVAL;
6248 }
6249
6250 /* With LD_ABS/IND some JITs save/restore skb from r1. */
6251 changes_data = bpf_helper_changes_pkt_data(fn->func);
6252 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6253 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6254 func_id_name(func_id), func_id);
6255 return -EINVAL;
6256 }
6257
6258 memset(&meta, 0, sizeof(meta));
6259 meta.pkt_access = fn->pkt_access;
6260
6261 err = check_func_proto(fn, func_id);
6262 if (err) {
6263 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
6264 func_id_name(func_id), func_id);
6265 return err;
6266 }
6267
6268 meta.func_id = func_id;
6269 /* check args */
6270 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6271 err = check_func_arg(env, i, &meta, fn);
6272 if (err)
6273 return err;
6274 }
6275
6276 err = record_func_map(env, &meta, func_id, insn_idx);
6277 if (err)
6278 return err;
6279
6280 err = record_func_key(env, &meta, func_id, insn_idx);
6281 if (err)
6282 return err;
6283
6284 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6285 * is inferred from register state.
6286 */
6287 for (i = 0; i < meta.access_size; i++) {
6288 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6289 BPF_WRITE, -1, false);
6290 if (err)
6291 return err;
6292 }
6293
6294 if (func_id == BPF_FUNC_tail_call) {
6295 err = check_reference_leak(env);
6296 if (err) {
6297 verbose(env, "tail_call would lead to reference leak\n");
6298 return err;
6299 }
6300 } else if (is_release_function(func_id)) {
6301 err = release_reference(env, meta.ref_obj_id);
6302 if (err) {
6303 verbose(env, "func %s#%d reference has not been acquired before\n",
6304 func_id_name(func_id), func_id);
6305 return err;
6306 }
6307 }
6308
6309 regs = cur_regs(env);
6310
6311 /* check that flags argument in get_local_storage(map, flags) is 0,
6312 * this is required because get_local_storage() can't return an error.
6313 */
6314 if (func_id == BPF_FUNC_get_local_storage &&
6315 !register_is_null(&regs[BPF_REG_2])) {
6316 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6317 return -EINVAL;
6318 }
6319
6320 if (func_id == BPF_FUNC_for_each_map_elem) {
6321 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6322 set_map_elem_callback_state);
6323 if (err < 0)
6324 return -EINVAL;
6325 }
6326
6327 if (func_id == BPF_FUNC_timer_set_callback) {
6328 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6329 set_timer_callback_state);
6330 if (err < 0)
6331 return -EINVAL;
6332 }
6333
6334 if (func_id == BPF_FUNC_snprintf) {
6335 err = check_bpf_snprintf_call(env, regs);
6336 if (err < 0)
6337 return err;
6338 }
6339
6340 /* reset caller saved regs */
6341 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6342 mark_reg_not_init(env, regs, caller_saved[i]);
6343 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6344 }
6345
6346 /* helper call returns 64-bit value. */
6347 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6348
6349 /* update return register (already marked as written above) */
6350 if (fn->ret_type == RET_INTEGER) {
6351 /* sets type to SCALAR_VALUE */
6352 mark_reg_unknown(env, regs, BPF_REG_0);
6353 } else if (fn->ret_type == RET_VOID) {
6354 regs[BPF_REG_0].type = NOT_INIT;
6355 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6356 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6357 /* There is no offset yet applied, variable or fixed */
6358 mark_reg_known_zero(env, regs, BPF_REG_0);
6359 /* remember map_ptr, so that check_map_access()
6360 * can check 'value_size' boundary of memory access
6361 * to map element returned from bpf_map_lookup_elem()
6362 */
6363 if (meta.map_ptr == NULL) {
6364 verbose(env,
6365 "kernel subsystem misconfigured verifier\n");
6366 return -EINVAL;
6367 }
6368 regs[BPF_REG_0].map_ptr = meta.map_ptr;
6369 regs[BPF_REG_0].map_uid = meta.map_uid;
6370 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6371 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
6372 if (map_value_has_spin_lock(meta.map_ptr))
6373 regs[BPF_REG_0].id = ++env->id_gen;
6374 } else {
6375 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
6376 }
6377 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6378 mark_reg_known_zero(env, regs, BPF_REG_0);
6379 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
6380 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6381 mark_reg_known_zero(env, regs, BPF_REG_0);
6382 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
6383 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6384 mark_reg_known_zero(env, regs, BPF_REG_0);
6385 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
6386 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6387 mark_reg_known_zero(env, regs, BPF_REG_0);
6388 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
6389 regs[BPF_REG_0].mem_size = meta.mem_size;
6390 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6391 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
6392 const struct btf_type *t;
6393
6394 mark_reg_known_zero(env, regs, BPF_REG_0);
6395 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
6396 if (!btf_type_is_struct(t)) {
6397 u32 tsize;
6398 const struct btf_type *ret;
6399 const char *tname;
6400
6401 /* resolve the type size of ksym. */
6402 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
6403 if (IS_ERR(ret)) {
6404 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
6405 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6406 tname, PTR_ERR(ret));
6407 return -EINVAL;
6408 }
6409 regs[BPF_REG_0].type =
6410 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6411 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
6412 regs[BPF_REG_0].mem_size = tsize;
6413 } else {
6414 regs[BPF_REG_0].type =
6415 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6416 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
6417 regs[BPF_REG_0].btf = meta.ret_btf;
6418 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6419 }
6420 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6421 fn->ret_type == RET_PTR_TO_BTF_ID) {
6422 int ret_btf_id;
6423
6424 mark_reg_known_zero(env, regs, BPF_REG_0);
6425 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6426 PTR_TO_BTF_ID :
6427 PTR_TO_BTF_ID_OR_NULL;
6428 ret_btf_id = *fn->ret_btf_id;
6429 if (ret_btf_id == 0) {
6430 verbose(env, "invalid return type %d of func %s#%d\n",
6431 fn->ret_type, func_id_name(func_id), func_id);
6432 return -EINVAL;
6433 }
6434 /* current BPF helper definitions are only coming from
6435 * built-in code with type IDs from vmlinux BTF
6436 */
6437 regs[BPF_REG_0].btf = btf_vmlinux;
6438 regs[BPF_REG_0].btf_id = ret_btf_id;
6439 } else {
6440 verbose(env, "unknown return type %d of func %s#%d\n",
6441 fn->ret_type, func_id_name(func_id), func_id);
6442 return -EINVAL;
6443 }
6444
6445 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6446 regs[BPF_REG_0].id = ++env->id_gen;
6447
6448 if (is_ptr_cast_function(func_id)) {
6449 /* For release_reference() */
6450 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
6451 } else if (is_acquire_function(func_id, meta.map_ptr)) {
6452 int id = acquire_reference_state(env, insn_idx);
6453
6454 if (id < 0)
6455 return id;
6456 /* For mark_ptr_or_null_reg() */
6457 regs[BPF_REG_0].id = id;
6458 /* For release_reference() */
6459 regs[BPF_REG_0].ref_obj_id = id;
6460 }
6461
6462 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6463
6464 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
6465 if (err)
6466 return err;
6467
6468 if ((func_id == BPF_FUNC_get_stack ||
6469 func_id == BPF_FUNC_get_task_stack) &&
6470 !env->prog->has_callchain_buf) {
6471 const char *err_str;
6472
6473 #ifdef CONFIG_PERF_EVENTS
6474 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6475 err_str = "cannot get callchain buffer for func %s#%d\n";
6476 #else
6477 err = -ENOTSUPP;
6478 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6479 #endif
6480 if (err) {
6481 verbose(env, err_str, func_id_name(func_id), func_id);
6482 return err;
6483 }
6484
6485 env->prog->has_callchain_buf = true;
6486 }
6487
6488 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6489 env->prog->call_get_stack = true;
6490
6491 if (func_id == BPF_FUNC_get_func_ip) {
6492 if (check_get_func_ip(env))
6493 return -ENOTSUPP;
6494 env->prog->call_get_func_ip = true;
6495 }
6496
6497 if (changes_data)
6498 clear_all_pkt_pointers(env);
6499 return 0;
6500 }
6501
6502 /* mark_btf_func_reg_size() is used when the reg size is determined by
6503 * the BTF func_proto's return value size and argument.
6504 */
6505 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6506 size_t reg_size)
6507 {
6508 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6509
6510 if (regno == BPF_REG_0) {
6511 /* Function return value */
6512 reg->live |= REG_LIVE_WRITTEN;
6513 reg->subreg_def = reg_size == sizeof(u64) ?
6514 DEF_NOT_SUBREG : env->insn_idx + 1;
6515 } else {
6516 /* Function argument */
6517 if (reg_size == sizeof(u64)) {
6518 mark_insn_zext(env, reg);
6519 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6520 } else {
6521 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6522 }
6523 }
6524 }
6525
6526 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6527 {
6528 const struct btf_type *t, *func, *func_proto, *ptr_type;
6529 struct bpf_reg_state *regs = cur_regs(env);
6530 const char *func_name, *ptr_type_name;
6531 u32 i, nargs, func_id, ptr_type_id;
6532 const struct btf_param *args;
6533 int err;
6534
6535 func_id = insn->imm;
6536 func = btf_type_by_id(btf_vmlinux, func_id);
6537 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6538 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6539
6540 if (!env->ops->check_kfunc_call ||
6541 !env->ops->check_kfunc_call(func_id)) {
6542 verbose(env, "calling kernel function %s is not allowed\n",
6543 func_name);
6544 return -EACCES;
6545 }
6546
6547 /* Check the arguments */
6548 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6549 if (err)
6550 return err;
6551
6552 for (i = 0; i < CALLER_SAVED_REGS; i++)
6553 mark_reg_not_init(env, regs, caller_saved[i]);
6554
6555 /* Check return type */
6556 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6557 if (btf_type_is_scalar(t)) {
6558 mark_reg_unknown(env, regs, BPF_REG_0);
6559 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6560 } else if (btf_type_is_ptr(t)) {
6561 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6562 &ptr_type_id);
6563 if (!btf_type_is_struct(ptr_type)) {
6564 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6565 ptr_type->name_off);
6566 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6567 func_name, btf_type_str(ptr_type),
6568 ptr_type_name);
6569 return -EINVAL;
6570 }
6571 mark_reg_known_zero(env, regs, BPF_REG_0);
6572 regs[BPF_REG_0].btf = btf_vmlinux;
6573 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6574 regs[BPF_REG_0].btf_id = ptr_type_id;
6575 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6576 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6577
6578 nargs = btf_type_vlen(func_proto);
6579 args = (const struct btf_param *)(func_proto + 1);
6580 for (i = 0; i < nargs; i++) {
6581 u32 regno = i + 1;
6582
6583 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6584 if (btf_type_is_ptr(t))
6585 mark_btf_func_reg_size(env, regno, sizeof(void *));
6586 else
6587 /* scalar. ensured by btf_check_kfunc_arg_match() */
6588 mark_btf_func_reg_size(env, regno, t->size);
6589 }
6590
6591 return 0;
6592 }
6593
6594 static bool signed_add_overflows(s64 a, s64 b)
6595 {
6596 /* Do the add in u64, where overflow is well-defined */
6597 s64 res = (s64)((u64)a + (u64)b);
6598
6599 if (b < 0)
6600 return res > a;
6601 return res < a;
6602 }
6603
6604 static bool signed_add32_overflows(s32 a, s32 b)
6605 {
6606 /* Do the add in u32, where overflow is well-defined */
6607 s32 res = (s32)((u32)a + (u32)b);
6608
6609 if (b < 0)
6610 return res > a;
6611 return res < a;
6612 }
6613
6614 static bool signed_sub_overflows(s64 a, s64 b)
6615 {
6616 /* Do the sub in u64, where overflow is well-defined */
6617 s64 res = (s64)((u64)a - (u64)b);
6618
6619 if (b < 0)
6620 return res < a;
6621 return res > a;
6622 }
6623
6624 static bool signed_sub32_overflows(s32 a, s32 b)
6625 {
6626 /* Do the sub in u32, where overflow is well-defined */
6627 s32 res = (s32)((u32)a - (u32)b);
6628
6629 if (b < 0)
6630 return res < a;
6631 return res > a;
6632 }
6633
6634 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6635 const struct bpf_reg_state *reg,
6636 enum bpf_reg_type type)
6637 {
6638 bool known = tnum_is_const(reg->var_off);
6639 s64 val = reg->var_off.value;
6640 s64 smin = reg->smin_value;
6641
6642 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6643 verbose(env, "math between %s pointer and %lld is not allowed\n",
6644 reg_type_str[type], val);
6645 return false;
6646 }
6647
6648 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6649 verbose(env, "%s pointer offset %d is not allowed\n",
6650 reg_type_str[type], reg->off);
6651 return false;
6652 }
6653
6654 if (smin == S64_MIN) {
6655 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6656 reg_type_str[type]);
6657 return false;
6658 }
6659
6660 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6661 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6662 smin, reg_type_str[type]);
6663 return false;
6664 }
6665
6666 return true;
6667 }
6668
6669 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6670 {
6671 return &env->insn_aux_data[env->insn_idx];
6672 }
6673
6674 enum {
6675 REASON_BOUNDS = -1,
6676 REASON_TYPE = -2,
6677 REASON_PATHS = -3,
6678 REASON_LIMIT = -4,
6679 REASON_STACK = -5,
6680 };
6681
6682 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
6683 u32 *alu_limit, bool mask_to_left)
6684 {
6685 u32 max = 0, ptr_limit = 0;
6686
6687 switch (ptr_reg->type) {
6688 case PTR_TO_STACK:
6689 /* Offset 0 is out-of-bounds, but acceptable start for the
6690 * left direction, see BPF_REG_FP. Also, unknown scalar
6691 * offset where we would need to deal with min/max bounds is
6692 * currently prohibited for unprivileged.
6693 */
6694 max = MAX_BPF_STACK + mask_to_left;
6695 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
6696 break;
6697 case PTR_TO_MAP_VALUE:
6698 max = ptr_reg->map_ptr->value_size;
6699 ptr_limit = (mask_to_left ?
6700 ptr_reg->smin_value :
6701 ptr_reg->umax_value) + ptr_reg->off;
6702 break;
6703 default:
6704 return REASON_TYPE;
6705 }
6706
6707 if (ptr_limit >= max)
6708 return REASON_LIMIT;
6709 *alu_limit = ptr_limit;
6710 return 0;
6711 }
6712
6713 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6714 const struct bpf_insn *insn)
6715 {
6716 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
6717 }
6718
6719 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6720 u32 alu_state, u32 alu_limit)
6721 {
6722 /* If we arrived here from different branches with different
6723 * state or limits to sanitize, then this won't work.
6724 */
6725 if (aux->alu_state &&
6726 (aux->alu_state != alu_state ||
6727 aux->alu_limit != alu_limit))
6728 return REASON_PATHS;
6729
6730 /* Corresponding fixup done in do_misc_fixups(). */
6731 aux->alu_state = alu_state;
6732 aux->alu_limit = alu_limit;
6733 return 0;
6734 }
6735
6736 static int sanitize_val_alu(struct bpf_verifier_env *env,
6737 struct bpf_insn *insn)
6738 {
6739 struct bpf_insn_aux_data *aux = cur_aux(env);
6740
6741 if (can_skip_alu_sanitation(env, insn))
6742 return 0;
6743
6744 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6745 }
6746
6747 static bool sanitize_needed(u8 opcode)
6748 {
6749 return opcode == BPF_ADD || opcode == BPF_SUB;
6750 }
6751
6752 struct bpf_sanitize_info {
6753 struct bpf_insn_aux_data aux;
6754 bool mask_to_left;
6755 };
6756
6757 static struct bpf_verifier_state *
6758 sanitize_speculative_path(struct bpf_verifier_env *env,
6759 const struct bpf_insn *insn,
6760 u32 next_idx, u32 curr_idx)
6761 {
6762 struct bpf_verifier_state *branch;
6763 struct bpf_reg_state *regs;
6764
6765 branch = push_stack(env, next_idx, curr_idx, true);
6766 if (branch && insn) {
6767 regs = branch->frame[branch->curframe]->regs;
6768 if (BPF_SRC(insn->code) == BPF_K) {
6769 mark_reg_unknown(env, regs, insn->dst_reg);
6770 } else if (BPF_SRC(insn->code) == BPF_X) {
6771 mark_reg_unknown(env, regs, insn->dst_reg);
6772 mark_reg_unknown(env, regs, insn->src_reg);
6773 }
6774 }
6775 return branch;
6776 }
6777
6778 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6779 struct bpf_insn *insn,
6780 const struct bpf_reg_state *ptr_reg,
6781 const struct bpf_reg_state *off_reg,
6782 struct bpf_reg_state *dst_reg,
6783 struct bpf_sanitize_info *info,
6784 const bool commit_window)
6785 {
6786 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
6787 struct bpf_verifier_state *vstate = env->cur_state;
6788 bool off_is_imm = tnum_is_const(off_reg->var_off);
6789 bool off_is_neg = off_reg->smin_value < 0;
6790 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6791 u8 opcode = BPF_OP(insn->code);
6792 u32 alu_state, alu_limit;
6793 struct bpf_reg_state tmp;
6794 bool ret;
6795 int err;
6796
6797 if (can_skip_alu_sanitation(env, insn))
6798 return 0;
6799
6800 /* We already marked aux for masking from non-speculative
6801 * paths, thus we got here in the first place. We only care
6802 * to explore bad access from here.
6803 */
6804 if (vstate->speculative)
6805 goto do_sim;
6806
6807 if (!commit_window) {
6808 if (!tnum_is_const(off_reg->var_off) &&
6809 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6810 return REASON_BOUNDS;
6811
6812 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6813 (opcode == BPF_SUB && !off_is_neg);
6814 }
6815
6816 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6817 if (err < 0)
6818 return err;
6819
6820 if (commit_window) {
6821 /* In commit phase we narrow the masking window based on
6822 * the observed pointer move after the simulated operation.
6823 */
6824 alu_state = info->aux.alu_state;
6825 alu_limit = abs(info->aux.alu_limit - alu_limit);
6826 } else {
6827 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6828 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6829 alu_state |= ptr_is_dst_reg ?
6830 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6831
6832 /* Limit pruning on unknown scalars to enable deep search for
6833 * potential masking differences from other program paths.
6834 */
6835 if (!off_is_imm)
6836 env->explore_alu_limits = true;
6837 }
6838
6839 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6840 if (err < 0)
6841 return err;
6842 do_sim:
6843 /* If we're in commit phase, we're done here given we already
6844 * pushed the truncated dst_reg into the speculative verification
6845 * stack.
6846 *
6847 * Also, when register is a known constant, we rewrite register-based
6848 * operation to immediate-based, and thus do not need masking (and as
6849 * a consequence, do not need to simulate the zero-truncation either).
6850 */
6851 if (commit_window || off_is_imm)
6852 return 0;
6853
6854 /* Simulate and find potential out-of-bounds access under
6855 * speculative execution from truncation as a result of
6856 * masking when off was not within expected range. If off
6857 * sits in dst, then we temporarily need to move ptr there
6858 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6859 * for cases where we use K-based arithmetic in one direction
6860 * and truncated reg-based in the other in order to explore
6861 * bad access.
6862 */
6863 if (!ptr_is_dst_reg) {
6864 tmp = *dst_reg;
6865 *dst_reg = *ptr_reg;
6866 }
6867 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6868 env->insn_idx);
6869 if (!ptr_is_dst_reg && ret)
6870 *dst_reg = tmp;
6871 return !ret ? REASON_STACK : 0;
6872 }
6873
6874 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6875 {
6876 struct bpf_verifier_state *vstate = env->cur_state;
6877
6878 /* If we simulate paths under speculation, we don't update the
6879 * insn as 'seen' such that when we verify unreachable paths in
6880 * the non-speculative domain, sanitize_dead_code() can still
6881 * rewrite/sanitize them.
6882 */
6883 if (!vstate->speculative)
6884 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6885 }
6886
6887 static int sanitize_err(struct bpf_verifier_env *env,
6888 const struct bpf_insn *insn, int reason,
6889 const struct bpf_reg_state *off_reg,
6890 const struct bpf_reg_state *dst_reg)
6891 {
6892 static const char *err = "pointer arithmetic with it prohibited for !root";
6893 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6894 u32 dst = insn->dst_reg, src = insn->src_reg;
6895
6896 switch (reason) {
6897 case REASON_BOUNDS:
6898 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6899 off_reg == dst_reg ? dst : src, err);
6900 break;
6901 case REASON_TYPE:
6902 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6903 off_reg == dst_reg ? src : dst, err);
6904 break;
6905 case REASON_PATHS:
6906 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6907 dst, op, err);
6908 break;
6909 case REASON_LIMIT:
6910 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6911 dst, op, err);
6912 break;
6913 case REASON_STACK:
6914 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6915 dst, err);
6916 break;
6917 default:
6918 verbose(env, "verifier internal error: unknown reason (%d)\n",
6919 reason);
6920 break;
6921 }
6922
6923 return -EACCES;
6924 }
6925
6926 /* check that stack access falls within stack limits and that 'reg' doesn't
6927 * have a variable offset.
6928 *
6929 * Variable offset is prohibited for unprivileged mode for simplicity since it
6930 * requires corresponding support in Spectre masking for stack ALU. See also
6931 * retrieve_ptr_limit().
6932 *
6933 *
6934 * 'off' includes 'reg->off'.
6935 */
6936 static int check_stack_access_for_ptr_arithmetic(
6937 struct bpf_verifier_env *env,
6938 int regno,
6939 const struct bpf_reg_state *reg,
6940 int off)
6941 {
6942 if (!tnum_is_const(reg->var_off)) {
6943 char tn_buf[48];
6944
6945 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6946 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6947 regno, tn_buf, off);
6948 return -EACCES;
6949 }
6950
6951 if (off >= 0 || off < -MAX_BPF_STACK) {
6952 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6953 "prohibited for !root; off=%d\n", regno, off);
6954 return -EACCES;
6955 }
6956
6957 return 0;
6958 }
6959
6960 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6961 const struct bpf_insn *insn,
6962 const struct bpf_reg_state *dst_reg)
6963 {
6964 u32 dst = insn->dst_reg;
6965
6966 /* For unprivileged we require that resulting offset must be in bounds
6967 * in order to be able to sanitize access later on.
6968 */
6969 if (env->bypass_spec_v1)
6970 return 0;
6971
6972 switch (dst_reg->type) {
6973 case PTR_TO_STACK:
6974 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6975 dst_reg->off + dst_reg->var_off.value))
6976 return -EACCES;
6977 break;
6978 case PTR_TO_MAP_VALUE:
6979 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6980 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6981 "prohibited for !root\n", dst);
6982 return -EACCES;
6983 }
6984 break;
6985 default:
6986 break;
6987 }
6988
6989 return 0;
6990 }
6991
6992 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6993 * Caller should also handle BPF_MOV case separately.
6994 * If we return -EACCES, caller may want to try again treating pointer as a
6995 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6996 */
6997 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6998 struct bpf_insn *insn,
6999 const struct bpf_reg_state *ptr_reg,
7000 const struct bpf_reg_state *off_reg)
7001 {
7002 struct bpf_verifier_state *vstate = env->cur_state;
7003 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7004 struct bpf_reg_state *regs = state->regs, *dst_reg;
7005 bool known = tnum_is_const(off_reg->var_off);
7006 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7007 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7008 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7009 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
7010 struct bpf_sanitize_info info = {};
7011 u8 opcode = BPF_OP(insn->code);
7012 u32 dst = insn->dst_reg;
7013 int ret;
7014
7015 dst_reg = &regs[dst];
7016
7017 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7018 smin_val > smax_val || umin_val > umax_val) {
7019 /* Taint dst register if offset had invalid bounds derived from
7020 * e.g. dead branches.
7021 */
7022 __mark_reg_unknown(env, dst_reg);
7023 return 0;
7024 }
7025
7026 if (BPF_CLASS(insn->code) != BPF_ALU64) {
7027 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
7028 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7029 __mark_reg_unknown(env, dst_reg);
7030 return 0;
7031 }
7032
7033 verbose(env,
7034 "R%d 32-bit pointer arithmetic prohibited\n",
7035 dst);
7036 return -EACCES;
7037 }
7038
7039 switch (ptr_reg->type) {
7040 case PTR_TO_MAP_VALUE_OR_NULL:
7041 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7042 dst, reg_type_str[ptr_reg->type]);
7043 return -EACCES;
7044 case CONST_PTR_TO_MAP:
7045 /* smin_val represents the known value */
7046 if (known && smin_val == 0 && opcode == BPF_ADD)
7047 break;
7048 fallthrough;
7049 case PTR_TO_PACKET_END:
7050 case PTR_TO_SOCKET:
7051 case PTR_TO_SOCK_COMMON:
7052 case PTR_TO_TCP_SOCK:
7053 case PTR_TO_XDP_SOCK:
7054 reject:
7055 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7056 dst, reg_type_str[ptr_reg->type]);
7057 return -EACCES;
7058 default:
7059 if (reg_type_may_be_null(ptr_reg->type))
7060 goto reject;
7061 break;
7062 }
7063
7064 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7065 * The id may be overwritten later if we create a new variable offset.
7066 */
7067 dst_reg->type = ptr_reg->type;
7068 dst_reg->id = ptr_reg->id;
7069
7070 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7071 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7072 return -EINVAL;
7073
7074 /* pointer types do not carry 32-bit bounds at the moment. */
7075 __mark_reg32_unbounded(dst_reg);
7076
7077 if (sanitize_needed(opcode)) {
7078 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
7079 &info, false);
7080 if (ret < 0)
7081 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7082 }
7083
7084 switch (opcode) {
7085 case BPF_ADD:
7086 /* We can take a fixed offset as long as it doesn't overflow
7087 * the s32 'off' field
7088 */
7089 if (known && (ptr_reg->off + smin_val ==
7090 (s64)(s32)(ptr_reg->off + smin_val))) {
7091 /* pointer += K. Accumulate it into fixed offset */
7092 dst_reg->smin_value = smin_ptr;
7093 dst_reg->smax_value = smax_ptr;
7094 dst_reg->umin_value = umin_ptr;
7095 dst_reg->umax_value = umax_ptr;
7096 dst_reg->var_off = ptr_reg->var_off;
7097 dst_reg->off = ptr_reg->off + smin_val;
7098 dst_reg->raw = ptr_reg->raw;
7099 break;
7100 }
7101 /* A new variable offset is created. Note that off_reg->off
7102 * == 0, since it's a scalar.
7103 * dst_reg gets the pointer type and since some positive
7104 * integer value was added to the pointer, give it a new 'id'
7105 * if it's a PTR_TO_PACKET.
7106 * this creates a new 'base' pointer, off_reg (variable) gets
7107 * added into the variable offset, and we copy the fixed offset
7108 * from ptr_reg.
7109 */
7110 if (signed_add_overflows(smin_ptr, smin_val) ||
7111 signed_add_overflows(smax_ptr, smax_val)) {
7112 dst_reg->smin_value = S64_MIN;
7113 dst_reg->smax_value = S64_MAX;
7114 } else {
7115 dst_reg->smin_value = smin_ptr + smin_val;
7116 dst_reg->smax_value = smax_ptr + smax_val;
7117 }
7118 if (umin_ptr + umin_val < umin_ptr ||
7119 umax_ptr + umax_val < umax_ptr) {
7120 dst_reg->umin_value = 0;
7121 dst_reg->umax_value = U64_MAX;
7122 } else {
7123 dst_reg->umin_value = umin_ptr + umin_val;
7124 dst_reg->umax_value = umax_ptr + umax_val;
7125 }
7126 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7127 dst_reg->off = ptr_reg->off;
7128 dst_reg->raw = ptr_reg->raw;
7129 if (reg_is_pkt_pointer(ptr_reg)) {
7130 dst_reg->id = ++env->id_gen;
7131 /* something was added to pkt_ptr, set range to zero */
7132 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7133 }
7134 break;
7135 case BPF_SUB:
7136 if (dst_reg == off_reg) {
7137 /* scalar -= pointer. Creates an unknown scalar */
7138 verbose(env, "R%d tried to subtract pointer from scalar\n",
7139 dst);
7140 return -EACCES;
7141 }
7142 /* We don't allow subtraction from FP, because (according to
7143 * test_verifier.c test "invalid fp arithmetic", JITs might not
7144 * be able to deal with it.
7145 */
7146 if (ptr_reg->type == PTR_TO_STACK) {
7147 verbose(env, "R%d subtraction from stack pointer prohibited\n",
7148 dst);
7149 return -EACCES;
7150 }
7151 if (known && (ptr_reg->off - smin_val ==
7152 (s64)(s32)(ptr_reg->off - smin_val))) {
7153 /* pointer -= K. Subtract it from fixed offset */
7154 dst_reg->smin_value = smin_ptr;
7155 dst_reg->smax_value = smax_ptr;
7156 dst_reg->umin_value = umin_ptr;
7157 dst_reg->umax_value = umax_ptr;
7158 dst_reg->var_off = ptr_reg->var_off;
7159 dst_reg->id = ptr_reg->id;
7160 dst_reg->off = ptr_reg->off - smin_val;
7161 dst_reg->raw = ptr_reg->raw;
7162 break;
7163 }
7164 /* A new variable offset is created. If the subtrahend is known
7165 * nonnegative, then any reg->range we had before is still good.
7166 */
7167 if (signed_sub_overflows(smin_ptr, smax_val) ||
7168 signed_sub_overflows(smax_ptr, smin_val)) {
7169 /* Overflow possible, we know nothing */
7170 dst_reg->smin_value = S64_MIN;
7171 dst_reg->smax_value = S64_MAX;
7172 } else {
7173 dst_reg->smin_value = smin_ptr - smax_val;
7174 dst_reg->smax_value = smax_ptr - smin_val;
7175 }
7176 if (umin_ptr < umax_val) {
7177 /* Overflow possible, we know nothing */
7178 dst_reg->umin_value = 0;
7179 dst_reg->umax_value = U64_MAX;
7180 } else {
7181 /* Cannot overflow (as long as bounds are consistent) */
7182 dst_reg->umin_value = umin_ptr - umax_val;
7183 dst_reg->umax_value = umax_ptr - umin_val;
7184 }
7185 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7186 dst_reg->off = ptr_reg->off;
7187 dst_reg->raw = ptr_reg->raw;
7188 if (reg_is_pkt_pointer(ptr_reg)) {
7189 dst_reg->id = ++env->id_gen;
7190 /* something was added to pkt_ptr, set range to zero */
7191 if (smin_val < 0)
7192 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
7193 }
7194 break;
7195 case BPF_AND:
7196 case BPF_OR:
7197 case BPF_XOR:
7198 /* bitwise ops on pointers are troublesome, prohibit. */
7199 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7200 dst, bpf_alu_string[opcode >> 4]);
7201 return -EACCES;
7202 default:
7203 /* other operators (e.g. MUL,LSH) produce non-pointer results */
7204 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7205 dst, bpf_alu_string[opcode >> 4]);
7206 return -EACCES;
7207 }
7208
7209 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7210 return -EINVAL;
7211
7212 __update_reg_bounds(dst_reg);
7213 __reg_deduce_bounds(dst_reg);
7214 __reg_bound_offset(dst_reg);
7215
7216 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7217 return -EACCES;
7218 if (sanitize_needed(opcode)) {
7219 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
7220 &info, true);
7221 if (ret < 0)
7222 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7223 }
7224
7225 return 0;
7226 }
7227
7228 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7229 struct bpf_reg_state *src_reg)
7230 {
7231 s32 smin_val = src_reg->s32_min_value;
7232 s32 smax_val = src_reg->s32_max_value;
7233 u32 umin_val = src_reg->u32_min_value;
7234 u32 umax_val = src_reg->u32_max_value;
7235
7236 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7237 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7238 dst_reg->s32_min_value = S32_MIN;
7239 dst_reg->s32_max_value = S32_MAX;
7240 } else {
7241 dst_reg->s32_min_value += smin_val;
7242 dst_reg->s32_max_value += smax_val;
7243 }
7244 if (dst_reg->u32_min_value + umin_val < umin_val ||
7245 dst_reg->u32_max_value + umax_val < umax_val) {
7246 dst_reg->u32_min_value = 0;
7247 dst_reg->u32_max_value = U32_MAX;
7248 } else {
7249 dst_reg->u32_min_value += umin_val;
7250 dst_reg->u32_max_value += umax_val;
7251 }
7252 }
7253
7254 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7255 struct bpf_reg_state *src_reg)
7256 {
7257 s64 smin_val = src_reg->smin_value;
7258 s64 smax_val = src_reg->smax_value;
7259 u64 umin_val = src_reg->umin_value;
7260 u64 umax_val = src_reg->umax_value;
7261
7262 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7263 signed_add_overflows(dst_reg->smax_value, smax_val)) {
7264 dst_reg->smin_value = S64_MIN;
7265 dst_reg->smax_value = S64_MAX;
7266 } else {
7267 dst_reg->smin_value += smin_val;
7268 dst_reg->smax_value += smax_val;
7269 }
7270 if (dst_reg->umin_value + umin_val < umin_val ||
7271 dst_reg->umax_value + umax_val < umax_val) {
7272 dst_reg->umin_value = 0;
7273 dst_reg->umax_value = U64_MAX;
7274 } else {
7275 dst_reg->umin_value += umin_val;
7276 dst_reg->umax_value += umax_val;
7277 }
7278 }
7279
7280 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7281 struct bpf_reg_state *src_reg)
7282 {
7283 s32 smin_val = src_reg->s32_min_value;
7284 s32 smax_val = src_reg->s32_max_value;
7285 u32 umin_val = src_reg->u32_min_value;
7286 u32 umax_val = src_reg->u32_max_value;
7287
7288 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7289 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7290 /* Overflow possible, we know nothing */
7291 dst_reg->s32_min_value = S32_MIN;
7292 dst_reg->s32_max_value = S32_MAX;
7293 } else {
7294 dst_reg->s32_min_value -= smax_val;
7295 dst_reg->s32_max_value -= smin_val;
7296 }
7297 if (dst_reg->u32_min_value < umax_val) {
7298 /* Overflow possible, we know nothing */
7299 dst_reg->u32_min_value = 0;
7300 dst_reg->u32_max_value = U32_MAX;
7301 } else {
7302 /* Cannot overflow (as long as bounds are consistent) */
7303 dst_reg->u32_min_value -= umax_val;
7304 dst_reg->u32_max_value -= umin_val;
7305 }
7306 }
7307
7308 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7309 struct bpf_reg_state *src_reg)
7310 {
7311 s64 smin_val = src_reg->smin_value;
7312 s64 smax_val = src_reg->smax_value;
7313 u64 umin_val = src_reg->umin_value;
7314 u64 umax_val = src_reg->umax_value;
7315
7316 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7317 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7318 /* Overflow possible, we know nothing */
7319 dst_reg->smin_value = S64_MIN;
7320 dst_reg->smax_value = S64_MAX;
7321 } else {
7322 dst_reg->smin_value -= smax_val;
7323 dst_reg->smax_value -= smin_val;
7324 }
7325 if (dst_reg->umin_value < umax_val) {
7326 /* Overflow possible, we know nothing */
7327 dst_reg->umin_value = 0;
7328 dst_reg->umax_value = U64_MAX;
7329 } else {
7330 /* Cannot overflow (as long as bounds are consistent) */
7331 dst_reg->umin_value -= umax_val;
7332 dst_reg->umax_value -= umin_val;
7333 }
7334 }
7335
7336 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7337 struct bpf_reg_state *src_reg)
7338 {
7339 s32 smin_val = src_reg->s32_min_value;
7340 u32 umin_val = src_reg->u32_min_value;
7341 u32 umax_val = src_reg->u32_max_value;
7342
7343 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7344 /* Ain't nobody got time to multiply that sign */
7345 __mark_reg32_unbounded(dst_reg);
7346 return;
7347 }
7348 /* Both values are positive, so we can work with unsigned and
7349 * copy the result to signed (unless it exceeds S32_MAX).
7350 */
7351 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7352 /* Potential overflow, we know nothing */
7353 __mark_reg32_unbounded(dst_reg);
7354 return;
7355 }
7356 dst_reg->u32_min_value *= umin_val;
7357 dst_reg->u32_max_value *= umax_val;
7358 if (dst_reg->u32_max_value > S32_MAX) {
7359 /* Overflow possible, we know nothing */
7360 dst_reg->s32_min_value = S32_MIN;
7361 dst_reg->s32_max_value = S32_MAX;
7362 } else {
7363 dst_reg->s32_min_value = dst_reg->u32_min_value;
7364 dst_reg->s32_max_value = dst_reg->u32_max_value;
7365 }
7366 }
7367
7368 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7369 struct bpf_reg_state *src_reg)
7370 {
7371 s64 smin_val = src_reg->smin_value;
7372 u64 umin_val = src_reg->umin_value;
7373 u64 umax_val = src_reg->umax_value;
7374
7375 if (smin_val < 0 || dst_reg->smin_value < 0) {
7376 /* Ain't nobody got time to multiply that sign */
7377 __mark_reg64_unbounded(dst_reg);
7378 return;
7379 }
7380 /* Both values are positive, so we can work with unsigned and
7381 * copy the result to signed (unless it exceeds S64_MAX).
7382 */
7383 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7384 /* Potential overflow, we know nothing */
7385 __mark_reg64_unbounded(dst_reg);
7386 return;
7387 }
7388 dst_reg->umin_value *= umin_val;
7389 dst_reg->umax_value *= umax_val;
7390 if (dst_reg->umax_value > S64_MAX) {
7391 /* Overflow possible, we know nothing */
7392 dst_reg->smin_value = S64_MIN;
7393 dst_reg->smax_value = S64_MAX;
7394 } else {
7395 dst_reg->smin_value = dst_reg->umin_value;
7396 dst_reg->smax_value = dst_reg->umax_value;
7397 }
7398 }
7399
7400 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7401 struct bpf_reg_state *src_reg)
7402 {
7403 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7404 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7405 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7406 s32 smin_val = src_reg->s32_min_value;
7407 u32 umax_val = src_reg->u32_max_value;
7408
7409 if (src_known && dst_known) {
7410 __mark_reg32_known(dst_reg, var32_off.value);
7411 return;
7412 }
7413
7414 /* We get our minimum from the var_off, since that's inherently
7415 * bitwise. Our maximum is the minimum of the operands' maxima.
7416 */
7417 dst_reg->u32_min_value = var32_off.value;
7418 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7419 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7420 /* Lose signed bounds when ANDing negative numbers,
7421 * ain't nobody got time for that.
7422 */
7423 dst_reg->s32_min_value = S32_MIN;
7424 dst_reg->s32_max_value = S32_MAX;
7425 } else {
7426 /* ANDing two positives gives a positive, so safe to
7427 * cast result into s64.
7428 */
7429 dst_reg->s32_min_value = dst_reg->u32_min_value;
7430 dst_reg->s32_max_value = dst_reg->u32_max_value;
7431 }
7432 }
7433
7434 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7435 struct bpf_reg_state *src_reg)
7436 {
7437 bool src_known = tnum_is_const(src_reg->var_off);
7438 bool dst_known = tnum_is_const(dst_reg->var_off);
7439 s64 smin_val = src_reg->smin_value;
7440 u64 umax_val = src_reg->umax_value;
7441
7442 if (src_known && dst_known) {
7443 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7444 return;
7445 }
7446
7447 /* We get our minimum from the var_off, since that's inherently
7448 * bitwise. Our maximum is the minimum of the operands' maxima.
7449 */
7450 dst_reg->umin_value = dst_reg->var_off.value;
7451 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7452 if (dst_reg->smin_value < 0 || smin_val < 0) {
7453 /* Lose signed bounds when ANDing negative numbers,
7454 * ain't nobody got time for that.
7455 */
7456 dst_reg->smin_value = S64_MIN;
7457 dst_reg->smax_value = S64_MAX;
7458 } else {
7459 /* ANDing two positives gives a positive, so safe to
7460 * cast result into s64.
7461 */
7462 dst_reg->smin_value = dst_reg->umin_value;
7463 dst_reg->smax_value = dst_reg->umax_value;
7464 }
7465 /* We may learn something more from the var_off */
7466 __update_reg_bounds(dst_reg);
7467 }
7468
7469 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7470 struct bpf_reg_state *src_reg)
7471 {
7472 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7473 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7474 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7475 s32 smin_val = src_reg->s32_min_value;
7476 u32 umin_val = src_reg->u32_min_value;
7477
7478 if (src_known && dst_known) {
7479 __mark_reg32_known(dst_reg, var32_off.value);
7480 return;
7481 }
7482
7483 /* We get our maximum from the var_off, and our minimum is the
7484 * maximum of the operands' minima
7485 */
7486 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7487 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7488 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7489 /* Lose signed bounds when ORing negative numbers,
7490 * ain't nobody got time for that.
7491 */
7492 dst_reg->s32_min_value = S32_MIN;
7493 dst_reg->s32_max_value = S32_MAX;
7494 } else {
7495 /* ORing two positives gives a positive, so safe to
7496 * cast result into s64.
7497 */
7498 dst_reg->s32_min_value = dst_reg->u32_min_value;
7499 dst_reg->s32_max_value = dst_reg->u32_max_value;
7500 }
7501 }
7502
7503 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7504 struct bpf_reg_state *src_reg)
7505 {
7506 bool src_known = tnum_is_const(src_reg->var_off);
7507 bool dst_known = tnum_is_const(dst_reg->var_off);
7508 s64 smin_val = src_reg->smin_value;
7509 u64 umin_val = src_reg->umin_value;
7510
7511 if (src_known && dst_known) {
7512 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7513 return;
7514 }
7515
7516 /* We get our maximum from the var_off, and our minimum is the
7517 * maximum of the operands' minima
7518 */
7519 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7520 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7521 if (dst_reg->smin_value < 0 || smin_val < 0) {
7522 /* Lose signed bounds when ORing negative numbers,
7523 * ain't nobody got time for that.
7524 */
7525 dst_reg->smin_value = S64_MIN;
7526 dst_reg->smax_value = S64_MAX;
7527 } else {
7528 /* ORing two positives gives a positive, so safe to
7529 * cast result into s64.
7530 */
7531 dst_reg->smin_value = dst_reg->umin_value;
7532 dst_reg->smax_value = dst_reg->umax_value;
7533 }
7534 /* We may learn something more from the var_off */
7535 __update_reg_bounds(dst_reg);
7536 }
7537
7538 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7539 struct bpf_reg_state *src_reg)
7540 {
7541 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7542 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7543 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7544 s32 smin_val = src_reg->s32_min_value;
7545
7546 if (src_known && dst_known) {
7547 __mark_reg32_known(dst_reg, var32_off.value);
7548 return;
7549 }
7550
7551 /* We get both minimum and maximum from the var32_off. */
7552 dst_reg->u32_min_value = var32_off.value;
7553 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7554
7555 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7556 /* XORing two positive sign numbers gives a positive,
7557 * so safe to cast u32 result into s32.
7558 */
7559 dst_reg->s32_min_value = dst_reg->u32_min_value;
7560 dst_reg->s32_max_value = dst_reg->u32_max_value;
7561 } else {
7562 dst_reg->s32_min_value = S32_MIN;
7563 dst_reg->s32_max_value = S32_MAX;
7564 }
7565 }
7566
7567 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7568 struct bpf_reg_state *src_reg)
7569 {
7570 bool src_known = tnum_is_const(src_reg->var_off);
7571 bool dst_known = tnum_is_const(dst_reg->var_off);
7572 s64 smin_val = src_reg->smin_value;
7573
7574 if (src_known && dst_known) {
7575 /* dst_reg->var_off.value has been updated earlier */
7576 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7577 return;
7578 }
7579
7580 /* We get both minimum and maximum from the var_off. */
7581 dst_reg->umin_value = dst_reg->var_off.value;
7582 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7583
7584 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7585 /* XORing two positive sign numbers gives a positive,
7586 * so safe to cast u64 result into s64.
7587 */
7588 dst_reg->smin_value = dst_reg->umin_value;
7589 dst_reg->smax_value = dst_reg->umax_value;
7590 } else {
7591 dst_reg->smin_value = S64_MIN;
7592 dst_reg->smax_value = S64_MAX;
7593 }
7594
7595 __update_reg_bounds(dst_reg);
7596 }
7597
7598 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7599 u64 umin_val, u64 umax_val)
7600 {
7601 /* We lose all sign bit information (except what we can pick
7602 * up from var_off)
7603 */
7604 dst_reg->s32_min_value = S32_MIN;
7605 dst_reg->s32_max_value = S32_MAX;
7606 /* If we might shift our top bit out, then we know nothing */
7607 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7608 dst_reg->u32_min_value = 0;
7609 dst_reg->u32_max_value = U32_MAX;
7610 } else {
7611 dst_reg->u32_min_value <<= umin_val;
7612 dst_reg->u32_max_value <<= umax_val;
7613 }
7614 }
7615
7616 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7617 struct bpf_reg_state *src_reg)
7618 {
7619 u32 umax_val = src_reg->u32_max_value;
7620 u32 umin_val = src_reg->u32_min_value;
7621 /* u32 alu operation will zext upper bits */
7622 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7623
7624 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7625 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7626 /* Not required but being careful mark reg64 bounds as unknown so
7627 * that we are forced to pick them up from tnum and zext later and
7628 * if some path skips this step we are still safe.
7629 */
7630 __mark_reg64_unbounded(dst_reg);
7631 __update_reg32_bounds(dst_reg);
7632 }
7633
7634 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7635 u64 umin_val, u64 umax_val)
7636 {
7637 /* Special case <<32 because it is a common compiler pattern to sign
7638 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7639 * positive we know this shift will also be positive so we can track
7640 * bounds correctly. Otherwise we lose all sign bit information except
7641 * what we can pick up from var_off. Perhaps we can generalize this
7642 * later to shifts of any length.
7643 */
7644 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7645 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7646 else
7647 dst_reg->smax_value = S64_MAX;
7648
7649 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7650 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7651 else
7652 dst_reg->smin_value = S64_MIN;
7653
7654 /* If we might shift our top bit out, then we know nothing */
7655 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7656 dst_reg->umin_value = 0;
7657 dst_reg->umax_value = U64_MAX;
7658 } else {
7659 dst_reg->umin_value <<= umin_val;
7660 dst_reg->umax_value <<= umax_val;
7661 }
7662 }
7663
7664 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7665 struct bpf_reg_state *src_reg)
7666 {
7667 u64 umax_val = src_reg->umax_value;
7668 u64 umin_val = src_reg->umin_value;
7669
7670 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7671 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7672 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7673
7674 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7675 /* We may learn something more from the var_off */
7676 __update_reg_bounds(dst_reg);
7677 }
7678
7679 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7680 struct bpf_reg_state *src_reg)
7681 {
7682 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7683 u32 umax_val = src_reg->u32_max_value;
7684 u32 umin_val = src_reg->u32_min_value;
7685
7686 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7687 * be negative, then either:
7688 * 1) src_reg might be zero, so the sign bit of the result is
7689 * unknown, so we lose our signed bounds
7690 * 2) it's known negative, thus the unsigned bounds capture the
7691 * signed bounds
7692 * 3) the signed bounds cross zero, so they tell us nothing
7693 * about the result
7694 * If the value in dst_reg is known nonnegative, then again the
7695 * unsigned bounds capture the signed bounds.
7696 * Thus, in all cases it suffices to blow away our signed bounds
7697 * and rely on inferring new ones from the unsigned bounds and
7698 * var_off of the result.
7699 */
7700 dst_reg->s32_min_value = S32_MIN;
7701 dst_reg->s32_max_value = S32_MAX;
7702
7703 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7704 dst_reg->u32_min_value >>= umax_val;
7705 dst_reg->u32_max_value >>= umin_val;
7706
7707 __mark_reg64_unbounded(dst_reg);
7708 __update_reg32_bounds(dst_reg);
7709 }
7710
7711 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7712 struct bpf_reg_state *src_reg)
7713 {
7714 u64 umax_val = src_reg->umax_value;
7715 u64 umin_val = src_reg->umin_value;
7716
7717 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7718 * be negative, then either:
7719 * 1) src_reg might be zero, so the sign bit of the result is
7720 * unknown, so we lose our signed bounds
7721 * 2) it's known negative, thus the unsigned bounds capture the
7722 * signed bounds
7723 * 3) the signed bounds cross zero, so they tell us nothing
7724 * about the result
7725 * If the value in dst_reg is known nonnegative, then again the
7726 * unsigned bounds capture the signed bounds.
7727 * Thus, in all cases it suffices to blow away our signed bounds
7728 * and rely on inferring new ones from the unsigned bounds and
7729 * var_off of the result.
7730 */
7731 dst_reg->smin_value = S64_MIN;
7732 dst_reg->smax_value = S64_MAX;
7733 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7734 dst_reg->umin_value >>= umax_val;
7735 dst_reg->umax_value >>= umin_val;
7736
7737 /* Its not easy to operate on alu32 bounds here because it depends
7738 * on bits being shifted in. Take easy way out and mark unbounded
7739 * so we can recalculate later from tnum.
7740 */
7741 __mark_reg32_unbounded(dst_reg);
7742 __update_reg_bounds(dst_reg);
7743 }
7744
7745 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7746 struct bpf_reg_state *src_reg)
7747 {
7748 u64 umin_val = src_reg->u32_min_value;
7749
7750 /* Upon reaching here, src_known is true and
7751 * umax_val is equal to umin_val.
7752 */
7753 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7754 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
7755
7756 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7757
7758 /* blow away the dst_reg umin_value/umax_value and rely on
7759 * dst_reg var_off to refine the result.
7760 */
7761 dst_reg->u32_min_value = 0;
7762 dst_reg->u32_max_value = U32_MAX;
7763
7764 __mark_reg64_unbounded(dst_reg);
7765 __update_reg32_bounds(dst_reg);
7766 }
7767
7768 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7769 struct bpf_reg_state *src_reg)
7770 {
7771 u64 umin_val = src_reg->umin_value;
7772
7773 /* Upon reaching here, src_known is true and umax_val is equal
7774 * to umin_val.
7775 */
7776 dst_reg->smin_value >>= umin_val;
7777 dst_reg->smax_value >>= umin_val;
7778
7779 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
7780
7781 /* blow away the dst_reg umin_value/umax_value and rely on
7782 * dst_reg var_off to refine the result.
7783 */
7784 dst_reg->umin_value = 0;
7785 dst_reg->umax_value = U64_MAX;
7786
7787 /* Its not easy to operate on alu32 bounds here because it depends
7788 * on bits being shifted in from upper 32-bits. Take easy way out
7789 * and mark unbounded so we can recalculate later from tnum.
7790 */
7791 __mark_reg32_unbounded(dst_reg);
7792 __update_reg_bounds(dst_reg);
7793 }
7794
7795 /* WARNING: This function does calculations on 64-bit values, but the actual
7796 * execution may occur on 32-bit values. Therefore, things like bitshifts
7797 * need extra checks in the 32-bit case.
7798 */
7799 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7800 struct bpf_insn *insn,
7801 struct bpf_reg_state *dst_reg,
7802 struct bpf_reg_state src_reg)
7803 {
7804 struct bpf_reg_state *regs = cur_regs(env);
7805 u8 opcode = BPF_OP(insn->code);
7806 bool src_known;
7807 s64 smin_val, smax_val;
7808 u64 umin_val, umax_val;
7809 s32 s32_min_val, s32_max_val;
7810 u32 u32_min_val, u32_max_val;
7811 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7812 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7813 int ret;
7814
7815 smin_val = src_reg.smin_value;
7816 smax_val = src_reg.smax_value;
7817 umin_val = src_reg.umin_value;
7818 umax_val = src_reg.umax_value;
7819
7820 s32_min_val = src_reg.s32_min_value;
7821 s32_max_val = src_reg.s32_max_value;
7822 u32_min_val = src_reg.u32_min_value;
7823 u32_max_val = src_reg.u32_max_value;
7824
7825 if (alu32) {
7826 src_known = tnum_subreg_is_const(src_reg.var_off);
7827 if ((src_known &&
7828 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7829 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7830 /* Taint dst register if offset had invalid bounds
7831 * derived from e.g. dead branches.
7832 */
7833 __mark_reg_unknown(env, dst_reg);
7834 return 0;
7835 }
7836 } else {
7837 src_known = tnum_is_const(src_reg.var_off);
7838 if ((src_known &&
7839 (smin_val != smax_val || umin_val != umax_val)) ||
7840 smin_val > smax_val || umin_val > umax_val) {
7841 /* Taint dst register if offset had invalid bounds
7842 * derived from e.g. dead branches.
7843 */
7844 __mark_reg_unknown(env, dst_reg);
7845 return 0;
7846 }
7847 }
7848
7849 if (!src_known &&
7850 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7851 __mark_reg_unknown(env, dst_reg);
7852 return 0;
7853 }
7854
7855 if (sanitize_needed(opcode)) {
7856 ret = sanitize_val_alu(env, insn);
7857 if (ret < 0)
7858 return sanitize_err(env, insn, ret, NULL, NULL);
7859 }
7860
7861 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7862 * There are two classes of instructions: The first class we track both
7863 * alu32 and alu64 sign/unsigned bounds independently this provides the
7864 * greatest amount of precision when alu operations are mixed with jmp32
7865 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7866 * and BPF_OR. This is possible because these ops have fairly easy to
7867 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7868 * See alu32 verifier tests for examples. The second class of
7869 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7870 * with regards to tracking sign/unsigned bounds because the bits may
7871 * cross subreg boundaries in the alu64 case. When this happens we mark
7872 * the reg unbounded in the subreg bound space and use the resulting
7873 * tnum to calculate an approximation of the sign/unsigned bounds.
7874 */
7875 switch (opcode) {
7876 case BPF_ADD:
7877 scalar32_min_max_add(dst_reg, &src_reg);
7878 scalar_min_max_add(dst_reg, &src_reg);
7879 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7880 break;
7881 case BPF_SUB:
7882 scalar32_min_max_sub(dst_reg, &src_reg);
7883 scalar_min_max_sub(dst_reg, &src_reg);
7884 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7885 break;
7886 case BPF_MUL:
7887 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7888 scalar32_min_max_mul(dst_reg, &src_reg);
7889 scalar_min_max_mul(dst_reg, &src_reg);
7890 break;
7891 case BPF_AND:
7892 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7893 scalar32_min_max_and(dst_reg, &src_reg);
7894 scalar_min_max_and(dst_reg, &src_reg);
7895 break;
7896 case BPF_OR:
7897 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7898 scalar32_min_max_or(dst_reg, &src_reg);
7899 scalar_min_max_or(dst_reg, &src_reg);
7900 break;
7901 case BPF_XOR:
7902 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7903 scalar32_min_max_xor(dst_reg, &src_reg);
7904 scalar_min_max_xor(dst_reg, &src_reg);
7905 break;
7906 case BPF_LSH:
7907 if (umax_val >= insn_bitness) {
7908 /* Shifts greater than 31 or 63 are undefined.
7909 * This includes shifts by a negative number.
7910 */
7911 mark_reg_unknown(env, regs, insn->dst_reg);
7912 break;
7913 }
7914 if (alu32)
7915 scalar32_min_max_lsh(dst_reg, &src_reg);
7916 else
7917 scalar_min_max_lsh(dst_reg, &src_reg);
7918 break;
7919 case BPF_RSH:
7920 if (umax_val >= insn_bitness) {
7921 /* Shifts greater than 31 or 63 are undefined.
7922 * This includes shifts by a negative number.
7923 */
7924 mark_reg_unknown(env, regs, insn->dst_reg);
7925 break;
7926 }
7927 if (alu32)
7928 scalar32_min_max_rsh(dst_reg, &src_reg);
7929 else
7930 scalar_min_max_rsh(dst_reg, &src_reg);
7931 break;
7932 case BPF_ARSH:
7933 if (umax_val >= insn_bitness) {
7934 /* Shifts greater than 31 or 63 are undefined.
7935 * This includes shifts by a negative number.
7936 */
7937 mark_reg_unknown(env, regs, insn->dst_reg);
7938 break;
7939 }
7940 if (alu32)
7941 scalar32_min_max_arsh(dst_reg, &src_reg);
7942 else
7943 scalar_min_max_arsh(dst_reg, &src_reg);
7944 break;
7945 default:
7946 mark_reg_unknown(env, regs, insn->dst_reg);
7947 break;
7948 }
7949
7950 /* ALU32 ops are zero extended into 64bit register */
7951 if (alu32)
7952 zext_32_to_64(dst_reg);
7953
7954 __update_reg_bounds(dst_reg);
7955 __reg_deduce_bounds(dst_reg);
7956 __reg_bound_offset(dst_reg);
7957 return 0;
7958 }
7959
7960 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7961 * and var_off.
7962 */
7963 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7964 struct bpf_insn *insn)
7965 {
7966 struct bpf_verifier_state *vstate = env->cur_state;
7967 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7968 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7969 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7970 u8 opcode = BPF_OP(insn->code);
7971 int err;
7972
7973 dst_reg = &regs[insn->dst_reg];
7974 src_reg = NULL;
7975 if (dst_reg->type != SCALAR_VALUE)
7976 ptr_reg = dst_reg;
7977 else
7978 /* Make sure ID is cleared otherwise dst_reg min/max could be
7979 * incorrectly propagated into other registers by find_equal_scalars()
7980 */
7981 dst_reg->id = 0;
7982 if (BPF_SRC(insn->code) == BPF_X) {
7983 src_reg = &regs[insn->src_reg];
7984 if (src_reg->type != SCALAR_VALUE) {
7985 if (dst_reg->type != SCALAR_VALUE) {
7986 /* Combining two pointers by any ALU op yields
7987 * an arbitrary scalar. Disallow all math except
7988 * pointer subtraction
7989 */
7990 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7991 mark_reg_unknown(env, regs, insn->dst_reg);
7992 return 0;
7993 }
7994 verbose(env, "R%d pointer %s pointer prohibited\n",
7995 insn->dst_reg,
7996 bpf_alu_string[opcode >> 4]);
7997 return -EACCES;
7998 } else {
7999 /* scalar += pointer
8000 * This is legal, but we have to reverse our
8001 * src/dest handling in computing the range
8002 */
8003 err = mark_chain_precision(env, insn->dst_reg);
8004 if (err)
8005 return err;
8006 return adjust_ptr_min_max_vals(env, insn,
8007 src_reg, dst_reg);
8008 }
8009 } else if (ptr_reg) {
8010 /* pointer += scalar */
8011 err = mark_chain_precision(env, insn->src_reg);
8012 if (err)
8013 return err;
8014 return adjust_ptr_min_max_vals(env, insn,
8015 dst_reg, src_reg);
8016 }
8017 } else {
8018 /* Pretend the src is a reg with a known value, since we only
8019 * need to be able to read from this state.
8020 */
8021 off_reg.type = SCALAR_VALUE;
8022 __mark_reg_known(&off_reg, insn->imm);
8023 src_reg = &off_reg;
8024 if (ptr_reg) /* pointer += K */
8025 return adjust_ptr_min_max_vals(env, insn,
8026 ptr_reg, src_reg);
8027 }
8028
8029 /* Got here implies adding two SCALAR_VALUEs */
8030 if (WARN_ON_ONCE(ptr_reg)) {
8031 print_verifier_state(env, state);
8032 verbose(env, "verifier internal error: unexpected ptr_reg\n");
8033 return -EINVAL;
8034 }
8035 if (WARN_ON(!src_reg)) {
8036 print_verifier_state(env, state);
8037 verbose(env, "verifier internal error: no src_reg\n");
8038 return -EINVAL;
8039 }
8040 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
8041 }
8042
8043 /* check validity of 32-bit and 64-bit arithmetic operations */
8044 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
8045 {
8046 struct bpf_reg_state *regs = cur_regs(env);
8047 u8 opcode = BPF_OP(insn->code);
8048 int err;
8049
8050 if (opcode == BPF_END || opcode == BPF_NEG) {
8051 if (opcode == BPF_NEG) {
8052 if (BPF_SRC(insn->code) != 0 ||
8053 insn->src_reg != BPF_REG_0 ||
8054 insn->off != 0 || insn->imm != 0) {
8055 verbose(env, "BPF_NEG uses reserved fields\n");
8056 return -EINVAL;
8057 }
8058 } else {
8059 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
8060 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8061 BPF_CLASS(insn->code) == BPF_ALU64) {
8062 verbose(env, "BPF_END uses reserved fields\n");
8063 return -EINVAL;
8064 }
8065 }
8066
8067 /* check src operand */
8068 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8069 if (err)
8070 return err;
8071
8072 if (is_pointer_value(env, insn->dst_reg)) {
8073 verbose(env, "R%d pointer arithmetic prohibited\n",
8074 insn->dst_reg);
8075 return -EACCES;
8076 }
8077
8078 /* check dest operand */
8079 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8080 if (err)
8081 return err;
8082
8083 } else if (opcode == BPF_MOV) {
8084
8085 if (BPF_SRC(insn->code) == BPF_X) {
8086 if (insn->imm != 0 || insn->off != 0) {
8087 verbose(env, "BPF_MOV uses reserved fields\n");
8088 return -EINVAL;
8089 }
8090
8091 /* check src operand */
8092 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8093 if (err)
8094 return err;
8095 } else {
8096 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8097 verbose(env, "BPF_MOV uses reserved fields\n");
8098 return -EINVAL;
8099 }
8100 }
8101
8102 /* check dest operand, mark as required later */
8103 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8104 if (err)
8105 return err;
8106
8107 if (BPF_SRC(insn->code) == BPF_X) {
8108 struct bpf_reg_state *src_reg = regs + insn->src_reg;
8109 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8110
8111 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8112 /* case: R1 = R2
8113 * copy register state to dest reg
8114 */
8115 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8116 /* Assign src and dst registers the same ID
8117 * that will be used by find_equal_scalars()
8118 * to propagate min/max range.
8119 */
8120 src_reg->id = ++env->id_gen;
8121 *dst_reg = *src_reg;
8122 dst_reg->live |= REG_LIVE_WRITTEN;
8123 dst_reg->subreg_def = DEF_NOT_SUBREG;
8124 } else {
8125 /* R1 = (u32) R2 */
8126 if (is_pointer_value(env, insn->src_reg)) {
8127 verbose(env,
8128 "R%d partial copy of pointer\n",
8129 insn->src_reg);
8130 return -EACCES;
8131 } else if (src_reg->type == SCALAR_VALUE) {
8132 *dst_reg = *src_reg;
8133 /* Make sure ID is cleared otherwise
8134 * dst_reg min/max could be incorrectly
8135 * propagated into src_reg by find_equal_scalars()
8136 */
8137 dst_reg->id = 0;
8138 dst_reg->live |= REG_LIVE_WRITTEN;
8139 dst_reg->subreg_def = env->insn_idx + 1;
8140 } else {
8141 mark_reg_unknown(env, regs,
8142 insn->dst_reg);
8143 }
8144 zext_32_to_64(dst_reg);
8145
8146 __update_reg_bounds(dst_reg);
8147 __reg_deduce_bounds(dst_reg);
8148 __reg_bound_offset(dst_reg);
8149 }
8150 } else {
8151 /* case: R = imm
8152 * remember the value we stored into this reg
8153 */
8154 /* clear any state __mark_reg_known doesn't set */
8155 mark_reg_unknown(env, regs, insn->dst_reg);
8156 regs[insn->dst_reg].type = SCALAR_VALUE;
8157 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8158 __mark_reg_known(regs + insn->dst_reg,
8159 insn->imm);
8160 } else {
8161 __mark_reg_known(regs + insn->dst_reg,
8162 (u32)insn->imm);
8163 }
8164 }
8165
8166 } else if (opcode > BPF_END) {
8167 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
8168 return -EINVAL;
8169
8170 } else { /* all other ALU ops: and, sub, xor, add, ... */
8171
8172 if (BPF_SRC(insn->code) == BPF_X) {
8173 if (insn->imm != 0 || insn->off != 0) {
8174 verbose(env, "BPF_ALU uses reserved fields\n");
8175 return -EINVAL;
8176 }
8177 /* check src1 operand */
8178 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8179 if (err)
8180 return err;
8181 } else {
8182 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
8183 verbose(env, "BPF_ALU uses reserved fields\n");
8184 return -EINVAL;
8185 }
8186 }
8187
8188 /* check src2 operand */
8189 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8190 if (err)
8191 return err;
8192
8193 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8194 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
8195 verbose(env, "div by zero\n");
8196 return -EINVAL;
8197 }
8198
8199 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8200 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8201 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8202
8203 if (insn->imm < 0 || insn->imm >= size) {
8204 verbose(env, "invalid shift %d\n", insn->imm);
8205 return -EINVAL;
8206 }
8207 }
8208
8209 /* check dest operand */
8210 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
8211 if (err)
8212 return err;
8213
8214 return adjust_reg_min_max_vals(env, insn);
8215 }
8216
8217 return 0;
8218 }
8219
8220 static void __find_good_pkt_pointers(struct bpf_func_state *state,
8221 struct bpf_reg_state *dst_reg,
8222 enum bpf_reg_type type, int new_range)
8223 {
8224 struct bpf_reg_state *reg;
8225 int i;
8226
8227 for (i = 0; i < MAX_BPF_REG; i++) {
8228 reg = &state->regs[i];
8229 if (reg->type == type && reg->id == dst_reg->id)
8230 /* keep the maximum range already checked */
8231 reg->range = max(reg->range, new_range);
8232 }
8233
8234 bpf_for_each_spilled_reg(i, state, reg) {
8235 if (!reg)
8236 continue;
8237 if (reg->type == type && reg->id == dst_reg->id)
8238 reg->range = max(reg->range, new_range);
8239 }
8240 }
8241
8242 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
8243 struct bpf_reg_state *dst_reg,
8244 enum bpf_reg_type type,
8245 bool range_right_open)
8246 {
8247 int new_range, i;
8248
8249 if (dst_reg->off < 0 ||
8250 (dst_reg->off == 0 && range_right_open))
8251 /* This doesn't give us any range */
8252 return;
8253
8254 if (dst_reg->umax_value > MAX_PACKET_OFF ||
8255 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
8256 /* Risk of overflow. For instance, ptr + (1<<63) may be less
8257 * than pkt_end, but that's because it's also less than pkt.
8258 */
8259 return;
8260
8261 new_range = dst_reg->off;
8262 if (range_right_open)
8263 new_range++;
8264
8265 /* Examples for register markings:
8266 *
8267 * pkt_data in dst register:
8268 *
8269 * r2 = r3;
8270 * r2 += 8;
8271 * if (r2 > pkt_end) goto <handle exception>
8272 * <access okay>
8273 *
8274 * r2 = r3;
8275 * r2 += 8;
8276 * if (r2 < pkt_end) goto <access okay>
8277 * <handle exception>
8278 *
8279 * Where:
8280 * r2 == dst_reg, pkt_end == src_reg
8281 * r2=pkt(id=n,off=8,r=0)
8282 * r3=pkt(id=n,off=0,r=0)
8283 *
8284 * pkt_data in src register:
8285 *
8286 * r2 = r3;
8287 * r2 += 8;
8288 * if (pkt_end >= r2) goto <access okay>
8289 * <handle exception>
8290 *
8291 * r2 = r3;
8292 * r2 += 8;
8293 * if (pkt_end <= r2) goto <handle exception>
8294 * <access okay>
8295 *
8296 * Where:
8297 * pkt_end == dst_reg, r2 == src_reg
8298 * r2=pkt(id=n,off=8,r=0)
8299 * r3=pkt(id=n,off=0,r=0)
8300 *
8301 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
8302 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8303 * and [r3, r3 + 8-1) respectively is safe to access depending on
8304 * the check.
8305 */
8306
8307 /* If our ids match, then we must have the same max_value. And we
8308 * don't care about the other reg's fixed offset, since if it's too big
8309 * the range won't allow anything.
8310 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8311 */
8312 for (i = 0; i <= vstate->curframe; i++)
8313 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8314 new_range);
8315 }
8316
8317 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
8318 {
8319 struct tnum subreg = tnum_subreg(reg->var_off);
8320 s32 sval = (s32)val;
8321
8322 switch (opcode) {
8323 case BPF_JEQ:
8324 if (tnum_is_const(subreg))
8325 return !!tnum_equals_const(subreg, val);
8326 break;
8327 case BPF_JNE:
8328 if (tnum_is_const(subreg))
8329 return !tnum_equals_const(subreg, val);
8330 break;
8331 case BPF_JSET:
8332 if ((~subreg.mask & subreg.value) & val)
8333 return 1;
8334 if (!((subreg.mask | subreg.value) & val))
8335 return 0;
8336 break;
8337 case BPF_JGT:
8338 if (reg->u32_min_value > val)
8339 return 1;
8340 else if (reg->u32_max_value <= val)
8341 return 0;
8342 break;
8343 case BPF_JSGT:
8344 if (reg->s32_min_value > sval)
8345 return 1;
8346 else if (reg->s32_max_value <= sval)
8347 return 0;
8348 break;
8349 case BPF_JLT:
8350 if (reg->u32_max_value < val)
8351 return 1;
8352 else if (reg->u32_min_value >= val)
8353 return 0;
8354 break;
8355 case BPF_JSLT:
8356 if (reg->s32_max_value < sval)
8357 return 1;
8358 else if (reg->s32_min_value >= sval)
8359 return 0;
8360 break;
8361 case BPF_JGE:
8362 if (reg->u32_min_value >= val)
8363 return 1;
8364 else if (reg->u32_max_value < val)
8365 return 0;
8366 break;
8367 case BPF_JSGE:
8368 if (reg->s32_min_value >= sval)
8369 return 1;
8370 else if (reg->s32_max_value < sval)
8371 return 0;
8372 break;
8373 case BPF_JLE:
8374 if (reg->u32_max_value <= val)
8375 return 1;
8376 else if (reg->u32_min_value > val)
8377 return 0;
8378 break;
8379 case BPF_JSLE:
8380 if (reg->s32_max_value <= sval)
8381 return 1;
8382 else if (reg->s32_min_value > sval)
8383 return 0;
8384 break;
8385 }
8386
8387 return -1;
8388 }
8389
8390
8391 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8392 {
8393 s64 sval = (s64)val;
8394
8395 switch (opcode) {
8396 case BPF_JEQ:
8397 if (tnum_is_const(reg->var_off))
8398 return !!tnum_equals_const(reg->var_off, val);
8399 break;
8400 case BPF_JNE:
8401 if (tnum_is_const(reg->var_off))
8402 return !tnum_equals_const(reg->var_off, val);
8403 break;
8404 case BPF_JSET:
8405 if ((~reg->var_off.mask & reg->var_off.value) & val)
8406 return 1;
8407 if (!((reg->var_off.mask | reg->var_off.value) & val))
8408 return 0;
8409 break;
8410 case BPF_JGT:
8411 if (reg->umin_value > val)
8412 return 1;
8413 else if (reg->umax_value <= val)
8414 return 0;
8415 break;
8416 case BPF_JSGT:
8417 if (reg->smin_value > sval)
8418 return 1;
8419 else if (reg->smax_value <= sval)
8420 return 0;
8421 break;
8422 case BPF_JLT:
8423 if (reg->umax_value < val)
8424 return 1;
8425 else if (reg->umin_value >= val)
8426 return 0;
8427 break;
8428 case BPF_JSLT:
8429 if (reg->smax_value < sval)
8430 return 1;
8431 else if (reg->smin_value >= sval)
8432 return 0;
8433 break;
8434 case BPF_JGE:
8435 if (reg->umin_value >= val)
8436 return 1;
8437 else if (reg->umax_value < val)
8438 return 0;
8439 break;
8440 case BPF_JSGE:
8441 if (reg->smin_value >= sval)
8442 return 1;
8443 else if (reg->smax_value < sval)
8444 return 0;
8445 break;
8446 case BPF_JLE:
8447 if (reg->umax_value <= val)
8448 return 1;
8449 else if (reg->umin_value > val)
8450 return 0;
8451 break;
8452 case BPF_JSLE:
8453 if (reg->smax_value <= sval)
8454 return 1;
8455 else if (reg->smin_value > sval)
8456 return 0;
8457 break;
8458 }
8459
8460 return -1;
8461 }
8462
8463 /* compute branch direction of the expression "if (reg opcode val) goto target;"
8464 * and return:
8465 * 1 - branch will be taken and "goto target" will be executed
8466 * 0 - branch will not be taken and fall-through to next insn
8467 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8468 * range [0,10]
8469 */
8470 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8471 bool is_jmp32)
8472 {
8473 if (__is_pointer_value(false, reg)) {
8474 if (!reg_type_not_null(reg->type))
8475 return -1;
8476
8477 /* If pointer is valid tests against zero will fail so we can
8478 * use this to direct branch taken.
8479 */
8480 if (val != 0)
8481 return -1;
8482
8483 switch (opcode) {
8484 case BPF_JEQ:
8485 return 0;
8486 case BPF_JNE:
8487 return 1;
8488 default:
8489 return -1;
8490 }
8491 }
8492
8493 if (is_jmp32)
8494 return is_branch32_taken(reg, val, opcode);
8495 return is_branch64_taken(reg, val, opcode);
8496 }
8497
8498 static int flip_opcode(u32 opcode)
8499 {
8500 /* How can we transform "a <op> b" into "b <op> a"? */
8501 static const u8 opcode_flip[16] = {
8502 /* these stay the same */
8503 [BPF_JEQ >> 4] = BPF_JEQ,
8504 [BPF_JNE >> 4] = BPF_JNE,
8505 [BPF_JSET >> 4] = BPF_JSET,
8506 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8507 [BPF_JGE >> 4] = BPF_JLE,
8508 [BPF_JGT >> 4] = BPF_JLT,
8509 [BPF_JLE >> 4] = BPF_JGE,
8510 [BPF_JLT >> 4] = BPF_JGT,
8511 [BPF_JSGE >> 4] = BPF_JSLE,
8512 [BPF_JSGT >> 4] = BPF_JSLT,
8513 [BPF_JSLE >> 4] = BPF_JSGE,
8514 [BPF_JSLT >> 4] = BPF_JSGT
8515 };
8516 return opcode_flip[opcode >> 4];
8517 }
8518
8519 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8520 struct bpf_reg_state *src_reg,
8521 u8 opcode)
8522 {
8523 struct bpf_reg_state *pkt;
8524
8525 if (src_reg->type == PTR_TO_PACKET_END) {
8526 pkt = dst_reg;
8527 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8528 pkt = src_reg;
8529 opcode = flip_opcode(opcode);
8530 } else {
8531 return -1;
8532 }
8533
8534 if (pkt->range >= 0)
8535 return -1;
8536
8537 switch (opcode) {
8538 case BPF_JLE:
8539 /* pkt <= pkt_end */
8540 fallthrough;
8541 case BPF_JGT:
8542 /* pkt > pkt_end */
8543 if (pkt->range == BEYOND_PKT_END)
8544 /* pkt has at last one extra byte beyond pkt_end */
8545 return opcode == BPF_JGT;
8546 break;
8547 case BPF_JLT:
8548 /* pkt < pkt_end */
8549 fallthrough;
8550 case BPF_JGE:
8551 /* pkt >= pkt_end */
8552 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8553 return opcode == BPF_JGE;
8554 break;
8555 }
8556 return -1;
8557 }
8558
8559 /* Adjusts the register min/max values in the case that the dst_reg is the
8560 * variable register that we are working on, and src_reg is a constant or we're
8561 * simply doing a BPF_K check.
8562 * In JEQ/JNE cases we also adjust the var_off values.
8563 */
8564 static void reg_set_min_max(struct bpf_reg_state *true_reg,
8565 struct bpf_reg_state *false_reg,
8566 u64 val, u32 val32,
8567 u8 opcode, bool is_jmp32)
8568 {
8569 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8570 struct tnum false_64off = false_reg->var_off;
8571 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8572 struct tnum true_64off = true_reg->var_off;
8573 s64 sval = (s64)val;
8574 s32 sval32 = (s32)val32;
8575
8576 /* If the dst_reg is a pointer, we can't learn anything about its
8577 * variable offset from the compare (unless src_reg were a pointer into
8578 * the same object, but we don't bother with that.
8579 * Since false_reg and true_reg have the same type by construction, we
8580 * only need to check one of them for pointerness.
8581 */
8582 if (__is_pointer_value(false, false_reg))
8583 return;
8584
8585 switch (opcode) {
8586 case BPF_JEQ:
8587 case BPF_JNE:
8588 {
8589 struct bpf_reg_state *reg =
8590 opcode == BPF_JEQ ? true_reg : false_reg;
8591
8592 /* JEQ/JNE comparison doesn't change the register equivalence.
8593 * r1 = r2;
8594 * if (r1 == 42) goto label;
8595 * ...
8596 * label: // here both r1 and r2 are known to be 42.
8597 *
8598 * Hence when marking register as known preserve it's ID.
8599 */
8600 if (is_jmp32)
8601 __mark_reg32_known(reg, val32);
8602 else
8603 ___mark_reg_known(reg, val);
8604 break;
8605 }
8606 case BPF_JSET:
8607 if (is_jmp32) {
8608 false_32off = tnum_and(false_32off, tnum_const(~val32));
8609 if (is_power_of_2(val32))
8610 true_32off = tnum_or(true_32off,
8611 tnum_const(val32));
8612 } else {
8613 false_64off = tnum_and(false_64off, tnum_const(~val));
8614 if (is_power_of_2(val))
8615 true_64off = tnum_or(true_64off,
8616 tnum_const(val));
8617 }
8618 break;
8619 case BPF_JGE:
8620 case BPF_JGT:
8621 {
8622 if (is_jmp32) {
8623 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8624 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8625
8626 false_reg->u32_max_value = min(false_reg->u32_max_value,
8627 false_umax);
8628 true_reg->u32_min_value = max(true_reg->u32_min_value,
8629 true_umin);
8630 } else {
8631 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8632 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8633
8634 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8635 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8636 }
8637 break;
8638 }
8639 case BPF_JSGE:
8640 case BPF_JSGT:
8641 {
8642 if (is_jmp32) {
8643 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8644 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
8645
8646 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8647 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8648 } else {
8649 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8650 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8651
8652 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8653 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8654 }
8655 break;
8656 }
8657 case BPF_JLE:
8658 case BPF_JLT:
8659 {
8660 if (is_jmp32) {
8661 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8662 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8663
8664 false_reg->u32_min_value = max(false_reg->u32_min_value,
8665 false_umin);
8666 true_reg->u32_max_value = min(true_reg->u32_max_value,
8667 true_umax);
8668 } else {
8669 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8670 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8671
8672 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8673 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8674 }
8675 break;
8676 }
8677 case BPF_JSLE:
8678 case BPF_JSLT:
8679 {
8680 if (is_jmp32) {
8681 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8682 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
8683
8684 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8685 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8686 } else {
8687 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8688 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8689
8690 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8691 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8692 }
8693 break;
8694 }
8695 default:
8696 return;
8697 }
8698
8699 if (is_jmp32) {
8700 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8701 tnum_subreg(false_32off));
8702 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8703 tnum_subreg(true_32off));
8704 __reg_combine_32_into_64(false_reg);
8705 __reg_combine_32_into_64(true_reg);
8706 } else {
8707 false_reg->var_off = false_64off;
8708 true_reg->var_off = true_64off;
8709 __reg_combine_64_into_32(false_reg);
8710 __reg_combine_64_into_32(true_reg);
8711 }
8712 }
8713
8714 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
8715 * the variable reg.
8716 */
8717 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
8718 struct bpf_reg_state *false_reg,
8719 u64 val, u32 val32,
8720 u8 opcode, bool is_jmp32)
8721 {
8722 opcode = flip_opcode(opcode);
8723 /* This uses zero as "not present in table"; luckily the zero opcode,
8724 * BPF_JA, can't get here.
8725 */
8726 if (opcode)
8727 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
8728 }
8729
8730 /* Regs are known to be equal, so intersect their min/max/var_off */
8731 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8732 struct bpf_reg_state *dst_reg)
8733 {
8734 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8735 dst_reg->umin_value);
8736 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8737 dst_reg->umax_value);
8738 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8739 dst_reg->smin_value);
8740 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8741 dst_reg->smax_value);
8742 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8743 dst_reg->var_off);
8744 /* We might have learned new bounds from the var_off. */
8745 __update_reg_bounds(src_reg);
8746 __update_reg_bounds(dst_reg);
8747 /* We might have learned something about the sign bit. */
8748 __reg_deduce_bounds(src_reg);
8749 __reg_deduce_bounds(dst_reg);
8750 /* We might have learned some bits from the bounds. */
8751 __reg_bound_offset(src_reg);
8752 __reg_bound_offset(dst_reg);
8753 /* Intersecting with the old var_off might have improved our bounds
8754 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8755 * then new var_off is (0; 0x7f...fc) which improves our umax.
8756 */
8757 __update_reg_bounds(src_reg);
8758 __update_reg_bounds(dst_reg);
8759 }
8760
8761 static void reg_combine_min_max(struct bpf_reg_state *true_src,
8762 struct bpf_reg_state *true_dst,
8763 struct bpf_reg_state *false_src,
8764 struct bpf_reg_state *false_dst,
8765 u8 opcode)
8766 {
8767 switch (opcode) {
8768 case BPF_JEQ:
8769 __reg_combine_min_max(true_src, true_dst);
8770 break;
8771 case BPF_JNE:
8772 __reg_combine_min_max(false_src, false_dst);
8773 break;
8774 }
8775 }
8776
8777 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8778 struct bpf_reg_state *reg, u32 id,
8779 bool is_null)
8780 {
8781 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8782 !WARN_ON_ONCE(!reg->id)) {
8783 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8784 !tnum_equals_const(reg->var_off, 0) ||
8785 reg->off)) {
8786 /* Old offset (both fixed and variable parts) should
8787 * have been known-zero, because we don't allow pointer
8788 * arithmetic on pointers that might be NULL. If we
8789 * see this happening, don't convert the register.
8790 */
8791 return;
8792 }
8793 if (is_null) {
8794 reg->type = SCALAR_VALUE;
8795 /* We don't need id and ref_obj_id from this point
8796 * onwards anymore, thus we should better reset it,
8797 * so that state pruning has chances to take effect.
8798 */
8799 reg->id = 0;
8800 reg->ref_obj_id = 0;
8801
8802 return;
8803 }
8804
8805 mark_ptr_not_null_reg(reg);
8806
8807 if (!reg_may_point_to_spin_lock(reg)) {
8808 /* For not-NULL ptr, reg->ref_obj_id will be reset
8809 * in release_reg_references().
8810 *
8811 * reg->id is still used by spin_lock ptr. Other
8812 * than spin_lock ptr type, reg->id can be reset.
8813 */
8814 reg->id = 0;
8815 }
8816 }
8817 }
8818
8819 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8820 bool is_null)
8821 {
8822 struct bpf_reg_state *reg;
8823 int i;
8824
8825 for (i = 0; i < MAX_BPF_REG; i++)
8826 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8827
8828 bpf_for_each_spilled_reg(i, state, reg) {
8829 if (!reg)
8830 continue;
8831 mark_ptr_or_null_reg(state, reg, id, is_null);
8832 }
8833 }
8834
8835 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8836 * be folded together at some point.
8837 */
8838 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8839 bool is_null)
8840 {
8841 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8842 struct bpf_reg_state *regs = state->regs;
8843 u32 ref_obj_id = regs[regno].ref_obj_id;
8844 u32 id = regs[regno].id;
8845 int i;
8846
8847 if (ref_obj_id && ref_obj_id == id && is_null)
8848 /* regs[regno] is in the " == NULL" branch.
8849 * No one could have freed the reference state before
8850 * doing the NULL check.
8851 */
8852 WARN_ON_ONCE(release_reference_state(state, id));
8853
8854 for (i = 0; i <= vstate->curframe; i++)
8855 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
8856 }
8857
8858 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8859 struct bpf_reg_state *dst_reg,
8860 struct bpf_reg_state *src_reg,
8861 struct bpf_verifier_state *this_branch,
8862 struct bpf_verifier_state *other_branch)
8863 {
8864 if (BPF_SRC(insn->code) != BPF_X)
8865 return false;
8866
8867 /* Pointers are always 64-bit. */
8868 if (BPF_CLASS(insn->code) == BPF_JMP32)
8869 return false;
8870
8871 switch (BPF_OP(insn->code)) {
8872 case BPF_JGT:
8873 if ((dst_reg->type == PTR_TO_PACKET &&
8874 src_reg->type == PTR_TO_PACKET_END) ||
8875 (dst_reg->type == PTR_TO_PACKET_META &&
8876 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8877 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8878 find_good_pkt_pointers(this_branch, dst_reg,
8879 dst_reg->type, false);
8880 mark_pkt_end(other_branch, insn->dst_reg, true);
8881 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8882 src_reg->type == PTR_TO_PACKET) ||
8883 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8884 src_reg->type == PTR_TO_PACKET_META)) {
8885 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8886 find_good_pkt_pointers(other_branch, src_reg,
8887 src_reg->type, true);
8888 mark_pkt_end(this_branch, insn->src_reg, false);
8889 } else {
8890 return false;
8891 }
8892 break;
8893 case BPF_JLT:
8894 if ((dst_reg->type == PTR_TO_PACKET &&
8895 src_reg->type == PTR_TO_PACKET_END) ||
8896 (dst_reg->type == PTR_TO_PACKET_META &&
8897 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8898 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8899 find_good_pkt_pointers(other_branch, dst_reg,
8900 dst_reg->type, true);
8901 mark_pkt_end(this_branch, insn->dst_reg, false);
8902 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8903 src_reg->type == PTR_TO_PACKET) ||
8904 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8905 src_reg->type == PTR_TO_PACKET_META)) {
8906 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8907 find_good_pkt_pointers(this_branch, src_reg,
8908 src_reg->type, false);
8909 mark_pkt_end(other_branch, insn->src_reg, true);
8910 } else {
8911 return false;
8912 }
8913 break;
8914 case BPF_JGE:
8915 if ((dst_reg->type == PTR_TO_PACKET &&
8916 src_reg->type == PTR_TO_PACKET_END) ||
8917 (dst_reg->type == PTR_TO_PACKET_META &&
8918 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8919 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8920 find_good_pkt_pointers(this_branch, dst_reg,
8921 dst_reg->type, true);
8922 mark_pkt_end(other_branch, insn->dst_reg, false);
8923 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8924 src_reg->type == PTR_TO_PACKET) ||
8925 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8926 src_reg->type == PTR_TO_PACKET_META)) {
8927 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8928 find_good_pkt_pointers(other_branch, src_reg,
8929 src_reg->type, false);
8930 mark_pkt_end(this_branch, insn->src_reg, true);
8931 } else {
8932 return false;
8933 }
8934 break;
8935 case BPF_JLE:
8936 if ((dst_reg->type == PTR_TO_PACKET &&
8937 src_reg->type == PTR_TO_PACKET_END) ||
8938 (dst_reg->type == PTR_TO_PACKET_META &&
8939 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8940 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8941 find_good_pkt_pointers(other_branch, dst_reg,
8942 dst_reg->type, false);
8943 mark_pkt_end(this_branch, insn->dst_reg, true);
8944 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8945 src_reg->type == PTR_TO_PACKET) ||
8946 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8947 src_reg->type == PTR_TO_PACKET_META)) {
8948 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8949 find_good_pkt_pointers(this_branch, src_reg,
8950 src_reg->type, true);
8951 mark_pkt_end(other_branch, insn->src_reg, false);
8952 } else {
8953 return false;
8954 }
8955 break;
8956 default:
8957 return false;
8958 }
8959
8960 return true;
8961 }
8962
8963 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8964 struct bpf_reg_state *known_reg)
8965 {
8966 struct bpf_func_state *state;
8967 struct bpf_reg_state *reg;
8968 int i, j;
8969
8970 for (i = 0; i <= vstate->curframe; i++) {
8971 state = vstate->frame[i];
8972 for (j = 0; j < MAX_BPF_REG; j++) {
8973 reg = &state->regs[j];
8974 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8975 *reg = *known_reg;
8976 }
8977
8978 bpf_for_each_spilled_reg(j, state, reg) {
8979 if (!reg)
8980 continue;
8981 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8982 *reg = *known_reg;
8983 }
8984 }
8985 }
8986
8987 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8988 struct bpf_insn *insn, int *insn_idx)
8989 {
8990 struct bpf_verifier_state *this_branch = env->cur_state;
8991 struct bpf_verifier_state *other_branch;
8992 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8993 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8994 u8 opcode = BPF_OP(insn->code);
8995 bool is_jmp32;
8996 int pred = -1;
8997 int err;
8998
8999 /* Only conditional jumps are expected to reach here. */
9000 if (opcode == BPF_JA || opcode > BPF_JSLE) {
9001 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
9002 return -EINVAL;
9003 }
9004
9005 if (BPF_SRC(insn->code) == BPF_X) {
9006 if (insn->imm != 0) {
9007 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9008 return -EINVAL;
9009 }
9010
9011 /* check src1 operand */
9012 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9013 if (err)
9014 return err;
9015
9016 if (is_pointer_value(env, insn->src_reg)) {
9017 verbose(env, "R%d pointer comparison prohibited\n",
9018 insn->src_reg);
9019 return -EACCES;
9020 }
9021 src_reg = &regs[insn->src_reg];
9022 } else {
9023 if (insn->src_reg != BPF_REG_0) {
9024 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
9025 return -EINVAL;
9026 }
9027 }
9028
9029 /* check src2 operand */
9030 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9031 if (err)
9032 return err;
9033
9034 dst_reg = &regs[insn->dst_reg];
9035 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
9036
9037 if (BPF_SRC(insn->code) == BPF_K) {
9038 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9039 } else if (src_reg->type == SCALAR_VALUE &&
9040 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9041 pred = is_branch_taken(dst_reg,
9042 tnum_subreg(src_reg->var_off).value,
9043 opcode,
9044 is_jmp32);
9045 } else if (src_reg->type == SCALAR_VALUE &&
9046 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9047 pred = is_branch_taken(dst_reg,
9048 src_reg->var_off.value,
9049 opcode,
9050 is_jmp32);
9051 } else if (reg_is_pkt_pointer_any(dst_reg) &&
9052 reg_is_pkt_pointer_any(src_reg) &&
9053 !is_jmp32) {
9054 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
9055 }
9056
9057 if (pred >= 0) {
9058 /* If we get here with a dst_reg pointer type it is because
9059 * above is_branch_taken() special cased the 0 comparison.
9060 */
9061 if (!__is_pointer_value(false, dst_reg))
9062 err = mark_chain_precision(env, insn->dst_reg);
9063 if (BPF_SRC(insn->code) == BPF_X && !err &&
9064 !__is_pointer_value(false, src_reg))
9065 err = mark_chain_precision(env, insn->src_reg);
9066 if (err)
9067 return err;
9068 }
9069
9070 if (pred == 1) {
9071 /* Only follow the goto, ignore fall-through. If needed, push
9072 * the fall-through branch for simulation under speculative
9073 * execution.
9074 */
9075 if (!env->bypass_spec_v1 &&
9076 !sanitize_speculative_path(env, insn, *insn_idx + 1,
9077 *insn_idx))
9078 return -EFAULT;
9079 *insn_idx += insn->off;
9080 return 0;
9081 } else if (pred == 0) {
9082 /* Only follow the fall-through branch, since that's where the
9083 * program will go. If needed, push the goto branch for
9084 * simulation under speculative execution.
9085 */
9086 if (!env->bypass_spec_v1 &&
9087 !sanitize_speculative_path(env, insn,
9088 *insn_idx + insn->off + 1,
9089 *insn_idx))
9090 return -EFAULT;
9091 return 0;
9092 }
9093
9094 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9095 false);
9096 if (!other_branch)
9097 return -EFAULT;
9098 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
9099
9100 /* detect if we are comparing against a constant value so we can adjust
9101 * our min/max values for our dst register.
9102 * this is only legit if both are scalars (or pointers to the same
9103 * object, I suppose, but we don't support that right now), because
9104 * otherwise the different base pointers mean the offsets aren't
9105 * comparable.
9106 */
9107 if (BPF_SRC(insn->code) == BPF_X) {
9108 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
9109
9110 if (dst_reg->type == SCALAR_VALUE &&
9111 src_reg->type == SCALAR_VALUE) {
9112 if (tnum_is_const(src_reg->var_off) ||
9113 (is_jmp32 &&
9114 tnum_is_const(tnum_subreg(src_reg->var_off))))
9115 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9116 dst_reg,
9117 src_reg->var_off.value,
9118 tnum_subreg(src_reg->var_off).value,
9119 opcode, is_jmp32);
9120 else if (tnum_is_const(dst_reg->var_off) ||
9121 (is_jmp32 &&
9122 tnum_is_const(tnum_subreg(dst_reg->var_off))))
9123 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
9124 src_reg,
9125 dst_reg->var_off.value,
9126 tnum_subreg(dst_reg->var_off).value,
9127 opcode, is_jmp32);
9128 else if (!is_jmp32 &&
9129 (opcode == BPF_JEQ || opcode == BPF_JNE))
9130 /* Comparing for equality, we can combine knowledge */
9131 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9132 &other_branch_regs[insn->dst_reg],
9133 src_reg, dst_reg, opcode);
9134 if (src_reg->id &&
9135 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
9136 find_equal_scalars(this_branch, src_reg);
9137 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9138 }
9139
9140 }
9141 } else if (dst_reg->type == SCALAR_VALUE) {
9142 reg_set_min_max(&other_branch_regs[insn->dst_reg],
9143 dst_reg, insn->imm, (u32)insn->imm,
9144 opcode, is_jmp32);
9145 }
9146
9147 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9148 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
9149 find_equal_scalars(this_branch, dst_reg);
9150 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9151 }
9152
9153 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9154 * NOTE: these optimizations below are related with pointer comparison
9155 * which will never be JMP32.
9156 */
9157 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
9158 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
9159 reg_type_may_be_null(dst_reg->type)) {
9160 /* Mark all identical registers in each branch as either
9161 * safe or unknown depending R == 0 or R != 0 conditional.
9162 */
9163 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9164 opcode == BPF_JNE);
9165 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9166 opcode == BPF_JEQ);
9167 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9168 this_branch, other_branch) &&
9169 is_pointer_value(env, insn->dst_reg)) {
9170 verbose(env, "R%d pointer comparison prohibited\n",
9171 insn->dst_reg);
9172 return -EACCES;
9173 }
9174 if (env->log.level & BPF_LOG_LEVEL)
9175 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
9176 return 0;
9177 }
9178
9179 /* verify BPF_LD_IMM64 instruction */
9180 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
9181 {
9182 struct bpf_insn_aux_data *aux = cur_aux(env);
9183 struct bpf_reg_state *regs = cur_regs(env);
9184 struct bpf_reg_state *dst_reg;
9185 struct bpf_map *map;
9186 int err;
9187
9188 if (BPF_SIZE(insn->code) != BPF_DW) {
9189 verbose(env, "invalid BPF_LD_IMM insn\n");
9190 return -EINVAL;
9191 }
9192 if (insn->off != 0) {
9193 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
9194 return -EINVAL;
9195 }
9196
9197 err = check_reg_arg(env, insn->dst_reg, DST_OP);
9198 if (err)
9199 return err;
9200
9201 dst_reg = &regs[insn->dst_reg];
9202 if (insn->src_reg == 0) {
9203 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9204
9205 dst_reg->type = SCALAR_VALUE;
9206 __mark_reg_known(&regs[insn->dst_reg], imm);
9207 return 0;
9208 }
9209
9210 /* All special src_reg cases are listed below. From this point onwards
9211 * we either succeed and assign a corresponding dst_reg->type after
9212 * zeroing the offset, or fail and reject the program.
9213 */
9214 mark_reg_known_zero(env, regs, insn->dst_reg);
9215
9216 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9217 dst_reg->type = aux->btf_var.reg_type;
9218 switch (dst_reg->type) {
9219 case PTR_TO_MEM:
9220 dst_reg->mem_size = aux->btf_var.mem_size;
9221 break;
9222 case PTR_TO_BTF_ID:
9223 case PTR_TO_PERCPU_BTF_ID:
9224 dst_reg->btf = aux->btf_var.btf;
9225 dst_reg->btf_id = aux->btf_var.btf_id;
9226 break;
9227 default:
9228 verbose(env, "bpf verifier is misconfigured\n");
9229 return -EFAULT;
9230 }
9231 return 0;
9232 }
9233
9234 if (insn->src_reg == BPF_PSEUDO_FUNC) {
9235 struct bpf_prog_aux *aux = env->prog->aux;
9236 u32 subprogno = insn[1].imm;
9237
9238 if (!aux->func_info) {
9239 verbose(env, "missing btf func_info\n");
9240 return -EINVAL;
9241 }
9242 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9243 verbose(env, "callback function not static\n");
9244 return -EINVAL;
9245 }
9246
9247 dst_reg->type = PTR_TO_FUNC;
9248 dst_reg->subprogno = subprogno;
9249 return 0;
9250 }
9251
9252 map = env->used_maps[aux->map_index];
9253 dst_reg->map_ptr = map;
9254
9255 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9256 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
9257 dst_reg->type = PTR_TO_MAP_VALUE;
9258 dst_reg->off = aux->map_off;
9259 if (map_value_has_spin_lock(map))
9260 dst_reg->id = ++env->id_gen;
9261 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9262 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
9263 dst_reg->type = CONST_PTR_TO_MAP;
9264 } else {
9265 verbose(env, "bpf verifier is misconfigured\n");
9266 return -EINVAL;
9267 }
9268
9269 return 0;
9270 }
9271
9272 static bool may_access_skb(enum bpf_prog_type type)
9273 {
9274 switch (type) {
9275 case BPF_PROG_TYPE_SOCKET_FILTER:
9276 case BPF_PROG_TYPE_SCHED_CLS:
9277 case BPF_PROG_TYPE_SCHED_ACT:
9278 return true;
9279 default:
9280 return false;
9281 }
9282 }
9283
9284 /* verify safety of LD_ABS|LD_IND instructions:
9285 * - they can only appear in the programs where ctx == skb
9286 * - since they are wrappers of function calls, they scratch R1-R5 registers,
9287 * preserve R6-R9, and store return value into R0
9288 *
9289 * Implicit input:
9290 * ctx == skb == R6 == CTX
9291 *
9292 * Explicit input:
9293 * SRC == any register
9294 * IMM == 32-bit immediate
9295 *
9296 * Output:
9297 * R0 - 8/16/32-bit skb data converted to cpu endianness
9298 */
9299 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
9300 {
9301 struct bpf_reg_state *regs = cur_regs(env);
9302 static const int ctx_reg = BPF_REG_6;
9303 u8 mode = BPF_MODE(insn->code);
9304 int i, err;
9305
9306 if (!may_access_skb(resolve_prog_type(env->prog))) {
9307 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
9308 return -EINVAL;
9309 }
9310
9311 if (!env->ops->gen_ld_abs) {
9312 verbose(env, "bpf verifier is misconfigured\n");
9313 return -EINVAL;
9314 }
9315
9316 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
9317 BPF_SIZE(insn->code) == BPF_DW ||
9318 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
9319 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
9320 return -EINVAL;
9321 }
9322
9323 /* check whether implicit source operand (register R6) is readable */
9324 err = check_reg_arg(env, ctx_reg, SRC_OP);
9325 if (err)
9326 return err;
9327
9328 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9329 * gen_ld_abs() may terminate the program at runtime, leading to
9330 * reference leak.
9331 */
9332 err = check_reference_leak(env);
9333 if (err) {
9334 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9335 return err;
9336 }
9337
9338 if (env->cur_state->active_spin_lock) {
9339 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9340 return -EINVAL;
9341 }
9342
9343 if (regs[ctx_reg].type != PTR_TO_CTX) {
9344 verbose(env,
9345 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
9346 return -EINVAL;
9347 }
9348
9349 if (mode == BPF_IND) {
9350 /* check explicit source operand */
9351 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9352 if (err)
9353 return err;
9354 }
9355
9356 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9357 if (err < 0)
9358 return err;
9359
9360 /* reset caller saved regs to unreadable */
9361 for (i = 0; i < CALLER_SAVED_REGS; i++) {
9362 mark_reg_not_init(env, regs, caller_saved[i]);
9363 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9364 }
9365
9366 /* mark destination R0 register as readable, since it contains
9367 * the value fetched from the packet.
9368 * Already marked as written above.
9369 */
9370 mark_reg_unknown(env, regs, BPF_REG_0);
9371 /* ld_abs load up to 32-bit skb data. */
9372 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
9373 return 0;
9374 }
9375
9376 static int check_return_code(struct bpf_verifier_env *env)
9377 {
9378 struct tnum enforce_attach_type_range = tnum_unknown;
9379 const struct bpf_prog *prog = env->prog;
9380 struct bpf_reg_state *reg;
9381 struct tnum range = tnum_range(0, 1);
9382 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9383 int err;
9384 struct bpf_func_state *frame = env->cur_state->frame[0];
9385 const bool is_subprog = frame->subprogno;
9386
9387 /* LSM and struct_ops func-ptr's return type could be "void" */
9388 if (!is_subprog &&
9389 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
9390 prog_type == BPF_PROG_TYPE_LSM) &&
9391 !prog->aux->attach_func_proto->type)
9392 return 0;
9393
9394 /* eBPF calling convention is such that R0 is used
9395 * to return the value from eBPF program.
9396 * Make sure that it's readable at this time
9397 * of bpf_exit, which means that program wrote
9398 * something into it earlier
9399 */
9400 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9401 if (err)
9402 return err;
9403
9404 if (is_pointer_value(env, BPF_REG_0)) {
9405 verbose(env, "R0 leaks addr as return value\n");
9406 return -EACCES;
9407 }
9408
9409 reg = cur_regs(env) + BPF_REG_0;
9410
9411 if (frame->in_async_callback_fn) {
9412 /* enforce return zero from async callbacks like timer */
9413 if (reg->type != SCALAR_VALUE) {
9414 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9415 reg_type_str[reg->type]);
9416 return -EINVAL;
9417 }
9418
9419 if (!tnum_in(tnum_const(0), reg->var_off)) {
9420 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9421 return -EINVAL;
9422 }
9423 return 0;
9424 }
9425
9426 if (is_subprog) {
9427 if (reg->type != SCALAR_VALUE) {
9428 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9429 reg_type_str[reg->type]);
9430 return -EINVAL;
9431 }
9432 return 0;
9433 }
9434
9435 switch (prog_type) {
9436 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9437 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
9438 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9439 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9440 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9441 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9442 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
9443 range = tnum_range(1, 1);
9444 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9445 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9446 range = tnum_range(0, 3);
9447 break;
9448 case BPF_PROG_TYPE_CGROUP_SKB:
9449 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9450 range = tnum_range(0, 3);
9451 enforce_attach_type_range = tnum_range(2, 3);
9452 }
9453 break;
9454 case BPF_PROG_TYPE_CGROUP_SOCK:
9455 case BPF_PROG_TYPE_SOCK_OPS:
9456 case BPF_PROG_TYPE_CGROUP_DEVICE:
9457 case BPF_PROG_TYPE_CGROUP_SYSCTL:
9458 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9459 break;
9460 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9461 if (!env->prog->aux->attach_btf_id)
9462 return 0;
9463 range = tnum_const(0);
9464 break;
9465 case BPF_PROG_TYPE_TRACING:
9466 switch (env->prog->expected_attach_type) {
9467 case BPF_TRACE_FENTRY:
9468 case BPF_TRACE_FEXIT:
9469 range = tnum_const(0);
9470 break;
9471 case BPF_TRACE_RAW_TP:
9472 case BPF_MODIFY_RETURN:
9473 return 0;
9474 case BPF_TRACE_ITER:
9475 break;
9476 default:
9477 return -ENOTSUPP;
9478 }
9479 break;
9480 case BPF_PROG_TYPE_SK_LOOKUP:
9481 range = tnum_range(SK_DROP, SK_PASS);
9482 break;
9483 case BPF_PROG_TYPE_EXT:
9484 /* freplace program can return anything as its return value
9485 * depends on the to-be-replaced kernel func or bpf program.
9486 */
9487 default:
9488 return 0;
9489 }
9490
9491 if (reg->type != SCALAR_VALUE) {
9492 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
9493 reg_type_str[reg->type]);
9494 return -EINVAL;
9495 }
9496
9497 if (!tnum_in(range, reg->var_off)) {
9498 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
9499 return -EINVAL;
9500 }
9501
9502 if (!tnum_is_unknown(enforce_attach_type_range) &&
9503 tnum_in(enforce_attach_type_range, reg->var_off))
9504 env->prog->enforce_expected_attach_type = 1;
9505 return 0;
9506 }
9507
9508 /* non-recursive DFS pseudo code
9509 * 1 procedure DFS-iterative(G,v):
9510 * 2 label v as discovered
9511 * 3 let S be a stack
9512 * 4 S.push(v)
9513 * 5 while S is not empty
9514 * 6 t <- S.pop()
9515 * 7 if t is what we're looking for:
9516 * 8 return t
9517 * 9 for all edges e in G.adjacentEdges(t) do
9518 * 10 if edge e is already labelled
9519 * 11 continue with the next edge
9520 * 12 w <- G.adjacentVertex(t,e)
9521 * 13 if vertex w is not discovered and not explored
9522 * 14 label e as tree-edge
9523 * 15 label w as discovered
9524 * 16 S.push(w)
9525 * 17 continue at 5
9526 * 18 else if vertex w is discovered
9527 * 19 label e as back-edge
9528 * 20 else
9529 * 21 // vertex w is explored
9530 * 22 label e as forward- or cross-edge
9531 * 23 label t as explored
9532 * 24 S.pop()
9533 *
9534 * convention:
9535 * 0x10 - discovered
9536 * 0x11 - discovered and fall-through edge labelled
9537 * 0x12 - discovered and fall-through and branch edges labelled
9538 * 0x20 - explored
9539 */
9540
9541 enum {
9542 DISCOVERED = 0x10,
9543 EXPLORED = 0x20,
9544 FALLTHROUGH = 1,
9545 BRANCH = 2,
9546 };
9547
9548 static u32 state_htab_size(struct bpf_verifier_env *env)
9549 {
9550 return env->prog->len;
9551 }
9552
9553 static struct bpf_verifier_state_list **explored_state(
9554 struct bpf_verifier_env *env,
9555 int idx)
9556 {
9557 struct bpf_verifier_state *cur = env->cur_state;
9558 struct bpf_func_state *state = cur->frame[cur->curframe];
9559
9560 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
9561 }
9562
9563 static void init_explored_state(struct bpf_verifier_env *env, int idx)
9564 {
9565 env->insn_aux_data[idx].prune_point = true;
9566 }
9567
9568 enum {
9569 DONE_EXPLORING = 0,
9570 KEEP_EXPLORING = 1,
9571 };
9572
9573 /* t, w, e - match pseudo-code above:
9574 * t - index of current instruction
9575 * w - next instruction
9576 * e - edge
9577 */
9578 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9579 bool loop_ok)
9580 {
9581 int *insn_stack = env->cfg.insn_stack;
9582 int *insn_state = env->cfg.insn_state;
9583
9584 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
9585 return DONE_EXPLORING;
9586
9587 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
9588 return DONE_EXPLORING;
9589
9590 if (w < 0 || w >= env->prog->len) {
9591 verbose_linfo(env, t, "%d: ", t);
9592 verbose(env, "jump out of range from insn %d to %d\n", t, w);
9593 return -EINVAL;
9594 }
9595
9596 if (e == BRANCH)
9597 /* mark branch target for state pruning */
9598 init_explored_state(env, w);
9599
9600 if (insn_state[w] == 0) {
9601 /* tree-edge */
9602 insn_state[t] = DISCOVERED | e;
9603 insn_state[w] = DISCOVERED;
9604 if (env->cfg.cur_stack >= env->prog->len)
9605 return -E2BIG;
9606 insn_stack[env->cfg.cur_stack++] = w;
9607 return KEEP_EXPLORING;
9608 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
9609 if (loop_ok && env->bpf_capable)
9610 return DONE_EXPLORING;
9611 verbose_linfo(env, t, "%d: ", t);
9612 verbose_linfo(env, w, "%d: ", w);
9613 verbose(env, "back-edge from insn %d to %d\n", t, w);
9614 return -EINVAL;
9615 } else if (insn_state[w] == EXPLORED) {
9616 /* forward- or cross-edge */
9617 insn_state[t] = DISCOVERED | e;
9618 } else {
9619 verbose(env, "insn state internal bug\n");
9620 return -EFAULT;
9621 }
9622 return DONE_EXPLORING;
9623 }
9624
9625 static int visit_func_call_insn(int t, int insn_cnt,
9626 struct bpf_insn *insns,
9627 struct bpf_verifier_env *env,
9628 bool visit_callee)
9629 {
9630 int ret;
9631
9632 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9633 if (ret)
9634 return ret;
9635
9636 if (t + 1 < insn_cnt)
9637 init_explored_state(env, t + 1);
9638 if (visit_callee) {
9639 init_explored_state(env, t);
9640 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9641 /* It's ok to allow recursion from CFG point of
9642 * view. __check_func_call() will do the actual
9643 * check.
9644 */
9645 bpf_pseudo_func(insns + t));
9646 }
9647 return ret;
9648 }
9649
9650 /* Visits the instruction at index t and returns one of the following:
9651 * < 0 - an error occurred
9652 * DONE_EXPLORING - the instruction was fully explored
9653 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9654 */
9655 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9656 {
9657 struct bpf_insn *insns = env->prog->insnsi;
9658 int ret;
9659
9660 if (bpf_pseudo_func(insns + t))
9661 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9662
9663 /* All non-branch instructions have a single fall-through edge. */
9664 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9665 BPF_CLASS(insns[t].code) != BPF_JMP32)
9666 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9667
9668 switch (BPF_OP(insns[t].code)) {
9669 case BPF_EXIT:
9670 return DONE_EXPLORING;
9671
9672 case BPF_CALL:
9673 if (insns[t].imm == BPF_FUNC_timer_set_callback)
9674 /* Mark this call insn to trigger is_state_visited() check
9675 * before call itself is processed by __check_func_call().
9676 * Otherwise new async state will be pushed for further
9677 * exploration.
9678 */
9679 init_explored_state(env, t);
9680 return visit_func_call_insn(t, insn_cnt, insns, env,
9681 insns[t].src_reg == BPF_PSEUDO_CALL);
9682
9683 case BPF_JA:
9684 if (BPF_SRC(insns[t].code) != BPF_K)
9685 return -EINVAL;
9686
9687 /* unconditional jump with single edge */
9688 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9689 true);
9690 if (ret)
9691 return ret;
9692
9693 /* unconditional jmp is not a good pruning point,
9694 * but it's marked, since backtracking needs
9695 * to record jmp history in is_state_visited().
9696 */
9697 init_explored_state(env, t + insns[t].off + 1);
9698 /* tell verifier to check for equivalent states
9699 * after every call and jump
9700 */
9701 if (t + 1 < insn_cnt)
9702 init_explored_state(env, t + 1);
9703
9704 return ret;
9705
9706 default:
9707 /* conditional jump with two edges */
9708 init_explored_state(env, t);
9709 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9710 if (ret)
9711 return ret;
9712
9713 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9714 }
9715 }
9716
9717 /* non-recursive depth-first-search to detect loops in BPF program
9718 * loop == back-edge in directed graph
9719 */
9720 static int check_cfg(struct bpf_verifier_env *env)
9721 {
9722 int insn_cnt = env->prog->len;
9723 int *insn_stack, *insn_state;
9724 int ret = 0;
9725 int i;
9726
9727 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9728 if (!insn_state)
9729 return -ENOMEM;
9730
9731 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
9732 if (!insn_stack) {
9733 kvfree(insn_state);
9734 return -ENOMEM;
9735 }
9736
9737 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9738 insn_stack[0] = 0; /* 0 is the first instruction */
9739 env->cfg.cur_stack = 1;
9740
9741 while (env->cfg.cur_stack > 0) {
9742 int t = insn_stack[env->cfg.cur_stack - 1];
9743
9744 ret = visit_insn(t, insn_cnt, env);
9745 switch (ret) {
9746 case DONE_EXPLORING:
9747 insn_state[t] = EXPLORED;
9748 env->cfg.cur_stack--;
9749 break;
9750 case KEEP_EXPLORING:
9751 break;
9752 default:
9753 if (ret > 0) {
9754 verbose(env, "visit_insn internal bug\n");
9755 ret = -EFAULT;
9756 }
9757 goto err_free;
9758 }
9759 }
9760
9761 if (env->cfg.cur_stack < 0) {
9762 verbose(env, "pop stack internal bug\n");
9763 ret = -EFAULT;
9764 goto err_free;
9765 }
9766
9767 for (i = 0; i < insn_cnt; i++) {
9768 if (insn_state[i] != EXPLORED) {
9769 verbose(env, "unreachable insn %d\n", i);
9770 ret = -EINVAL;
9771 goto err_free;
9772 }
9773 }
9774 ret = 0; /* cfg looks good */
9775
9776 err_free:
9777 kvfree(insn_state);
9778 kvfree(insn_stack);
9779 env->cfg.insn_state = env->cfg.insn_stack = NULL;
9780 return ret;
9781 }
9782
9783 static int check_abnormal_return(struct bpf_verifier_env *env)
9784 {
9785 int i;
9786
9787 for (i = 1; i < env->subprog_cnt; i++) {
9788 if (env->subprog_info[i].has_ld_abs) {
9789 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9790 return -EINVAL;
9791 }
9792 if (env->subprog_info[i].has_tail_call) {
9793 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9794 return -EINVAL;
9795 }
9796 }
9797 return 0;
9798 }
9799
9800 /* The minimum supported BTF func info size */
9801 #define MIN_BPF_FUNCINFO_SIZE 8
9802 #define MAX_FUNCINFO_REC_SIZE 252
9803
9804 static int check_btf_func(struct bpf_verifier_env *env,
9805 const union bpf_attr *attr,
9806 bpfptr_t uattr)
9807 {
9808 const struct btf_type *type, *func_proto, *ret_type;
9809 u32 i, nfuncs, urec_size, min_size;
9810 u32 krec_size = sizeof(struct bpf_func_info);
9811 struct bpf_func_info *krecord;
9812 struct bpf_func_info_aux *info_aux = NULL;
9813 struct bpf_prog *prog;
9814 const struct btf *btf;
9815 bpfptr_t urecord;
9816 u32 prev_offset = 0;
9817 bool scalar_return;
9818 int ret = -ENOMEM;
9819
9820 nfuncs = attr->func_info_cnt;
9821 if (!nfuncs) {
9822 if (check_abnormal_return(env))
9823 return -EINVAL;
9824 return 0;
9825 }
9826
9827 if (nfuncs != env->subprog_cnt) {
9828 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9829 return -EINVAL;
9830 }
9831
9832 urec_size = attr->func_info_rec_size;
9833 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9834 urec_size > MAX_FUNCINFO_REC_SIZE ||
9835 urec_size % sizeof(u32)) {
9836 verbose(env, "invalid func info rec size %u\n", urec_size);
9837 return -EINVAL;
9838 }
9839
9840 prog = env->prog;
9841 btf = prog->aux->btf;
9842
9843 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
9844 min_size = min_t(u32, krec_size, urec_size);
9845
9846 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
9847 if (!krecord)
9848 return -ENOMEM;
9849 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9850 if (!info_aux)
9851 goto err_free;
9852
9853 for (i = 0; i < nfuncs; i++) {
9854 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9855 if (ret) {
9856 if (ret == -E2BIG) {
9857 verbose(env, "nonzero tailing record in func info");
9858 /* set the size kernel expects so loader can zero
9859 * out the rest of the record.
9860 */
9861 if (copy_to_bpfptr_offset(uattr,
9862 offsetof(union bpf_attr, func_info_rec_size),
9863 &min_size, sizeof(min_size)))
9864 ret = -EFAULT;
9865 }
9866 goto err_free;
9867 }
9868
9869 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
9870 ret = -EFAULT;
9871 goto err_free;
9872 }
9873
9874 /* check insn_off */
9875 ret = -EINVAL;
9876 if (i == 0) {
9877 if (krecord[i].insn_off) {
9878 verbose(env,
9879 "nonzero insn_off %u for the first func info record",
9880 krecord[i].insn_off);
9881 goto err_free;
9882 }
9883 } else if (krecord[i].insn_off <= prev_offset) {
9884 verbose(env,
9885 "same or smaller insn offset (%u) than previous func info record (%u)",
9886 krecord[i].insn_off, prev_offset);
9887 goto err_free;
9888 }
9889
9890 if (env->subprog_info[i].start != krecord[i].insn_off) {
9891 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
9892 goto err_free;
9893 }
9894
9895 /* check type_id */
9896 type = btf_type_by_id(btf, krecord[i].type_id);
9897 if (!type || !btf_type_is_func(type)) {
9898 verbose(env, "invalid type id %d in func info",
9899 krecord[i].type_id);
9900 goto err_free;
9901 }
9902 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9903
9904 func_proto = btf_type_by_id(btf, type->type);
9905 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9906 /* btf_func_check() already verified it during BTF load */
9907 goto err_free;
9908 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9909 scalar_return =
9910 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9911 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9912 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9913 goto err_free;
9914 }
9915 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9916 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9917 goto err_free;
9918 }
9919
9920 prev_offset = krecord[i].insn_off;
9921 bpfptr_add(&urecord, urec_size);
9922 }
9923
9924 prog->aux->func_info = krecord;
9925 prog->aux->func_info_cnt = nfuncs;
9926 prog->aux->func_info_aux = info_aux;
9927 return 0;
9928
9929 err_free:
9930 kvfree(krecord);
9931 kfree(info_aux);
9932 return ret;
9933 }
9934
9935 static void adjust_btf_func(struct bpf_verifier_env *env)
9936 {
9937 struct bpf_prog_aux *aux = env->prog->aux;
9938 int i;
9939
9940 if (!aux->func_info)
9941 return;
9942
9943 for (i = 0; i < env->subprog_cnt; i++)
9944 aux->func_info[i].insn_off = env->subprog_info[i].start;
9945 }
9946
9947 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9948 sizeof(((struct bpf_line_info *)(0))->line_col))
9949 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9950
9951 static int check_btf_line(struct bpf_verifier_env *env,
9952 const union bpf_attr *attr,
9953 bpfptr_t uattr)
9954 {
9955 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9956 struct bpf_subprog_info *sub;
9957 struct bpf_line_info *linfo;
9958 struct bpf_prog *prog;
9959 const struct btf *btf;
9960 bpfptr_t ulinfo;
9961 int err;
9962
9963 nr_linfo = attr->line_info_cnt;
9964 if (!nr_linfo)
9965 return 0;
9966 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9967 return -EINVAL;
9968
9969 rec_size = attr->line_info_rec_size;
9970 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9971 rec_size > MAX_LINEINFO_REC_SIZE ||
9972 rec_size & (sizeof(u32) - 1))
9973 return -EINVAL;
9974
9975 /* Need to zero it in case the userspace may
9976 * pass in a smaller bpf_line_info object.
9977 */
9978 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9979 GFP_KERNEL | __GFP_NOWARN);
9980 if (!linfo)
9981 return -ENOMEM;
9982
9983 prog = env->prog;
9984 btf = prog->aux->btf;
9985
9986 s = 0;
9987 sub = env->subprog_info;
9988 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
9989 expected_size = sizeof(struct bpf_line_info);
9990 ncopy = min_t(u32, expected_size, rec_size);
9991 for (i = 0; i < nr_linfo; i++) {
9992 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9993 if (err) {
9994 if (err == -E2BIG) {
9995 verbose(env, "nonzero tailing record in line_info");
9996 if (copy_to_bpfptr_offset(uattr,
9997 offsetof(union bpf_attr, line_info_rec_size),
9998 &expected_size, sizeof(expected_size)))
9999 err = -EFAULT;
10000 }
10001 goto err_free;
10002 }
10003
10004 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
10005 err = -EFAULT;
10006 goto err_free;
10007 }
10008
10009 /*
10010 * Check insn_off to ensure
10011 * 1) strictly increasing AND
10012 * 2) bounded by prog->len
10013 *
10014 * The linfo[0].insn_off == 0 check logically falls into
10015 * the later "missing bpf_line_info for func..." case
10016 * because the first linfo[0].insn_off must be the
10017 * first sub also and the first sub must have
10018 * subprog_info[0].start == 0.
10019 */
10020 if ((i && linfo[i].insn_off <= prev_offset) ||
10021 linfo[i].insn_off >= prog->len) {
10022 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10023 i, linfo[i].insn_off, prev_offset,
10024 prog->len);
10025 err = -EINVAL;
10026 goto err_free;
10027 }
10028
10029 if (!prog->insnsi[linfo[i].insn_off].code) {
10030 verbose(env,
10031 "Invalid insn code at line_info[%u].insn_off\n",
10032 i);
10033 err = -EINVAL;
10034 goto err_free;
10035 }
10036
10037 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10038 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
10039 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10040 err = -EINVAL;
10041 goto err_free;
10042 }
10043
10044 if (s != env->subprog_cnt) {
10045 if (linfo[i].insn_off == sub[s].start) {
10046 sub[s].linfo_idx = i;
10047 s++;
10048 } else if (sub[s].start < linfo[i].insn_off) {
10049 verbose(env, "missing bpf_line_info for func#%u\n", s);
10050 err = -EINVAL;
10051 goto err_free;
10052 }
10053 }
10054
10055 prev_offset = linfo[i].insn_off;
10056 bpfptr_add(&ulinfo, rec_size);
10057 }
10058
10059 if (s != env->subprog_cnt) {
10060 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10061 env->subprog_cnt - s, s);
10062 err = -EINVAL;
10063 goto err_free;
10064 }
10065
10066 prog->aux->linfo = linfo;
10067 prog->aux->nr_linfo = nr_linfo;
10068
10069 return 0;
10070
10071 err_free:
10072 kvfree(linfo);
10073 return err;
10074 }
10075
10076 static int check_btf_info(struct bpf_verifier_env *env,
10077 const union bpf_attr *attr,
10078 bpfptr_t uattr)
10079 {
10080 struct btf *btf;
10081 int err;
10082
10083 if (!attr->func_info_cnt && !attr->line_info_cnt) {
10084 if (check_abnormal_return(env))
10085 return -EINVAL;
10086 return 0;
10087 }
10088
10089 btf = btf_get_by_fd(attr->prog_btf_fd);
10090 if (IS_ERR(btf))
10091 return PTR_ERR(btf);
10092 if (btf_is_kernel(btf)) {
10093 btf_put(btf);
10094 return -EACCES;
10095 }
10096 env->prog->aux->btf = btf;
10097
10098 err = check_btf_func(env, attr, uattr);
10099 if (err)
10100 return err;
10101
10102 err = check_btf_line(env, attr, uattr);
10103 if (err)
10104 return err;
10105
10106 return 0;
10107 }
10108
10109 /* check %cur's range satisfies %old's */
10110 static bool range_within(struct bpf_reg_state *old,
10111 struct bpf_reg_state *cur)
10112 {
10113 return old->umin_value <= cur->umin_value &&
10114 old->umax_value >= cur->umax_value &&
10115 old->smin_value <= cur->smin_value &&
10116 old->smax_value >= cur->smax_value &&
10117 old->u32_min_value <= cur->u32_min_value &&
10118 old->u32_max_value >= cur->u32_max_value &&
10119 old->s32_min_value <= cur->s32_min_value &&
10120 old->s32_max_value >= cur->s32_max_value;
10121 }
10122
10123 /* If in the old state two registers had the same id, then they need to have
10124 * the same id in the new state as well. But that id could be different from
10125 * the old state, so we need to track the mapping from old to new ids.
10126 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10127 * regs with old id 5 must also have new id 9 for the new state to be safe. But
10128 * regs with a different old id could still have new id 9, we don't care about
10129 * that.
10130 * So we look through our idmap to see if this old id has been seen before. If
10131 * so, we require the new id to match; otherwise, we add the id pair to the map.
10132 */
10133 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
10134 {
10135 unsigned int i;
10136
10137 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
10138 if (!idmap[i].old) {
10139 /* Reached an empty slot; haven't seen this id before */
10140 idmap[i].old = old_id;
10141 idmap[i].cur = cur_id;
10142 return true;
10143 }
10144 if (idmap[i].old == old_id)
10145 return idmap[i].cur == cur_id;
10146 }
10147 /* We ran out of idmap slots, which should be impossible */
10148 WARN_ON_ONCE(1);
10149 return false;
10150 }
10151
10152 static void clean_func_state(struct bpf_verifier_env *env,
10153 struct bpf_func_state *st)
10154 {
10155 enum bpf_reg_liveness live;
10156 int i, j;
10157
10158 for (i = 0; i < BPF_REG_FP; i++) {
10159 live = st->regs[i].live;
10160 /* liveness must not touch this register anymore */
10161 st->regs[i].live |= REG_LIVE_DONE;
10162 if (!(live & REG_LIVE_READ))
10163 /* since the register is unused, clear its state
10164 * to make further comparison simpler
10165 */
10166 __mark_reg_not_init(env, &st->regs[i]);
10167 }
10168
10169 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10170 live = st->stack[i].spilled_ptr.live;
10171 /* liveness must not touch this stack slot anymore */
10172 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10173 if (!(live & REG_LIVE_READ)) {
10174 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
10175 for (j = 0; j < BPF_REG_SIZE; j++)
10176 st->stack[i].slot_type[j] = STACK_INVALID;
10177 }
10178 }
10179 }
10180
10181 static void clean_verifier_state(struct bpf_verifier_env *env,
10182 struct bpf_verifier_state *st)
10183 {
10184 int i;
10185
10186 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10187 /* all regs in this state in all frames were already marked */
10188 return;
10189
10190 for (i = 0; i <= st->curframe; i++)
10191 clean_func_state(env, st->frame[i]);
10192 }
10193
10194 /* the parentage chains form a tree.
10195 * the verifier states are added to state lists at given insn and
10196 * pushed into state stack for future exploration.
10197 * when the verifier reaches bpf_exit insn some of the verifer states
10198 * stored in the state lists have their final liveness state already,
10199 * but a lot of states will get revised from liveness point of view when
10200 * the verifier explores other branches.
10201 * Example:
10202 * 1: r0 = 1
10203 * 2: if r1 == 100 goto pc+1
10204 * 3: r0 = 2
10205 * 4: exit
10206 * when the verifier reaches exit insn the register r0 in the state list of
10207 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10208 * of insn 2 and goes exploring further. At the insn 4 it will walk the
10209 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10210 *
10211 * Since the verifier pushes the branch states as it sees them while exploring
10212 * the program the condition of walking the branch instruction for the second
10213 * time means that all states below this branch were already explored and
10214 * their final liveness marks are already propagated.
10215 * Hence when the verifier completes the search of state list in is_state_visited()
10216 * we can call this clean_live_states() function to mark all liveness states
10217 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10218 * will not be used.
10219 * This function also clears the registers and stack for states that !READ
10220 * to simplify state merging.
10221 *
10222 * Important note here that walking the same branch instruction in the callee
10223 * doesn't meant that the states are DONE. The verifier has to compare
10224 * the callsites
10225 */
10226 static void clean_live_states(struct bpf_verifier_env *env, int insn,
10227 struct bpf_verifier_state *cur)
10228 {
10229 struct bpf_verifier_state_list *sl;
10230 int i;
10231
10232 sl = *explored_state(env, insn);
10233 while (sl) {
10234 if (sl->state.branches)
10235 goto next;
10236 if (sl->state.insn_idx != insn ||
10237 sl->state.curframe != cur->curframe)
10238 goto next;
10239 for (i = 0; i <= cur->curframe; i++)
10240 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10241 goto next;
10242 clean_verifier_state(env, &sl->state);
10243 next:
10244 sl = sl->next;
10245 }
10246 }
10247
10248 /* Returns true if (rold safe implies rcur safe) */
10249 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10250 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
10251 {
10252 bool equal;
10253
10254 if (!(rold->live & REG_LIVE_READ))
10255 /* explored state didn't use this */
10256 return true;
10257
10258 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
10259
10260 if (rold->type == PTR_TO_STACK)
10261 /* two stack pointers are equal only if they're pointing to
10262 * the same stack frame, since fp-8 in foo != fp-8 in bar
10263 */
10264 return equal && rold->frameno == rcur->frameno;
10265
10266 if (equal)
10267 return true;
10268
10269 if (rold->type == NOT_INIT)
10270 /* explored state can't have used this */
10271 return true;
10272 if (rcur->type == NOT_INIT)
10273 return false;
10274 switch (rold->type) {
10275 case SCALAR_VALUE:
10276 if (env->explore_alu_limits)
10277 return false;
10278 if (rcur->type == SCALAR_VALUE) {
10279 if (!rold->precise && !rcur->precise)
10280 return true;
10281 /* new val must satisfy old val knowledge */
10282 return range_within(rold, rcur) &&
10283 tnum_in(rold->var_off, rcur->var_off);
10284 } else {
10285 /* We're trying to use a pointer in place of a scalar.
10286 * Even if the scalar was unbounded, this could lead to
10287 * pointer leaks because scalars are allowed to leak
10288 * while pointers are not. We could make this safe in
10289 * special cases if root is calling us, but it's
10290 * probably not worth the hassle.
10291 */
10292 return false;
10293 }
10294 case PTR_TO_MAP_KEY:
10295 case PTR_TO_MAP_VALUE:
10296 /* If the new min/max/var_off satisfy the old ones and
10297 * everything else matches, we are OK.
10298 * 'id' is not compared, since it's only used for maps with
10299 * bpf_spin_lock inside map element and in such cases if
10300 * the rest of the prog is valid for one map element then
10301 * it's valid for all map elements regardless of the key
10302 * used in bpf_map_lookup()
10303 */
10304 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10305 range_within(rold, rcur) &&
10306 tnum_in(rold->var_off, rcur->var_off);
10307 case PTR_TO_MAP_VALUE_OR_NULL:
10308 /* a PTR_TO_MAP_VALUE could be safe to use as a
10309 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10310 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10311 * checked, doing so could have affected others with the same
10312 * id, and we can't check for that because we lost the id when
10313 * we converted to a PTR_TO_MAP_VALUE.
10314 */
10315 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10316 return false;
10317 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10318 return false;
10319 /* Check our ids match any regs they're supposed to */
10320 return check_ids(rold->id, rcur->id, idmap);
10321 case PTR_TO_PACKET_META:
10322 case PTR_TO_PACKET:
10323 if (rcur->type != rold->type)
10324 return false;
10325 /* We must have at least as much range as the old ptr
10326 * did, so that any accesses which were safe before are
10327 * still safe. This is true even if old range < old off,
10328 * since someone could have accessed through (ptr - k), or
10329 * even done ptr -= k in a register, to get a safe access.
10330 */
10331 if (rold->range > rcur->range)
10332 return false;
10333 /* If the offsets don't match, we can't trust our alignment;
10334 * nor can we be sure that we won't fall out of range.
10335 */
10336 if (rold->off != rcur->off)
10337 return false;
10338 /* id relations must be preserved */
10339 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10340 return false;
10341 /* new val must satisfy old val knowledge */
10342 return range_within(rold, rcur) &&
10343 tnum_in(rold->var_off, rcur->var_off);
10344 case PTR_TO_CTX:
10345 case CONST_PTR_TO_MAP:
10346 case PTR_TO_PACKET_END:
10347 case PTR_TO_FLOW_KEYS:
10348 case PTR_TO_SOCKET:
10349 case PTR_TO_SOCKET_OR_NULL:
10350 case PTR_TO_SOCK_COMMON:
10351 case PTR_TO_SOCK_COMMON_OR_NULL:
10352 case PTR_TO_TCP_SOCK:
10353 case PTR_TO_TCP_SOCK_OR_NULL:
10354 case PTR_TO_XDP_SOCK:
10355 /* Only valid matches are exact, which memcmp() above
10356 * would have accepted
10357 */
10358 default:
10359 /* Don't know what's going on, just say it's not safe */
10360 return false;
10361 }
10362
10363 /* Shouldn't get here; if we do, say it's not safe */
10364 WARN_ON_ONCE(1);
10365 return false;
10366 }
10367
10368 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10369 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
10370 {
10371 int i, spi;
10372
10373 /* walk slots of the explored stack and ignore any additional
10374 * slots in the current stack, since explored(safe) state
10375 * didn't use them
10376 */
10377 for (i = 0; i < old->allocated_stack; i++) {
10378 spi = i / BPF_REG_SIZE;
10379
10380 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10381 i += BPF_REG_SIZE - 1;
10382 /* explored state didn't use this */
10383 continue;
10384 }
10385
10386 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10387 continue;
10388
10389 /* explored stack has more populated slots than current stack
10390 * and these slots were used
10391 */
10392 if (i >= cur->allocated_stack)
10393 return false;
10394
10395 /* if old state was safe with misc data in the stack
10396 * it will be safe with zero-initialized stack.
10397 * The opposite is not true
10398 */
10399 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10400 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10401 continue;
10402 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10403 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10404 /* Ex: old explored (safe) state has STACK_SPILL in
10405 * this stack slot, but current has STACK_MISC ->
10406 * this verifier states are not equivalent,
10407 * return false to continue verification of this path
10408 */
10409 return false;
10410 if (i % BPF_REG_SIZE)
10411 continue;
10412 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10413 continue;
10414 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10415 &cur->stack[spi].spilled_ptr, idmap))
10416 /* when explored and current stack slot are both storing
10417 * spilled registers, check that stored pointers types
10418 * are the same as well.
10419 * Ex: explored safe path could have stored
10420 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10421 * but current path has stored:
10422 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10423 * such verifier states are not equivalent.
10424 * return false to continue verification of this path
10425 */
10426 return false;
10427 }
10428 return true;
10429 }
10430
10431 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10432 {
10433 if (old->acquired_refs != cur->acquired_refs)
10434 return false;
10435 return !memcmp(old->refs, cur->refs,
10436 sizeof(*old->refs) * old->acquired_refs);
10437 }
10438
10439 /* compare two verifier states
10440 *
10441 * all states stored in state_list are known to be valid, since
10442 * verifier reached 'bpf_exit' instruction through them
10443 *
10444 * this function is called when verifier exploring different branches of
10445 * execution popped from the state stack. If it sees an old state that has
10446 * more strict register state and more strict stack state then this execution
10447 * branch doesn't need to be explored further, since verifier already
10448 * concluded that more strict state leads to valid finish.
10449 *
10450 * Therefore two states are equivalent if register state is more conservative
10451 * and explored stack state is more conservative than the current one.
10452 * Example:
10453 * explored current
10454 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10455 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10456 *
10457 * In other words if current stack state (one being explored) has more
10458 * valid slots than old one that already passed validation, it means
10459 * the verifier can stop exploring and conclude that current state is valid too
10460 *
10461 * Similarly with registers. If explored state has register type as invalid
10462 * whereas register type in current state is meaningful, it means that
10463 * the current state will reach 'bpf_exit' instruction safely
10464 */
10465 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
10466 struct bpf_func_state *cur)
10467 {
10468 int i;
10469
10470 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10471 for (i = 0; i < MAX_BPF_REG; i++)
10472 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10473 env->idmap_scratch))
10474 return false;
10475
10476 if (!stacksafe(env, old, cur, env->idmap_scratch))
10477 return false;
10478
10479 if (!refsafe(old, cur))
10480 return false;
10481
10482 return true;
10483 }
10484
10485 static bool states_equal(struct bpf_verifier_env *env,
10486 struct bpf_verifier_state *old,
10487 struct bpf_verifier_state *cur)
10488 {
10489 int i;
10490
10491 if (old->curframe != cur->curframe)
10492 return false;
10493
10494 /* Verification state from speculative execution simulation
10495 * must never prune a non-speculative execution one.
10496 */
10497 if (old->speculative && !cur->speculative)
10498 return false;
10499
10500 if (old->active_spin_lock != cur->active_spin_lock)
10501 return false;
10502
10503 /* for states to be equal callsites have to be the same
10504 * and all frame states need to be equivalent
10505 */
10506 for (i = 0; i <= old->curframe; i++) {
10507 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10508 return false;
10509 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
10510 return false;
10511 }
10512 return true;
10513 }
10514
10515 /* Return 0 if no propagation happened. Return negative error code if error
10516 * happened. Otherwise, return the propagated bit.
10517 */
10518 static int propagate_liveness_reg(struct bpf_verifier_env *env,
10519 struct bpf_reg_state *reg,
10520 struct bpf_reg_state *parent_reg)
10521 {
10522 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10523 u8 flag = reg->live & REG_LIVE_READ;
10524 int err;
10525
10526 /* When comes here, read flags of PARENT_REG or REG could be any of
10527 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10528 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10529 */
10530 if (parent_flag == REG_LIVE_READ64 ||
10531 /* Or if there is no read flag from REG. */
10532 !flag ||
10533 /* Or if the read flag from REG is the same as PARENT_REG. */
10534 parent_flag == flag)
10535 return 0;
10536
10537 err = mark_reg_read(env, reg, parent_reg, flag);
10538 if (err)
10539 return err;
10540
10541 return flag;
10542 }
10543
10544 /* A write screens off any subsequent reads; but write marks come from the
10545 * straight-line code between a state and its parent. When we arrive at an
10546 * equivalent state (jump target or such) we didn't arrive by the straight-line
10547 * code, so read marks in the state must propagate to the parent regardless
10548 * of the state's write marks. That's what 'parent == state->parent' comparison
10549 * in mark_reg_read() is for.
10550 */
10551 static int propagate_liveness(struct bpf_verifier_env *env,
10552 const struct bpf_verifier_state *vstate,
10553 struct bpf_verifier_state *vparent)
10554 {
10555 struct bpf_reg_state *state_reg, *parent_reg;
10556 struct bpf_func_state *state, *parent;
10557 int i, frame, err = 0;
10558
10559 if (vparent->curframe != vstate->curframe) {
10560 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10561 vparent->curframe, vstate->curframe);
10562 return -EFAULT;
10563 }
10564 /* Propagate read liveness of registers... */
10565 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
10566 for (frame = 0; frame <= vstate->curframe; frame++) {
10567 parent = vparent->frame[frame];
10568 state = vstate->frame[frame];
10569 parent_reg = parent->regs;
10570 state_reg = state->regs;
10571 /* We don't need to worry about FP liveness, it's read-only */
10572 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
10573 err = propagate_liveness_reg(env, &state_reg[i],
10574 &parent_reg[i]);
10575 if (err < 0)
10576 return err;
10577 if (err == REG_LIVE_READ64)
10578 mark_insn_zext(env, &parent_reg[i]);
10579 }
10580
10581 /* Propagate stack slots. */
10582 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10583 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
10584 parent_reg = &parent->stack[i].spilled_ptr;
10585 state_reg = &state->stack[i].spilled_ptr;
10586 err = propagate_liveness_reg(env, state_reg,
10587 parent_reg);
10588 if (err < 0)
10589 return err;
10590 }
10591 }
10592 return 0;
10593 }
10594
10595 /* find precise scalars in the previous equivalent state and
10596 * propagate them into the current state
10597 */
10598 static int propagate_precision(struct bpf_verifier_env *env,
10599 const struct bpf_verifier_state *old)
10600 {
10601 struct bpf_reg_state *state_reg;
10602 struct bpf_func_state *state;
10603 int i, err = 0;
10604
10605 state = old->frame[old->curframe];
10606 state_reg = state->regs;
10607 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10608 if (state_reg->type != SCALAR_VALUE ||
10609 !state_reg->precise)
10610 continue;
10611 if (env->log.level & BPF_LOG_LEVEL2)
10612 verbose(env, "propagating r%d\n", i);
10613 err = mark_chain_precision(env, i);
10614 if (err < 0)
10615 return err;
10616 }
10617
10618 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10619 if (state->stack[i].slot_type[0] != STACK_SPILL)
10620 continue;
10621 state_reg = &state->stack[i].spilled_ptr;
10622 if (state_reg->type != SCALAR_VALUE ||
10623 !state_reg->precise)
10624 continue;
10625 if (env->log.level & BPF_LOG_LEVEL2)
10626 verbose(env, "propagating fp%d\n",
10627 (-i - 1) * BPF_REG_SIZE);
10628 err = mark_chain_precision_stack(env, i);
10629 if (err < 0)
10630 return err;
10631 }
10632 return 0;
10633 }
10634
10635 static bool states_maybe_looping(struct bpf_verifier_state *old,
10636 struct bpf_verifier_state *cur)
10637 {
10638 struct bpf_func_state *fold, *fcur;
10639 int i, fr = cur->curframe;
10640
10641 if (old->curframe != fr)
10642 return false;
10643
10644 fold = old->frame[fr];
10645 fcur = cur->frame[fr];
10646 for (i = 0; i < MAX_BPF_REG; i++)
10647 if (memcmp(&fold->regs[i], &fcur->regs[i],
10648 offsetof(struct bpf_reg_state, parent)))
10649 return false;
10650 return true;
10651 }
10652
10653
10654 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
10655 {
10656 struct bpf_verifier_state_list *new_sl;
10657 struct bpf_verifier_state_list *sl, **pprev;
10658 struct bpf_verifier_state *cur = env->cur_state, *new;
10659 int i, j, err, states_cnt = 0;
10660 bool add_new_state = env->test_state_freq ? true : false;
10661
10662 cur->last_insn_idx = env->prev_insn_idx;
10663 if (!env->insn_aux_data[insn_idx].prune_point)
10664 /* this 'insn_idx' instruction wasn't marked, so we will not
10665 * be doing state search here
10666 */
10667 return 0;
10668
10669 /* bpf progs typically have pruning point every 4 instructions
10670 * http://vger.kernel.org/bpfconf2019.html#session-1
10671 * Do not add new state for future pruning if the verifier hasn't seen
10672 * at least 2 jumps and at least 8 instructions.
10673 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10674 * In tests that amounts to up to 50% reduction into total verifier
10675 * memory consumption and 20% verifier time speedup.
10676 */
10677 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10678 env->insn_processed - env->prev_insn_processed >= 8)
10679 add_new_state = true;
10680
10681 pprev = explored_state(env, insn_idx);
10682 sl = *pprev;
10683
10684 clean_live_states(env, insn_idx, cur);
10685
10686 while (sl) {
10687 states_cnt++;
10688 if (sl->state.insn_idx != insn_idx)
10689 goto next;
10690
10691 if (sl->state.branches) {
10692 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
10693
10694 if (frame->in_async_callback_fn &&
10695 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
10696 /* Different async_entry_cnt means that the verifier is
10697 * processing another entry into async callback.
10698 * Seeing the same state is not an indication of infinite
10699 * loop or infinite recursion.
10700 * But finding the same state doesn't mean that it's safe
10701 * to stop processing the current state. The previous state
10702 * hasn't yet reached bpf_exit, since state.branches > 0.
10703 * Checking in_async_callback_fn alone is not enough either.
10704 * Since the verifier still needs to catch infinite loops
10705 * inside async callbacks.
10706 */
10707 } else if (states_maybe_looping(&sl->state, cur) &&
10708 states_equal(env, &sl->state, cur)) {
10709 verbose_linfo(env, insn_idx, "; ");
10710 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10711 return -EINVAL;
10712 }
10713 /* if the verifier is processing a loop, avoid adding new state
10714 * too often, since different loop iterations have distinct
10715 * states and may not help future pruning.
10716 * This threshold shouldn't be too low to make sure that
10717 * a loop with large bound will be rejected quickly.
10718 * The most abusive loop will be:
10719 * r1 += 1
10720 * if r1 < 1000000 goto pc-2
10721 * 1M insn_procssed limit / 100 == 10k peak states.
10722 * This threshold shouldn't be too high either, since states
10723 * at the end of the loop are likely to be useful in pruning.
10724 */
10725 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10726 env->insn_processed - env->prev_insn_processed < 100)
10727 add_new_state = false;
10728 goto miss;
10729 }
10730 if (states_equal(env, &sl->state, cur)) {
10731 sl->hit_cnt++;
10732 /* reached equivalent register/stack state,
10733 * prune the search.
10734 * Registers read by the continuation are read by us.
10735 * If we have any write marks in env->cur_state, they
10736 * will prevent corresponding reads in the continuation
10737 * from reaching our parent (an explored_state). Our
10738 * own state will get the read marks recorded, but
10739 * they'll be immediately forgotten as we're pruning
10740 * this state and will pop a new one.
10741 */
10742 err = propagate_liveness(env, &sl->state, cur);
10743
10744 /* if previous state reached the exit with precision and
10745 * current state is equivalent to it (except precsion marks)
10746 * the precision needs to be propagated back in
10747 * the current state.
10748 */
10749 err = err ? : push_jmp_history(env, cur);
10750 err = err ? : propagate_precision(env, &sl->state);
10751 if (err)
10752 return err;
10753 return 1;
10754 }
10755 miss:
10756 /* when new state is not going to be added do not increase miss count.
10757 * Otherwise several loop iterations will remove the state
10758 * recorded earlier. The goal of these heuristics is to have
10759 * states from some iterations of the loop (some in the beginning
10760 * and some at the end) to help pruning.
10761 */
10762 if (add_new_state)
10763 sl->miss_cnt++;
10764 /* heuristic to determine whether this state is beneficial
10765 * to keep checking from state equivalence point of view.
10766 * Higher numbers increase max_states_per_insn and verification time,
10767 * but do not meaningfully decrease insn_processed.
10768 */
10769 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10770 /* the state is unlikely to be useful. Remove it to
10771 * speed up verification
10772 */
10773 *pprev = sl->next;
10774 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
10775 u32 br = sl->state.branches;
10776
10777 WARN_ONCE(br,
10778 "BUG live_done but branches_to_explore %d\n",
10779 br);
10780 free_verifier_state(&sl->state, false);
10781 kfree(sl);
10782 env->peak_states--;
10783 } else {
10784 /* cannot free this state, since parentage chain may
10785 * walk it later. Add it for free_list instead to
10786 * be freed at the end of verification
10787 */
10788 sl->next = env->free_list;
10789 env->free_list = sl;
10790 }
10791 sl = *pprev;
10792 continue;
10793 }
10794 next:
10795 pprev = &sl->next;
10796 sl = *pprev;
10797 }
10798
10799 if (env->max_states_per_insn < states_cnt)
10800 env->max_states_per_insn = states_cnt;
10801
10802 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
10803 return push_jmp_history(env, cur);
10804
10805 if (!add_new_state)
10806 return push_jmp_history(env, cur);
10807
10808 /* There were no equivalent states, remember the current one.
10809 * Technically the current state is not proven to be safe yet,
10810 * but it will either reach outer most bpf_exit (which means it's safe)
10811 * or it will be rejected. When there are no loops the verifier won't be
10812 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
10813 * again on the way to bpf_exit.
10814 * When looping the sl->state.branches will be > 0 and this state
10815 * will not be considered for equivalence until branches == 0.
10816 */
10817 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
10818 if (!new_sl)
10819 return -ENOMEM;
10820 env->total_states++;
10821 env->peak_states++;
10822 env->prev_jmps_processed = env->jmps_processed;
10823 env->prev_insn_processed = env->insn_processed;
10824
10825 /* add new state to the head of linked list */
10826 new = &new_sl->state;
10827 err = copy_verifier_state(new, cur);
10828 if (err) {
10829 free_verifier_state(new, false);
10830 kfree(new_sl);
10831 return err;
10832 }
10833 new->insn_idx = insn_idx;
10834 WARN_ONCE(new->branches != 1,
10835 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
10836
10837 cur->parent = new;
10838 cur->first_insn_idx = insn_idx;
10839 clear_jmp_history(cur);
10840 new_sl->next = *explored_state(env, insn_idx);
10841 *explored_state(env, insn_idx) = new_sl;
10842 /* connect new state to parentage chain. Current frame needs all
10843 * registers connected. Only r6 - r9 of the callers are alive (pushed
10844 * to the stack implicitly by JITs) so in callers' frames connect just
10845 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10846 * the state of the call instruction (with WRITTEN set), and r0 comes
10847 * from callee with its full parentage chain, anyway.
10848 */
10849 /* clear write marks in current state: the writes we did are not writes
10850 * our child did, so they don't screen off its reads from us.
10851 * (There are no read marks in current state, because reads always mark
10852 * their parent and current state never has children yet. Only
10853 * explored_states can get read marks.)
10854 */
10855 for (j = 0; j <= cur->curframe; j++) {
10856 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10857 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10858 for (i = 0; i < BPF_REG_FP; i++)
10859 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10860 }
10861
10862 /* all stack frames are accessible from callee, clear them all */
10863 for (j = 0; j <= cur->curframe; j++) {
10864 struct bpf_func_state *frame = cur->frame[j];
10865 struct bpf_func_state *newframe = new->frame[j];
10866
10867 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
10868 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
10869 frame->stack[i].spilled_ptr.parent =
10870 &newframe->stack[i].spilled_ptr;
10871 }
10872 }
10873 return 0;
10874 }
10875
10876 /* Return true if it's OK to have the same insn return a different type. */
10877 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10878 {
10879 switch (type) {
10880 case PTR_TO_CTX:
10881 case PTR_TO_SOCKET:
10882 case PTR_TO_SOCKET_OR_NULL:
10883 case PTR_TO_SOCK_COMMON:
10884 case PTR_TO_SOCK_COMMON_OR_NULL:
10885 case PTR_TO_TCP_SOCK:
10886 case PTR_TO_TCP_SOCK_OR_NULL:
10887 case PTR_TO_XDP_SOCK:
10888 case PTR_TO_BTF_ID:
10889 case PTR_TO_BTF_ID_OR_NULL:
10890 return false;
10891 default:
10892 return true;
10893 }
10894 }
10895
10896 /* If an instruction was previously used with particular pointer types, then we
10897 * need to be careful to avoid cases such as the below, where it may be ok
10898 * for one branch accessing the pointer, but not ok for the other branch:
10899 *
10900 * R1 = sock_ptr
10901 * goto X;
10902 * ...
10903 * R1 = some_other_valid_ptr;
10904 * goto X;
10905 * ...
10906 * R2 = *(u32 *)(R1 + 0);
10907 */
10908 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10909 {
10910 return src != prev && (!reg_type_mismatch_ok(src) ||
10911 !reg_type_mismatch_ok(prev));
10912 }
10913
10914 static int do_check(struct bpf_verifier_env *env)
10915 {
10916 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10917 struct bpf_verifier_state *state = env->cur_state;
10918 struct bpf_insn *insns = env->prog->insnsi;
10919 struct bpf_reg_state *regs;
10920 int insn_cnt = env->prog->len;
10921 bool do_print_state = false;
10922 int prev_insn_idx = -1;
10923
10924 for (;;) {
10925 struct bpf_insn *insn;
10926 u8 class;
10927 int err;
10928
10929 env->prev_insn_idx = prev_insn_idx;
10930 if (env->insn_idx >= insn_cnt) {
10931 verbose(env, "invalid insn idx %d insn_cnt %d\n",
10932 env->insn_idx, insn_cnt);
10933 return -EFAULT;
10934 }
10935
10936 insn = &insns[env->insn_idx];
10937 class = BPF_CLASS(insn->code);
10938
10939 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10940 verbose(env,
10941 "BPF program is too large. Processed %d insn\n",
10942 env->insn_processed);
10943 return -E2BIG;
10944 }
10945
10946 err = is_state_visited(env, env->insn_idx);
10947 if (err < 0)
10948 return err;
10949 if (err == 1) {
10950 /* found equivalent state, can prune the search */
10951 if (env->log.level & BPF_LOG_LEVEL) {
10952 if (do_print_state)
10953 verbose(env, "\nfrom %d to %d%s: safe\n",
10954 env->prev_insn_idx, env->insn_idx,
10955 env->cur_state->speculative ?
10956 " (speculative execution)" : "");
10957 else
10958 verbose(env, "%d: safe\n", env->insn_idx);
10959 }
10960 goto process_bpf_exit;
10961 }
10962
10963 if (signal_pending(current))
10964 return -EAGAIN;
10965
10966 if (need_resched())
10967 cond_resched();
10968
10969 if (env->log.level & BPF_LOG_LEVEL2 ||
10970 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10971 if (env->log.level & BPF_LOG_LEVEL2)
10972 verbose(env, "%d:", env->insn_idx);
10973 else
10974 verbose(env, "\nfrom %d to %d%s:",
10975 env->prev_insn_idx, env->insn_idx,
10976 env->cur_state->speculative ?
10977 " (speculative execution)" : "");
10978 print_verifier_state(env, state->frame[state->curframe]);
10979 do_print_state = false;
10980 }
10981
10982 if (env->log.level & BPF_LOG_LEVEL) {
10983 const struct bpf_insn_cbs cbs = {
10984 .cb_call = disasm_kfunc_name,
10985 .cb_print = verbose,
10986 .private_data = env,
10987 };
10988
10989 verbose_linfo(env, env->insn_idx, "; ");
10990 verbose(env, "%d: ", env->insn_idx);
10991 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10992 }
10993
10994 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10995 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10996 env->prev_insn_idx);
10997 if (err)
10998 return err;
10999 }
11000
11001 regs = cur_regs(env);
11002 sanitize_mark_insn_seen(env);
11003 prev_insn_idx = env->insn_idx;
11004
11005 if (class == BPF_ALU || class == BPF_ALU64) {
11006 err = check_alu_op(env, insn);
11007 if (err)
11008 return err;
11009
11010 } else if (class == BPF_LDX) {
11011 enum bpf_reg_type *prev_src_type, src_reg_type;
11012
11013 /* check for reserved fields is already done */
11014
11015 /* check src operand */
11016 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11017 if (err)
11018 return err;
11019
11020 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
11021 if (err)
11022 return err;
11023
11024 src_reg_type = regs[insn->src_reg].type;
11025
11026 /* check that memory (src_reg + off) is readable,
11027 * the state of dst_reg will be updated by this func
11028 */
11029 err = check_mem_access(env, env->insn_idx, insn->src_reg,
11030 insn->off, BPF_SIZE(insn->code),
11031 BPF_READ, insn->dst_reg, false);
11032 if (err)
11033 return err;
11034
11035 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11036
11037 if (*prev_src_type == NOT_INIT) {
11038 /* saw a valid insn
11039 * dst_reg = *(u32 *)(src_reg + off)
11040 * save type to validate intersecting paths
11041 */
11042 *prev_src_type = src_reg_type;
11043
11044 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
11045 /* ABuser program is trying to use the same insn
11046 * dst_reg = *(u32*) (src_reg + off)
11047 * with different pointer types:
11048 * src_reg == ctx in one branch and
11049 * src_reg == stack|map in some other branch.
11050 * Reject it.
11051 */
11052 verbose(env, "same insn cannot be used with different pointers\n");
11053 return -EINVAL;
11054 }
11055
11056 } else if (class == BPF_STX) {
11057 enum bpf_reg_type *prev_dst_type, dst_reg_type;
11058
11059 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11060 err = check_atomic(env, env->insn_idx, insn);
11061 if (err)
11062 return err;
11063 env->insn_idx++;
11064 continue;
11065 }
11066
11067 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11068 verbose(env, "BPF_STX uses reserved fields\n");
11069 return -EINVAL;
11070 }
11071
11072 /* check src1 operand */
11073 err = check_reg_arg(env, insn->src_reg, SRC_OP);
11074 if (err)
11075 return err;
11076 /* check src2 operand */
11077 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11078 if (err)
11079 return err;
11080
11081 dst_reg_type = regs[insn->dst_reg].type;
11082
11083 /* check that memory (dst_reg + off) is writeable */
11084 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11085 insn->off, BPF_SIZE(insn->code),
11086 BPF_WRITE, insn->src_reg, false);
11087 if (err)
11088 return err;
11089
11090 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
11091
11092 if (*prev_dst_type == NOT_INIT) {
11093 *prev_dst_type = dst_reg_type;
11094 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
11095 verbose(env, "same insn cannot be used with different pointers\n");
11096 return -EINVAL;
11097 }
11098
11099 } else if (class == BPF_ST) {
11100 if (BPF_MODE(insn->code) != BPF_MEM ||
11101 insn->src_reg != BPF_REG_0) {
11102 verbose(env, "BPF_ST uses reserved fields\n");
11103 return -EINVAL;
11104 }
11105 /* check src operand */
11106 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
11107 if (err)
11108 return err;
11109
11110 if (is_ctx_reg(env, insn->dst_reg)) {
11111 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
11112 insn->dst_reg,
11113 reg_type_str[reg_state(env, insn->dst_reg)->type]);
11114 return -EACCES;
11115 }
11116
11117 /* check that memory (dst_reg + off) is writeable */
11118 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11119 insn->off, BPF_SIZE(insn->code),
11120 BPF_WRITE, -1, false);
11121 if (err)
11122 return err;
11123
11124 } else if (class == BPF_JMP || class == BPF_JMP32) {
11125 u8 opcode = BPF_OP(insn->code);
11126
11127 env->jmps_processed++;
11128 if (opcode == BPF_CALL) {
11129 if (BPF_SRC(insn->code) != BPF_K ||
11130 insn->off != 0 ||
11131 (insn->src_reg != BPF_REG_0 &&
11132 insn->src_reg != BPF_PSEUDO_CALL &&
11133 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
11134 insn->dst_reg != BPF_REG_0 ||
11135 class == BPF_JMP32) {
11136 verbose(env, "BPF_CALL uses reserved fields\n");
11137 return -EINVAL;
11138 }
11139
11140 if (env->cur_state->active_spin_lock &&
11141 (insn->src_reg == BPF_PSEUDO_CALL ||
11142 insn->imm != BPF_FUNC_spin_unlock)) {
11143 verbose(env, "function calls are not allowed while holding a lock\n");
11144 return -EINVAL;
11145 }
11146 if (insn->src_reg == BPF_PSEUDO_CALL)
11147 err = check_func_call(env, insn, &env->insn_idx);
11148 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11149 err = check_kfunc_call(env, insn);
11150 else
11151 err = check_helper_call(env, insn, &env->insn_idx);
11152 if (err)
11153 return err;
11154 } else if (opcode == BPF_JA) {
11155 if (BPF_SRC(insn->code) != BPF_K ||
11156 insn->imm != 0 ||
11157 insn->src_reg != BPF_REG_0 ||
11158 insn->dst_reg != BPF_REG_0 ||
11159 class == BPF_JMP32) {
11160 verbose(env, "BPF_JA uses reserved fields\n");
11161 return -EINVAL;
11162 }
11163
11164 env->insn_idx += insn->off + 1;
11165 continue;
11166
11167 } else if (opcode == BPF_EXIT) {
11168 if (BPF_SRC(insn->code) != BPF_K ||
11169 insn->imm != 0 ||
11170 insn->src_reg != BPF_REG_0 ||
11171 insn->dst_reg != BPF_REG_0 ||
11172 class == BPF_JMP32) {
11173 verbose(env, "BPF_EXIT uses reserved fields\n");
11174 return -EINVAL;
11175 }
11176
11177 if (env->cur_state->active_spin_lock) {
11178 verbose(env, "bpf_spin_unlock is missing\n");
11179 return -EINVAL;
11180 }
11181
11182 if (state->curframe) {
11183 /* exit from nested function */
11184 err = prepare_func_exit(env, &env->insn_idx);
11185 if (err)
11186 return err;
11187 do_print_state = true;
11188 continue;
11189 }
11190
11191 err = check_reference_leak(env);
11192 if (err)
11193 return err;
11194
11195 err = check_return_code(env);
11196 if (err)
11197 return err;
11198 process_bpf_exit:
11199 update_branch_counts(env, env->cur_state);
11200 err = pop_stack(env, &prev_insn_idx,
11201 &env->insn_idx, pop_log);
11202 if (err < 0) {
11203 if (err != -ENOENT)
11204 return err;
11205 break;
11206 } else {
11207 do_print_state = true;
11208 continue;
11209 }
11210 } else {
11211 err = check_cond_jmp_op(env, insn, &env->insn_idx);
11212 if (err)
11213 return err;
11214 }
11215 } else if (class == BPF_LD) {
11216 u8 mode = BPF_MODE(insn->code);
11217
11218 if (mode == BPF_ABS || mode == BPF_IND) {
11219 err = check_ld_abs(env, insn);
11220 if (err)
11221 return err;
11222
11223 } else if (mode == BPF_IMM) {
11224 err = check_ld_imm(env, insn);
11225 if (err)
11226 return err;
11227
11228 env->insn_idx++;
11229 sanitize_mark_insn_seen(env);
11230 } else {
11231 verbose(env, "invalid BPF_LD mode\n");
11232 return -EINVAL;
11233 }
11234 } else {
11235 verbose(env, "unknown insn class %d\n", class);
11236 return -EINVAL;
11237 }
11238
11239 env->insn_idx++;
11240 }
11241
11242 return 0;
11243 }
11244
11245 static int find_btf_percpu_datasec(struct btf *btf)
11246 {
11247 const struct btf_type *t;
11248 const char *tname;
11249 int i, n;
11250
11251 /*
11252 * Both vmlinux and module each have their own ".data..percpu"
11253 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11254 * types to look at only module's own BTF types.
11255 */
11256 n = btf_nr_types(btf);
11257 if (btf_is_module(btf))
11258 i = btf_nr_types(btf_vmlinux);
11259 else
11260 i = 1;
11261
11262 for(; i < n; i++) {
11263 t = btf_type_by_id(btf, i);
11264 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11265 continue;
11266
11267 tname = btf_name_by_offset(btf, t->name_off);
11268 if (!strcmp(tname, ".data..percpu"))
11269 return i;
11270 }
11271
11272 return -ENOENT;
11273 }
11274
11275 /* replace pseudo btf_id with kernel symbol address */
11276 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11277 struct bpf_insn *insn,
11278 struct bpf_insn_aux_data *aux)
11279 {
11280 const struct btf_var_secinfo *vsi;
11281 const struct btf_type *datasec;
11282 struct btf_mod_pair *btf_mod;
11283 const struct btf_type *t;
11284 const char *sym_name;
11285 bool percpu = false;
11286 u32 type, id = insn->imm;
11287 struct btf *btf;
11288 s32 datasec_id;
11289 u64 addr;
11290 int i, btf_fd, err;
11291
11292 btf_fd = insn[1].imm;
11293 if (btf_fd) {
11294 btf = btf_get_by_fd(btf_fd);
11295 if (IS_ERR(btf)) {
11296 verbose(env, "invalid module BTF object FD specified.\n");
11297 return -EINVAL;
11298 }
11299 } else {
11300 if (!btf_vmlinux) {
11301 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11302 return -EINVAL;
11303 }
11304 btf = btf_vmlinux;
11305 btf_get(btf);
11306 }
11307
11308 t = btf_type_by_id(btf, id);
11309 if (!t) {
11310 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
11311 err = -ENOENT;
11312 goto err_put;
11313 }
11314
11315 if (!btf_type_is_var(t)) {
11316 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11317 err = -EINVAL;
11318 goto err_put;
11319 }
11320
11321 sym_name = btf_name_by_offset(btf, t->name_off);
11322 addr = kallsyms_lookup_name(sym_name);
11323 if (!addr) {
11324 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11325 sym_name);
11326 err = -ENOENT;
11327 goto err_put;
11328 }
11329
11330 datasec_id = find_btf_percpu_datasec(btf);
11331 if (datasec_id > 0) {
11332 datasec = btf_type_by_id(btf, datasec_id);
11333 for_each_vsi(i, datasec, vsi) {
11334 if (vsi->type == id) {
11335 percpu = true;
11336 break;
11337 }
11338 }
11339 }
11340
11341 insn[0].imm = (u32)addr;
11342 insn[1].imm = addr >> 32;
11343
11344 type = t->type;
11345 t = btf_type_skip_modifiers(btf, type, NULL);
11346 if (percpu) {
11347 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
11348 aux->btf_var.btf = btf;
11349 aux->btf_var.btf_id = type;
11350 } else if (!btf_type_is_struct(t)) {
11351 const struct btf_type *ret;
11352 const char *tname;
11353 u32 tsize;
11354
11355 /* resolve the type size of ksym. */
11356 ret = btf_resolve_size(btf, t, &tsize);
11357 if (IS_ERR(ret)) {
11358 tname = btf_name_by_offset(btf, t->name_off);
11359 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11360 tname, PTR_ERR(ret));
11361 err = -EINVAL;
11362 goto err_put;
11363 }
11364 aux->btf_var.reg_type = PTR_TO_MEM;
11365 aux->btf_var.mem_size = tsize;
11366 } else {
11367 aux->btf_var.reg_type = PTR_TO_BTF_ID;
11368 aux->btf_var.btf = btf;
11369 aux->btf_var.btf_id = type;
11370 }
11371
11372 /* check whether we recorded this BTF (and maybe module) already */
11373 for (i = 0; i < env->used_btf_cnt; i++) {
11374 if (env->used_btfs[i].btf == btf) {
11375 btf_put(btf);
11376 return 0;
11377 }
11378 }
11379
11380 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11381 err = -E2BIG;
11382 goto err_put;
11383 }
11384
11385 btf_mod = &env->used_btfs[env->used_btf_cnt];
11386 btf_mod->btf = btf;
11387 btf_mod->module = NULL;
11388
11389 /* if we reference variables from kernel module, bump its refcount */
11390 if (btf_is_module(btf)) {
11391 btf_mod->module = btf_try_get_module(btf);
11392 if (!btf_mod->module) {
11393 err = -ENXIO;
11394 goto err_put;
11395 }
11396 }
11397
11398 env->used_btf_cnt++;
11399
11400 return 0;
11401 err_put:
11402 btf_put(btf);
11403 return err;
11404 }
11405
11406 static int check_map_prealloc(struct bpf_map *map)
11407 {
11408 return (map->map_type != BPF_MAP_TYPE_HASH &&
11409 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11410 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
11411 !(map->map_flags & BPF_F_NO_PREALLOC);
11412 }
11413
11414 static bool is_tracing_prog_type(enum bpf_prog_type type)
11415 {
11416 switch (type) {
11417 case BPF_PROG_TYPE_KPROBE:
11418 case BPF_PROG_TYPE_TRACEPOINT:
11419 case BPF_PROG_TYPE_PERF_EVENT:
11420 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11421 return true;
11422 default:
11423 return false;
11424 }
11425 }
11426
11427 static bool is_preallocated_map(struct bpf_map *map)
11428 {
11429 if (!check_map_prealloc(map))
11430 return false;
11431 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11432 return false;
11433 return true;
11434 }
11435
11436 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11437 struct bpf_map *map,
11438 struct bpf_prog *prog)
11439
11440 {
11441 enum bpf_prog_type prog_type = resolve_prog_type(prog);
11442 /*
11443 * Validate that trace type programs use preallocated hash maps.
11444 *
11445 * For programs attached to PERF events this is mandatory as the
11446 * perf NMI can hit any arbitrary code sequence.
11447 *
11448 * All other trace types using preallocated hash maps are unsafe as
11449 * well because tracepoint or kprobes can be inside locked regions
11450 * of the memory allocator or at a place where a recursion into the
11451 * memory allocator would see inconsistent state.
11452 *
11453 * On RT enabled kernels run-time allocation of all trace type
11454 * programs is strictly prohibited due to lock type constraints. On
11455 * !RT kernels it is allowed for backwards compatibility reasons for
11456 * now, but warnings are emitted so developers are made aware of
11457 * the unsafety and can fix their programs before this is enforced.
11458 */
11459 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11460 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
11461 verbose(env, "perf_event programs can only use preallocated hash map\n");
11462 return -EINVAL;
11463 }
11464 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11465 verbose(env, "trace type programs can only use preallocated hash map\n");
11466 return -EINVAL;
11467 }
11468 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11469 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
11470 }
11471
11472 if (map_value_has_spin_lock(map)) {
11473 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11474 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11475 return -EINVAL;
11476 }
11477
11478 if (is_tracing_prog_type(prog_type)) {
11479 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11480 return -EINVAL;
11481 }
11482
11483 if (prog->aux->sleepable) {
11484 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11485 return -EINVAL;
11486 }
11487 }
11488
11489 if (map_value_has_timer(map)) {
11490 if (is_tracing_prog_type(prog_type)) {
11491 verbose(env, "tracing progs cannot use bpf_timer yet\n");
11492 return -EINVAL;
11493 }
11494 }
11495
11496 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
11497 !bpf_offload_prog_map_match(prog, map)) {
11498 verbose(env, "offload device mismatch between prog and map\n");
11499 return -EINVAL;
11500 }
11501
11502 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11503 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11504 return -EINVAL;
11505 }
11506
11507 if (prog->aux->sleepable)
11508 switch (map->map_type) {
11509 case BPF_MAP_TYPE_HASH:
11510 case BPF_MAP_TYPE_LRU_HASH:
11511 case BPF_MAP_TYPE_ARRAY:
11512 case BPF_MAP_TYPE_PERCPU_HASH:
11513 case BPF_MAP_TYPE_PERCPU_ARRAY:
11514 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11515 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11516 case BPF_MAP_TYPE_HASH_OF_MAPS:
11517 if (!is_preallocated_map(map)) {
11518 verbose(env,
11519 "Sleepable programs can only use preallocated maps\n");
11520 return -EINVAL;
11521 }
11522 break;
11523 case BPF_MAP_TYPE_RINGBUF:
11524 break;
11525 default:
11526 verbose(env,
11527 "Sleepable programs can only use array, hash, and ringbuf maps\n");
11528 return -EINVAL;
11529 }
11530
11531 return 0;
11532 }
11533
11534 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11535 {
11536 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11537 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11538 }
11539
11540 /* find and rewrite pseudo imm in ld_imm64 instructions:
11541 *
11542 * 1. if it accesses map FD, replace it with actual map pointer.
11543 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11544 *
11545 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
11546 */
11547 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
11548 {
11549 struct bpf_insn *insn = env->prog->insnsi;
11550 int insn_cnt = env->prog->len;
11551 int i, j, err;
11552
11553 err = bpf_prog_calc_tag(env->prog);
11554 if (err)
11555 return err;
11556
11557 for (i = 0; i < insn_cnt; i++, insn++) {
11558 if (BPF_CLASS(insn->code) == BPF_LDX &&
11559 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
11560 verbose(env, "BPF_LDX uses reserved fields\n");
11561 return -EINVAL;
11562 }
11563
11564 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
11565 struct bpf_insn_aux_data *aux;
11566 struct bpf_map *map;
11567 struct fd f;
11568 u64 addr;
11569 u32 fd;
11570
11571 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11572 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11573 insn[1].off != 0) {
11574 verbose(env, "invalid bpf_ld_imm64 insn\n");
11575 return -EINVAL;
11576 }
11577
11578 if (insn[0].src_reg == 0)
11579 /* valid generic load 64-bit imm */
11580 goto next_insn;
11581
11582 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11583 aux = &env->insn_aux_data[i];
11584 err = check_pseudo_btf_id(env, insn, aux);
11585 if (err)
11586 return err;
11587 goto next_insn;
11588 }
11589
11590 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11591 aux = &env->insn_aux_data[i];
11592 aux->ptr_type = PTR_TO_FUNC;
11593 goto next_insn;
11594 }
11595
11596 /* In final convert_pseudo_ld_imm64() step, this is
11597 * converted into regular 64-bit imm load insn.
11598 */
11599 switch (insn[0].src_reg) {
11600 case BPF_PSEUDO_MAP_VALUE:
11601 case BPF_PSEUDO_MAP_IDX_VALUE:
11602 break;
11603 case BPF_PSEUDO_MAP_FD:
11604 case BPF_PSEUDO_MAP_IDX:
11605 if (insn[1].imm == 0)
11606 break;
11607 fallthrough;
11608 default:
11609 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
11610 return -EINVAL;
11611 }
11612
11613 switch (insn[0].src_reg) {
11614 case BPF_PSEUDO_MAP_IDX_VALUE:
11615 case BPF_PSEUDO_MAP_IDX:
11616 if (bpfptr_is_null(env->fd_array)) {
11617 verbose(env, "fd_idx without fd_array is invalid\n");
11618 return -EPROTO;
11619 }
11620 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11621 insn[0].imm * sizeof(fd),
11622 sizeof(fd)))
11623 return -EFAULT;
11624 break;
11625 default:
11626 fd = insn[0].imm;
11627 break;
11628 }
11629
11630 f = fdget(fd);
11631 map = __bpf_map_get(f);
11632 if (IS_ERR(map)) {
11633 verbose(env, "fd %d is not pointing to valid bpf_map\n",
11634 insn[0].imm);
11635 return PTR_ERR(map);
11636 }
11637
11638 err = check_map_prog_compatibility(env, map, env->prog);
11639 if (err) {
11640 fdput(f);
11641 return err;
11642 }
11643
11644 aux = &env->insn_aux_data[i];
11645 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11646 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
11647 addr = (unsigned long)map;
11648 } else {
11649 u32 off = insn[1].imm;
11650
11651 if (off >= BPF_MAX_VAR_OFF) {
11652 verbose(env, "direct value offset of %u is not allowed\n", off);
11653 fdput(f);
11654 return -EINVAL;
11655 }
11656
11657 if (!map->ops->map_direct_value_addr) {
11658 verbose(env, "no direct value access support for this map type\n");
11659 fdput(f);
11660 return -EINVAL;
11661 }
11662
11663 err = map->ops->map_direct_value_addr(map, &addr, off);
11664 if (err) {
11665 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11666 map->value_size, off);
11667 fdput(f);
11668 return err;
11669 }
11670
11671 aux->map_off = off;
11672 addr += off;
11673 }
11674
11675 insn[0].imm = (u32)addr;
11676 insn[1].imm = addr >> 32;
11677
11678 /* check whether we recorded this map already */
11679 for (j = 0; j < env->used_map_cnt; j++) {
11680 if (env->used_maps[j] == map) {
11681 aux->map_index = j;
11682 fdput(f);
11683 goto next_insn;
11684 }
11685 }
11686
11687 if (env->used_map_cnt >= MAX_USED_MAPS) {
11688 fdput(f);
11689 return -E2BIG;
11690 }
11691
11692 /* hold the map. If the program is rejected by verifier,
11693 * the map will be released by release_maps() or it
11694 * will be used by the valid program until it's unloaded
11695 * and all maps are released in free_used_maps()
11696 */
11697 bpf_map_inc(map);
11698
11699 aux->map_index = env->used_map_cnt;
11700 env->used_maps[env->used_map_cnt++] = map;
11701
11702 if (bpf_map_is_cgroup_storage(map) &&
11703 bpf_cgroup_storage_assign(env->prog->aux, map)) {
11704 verbose(env, "only one cgroup storage of each type is allowed\n");
11705 fdput(f);
11706 return -EBUSY;
11707 }
11708
11709 fdput(f);
11710 next_insn:
11711 insn++;
11712 i++;
11713 continue;
11714 }
11715
11716 /* Basic sanity check before we invest more work here. */
11717 if (!bpf_opcode_in_insntable(insn->code)) {
11718 verbose(env, "unknown opcode %02x\n", insn->code);
11719 return -EINVAL;
11720 }
11721 }
11722
11723 /* now all pseudo BPF_LD_IMM64 instructions load valid
11724 * 'struct bpf_map *' into a register instead of user map_fd.
11725 * These pointers will be used later by verifier to validate map access.
11726 */
11727 return 0;
11728 }
11729
11730 /* drop refcnt of maps used by the rejected program */
11731 static void release_maps(struct bpf_verifier_env *env)
11732 {
11733 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11734 env->used_map_cnt);
11735 }
11736
11737 /* drop refcnt of maps used by the rejected program */
11738 static void release_btfs(struct bpf_verifier_env *env)
11739 {
11740 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11741 env->used_btf_cnt);
11742 }
11743
11744 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
11745 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
11746 {
11747 struct bpf_insn *insn = env->prog->insnsi;
11748 int insn_cnt = env->prog->len;
11749 int i;
11750
11751 for (i = 0; i < insn_cnt; i++, insn++) {
11752 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11753 continue;
11754 if (insn->src_reg == BPF_PSEUDO_FUNC)
11755 continue;
11756 insn->src_reg = 0;
11757 }
11758 }
11759
11760 /* single env->prog->insni[off] instruction was replaced with the range
11761 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11762 * [0, off) and [off, end) to new locations, so the patched range stays zero
11763 */
11764 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
11765 struct bpf_insn_aux_data *new_data,
11766 struct bpf_prog *new_prog, u32 off, u32 cnt)
11767 {
11768 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
11769 struct bpf_insn *insn = new_prog->insnsi;
11770 u32 old_seen = old_data[off].seen;
11771 u32 prog_len;
11772 int i;
11773
11774 /* aux info at OFF always needs adjustment, no matter fast path
11775 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11776 * original insn at old prog.
11777 */
11778 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11779
11780 if (cnt == 1)
11781 return;
11782 prog_len = new_prog->len;
11783
11784 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11785 memcpy(new_data + off + cnt - 1, old_data + off,
11786 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
11787 for (i = off; i < off + cnt - 1; i++) {
11788 /* Expand insni[off]'s seen count to the patched range. */
11789 new_data[i].seen = old_seen;
11790 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11791 }
11792 env->insn_aux_data = new_data;
11793 vfree(old_data);
11794 }
11795
11796 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11797 {
11798 int i;
11799
11800 if (len == 1)
11801 return;
11802 /* NOTE: fake 'exit' subprog should be updated as well. */
11803 for (i = 0; i <= env->subprog_cnt; i++) {
11804 if (env->subprog_info[i].start <= off)
11805 continue;
11806 env->subprog_info[i].start += len - 1;
11807 }
11808 }
11809
11810 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
11811 {
11812 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11813 int i, sz = prog->aux->size_poke_tab;
11814 struct bpf_jit_poke_descriptor *desc;
11815
11816 for (i = 0; i < sz; i++) {
11817 desc = &tab[i];
11818 if (desc->insn_idx <= off)
11819 continue;
11820 desc->insn_idx += len - 1;
11821 }
11822 }
11823
11824 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11825 const struct bpf_insn *patch, u32 len)
11826 {
11827 struct bpf_prog *new_prog;
11828 struct bpf_insn_aux_data *new_data = NULL;
11829
11830 if (len > 1) {
11831 new_data = vzalloc(array_size(env->prog->len + len - 1,
11832 sizeof(struct bpf_insn_aux_data)));
11833 if (!new_data)
11834 return NULL;
11835 }
11836
11837 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
11838 if (IS_ERR(new_prog)) {
11839 if (PTR_ERR(new_prog) == -ERANGE)
11840 verbose(env,
11841 "insn %d cannot be patched due to 16-bit range\n",
11842 env->insn_aux_data[off].orig_idx);
11843 vfree(new_data);
11844 return NULL;
11845 }
11846 adjust_insn_aux_data(env, new_data, new_prog, off, len);
11847 adjust_subprog_starts(env, off, len);
11848 adjust_poke_descs(new_prog, off, len);
11849 return new_prog;
11850 }
11851
11852 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11853 u32 off, u32 cnt)
11854 {
11855 int i, j;
11856
11857 /* find first prog starting at or after off (first to remove) */
11858 for (i = 0; i < env->subprog_cnt; i++)
11859 if (env->subprog_info[i].start >= off)
11860 break;
11861 /* find first prog starting at or after off + cnt (first to stay) */
11862 for (j = i; j < env->subprog_cnt; j++)
11863 if (env->subprog_info[j].start >= off + cnt)
11864 break;
11865 /* if j doesn't start exactly at off + cnt, we are just removing
11866 * the front of previous prog
11867 */
11868 if (env->subprog_info[j].start != off + cnt)
11869 j--;
11870
11871 if (j > i) {
11872 struct bpf_prog_aux *aux = env->prog->aux;
11873 int move;
11874
11875 /* move fake 'exit' subprog as well */
11876 move = env->subprog_cnt + 1 - j;
11877
11878 memmove(env->subprog_info + i,
11879 env->subprog_info + j,
11880 sizeof(*env->subprog_info) * move);
11881 env->subprog_cnt -= j - i;
11882
11883 /* remove func_info */
11884 if (aux->func_info) {
11885 move = aux->func_info_cnt - j;
11886
11887 memmove(aux->func_info + i,
11888 aux->func_info + j,
11889 sizeof(*aux->func_info) * move);
11890 aux->func_info_cnt -= j - i;
11891 /* func_info->insn_off is set after all code rewrites,
11892 * in adjust_btf_func() - no need to adjust
11893 */
11894 }
11895 } else {
11896 /* convert i from "first prog to remove" to "first to adjust" */
11897 if (env->subprog_info[i].start == off)
11898 i++;
11899 }
11900
11901 /* update fake 'exit' subprog as well */
11902 for (; i <= env->subprog_cnt; i++)
11903 env->subprog_info[i].start -= cnt;
11904
11905 return 0;
11906 }
11907
11908 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11909 u32 cnt)
11910 {
11911 struct bpf_prog *prog = env->prog;
11912 u32 i, l_off, l_cnt, nr_linfo;
11913 struct bpf_line_info *linfo;
11914
11915 nr_linfo = prog->aux->nr_linfo;
11916 if (!nr_linfo)
11917 return 0;
11918
11919 linfo = prog->aux->linfo;
11920
11921 /* find first line info to remove, count lines to be removed */
11922 for (i = 0; i < nr_linfo; i++)
11923 if (linfo[i].insn_off >= off)
11924 break;
11925
11926 l_off = i;
11927 l_cnt = 0;
11928 for (; i < nr_linfo; i++)
11929 if (linfo[i].insn_off < off + cnt)
11930 l_cnt++;
11931 else
11932 break;
11933
11934 /* First live insn doesn't match first live linfo, it needs to "inherit"
11935 * last removed linfo. prog is already modified, so prog->len == off
11936 * means no live instructions after (tail of the program was removed).
11937 */
11938 if (prog->len != off && l_cnt &&
11939 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11940 l_cnt--;
11941 linfo[--i].insn_off = off + cnt;
11942 }
11943
11944 /* remove the line info which refer to the removed instructions */
11945 if (l_cnt) {
11946 memmove(linfo + l_off, linfo + i,
11947 sizeof(*linfo) * (nr_linfo - i));
11948
11949 prog->aux->nr_linfo -= l_cnt;
11950 nr_linfo = prog->aux->nr_linfo;
11951 }
11952
11953 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11954 for (i = l_off; i < nr_linfo; i++)
11955 linfo[i].insn_off -= cnt;
11956
11957 /* fix up all subprogs (incl. 'exit') which start >= off */
11958 for (i = 0; i <= env->subprog_cnt; i++)
11959 if (env->subprog_info[i].linfo_idx > l_off) {
11960 /* program may have started in the removed region but
11961 * may not be fully removed
11962 */
11963 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11964 env->subprog_info[i].linfo_idx -= l_cnt;
11965 else
11966 env->subprog_info[i].linfo_idx = l_off;
11967 }
11968
11969 return 0;
11970 }
11971
11972 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11973 {
11974 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11975 unsigned int orig_prog_len = env->prog->len;
11976 int err;
11977
11978 if (bpf_prog_is_dev_bound(env->prog->aux))
11979 bpf_prog_offload_remove_insns(env, off, cnt);
11980
11981 err = bpf_remove_insns(env->prog, off, cnt);
11982 if (err)
11983 return err;
11984
11985 err = adjust_subprog_starts_after_remove(env, off, cnt);
11986 if (err)
11987 return err;
11988
11989 err = bpf_adj_linfo_after_remove(env, off, cnt);
11990 if (err)
11991 return err;
11992
11993 memmove(aux_data + off, aux_data + off + cnt,
11994 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11995
11996 return 0;
11997 }
11998
11999 /* The verifier does more data flow analysis than llvm and will not
12000 * explore branches that are dead at run time. Malicious programs can
12001 * have dead code too. Therefore replace all dead at-run-time code
12002 * with 'ja -1'.
12003 *
12004 * Just nops are not optimal, e.g. if they would sit at the end of the
12005 * program and through another bug we would manage to jump there, then
12006 * we'd execute beyond program memory otherwise. Returning exception
12007 * code also wouldn't work since we can have subprogs where the dead
12008 * code could be located.
12009 */
12010 static void sanitize_dead_code(struct bpf_verifier_env *env)
12011 {
12012 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12013 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
12014 struct bpf_insn *insn = env->prog->insnsi;
12015 const int insn_cnt = env->prog->len;
12016 int i;
12017
12018 for (i = 0; i < insn_cnt; i++) {
12019 if (aux_data[i].seen)
12020 continue;
12021 memcpy(insn + i, &trap, sizeof(trap));
12022 aux_data[i].zext_dst = false;
12023 }
12024 }
12025
12026 static bool insn_is_cond_jump(u8 code)
12027 {
12028 u8 op;
12029
12030 if (BPF_CLASS(code) == BPF_JMP32)
12031 return true;
12032
12033 if (BPF_CLASS(code) != BPF_JMP)
12034 return false;
12035
12036 op = BPF_OP(code);
12037 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12038 }
12039
12040 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12041 {
12042 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12043 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12044 struct bpf_insn *insn = env->prog->insnsi;
12045 const int insn_cnt = env->prog->len;
12046 int i;
12047
12048 for (i = 0; i < insn_cnt; i++, insn++) {
12049 if (!insn_is_cond_jump(insn->code))
12050 continue;
12051
12052 if (!aux_data[i + 1].seen)
12053 ja.off = insn->off;
12054 else if (!aux_data[i + 1 + insn->off].seen)
12055 ja.off = 0;
12056 else
12057 continue;
12058
12059 if (bpf_prog_is_dev_bound(env->prog->aux))
12060 bpf_prog_offload_replace_insn(env, i, &ja);
12061
12062 memcpy(insn, &ja, sizeof(ja));
12063 }
12064 }
12065
12066 static int opt_remove_dead_code(struct bpf_verifier_env *env)
12067 {
12068 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12069 int insn_cnt = env->prog->len;
12070 int i, err;
12071
12072 for (i = 0; i < insn_cnt; i++) {
12073 int j;
12074
12075 j = 0;
12076 while (i + j < insn_cnt && !aux_data[i + j].seen)
12077 j++;
12078 if (!j)
12079 continue;
12080
12081 err = verifier_remove_insns(env, i, j);
12082 if (err)
12083 return err;
12084 insn_cnt = env->prog->len;
12085 }
12086
12087 return 0;
12088 }
12089
12090 static int opt_remove_nops(struct bpf_verifier_env *env)
12091 {
12092 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12093 struct bpf_insn *insn = env->prog->insnsi;
12094 int insn_cnt = env->prog->len;
12095 int i, err;
12096
12097 for (i = 0; i < insn_cnt; i++) {
12098 if (memcmp(&insn[i], &ja, sizeof(ja)))
12099 continue;
12100
12101 err = verifier_remove_insns(env, i, 1);
12102 if (err)
12103 return err;
12104 insn_cnt--;
12105 i--;
12106 }
12107
12108 return 0;
12109 }
12110
12111 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12112 const union bpf_attr *attr)
12113 {
12114 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
12115 struct bpf_insn_aux_data *aux = env->insn_aux_data;
12116 int i, patch_len, delta = 0, len = env->prog->len;
12117 struct bpf_insn *insns = env->prog->insnsi;
12118 struct bpf_prog *new_prog;
12119 bool rnd_hi32;
12120
12121 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
12122 zext_patch[1] = BPF_ZEXT_REG(0);
12123 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12124 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12125 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
12126 for (i = 0; i < len; i++) {
12127 int adj_idx = i + delta;
12128 struct bpf_insn insn;
12129 int load_reg;
12130
12131 insn = insns[adj_idx];
12132 load_reg = insn_def_regno(&insn);
12133 if (!aux[adj_idx].zext_dst) {
12134 u8 code, class;
12135 u32 imm_rnd;
12136
12137 if (!rnd_hi32)
12138 continue;
12139
12140 code = insn.code;
12141 class = BPF_CLASS(code);
12142 if (load_reg == -1)
12143 continue;
12144
12145 /* NOTE: arg "reg" (the fourth one) is only used for
12146 * BPF_STX + SRC_OP, so it is safe to pass NULL
12147 * here.
12148 */
12149 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
12150 if (class == BPF_LD &&
12151 BPF_MODE(code) == BPF_IMM)
12152 i++;
12153 continue;
12154 }
12155
12156 /* ctx load could be transformed into wider load. */
12157 if (class == BPF_LDX &&
12158 aux[adj_idx].ptr_type == PTR_TO_CTX)
12159 continue;
12160
12161 imm_rnd = get_random_int();
12162 rnd_hi32_patch[0] = insn;
12163 rnd_hi32_patch[1].imm = imm_rnd;
12164 rnd_hi32_patch[3].dst_reg = load_reg;
12165 patch = rnd_hi32_patch;
12166 patch_len = 4;
12167 goto apply_patch_buffer;
12168 }
12169
12170 /* Add in an zero-extend instruction if a) the JIT has requested
12171 * it or b) it's a CMPXCHG.
12172 *
12173 * The latter is because: BPF_CMPXCHG always loads a value into
12174 * R0, therefore always zero-extends. However some archs'
12175 * equivalent instruction only does this load when the
12176 * comparison is successful. This detail of CMPXCHG is
12177 * orthogonal to the general zero-extension behaviour of the
12178 * CPU, so it's treated independently of bpf_jit_needs_zext.
12179 */
12180 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
12181 continue;
12182
12183 if (WARN_ON(load_reg == -1)) {
12184 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12185 return -EFAULT;
12186 }
12187
12188 zext_patch[0] = insn;
12189 zext_patch[1].dst_reg = load_reg;
12190 zext_patch[1].src_reg = load_reg;
12191 patch = zext_patch;
12192 patch_len = 2;
12193 apply_patch_buffer:
12194 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
12195 if (!new_prog)
12196 return -ENOMEM;
12197 env->prog = new_prog;
12198 insns = new_prog->insnsi;
12199 aux = env->insn_aux_data;
12200 delta += patch_len - 1;
12201 }
12202
12203 return 0;
12204 }
12205
12206 /* convert load instructions that access fields of a context type into a
12207 * sequence of instructions that access fields of the underlying structure:
12208 * struct __sk_buff -> struct sk_buff
12209 * struct bpf_sock_ops -> struct sock
12210 */
12211 static int convert_ctx_accesses(struct bpf_verifier_env *env)
12212 {
12213 const struct bpf_verifier_ops *ops = env->ops;
12214 int i, cnt, size, ctx_field_size, delta = 0;
12215 const int insn_cnt = env->prog->len;
12216 struct bpf_insn insn_buf[16], *insn;
12217 u32 target_size, size_default, off;
12218 struct bpf_prog *new_prog;
12219 enum bpf_access_type type;
12220 bool is_narrower_load;
12221
12222 if (ops->gen_prologue || env->seen_direct_write) {
12223 if (!ops->gen_prologue) {
12224 verbose(env, "bpf verifier is misconfigured\n");
12225 return -EINVAL;
12226 }
12227 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12228 env->prog);
12229 if (cnt >= ARRAY_SIZE(insn_buf)) {
12230 verbose(env, "bpf verifier is misconfigured\n");
12231 return -EINVAL;
12232 } else if (cnt) {
12233 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
12234 if (!new_prog)
12235 return -ENOMEM;
12236
12237 env->prog = new_prog;
12238 delta += cnt - 1;
12239 }
12240 }
12241
12242 if (bpf_prog_is_dev_bound(env->prog->aux))
12243 return 0;
12244
12245 insn = env->prog->insnsi + delta;
12246
12247 for (i = 0; i < insn_cnt; i++, insn++) {
12248 bpf_convert_ctx_access_t convert_ctx_access;
12249 bool ctx_access;
12250
12251 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12252 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12253 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
12254 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
12255 type = BPF_READ;
12256 ctx_access = true;
12257 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12258 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12259 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12260 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12261 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12262 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12263 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12264 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
12265 type = BPF_WRITE;
12266 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12267 } else {
12268 continue;
12269 }
12270
12271 if (type == BPF_WRITE &&
12272 env->insn_aux_data[i + delta].sanitize_stack_spill) {
12273 struct bpf_insn patch[] = {
12274 *insn,
12275 BPF_ST_NOSPEC(),
12276 };
12277
12278 cnt = ARRAY_SIZE(patch);
12279 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12280 if (!new_prog)
12281 return -ENOMEM;
12282
12283 delta += cnt - 1;
12284 env->prog = new_prog;
12285 insn = new_prog->insnsi + i + delta;
12286 continue;
12287 }
12288
12289 if (!ctx_access)
12290 continue;
12291
12292 switch (env->insn_aux_data[i + delta].ptr_type) {
12293 case PTR_TO_CTX:
12294 if (!ops->convert_ctx_access)
12295 continue;
12296 convert_ctx_access = ops->convert_ctx_access;
12297 break;
12298 case PTR_TO_SOCKET:
12299 case PTR_TO_SOCK_COMMON:
12300 convert_ctx_access = bpf_sock_convert_ctx_access;
12301 break;
12302 case PTR_TO_TCP_SOCK:
12303 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12304 break;
12305 case PTR_TO_XDP_SOCK:
12306 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12307 break;
12308 case PTR_TO_BTF_ID:
12309 if (type == BPF_READ) {
12310 insn->code = BPF_LDX | BPF_PROBE_MEM |
12311 BPF_SIZE((insn)->code);
12312 env->prog->aux->num_exentries++;
12313 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
12314 verbose(env, "Writes through BTF pointers are not allowed\n");
12315 return -EINVAL;
12316 }
12317 continue;
12318 default:
12319 continue;
12320 }
12321
12322 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
12323 size = BPF_LDST_BYTES(insn);
12324
12325 /* If the read access is a narrower load of the field,
12326 * convert to a 4/8-byte load, to minimum program type specific
12327 * convert_ctx_access changes. If conversion is successful,
12328 * we will apply proper mask to the result.
12329 */
12330 is_narrower_load = size < ctx_field_size;
12331 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12332 off = insn->off;
12333 if (is_narrower_load) {
12334 u8 size_code;
12335
12336 if (type == BPF_WRITE) {
12337 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
12338 return -EINVAL;
12339 }
12340
12341 size_code = BPF_H;
12342 if (ctx_field_size == 4)
12343 size_code = BPF_W;
12344 else if (ctx_field_size == 8)
12345 size_code = BPF_DW;
12346
12347 insn->off = off & ~(size_default - 1);
12348 insn->code = BPF_LDX | BPF_MEM | size_code;
12349 }
12350
12351 target_size = 0;
12352 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12353 &target_size);
12354 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12355 (ctx_field_size && !target_size)) {
12356 verbose(env, "bpf verifier is misconfigured\n");
12357 return -EINVAL;
12358 }
12359
12360 if (is_narrower_load && size < target_size) {
12361 u8 shift = bpf_ctx_narrow_access_offset(
12362 off, size, size_default) * 8;
12363 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12364 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12365 return -EINVAL;
12366 }
12367 if (ctx_field_size <= 4) {
12368 if (shift)
12369 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12370 insn->dst_reg,
12371 shift);
12372 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
12373 (1 << size * 8) - 1);
12374 } else {
12375 if (shift)
12376 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12377 insn->dst_reg,
12378 shift);
12379 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
12380 (1ULL << size * 8) - 1);
12381 }
12382 }
12383
12384 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12385 if (!new_prog)
12386 return -ENOMEM;
12387
12388 delta += cnt - 1;
12389
12390 /* keep walking new program and skip insns we just inserted */
12391 env->prog = new_prog;
12392 insn = new_prog->insnsi + i + delta;
12393 }
12394
12395 return 0;
12396 }
12397
12398 static int jit_subprogs(struct bpf_verifier_env *env)
12399 {
12400 struct bpf_prog *prog = env->prog, **func, *tmp;
12401 int i, j, subprog_start, subprog_end = 0, len, subprog;
12402 struct bpf_map *map_ptr;
12403 struct bpf_insn *insn;
12404 void *old_bpf_func;
12405 int err, num_exentries;
12406
12407 if (env->subprog_cnt <= 1)
12408 return 0;
12409
12410 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12411 if (bpf_pseudo_func(insn)) {
12412 env->insn_aux_data[i].call_imm = insn->imm;
12413 /* subprog is encoded in insn[1].imm */
12414 continue;
12415 }
12416
12417 if (!bpf_pseudo_call(insn))
12418 continue;
12419 /* Upon error here we cannot fall back to interpreter but
12420 * need a hard reject of the program. Thus -EFAULT is
12421 * propagated in any case.
12422 */
12423 subprog = find_subprog(env, i + insn->imm + 1);
12424 if (subprog < 0) {
12425 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12426 i + insn->imm + 1);
12427 return -EFAULT;
12428 }
12429 /* temporarily remember subprog id inside insn instead of
12430 * aux_data, since next loop will split up all insns into funcs
12431 */
12432 insn->off = subprog;
12433 /* remember original imm in case JIT fails and fallback
12434 * to interpreter will be needed
12435 */
12436 env->insn_aux_data[i].call_imm = insn->imm;
12437 /* point imm to __bpf_call_base+1 from JITs point of view */
12438 insn->imm = 1;
12439 }
12440
12441 err = bpf_prog_alloc_jited_linfo(prog);
12442 if (err)
12443 goto out_undo_insn;
12444
12445 err = -ENOMEM;
12446 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
12447 if (!func)
12448 goto out_undo_insn;
12449
12450 for (i = 0; i < env->subprog_cnt; i++) {
12451 subprog_start = subprog_end;
12452 subprog_end = env->subprog_info[i + 1].start;
12453
12454 len = subprog_end - subprog_start;
12455 /* bpf_prog_run() doesn't call subprogs directly,
12456 * hence main prog stats include the runtime of subprogs.
12457 * subprogs don't have IDs and not reachable via prog_get_next_id
12458 * func[i]->stats will never be accessed and stays NULL
12459 */
12460 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
12461 if (!func[i])
12462 goto out_free;
12463 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12464 len * sizeof(struct bpf_insn));
12465 func[i]->type = prog->type;
12466 func[i]->len = len;
12467 if (bpf_prog_calc_tag(func[i]))
12468 goto out_free;
12469 func[i]->is_func = 1;
12470 func[i]->aux->func_idx = i;
12471 /* Below members will be freed only at prog->aux */
12472 func[i]->aux->btf = prog->aux->btf;
12473 func[i]->aux->func_info = prog->aux->func_info;
12474 func[i]->aux->poke_tab = prog->aux->poke_tab;
12475 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
12476
12477 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12478 struct bpf_jit_poke_descriptor *poke;
12479
12480 poke = &prog->aux->poke_tab[j];
12481 if (poke->insn_idx < subprog_end &&
12482 poke->insn_idx >= subprog_start)
12483 poke->aux = func[i]->aux;
12484 }
12485
12486 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12487 * Long term would need debug info to populate names
12488 */
12489 func[i]->aux->name[0] = 'F';
12490 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
12491 func[i]->jit_requested = 1;
12492 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
12493 func[i]->aux->linfo = prog->aux->linfo;
12494 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12495 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12496 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
12497 num_exentries = 0;
12498 insn = func[i]->insnsi;
12499 for (j = 0; j < func[i]->len; j++, insn++) {
12500 if (BPF_CLASS(insn->code) == BPF_LDX &&
12501 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12502 num_exentries++;
12503 }
12504 func[i]->aux->num_exentries = num_exentries;
12505 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
12506 func[i] = bpf_int_jit_compile(func[i]);
12507 if (!func[i]->jited) {
12508 err = -ENOTSUPP;
12509 goto out_free;
12510 }
12511 cond_resched();
12512 }
12513
12514 /* at this point all bpf functions were successfully JITed
12515 * now populate all bpf_calls with correct addresses and
12516 * run last pass of JIT
12517 */
12518 for (i = 0; i < env->subprog_cnt; i++) {
12519 insn = func[i]->insnsi;
12520 for (j = 0; j < func[i]->len; j++, insn++) {
12521 if (bpf_pseudo_func(insn)) {
12522 subprog = insn[1].imm;
12523 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12524 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12525 continue;
12526 }
12527 if (!bpf_pseudo_call(insn))
12528 continue;
12529 subprog = insn->off;
12530 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12531 __bpf_call_base;
12532 }
12533
12534 /* we use the aux data to keep a list of the start addresses
12535 * of the JITed images for each function in the program
12536 *
12537 * for some architectures, such as powerpc64, the imm field
12538 * might not be large enough to hold the offset of the start
12539 * address of the callee's JITed image from __bpf_call_base
12540 *
12541 * in such cases, we can lookup the start address of a callee
12542 * by using its subprog id, available from the off field of
12543 * the call instruction, as an index for this list
12544 */
12545 func[i]->aux->func = func;
12546 func[i]->aux->func_cnt = env->subprog_cnt;
12547 }
12548 for (i = 0; i < env->subprog_cnt; i++) {
12549 old_bpf_func = func[i]->bpf_func;
12550 tmp = bpf_int_jit_compile(func[i]);
12551 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12552 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
12553 err = -ENOTSUPP;
12554 goto out_free;
12555 }
12556 cond_resched();
12557 }
12558
12559 /* finally lock prog and jit images for all functions and
12560 * populate kallsysm
12561 */
12562 for (i = 0; i < env->subprog_cnt; i++) {
12563 bpf_prog_lock_ro(func[i]);
12564 bpf_prog_kallsyms_add(func[i]);
12565 }
12566
12567 /* Last step: make now unused interpreter insns from main
12568 * prog consistent for later dump requests, so they can
12569 * later look the same as if they were interpreted only.
12570 */
12571 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12572 if (bpf_pseudo_func(insn)) {
12573 insn[0].imm = env->insn_aux_data[i].call_imm;
12574 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12575 continue;
12576 }
12577 if (!bpf_pseudo_call(insn))
12578 continue;
12579 insn->off = env->insn_aux_data[i].call_imm;
12580 subprog = find_subprog(env, i + insn->off + 1);
12581 insn->imm = subprog;
12582 }
12583
12584 prog->jited = 1;
12585 prog->bpf_func = func[0]->bpf_func;
12586 prog->aux->func = func;
12587 prog->aux->func_cnt = env->subprog_cnt;
12588 bpf_prog_jit_attempt_done(prog);
12589 return 0;
12590 out_free:
12591 /* We failed JIT'ing, so at this point we need to unregister poke
12592 * descriptors from subprogs, so that kernel is not attempting to
12593 * patch it anymore as we're freeing the subprog JIT memory.
12594 */
12595 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12596 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12597 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12598 }
12599 /* At this point we're guaranteed that poke descriptors are not
12600 * live anymore. We can just unlink its descriptor table as it's
12601 * released with the main prog.
12602 */
12603 for (i = 0; i < env->subprog_cnt; i++) {
12604 if (!func[i])
12605 continue;
12606 func[i]->aux->poke_tab = NULL;
12607 bpf_jit_free(func[i]);
12608 }
12609 kfree(func);
12610 out_undo_insn:
12611 /* cleanup main prog to be interpreted */
12612 prog->jit_requested = 0;
12613 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
12614 if (!bpf_pseudo_call(insn))
12615 continue;
12616 insn->off = 0;
12617 insn->imm = env->insn_aux_data[i].call_imm;
12618 }
12619 bpf_prog_jit_attempt_done(prog);
12620 return err;
12621 }
12622
12623 static int fixup_call_args(struct bpf_verifier_env *env)
12624 {
12625 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12626 struct bpf_prog *prog = env->prog;
12627 struct bpf_insn *insn = prog->insnsi;
12628 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
12629 int i, depth;
12630 #endif
12631 int err = 0;
12632
12633 if (env->prog->jit_requested &&
12634 !bpf_prog_is_dev_bound(env->prog->aux)) {
12635 err = jit_subprogs(env);
12636 if (err == 0)
12637 return 0;
12638 if (err == -EFAULT)
12639 return err;
12640 }
12641 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
12642 if (has_kfunc_call) {
12643 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12644 return -EINVAL;
12645 }
12646 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12647 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12648 * have to be rejected, since interpreter doesn't support them yet.
12649 */
12650 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12651 return -EINVAL;
12652 }
12653 for (i = 0; i < prog->len; i++, insn++) {
12654 if (bpf_pseudo_func(insn)) {
12655 /* When JIT fails the progs with callback calls
12656 * have to be rejected, since interpreter doesn't support them yet.
12657 */
12658 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12659 return -EINVAL;
12660 }
12661
12662 if (!bpf_pseudo_call(insn))
12663 continue;
12664 depth = get_callee_stack_depth(env, insn, i);
12665 if (depth < 0)
12666 return depth;
12667 bpf_patch_call_args(insn, depth);
12668 }
12669 err = 0;
12670 #endif
12671 return err;
12672 }
12673
12674 static int fixup_kfunc_call(struct bpf_verifier_env *env,
12675 struct bpf_insn *insn)
12676 {
12677 const struct bpf_kfunc_desc *desc;
12678
12679 /* insn->imm has the btf func_id. Replace it with
12680 * an address (relative to __bpf_base_call).
12681 */
12682 desc = find_kfunc_desc(env->prog, insn->imm);
12683 if (!desc) {
12684 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12685 insn->imm);
12686 return -EFAULT;
12687 }
12688
12689 insn->imm = desc->imm;
12690
12691 return 0;
12692 }
12693
12694 /* Do various post-verification rewrites in a single program pass.
12695 * These rewrites simplify JIT and interpreter implementations.
12696 */
12697 static int do_misc_fixups(struct bpf_verifier_env *env)
12698 {
12699 struct bpf_prog *prog = env->prog;
12700 bool expect_blinding = bpf_jit_blinding_enabled(prog);
12701 enum bpf_prog_type prog_type = resolve_prog_type(prog);
12702 struct bpf_insn *insn = prog->insnsi;
12703 const struct bpf_func_proto *fn;
12704 const int insn_cnt = prog->len;
12705 const struct bpf_map_ops *ops;
12706 struct bpf_insn_aux_data *aux;
12707 struct bpf_insn insn_buf[16];
12708 struct bpf_prog *new_prog;
12709 struct bpf_map *map_ptr;
12710 int i, ret, cnt, delta = 0;
12711
12712 for (i = 0; i < insn_cnt; i++, insn++) {
12713 /* Make divide-by-zero exceptions impossible. */
12714 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12715 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12716 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
12717 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
12718 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
12719 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12720 struct bpf_insn *patchlet;
12721 struct bpf_insn chk_and_div[] = {
12722 /* [R,W]x div 0 -> 0 */
12723 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12724 BPF_JNE | BPF_K, insn->src_reg,
12725 0, 2, 0),
12726 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12727 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12728 *insn,
12729 };
12730 struct bpf_insn chk_and_mod[] = {
12731 /* [R,W]x mod 0 -> [R,W]x */
12732 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12733 BPF_JEQ | BPF_K, insn->src_reg,
12734 0, 1 + (is64 ? 0 : 1), 0),
12735 *insn,
12736 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12737 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
12738 };
12739
12740 patchlet = isdiv ? chk_and_div : chk_and_mod;
12741 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
12742 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
12743
12744 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
12745 if (!new_prog)
12746 return -ENOMEM;
12747
12748 delta += cnt - 1;
12749 env->prog = prog = new_prog;
12750 insn = new_prog->insnsi + i + delta;
12751 continue;
12752 }
12753
12754 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
12755 if (BPF_CLASS(insn->code) == BPF_LD &&
12756 (BPF_MODE(insn->code) == BPF_ABS ||
12757 BPF_MODE(insn->code) == BPF_IND)) {
12758 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12759 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12760 verbose(env, "bpf verifier is misconfigured\n");
12761 return -EINVAL;
12762 }
12763
12764 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12765 if (!new_prog)
12766 return -ENOMEM;
12767
12768 delta += cnt - 1;
12769 env->prog = prog = new_prog;
12770 insn = new_prog->insnsi + i + delta;
12771 continue;
12772 }
12773
12774 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
12775 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12776 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12777 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12778 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
12779 struct bpf_insn *patch = &insn_buf[0];
12780 bool issrc, isneg, isimm;
12781 u32 off_reg;
12782
12783 aux = &env->insn_aux_data[i + delta];
12784 if (!aux->alu_state ||
12785 aux->alu_state == BPF_ALU_NON_POINTER)
12786 continue;
12787
12788 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12789 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12790 BPF_ALU_SANITIZE_SRC;
12791 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
12792
12793 off_reg = issrc ? insn->src_reg : insn->dst_reg;
12794 if (isimm) {
12795 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12796 } else {
12797 if (isneg)
12798 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12799 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12800 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12801 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12802 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12803 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12804 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12805 }
12806 if (!issrc)
12807 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12808 insn->src_reg = BPF_REG_AX;
12809 if (isneg)
12810 insn->code = insn->code == code_add ?
12811 code_sub : code_add;
12812 *patch++ = *insn;
12813 if (issrc && isneg && !isimm)
12814 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12815 cnt = patch - insn_buf;
12816
12817 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12818 if (!new_prog)
12819 return -ENOMEM;
12820
12821 delta += cnt - 1;
12822 env->prog = prog = new_prog;
12823 insn = new_prog->insnsi + i + delta;
12824 continue;
12825 }
12826
12827 if (insn->code != (BPF_JMP | BPF_CALL))
12828 continue;
12829 if (insn->src_reg == BPF_PSEUDO_CALL)
12830 continue;
12831 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12832 ret = fixup_kfunc_call(env, insn);
12833 if (ret)
12834 return ret;
12835 continue;
12836 }
12837
12838 if (insn->imm == BPF_FUNC_get_route_realm)
12839 prog->dst_needed = 1;
12840 if (insn->imm == BPF_FUNC_get_prandom_u32)
12841 bpf_user_rnd_init_once();
12842 if (insn->imm == BPF_FUNC_override_return)
12843 prog->kprobe_override = 1;
12844 if (insn->imm == BPF_FUNC_tail_call) {
12845 /* If we tail call into other programs, we
12846 * cannot make any assumptions since they can
12847 * be replaced dynamically during runtime in
12848 * the program array.
12849 */
12850 prog->cb_access = 1;
12851 if (!allow_tail_call_in_subprogs(env))
12852 prog->aux->stack_depth = MAX_BPF_STACK;
12853 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
12854
12855 /* mark bpf_tail_call as different opcode to avoid
12856 * conditional branch in the interpreter for every normal
12857 * call and to prevent accidental JITing by JIT compiler
12858 * that doesn't support bpf_tail_call yet
12859 */
12860 insn->imm = 0;
12861 insn->code = BPF_JMP | BPF_TAIL_CALL;
12862
12863 aux = &env->insn_aux_data[i + delta];
12864 if (env->bpf_capable && !expect_blinding &&
12865 prog->jit_requested &&
12866 !bpf_map_key_poisoned(aux) &&
12867 !bpf_map_ptr_poisoned(aux) &&
12868 !bpf_map_ptr_unpriv(aux)) {
12869 struct bpf_jit_poke_descriptor desc = {
12870 .reason = BPF_POKE_REASON_TAIL_CALL,
12871 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12872 .tail_call.key = bpf_map_key_immediate(aux),
12873 .insn_idx = i + delta,
12874 };
12875
12876 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12877 if (ret < 0) {
12878 verbose(env, "adding tail call poke descriptor failed\n");
12879 return ret;
12880 }
12881
12882 insn->imm = ret + 1;
12883 continue;
12884 }
12885
12886 if (!bpf_map_ptr_unpriv(aux))
12887 continue;
12888
12889 /* instead of changing every JIT dealing with tail_call
12890 * emit two extra insns:
12891 * if (index >= max_entries) goto out;
12892 * index &= array->index_mask;
12893 * to avoid out-of-bounds cpu speculation
12894 */
12895 if (bpf_map_ptr_poisoned(aux)) {
12896 verbose(env, "tail_call abusing map_ptr\n");
12897 return -EINVAL;
12898 }
12899
12900 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12901 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12902 map_ptr->max_entries, 2);
12903 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12904 container_of(map_ptr,
12905 struct bpf_array,
12906 map)->index_mask);
12907 insn_buf[2] = *insn;
12908 cnt = 3;
12909 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12910 if (!new_prog)
12911 return -ENOMEM;
12912
12913 delta += cnt - 1;
12914 env->prog = prog = new_prog;
12915 insn = new_prog->insnsi + i + delta;
12916 continue;
12917 }
12918
12919 if (insn->imm == BPF_FUNC_timer_set_callback) {
12920 /* The verifier will process callback_fn as many times as necessary
12921 * with different maps and the register states prepared by
12922 * set_timer_callback_state will be accurate.
12923 *
12924 * The following use case is valid:
12925 * map1 is shared by prog1, prog2, prog3.
12926 * prog1 calls bpf_timer_init for some map1 elements
12927 * prog2 calls bpf_timer_set_callback for some map1 elements.
12928 * Those that were not bpf_timer_init-ed will return -EINVAL.
12929 * prog3 calls bpf_timer_start for some map1 elements.
12930 * Those that were not both bpf_timer_init-ed and
12931 * bpf_timer_set_callback-ed will return -EINVAL.
12932 */
12933 struct bpf_insn ld_addrs[2] = {
12934 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
12935 };
12936
12937 insn_buf[0] = ld_addrs[0];
12938 insn_buf[1] = ld_addrs[1];
12939 insn_buf[2] = *insn;
12940 cnt = 3;
12941
12942 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12943 if (!new_prog)
12944 return -ENOMEM;
12945
12946 delta += cnt - 1;
12947 env->prog = prog = new_prog;
12948 insn = new_prog->insnsi + i + delta;
12949 goto patch_call_imm;
12950 }
12951
12952 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
12953 * and other inlining handlers are currently limited to 64 bit
12954 * only.
12955 */
12956 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12957 (insn->imm == BPF_FUNC_map_lookup_elem ||
12958 insn->imm == BPF_FUNC_map_update_elem ||
12959 insn->imm == BPF_FUNC_map_delete_elem ||
12960 insn->imm == BPF_FUNC_map_push_elem ||
12961 insn->imm == BPF_FUNC_map_pop_elem ||
12962 insn->imm == BPF_FUNC_map_peek_elem ||
12963 insn->imm == BPF_FUNC_redirect_map)) {
12964 aux = &env->insn_aux_data[i + delta];
12965 if (bpf_map_ptr_poisoned(aux))
12966 goto patch_call_imm;
12967
12968 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
12969 ops = map_ptr->ops;
12970 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12971 ops->map_gen_lookup) {
12972 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
12973 if (cnt == -EOPNOTSUPP)
12974 goto patch_map_ops_generic;
12975 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12976 verbose(env, "bpf verifier is misconfigured\n");
12977 return -EINVAL;
12978 }
12979
12980 new_prog = bpf_patch_insn_data(env, i + delta,
12981 insn_buf, cnt);
12982 if (!new_prog)
12983 return -ENOMEM;
12984
12985 delta += cnt - 1;
12986 env->prog = prog = new_prog;
12987 insn = new_prog->insnsi + i + delta;
12988 continue;
12989 }
12990
12991 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12992 (void *(*)(struct bpf_map *map, void *key))NULL));
12993 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12994 (int (*)(struct bpf_map *map, void *key))NULL));
12995 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12996 (int (*)(struct bpf_map *map, void *key, void *value,
12997 u64 flags))NULL));
12998 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12999 (int (*)(struct bpf_map *map, void *value,
13000 u64 flags))NULL));
13001 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13002 (int (*)(struct bpf_map *map, void *value))NULL));
13003 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13004 (int (*)(struct bpf_map *map, void *value))NULL));
13005 BUILD_BUG_ON(!__same_type(ops->map_redirect,
13006 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
13007
13008 patch_map_ops_generic:
13009 switch (insn->imm) {
13010 case BPF_FUNC_map_lookup_elem:
13011 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
13012 __bpf_call_base;
13013 continue;
13014 case BPF_FUNC_map_update_elem:
13015 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
13016 __bpf_call_base;
13017 continue;
13018 case BPF_FUNC_map_delete_elem:
13019 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
13020 __bpf_call_base;
13021 continue;
13022 case BPF_FUNC_map_push_elem:
13023 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
13024 __bpf_call_base;
13025 continue;
13026 case BPF_FUNC_map_pop_elem:
13027 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
13028 __bpf_call_base;
13029 continue;
13030 case BPF_FUNC_map_peek_elem:
13031 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
13032 __bpf_call_base;
13033 continue;
13034 case BPF_FUNC_redirect_map:
13035 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
13036 __bpf_call_base;
13037 continue;
13038 }
13039
13040 goto patch_call_imm;
13041 }
13042
13043 /* Implement bpf_jiffies64 inline. */
13044 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13045 insn->imm == BPF_FUNC_jiffies64) {
13046 struct bpf_insn ld_jiffies_addr[2] = {
13047 BPF_LD_IMM64(BPF_REG_0,
13048 (unsigned long)&jiffies),
13049 };
13050
13051 insn_buf[0] = ld_jiffies_addr[0];
13052 insn_buf[1] = ld_jiffies_addr[1];
13053 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13054 BPF_REG_0, 0);
13055 cnt = 3;
13056
13057 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13058 cnt);
13059 if (!new_prog)
13060 return -ENOMEM;
13061
13062 delta += cnt - 1;
13063 env->prog = prog = new_prog;
13064 insn = new_prog->insnsi + i + delta;
13065 continue;
13066 }
13067
13068 /* Implement bpf_get_func_ip inline. */
13069 if (prog_type == BPF_PROG_TYPE_TRACING &&
13070 insn->imm == BPF_FUNC_get_func_ip) {
13071 /* Load IP address from ctx - 8 */
13072 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13073
13074 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13075 if (!new_prog)
13076 return -ENOMEM;
13077
13078 env->prog = prog = new_prog;
13079 insn = new_prog->insnsi + i + delta;
13080 continue;
13081 }
13082
13083 patch_call_imm:
13084 fn = env->ops->get_func_proto(insn->imm, env->prog);
13085 /* all functions that have prototype and verifier allowed
13086 * programs to call them, must be real in-kernel functions
13087 */
13088 if (!fn->func) {
13089 verbose(env,
13090 "kernel subsystem misconfigured func %s#%d\n",
13091 func_id_name(insn->imm), insn->imm);
13092 return -EFAULT;
13093 }
13094 insn->imm = fn->func - __bpf_call_base;
13095 }
13096
13097 /* Since poke tab is now finalized, publish aux to tracker. */
13098 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13099 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13100 if (!map_ptr->ops->map_poke_track ||
13101 !map_ptr->ops->map_poke_untrack ||
13102 !map_ptr->ops->map_poke_run) {
13103 verbose(env, "bpf verifier is misconfigured\n");
13104 return -EINVAL;
13105 }
13106
13107 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13108 if (ret < 0) {
13109 verbose(env, "tracking tail call prog failed\n");
13110 return ret;
13111 }
13112 }
13113
13114 sort_kfunc_descs_by_imm(env->prog);
13115
13116 return 0;
13117 }
13118
13119 static void free_states(struct bpf_verifier_env *env)
13120 {
13121 struct bpf_verifier_state_list *sl, *sln;
13122 int i;
13123
13124 sl = env->free_list;
13125 while (sl) {
13126 sln = sl->next;
13127 free_verifier_state(&sl->state, false);
13128 kfree(sl);
13129 sl = sln;
13130 }
13131 env->free_list = NULL;
13132
13133 if (!env->explored_states)
13134 return;
13135
13136 for (i = 0; i < state_htab_size(env); i++) {
13137 sl = env->explored_states[i];
13138
13139 while (sl) {
13140 sln = sl->next;
13141 free_verifier_state(&sl->state, false);
13142 kfree(sl);
13143 sl = sln;
13144 }
13145 env->explored_states[i] = NULL;
13146 }
13147 }
13148
13149 static int do_check_common(struct bpf_verifier_env *env, int subprog)
13150 {
13151 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
13152 struct bpf_verifier_state *state;
13153 struct bpf_reg_state *regs;
13154 int ret, i;
13155
13156 env->prev_linfo = NULL;
13157 env->pass_cnt++;
13158
13159 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13160 if (!state)
13161 return -ENOMEM;
13162 state->curframe = 0;
13163 state->speculative = false;
13164 state->branches = 1;
13165 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13166 if (!state->frame[0]) {
13167 kfree(state);
13168 return -ENOMEM;
13169 }
13170 env->cur_state = state;
13171 init_func_state(env, state->frame[0],
13172 BPF_MAIN_FUNC /* callsite */,
13173 0 /* frameno */,
13174 subprog);
13175
13176 regs = state->frame[state->curframe]->regs;
13177 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
13178 ret = btf_prepare_func_args(env, subprog, regs);
13179 if (ret)
13180 goto out;
13181 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13182 if (regs[i].type == PTR_TO_CTX)
13183 mark_reg_known_zero(env, regs, i);
13184 else if (regs[i].type == SCALAR_VALUE)
13185 mark_reg_unknown(env, regs, i);
13186 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13187 const u32 mem_size = regs[i].mem_size;
13188
13189 mark_reg_known_zero(env, regs, i);
13190 regs[i].mem_size = mem_size;
13191 regs[i].id = ++env->id_gen;
13192 }
13193 }
13194 } else {
13195 /* 1st arg to a function */
13196 regs[BPF_REG_1].type = PTR_TO_CTX;
13197 mark_reg_known_zero(env, regs, BPF_REG_1);
13198 ret = btf_check_subprog_arg_match(env, subprog, regs);
13199 if (ret == -EFAULT)
13200 /* unlikely verifier bug. abort.
13201 * ret == 0 and ret < 0 are sadly acceptable for
13202 * main() function due to backward compatibility.
13203 * Like socket filter program may be written as:
13204 * int bpf_prog(struct pt_regs *ctx)
13205 * and never dereference that ctx in the program.
13206 * 'struct pt_regs' is a type mismatch for socket
13207 * filter that should be using 'struct __sk_buff'.
13208 */
13209 goto out;
13210 }
13211
13212 ret = do_check(env);
13213 out:
13214 /* check for NULL is necessary, since cur_state can be freed inside
13215 * do_check() under memory pressure.
13216 */
13217 if (env->cur_state) {
13218 free_verifier_state(env->cur_state, true);
13219 env->cur_state = NULL;
13220 }
13221 while (!pop_stack(env, NULL, NULL, false));
13222 if (!ret && pop_log)
13223 bpf_vlog_reset(&env->log, 0);
13224 free_states(env);
13225 return ret;
13226 }
13227
13228 /* Verify all global functions in a BPF program one by one based on their BTF.
13229 * All global functions must pass verification. Otherwise the whole program is rejected.
13230 * Consider:
13231 * int bar(int);
13232 * int foo(int f)
13233 * {
13234 * return bar(f);
13235 * }
13236 * int bar(int b)
13237 * {
13238 * ...
13239 * }
13240 * foo() will be verified first for R1=any_scalar_value. During verification it
13241 * will be assumed that bar() already verified successfully and call to bar()
13242 * from foo() will be checked for type match only. Later bar() will be verified
13243 * independently to check that it's safe for R1=any_scalar_value.
13244 */
13245 static int do_check_subprogs(struct bpf_verifier_env *env)
13246 {
13247 struct bpf_prog_aux *aux = env->prog->aux;
13248 int i, ret;
13249
13250 if (!aux->func_info)
13251 return 0;
13252
13253 for (i = 1; i < env->subprog_cnt; i++) {
13254 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13255 continue;
13256 env->insn_idx = env->subprog_info[i].start;
13257 WARN_ON_ONCE(env->insn_idx == 0);
13258 ret = do_check_common(env, i);
13259 if (ret) {
13260 return ret;
13261 } else if (env->log.level & BPF_LOG_LEVEL) {
13262 verbose(env,
13263 "Func#%d is safe for any args that match its prototype\n",
13264 i);
13265 }
13266 }
13267 return 0;
13268 }
13269
13270 static int do_check_main(struct bpf_verifier_env *env)
13271 {
13272 int ret;
13273
13274 env->insn_idx = 0;
13275 ret = do_check_common(env, 0);
13276 if (!ret)
13277 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13278 return ret;
13279 }
13280
13281
13282 static void print_verification_stats(struct bpf_verifier_env *env)
13283 {
13284 int i;
13285
13286 if (env->log.level & BPF_LOG_STATS) {
13287 verbose(env, "verification time %lld usec\n",
13288 div_u64(env->verification_time, 1000));
13289 verbose(env, "stack depth ");
13290 for (i = 0; i < env->subprog_cnt; i++) {
13291 u32 depth = env->subprog_info[i].stack_depth;
13292
13293 verbose(env, "%d", depth);
13294 if (i + 1 < env->subprog_cnt)
13295 verbose(env, "+");
13296 }
13297 verbose(env, "\n");
13298 }
13299 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13300 "total_states %d peak_states %d mark_read %d\n",
13301 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13302 env->max_states_per_insn, env->total_states,
13303 env->peak_states, env->longest_mark_read_walk);
13304 }
13305
13306 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13307 {
13308 const struct btf_type *t, *func_proto;
13309 const struct bpf_struct_ops *st_ops;
13310 const struct btf_member *member;
13311 struct bpf_prog *prog = env->prog;
13312 u32 btf_id, member_idx;
13313 const char *mname;
13314
13315 if (!prog->gpl_compatible) {
13316 verbose(env, "struct ops programs must have a GPL compatible license\n");
13317 return -EINVAL;
13318 }
13319
13320 btf_id = prog->aux->attach_btf_id;
13321 st_ops = bpf_struct_ops_find(btf_id);
13322 if (!st_ops) {
13323 verbose(env, "attach_btf_id %u is not a supported struct\n",
13324 btf_id);
13325 return -ENOTSUPP;
13326 }
13327
13328 t = st_ops->type;
13329 member_idx = prog->expected_attach_type;
13330 if (member_idx >= btf_type_vlen(t)) {
13331 verbose(env, "attach to invalid member idx %u of struct %s\n",
13332 member_idx, st_ops->name);
13333 return -EINVAL;
13334 }
13335
13336 member = &btf_type_member(t)[member_idx];
13337 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13338 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13339 NULL);
13340 if (!func_proto) {
13341 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13342 mname, member_idx, st_ops->name);
13343 return -EINVAL;
13344 }
13345
13346 if (st_ops->check_member) {
13347 int err = st_ops->check_member(t, member);
13348
13349 if (err) {
13350 verbose(env, "attach to unsupported member %s of struct %s\n",
13351 mname, st_ops->name);
13352 return err;
13353 }
13354 }
13355
13356 prog->aux->attach_func_proto = func_proto;
13357 prog->aux->attach_func_name = mname;
13358 env->ops = st_ops->verifier_ops;
13359
13360 return 0;
13361 }
13362 #define SECURITY_PREFIX "security_"
13363
13364 static int check_attach_modify_return(unsigned long addr, const char *func_name)
13365 {
13366 if (within_error_injection_list(addr) ||
13367 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
13368 return 0;
13369
13370 return -EINVAL;
13371 }
13372
13373 /* list of non-sleepable functions that are otherwise on
13374 * ALLOW_ERROR_INJECTION list
13375 */
13376 BTF_SET_START(btf_non_sleepable_error_inject)
13377 /* Three functions below can be called from sleepable and non-sleepable context.
13378 * Assume non-sleepable from bpf safety point of view.
13379 */
13380 BTF_ID(func, __add_to_page_cache_locked)
13381 BTF_ID(func, should_fail_alloc_page)
13382 BTF_ID(func, should_failslab)
13383 BTF_SET_END(btf_non_sleepable_error_inject)
13384
13385 static int check_non_sleepable_error_inject(u32 btf_id)
13386 {
13387 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13388 }
13389
13390 int bpf_check_attach_target(struct bpf_verifier_log *log,
13391 const struct bpf_prog *prog,
13392 const struct bpf_prog *tgt_prog,
13393 u32 btf_id,
13394 struct bpf_attach_target_info *tgt_info)
13395 {
13396 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
13397 const char prefix[] = "btf_trace_";
13398 int ret = 0, subprog = -1, i;
13399 const struct btf_type *t;
13400 bool conservative = true;
13401 const char *tname;
13402 struct btf *btf;
13403 long addr = 0;
13404
13405 if (!btf_id) {
13406 bpf_log(log, "Tracing programs must provide btf_id\n");
13407 return -EINVAL;
13408 }
13409 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
13410 if (!btf) {
13411 bpf_log(log,
13412 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13413 return -EINVAL;
13414 }
13415 t = btf_type_by_id(btf, btf_id);
13416 if (!t) {
13417 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
13418 return -EINVAL;
13419 }
13420 tname = btf_name_by_offset(btf, t->name_off);
13421 if (!tname) {
13422 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
13423 return -EINVAL;
13424 }
13425 if (tgt_prog) {
13426 struct bpf_prog_aux *aux = tgt_prog->aux;
13427
13428 for (i = 0; i < aux->func_info_cnt; i++)
13429 if (aux->func_info[i].type_id == btf_id) {
13430 subprog = i;
13431 break;
13432 }
13433 if (subprog == -1) {
13434 bpf_log(log, "Subprog %s doesn't exist\n", tname);
13435 return -EINVAL;
13436 }
13437 conservative = aux->func_info_aux[subprog].unreliable;
13438 if (prog_extension) {
13439 if (conservative) {
13440 bpf_log(log,
13441 "Cannot replace static functions\n");
13442 return -EINVAL;
13443 }
13444 if (!prog->jit_requested) {
13445 bpf_log(log,
13446 "Extension programs should be JITed\n");
13447 return -EINVAL;
13448 }
13449 }
13450 if (!tgt_prog->jited) {
13451 bpf_log(log, "Can attach to only JITed progs\n");
13452 return -EINVAL;
13453 }
13454 if (tgt_prog->type == prog->type) {
13455 /* Cannot fentry/fexit another fentry/fexit program.
13456 * Cannot attach program extension to another extension.
13457 * It's ok to attach fentry/fexit to extension program.
13458 */
13459 bpf_log(log, "Cannot recursively attach\n");
13460 return -EINVAL;
13461 }
13462 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13463 prog_extension &&
13464 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13465 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13466 /* Program extensions can extend all program types
13467 * except fentry/fexit. The reason is the following.
13468 * The fentry/fexit programs are used for performance
13469 * analysis, stats and can be attached to any program
13470 * type except themselves. When extension program is
13471 * replacing XDP function it is necessary to allow
13472 * performance analysis of all functions. Both original
13473 * XDP program and its program extension. Hence
13474 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13475 * allowed. If extending of fentry/fexit was allowed it
13476 * would be possible to create long call chain
13477 * fentry->extension->fentry->extension beyond
13478 * reasonable stack size. Hence extending fentry is not
13479 * allowed.
13480 */
13481 bpf_log(log, "Cannot extend fentry/fexit\n");
13482 return -EINVAL;
13483 }
13484 } else {
13485 if (prog_extension) {
13486 bpf_log(log, "Cannot replace kernel functions\n");
13487 return -EINVAL;
13488 }
13489 }
13490
13491 switch (prog->expected_attach_type) {
13492 case BPF_TRACE_RAW_TP:
13493 if (tgt_prog) {
13494 bpf_log(log,
13495 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13496 return -EINVAL;
13497 }
13498 if (!btf_type_is_typedef(t)) {
13499 bpf_log(log, "attach_btf_id %u is not a typedef\n",
13500 btf_id);
13501 return -EINVAL;
13502 }
13503 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
13504 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
13505 btf_id, tname);
13506 return -EINVAL;
13507 }
13508 tname += sizeof(prefix) - 1;
13509 t = btf_type_by_id(btf, t->type);
13510 if (!btf_type_is_ptr(t))
13511 /* should never happen in valid vmlinux build */
13512 return -EINVAL;
13513 t = btf_type_by_id(btf, t->type);
13514 if (!btf_type_is_func_proto(t))
13515 /* should never happen in valid vmlinux build */
13516 return -EINVAL;
13517
13518 break;
13519 case BPF_TRACE_ITER:
13520 if (!btf_type_is_func(t)) {
13521 bpf_log(log, "attach_btf_id %u is not a function\n",
13522 btf_id);
13523 return -EINVAL;
13524 }
13525 t = btf_type_by_id(btf, t->type);
13526 if (!btf_type_is_func_proto(t))
13527 return -EINVAL;
13528 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13529 if (ret)
13530 return ret;
13531 break;
13532 default:
13533 if (!prog_extension)
13534 return -EINVAL;
13535 fallthrough;
13536 case BPF_MODIFY_RETURN:
13537 case BPF_LSM_MAC:
13538 case BPF_TRACE_FENTRY:
13539 case BPF_TRACE_FEXIT:
13540 if (!btf_type_is_func(t)) {
13541 bpf_log(log, "attach_btf_id %u is not a function\n",
13542 btf_id);
13543 return -EINVAL;
13544 }
13545 if (prog_extension &&
13546 btf_check_type_match(log, prog, btf, t))
13547 return -EINVAL;
13548 t = btf_type_by_id(btf, t->type);
13549 if (!btf_type_is_func_proto(t))
13550 return -EINVAL;
13551
13552 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13553 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13554 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13555 return -EINVAL;
13556
13557 if (tgt_prog && conservative)
13558 t = NULL;
13559
13560 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13561 if (ret < 0)
13562 return ret;
13563
13564 if (tgt_prog) {
13565 if (subprog == 0)
13566 addr = (long) tgt_prog->bpf_func;
13567 else
13568 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
13569 } else {
13570 addr = kallsyms_lookup_name(tname);
13571 if (!addr) {
13572 bpf_log(log,
13573 "The address of function %s cannot be found\n",
13574 tname);
13575 return -ENOENT;
13576 }
13577 }
13578
13579 if (prog->aux->sleepable) {
13580 ret = -EINVAL;
13581 switch (prog->type) {
13582 case BPF_PROG_TYPE_TRACING:
13583 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13584 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13585 */
13586 if (!check_non_sleepable_error_inject(btf_id) &&
13587 within_error_injection_list(addr))
13588 ret = 0;
13589 break;
13590 case BPF_PROG_TYPE_LSM:
13591 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13592 * Only some of them are sleepable.
13593 */
13594 if (bpf_lsm_is_sleepable_hook(btf_id))
13595 ret = 0;
13596 break;
13597 default:
13598 break;
13599 }
13600 if (ret) {
13601 bpf_log(log, "%s is not sleepable\n", tname);
13602 return ret;
13603 }
13604 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
13605 if (tgt_prog) {
13606 bpf_log(log, "can't modify return codes of BPF programs\n");
13607 return -EINVAL;
13608 }
13609 ret = check_attach_modify_return(addr, tname);
13610 if (ret) {
13611 bpf_log(log, "%s() is not modifiable\n", tname);
13612 return ret;
13613 }
13614 }
13615
13616 break;
13617 }
13618 tgt_info->tgt_addr = addr;
13619 tgt_info->tgt_name = tname;
13620 tgt_info->tgt_type = t;
13621 return 0;
13622 }
13623
13624 BTF_SET_START(btf_id_deny)
13625 BTF_ID_UNUSED
13626 #ifdef CONFIG_SMP
13627 BTF_ID(func, migrate_disable)
13628 BTF_ID(func, migrate_enable)
13629 #endif
13630 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13631 BTF_ID(func, rcu_read_unlock_strict)
13632 #endif
13633 BTF_SET_END(btf_id_deny)
13634
13635 static int check_attach_btf_id(struct bpf_verifier_env *env)
13636 {
13637 struct bpf_prog *prog = env->prog;
13638 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
13639 struct bpf_attach_target_info tgt_info = {};
13640 u32 btf_id = prog->aux->attach_btf_id;
13641 struct bpf_trampoline *tr;
13642 int ret;
13643 u64 key;
13644
13645 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13646 if (prog->aux->sleepable)
13647 /* attach_btf_id checked to be zero already */
13648 return 0;
13649 verbose(env, "Syscall programs can only be sleepable\n");
13650 return -EINVAL;
13651 }
13652
13653 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13654 prog->type != BPF_PROG_TYPE_LSM) {
13655 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13656 return -EINVAL;
13657 }
13658
13659 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13660 return check_struct_ops_btf_id(env);
13661
13662 if (prog->type != BPF_PROG_TYPE_TRACING &&
13663 prog->type != BPF_PROG_TYPE_LSM &&
13664 prog->type != BPF_PROG_TYPE_EXT)
13665 return 0;
13666
13667 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13668 if (ret)
13669 return ret;
13670
13671 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
13672 /* to make freplace equivalent to their targets, they need to
13673 * inherit env->ops and expected_attach_type for the rest of the
13674 * verification
13675 */
13676 env->ops = bpf_verifier_ops[tgt_prog->type];
13677 prog->expected_attach_type = tgt_prog->expected_attach_type;
13678 }
13679
13680 /* store info about the attachment target that will be used later */
13681 prog->aux->attach_func_proto = tgt_info.tgt_type;
13682 prog->aux->attach_func_name = tgt_info.tgt_name;
13683
13684 if (tgt_prog) {
13685 prog->aux->saved_dst_prog_type = tgt_prog->type;
13686 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13687 }
13688
13689 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13690 prog->aux->attach_btf_trace = true;
13691 return 0;
13692 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13693 if (!bpf_iter_prog_supported(prog))
13694 return -EINVAL;
13695 return 0;
13696 }
13697
13698 if (prog->type == BPF_PROG_TYPE_LSM) {
13699 ret = bpf_lsm_verify_prog(&env->log, prog);
13700 if (ret < 0)
13701 return ret;
13702 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13703 btf_id_set_contains(&btf_id_deny, btf_id)) {
13704 return -EINVAL;
13705 }
13706
13707 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
13708 tr = bpf_trampoline_get(key, &tgt_info);
13709 if (!tr)
13710 return -ENOMEM;
13711
13712 prog->aux->dst_trampoline = tr;
13713 return 0;
13714 }
13715
13716 struct btf *bpf_get_btf_vmlinux(void)
13717 {
13718 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13719 mutex_lock(&bpf_verifier_lock);
13720 if (!btf_vmlinux)
13721 btf_vmlinux = btf_parse_vmlinux();
13722 mutex_unlock(&bpf_verifier_lock);
13723 }
13724 return btf_vmlinux;
13725 }
13726
13727 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
13728 {
13729 u64 start_time = ktime_get_ns();
13730 struct bpf_verifier_env *env;
13731 struct bpf_verifier_log *log;
13732 int i, len, ret = -EINVAL;
13733 bool is_priv;
13734
13735 /* no program is valid */
13736 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13737 return -EINVAL;
13738
13739 /* 'struct bpf_verifier_env' can be global, but since it's not small,
13740 * allocate/free it every time bpf_check() is called
13741 */
13742 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
13743 if (!env)
13744 return -ENOMEM;
13745 log = &env->log;
13746
13747 len = (*prog)->len;
13748 env->insn_aux_data =
13749 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
13750 ret = -ENOMEM;
13751 if (!env->insn_aux_data)
13752 goto err_free_env;
13753 for (i = 0; i < len; i++)
13754 env->insn_aux_data[i].orig_idx = i;
13755 env->prog = *prog;
13756 env->ops = bpf_verifier_ops[env->prog->type];
13757 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
13758 is_priv = bpf_capable();
13759
13760 bpf_get_btf_vmlinux();
13761
13762 /* grab the mutex to protect few globals used by verifier */
13763 if (!is_priv)
13764 mutex_lock(&bpf_verifier_lock);
13765
13766 if (attr->log_level || attr->log_buf || attr->log_size) {
13767 /* user requested verbose verifier output
13768 * and supplied buffer to store the verification trace
13769 */
13770 log->level = attr->log_level;
13771 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13772 log->len_total = attr->log_size;
13773
13774 /* log attributes have to be sane */
13775 if (!bpf_verifier_log_attr_valid(log)) {
13776 ret = -EINVAL;
13777 goto err_unlock;
13778 }
13779 }
13780
13781 if (IS_ERR(btf_vmlinux)) {
13782 /* Either gcc or pahole or kernel are broken. */
13783 verbose(env, "in-kernel BTF is malformed\n");
13784 ret = PTR_ERR(btf_vmlinux);
13785 goto skip_full_check;
13786 }
13787
13788 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13789 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
13790 env->strict_alignment = true;
13791 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13792 env->strict_alignment = false;
13793
13794 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
13795 env->allow_uninit_stack = bpf_allow_uninit_stack();
13796 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
13797 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13798 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13799 env->bpf_capable = bpf_capable();
13800
13801 if (is_priv)
13802 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13803
13804 env->explored_states = kvcalloc(state_htab_size(env),
13805 sizeof(struct bpf_verifier_state_list *),
13806 GFP_USER);
13807 ret = -ENOMEM;
13808 if (!env->explored_states)
13809 goto skip_full_check;
13810
13811 ret = add_subprog_and_kfunc(env);
13812 if (ret < 0)
13813 goto skip_full_check;
13814
13815 ret = check_subprogs(env);
13816 if (ret < 0)
13817 goto skip_full_check;
13818
13819 ret = check_btf_info(env, attr, uattr);
13820 if (ret < 0)
13821 goto skip_full_check;
13822
13823 ret = check_attach_btf_id(env);
13824 if (ret)
13825 goto skip_full_check;
13826
13827 ret = resolve_pseudo_ldimm64(env);
13828 if (ret < 0)
13829 goto skip_full_check;
13830
13831 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13832 ret = bpf_prog_offload_verifier_prep(env->prog);
13833 if (ret)
13834 goto skip_full_check;
13835 }
13836
13837 ret = check_cfg(env);
13838 if (ret < 0)
13839 goto skip_full_check;
13840
13841 ret = do_check_subprogs(env);
13842 ret = ret ?: do_check_main(env);
13843
13844 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13845 ret = bpf_prog_offload_finalize(env);
13846
13847 skip_full_check:
13848 kvfree(env->explored_states);
13849
13850 if (ret == 0)
13851 ret = check_max_stack_depth(env);
13852
13853 /* instruction rewrites happen after this point */
13854 if (is_priv) {
13855 if (ret == 0)
13856 opt_hard_wire_dead_code_branches(env);
13857 if (ret == 0)
13858 ret = opt_remove_dead_code(env);
13859 if (ret == 0)
13860 ret = opt_remove_nops(env);
13861 } else {
13862 if (ret == 0)
13863 sanitize_dead_code(env);
13864 }
13865
13866 if (ret == 0)
13867 /* program is valid, convert *(u32*)(ctx + off) accesses */
13868 ret = convert_ctx_accesses(env);
13869
13870 if (ret == 0)
13871 ret = do_misc_fixups(env);
13872
13873 /* do 32-bit optimization after insn patching has done so those patched
13874 * insns could be handled correctly.
13875 */
13876 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13877 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13878 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13879 : false;
13880 }
13881
13882 if (ret == 0)
13883 ret = fixup_call_args(env);
13884
13885 env->verification_time = ktime_get_ns() - start_time;
13886 print_verification_stats(env);
13887
13888 if (log->level && bpf_verifier_log_full(log))
13889 ret = -ENOSPC;
13890 if (log->level && !log->ubuf) {
13891 ret = -EFAULT;
13892 goto err_release_maps;
13893 }
13894
13895 if (ret)
13896 goto err_release_maps;
13897
13898 if (env->used_map_cnt) {
13899 /* if program passed verifier, update used_maps in bpf_prog_info */
13900 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13901 sizeof(env->used_maps[0]),
13902 GFP_KERNEL);
13903
13904 if (!env->prog->aux->used_maps) {
13905 ret = -ENOMEM;
13906 goto err_release_maps;
13907 }
13908
13909 memcpy(env->prog->aux->used_maps, env->used_maps,
13910 sizeof(env->used_maps[0]) * env->used_map_cnt);
13911 env->prog->aux->used_map_cnt = env->used_map_cnt;
13912 }
13913 if (env->used_btf_cnt) {
13914 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13915 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13916 sizeof(env->used_btfs[0]),
13917 GFP_KERNEL);
13918 if (!env->prog->aux->used_btfs) {
13919 ret = -ENOMEM;
13920 goto err_release_maps;
13921 }
13922
13923 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13924 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13925 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13926 }
13927 if (env->used_map_cnt || env->used_btf_cnt) {
13928 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13929 * bpf_ld_imm64 instructions
13930 */
13931 convert_pseudo_ld_imm64(env);
13932 }
13933
13934 adjust_btf_func(env);
13935
13936 err_release_maps:
13937 if (!env->prog->aux->used_maps)
13938 /* if we didn't copy map pointers into bpf_prog_info, release
13939 * them now. Otherwise free_used_maps() will release them.
13940 */
13941 release_maps(env);
13942 if (!env->prog->aux->used_btfs)
13943 release_btfs(env);
13944
13945 /* extension progs temporarily inherit the attach_type of their targets
13946 for verification purposes, so set it back to zero before returning
13947 */
13948 if (env->prog->type == BPF_PROG_TYPE_EXT)
13949 env->prog->expected_attach_type = 0;
13950
13951 *prog = env->prog;
13952 err_unlock:
13953 if (!is_priv)
13954 mutex_unlock(&bpf_verifier_lock);
13955 vfree(env->insn_aux_data);
13956 err_free_env:
13957 kfree(env);
13958 return ret;
13959 }