]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - kernel/bpf/verifier.c
bpf: Fix leakage of uninitialized bpf stack under speculation
[mirror_ubuntu-hirsute-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 pathes 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 ether 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 struct bpf_call_arg_meta {
232 struct bpf_map *map_ptr;
233 bool raw_mode;
234 bool pkt_access;
235 int regno;
236 int access_size;
237 int mem_size;
238 u64 msize_max_value;
239 int ref_obj_id;
240 int func_id;
241 struct btf *btf;
242 u32 btf_id;
243 struct btf *ret_btf;
244 u32 ret_btf_id;
245 };
246
247 struct btf *btf_vmlinux;
248
249 static DEFINE_MUTEX(bpf_verifier_lock);
250
251 static const struct bpf_line_info *
252 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
253 {
254 const struct bpf_line_info *linfo;
255 const struct bpf_prog *prog;
256 u32 i, nr_linfo;
257
258 prog = env->prog;
259 nr_linfo = prog->aux->nr_linfo;
260
261 if (!nr_linfo || insn_off >= prog->len)
262 return NULL;
263
264 linfo = prog->aux->linfo;
265 for (i = 1; i < nr_linfo; i++)
266 if (insn_off < linfo[i].insn_off)
267 break;
268
269 return &linfo[i - 1];
270 }
271
272 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
273 va_list args)
274 {
275 unsigned int n;
276
277 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
278
279 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
280 "verifier log line truncated - local buffer too short\n");
281
282 n = min(log->len_total - log->len_used - 1, n);
283 log->kbuf[n] = '\0';
284
285 if (log->level == BPF_LOG_KERNEL) {
286 pr_err("BPF:%s\n", log->kbuf);
287 return;
288 }
289 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
290 log->len_used += n;
291 else
292 log->ubuf = NULL;
293 }
294
295 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
296 {
297 char zero = 0;
298
299 if (!bpf_verifier_log_needed(log))
300 return;
301
302 log->len_used = new_pos;
303 if (put_user(zero, log->ubuf + new_pos))
304 log->ubuf = NULL;
305 }
306
307 /* log_level controls verbosity level of eBPF verifier.
308 * bpf_verifier_log_write() is used to dump the verification trace to the log,
309 * so the user can figure out what's wrong with the program
310 */
311 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
312 const char *fmt, ...)
313 {
314 va_list args;
315
316 if (!bpf_verifier_log_needed(&env->log))
317 return;
318
319 va_start(args, fmt);
320 bpf_verifier_vlog(&env->log, fmt, args);
321 va_end(args);
322 }
323 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
324
325 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
326 {
327 struct bpf_verifier_env *env = private_data;
328 va_list args;
329
330 if (!bpf_verifier_log_needed(&env->log))
331 return;
332
333 va_start(args, fmt);
334 bpf_verifier_vlog(&env->log, fmt, args);
335 va_end(args);
336 }
337
338 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
339 const char *fmt, ...)
340 {
341 va_list args;
342
343 if (!bpf_verifier_log_needed(log))
344 return;
345
346 va_start(args, fmt);
347 bpf_verifier_vlog(log, fmt, args);
348 va_end(args);
349 }
350
351 static const char *ltrim(const char *s)
352 {
353 while (isspace(*s))
354 s++;
355
356 return s;
357 }
358
359 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
360 u32 insn_off,
361 const char *prefix_fmt, ...)
362 {
363 const struct bpf_line_info *linfo;
364
365 if (!bpf_verifier_log_needed(&env->log))
366 return;
367
368 linfo = find_linfo(env, insn_off);
369 if (!linfo || linfo == env->prev_linfo)
370 return;
371
372 if (prefix_fmt) {
373 va_list args;
374
375 va_start(args, prefix_fmt);
376 bpf_verifier_vlog(&env->log, prefix_fmt, args);
377 va_end(args);
378 }
379
380 verbose(env, "%s\n",
381 ltrim(btf_name_by_offset(env->prog->aux->btf,
382 linfo->line_off)));
383
384 env->prev_linfo = linfo;
385 }
386
387 static bool type_is_pkt_pointer(enum bpf_reg_type type)
388 {
389 return type == PTR_TO_PACKET ||
390 type == PTR_TO_PACKET_META;
391 }
392
393 static bool type_is_sk_pointer(enum bpf_reg_type type)
394 {
395 return type == PTR_TO_SOCKET ||
396 type == PTR_TO_SOCK_COMMON ||
397 type == PTR_TO_TCP_SOCK ||
398 type == PTR_TO_XDP_SOCK;
399 }
400
401 static bool reg_type_not_null(enum bpf_reg_type type)
402 {
403 return type == PTR_TO_SOCKET ||
404 type == PTR_TO_TCP_SOCK ||
405 type == PTR_TO_MAP_VALUE ||
406 type == PTR_TO_SOCK_COMMON;
407 }
408
409 static bool reg_type_may_be_null(enum bpf_reg_type type)
410 {
411 return type == PTR_TO_MAP_VALUE_OR_NULL ||
412 type == PTR_TO_SOCKET_OR_NULL ||
413 type == PTR_TO_SOCK_COMMON_OR_NULL ||
414 type == PTR_TO_TCP_SOCK_OR_NULL ||
415 type == PTR_TO_BTF_ID_OR_NULL ||
416 type == PTR_TO_MEM_OR_NULL ||
417 type == PTR_TO_RDONLY_BUF_OR_NULL ||
418 type == PTR_TO_RDWR_BUF_OR_NULL;
419 }
420
421 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
422 {
423 return reg->type == PTR_TO_MAP_VALUE &&
424 map_value_has_spin_lock(reg->map_ptr);
425 }
426
427 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
428 {
429 return type == PTR_TO_SOCKET ||
430 type == PTR_TO_SOCKET_OR_NULL ||
431 type == PTR_TO_TCP_SOCK ||
432 type == PTR_TO_TCP_SOCK_OR_NULL ||
433 type == PTR_TO_MEM ||
434 type == PTR_TO_MEM_OR_NULL;
435 }
436
437 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
438 {
439 return type == ARG_PTR_TO_SOCK_COMMON;
440 }
441
442 static bool arg_type_may_be_null(enum bpf_arg_type type)
443 {
444 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
445 type == ARG_PTR_TO_MEM_OR_NULL ||
446 type == ARG_PTR_TO_CTX_OR_NULL ||
447 type == ARG_PTR_TO_SOCKET_OR_NULL ||
448 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
449 }
450
451 /* Determine whether the function releases some resources allocated by another
452 * function call. The first reference type argument will be assumed to be
453 * released by release_reference().
454 */
455 static bool is_release_function(enum bpf_func_id func_id)
456 {
457 return func_id == BPF_FUNC_sk_release ||
458 func_id == BPF_FUNC_ringbuf_submit ||
459 func_id == BPF_FUNC_ringbuf_discard;
460 }
461
462 static bool may_be_acquire_function(enum bpf_func_id func_id)
463 {
464 return func_id == BPF_FUNC_sk_lookup_tcp ||
465 func_id == BPF_FUNC_sk_lookup_udp ||
466 func_id == BPF_FUNC_skc_lookup_tcp ||
467 func_id == BPF_FUNC_map_lookup_elem ||
468 func_id == BPF_FUNC_ringbuf_reserve;
469 }
470
471 static bool is_acquire_function(enum bpf_func_id func_id,
472 const struct bpf_map *map)
473 {
474 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
475
476 if (func_id == BPF_FUNC_sk_lookup_tcp ||
477 func_id == BPF_FUNC_sk_lookup_udp ||
478 func_id == BPF_FUNC_skc_lookup_tcp ||
479 func_id == BPF_FUNC_ringbuf_reserve)
480 return true;
481
482 if (func_id == BPF_FUNC_map_lookup_elem &&
483 (map_type == BPF_MAP_TYPE_SOCKMAP ||
484 map_type == BPF_MAP_TYPE_SOCKHASH))
485 return true;
486
487 return false;
488 }
489
490 static bool is_ptr_cast_function(enum bpf_func_id func_id)
491 {
492 return func_id == BPF_FUNC_tcp_sock ||
493 func_id == BPF_FUNC_sk_fullsock ||
494 func_id == BPF_FUNC_skc_to_tcp_sock ||
495 func_id == BPF_FUNC_skc_to_tcp6_sock ||
496 func_id == BPF_FUNC_skc_to_udp6_sock ||
497 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
498 func_id == BPF_FUNC_skc_to_tcp_request_sock;
499 }
500
501 /* string representation of 'enum bpf_reg_type' */
502 static const char * const reg_type_str[] = {
503 [NOT_INIT] = "?",
504 [SCALAR_VALUE] = "inv",
505 [PTR_TO_CTX] = "ctx",
506 [CONST_PTR_TO_MAP] = "map_ptr",
507 [PTR_TO_MAP_VALUE] = "map_value",
508 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
509 [PTR_TO_STACK] = "fp",
510 [PTR_TO_PACKET] = "pkt",
511 [PTR_TO_PACKET_META] = "pkt_meta",
512 [PTR_TO_PACKET_END] = "pkt_end",
513 [PTR_TO_FLOW_KEYS] = "flow_keys",
514 [PTR_TO_SOCKET] = "sock",
515 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
516 [PTR_TO_SOCK_COMMON] = "sock_common",
517 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
518 [PTR_TO_TCP_SOCK] = "tcp_sock",
519 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
520 [PTR_TO_TP_BUFFER] = "tp_buffer",
521 [PTR_TO_XDP_SOCK] = "xdp_sock",
522 [PTR_TO_BTF_ID] = "ptr_",
523 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
524 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
525 [PTR_TO_MEM] = "mem",
526 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
527 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
528 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
529 [PTR_TO_RDWR_BUF] = "rdwr_buf",
530 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
531 };
532
533 static char slot_type_char[] = {
534 [STACK_INVALID] = '?',
535 [STACK_SPILL] = 'r',
536 [STACK_MISC] = 'm',
537 [STACK_ZERO] = '0',
538 };
539
540 static void print_liveness(struct bpf_verifier_env *env,
541 enum bpf_reg_liveness live)
542 {
543 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
544 verbose(env, "_");
545 if (live & REG_LIVE_READ)
546 verbose(env, "r");
547 if (live & REG_LIVE_WRITTEN)
548 verbose(env, "w");
549 if (live & REG_LIVE_DONE)
550 verbose(env, "D");
551 }
552
553 static struct bpf_func_state *func(struct bpf_verifier_env *env,
554 const struct bpf_reg_state *reg)
555 {
556 struct bpf_verifier_state *cur = env->cur_state;
557
558 return cur->frame[reg->frameno];
559 }
560
561 static const char *kernel_type_name(const struct btf* btf, u32 id)
562 {
563 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
564 }
565
566 static void print_verifier_state(struct bpf_verifier_env *env,
567 const struct bpf_func_state *state)
568 {
569 const struct bpf_reg_state *reg;
570 enum bpf_reg_type t;
571 int i;
572
573 if (state->frameno)
574 verbose(env, " frame%d:", state->frameno);
575 for (i = 0; i < MAX_BPF_REG; i++) {
576 reg = &state->regs[i];
577 t = reg->type;
578 if (t == NOT_INIT)
579 continue;
580 verbose(env, " R%d", i);
581 print_liveness(env, reg->live);
582 verbose(env, "=%s", reg_type_str[t]);
583 if (t == SCALAR_VALUE && reg->precise)
584 verbose(env, "P");
585 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
586 tnum_is_const(reg->var_off)) {
587 /* reg->off should be 0 for SCALAR_VALUE */
588 verbose(env, "%lld", reg->var_off.value + reg->off);
589 } else {
590 if (t == PTR_TO_BTF_ID ||
591 t == PTR_TO_BTF_ID_OR_NULL ||
592 t == PTR_TO_PERCPU_BTF_ID)
593 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
594 verbose(env, "(id=%d", reg->id);
595 if (reg_type_may_be_refcounted_or_null(t))
596 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
597 if (t != SCALAR_VALUE)
598 verbose(env, ",off=%d", reg->off);
599 if (type_is_pkt_pointer(t))
600 verbose(env, ",r=%d", reg->range);
601 else if (t == CONST_PTR_TO_MAP ||
602 t == PTR_TO_MAP_VALUE ||
603 t == PTR_TO_MAP_VALUE_OR_NULL)
604 verbose(env, ",ks=%d,vs=%d",
605 reg->map_ptr->key_size,
606 reg->map_ptr->value_size);
607 if (tnum_is_const(reg->var_off)) {
608 /* Typically an immediate SCALAR_VALUE, but
609 * could be a pointer whose offset is too big
610 * for reg->off
611 */
612 verbose(env, ",imm=%llx", reg->var_off.value);
613 } else {
614 if (reg->smin_value != reg->umin_value &&
615 reg->smin_value != S64_MIN)
616 verbose(env, ",smin_value=%lld",
617 (long long)reg->smin_value);
618 if (reg->smax_value != reg->umax_value &&
619 reg->smax_value != S64_MAX)
620 verbose(env, ",smax_value=%lld",
621 (long long)reg->smax_value);
622 if (reg->umin_value != 0)
623 verbose(env, ",umin_value=%llu",
624 (unsigned long long)reg->umin_value);
625 if (reg->umax_value != U64_MAX)
626 verbose(env, ",umax_value=%llu",
627 (unsigned long long)reg->umax_value);
628 if (!tnum_is_unknown(reg->var_off)) {
629 char tn_buf[48];
630
631 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
632 verbose(env, ",var_off=%s", tn_buf);
633 }
634 if (reg->s32_min_value != reg->smin_value &&
635 reg->s32_min_value != S32_MIN)
636 verbose(env, ",s32_min_value=%d",
637 (int)(reg->s32_min_value));
638 if (reg->s32_max_value != reg->smax_value &&
639 reg->s32_max_value != S32_MAX)
640 verbose(env, ",s32_max_value=%d",
641 (int)(reg->s32_max_value));
642 if (reg->u32_min_value != reg->umin_value &&
643 reg->u32_min_value != U32_MIN)
644 verbose(env, ",u32_min_value=%d",
645 (int)(reg->u32_min_value));
646 if (reg->u32_max_value != reg->umax_value &&
647 reg->u32_max_value != U32_MAX)
648 verbose(env, ",u32_max_value=%d",
649 (int)(reg->u32_max_value));
650 }
651 verbose(env, ")");
652 }
653 }
654 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
655 char types_buf[BPF_REG_SIZE + 1];
656 bool valid = false;
657 int j;
658
659 for (j = 0; j < BPF_REG_SIZE; j++) {
660 if (state->stack[i].slot_type[j] != STACK_INVALID)
661 valid = true;
662 types_buf[j] = slot_type_char[
663 state->stack[i].slot_type[j]];
664 }
665 types_buf[BPF_REG_SIZE] = 0;
666 if (!valid)
667 continue;
668 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
669 print_liveness(env, state->stack[i].spilled_ptr.live);
670 if (state->stack[i].slot_type[0] == STACK_SPILL) {
671 reg = &state->stack[i].spilled_ptr;
672 t = reg->type;
673 verbose(env, "=%s", reg_type_str[t]);
674 if (t == SCALAR_VALUE && reg->precise)
675 verbose(env, "P");
676 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
677 verbose(env, "%lld", reg->var_off.value + reg->off);
678 } else {
679 verbose(env, "=%s", types_buf);
680 }
681 }
682 if (state->acquired_refs && state->refs[0].id) {
683 verbose(env, " refs=%d", state->refs[0].id);
684 for (i = 1; i < state->acquired_refs; i++)
685 if (state->refs[i].id)
686 verbose(env, ",%d", state->refs[i].id);
687 }
688 verbose(env, "\n");
689 }
690
691 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
692 static int copy_##NAME##_state(struct bpf_func_state *dst, \
693 const struct bpf_func_state *src) \
694 { \
695 if (!src->FIELD) \
696 return 0; \
697 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
698 /* internal bug, make state invalid to reject the program */ \
699 memset(dst, 0, sizeof(*dst)); \
700 return -EFAULT; \
701 } \
702 memcpy(dst->FIELD, src->FIELD, \
703 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
704 return 0; \
705 }
706 /* copy_reference_state() */
707 COPY_STATE_FN(reference, acquired_refs, refs, 1)
708 /* copy_stack_state() */
709 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
710 #undef COPY_STATE_FN
711
712 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
713 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
714 bool copy_old) \
715 { \
716 u32 old_size = state->COUNT; \
717 struct bpf_##NAME##_state *new_##FIELD; \
718 int slot = size / SIZE; \
719 \
720 if (size <= old_size || !size) { \
721 if (copy_old) \
722 return 0; \
723 state->COUNT = slot * SIZE; \
724 if (!size && old_size) { \
725 kfree(state->FIELD); \
726 state->FIELD = NULL; \
727 } \
728 return 0; \
729 } \
730 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
731 GFP_KERNEL); \
732 if (!new_##FIELD) \
733 return -ENOMEM; \
734 if (copy_old) { \
735 if (state->FIELD) \
736 memcpy(new_##FIELD, state->FIELD, \
737 sizeof(*new_##FIELD) * (old_size / SIZE)); \
738 memset(new_##FIELD + old_size / SIZE, 0, \
739 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
740 } \
741 state->COUNT = slot * SIZE; \
742 kfree(state->FIELD); \
743 state->FIELD = new_##FIELD; \
744 return 0; \
745 }
746 /* realloc_reference_state() */
747 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
748 /* realloc_stack_state() */
749 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
750 #undef REALLOC_STATE_FN
751
752 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
753 * make it consume minimal amount of memory. check_stack_write() access from
754 * the program calls into realloc_func_state() to grow the stack size.
755 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
756 * which realloc_stack_state() copies over. It points to previous
757 * bpf_verifier_state which is never reallocated.
758 */
759 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
760 int refs_size, bool copy_old)
761 {
762 int err = realloc_reference_state(state, refs_size, copy_old);
763 if (err)
764 return err;
765 return realloc_stack_state(state, stack_size, copy_old);
766 }
767
768 /* Acquire a pointer id from the env and update the state->refs to include
769 * this new pointer reference.
770 * On success, returns a valid pointer id to associate with the register
771 * On failure, returns a negative errno.
772 */
773 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
774 {
775 struct bpf_func_state *state = cur_func(env);
776 int new_ofs = state->acquired_refs;
777 int id, err;
778
779 err = realloc_reference_state(state, state->acquired_refs + 1, true);
780 if (err)
781 return err;
782 id = ++env->id_gen;
783 state->refs[new_ofs].id = id;
784 state->refs[new_ofs].insn_idx = insn_idx;
785
786 return id;
787 }
788
789 /* release function corresponding to acquire_reference_state(). Idempotent. */
790 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
791 {
792 int i, last_idx;
793
794 last_idx = state->acquired_refs - 1;
795 for (i = 0; i < state->acquired_refs; i++) {
796 if (state->refs[i].id == ptr_id) {
797 if (last_idx && i != last_idx)
798 memcpy(&state->refs[i], &state->refs[last_idx],
799 sizeof(*state->refs));
800 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
801 state->acquired_refs--;
802 return 0;
803 }
804 }
805 return -EINVAL;
806 }
807
808 static int transfer_reference_state(struct bpf_func_state *dst,
809 struct bpf_func_state *src)
810 {
811 int err = realloc_reference_state(dst, src->acquired_refs, false);
812 if (err)
813 return err;
814 err = copy_reference_state(dst, src);
815 if (err)
816 return err;
817 return 0;
818 }
819
820 static void free_func_state(struct bpf_func_state *state)
821 {
822 if (!state)
823 return;
824 kfree(state->refs);
825 kfree(state->stack);
826 kfree(state);
827 }
828
829 static void clear_jmp_history(struct bpf_verifier_state *state)
830 {
831 kfree(state->jmp_history);
832 state->jmp_history = NULL;
833 state->jmp_history_cnt = 0;
834 }
835
836 static void free_verifier_state(struct bpf_verifier_state *state,
837 bool free_self)
838 {
839 int i;
840
841 for (i = 0; i <= state->curframe; i++) {
842 free_func_state(state->frame[i]);
843 state->frame[i] = NULL;
844 }
845 clear_jmp_history(state);
846 if (free_self)
847 kfree(state);
848 }
849
850 /* copy verifier state from src to dst growing dst stack space
851 * when necessary to accommodate larger src stack
852 */
853 static int copy_func_state(struct bpf_func_state *dst,
854 const struct bpf_func_state *src)
855 {
856 int err;
857
858 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
859 false);
860 if (err)
861 return err;
862 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
863 err = copy_reference_state(dst, src);
864 if (err)
865 return err;
866 return copy_stack_state(dst, src);
867 }
868
869 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
870 const struct bpf_verifier_state *src)
871 {
872 struct bpf_func_state *dst;
873 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
874 int i, err;
875
876 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
877 kfree(dst_state->jmp_history);
878 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
879 if (!dst_state->jmp_history)
880 return -ENOMEM;
881 }
882 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
883 dst_state->jmp_history_cnt = src->jmp_history_cnt;
884
885 /* if dst has more stack frames then src frame, free them */
886 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
887 free_func_state(dst_state->frame[i]);
888 dst_state->frame[i] = NULL;
889 }
890 dst_state->speculative = src->speculative;
891 dst_state->curframe = src->curframe;
892 dst_state->active_spin_lock = src->active_spin_lock;
893 dst_state->branches = src->branches;
894 dst_state->parent = src->parent;
895 dst_state->first_insn_idx = src->first_insn_idx;
896 dst_state->last_insn_idx = src->last_insn_idx;
897 for (i = 0; i <= src->curframe; i++) {
898 dst = dst_state->frame[i];
899 if (!dst) {
900 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
901 if (!dst)
902 return -ENOMEM;
903 dst_state->frame[i] = dst;
904 }
905 err = copy_func_state(dst, src->frame[i]);
906 if (err)
907 return err;
908 }
909 return 0;
910 }
911
912 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
913 {
914 while (st) {
915 u32 br = --st->branches;
916
917 /* WARN_ON(br > 1) technically makes sense here,
918 * but see comment in push_stack(), hence:
919 */
920 WARN_ONCE((int)br < 0,
921 "BUG update_branch_counts:branches_to_explore=%d\n",
922 br);
923 if (br)
924 break;
925 st = st->parent;
926 }
927 }
928
929 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
930 int *insn_idx, bool pop_log)
931 {
932 struct bpf_verifier_state *cur = env->cur_state;
933 struct bpf_verifier_stack_elem *elem, *head = env->head;
934 int err;
935
936 if (env->head == NULL)
937 return -ENOENT;
938
939 if (cur) {
940 err = copy_verifier_state(cur, &head->st);
941 if (err)
942 return err;
943 }
944 if (pop_log)
945 bpf_vlog_reset(&env->log, head->log_pos);
946 if (insn_idx)
947 *insn_idx = head->insn_idx;
948 if (prev_insn_idx)
949 *prev_insn_idx = head->prev_insn_idx;
950 elem = head->next;
951 free_verifier_state(&head->st, false);
952 kfree(head);
953 env->head = elem;
954 env->stack_size--;
955 return 0;
956 }
957
958 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
959 int insn_idx, int prev_insn_idx,
960 bool speculative)
961 {
962 struct bpf_verifier_state *cur = env->cur_state;
963 struct bpf_verifier_stack_elem *elem;
964 int err;
965
966 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
967 if (!elem)
968 goto err;
969
970 elem->insn_idx = insn_idx;
971 elem->prev_insn_idx = prev_insn_idx;
972 elem->next = env->head;
973 elem->log_pos = env->log.len_used;
974 env->head = elem;
975 env->stack_size++;
976 err = copy_verifier_state(&elem->st, cur);
977 if (err)
978 goto err;
979 elem->st.speculative |= speculative;
980 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
981 verbose(env, "The sequence of %d jumps is too complex.\n",
982 env->stack_size);
983 goto err;
984 }
985 if (elem->st.parent) {
986 ++elem->st.parent->branches;
987 /* WARN_ON(branches > 2) technically makes sense here,
988 * but
989 * 1. speculative states will bump 'branches' for non-branch
990 * instructions
991 * 2. is_state_visited() heuristics may decide not to create
992 * a new state for a sequence of branches and all such current
993 * and cloned states will be pointing to a single parent state
994 * which might have large 'branches' count.
995 */
996 }
997 return &elem->st;
998 err:
999 free_verifier_state(env->cur_state, true);
1000 env->cur_state = NULL;
1001 /* pop all elements and return */
1002 while (!pop_stack(env, NULL, NULL, false));
1003 return NULL;
1004 }
1005
1006 #define CALLER_SAVED_REGS 6
1007 static const int caller_saved[CALLER_SAVED_REGS] = {
1008 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1009 };
1010
1011 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1012 struct bpf_reg_state *reg);
1013
1014 /* This helper doesn't clear reg->id */
1015 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1016 {
1017 reg->var_off = tnum_const(imm);
1018 reg->smin_value = (s64)imm;
1019 reg->smax_value = (s64)imm;
1020 reg->umin_value = imm;
1021 reg->umax_value = imm;
1022
1023 reg->s32_min_value = (s32)imm;
1024 reg->s32_max_value = (s32)imm;
1025 reg->u32_min_value = (u32)imm;
1026 reg->u32_max_value = (u32)imm;
1027 }
1028
1029 /* Mark the unknown part of a register (variable offset or scalar value) as
1030 * known to have the value @imm.
1031 */
1032 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1033 {
1034 /* Clear id, off, and union(map_ptr, range) */
1035 memset(((u8 *)reg) + sizeof(reg->type), 0,
1036 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1037 ___mark_reg_known(reg, imm);
1038 }
1039
1040 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1041 {
1042 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1043 reg->s32_min_value = (s32)imm;
1044 reg->s32_max_value = (s32)imm;
1045 reg->u32_min_value = (u32)imm;
1046 reg->u32_max_value = (u32)imm;
1047 }
1048
1049 /* Mark the 'variable offset' part of a register as zero. This should be
1050 * used only on registers holding a pointer type.
1051 */
1052 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1053 {
1054 __mark_reg_known(reg, 0);
1055 }
1056
1057 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1058 {
1059 __mark_reg_known(reg, 0);
1060 reg->type = SCALAR_VALUE;
1061 }
1062
1063 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1064 struct bpf_reg_state *regs, u32 regno)
1065 {
1066 if (WARN_ON(regno >= MAX_BPF_REG)) {
1067 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1068 /* Something bad happened, let's kill all regs */
1069 for (regno = 0; regno < MAX_BPF_REG; regno++)
1070 __mark_reg_not_init(env, regs + regno);
1071 return;
1072 }
1073 __mark_reg_known_zero(regs + regno);
1074 }
1075
1076 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1077 {
1078 return type_is_pkt_pointer(reg->type);
1079 }
1080
1081 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1082 {
1083 return reg_is_pkt_pointer(reg) ||
1084 reg->type == PTR_TO_PACKET_END;
1085 }
1086
1087 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1088 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1089 enum bpf_reg_type which)
1090 {
1091 /* The register can already have a range from prior markings.
1092 * This is fine as long as it hasn't been advanced from its
1093 * origin.
1094 */
1095 return reg->type == which &&
1096 reg->id == 0 &&
1097 reg->off == 0 &&
1098 tnum_equals_const(reg->var_off, 0);
1099 }
1100
1101 /* Reset the min/max bounds of a register */
1102 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1103 {
1104 reg->smin_value = S64_MIN;
1105 reg->smax_value = S64_MAX;
1106 reg->umin_value = 0;
1107 reg->umax_value = U64_MAX;
1108
1109 reg->s32_min_value = S32_MIN;
1110 reg->s32_max_value = S32_MAX;
1111 reg->u32_min_value = 0;
1112 reg->u32_max_value = U32_MAX;
1113 }
1114
1115 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1116 {
1117 reg->smin_value = S64_MIN;
1118 reg->smax_value = S64_MAX;
1119 reg->umin_value = 0;
1120 reg->umax_value = U64_MAX;
1121 }
1122
1123 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1124 {
1125 reg->s32_min_value = S32_MIN;
1126 reg->s32_max_value = S32_MAX;
1127 reg->u32_min_value = 0;
1128 reg->u32_max_value = U32_MAX;
1129 }
1130
1131 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1132 {
1133 struct tnum var32_off = tnum_subreg(reg->var_off);
1134
1135 /* min signed is max(sign bit) | min(other bits) */
1136 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1137 var32_off.value | (var32_off.mask & S32_MIN));
1138 /* max signed is min(sign bit) | max(other bits) */
1139 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1140 var32_off.value | (var32_off.mask & S32_MAX));
1141 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1142 reg->u32_max_value = min(reg->u32_max_value,
1143 (u32)(var32_off.value | var32_off.mask));
1144 }
1145
1146 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1147 {
1148 /* min signed is max(sign bit) | min(other bits) */
1149 reg->smin_value = max_t(s64, reg->smin_value,
1150 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1151 /* max signed is min(sign bit) | max(other bits) */
1152 reg->smax_value = min_t(s64, reg->smax_value,
1153 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1154 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1155 reg->umax_value = min(reg->umax_value,
1156 reg->var_off.value | reg->var_off.mask);
1157 }
1158
1159 static void __update_reg_bounds(struct bpf_reg_state *reg)
1160 {
1161 __update_reg32_bounds(reg);
1162 __update_reg64_bounds(reg);
1163 }
1164
1165 /* Uses signed min/max values to inform unsigned, and vice-versa */
1166 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1167 {
1168 /* Learn sign from signed bounds.
1169 * If we cannot cross the sign boundary, then signed and unsigned bounds
1170 * are the same, so combine. This works even in the negative case, e.g.
1171 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1172 */
1173 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1174 reg->s32_min_value = reg->u32_min_value =
1175 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1176 reg->s32_max_value = reg->u32_max_value =
1177 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1178 return;
1179 }
1180 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1181 * boundary, so we must be careful.
1182 */
1183 if ((s32)reg->u32_max_value >= 0) {
1184 /* Positive. We can't learn anything from the smin, but smax
1185 * is positive, hence safe.
1186 */
1187 reg->s32_min_value = reg->u32_min_value;
1188 reg->s32_max_value = reg->u32_max_value =
1189 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1190 } else if ((s32)reg->u32_min_value < 0) {
1191 /* Negative. We can't learn anything from the smax, but smin
1192 * is negative, hence safe.
1193 */
1194 reg->s32_min_value = reg->u32_min_value =
1195 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1196 reg->s32_max_value = reg->u32_max_value;
1197 }
1198 }
1199
1200 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1201 {
1202 /* Learn sign from signed bounds.
1203 * If we cannot cross the sign boundary, then signed and unsigned bounds
1204 * are the same, so combine. This works even in the negative case, e.g.
1205 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1206 */
1207 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1208 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1209 reg->umin_value);
1210 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1211 reg->umax_value);
1212 return;
1213 }
1214 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1215 * boundary, so we must be careful.
1216 */
1217 if ((s64)reg->umax_value >= 0) {
1218 /* Positive. We can't learn anything from the smin, but smax
1219 * is positive, hence safe.
1220 */
1221 reg->smin_value = reg->umin_value;
1222 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1223 reg->umax_value);
1224 } else if ((s64)reg->umin_value < 0) {
1225 /* Negative. We can't learn anything from the smax, but smin
1226 * is negative, hence safe.
1227 */
1228 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1229 reg->umin_value);
1230 reg->smax_value = reg->umax_value;
1231 }
1232 }
1233
1234 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1235 {
1236 __reg32_deduce_bounds(reg);
1237 __reg64_deduce_bounds(reg);
1238 }
1239
1240 /* Attempts to improve var_off based on unsigned min/max information */
1241 static void __reg_bound_offset(struct bpf_reg_state *reg)
1242 {
1243 struct tnum var64_off = tnum_intersect(reg->var_off,
1244 tnum_range(reg->umin_value,
1245 reg->umax_value));
1246 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1247 tnum_range(reg->u32_min_value,
1248 reg->u32_max_value));
1249
1250 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1251 }
1252
1253 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1254 {
1255 reg->umin_value = reg->u32_min_value;
1256 reg->umax_value = reg->u32_max_value;
1257 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1258 * but must be positive otherwise set to worse case bounds
1259 * and refine later from tnum.
1260 */
1261 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
1262 reg->smax_value = reg->s32_max_value;
1263 else
1264 reg->smax_value = U32_MAX;
1265 if (reg->s32_min_value >= 0)
1266 reg->smin_value = reg->s32_min_value;
1267 else
1268 reg->smin_value = 0;
1269 }
1270
1271 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1272 {
1273 /* special case when 64-bit register has upper 32-bit register
1274 * zeroed. Typically happens after zext or <<32, >>32 sequence
1275 * allowing us to use 32-bit bounds directly,
1276 */
1277 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1278 __reg_assign_32_into_64(reg);
1279 } else {
1280 /* Otherwise the best we can do is push lower 32bit known and
1281 * unknown bits into register (var_off set from jmp logic)
1282 * then learn as much as possible from the 64-bit tnum
1283 * known and unknown bits. The previous smin/smax bounds are
1284 * invalid here because of jmp32 compare so mark them unknown
1285 * so they do not impact tnum bounds calculation.
1286 */
1287 __mark_reg64_unbounded(reg);
1288 __update_reg_bounds(reg);
1289 }
1290
1291 /* Intersecting with the old var_off might have improved our bounds
1292 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1293 * then new var_off is (0; 0x7f...fc) which improves our umax.
1294 */
1295 __reg_deduce_bounds(reg);
1296 __reg_bound_offset(reg);
1297 __update_reg_bounds(reg);
1298 }
1299
1300 static bool __reg64_bound_s32(s64 a)
1301 {
1302 return a > S32_MIN && a < S32_MAX;
1303 }
1304
1305 static bool __reg64_bound_u32(u64 a)
1306 {
1307 if (a > U32_MIN && a < U32_MAX)
1308 return true;
1309 return false;
1310 }
1311
1312 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1313 {
1314 __mark_reg32_unbounded(reg);
1315
1316 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1317 reg->s32_min_value = (s32)reg->smin_value;
1318 reg->s32_max_value = (s32)reg->smax_value;
1319 }
1320 if (__reg64_bound_u32(reg->umin_value))
1321 reg->u32_min_value = (u32)reg->umin_value;
1322 if (__reg64_bound_u32(reg->umax_value))
1323 reg->u32_max_value = (u32)reg->umax_value;
1324
1325 /* Intersecting with the old var_off might have improved our bounds
1326 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1327 * then new var_off is (0; 0x7f...fc) which improves our umax.
1328 */
1329 __reg_deduce_bounds(reg);
1330 __reg_bound_offset(reg);
1331 __update_reg_bounds(reg);
1332 }
1333
1334 /* Mark a register as having a completely unknown (scalar) value. */
1335 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1336 struct bpf_reg_state *reg)
1337 {
1338 /*
1339 * Clear type, id, off, and union(map_ptr, range) and
1340 * padding between 'type' and union
1341 */
1342 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1343 reg->type = SCALAR_VALUE;
1344 reg->var_off = tnum_unknown;
1345 reg->frameno = 0;
1346 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
1347 __mark_reg_unbounded(reg);
1348 }
1349
1350 static void mark_reg_unknown(struct bpf_verifier_env *env,
1351 struct bpf_reg_state *regs, u32 regno)
1352 {
1353 if (WARN_ON(regno >= MAX_BPF_REG)) {
1354 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1355 /* Something bad happened, let's kill all regs except FP */
1356 for (regno = 0; regno < BPF_REG_FP; regno++)
1357 __mark_reg_not_init(env, regs + regno);
1358 return;
1359 }
1360 __mark_reg_unknown(env, regs + regno);
1361 }
1362
1363 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1364 struct bpf_reg_state *reg)
1365 {
1366 __mark_reg_unknown(env, reg);
1367 reg->type = NOT_INIT;
1368 }
1369
1370 static void mark_reg_not_init(struct bpf_verifier_env *env,
1371 struct bpf_reg_state *regs, u32 regno)
1372 {
1373 if (WARN_ON(regno >= MAX_BPF_REG)) {
1374 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1375 /* Something bad happened, let's kill all regs except FP */
1376 for (regno = 0; regno < BPF_REG_FP; regno++)
1377 __mark_reg_not_init(env, regs + regno);
1378 return;
1379 }
1380 __mark_reg_not_init(env, regs + regno);
1381 }
1382
1383 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1384 struct bpf_reg_state *regs, u32 regno,
1385 enum bpf_reg_type reg_type,
1386 struct btf *btf, u32 btf_id)
1387 {
1388 if (reg_type == SCALAR_VALUE) {
1389 mark_reg_unknown(env, regs, regno);
1390 return;
1391 }
1392 mark_reg_known_zero(env, regs, regno);
1393 regs[regno].type = PTR_TO_BTF_ID;
1394 regs[regno].btf = btf;
1395 regs[regno].btf_id = btf_id;
1396 }
1397
1398 #define DEF_NOT_SUBREG (0)
1399 static void init_reg_state(struct bpf_verifier_env *env,
1400 struct bpf_func_state *state)
1401 {
1402 struct bpf_reg_state *regs = state->regs;
1403 int i;
1404
1405 for (i = 0; i < MAX_BPF_REG; i++) {
1406 mark_reg_not_init(env, regs, i);
1407 regs[i].live = REG_LIVE_NONE;
1408 regs[i].parent = NULL;
1409 regs[i].subreg_def = DEF_NOT_SUBREG;
1410 }
1411
1412 /* frame pointer */
1413 regs[BPF_REG_FP].type = PTR_TO_STACK;
1414 mark_reg_known_zero(env, regs, BPF_REG_FP);
1415 regs[BPF_REG_FP].frameno = state->frameno;
1416 }
1417
1418 #define BPF_MAIN_FUNC (-1)
1419 static void init_func_state(struct bpf_verifier_env *env,
1420 struct bpf_func_state *state,
1421 int callsite, int frameno, int subprogno)
1422 {
1423 state->callsite = callsite;
1424 state->frameno = frameno;
1425 state->subprogno = subprogno;
1426 init_reg_state(env, state);
1427 }
1428
1429 enum reg_arg_type {
1430 SRC_OP, /* register is used as source operand */
1431 DST_OP, /* register is used as destination operand */
1432 DST_OP_NO_MARK /* same as above, check only, don't mark */
1433 };
1434
1435 static int cmp_subprogs(const void *a, const void *b)
1436 {
1437 return ((struct bpf_subprog_info *)a)->start -
1438 ((struct bpf_subprog_info *)b)->start;
1439 }
1440
1441 static int find_subprog(struct bpf_verifier_env *env, int off)
1442 {
1443 struct bpf_subprog_info *p;
1444
1445 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1446 sizeof(env->subprog_info[0]), cmp_subprogs);
1447 if (!p)
1448 return -ENOENT;
1449 return p - env->subprog_info;
1450
1451 }
1452
1453 static int add_subprog(struct bpf_verifier_env *env, int off)
1454 {
1455 int insn_cnt = env->prog->len;
1456 int ret;
1457
1458 if (off >= insn_cnt || off < 0) {
1459 verbose(env, "call to invalid destination\n");
1460 return -EINVAL;
1461 }
1462 ret = find_subprog(env, off);
1463 if (ret >= 0)
1464 return 0;
1465 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1466 verbose(env, "too many subprograms\n");
1467 return -E2BIG;
1468 }
1469 env->subprog_info[env->subprog_cnt++].start = off;
1470 sort(env->subprog_info, env->subprog_cnt,
1471 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1472 return 0;
1473 }
1474
1475 static int check_subprogs(struct bpf_verifier_env *env)
1476 {
1477 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1478 struct bpf_subprog_info *subprog = env->subprog_info;
1479 struct bpf_insn *insn = env->prog->insnsi;
1480 int insn_cnt = env->prog->len;
1481
1482 /* Add entry function. */
1483 ret = add_subprog(env, 0);
1484 if (ret < 0)
1485 return ret;
1486
1487 /* determine subprog starts. The end is one before the next starts */
1488 for (i = 0; i < insn_cnt; i++) {
1489 if (insn[i].code != (BPF_JMP | BPF_CALL))
1490 continue;
1491 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1492 continue;
1493 if (!env->bpf_capable) {
1494 verbose(env,
1495 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1496 return -EPERM;
1497 }
1498 ret = add_subprog(env, i + insn[i].imm + 1);
1499 if (ret < 0)
1500 return ret;
1501 }
1502
1503 /* Add a fake 'exit' subprog which could simplify subprog iteration
1504 * logic. 'subprog_cnt' should not be increased.
1505 */
1506 subprog[env->subprog_cnt].start = insn_cnt;
1507
1508 if (env->log.level & BPF_LOG_LEVEL2)
1509 for (i = 0; i < env->subprog_cnt; i++)
1510 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1511
1512 /* now check that all jumps are within the same subprog */
1513 subprog_start = subprog[cur_subprog].start;
1514 subprog_end = subprog[cur_subprog + 1].start;
1515 for (i = 0; i < insn_cnt; i++) {
1516 u8 code = insn[i].code;
1517
1518 if (code == (BPF_JMP | BPF_CALL) &&
1519 insn[i].imm == BPF_FUNC_tail_call &&
1520 insn[i].src_reg != BPF_PSEUDO_CALL)
1521 subprog[cur_subprog].has_tail_call = true;
1522 if (BPF_CLASS(code) == BPF_LD &&
1523 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1524 subprog[cur_subprog].has_ld_abs = true;
1525 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1526 goto next;
1527 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1528 goto next;
1529 off = i + insn[i].off + 1;
1530 if (off < subprog_start || off >= subprog_end) {
1531 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1532 return -EINVAL;
1533 }
1534 next:
1535 if (i == subprog_end - 1) {
1536 /* to avoid fall-through from one subprog into another
1537 * the last insn of the subprog should be either exit
1538 * or unconditional jump back
1539 */
1540 if (code != (BPF_JMP | BPF_EXIT) &&
1541 code != (BPF_JMP | BPF_JA)) {
1542 verbose(env, "last insn is not an exit or jmp\n");
1543 return -EINVAL;
1544 }
1545 subprog_start = subprog_end;
1546 cur_subprog++;
1547 if (cur_subprog < env->subprog_cnt)
1548 subprog_end = subprog[cur_subprog + 1].start;
1549 }
1550 }
1551 return 0;
1552 }
1553
1554 /* Parentage chain of this register (or stack slot) should take care of all
1555 * issues like callee-saved registers, stack slot allocation time, etc.
1556 */
1557 static int mark_reg_read(struct bpf_verifier_env *env,
1558 const struct bpf_reg_state *state,
1559 struct bpf_reg_state *parent, u8 flag)
1560 {
1561 bool writes = parent == state->parent; /* Observe write marks */
1562 int cnt = 0;
1563
1564 while (parent) {
1565 /* if read wasn't screened by an earlier write ... */
1566 if (writes && state->live & REG_LIVE_WRITTEN)
1567 break;
1568 if (parent->live & REG_LIVE_DONE) {
1569 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1570 reg_type_str[parent->type],
1571 parent->var_off.value, parent->off);
1572 return -EFAULT;
1573 }
1574 /* The first condition is more likely to be true than the
1575 * second, checked it first.
1576 */
1577 if ((parent->live & REG_LIVE_READ) == flag ||
1578 parent->live & REG_LIVE_READ64)
1579 /* The parentage chain never changes and
1580 * this parent was already marked as LIVE_READ.
1581 * There is no need to keep walking the chain again and
1582 * keep re-marking all parents as LIVE_READ.
1583 * This case happens when the same register is read
1584 * multiple times without writes into it in-between.
1585 * Also, if parent has the stronger REG_LIVE_READ64 set,
1586 * then no need to set the weak REG_LIVE_READ32.
1587 */
1588 break;
1589 /* ... then we depend on parent's value */
1590 parent->live |= flag;
1591 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1592 if (flag == REG_LIVE_READ64)
1593 parent->live &= ~REG_LIVE_READ32;
1594 state = parent;
1595 parent = state->parent;
1596 writes = true;
1597 cnt++;
1598 }
1599
1600 if (env->longest_mark_read_walk < cnt)
1601 env->longest_mark_read_walk = cnt;
1602 return 0;
1603 }
1604
1605 /* This function is supposed to be used by the following 32-bit optimization
1606 * code only. It returns TRUE if the source or destination register operates
1607 * on 64-bit, otherwise return FALSE.
1608 */
1609 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1610 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1611 {
1612 u8 code, class, op;
1613
1614 code = insn->code;
1615 class = BPF_CLASS(code);
1616 op = BPF_OP(code);
1617 if (class == BPF_JMP) {
1618 /* BPF_EXIT for "main" will reach here. Return TRUE
1619 * conservatively.
1620 */
1621 if (op == BPF_EXIT)
1622 return true;
1623 if (op == BPF_CALL) {
1624 /* BPF to BPF call will reach here because of marking
1625 * caller saved clobber with DST_OP_NO_MARK for which we
1626 * don't care the register def because they are anyway
1627 * marked as NOT_INIT already.
1628 */
1629 if (insn->src_reg == BPF_PSEUDO_CALL)
1630 return false;
1631 /* Helper call will reach here because of arg type
1632 * check, conservatively return TRUE.
1633 */
1634 if (t == SRC_OP)
1635 return true;
1636
1637 return false;
1638 }
1639 }
1640
1641 if (class == BPF_ALU64 || class == BPF_JMP ||
1642 /* BPF_END always use BPF_ALU class. */
1643 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1644 return true;
1645
1646 if (class == BPF_ALU || class == BPF_JMP32)
1647 return false;
1648
1649 if (class == BPF_LDX) {
1650 if (t != SRC_OP)
1651 return BPF_SIZE(code) == BPF_DW;
1652 /* LDX source must be ptr. */
1653 return true;
1654 }
1655
1656 if (class == BPF_STX) {
1657 if (reg->type != SCALAR_VALUE)
1658 return true;
1659 return BPF_SIZE(code) == BPF_DW;
1660 }
1661
1662 if (class == BPF_LD) {
1663 u8 mode = BPF_MODE(code);
1664
1665 /* LD_IMM64 */
1666 if (mode == BPF_IMM)
1667 return true;
1668
1669 /* Both LD_IND and LD_ABS return 32-bit data. */
1670 if (t != SRC_OP)
1671 return false;
1672
1673 /* Implicit ctx ptr. */
1674 if (regno == BPF_REG_6)
1675 return true;
1676
1677 /* Explicit source could be any width. */
1678 return true;
1679 }
1680
1681 if (class == BPF_ST)
1682 /* The only source register for BPF_ST is a ptr. */
1683 return true;
1684
1685 /* Conservatively return true at default. */
1686 return true;
1687 }
1688
1689 /* Return TRUE if INSN doesn't have explicit value define. */
1690 static bool insn_no_def(struct bpf_insn *insn)
1691 {
1692 u8 class = BPF_CLASS(insn->code);
1693
1694 return (class == BPF_JMP || class == BPF_JMP32 ||
1695 class == BPF_STX || class == BPF_ST);
1696 }
1697
1698 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
1699 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1700 {
1701 if (insn_no_def(insn))
1702 return false;
1703
1704 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1705 }
1706
1707 static void mark_insn_zext(struct bpf_verifier_env *env,
1708 struct bpf_reg_state *reg)
1709 {
1710 s32 def_idx = reg->subreg_def;
1711
1712 if (def_idx == DEF_NOT_SUBREG)
1713 return;
1714
1715 env->insn_aux_data[def_idx - 1].zext_dst = true;
1716 /* The dst will be zero extended, so won't be sub-register anymore. */
1717 reg->subreg_def = DEF_NOT_SUBREG;
1718 }
1719
1720 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1721 enum reg_arg_type t)
1722 {
1723 struct bpf_verifier_state *vstate = env->cur_state;
1724 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1725 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1726 struct bpf_reg_state *reg, *regs = state->regs;
1727 bool rw64;
1728
1729 if (regno >= MAX_BPF_REG) {
1730 verbose(env, "R%d is invalid\n", regno);
1731 return -EINVAL;
1732 }
1733
1734 reg = &regs[regno];
1735 rw64 = is_reg64(env, insn, regno, reg, t);
1736 if (t == SRC_OP) {
1737 /* check whether register used as source operand can be read */
1738 if (reg->type == NOT_INIT) {
1739 verbose(env, "R%d !read_ok\n", regno);
1740 return -EACCES;
1741 }
1742 /* We don't need to worry about FP liveness because it's read-only */
1743 if (regno == BPF_REG_FP)
1744 return 0;
1745
1746 if (rw64)
1747 mark_insn_zext(env, reg);
1748
1749 return mark_reg_read(env, reg, reg->parent,
1750 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1751 } else {
1752 /* check whether register used as dest operand can be written to */
1753 if (regno == BPF_REG_FP) {
1754 verbose(env, "frame pointer is read only\n");
1755 return -EACCES;
1756 }
1757 reg->live |= REG_LIVE_WRITTEN;
1758 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1759 if (t == DST_OP)
1760 mark_reg_unknown(env, regs, regno);
1761 }
1762 return 0;
1763 }
1764
1765 /* for any branch, call, exit record the history of jmps in the given state */
1766 static int push_jmp_history(struct bpf_verifier_env *env,
1767 struct bpf_verifier_state *cur)
1768 {
1769 u32 cnt = cur->jmp_history_cnt;
1770 struct bpf_idx_pair *p;
1771
1772 cnt++;
1773 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1774 if (!p)
1775 return -ENOMEM;
1776 p[cnt - 1].idx = env->insn_idx;
1777 p[cnt - 1].prev_idx = env->prev_insn_idx;
1778 cur->jmp_history = p;
1779 cur->jmp_history_cnt = cnt;
1780 return 0;
1781 }
1782
1783 /* Backtrack one insn at a time. If idx is not at the top of recorded
1784 * history then previous instruction came from straight line execution.
1785 */
1786 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1787 u32 *history)
1788 {
1789 u32 cnt = *history;
1790
1791 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1792 i = st->jmp_history[cnt - 1].prev_idx;
1793 (*history)--;
1794 } else {
1795 i--;
1796 }
1797 return i;
1798 }
1799
1800 /* For given verifier state backtrack_insn() is called from the last insn to
1801 * the first insn. Its purpose is to compute a bitmask of registers and
1802 * stack slots that needs precision in the parent verifier state.
1803 */
1804 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1805 u32 *reg_mask, u64 *stack_mask)
1806 {
1807 const struct bpf_insn_cbs cbs = {
1808 .cb_print = verbose,
1809 .private_data = env,
1810 };
1811 struct bpf_insn *insn = env->prog->insnsi + idx;
1812 u8 class = BPF_CLASS(insn->code);
1813 u8 opcode = BPF_OP(insn->code);
1814 u8 mode = BPF_MODE(insn->code);
1815 u32 dreg = 1u << insn->dst_reg;
1816 u32 sreg = 1u << insn->src_reg;
1817 u32 spi;
1818
1819 if (insn->code == 0)
1820 return 0;
1821 if (env->log.level & BPF_LOG_LEVEL) {
1822 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1823 verbose(env, "%d: ", idx);
1824 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1825 }
1826
1827 if (class == BPF_ALU || class == BPF_ALU64) {
1828 if (!(*reg_mask & dreg))
1829 return 0;
1830 if (opcode == BPF_MOV) {
1831 if (BPF_SRC(insn->code) == BPF_X) {
1832 /* dreg = sreg
1833 * dreg needs precision after this insn
1834 * sreg needs precision before this insn
1835 */
1836 *reg_mask &= ~dreg;
1837 *reg_mask |= sreg;
1838 } else {
1839 /* dreg = K
1840 * dreg needs precision after this insn.
1841 * Corresponding register is already marked
1842 * as precise=true in this verifier state.
1843 * No further markings in parent are necessary
1844 */
1845 *reg_mask &= ~dreg;
1846 }
1847 } else {
1848 if (BPF_SRC(insn->code) == BPF_X) {
1849 /* dreg += sreg
1850 * both dreg and sreg need precision
1851 * before this insn
1852 */
1853 *reg_mask |= sreg;
1854 } /* else dreg += K
1855 * dreg still needs precision before this insn
1856 */
1857 }
1858 } else if (class == BPF_LDX) {
1859 if (!(*reg_mask & dreg))
1860 return 0;
1861 *reg_mask &= ~dreg;
1862
1863 /* scalars can only be spilled into stack w/o losing precision.
1864 * Load from any other memory can be zero extended.
1865 * The desire to keep that precision is already indicated
1866 * by 'precise' mark in corresponding register of this state.
1867 * No further tracking necessary.
1868 */
1869 if (insn->src_reg != BPF_REG_FP)
1870 return 0;
1871 if (BPF_SIZE(insn->code) != BPF_DW)
1872 return 0;
1873
1874 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1875 * that [fp - off] slot contains scalar that needs to be
1876 * tracked with precision
1877 */
1878 spi = (-insn->off - 1) / BPF_REG_SIZE;
1879 if (spi >= 64) {
1880 verbose(env, "BUG spi %d\n", spi);
1881 WARN_ONCE(1, "verifier backtracking bug");
1882 return -EFAULT;
1883 }
1884 *stack_mask |= 1ull << spi;
1885 } else if (class == BPF_STX || class == BPF_ST) {
1886 if (*reg_mask & dreg)
1887 /* stx & st shouldn't be using _scalar_ dst_reg
1888 * to access memory. It means backtracking
1889 * encountered a case of pointer subtraction.
1890 */
1891 return -ENOTSUPP;
1892 /* scalars can only be spilled into stack */
1893 if (insn->dst_reg != BPF_REG_FP)
1894 return 0;
1895 if (BPF_SIZE(insn->code) != BPF_DW)
1896 return 0;
1897 spi = (-insn->off - 1) / BPF_REG_SIZE;
1898 if (spi >= 64) {
1899 verbose(env, "BUG spi %d\n", spi);
1900 WARN_ONCE(1, "verifier backtracking bug");
1901 return -EFAULT;
1902 }
1903 if (!(*stack_mask & (1ull << spi)))
1904 return 0;
1905 *stack_mask &= ~(1ull << spi);
1906 if (class == BPF_STX)
1907 *reg_mask |= sreg;
1908 } else if (class == BPF_JMP || class == BPF_JMP32) {
1909 if (opcode == BPF_CALL) {
1910 if (insn->src_reg == BPF_PSEUDO_CALL)
1911 return -ENOTSUPP;
1912 /* regular helper call sets R0 */
1913 *reg_mask &= ~1;
1914 if (*reg_mask & 0x3f) {
1915 /* if backtracing was looking for registers R1-R5
1916 * they should have been found already.
1917 */
1918 verbose(env, "BUG regs %x\n", *reg_mask);
1919 WARN_ONCE(1, "verifier backtracking bug");
1920 return -EFAULT;
1921 }
1922 } else if (opcode == BPF_EXIT) {
1923 return -ENOTSUPP;
1924 }
1925 } else if (class == BPF_LD) {
1926 if (!(*reg_mask & dreg))
1927 return 0;
1928 *reg_mask &= ~dreg;
1929 /* It's ld_imm64 or ld_abs or ld_ind.
1930 * For ld_imm64 no further tracking of precision
1931 * into parent is necessary
1932 */
1933 if (mode == BPF_IND || mode == BPF_ABS)
1934 /* to be analyzed */
1935 return -ENOTSUPP;
1936 }
1937 return 0;
1938 }
1939
1940 /* the scalar precision tracking algorithm:
1941 * . at the start all registers have precise=false.
1942 * . scalar ranges are tracked as normal through alu and jmp insns.
1943 * . once precise value of the scalar register is used in:
1944 * . ptr + scalar alu
1945 * . if (scalar cond K|scalar)
1946 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1947 * backtrack through the verifier states and mark all registers and
1948 * stack slots with spilled constants that these scalar regisers
1949 * should be precise.
1950 * . during state pruning two registers (or spilled stack slots)
1951 * are equivalent if both are not precise.
1952 *
1953 * Note the verifier cannot simply walk register parentage chain,
1954 * since many different registers and stack slots could have been
1955 * used to compute single precise scalar.
1956 *
1957 * The approach of starting with precise=true for all registers and then
1958 * backtrack to mark a register as not precise when the verifier detects
1959 * that program doesn't care about specific value (e.g., when helper
1960 * takes register as ARG_ANYTHING parameter) is not safe.
1961 *
1962 * It's ok to walk single parentage chain of the verifier states.
1963 * It's possible that this backtracking will go all the way till 1st insn.
1964 * All other branches will be explored for needing precision later.
1965 *
1966 * The backtracking needs to deal with cases like:
1967 * 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)
1968 * r9 -= r8
1969 * r5 = r9
1970 * if r5 > 0x79f goto pc+7
1971 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1972 * r5 += 1
1973 * ...
1974 * call bpf_perf_event_output#25
1975 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1976 *
1977 * and this case:
1978 * r6 = 1
1979 * call foo // uses callee's r6 inside to compute r0
1980 * r0 += r6
1981 * if r0 == 0 goto
1982 *
1983 * to track above reg_mask/stack_mask needs to be independent for each frame.
1984 *
1985 * Also if parent's curframe > frame where backtracking started,
1986 * the verifier need to mark registers in both frames, otherwise callees
1987 * may incorrectly prune callers. This is similar to
1988 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1989 *
1990 * For now backtracking falls back into conservative marking.
1991 */
1992 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1993 struct bpf_verifier_state *st)
1994 {
1995 struct bpf_func_state *func;
1996 struct bpf_reg_state *reg;
1997 int i, j;
1998
1999 /* big hammer: mark all scalars precise in this path.
2000 * pop_stack may still get !precise scalars.
2001 */
2002 for (; st; st = st->parent)
2003 for (i = 0; i <= st->curframe; i++) {
2004 func = st->frame[i];
2005 for (j = 0; j < BPF_REG_FP; j++) {
2006 reg = &func->regs[j];
2007 if (reg->type != SCALAR_VALUE)
2008 continue;
2009 reg->precise = true;
2010 }
2011 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2012 if (func->stack[j].slot_type[0] != STACK_SPILL)
2013 continue;
2014 reg = &func->stack[j].spilled_ptr;
2015 if (reg->type != SCALAR_VALUE)
2016 continue;
2017 reg->precise = true;
2018 }
2019 }
2020 }
2021
2022 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2023 int spi)
2024 {
2025 struct bpf_verifier_state *st = env->cur_state;
2026 int first_idx = st->first_insn_idx;
2027 int last_idx = env->insn_idx;
2028 struct bpf_func_state *func;
2029 struct bpf_reg_state *reg;
2030 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2031 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2032 bool skip_first = true;
2033 bool new_marks = false;
2034 int i, err;
2035
2036 if (!env->bpf_capable)
2037 return 0;
2038
2039 func = st->frame[st->curframe];
2040 if (regno >= 0) {
2041 reg = &func->regs[regno];
2042 if (reg->type != SCALAR_VALUE) {
2043 WARN_ONCE(1, "backtracing misuse");
2044 return -EFAULT;
2045 }
2046 if (!reg->precise)
2047 new_marks = true;
2048 else
2049 reg_mask = 0;
2050 reg->precise = true;
2051 }
2052
2053 while (spi >= 0) {
2054 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2055 stack_mask = 0;
2056 break;
2057 }
2058 reg = &func->stack[spi].spilled_ptr;
2059 if (reg->type != SCALAR_VALUE) {
2060 stack_mask = 0;
2061 break;
2062 }
2063 if (!reg->precise)
2064 new_marks = true;
2065 else
2066 stack_mask = 0;
2067 reg->precise = true;
2068 break;
2069 }
2070
2071 if (!new_marks)
2072 return 0;
2073 if (!reg_mask && !stack_mask)
2074 return 0;
2075 for (;;) {
2076 DECLARE_BITMAP(mask, 64);
2077 u32 history = st->jmp_history_cnt;
2078
2079 if (env->log.level & BPF_LOG_LEVEL)
2080 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2081 for (i = last_idx;;) {
2082 if (skip_first) {
2083 err = 0;
2084 skip_first = false;
2085 } else {
2086 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2087 }
2088 if (err == -ENOTSUPP) {
2089 mark_all_scalars_precise(env, st);
2090 return 0;
2091 } else if (err) {
2092 return err;
2093 }
2094 if (!reg_mask && !stack_mask)
2095 /* Found assignment(s) into tracked register in this state.
2096 * Since this state is already marked, just return.
2097 * Nothing to be tracked further in the parent state.
2098 */
2099 return 0;
2100 if (i == first_idx)
2101 break;
2102 i = get_prev_insn_idx(st, i, &history);
2103 if (i >= env->prog->len) {
2104 /* This can happen if backtracking reached insn 0
2105 * and there are still reg_mask or stack_mask
2106 * to backtrack.
2107 * It means the backtracking missed the spot where
2108 * particular register was initialized with a constant.
2109 */
2110 verbose(env, "BUG backtracking idx %d\n", i);
2111 WARN_ONCE(1, "verifier backtracking bug");
2112 return -EFAULT;
2113 }
2114 }
2115 st = st->parent;
2116 if (!st)
2117 break;
2118
2119 new_marks = false;
2120 func = st->frame[st->curframe];
2121 bitmap_from_u64(mask, reg_mask);
2122 for_each_set_bit(i, mask, 32) {
2123 reg = &func->regs[i];
2124 if (reg->type != SCALAR_VALUE) {
2125 reg_mask &= ~(1u << i);
2126 continue;
2127 }
2128 if (!reg->precise)
2129 new_marks = true;
2130 reg->precise = true;
2131 }
2132
2133 bitmap_from_u64(mask, stack_mask);
2134 for_each_set_bit(i, mask, 64) {
2135 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2136 /* the sequence of instructions:
2137 * 2: (bf) r3 = r10
2138 * 3: (7b) *(u64 *)(r3 -8) = r0
2139 * 4: (79) r4 = *(u64 *)(r10 -8)
2140 * doesn't contain jmps. It's backtracked
2141 * as a single block.
2142 * During backtracking insn 3 is not recognized as
2143 * stack access, so at the end of backtracking
2144 * stack slot fp-8 is still marked in stack_mask.
2145 * However the parent state may not have accessed
2146 * fp-8 and it's "unallocated" stack space.
2147 * In such case fallback to conservative.
2148 */
2149 mark_all_scalars_precise(env, st);
2150 return 0;
2151 }
2152
2153 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2154 stack_mask &= ~(1ull << i);
2155 continue;
2156 }
2157 reg = &func->stack[i].spilled_ptr;
2158 if (reg->type != SCALAR_VALUE) {
2159 stack_mask &= ~(1ull << i);
2160 continue;
2161 }
2162 if (!reg->precise)
2163 new_marks = true;
2164 reg->precise = true;
2165 }
2166 if (env->log.level & BPF_LOG_LEVEL) {
2167 print_verifier_state(env, func);
2168 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2169 new_marks ? "didn't have" : "already had",
2170 reg_mask, stack_mask);
2171 }
2172
2173 if (!reg_mask && !stack_mask)
2174 break;
2175 if (!new_marks)
2176 break;
2177
2178 last_idx = st->last_insn_idx;
2179 first_idx = st->first_insn_idx;
2180 }
2181 return 0;
2182 }
2183
2184 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2185 {
2186 return __mark_chain_precision(env, regno, -1);
2187 }
2188
2189 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2190 {
2191 return __mark_chain_precision(env, -1, spi);
2192 }
2193
2194 static bool is_spillable_regtype(enum bpf_reg_type type)
2195 {
2196 switch (type) {
2197 case PTR_TO_MAP_VALUE:
2198 case PTR_TO_MAP_VALUE_OR_NULL:
2199 case PTR_TO_STACK:
2200 case PTR_TO_CTX:
2201 case PTR_TO_PACKET:
2202 case PTR_TO_PACKET_META:
2203 case PTR_TO_PACKET_END:
2204 case PTR_TO_FLOW_KEYS:
2205 case CONST_PTR_TO_MAP:
2206 case PTR_TO_SOCKET:
2207 case PTR_TO_SOCKET_OR_NULL:
2208 case PTR_TO_SOCK_COMMON:
2209 case PTR_TO_SOCK_COMMON_OR_NULL:
2210 case PTR_TO_TCP_SOCK:
2211 case PTR_TO_TCP_SOCK_OR_NULL:
2212 case PTR_TO_XDP_SOCK:
2213 case PTR_TO_BTF_ID:
2214 case PTR_TO_BTF_ID_OR_NULL:
2215 case PTR_TO_RDONLY_BUF:
2216 case PTR_TO_RDONLY_BUF_OR_NULL:
2217 case PTR_TO_RDWR_BUF:
2218 case PTR_TO_RDWR_BUF_OR_NULL:
2219 case PTR_TO_PERCPU_BTF_ID:
2220 case PTR_TO_MEM:
2221 case PTR_TO_MEM_OR_NULL:
2222 return true;
2223 default:
2224 return false;
2225 }
2226 }
2227
2228 /* Does this register contain a constant zero? */
2229 static bool register_is_null(struct bpf_reg_state *reg)
2230 {
2231 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2232 }
2233
2234 static bool register_is_const(struct bpf_reg_state *reg)
2235 {
2236 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2237 }
2238
2239 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2240 {
2241 return tnum_is_unknown(reg->var_off) &&
2242 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2243 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2244 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2245 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2246 }
2247
2248 static bool register_is_bounded(struct bpf_reg_state *reg)
2249 {
2250 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2251 }
2252
2253 static bool __is_pointer_value(bool allow_ptr_leaks,
2254 const struct bpf_reg_state *reg)
2255 {
2256 if (allow_ptr_leaks)
2257 return false;
2258
2259 return reg->type != SCALAR_VALUE;
2260 }
2261
2262 static void save_register_state(struct bpf_func_state *state,
2263 int spi, struct bpf_reg_state *reg)
2264 {
2265 int i;
2266
2267 state->stack[spi].spilled_ptr = *reg;
2268 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2269
2270 for (i = 0; i < BPF_REG_SIZE; i++)
2271 state->stack[spi].slot_type[i] = STACK_SPILL;
2272 }
2273
2274 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2275 * stack boundary and alignment are checked in check_mem_access()
2276 */
2277 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2278 /* stack frame we're writing to */
2279 struct bpf_func_state *state,
2280 int off, int size, int value_regno,
2281 int insn_idx)
2282 {
2283 struct bpf_func_state *cur; /* state of the current function */
2284 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2285 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
2286 struct bpf_reg_state *reg = NULL;
2287
2288 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2289 state->acquired_refs, true);
2290 if (err)
2291 return err;
2292 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2293 * so it's aligned access and [off, off + size) are within stack limits
2294 */
2295 if (!env->allow_ptr_leaks &&
2296 state->stack[spi].slot_type[0] == STACK_SPILL &&
2297 size != BPF_REG_SIZE) {
2298 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2299 return -EACCES;
2300 }
2301
2302 cur = env->cur_state->frame[env->cur_state->curframe];
2303 if (value_regno >= 0)
2304 reg = &cur->regs[value_regno];
2305
2306 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2307 !register_is_null(reg) && env->bpf_capable) {
2308 if (dst_reg != BPF_REG_FP) {
2309 /* The backtracking logic can only recognize explicit
2310 * stack slot address like [fp - 8]. Other spill of
2311 * scalar via different register has to be conervative.
2312 * Backtrack from here and mark all registers as precise
2313 * that contributed into 'reg' being a constant.
2314 */
2315 err = mark_chain_precision(env, value_regno);
2316 if (err)
2317 return err;
2318 }
2319 save_register_state(state, spi, reg);
2320 } else if (reg && is_spillable_regtype(reg->type)) {
2321 /* register containing pointer is being spilled into stack */
2322 if (size != BPF_REG_SIZE) {
2323 verbose_linfo(env, insn_idx, "; ");
2324 verbose(env, "invalid size of register spill\n");
2325 return -EACCES;
2326 }
2327
2328 if (state != cur && reg->type == PTR_TO_STACK) {
2329 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2330 return -EINVAL;
2331 }
2332
2333 if (!env->bypass_spec_v4) {
2334 bool sanitize = false;
2335
2336 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2337 register_is_const(&state->stack[spi].spilled_ptr))
2338 sanitize = true;
2339 for (i = 0; i < BPF_REG_SIZE; i++)
2340 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2341 sanitize = true;
2342 break;
2343 }
2344 if (sanitize) {
2345 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2346 int soff = (-spi - 1) * BPF_REG_SIZE;
2347
2348 /* detected reuse of integer stack slot with a pointer
2349 * which means either llvm is reusing stack slot or
2350 * an attacker is trying to exploit CVE-2018-3639
2351 * (speculative store bypass)
2352 * Have to sanitize that slot with preemptive
2353 * store of zero.
2354 */
2355 if (*poff && *poff != soff) {
2356 /* disallow programs where single insn stores
2357 * into two different stack slots, since verifier
2358 * cannot sanitize them
2359 */
2360 verbose(env,
2361 "insn %d cannot access two stack slots fp%d and fp%d",
2362 insn_idx, *poff, soff);
2363 return -EINVAL;
2364 }
2365 *poff = soff;
2366 }
2367 }
2368 save_register_state(state, spi, reg);
2369 } else {
2370 u8 type = STACK_MISC;
2371
2372 /* regular write of data into stack destroys any spilled ptr */
2373 state->stack[spi].spilled_ptr.type = NOT_INIT;
2374 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2375 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2376 for (i = 0; i < BPF_REG_SIZE; i++)
2377 state->stack[spi].slot_type[i] = STACK_MISC;
2378
2379 /* only mark the slot as written if all 8 bytes were written
2380 * otherwise read propagation may incorrectly stop too soon
2381 * when stack slots are partially written.
2382 * This heuristic means that read propagation will be
2383 * conservative, since it will add reg_live_read marks
2384 * to stack slots all the way to first state when programs
2385 * writes+reads less than 8 bytes
2386 */
2387 if (size == BPF_REG_SIZE)
2388 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2389
2390 /* when we zero initialize stack slots mark them as such */
2391 if (reg && register_is_null(reg)) {
2392 /* backtracking doesn't work for STACK_ZERO yet. */
2393 err = mark_chain_precision(env, value_regno);
2394 if (err)
2395 return err;
2396 type = STACK_ZERO;
2397 }
2398
2399 /* Mark slots affected by this stack write. */
2400 for (i = 0; i < size; i++)
2401 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2402 type;
2403 }
2404 return 0;
2405 }
2406
2407 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2408 * known to contain a variable offset.
2409 * This function checks whether the write is permitted and conservatively
2410 * tracks the effects of the write, considering that each stack slot in the
2411 * dynamic range is potentially written to.
2412 *
2413 * 'off' includes 'regno->off'.
2414 * 'value_regno' can be -1, meaning that an unknown value is being written to
2415 * the stack.
2416 *
2417 * Spilled pointers in range are not marked as written because we don't know
2418 * what's going to be actually written. This means that read propagation for
2419 * future reads cannot be terminated by this write.
2420 *
2421 * For privileged programs, uninitialized stack slots are considered
2422 * initialized by this write (even though we don't know exactly what offsets
2423 * are going to be written to). The idea is that we don't want the verifier to
2424 * reject future reads that access slots written to through variable offsets.
2425 */
2426 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2427 /* func where register points to */
2428 struct bpf_func_state *state,
2429 int ptr_regno, int off, int size,
2430 int value_regno, int insn_idx)
2431 {
2432 struct bpf_func_state *cur; /* state of the current function */
2433 int min_off, max_off;
2434 int i, err;
2435 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2436 bool writing_zero = false;
2437 /* set if the fact that we're writing a zero is used to let any
2438 * stack slots remain STACK_ZERO
2439 */
2440 bool zero_used = false;
2441
2442 cur = env->cur_state->frame[env->cur_state->curframe];
2443 ptr_reg = &cur->regs[ptr_regno];
2444 min_off = ptr_reg->smin_value + off;
2445 max_off = ptr_reg->smax_value + off + size;
2446 if (value_regno >= 0)
2447 value_reg = &cur->regs[value_regno];
2448 if (value_reg && register_is_null(value_reg))
2449 writing_zero = true;
2450
2451 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2452 state->acquired_refs, true);
2453 if (err)
2454 return err;
2455
2456
2457 /* Variable offset writes destroy any spilled pointers in range. */
2458 for (i = min_off; i < max_off; i++) {
2459 u8 new_type, *stype;
2460 int slot, spi;
2461
2462 slot = -i - 1;
2463 spi = slot / BPF_REG_SIZE;
2464 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2465
2466 if (!env->allow_ptr_leaks
2467 && *stype != NOT_INIT
2468 && *stype != SCALAR_VALUE) {
2469 /* Reject the write if there's are spilled pointers in
2470 * range. If we didn't reject here, the ptr status
2471 * would be erased below (even though not all slots are
2472 * actually overwritten), possibly opening the door to
2473 * leaks.
2474 */
2475 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2476 insn_idx, i);
2477 return -EINVAL;
2478 }
2479
2480 /* Erase all spilled pointers. */
2481 state->stack[spi].spilled_ptr.type = NOT_INIT;
2482
2483 /* Update the slot type. */
2484 new_type = STACK_MISC;
2485 if (writing_zero && *stype == STACK_ZERO) {
2486 new_type = STACK_ZERO;
2487 zero_used = true;
2488 }
2489 /* If the slot is STACK_INVALID, we check whether it's OK to
2490 * pretend that it will be initialized by this write. The slot
2491 * might not actually be written to, and so if we mark it as
2492 * initialized future reads might leak uninitialized memory.
2493 * For privileged programs, we will accept such reads to slots
2494 * that may or may not be written because, if we're reject
2495 * them, the error would be too confusing.
2496 */
2497 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2498 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2499 insn_idx, i);
2500 return -EINVAL;
2501 }
2502 *stype = new_type;
2503 }
2504 if (zero_used) {
2505 /* backtracking doesn't work for STACK_ZERO yet. */
2506 err = mark_chain_precision(env, value_regno);
2507 if (err)
2508 return err;
2509 }
2510 return 0;
2511 }
2512
2513 /* When register 'dst_regno' is assigned some values from stack[min_off,
2514 * max_off), we set the register's type according to the types of the
2515 * respective stack slots. If all the stack values are known to be zeros, then
2516 * so is the destination reg. Otherwise, the register is considered to be
2517 * SCALAR. This function does not deal with register filling; the caller must
2518 * ensure that all spilled registers in the stack range have been marked as
2519 * read.
2520 */
2521 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2522 /* func where src register points to */
2523 struct bpf_func_state *ptr_state,
2524 int min_off, int max_off, int dst_regno)
2525 {
2526 struct bpf_verifier_state *vstate = env->cur_state;
2527 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2528 int i, slot, spi;
2529 u8 *stype;
2530 int zeros = 0;
2531
2532 for (i = min_off; i < max_off; i++) {
2533 slot = -i - 1;
2534 spi = slot / BPF_REG_SIZE;
2535 stype = ptr_state->stack[spi].slot_type;
2536 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2537 break;
2538 zeros++;
2539 }
2540 if (zeros == max_off - min_off) {
2541 /* any access_size read into register is zero extended,
2542 * so the whole register == const_zero
2543 */
2544 __mark_reg_const_zero(&state->regs[dst_regno]);
2545 /* backtracking doesn't support STACK_ZERO yet,
2546 * so mark it precise here, so that later
2547 * backtracking can stop here.
2548 * Backtracking may not need this if this register
2549 * doesn't participate in pointer adjustment.
2550 * Forward propagation of precise flag is not
2551 * necessary either. This mark is only to stop
2552 * backtracking. Any register that contributed
2553 * to const 0 was marked precise before spill.
2554 */
2555 state->regs[dst_regno].precise = true;
2556 } else {
2557 /* have read misc data from the stack */
2558 mark_reg_unknown(env, state->regs, dst_regno);
2559 }
2560 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2561 }
2562
2563 /* Read the stack at 'off' and put the results into the register indicated by
2564 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2565 * spilled reg.
2566 *
2567 * 'dst_regno' can be -1, meaning that the read value is not going to a
2568 * register.
2569 *
2570 * The access is assumed to be within the current stack bounds.
2571 */
2572 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2573 /* func where src register points to */
2574 struct bpf_func_state *reg_state,
2575 int off, int size, int dst_regno)
2576 {
2577 struct bpf_verifier_state *vstate = env->cur_state;
2578 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2579 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2580 struct bpf_reg_state *reg;
2581 u8 *stype;
2582
2583 stype = reg_state->stack[spi].slot_type;
2584 reg = &reg_state->stack[spi].spilled_ptr;
2585
2586 if (stype[0] == STACK_SPILL) {
2587 if (size != BPF_REG_SIZE) {
2588 if (reg->type != SCALAR_VALUE) {
2589 verbose_linfo(env, env->insn_idx, "; ");
2590 verbose(env, "invalid size of register fill\n");
2591 return -EACCES;
2592 }
2593 if (dst_regno >= 0) {
2594 mark_reg_unknown(env, state->regs, dst_regno);
2595 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2596 }
2597 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2598 return 0;
2599 }
2600 for (i = 1; i < BPF_REG_SIZE; i++) {
2601 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2602 verbose(env, "corrupted spill memory\n");
2603 return -EACCES;
2604 }
2605 }
2606
2607 if (dst_regno >= 0) {
2608 /* restore register state from stack */
2609 state->regs[dst_regno] = *reg;
2610 /* mark reg as written since spilled pointer state likely
2611 * has its liveness marks cleared by is_state_visited()
2612 * which resets stack/reg liveness for state transitions
2613 */
2614 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2615 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2616 /* If dst_regno==-1, the caller is asking us whether
2617 * it is acceptable to use this value as a SCALAR_VALUE
2618 * (e.g. for XADD).
2619 * We must not allow unprivileged callers to do that
2620 * with spilled pointers.
2621 */
2622 verbose(env, "leaking pointer from stack off %d\n",
2623 off);
2624 return -EACCES;
2625 }
2626 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2627 } else {
2628 u8 type;
2629
2630 for (i = 0; i < size; i++) {
2631 type = stype[(slot - i) % BPF_REG_SIZE];
2632 if (type == STACK_MISC)
2633 continue;
2634 if (type == STACK_ZERO)
2635 continue;
2636 verbose(env, "invalid read from stack off %d+%d size %d\n",
2637 off, i, size);
2638 return -EACCES;
2639 }
2640 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2641 if (dst_regno >= 0)
2642 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2643 }
2644 return 0;
2645 }
2646
2647 enum stack_access_src {
2648 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2649 ACCESS_HELPER = 2, /* the access is performed by a helper */
2650 };
2651
2652 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2653 int regno, int off, int access_size,
2654 bool zero_size_allowed,
2655 enum stack_access_src type,
2656 struct bpf_call_arg_meta *meta);
2657
2658 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2659 {
2660 return cur_regs(env) + regno;
2661 }
2662
2663 /* Read the stack at 'ptr_regno + off' and put the result into the register
2664 * 'dst_regno'.
2665 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2666 * but not its variable offset.
2667 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2668 *
2669 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2670 * filling registers (i.e. reads of spilled register cannot be detected when
2671 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2672 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2673 * offset; for a fixed offset check_stack_read_fixed_off should be used
2674 * instead.
2675 */
2676 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2677 int ptr_regno, int off, int size, int dst_regno)
2678 {
2679 /* The state of the source register. */
2680 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2681 struct bpf_func_state *ptr_state = func(env, reg);
2682 int err;
2683 int min_off, max_off;
2684
2685 /* Note that we pass a NULL meta, so raw access will not be permitted.
2686 */
2687 err = check_stack_range_initialized(env, ptr_regno, off, size,
2688 false, ACCESS_DIRECT, NULL);
2689 if (err)
2690 return err;
2691
2692 min_off = reg->smin_value + off;
2693 max_off = reg->smax_value + off;
2694 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2695 return 0;
2696 }
2697
2698 /* check_stack_read dispatches to check_stack_read_fixed_off or
2699 * check_stack_read_var_off.
2700 *
2701 * The caller must ensure that the offset falls within the allocated stack
2702 * bounds.
2703 *
2704 * 'dst_regno' is a register which will receive the value from the stack. It
2705 * can be -1, meaning that the read value is not going to a register.
2706 */
2707 static int check_stack_read(struct bpf_verifier_env *env,
2708 int ptr_regno, int off, int size,
2709 int dst_regno)
2710 {
2711 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2712 struct bpf_func_state *state = func(env, reg);
2713 int err;
2714 /* Some accesses are only permitted with a static offset. */
2715 bool var_off = !tnum_is_const(reg->var_off);
2716
2717 /* The offset is required to be static when reads don't go to a
2718 * register, in order to not leak pointers (see
2719 * check_stack_read_fixed_off).
2720 */
2721 if (dst_regno < 0 && var_off) {
2722 char tn_buf[48];
2723
2724 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2725 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2726 tn_buf, off, size);
2727 return -EACCES;
2728 }
2729 /* Variable offset is prohibited for unprivileged mode for simplicity
2730 * since it requires corresponding support in Spectre masking for stack
2731 * ALU. See also retrieve_ptr_limit().
2732 */
2733 if (!env->bypass_spec_v1 && var_off) {
2734 char tn_buf[48];
2735
2736 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2737 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2738 ptr_regno, tn_buf);
2739 return -EACCES;
2740 }
2741
2742 if (!var_off) {
2743 off += reg->var_off.value;
2744 err = check_stack_read_fixed_off(env, state, off, size,
2745 dst_regno);
2746 } else {
2747 /* Variable offset stack reads need more conservative handling
2748 * than fixed offset ones. Note that dst_regno >= 0 on this
2749 * branch.
2750 */
2751 err = check_stack_read_var_off(env, ptr_regno, off, size,
2752 dst_regno);
2753 }
2754 return err;
2755 }
2756
2757
2758 /* check_stack_write dispatches to check_stack_write_fixed_off or
2759 * check_stack_write_var_off.
2760 *
2761 * 'ptr_regno' is the register used as a pointer into the stack.
2762 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2763 * 'value_regno' is the register whose value we're writing to the stack. It can
2764 * be -1, meaning that we're not writing from a register.
2765 *
2766 * The caller must ensure that the offset falls within the maximum stack size.
2767 */
2768 static int check_stack_write(struct bpf_verifier_env *env,
2769 int ptr_regno, int off, int size,
2770 int value_regno, int insn_idx)
2771 {
2772 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2773 struct bpf_func_state *state = func(env, reg);
2774 int err;
2775
2776 if (tnum_is_const(reg->var_off)) {
2777 off += reg->var_off.value;
2778 err = check_stack_write_fixed_off(env, state, off, size,
2779 value_regno, insn_idx);
2780 } else {
2781 /* Variable offset stack reads need more conservative handling
2782 * than fixed offset ones.
2783 */
2784 err = check_stack_write_var_off(env, state,
2785 ptr_regno, off, size,
2786 value_regno, insn_idx);
2787 }
2788 return err;
2789 }
2790
2791 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2792 int off, int size, enum bpf_access_type type)
2793 {
2794 struct bpf_reg_state *regs = cur_regs(env);
2795 struct bpf_map *map = regs[regno].map_ptr;
2796 u32 cap = bpf_map_flags_to_cap(map);
2797
2798 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2799 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2800 map->value_size, off, size);
2801 return -EACCES;
2802 }
2803
2804 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2805 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2806 map->value_size, off, size);
2807 return -EACCES;
2808 }
2809
2810 return 0;
2811 }
2812
2813 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2814 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2815 int off, int size, u32 mem_size,
2816 bool zero_size_allowed)
2817 {
2818 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2819 struct bpf_reg_state *reg;
2820
2821 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2822 return 0;
2823
2824 reg = &cur_regs(env)[regno];
2825 switch (reg->type) {
2826 case PTR_TO_MAP_VALUE:
2827 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2828 mem_size, off, size);
2829 break;
2830 case PTR_TO_PACKET:
2831 case PTR_TO_PACKET_META:
2832 case PTR_TO_PACKET_END:
2833 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2834 off, size, regno, reg->id, off, mem_size);
2835 break;
2836 case PTR_TO_MEM:
2837 default:
2838 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2839 mem_size, off, size);
2840 }
2841
2842 return -EACCES;
2843 }
2844
2845 /* check read/write into a memory region with possible variable offset */
2846 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2847 int off, int size, u32 mem_size,
2848 bool zero_size_allowed)
2849 {
2850 struct bpf_verifier_state *vstate = env->cur_state;
2851 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2852 struct bpf_reg_state *reg = &state->regs[regno];
2853 int err;
2854
2855 /* We may have adjusted the register pointing to memory region, so we
2856 * need to try adding each of min_value and max_value to off
2857 * to make sure our theoretical access will be safe.
2858 */
2859 if (env->log.level & BPF_LOG_LEVEL)
2860 print_verifier_state(env, state);
2861
2862 /* The minimum value is only important with signed
2863 * comparisons where we can't assume the floor of a
2864 * value is 0. If we are using signed variables for our
2865 * index'es we need to make sure that whatever we use
2866 * will have a set floor within our range.
2867 */
2868 if (reg->smin_value < 0 &&
2869 (reg->smin_value == S64_MIN ||
2870 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2871 reg->smin_value + off < 0)) {
2872 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2873 regno);
2874 return -EACCES;
2875 }
2876 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2877 mem_size, zero_size_allowed);
2878 if (err) {
2879 verbose(env, "R%d min value is outside of the allowed memory range\n",
2880 regno);
2881 return err;
2882 }
2883
2884 /* If we haven't set a max value then we need to bail since we can't be
2885 * sure we won't do bad things.
2886 * If reg->umax_value + off could overflow, treat that as unbounded too.
2887 */
2888 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2889 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
2890 regno);
2891 return -EACCES;
2892 }
2893 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2894 mem_size, zero_size_allowed);
2895 if (err) {
2896 verbose(env, "R%d max value is outside of the allowed memory range\n",
2897 regno);
2898 return err;
2899 }
2900
2901 return 0;
2902 }
2903
2904 /* check read/write into a map element with possible variable offset */
2905 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2906 int off, int size, bool zero_size_allowed)
2907 {
2908 struct bpf_verifier_state *vstate = env->cur_state;
2909 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2910 struct bpf_reg_state *reg = &state->regs[regno];
2911 struct bpf_map *map = reg->map_ptr;
2912 int err;
2913
2914 err = check_mem_region_access(env, regno, off, size, map->value_size,
2915 zero_size_allowed);
2916 if (err)
2917 return err;
2918
2919 if (map_value_has_spin_lock(map)) {
2920 u32 lock = map->spin_lock_off;
2921
2922 /* if any part of struct bpf_spin_lock can be touched by
2923 * load/store reject this program.
2924 * To check that [x1, x2) overlaps with [y1, y2)
2925 * it is sufficient to check x1 < y2 && y1 < x2.
2926 */
2927 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2928 lock < reg->umax_value + off + size) {
2929 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2930 return -EACCES;
2931 }
2932 }
2933 return err;
2934 }
2935
2936 #define MAX_PACKET_OFF 0xffff
2937
2938 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2939 {
2940 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
2941 }
2942
2943 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2944 const struct bpf_call_arg_meta *meta,
2945 enum bpf_access_type t)
2946 {
2947 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2948
2949 switch (prog_type) {
2950 /* Program types only with direct read access go here! */
2951 case BPF_PROG_TYPE_LWT_IN:
2952 case BPF_PROG_TYPE_LWT_OUT:
2953 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2954 case BPF_PROG_TYPE_SK_REUSEPORT:
2955 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2956 case BPF_PROG_TYPE_CGROUP_SKB:
2957 if (t == BPF_WRITE)
2958 return false;
2959 fallthrough;
2960
2961 /* Program types with direct read + write access go here! */
2962 case BPF_PROG_TYPE_SCHED_CLS:
2963 case BPF_PROG_TYPE_SCHED_ACT:
2964 case BPF_PROG_TYPE_XDP:
2965 case BPF_PROG_TYPE_LWT_XMIT:
2966 case BPF_PROG_TYPE_SK_SKB:
2967 case BPF_PROG_TYPE_SK_MSG:
2968 if (meta)
2969 return meta->pkt_access;
2970
2971 env->seen_direct_write = true;
2972 return true;
2973
2974 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2975 if (t == BPF_WRITE)
2976 env->seen_direct_write = true;
2977
2978 return true;
2979
2980 default:
2981 return false;
2982 }
2983 }
2984
2985 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2986 int size, bool zero_size_allowed)
2987 {
2988 struct bpf_reg_state *regs = cur_regs(env);
2989 struct bpf_reg_state *reg = &regs[regno];
2990 int err;
2991
2992 /* We may have added a variable offset to the packet pointer; but any
2993 * reg->range we have comes after that. We are only checking the fixed
2994 * offset.
2995 */
2996
2997 /* We don't allow negative numbers, because we aren't tracking enough
2998 * detail to prove they're safe.
2999 */
3000 if (reg->smin_value < 0) {
3001 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3002 regno);
3003 return -EACCES;
3004 }
3005
3006 err = reg->range < 0 ? -EINVAL :
3007 __check_mem_access(env, regno, off, size, reg->range,
3008 zero_size_allowed);
3009 if (err) {
3010 verbose(env, "R%d offset is outside of the packet\n", regno);
3011 return err;
3012 }
3013
3014 /* __check_mem_access has made sure "off + size - 1" is within u16.
3015 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3016 * otherwise find_good_pkt_pointers would have refused to set range info
3017 * that __check_mem_access would have rejected this pkt access.
3018 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3019 */
3020 env->prog->aux->max_pkt_offset =
3021 max_t(u32, env->prog->aux->max_pkt_offset,
3022 off + reg->umax_value + size - 1);
3023
3024 return err;
3025 }
3026
3027 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
3028 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3029 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3030 struct btf **btf, u32 *btf_id)
3031 {
3032 struct bpf_insn_access_aux info = {
3033 .reg_type = *reg_type,
3034 .log = &env->log,
3035 };
3036
3037 if (env->ops->is_valid_access &&
3038 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3039 /* A non zero info.ctx_field_size indicates that this field is a
3040 * candidate for later verifier transformation to load the whole
3041 * field and then apply a mask when accessed with a narrower
3042 * access than actual ctx access size. A zero info.ctx_field_size
3043 * will only allow for whole field access and rejects any other
3044 * type of narrower access.
3045 */
3046 *reg_type = info.reg_type;
3047
3048 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3049 *btf = info.btf;
3050 *btf_id = info.btf_id;
3051 } else {
3052 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3053 }
3054 /* remember the offset of last byte accessed in ctx */
3055 if (env->prog->aux->max_ctx_offset < off + size)
3056 env->prog->aux->max_ctx_offset = off + size;
3057 return 0;
3058 }
3059
3060 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3061 return -EACCES;
3062 }
3063
3064 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3065 int size)
3066 {
3067 if (size < 0 || off < 0 ||
3068 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3069 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3070 off, size);
3071 return -EACCES;
3072 }
3073 return 0;
3074 }
3075
3076 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3077 u32 regno, int off, int size,
3078 enum bpf_access_type t)
3079 {
3080 struct bpf_reg_state *regs = cur_regs(env);
3081 struct bpf_reg_state *reg = &regs[regno];
3082 struct bpf_insn_access_aux info = {};
3083 bool valid;
3084
3085 if (reg->smin_value < 0) {
3086 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3087 regno);
3088 return -EACCES;
3089 }
3090
3091 switch (reg->type) {
3092 case PTR_TO_SOCK_COMMON:
3093 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3094 break;
3095 case PTR_TO_SOCKET:
3096 valid = bpf_sock_is_valid_access(off, size, t, &info);
3097 break;
3098 case PTR_TO_TCP_SOCK:
3099 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3100 break;
3101 case PTR_TO_XDP_SOCK:
3102 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3103 break;
3104 default:
3105 valid = false;
3106 }
3107
3108
3109 if (valid) {
3110 env->insn_aux_data[insn_idx].ctx_field_size =
3111 info.ctx_field_size;
3112 return 0;
3113 }
3114
3115 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3116 regno, reg_type_str[reg->type], off, size);
3117
3118 return -EACCES;
3119 }
3120
3121 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3122 {
3123 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3124 }
3125
3126 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3127 {
3128 const struct bpf_reg_state *reg = reg_state(env, regno);
3129
3130 return reg->type == PTR_TO_CTX;
3131 }
3132
3133 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3134 {
3135 const struct bpf_reg_state *reg = reg_state(env, regno);
3136
3137 return type_is_sk_pointer(reg->type);
3138 }
3139
3140 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3141 {
3142 const struct bpf_reg_state *reg = reg_state(env, regno);
3143
3144 return type_is_pkt_pointer(reg->type);
3145 }
3146
3147 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3148 {
3149 const struct bpf_reg_state *reg = reg_state(env, regno);
3150
3151 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3152 return reg->type == PTR_TO_FLOW_KEYS;
3153 }
3154
3155 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3156 const struct bpf_reg_state *reg,
3157 int off, int size, bool strict)
3158 {
3159 struct tnum reg_off;
3160 int ip_align;
3161
3162 /* Byte size accesses are always allowed. */
3163 if (!strict || size == 1)
3164 return 0;
3165
3166 /* For platforms that do not have a Kconfig enabling
3167 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3168 * NET_IP_ALIGN is universally set to '2'. And on platforms
3169 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3170 * to this code only in strict mode where we want to emulate
3171 * the NET_IP_ALIGN==2 checking. Therefore use an
3172 * unconditional IP align value of '2'.
3173 */
3174 ip_align = 2;
3175
3176 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3177 if (!tnum_is_aligned(reg_off, size)) {
3178 char tn_buf[48];
3179
3180 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3181 verbose(env,
3182 "misaligned packet access off %d+%s+%d+%d size %d\n",
3183 ip_align, tn_buf, reg->off, off, size);
3184 return -EACCES;
3185 }
3186
3187 return 0;
3188 }
3189
3190 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3191 const struct bpf_reg_state *reg,
3192 const char *pointer_desc,
3193 int off, int size, bool strict)
3194 {
3195 struct tnum reg_off;
3196
3197 /* Byte size accesses are always allowed. */
3198 if (!strict || size == 1)
3199 return 0;
3200
3201 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3202 if (!tnum_is_aligned(reg_off, size)) {
3203 char tn_buf[48];
3204
3205 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3206 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3207 pointer_desc, tn_buf, reg->off, off, size);
3208 return -EACCES;
3209 }
3210
3211 return 0;
3212 }
3213
3214 static int check_ptr_alignment(struct bpf_verifier_env *env,
3215 const struct bpf_reg_state *reg, int off,
3216 int size, bool strict_alignment_once)
3217 {
3218 bool strict = env->strict_alignment || strict_alignment_once;
3219 const char *pointer_desc = "";
3220
3221 switch (reg->type) {
3222 case PTR_TO_PACKET:
3223 case PTR_TO_PACKET_META:
3224 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3225 * right in front, treat it the very same way.
3226 */
3227 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3228 case PTR_TO_FLOW_KEYS:
3229 pointer_desc = "flow keys ";
3230 break;
3231 case PTR_TO_MAP_VALUE:
3232 pointer_desc = "value ";
3233 break;
3234 case PTR_TO_CTX:
3235 pointer_desc = "context ";
3236 break;
3237 case PTR_TO_STACK:
3238 pointer_desc = "stack ";
3239 /* The stack spill tracking logic in check_stack_write_fixed_off()
3240 * and check_stack_read_fixed_off() relies on stack accesses being
3241 * aligned.
3242 */
3243 strict = true;
3244 break;
3245 case PTR_TO_SOCKET:
3246 pointer_desc = "sock ";
3247 break;
3248 case PTR_TO_SOCK_COMMON:
3249 pointer_desc = "sock_common ";
3250 break;
3251 case PTR_TO_TCP_SOCK:
3252 pointer_desc = "tcp_sock ";
3253 break;
3254 case PTR_TO_XDP_SOCK:
3255 pointer_desc = "xdp_sock ";
3256 break;
3257 default:
3258 break;
3259 }
3260 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3261 strict);
3262 }
3263
3264 static int update_stack_depth(struct bpf_verifier_env *env,
3265 const struct bpf_func_state *func,
3266 int off)
3267 {
3268 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3269
3270 if (stack >= -off)
3271 return 0;
3272
3273 /* update known max for given subprogram */
3274 env->subprog_info[func->subprogno].stack_depth = -off;
3275 return 0;
3276 }
3277
3278 /* starting from main bpf function walk all instructions of the function
3279 * and recursively walk all callees that given function can call.
3280 * Ignore jump and exit insns.
3281 * Since recursion is prevented by check_cfg() this algorithm
3282 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3283 */
3284 static int check_max_stack_depth(struct bpf_verifier_env *env)
3285 {
3286 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3287 struct bpf_subprog_info *subprog = env->subprog_info;
3288 struct bpf_insn *insn = env->prog->insnsi;
3289 bool tail_call_reachable = false;
3290 int ret_insn[MAX_CALL_FRAMES];
3291 int ret_prog[MAX_CALL_FRAMES];
3292 int j;
3293
3294 process_func:
3295 /* protect against potential stack overflow that might happen when
3296 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3297 * depth for such case down to 256 so that the worst case scenario
3298 * would result in 8k stack size (32 which is tailcall limit * 256 =
3299 * 8k).
3300 *
3301 * To get the idea what might happen, see an example:
3302 * func1 -> sub rsp, 128
3303 * subfunc1 -> sub rsp, 256
3304 * tailcall1 -> add rsp, 256
3305 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3306 * subfunc2 -> sub rsp, 64
3307 * subfunc22 -> sub rsp, 128
3308 * tailcall2 -> add rsp, 128
3309 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3310 *
3311 * tailcall will unwind the current stack frame but it will not get rid
3312 * of caller's stack as shown on the example above.
3313 */
3314 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3315 verbose(env,
3316 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3317 depth);
3318 return -EACCES;
3319 }
3320 /* round up to 32-bytes, since this is granularity
3321 * of interpreter stack size
3322 */
3323 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3324 if (depth > MAX_BPF_STACK) {
3325 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3326 frame + 1, depth);
3327 return -EACCES;
3328 }
3329 continue_func:
3330 subprog_end = subprog[idx + 1].start;
3331 for (; i < subprog_end; i++) {
3332 if (insn[i].code != (BPF_JMP | BPF_CALL))
3333 continue;
3334 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3335 continue;
3336 /* remember insn and function to return to */
3337 ret_insn[frame] = i + 1;
3338 ret_prog[frame] = idx;
3339
3340 /* find the callee */
3341 i = i + insn[i].imm + 1;
3342 idx = find_subprog(env, i);
3343 if (idx < 0) {
3344 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3345 i);
3346 return -EFAULT;
3347 }
3348
3349 if (subprog[idx].has_tail_call)
3350 tail_call_reachable = true;
3351
3352 frame++;
3353 if (frame >= MAX_CALL_FRAMES) {
3354 verbose(env, "the call stack of %d frames is too deep !\n",
3355 frame);
3356 return -E2BIG;
3357 }
3358 goto process_func;
3359 }
3360 /* if tail call got detected across bpf2bpf calls then mark each of the
3361 * currently present subprog frames as tail call reachable subprogs;
3362 * this info will be utilized by JIT so that we will be preserving the
3363 * tail call counter throughout bpf2bpf calls combined with tailcalls
3364 */
3365 if (tail_call_reachable)
3366 for (j = 0; j < frame; j++)
3367 subprog[ret_prog[j]].tail_call_reachable = true;
3368
3369 /* end of for() loop means the last insn of the 'subprog'
3370 * was reached. Doesn't matter whether it was JA or EXIT
3371 */
3372 if (frame == 0)
3373 return 0;
3374 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3375 frame--;
3376 i = ret_insn[frame];
3377 idx = ret_prog[frame];
3378 goto continue_func;
3379 }
3380
3381 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3382 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3383 const struct bpf_insn *insn, int idx)
3384 {
3385 int start = idx + insn->imm + 1, subprog;
3386
3387 subprog = find_subprog(env, start);
3388 if (subprog < 0) {
3389 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3390 start);
3391 return -EFAULT;
3392 }
3393 return env->subprog_info[subprog].stack_depth;
3394 }
3395 #endif
3396
3397 int check_ctx_reg(struct bpf_verifier_env *env,
3398 const struct bpf_reg_state *reg, int regno)
3399 {
3400 /* Access to ctx or passing it to a helper is only allowed in
3401 * its original, unmodified form.
3402 */
3403
3404 if (reg->off) {
3405 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3406 regno, reg->off);
3407 return -EACCES;
3408 }
3409
3410 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3411 char tn_buf[48];
3412
3413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3414 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3415 return -EACCES;
3416 }
3417
3418 return 0;
3419 }
3420
3421 static int __check_buffer_access(struct bpf_verifier_env *env,
3422 const char *buf_info,
3423 const struct bpf_reg_state *reg,
3424 int regno, int off, int size)
3425 {
3426 if (off < 0) {
3427 verbose(env,
3428 "R%d invalid %s buffer access: off=%d, size=%d\n",
3429 regno, buf_info, off, size);
3430 return -EACCES;
3431 }
3432 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3433 char tn_buf[48];
3434
3435 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3436 verbose(env,
3437 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3438 regno, off, tn_buf);
3439 return -EACCES;
3440 }
3441
3442 return 0;
3443 }
3444
3445 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3446 const struct bpf_reg_state *reg,
3447 int regno, int off, int size)
3448 {
3449 int err;
3450
3451 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3452 if (err)
3453 return err;
3454
3455 if (off + size > env->prog->aux->max_tp_access)
3456 env->prog->aux->max_tp_access = off + size;
3457
3458 return 0;
3459 }
3460
3461 static int check_buffer_access(struct bpf_verifier_env *env,
3462 const struct bpf_reg_state *reg,
3463 int regno, int off, int size,
3464 bool zero_size_allowed,
3465 const char *buf_info,
3466 u32 *max_access)
3467 {
3468 int err;
3469
3470 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3471 if (err)
3472 return err;
3473
3474 if (off + size > *max_access)
3475 *max_access = off + size;
3476
3477 return 0;
3478 }
3479
3480 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
3481 static void zext_32_to_64(struct bpf_reg_state *reg)
3482 {
3483 reg->var_off = tnum_subreg(reg->var_off);
3484 __reg_assign_32_into_64(reg);
3485 }
3486
3487 /* truncate register to smaller size (in bytes)
3488 * must be called with size < BPF_REG_SIZE
3489 */
3490 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3491 {
3492 u64 mask;
3493
3494 /* clear high bits in bit representation */
3495 reg->var_off = tnum_cast(reg->var_off, size);
3496
3497 /* fix arithmetic bounds */
3498 mask = ((u64)1 << (size * 8)) - 1;
3499 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3500 reg->umin_value &= mask;
3501 reg->umax_value &= mask;
3502 } else {
3503 reg->umin_value = 0;
3504 reg->umax_value = mask;
3505 }
3506 reg->smin_value = reg->umin_value;
3507 reg->smax_value = reg->umax_value;
3508
3509 /* If size is smaller than 32bit register the 32bit register
3510 * values are also truncated so we push 64-bit bounds into
3511 * 32-bit bounds. Above were truncated < 32-bits already.
3512 */
3513 if (size >= 4)
3514 return;
3515 __reg_combine_64_into_32(reg);
3516 }
3517
3518 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3519 {
3520 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3521 }
3522
3523 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3524 {
3525 void *ptr;
3526 u64 addr;
3527 int err;
3528
3529 err = map->ops->map_direct_value_addr(map, &addr, off);
3530 if (err)
3531 return err;
3532 ptr = (void *)(long)addr + off;
3533
3534 switch (size) {
3535 case sizeof(u8):
3536 *val = (u64)*(u8 *)ptr;
3537 break;
3538 case sizeof(u16):
3539 *val = (u64)*(u16 *)ptr;
3540 break;
3541 case sizeof(u32):
3542 *val = (u64)*(u32 *)ptr;
3543 break;
3544 case sizeof(u64):
3545 *val = *(u64 *)ptr;
3546 break;
3547 default:
3548 return -EINVAL;
3549 }
3550 return 0;
3551 }
3552
3553 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3554 struct bpf_reg_state *regs,
3555 int regno, int off, int size,
3556 enum bpf_access_type atype,
3557 int value_regno)
3558 {
3559 struct bpf_reg_state *reg = regs + regno;
3560 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3561 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
3562 u32 btf_id;
3563 int ret;
3564
3565 if (off < 0) {
3566 verbose(env,
3567 "R%d is ptr_%s invalid negative access: off=%d\n",
3568 regno, tname, off);
3569 return -EACCES;
3570 }
3571 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3572 char tn_buf[48];
3573
3574 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3575 verbose(env,
3576 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3577 regno, tname, off, tn_buf);
3578 return -EACCES;
3579 }
3580
3581 if (env->ops->btf_struct_access) {
3582 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3583 off, size, atype, &btf_id);
3584 } else {
3585 if (atype != BPF_READ) {
3586 verbose(env, "only read is supported\n");
3587 return -EACCES;
3588 }
3589
3590 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3591 atype, &btf_id);
3592 }
3593
3594 if (ret < 0)
3595 return ret;
3596
3597 if (atype == BPF_READ && value_regno >= 0)
3598 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
3599
3600 return 0;
3601 }
3602
3603 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3604 struct bpf_reg_state *regs,
3605 int regno, int off, int size,
3606 enum bpf_access_type atype,
3607 int value_regno)
3608 {
3609 struct bpf_reg_state *reg = regs + regno;
3610 struct bpf_map *map = reg->map_ptr;
3611 const struct btf_type *t;
3612 const char *tname;
3613 u32 btf_id;
3614 int ret;
3615
3616 if (!btf_vmlinux) {
3617 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3618 return -ENOTSUPP;
3619 }
3620
3621 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3622 verbose(env, "map_ptr access not supported for map type %d\n",
3623 map->map_type);
3624 return -ENOTSUPP;
3625 }
3626
3627 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3628 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3629
3630 if (!env->allow_ptr_to_map_access) {
3631 verbose(env,
3632 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3633 tname);
3634 return -EPERM;
3635 }
3636
3637 if (off < 0) {
3638 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3639 regno, tname, off);
3640 return -EACCES;
3641 }
3642
3643 if (atype != BPF_READ) {
3644 verbose(env, "only read from %s is supported\n", tname);
3645 return -EACCES;
3646 }
3647
3648 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
3649 if (ret < 0)
3650 return ret;
3651
3652 if (value_regno >= 0)
3653 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
3654
3655 return 0;
3656 }
3657
3658 /* Check that the stack access at the given offset is within bounds. The
3659 * maximum valid offset is -1.
3660 *
3661 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3662 * -state->allocated_stack for reads.
3663 */
3664 static int check_stack_slot_within_bounds(int off,
3665 struct bpf_func_state *state,
3666 enum bpf_access_type t)
3667 {
3668 int min_valid_off;
3669
3670 if (t == BPF_WRITE)
3671 min_valid_off = -MAX_BPF_STACK;
3672 else
3673 min_valid_off = -state->allocated_stack;
3674
3675 if (off < min_valid_off || off > -1)
3676 return -EACCES;
3677 return 0;
3678 }
3679
3680 /* Check that the stack access at 'regno + off' falls within the maximum stack
3681 * bounds.
3682 *
3683 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3684 */
3685 static int check_stack_access_within_bounds(
3686 struct bpf_verifier_env *env,
3687 int regno, int off, int access_size,
3688 enum stack_access_src src, enum bpf_access_type type)
3689 {
3690 struct bpf_reg_state *regs = cur_regs(env);
3691 struct bpf_reg_state *reg = regs + regno;
3692 struct bpf_func_state *state = func(env, reg);
3693 int min_off, max_off;
3694 int err;
3695 char *err_extra;
3696
3697 if (src == ACCESS_HELPER)
3698 /* We don't know if helpers are reading or writing (or both). */
3699 err_extra = " indirect access to";
3700 else if (type == BPF_READ)
3701 err_extra = " read from";
3702 else
3703 err_extra = " write to";
3704
3705 if (tnum_is_const(reg->var_off)) {
3706 min_off = reg->var_off.value + off;
3707 if (access_size > 0)
3708 max_off = min_off + access_size - 1;
3709 else
3710 max_off = min_off;
3711 } else {
3712 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3713 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3714 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3715 err_extra, regno);
3716 return -EACCES;
3717 }
3718 min_off = reg->smin_value + off;
3719 if (access_size > 0)
3720 max_off = reg->smax_value + off + access_size - 1;
3721 else
3722 max_off = min_off;
3723 }
3724
3725 err = check_stack_slot_within_bounds(min_off, state, type);
3726 if (!err)
3727 err = check_stack_slot_within_bounds(max_off, state, type);
3728
3729 if (err) {
3730 if (tnum_is_const(reg->var_off)) {
3731 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3732 err_extra, regno, off, access_size);
3733 } else {
3734 char tn_buf[48];
3735
3736 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3737 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3738 err_extra, regno, tn_buf, access_size);
3739 }
3740 }
3741 return err;
3742 }
3743
3744 /* check whether memory at (regno + off) is accessible for t = (read | write)
3745 * if t==write, value_regno is a register which value is stored into memory
3746 * if t==read, value_regno is a register which will receive the value from memory
3747 * if t==write && value_regno==-1, some unknown value is stored into memory
3748 * if t==read && value_regno==-1, don't care what we read from memory
3749 */
3750 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3751 int off, int bpf_size, enum bpf_access_type t,
3752 int value_regno, bool strict_alignment_once)
3753 {
3754 struct bpf_reg_state *regs = cur_regs(env);
3755 struct bpf_reg_state *reg = regs + regno;
3756 struct bpf_func_state *state;
3757 int size, err = 0;
3758
3759 size = bpf_size_to_bytes(bpf_size);
3760 if (size < 0)
3761 return size;
3762
3763 /* alignment checks will add in reg->off themselves */
3764 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3765 if (err)
3766 return err;
3767
3768 /* for access checks, reg->off is just part of off */
3769 off += reg->off;
3770
3771 if (reg->type == PTR_TO_MAP_VALUE) {
3772 if (t == BPF_WRITE && value_regno >= 0 &&
3773 is_pointer_value(env, value_regno)) {
3774 verbose(env, "R%d leaks addr into map\n", value_regno);
3775 return -EACCES;
3776 }
3777 err = check_map_access_type(env, regno, off, size, t);
3778 if (err)
3779 return err;
3780 err = check_map_access(env, regno, off, size, false);
3781 if (!err && t == BPF_READ && value_regno >= 0) {
3782 struct bpf_map *map = reg->map_ptr;
3783
3784 /* if map is read-only, track its contents as scalars */
3785 if (tnum_is_const(reg->var_off) &&
3786 bpf_map_is_rdonly(map) &&
3787 map->ops->map_direct_value_addr) {
3788 int map_off = off + reg->var_off.value;
3789 u64 val = 0;
3790
3791 err = bpf_map_direct_read(map, map_off, size,
3792 &val);
3793 if (err)
3794 return err;
3795
3796 regs[value_regno].type = SCALAR_VALUE;
3797 __mark_reg_known(&regs[value_regno], val);
3798 } else {
3799 mark_reg_unknown(env, regs, value_regno);
3800 }
3801 }
3802 } else if (reg->type == PTR_TO_MEM) {
3803 if (t == BPF_WRITE && value_regno >= 0 &&
3804 is_pointer_value(env, value_regno)) {
3805 verbose(env, "R%d leaks addr into mem\n", value_regno);
3806 return -EACCES;
3807 }
3808 err = check_mem_region_access(env, regno, off, size,
3809 reg->mem_size, false);
3810 if (!err && t == BPF_READ && value_regno >= 0)
3811 mark_reg_unknown(env, regs, value_regno);
3812 } else if (reg->type == PTR_TO_CTX) {
3813 enum bpf_reg_type reg_type = SCALAR_VALUE;
3814 struct btf *btf = NULL;
3815 u32 btf_id = 0;
3816
3817 if (t == BPF_WRITE && value_regno >= 0 &&
3818 is_pointer_value(env, value_regno)) {
3819 verbose(env, "R%d leaks addr into ctx\n", value_regno);
3820 return -EACCES;
3821 }
3822
3823 err = check_ctx_reg(env, reg, regno);
3824 if (err < 0)
3825 return err;
3826
3827 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
3828 if (err)
3829 verbose_linfo(env, insn_idx, "; ");
3830 if (!err && t == BPF_READ && value_regno >= 0) {
3831 /* ctx access returns either a scalar, or a
3832 * PTR_TO_PACKET[_META,_END]. In the latter
3833 * case, we know the offset is zero.
3834 */
3835 if (reg_type == SCALAR_VALUE) {
3836 mark_reg_unknown(env, regs, value_regno);
3837 } else {
3838 mark_reg_known_zero(env, regs,
3839 value_regno);
3840 if (reg_type_may_be_null(reg_type))
3841 regs[value_regno].id = ++env->id_gen;
3842 /* A load of ctx field could have different
3843 * actual load size with the one encoded in the
3844 * insn. When the dst is PTR, it is for sure not
3845 * a sub-register.
3846 */
3847 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
3848 if (reg_type == PTR_TO_BTF_ID ||
3849 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3850 regs[value_regno].btf = btf;
3851 regs[value_regno].btf_id = btf_id;
3852 }
3853 }
3854 regs[value_regno].type = reg_type;
3855 }
3856
3857 } else if (reg->type == PTR_TO_STACK) {
3858 /* Basic bounds checks. */
3859 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
3860 if (err)
3861 return err;
3862
3863 state = func(env, reg);
3864 err = update_stack_depth(env, state, off);
3865 if (err)
3866 return err;
3867
3868 if (t == BPF_READ)
3869 err = check_stack_read(env, regno, off, size,
3870 value_regno);
3871 else
3872 err = check_stack_write(env, regno, off, size,
3873 value_regno, insn_idx);
3874 } else if (reg_is_pkt_pointer(reg)) {
3875 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
3876 verbose(env, "cannot write into packet\n");
3877 return -EACCES;
3878 }
3879 if (t == BPF_WRITE && value_regno >= 0 &&
3880 is_pointer_value(env, value_regno)) {
3881 verbose(env, "R%d leaks addr into packet\n",
3882 value_regno);
3883 return -EACCES;
3884 }
3885 err = check_packet_access(env, regno, off, size, false);
3886 if (!err && t == BPF_READ && value_regno >= 0)
3887 mark_reg_unknown(env, regs, value_regno);
3888 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3889 if (t == BPF_WRITE && value_regno >= 0 &&
3890 is_pointer_value(env, value_regno)) {
3891 verbose(env, "R%d leaks addr into flow keys\n",
3892 value_regno);
3893 return -EACCES;
3894 }
3895
3896 err = check_flow_keys_access(env, off, size);
3897 if (!err && t == BPF_READ && value_regno >= 0)
3898 mark_reg_unknown(env, regs, value_regno);
3899 } else if (type_is_sk_pointer(reg->type)) {
3900 if (t == BPF_WRITE) {
3901 verbose(env, "R%d cannot write into %s\n",
3902 regno, reg_type_str[reg->type]);
3903 return -EACCES;
3904 }
3905 err = check_sock_access(env, insn_idx, regno, off, size, t);
3906 if (!err && value_regno >= 0)
3907 mark_reg_unknown(env, regs, value_regno);
3908 } else if (reg->type == PTR_TO_TP_BUFFER) {
3909 err = check_tp_buffer_access(env, reg, regno, off, size);
3910 if (!err && t == BPF_READ && value_regno >= 0)
3911 mark_reg_unknown(env, regs, value_regno);
3912 } else if (reg->type == PTR_TO_BTF_ID) {
3913 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3914 value_regno);
3915 } else if (reg->type == CONST_PTR_TO_MAP) {
3916 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3917 value_regno);
3918 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3919 if (t == BPF_WRITE) {
3920 verbose(env, "R%d cannot write into %s\n",
3921 regno, reg_type_str[reg->type]);
3922 return -EACCES;
3923 }
3924 err = check_buffer_access(env, reg, regno, off, size, false,
3925 "rdonly",
3926 &env->prog->aux->max_rdonly_access);
3927 if (!err && value_regno >= 0)
3928 mark_reg_unknown(env, regs, value_regno);
3929 } else if (reg->type == PTR_TO_RDWR_BUF) {
3930 err = check_buffer_access(env, reg, regno, off, size, false,
3931 "rdwr",
3932 &env->prog->aux->max_rdwr_access);
3933 if (!err && t == BPF_READ && value_regno >= 0)
3934 mark_reg_unknown(env, regs, value_regno);
3935 } else {
3936 verbose(env, "R%d invalid mem access '%s'\n", regno,
3937 reg_type_str[reg->type]);
3938 return -EACCES;
3939 }
3940
3941 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
3942 regs[value_regno].type == SCALAR_VALUE) {
3943 /* b/h/w load zero-extends, mark upper bits as known 0 */
3944 coerce_reg_to_size(&regs[value_regno], size);
3945 }
3946 return err;
3947 }
3948
3949 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
3950 {
3951 int err;
3952
3953 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
3954 insn->imm != 0) {
3955 verbose(env, "BPF_XADD uses reserved fields\n");
3956 return -EINVAL;
3957 }
3958
3959 /* check src1 operand */
3960 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3961 if (err)
3962 return err;
3963
3964 /* check src2 operand */
3965 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3966 if (err)
3967 return err;
3968
3969 if (is_pointer_value(env, insn->src_reg)) {
3970 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
3971 return -EACCES;
3972 }
3973
3974 if (is_ctx_reg(env, insn->dst_reg) ||
3975 is_pkt_reg(env, insn->dst_reg) ||
3976 is_flow_key_reg(env, insn->dst_reg) ||
3977 is_sk_reg(env, insn->dst_reg)) {
3978 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3979 insn->dst_reg,
3980 reg_type_str[reg_state(env, insn->dst_reg)->type]);
3981 return -EACCES;
3982 }
3983
3984 /* check whether atomic_add can read the memory */
3985 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3986 BPF_SIZE(insn->code), BPF_READ, -1, true);
3987 if (err)
3988 return err;
3989
3990 /* check whether atomic_add can write into the same memory */
3991 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3992 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3993 }
3994
3995 /* When register 'regno' is used to read the stack (either directly or through
3996 * a helper function) make sure that it's within stack boundary and, depending
3997 * on the access type, that all elements of the stack are initialized.
3998 *
3999 * 'off' includes 'regno->off', but not its dynamic part (if any).
4000 *
4001 * All registers that have been spilled on the stack in the slots within the
4002 * read offsets are marked as read.
4003 */
4004 static int check_stack_range_initialized(
4005 struct bpf_verifier_env *env, int regno, int off,
4006 int access_size, bool zero_size_allowed,
4007 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4008 {
4009 struct bpf_reg_state *reg = reg_state(env, regno);
4010 struct bpf_func_state *state = func(env, reg);
4011 int err, min_off, max_off, i, j, slot, spi;
4012 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4013 enum bpf_access_type bounds_check_type;
4014 /* Some accesses can write anything into the stack, others are
4015 * read-only.
4016 */
4017 bool clobber = false;
4018
4019 if (access_size == 0 && !zero_size_allowed) {
4020 verbose(env, "invalid zero-sized read\n");
4021 return -EACCES;
4022 }
4023
4024 if (type == ACCESS_HELPER) {
4025 /* The bounds checks for writes are more permissive than for
4026 * reads. However, if raw_mode is not set, we'll do extra
4027 * checks below.
4028 */
4029 bounds_check_type = BPF_WRITE;
4030 clobber = true;
4031 } else {
4032 bounds_check_type = BPF_READ;
4033 }
4034 err = check_stack_access_within_bounds(env, regno, off, access_size,
4035 type, bounds_check_type);
4036 if (err)
4037 return err;
4038
4039
4040 if (tnum_is_const(reg->var_off)) {
4041 min_off = max_off = reg->var_off.value + off;
4042 } else {
4043 /* Variable offset is prohibited for unprivileged mode for
4044 * simplicity since it requires corresponding support in
4045 * Spectre masking for stack ALU.
4046 * See also retrieve_ptr_limit().
4047 */
4048 if (!env->bypass_spec_v1) {
4049 char tn_buf[48];
4050
4051 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4052 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4053 regno, err_extra, tn_buf);
4054 return -EACCES;
4055 }
4056 /* Only initialized buffer on stack is allowed to be accessed
4057 * with variable offset. With uninitialized buffer it's hard to
4058 * guarantee that whole memory is marked as initialized on
4059 * helper return since specific bounds are unknown what may
4060 * cause uninitialized stack leaking.
4061 */
4062 if (meta && meta->raw_mode)
4063 meta = NULL;
4064
4065 min_off = reg->smin_value + off;
4066 max_off = reg->smax_value + off;
4067 }
4068
4069 if (meta && meta->raw_mode) {
4070 meta->access_size = access_size;
4071 meta->regno = regno;
4072 return 0;
4073 }
4074
4075 for (i = min_off; i < max_off + access_size; i++) {
4076 u8 *stype;
4077
4078 slot = -i - 1;
4079 spi = slot / BPF_REG_SIZE;
4080 if (state->allocated_stack <= slot)
4081 goto err;
4082 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4083 if (*stype == STACK_MISC)
4084 goto mark;
4085 if (*stype == STACK_ZERO) {
4086 if (clobber) {
4087 /* helper can write anything into the stack */
4088 *stype = STACK_MISC;
4089 }
4090 goto mark;
4091 }
4092
4093 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4094 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4095 goto mark;
4096
4097 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4098 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4099 env->allow_ptr_leaks)) {
4100 if (clobber) {
4101 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4102 for (j = 0; j < BPF_REG_SIZE; j++)
4103 state->stack[spi].slot_type[j] = STACK_MISC;
4104 }
4105 goto mark;
4106 }
4107
4108 err:
4109 if (tnum_is_const(reg->var_off)) {
4110 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4111 err_extra, regno, min_off, i - min_off, access_size);
4112 } else {
4113 char tn_buf[48];
4114
4115 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4116 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4117 err_extra, regno, tn_buf, i - min_off, access_size);
4118 }
4119 return -EACCES;
4120 mark:
4121 /* reading any byte out of 8-byte 'spill_slot' will cause
4122 * the whole slot to be marked as 'read'
4123 */
4124 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4125 state->stack[spi].spilled_ptr.parent,
4126 REG_LIVE_READ64);
4127 }
4128 return update_stack_depth(env, state, min_off);
4129 }
4130
4131 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4132 int access_size, bool zero_size_allowed,
4133 struct bpf_call_arg_meta *meta)
4134 {
4135 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4136
4137 switch (reg->type) {
4138 case PTR_TO_PACKET:
4139 case PTR_TO_PACKET_META:
4140 return check_packet_access(env, regno, reg->off, access_size,
4141 zero_size_allowed);
4142 case PTR_TO_MAP_VALUE:
4143 if (check_map_access_type(env, regno, reg->off, access_size,
4144 meta && meta->raw_mode ? BPF_WRITE :
4145 BPF_READ))
4146 return -EACCES;
4147 return check_map_access(env, regno, reg->off, access_size,
4148 zero_size_allowed);
4149 case PTR_TO_MEM:
4150 return check_mem_region_access(env, regno, reg->off,
4151 access_size, reg->mem_size,
4152 zero_size_allowed);
4153 case PTR_TO_RDONLY_BUF:
4154 if (meta && meta->raw_mode)
4155 return -EACCES;
4156 return check_buffer_access(env, reg, regno, reg->off,
4157 access_size, zero_size_allowed,
4158 "rdonly",
4159 &env->prog->aux->max_rdonly_access);
4160 case PTR_TO_RDWR_BUF:
4161 return check_buffer_access(env, reg, regno, reg->off,
4162 access_size, zero_size_allowed,
4163 "rdwr",
4164 &env->prog->aux->max_rdwr_access);
4165 case PTR_TO_STACK:
4166 return check_stack_range_initialized(
4167 env,
4168 regno, reg->off, access_size,
4169 zero_size_allowed, ACCESS_HELPER, meta);
4170 default: /* scalar_value or invalid ptr */
4171 /* Allow zero-byte read from NULL, regardless of pointer type */
4172 if (zero_size_allowed && access_size == 0 &&
4173 register_is_null(reg))
4174 return 0;
4175
4176 verbose(env, "R%d type=%s expected=%s\n", regno,
4177 reg_type_str[reg->type],
4178 reg_type_str[PTR_TO_STACK]);
4179 return -EACCES;
4180 }
4181 }
4182
4183 /* Implementation details:
4184 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4185 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4186 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4187 * value_or_null->value transition, since the verifier only cares about
4188 * the range of access to valid map value pointer and doesn't care about actual
4189 * address of the map element.
4190 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4191 * reg->id > 0 after value_or_null->value transition. By doing so
4192 * two bpf_map_lookups will be considered two different pointers that
4193 * point to different bpf_spin_locks.
4194 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4195 * dead-locks.
4196 * Since only one bpf_spin_lock is allowed the checks are simpler than
4197 * reg_is_refcounted() logic. The verifier needs to remember only
4198 * one spin_lock instead of array of acquired_refs.
4199 * cur_state->active_spin_lock remembers which map value element got locked
4200 * and clears it after bpf_spin_unlock.
4201 */
4202 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4203 bool is_lock)
4204 {
4205 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4206 struct bpf_verifier_state *cur = env->cur_state;
4207 bool is_const = tnum_is_const(reg->var_off);
4208 struct bpf_map *map = reg->map_ptr;
4209 u64 val = reg->var_off.value;
4210
4211 if (!is_const) {
4212 verbose(env,
4213 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4214 regno);
4215 return -EINVAL;
4216 }
4217 if (!map->btf) {
4218 verbose(env,
4219 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4220 map->name);
4221 return -EINVAL;
4222 }
4223 if (!map_value_has_spin_lock(map)) {
4224 if (map->spin_lock_off == -E2BIG)
4225 verbose(env,
4226 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4227 map->name);
4228 else if (map->spin_lock_off == -ENOENT)
4229 verbose(env,
4230 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4231 map->name);
4232 else
4233 verbose(env,
4234 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4235 map->name);
4236 return -EINVAL;
4237 }
4238 if (map->spin_lock_off != val + reg->off) {
4239 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4240 val + reg->off);
4241 return -EINVAL;
4242 }
4243 if (is_lock) {
4244 if (cur->active_spin_lock) {
4245 verbose(env,
4246 "Locking two bpf_spin_locks are not allowed\n");
4247 return -EINVAL;
4248 }
4249 cur->active_spin_lock = reg->id;
4250 } else {
4251 if (!cur->active_spin_lock) {
4252 verbose(env, "bpf_spin_unlock without taking a lock\n");
4253 return -EINVAL;
4254 }
4255 if (cur->active_spin_lock != reg->id) {
4256 verbose(env, "bpf_spin_unlock of different lock\n");
4257 return -EINVAL;
4258 }
4259 cur->active_spin_lock = 0;
4260 }
4261 return 0;
4262 }
4263
4264 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4265 {
4266 return type == ARG_PTR_TO_MEM ||
4267 type == ARG_PTR_TO_MEM_OR_NULL ||
4268 type == ARG_PTR_TO_UNINIT_MEM;
4269 }
4270
4271 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4272 {
4273 return type == ARG_CONST_SIZE ||
4274 type == ARG_CONST_SIZE_OR_ZERO;
4275 }
4276
4277 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4278 {
4279 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4280 }
4281
4282 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4283 {
4284 return type == ARG_PTR_TO_INT ||
4285 type == ARG_PTR_TO_LONG;
4286 }
4287
4288 static int int_ptr_type_to_size(enum bpf_arg_type type)
4289 {
4290 if (type == ARG_PTR_TO_INT)
4291 return sizeof(u32);
4292 else if (type == ARG_PTR_TO_LONG)
4293 return sizeof(u64);
4294
4295 return -EINVAL;
4296 }
4297
4298 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4299 const struct bpf_call_arg_meta *meta,
4300 enum bpf_arg_type *arg_type)
4301 {
4302 if (!meta->map_ptr) {
4303 /* kernel subsystem misconfigured verifier */
4304 verbose(env, "invalid map_ptr to access map->type\n");
4305 return -EACCES;
4306 }
4307
4308 switch (meta->map_ptr->map_type) {
4309 case BPF_MAP_TYPE_SOCKMAP:
4310 case BPF_MAP_TYPE_SOCKHASH:
4311 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4312 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4313 } else {
4314 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4315 return -EINVAL;
4316 }
4317 break;
4318
4319 default:
4320 break;
4321 }
4322 return 0;
4323 }
4324
4325 struct bpf_reg_types {
4326 const enum bpf_reg_type types[10];
4327 u32 *btf_id;
4328 };
4329
4330 static const struct bpf_reg_types map_key_value_types = {
4331 .types = {
4332 PTR_TO_STACK,
4333 PTR_TO_PACKET,
4334 PTR_TO_PACKET_META,
4335 PTR_TO_MAP_VALUE,
4336 },
4337 };
4338
4339 static const struct bpf_reg_types sock_types = {
4340 .types = {
4341 PTR_TO_SOCK_COMMON,
4342 PTR_TO_SOCKET,
4343 PTR_TO_TCP_SOCK,
4344 PTR_TO_XDP_SOCK,
4345 },
4346 };
4347
4348 #ifdef CONFIG_NET
4349 static const struct bpf_reg_types btf_id_sock_common_types = {
4350 .types = {
4351 PTR_TO_SOCK_COMMON,
4352 PTR_TO_SOCKET,
4353 PTR_TO_TCP_SOCK,
4354 PTR_TO_XDP_SOCK,
4355 PTR_TO_BTF_ID,
4356 },
4357 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4358 };
4359 #endif
4360
4361 static const struct bpf_reg_types mem_types = {
4362 .types = {
4363 PTR_TO_STACK,
4364 PTR_TO_PACKET,
4365 PTR_TO_PACKET_META,
4366 PTR_TO_MAP_VALUE,
4367 PTR_TO_MEM,
4368 PTR_TO_RDONLY_BUF,
4369 PTR_TO_RDWR_BUF,
4370 },
4371 };
4372
4373 static const struct bpf_reg_types int_ptr_types = {
4374 .types = {
4375 PTR_TO_STACK,
4376 PTR_TO_PACKET,
4377 PTR_TO_PACKET_META,
4378 PTR_TO_MAP_VALUE,
4379 },
4380 };
4381
4382 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4383 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4384 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4385 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4386 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4387 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4388 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4389 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4390
4391 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4392 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4393 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4394 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4395 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4396 [ARG_CONST_SIZE] = &scalar_types,
4397 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4398 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4399 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4400 [ARG_PTR_TO_CTX] = &context_types,
4401 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4402 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4403 #ifdef CONFIG_NET
4404 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4405 #endif
4406 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4407 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4408 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4409 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4410 [ARG_PTR_TO_MEM] = &mem_types,
4411 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4412 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4413 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4414 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4415 [ARG_PTR_TO_INT] = &int_ptr_types,
4416 [ARG_PTR_TO_LONG] = &int_ptr_types,
4417 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4418 };
4419
4420 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4421 enum bpf_arg_type arg_type,
4422 const u32 *arg_btf_id)
4423 {
4424 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4425 enum bpf_reg_type expected, type = reg->type;
4426 const struct bpf_reg_types *compatible;
4427 int i, j;
4428
4429 compatible = compatible_reg_types[arg_type];
4430 if (!compatible) {
4431 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4432 return -EFAULT;
4433 }
4434
4435 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4436 expected = compatible->types[i];
4437 if (expected == NOT_INIT)
4438 break;
4439
4440 if (type == expected)
4441 goto found;
4442 }
4443
4444 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4445 for (j = 0; j + 1 < i; j++)
4446 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4447 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4448 return -EACCES;
4449
4450 found:
4451 if (type == PTR_TO_BTF_ID) {
4452 if (!arg_btf_id) {
4453 if (!compatible->btf_id) {
4454 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4455 return -EFAULT;
4456 }
4457 arg_btf_id = compatible->btf_id;
4458 }
4459
4460 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4461 btf_vmlinux, *arg_btf_id)) {
4462 verbose(env, "R%d is of type %s but %s is expected\n",
4463 regno, kernel_type_name(reg->btf, reg->btf_id),
4464 kernel_type_name(btf_vmlinux, *arg_btf_id));
4465 return -EACCES;
4466 }
4467
4468 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4469 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4470 regno);
4471 return -EACCES;
4472 }
4473 }
4474
4475 return 0;
4476 }
4477
4478 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4479 struct bpf_call_arg_meta *meta,
4480 const struct bpf_func_proto *fn)
4481 {
4482 u32 regno = BPF_REG_1 + arg;
4483 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4484 enum bpf_arg_type arg_type = fn->arg_type[arg];
4485 enum bpf_reg_type type = reg->type;
4486 int err = 0;
4487
4488 if (arg_type == ARG_DONTCARE)
4489 return 0;
4490
4491 err = check_reg_arg(env, regno, SRC_OP);
4492 if (err)
4493 return err;
4494
4495 if (arg_type == ARG_ANYTHING) {
4496 if (is_pointer_value(env, regno)) {
4497 verbose(env, "R%d leaks addr into helper function\n",
4498 regno);
4499 return -EACCES;
4500 }
4501 return 0;
4502 }
4503
4504 if (type_is_pkt_pointer(type) &&
4505 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4506 verbose(env, "helper access to the packet is not allowed\n");
4507 return -EACCES;
4508 }
4509
4510 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4511 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4512 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4513 err = resolve_map_arg_type(env, meta, &arg_type);
4514 if (err)
4515 return err;
4516 }
4517
4518 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4519 /* A NULL register has a SCALAR_VALUE type, so skip
4520 * type checking.
4521 */
4522 goto skip_type_check;
4523
4524 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4525 if (err)
4526 return err;
4527
4528 if (type == PTR_TO_CTX) {
4529 err = check_ctx_reg(env, reg, regno);
4530 if (err < 0)
4531 return err;
4532 }
4533
4534 skip_type_check:
4535 if (reg->ref_obj_id) {
4536 if (meta->ref_obj_id) {
4537 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4538 regno, reg->ref_obj_id,
4539 meta->ref_obj_id);
4540 return -EFAULT;
4541 }
4542 meta->ref_obj_id = reg->ref_obj_id;
4543 }
4544
4545 if (arg_type == ARG_CONST_MAP_PTR) {
4546 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4547 meta->map_ptr = reg->map_ptr;
4548 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4549 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4550 * check that [key, key + map->key_size) are within
4551 * stack limits and initialized
4552 */
4553 if (!meta->map_ptr) {
4554 /* in function declaration map_ptr must come before
4555 * map_key, so that it's verified and known before
4556 * we have to check map_key here. Otherwise it means
4557 * that kernel subsystem misconfigured verifier
4558 */
4559 verbose(env, "invalid map_ptr to access map->key\n");
4560 return -EACCES;
4561 }
4562 err = check_helper_mem_access(env, regno,
4563 meta->map_ptr->key_size, false,
4564 NULL);
4565 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4566 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4567 !register_is_null(reg)) ||
4568 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4569 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4570 * check [value, value + map->value_size) validity
4571 */
4572 if (!meta->map_ptr) {
4573 /* kernel subsystem misconfigured verifier */
4574 verbose(env, "invalid map_ptr to access map->value\n");
4575 return -EACCES;
4576 }
4577 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4578 err = check_helper_mem_access(env, regno,
4579 meta->map_ptr->value_size, false,
4580 meta);
4581 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4582 if (!reg->btf_id) {
4583 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4584 return -EACCES;
4585 }
4586 meta->ret_btf = reg->btf;
4587 meta->ret_btf_id = reg->btf_id;
4588 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4589 if (meta->func_id == BPF_FUNC_spin_lock) {
4590 if (process_spin_lock(env, regno, true))
4591 return -EACCES;
4592 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4593 if (process_spin_lock(env, regno, false))
4594 return -EACCES;
4595 } else {
4596 verbose(env, "verifier internal error\n");
4597 return -EFAULT;
4598 }
4599 } else if (arg_type_is_mem_ptr(arg_type)) {
4600 /* The access to this pointer is only checked when we hit the
4601 * next is_mem_size argument below.
4602 */
4603 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4604 } else if (arg_type_is_mem_size(arg_type)) {
4605 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4606
4607 /* This is used to refine r0 return value bounds for helpers
4608 * that enforce this value as an upper bound on return values.
4609 * See do_refine_retval_range() for helpers that can refine
4610 * the return value. C type of helper is u32 so we pull register
4611 * bound from umax_value however, if negative verifier errors
4612 * out. Only upper bounds can be learned because retval is an
4613 * int type and negative retvals are allowed.
4614 */
4615 meta->msize_max_value = reg->umax_value;
4616
4617 /* The register is SCALAR_VALUE; the access check
4618 * happens using its boundaries.
4619 */
4620 if (!tnum_is_const(reg->var_off))
4621 /* For unprivileged variable accesses, disable raw
4622 * mode so that the program is required to
4623 * initialize all the memory that the helper could
4624 * just partially fill up.
4625 */
4626 meta = NULL;
4627
4628 if (reg->smin_value < 0) {
4629 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4630 regno);
4631 return -EACCES;
4632 }
4633
4634 if (reg->umin_value == 0) {
4635 err = check_helper_mem_access(env, regno - 1, 0,
4636 zero_size_allowed,
4637 meta);
4638 if (err)
4639 return err;
4640 }
4641
4642 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4643 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4644 regno);
4645 return -EACCES;
4646 }
4647 err = check_helper_mem_access(env, regno - 1,
4648 reg->umax_value,
4649 zero_size_allowed, meta);
4650 if (!err)
4651 err = mark_chain_precision(env, regno);
4652 } else if (arg_type_is_alloc_size(arg_type)) {
4653 if (!tnum_is_const(reg->var_off)) {
4654 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4655 regno);
4656 return -EACCES;
4657 }
4658 meta->mem_size = reg->var_off.value;
4659 } else if (arg_type_is_int_ptr(arg_type)) {
4660 int size = int_ptr_type_to_size(arg_type);
4661
4662 err = check_helper_mem_access(env, regno, size, false, meta);
4663 if (err)
4664 return err;
4665 err = check_ptr_alignment(env, reg, 0, size, true);
4666 }
4667
4668 return err;
4669 }
4670
4671 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4672 {
4673 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4674 enum bpf_prog_type type = resolve_prog_type(env->prog);
4675
4676 if (func_id != BPF_FUNC_map_update_elem)
4677 return false;
4678
4679 /* It's not possible to get access to a locked struct sock in these
4680 * contexts, so updating is safe.
4681 */
4682 switch (type) {
4683 case BPF_PROG_TYPE_TRACING:
4684 if (eatype == BPF_TRACE_ITER)
4685 return true;
4686 break;
4687 case BPF_PROG_TYPE_SOCKET_FILTER:
4688 case BPF_PROG_TYPE_SCHED_CLS:
4689 case BPF_PROG_TYPE_SCHED_ACT:
4690 case BPF_PROG_TYPE_XDP:
4691 case BPF_PROG_TYPE_SK_REUSEPORT:
4692 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4693 case BPF_PROG_TYPE_SK_LOOKUP:
4694 return true;
4695 default:
4696 break;
4697 }
4698
4699 verbose(env, "cannot update sockmap in this context\n");
4700 return false;
4701 }
4702
4703 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4704 {
4705 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4706 }
4707
4708 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4709 struct bpf_map *map, int func_id)
4710 {
4711 if (!map)
4712 return 0;
4713
4714 /* We need a two way check, first is from map perspective ... */
4715 switch (map->map_type) {
4716 case BPF_MAP_TYPE_PROG_ARRAY:
4717 if (func_id != BPF_FUNC_tail_call)
4718 goto error;
4719 break;
4720 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4721 if (func_id != BPF_FUNC_perf_event_read &&
4722 func_id != BPF_FUNC_perf_event_output &&
4723 func_id != BPF_FUNC_skb_output &&
4724 func_id != BPF_FUNC_perf_event_read_value &&
4725 func_id != BPF_FUNC_xdp_output)
4726 goto error;
4727 break;
4728 case BPF_MAP_TYPE_RINGBUF:
4729 if (func_id != BPF_FUNC_ringbuf_output &&
4730 func_id != BPF_FUNC_ringbuf_reserve &&
4731 func_id != BPF_FUNC_ringbuf_submit &&
4732 func_id != BPF_FUNC_ringbuf_discard &&
4733 func_id != BPF_FUNC_ringbuf_query)
4734 goto error;
4735 break;
4736 case BPF_MAP_TYPE_STACK_TRACE:
4737 if (func_id != BPF_FUNC_get_stackid)
4738 goto error;
4739 break;
4740 case BPF_MAP_TYPE_CGROUP_ARRAY:
4741 if (func_id != BPF_FUNC_skb_under_cgroup &&
4742 func_id != BPF_FUNC_current_task_under_cgroup)
4743 goto error;
4744 break;
4745 case BPF_MAP_TYPE_CGROUP_STORAGE:
4746 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4747 if (func_id != BPF_FUNC_get_local_storage)
4748 goto error;
4749 break;
4750 case BPF_MAP_TYPE_DEVMAP:
4751 case BPF_MAP_TYPE_DEVMAP_HASH:
4752 if (func_id != BPF_FUNC_redirect_map &&
4753 func_id != BPF_FUNC_map_lookup_elem)
4754 goto error;
4755 break;
4756 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4757 * appear.
4758 */
4759 case BPF_MAP_TYPE_CPUMAP:
4760 if (func_id != BPF_FUNC_redirect_map)
4761 goto error;
4762 break;
4763 case BPF_MAP_TYPE_XSKMAP:
4764 if (func_id != BPF_FUNC_redirect_map &&
4765 func_id != BPF_FUNC_map_lookup_elem)
4766 goto error;
4767 break;
4768 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4769 case BPF_MAP_TYPE_HASH_OF_MAPS:
4770 if (func_id != BPF_FUNC_map_lookup_elem)
4771 goto error;
4772 break;
4773 case BPF_MAP_TYPE_SOCKMAP:
4774 if (func_id != BPF_FUNC_sk_redirect_map &&
4775 func_id != BPF_FUNC_sock_map_update &&
4776 func_id != BPF_FUNC_map_delete_elem &&
4777 func_id != BPF_FUNC_msg_redirect_map &&
4778 func_id != BPF_FUNC_sk_select_reuseport &&
4779 func_id != BPF_FUNC_map_lookup_elem &&
4780 !may_update_sockmap(env, func_id))
4781 goto error;
4782 break;
4783 case BPF_MAP_TYPE_SOCKHASH:
4784 if (func_id != BPF_FUNC_sk_redirect_hash &&
4785 func_id != BPF_FUNC_sock_hash_update &&
4786 func_id != BPF_FUNC_map_delete_elem &&
4787 func_id != BPF_FUNC_msg_redirect_hash &&
4788 func_id != BPF_FUNC_sk_select_reuseport &&
4789 func_id != BPF_FUNC_map_lookup_elem &&
4790 !may_update_sockmap(env, func_id))
4791 goto error;
4792 break;
4793 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4794 if (func_id != BPF_FUNC_sk_select_reuseport)
4795 goto error;
4796 break;
4797 case BPF_MAP_TYPE_QUEUE:
4798 case BPF_MAP_TYPE_STACK:
4799 if (func_id != BPF_FUNC_map_peek_elem &&
4800 func_id != BPF_FUNC_map_pop_elem &&
4801 func_id != BPF_FUNC_map_push_elem)
4802 goto error;
4803 break;
4804 case BPF_MAP_TYPE_SK_STORAGE:
4805 if (func_id != BPF_FUNC_sk_storage_get &&
4806 func_id != BPF_FUNC_sk_storage_delete)
4807 goto error;
4808 break;
4809 case BPF_MAP_TYPE_INODE_STORAGE:
4810 if (func_id != BPF_FUNC_inode_storage_get &&
4811 func_id != BPF_FUNC_inode_storage_delete)
4812 goto error;
4813 break;
4814 case BPF_MAP_TYPE_TASK_STORAGE:
4815 if (func_id != BPF_FUNC_task_storage_get &&
4816 func_id != BPF_FUNC_task_storage_delete)
4817 goto error;
4818 break;
4819 default:
4820 break;
4821 }
4822
4823 /* ... and second from the function itself. */
4824 switch (func_id) {
4825 case BPF_FUNC_tail_call:
4826 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4827 goto error;
4828 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4829 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
4830 return -EINVAL;
4831 }
4832 break;
4833 case BPF_FUNC_perf_event_read:
4834 case BPF_FUNC_perf_event_output:
4835 case BPF_FUNC_perf_event_read_value:
4836 case BPF_FUNC_skb_output:
4837 case BPF_FUNC_xdp_output:
4838 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4839 goto error;
4840 break;
4841 case BPF_FUNC_get_stackid:
4842 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4843 goto error;
4844 break;
4845 case BPF_FUNC_current_task_under_cgroup:
4846 case BPF_FUNC_skb_under_cgroup:
4847 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4848 goto error;
4849 break;
4850 case BPF_FUNC_redirect_map:
4851 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
4852 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
4853 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4854 map->map_type != BPF_MAP_TYPE_XSKMAP)
4855 goto error;
4856 break;
4857 case BPF_FUNC_sk_redirect_map:
4858 case BPF_FUNC_msg_redirect_map:
4859 case BPF_FUNC_sock_map_update:
4860 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4861 goto error;
4862 break;
4863 case BPF_FUNC_sk_redirect_hash:
4864 case BPF_FUNC_msg_redirect_hash:
4865 case BPF_FUNC_sock_hash_update:
4866 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
4867 goto error;
4868 break;
4869 case BPF_FUNC_get_local_storage:
4870 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4871 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
4872 goto error;
4873 break;
4874 case BPF_FUNC_sk_select_reuseport:
4875 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4876 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4877 map->map_type != BPF_MAP_TYPE_SOCKHASH)
4878 goto error;
4879 break;
4880 case BPF_FUNC_map_peek_elem:
4881 case BPF_FUNC_map_pop_elem:
4882 case BPF_FUNC_map_push_elem:
4883 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4884 map->map_type != BPF_MAP_TYPE_STACK)
4885 goto error;
4886 break;
4887 case BPF_FUNC_sk_storage_get:
4888 case BPF_FUNC_sk_storage_delete:
4889 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
4890 goto error;
4891 break;
4892 case BPF_FUNC_inode_storage_get:
4893 case BPF_FUNC_inode_storage_delete:
4894 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
4895 goto error;
4896 break;
4897 case BPF_FUNC_task_storage_get:
4898 case BPF_FUNC_task_storage_delete:
4899 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
4900 goto error;
4901 break;
4902 default:
4903 break;
4904 }
4905
4906 return 0;
4907 error:
4908 verbose(env, "cannot pass map_type %d into func %s#%d\n",
4909 map->map_type, func_id_name(func_id), func_id);
4910 return -EINVAL;
4911 }
4912
4913 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
4914 {
4915 int count = 0;
4916
4917 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
4918 count++;
4919 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
4920 count++;
4921 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
4922 count++;
4923 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
4924 count++;
4925 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
4926 count++;
4927
4928 /* We only support one arg being in raw mode at the moment,
4929 * which is sufficient for the helper functions we have
4930 * right now.
4931 */
4932 return count <= 1;
4933 }
4934
4935 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
4936 enum bpf_arg_type arg_next)
4937 {
4938 return (arg_type_is_mem_ptr(arg_curr) &&
4939 !arg_type_is_mem_size(arg_next)) ||
4940 (!arg_type_is_mem_ptr(arg_curr) &&
4941 arg_type_is_mem_size(arg_next));
4942 }
4943
4944 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
4945 {
4946 /* bpf_xxx(..., buf, len) call will access 'len'
4947 * bytes from memory 'buf'. Both arg types need
4948 * to be paired, so make sure there's no buggy
4949 * helper function specification.
4950 */
4951 if (arg_type_is_mem_size(fn->arg1_type) ||
4952 arg_type_is_mem_ptr(fn->arg5_type) ||
4953 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
4954 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
4955 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
4956 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
4957 return false;
4958
4959 return true;
4960 }
4961
4962 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
4963 {
4964 int count = 0;
4965
4966 if (arg_type_may_be_refcounted(fn->arg1_type))
4967 count++;
4968 if (arg_type_may_be_refcounted(fn->arg2_type))
4969 count++;
4970 if (arg_type_may_be_refcounted(fn->arg3_type))
4971 count++;
4972 if (arg_type_may_be_refcounted(fn->arg4_type))
4973 count++;
4974 if (arg_type_may_be_refcounted(fn->arg5_type))
4975 count++;
4976
4977 /* A reference acquiring function cannot acquire
4978 * another refcounted ptr.
4979 */
4980 if (may_be_acquire_function(func_id) && count)
4981 return false;
4982
4983 /* We only support one arg being unreferenced at the moment,
4984 * which is sufficient for the helper functions we have right now.
4985 */
4986 return count <= 1;
4987 }
4988
4989 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
4990 {
4991 int i;
4992
4993 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
4994 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
4995 return false;
4996
4997 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
4998 return false;
4999 }
5000
5001 return true;
5002 }
5003
5004 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5005 {
5006 return check_raw_mode_ok(fn) &&
5007 check_arg_pair_ok(fn) &&
5008 check_btf_id_ok(fn) &&
5009 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5010 }
5011
5012 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5013 * are now invalid, so turn them into unknown SCALAR_VALUE.
5014 */
5015 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5016 struct bpf_func_state *state)
5017 {
5018 struct bpf_reg_state *regs = state->regs, *reg;
5019 int i;
5020
5021 for (i = 0; i < MAX_BPF_REG; i++)
5022 if (reg_is_pkt_pointer_any(&regs[i]))
5023 mark_reg_unknown(env, regs, i);
5024
5025 bpf_for_each_spilled_reg(i, state, reg) {
5026 if (!reg)
5027 continue;
5028 if (reg_is_pkt_pointer_any(reg))
5029 __mark_reg_unknown(env, reg);
5030 }
5031 }
5032
5033 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5034 {
5035 struct bpf_verifier_state *vstate = env->cur_state;
5036 int i;
5037
5038 for (i = 0; i <= vstate->curframe; i++)
5039 __clear_all_pkt_pointers(env, vstate->frame[i]);
5040 }
5041
5042 enum {
5043 AT_PKT_END = -1,
5044 BEYOND_PKT_END = -2,
5045 };
5046
5047 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5048 {
5049 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5050 struct bpf_reg_state *reg = &state->regs[regn];
5051
5052 if (reg->type != PTR_TO_PACKET)
5053 /* PTR_TO_PACKET_META is not supported yet */
5054 return;
5055
5056 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5057 * How far beyond pkt_end it goes is unknown.
5058 * if (!range_open) it's the case of pkt >= pkt_end
5059 * if (range_open) it's the case of pkt > pkt_end
5060 * hence this pointer is at least 1 byte bigger than pkt_end
5061 */
5062 if (range_open)
5063 reg->range = BEYOND_PKT_END;
5064 else
5065 reg->range = AT_PKT_END;
5066 }
5067
5068 static void release_reg_references(struct bpf_verifier_env *env,
5069 struct bpf_func_state *state,
5070 int ref_obj_id)
5071 {
5072 struct bpf_reg_state *regs = state->regs, *reg;
5073 int i;
5074
5075 for (i = 0; i < MAX_BPF_REG; i++)
5076 if (regs[i].ref_obj_id == ref_obj_id)
5077 mark_reg_unknown(env, regs, i);
5078
5079 bpf_for_each_spilled_reg(i, state, reg) {
5080 if (!reg)
5081 continue;
5082 if (reg->ref_obj_id == ref_obj_id)
5083 __mark_reg_unknown(env, reg);
5084 }
5085 }
5086
5087 /* The pointer with the specified id has released its reference to kernel
5088 * resources. Identify all copies of the same pointer and clear the reference.
5089 */
5090 static int release_reference(struct bpf_verifier_env *env,
5091 int ref_obj_id)
5092 {
5093 struct bpf_verifier_state *vstate = env->cur_state;
5094 int err;
5095 int i;
5096
5097 err = release_reference_state(cur_func(env), ref_obj_id);
5098 if (err)
5099 return err;
5100
5101 for (i = 0; i <= vstate->curframe; i++)
5102 release_reg_references(env, vstate->frame[i], ref_obj_id);
5103
5104 return 0;
5105 }
5106
5107 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5108 struct bpf_reg_state *regs)
5109 {
5110 int i;
5111
5112 /* after the call registers r0 - r5 were scratched */
5113 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5114 mark_reg_not_init(env, regs, caller_saved[i]);
5115 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5116 }
5117 }
5118
5119 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5120 int *insn_idx)
5121 {
5122 struct bpf_verifier_state *state = env->cur_state;
5123 struct bpf_func_info_aux *func_info_aux;
5124 struct bpf_func_state *caller, *callee;
5125 int i, err, subprog, target_insn;
5126 bool is_global = false;
5127
5128 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5129 verbose(env, "the call stack of %d frames is too deep\n",
5130 state->curframe + 2);
5131 return -E2BIG;
5132 }
5133
5134 target_insn = *insn_idx + insn->imm;
5135 subprog = find_subprog(env, target_insn + 1);
5136 if (subprog < 0) {
5137 verbose(env, "verifier bug. No program starts at insn %d\n",
5138 target_insn + 1);
5139 return -EFAULT;
5140 }
5141
5142 caller = state->frame[state->curframe];
5143 if (state->frame[state->curframe + 1]) {
5144 verbose(env, "verifier bug. Frame %d already allocated\n",
5145 state->curframe + 1);
5146 return -EFAULT;
5147 }
5148
5149 func_info_aux = env->prog->aux->func_info_aux;
5150 if (func_info_aux)
5151 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5152 err = btf_check_func_arg_match(env, subprog, caller->regs);
5153 if (err == -EFAULT)
5154 return err;
5155 if (is_global) {
5156 if (err) {
5157 verbose(env, "Caller passes invalid args into func#%d\n",
5158 subprog);
5159 return err;
5160 } else {
5161 if (env->log.level & BPF_LOG_LEVEL)
5162 verbose(env,
5163 "Func#%d is global and valid. Skipping.\n",
5164 subprog);
5165 clear_caller_saved_regs(env, caller->regs);
5166
5167 /* All global functions return a 64-bit SCALAR_VALUE */
5168 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5169 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5170
5171 /* continue with next insn after call */
5172 return 0;
5173 }
5174 }
5175
5176 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5177 if (!callee)
5178 return -ENOMEM;
5179 state->frame[state->curframe + 1] = callee;
5180
5181 /* callee cannot access r0, r6 - r9 for reading and has to write
5182 * into its own stack before reading from it.
5183 * callee can read/write into caller's stack
5184 */
5185 init_func_state(env, callee,
5186 /* remember the callsite, it will be used by bpf_exit */
5187 *insn_idx /* callsite */,
5188 state->curframe + 1 /* frameno within this callchain */,
5189 subprog /* subprog number within this prog */);
5190
5191 /* Transfer references to the callee */
5192 err = transfer_reference_state(callee, caller);
5193 if (err)
5194 return err;
5195
5196 /* copy r1 - r5 args that callee can access. The copy includes parent
5197 * pointers, which connects us up to the liveness chain
5198 */
5199 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5200 callee->regs[i] = caller->regs[i];
5201
5202 clear_caller_saved_regs(env, caller->regs);
5203
5204 /* only increment it after check_reg_arg() finished */
5205 state->curframe++;
5206
5207 /* and go analyze first insn of the callee */
5208 *insn_idx = target_insn;
5209
5210 if (env->log.level & BPF_LOG_LEVEL) {
5211 verbose(env, "caller:\n");
5212 print_verifier_state(env, caller);
5213 verbose(env, "callee:\n");
5214 print_verifier_state(env, callee);
5215 }
5216 return 0;
5217 }
5218
5219 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5220 {
5221 struct bpf_verifier_state *state = env->cur_state;
5222 struct bpf_func_state *caller, *callee;
5223 struct bpf_reg_state *r0;
5224 int err;
5225
5226 callee = state->frame[state->curframe];
5227 r0 = &callee->regs[BPF_REG_0];
5228 if (r0->type == PTR_TO_STACK) {
5229 /* technically it's ok to return caller's stack pointer
5230 * (or caller's caller's pointer) back to the caller,
5231 * since these pointers are valid. Only current stack
5232 * pointer will be invalid as soon as function exits,
5233 * but let's be conservative
5234 */
5235 verbose(env, "cannot return stack pointer to the caller\n");
5236 return -EINVAL;
5237 }
5238
5239 state->curframe--;
5240 caller = state->frame[state->curframe];
5241 /* return to the caller whatever r0 had in the callee */
5242 caller->regs[BPF_REG_0] = *r0;
5243
5244 /* Transfer references to the caller */
5245 err = transfer_reference_state(caller, callee);
5246 if (err)
5247 return err;
5248
5249 *insn_idx = callee->callsite + 1;
5250 if (env->log.level & BPF_LOG_LEVEL) {
5251 verbose(env, "returning from callee:\n");
5252 print_verifier_state(env, callee);
5253 verbose(env, "to caller at %d:\n", *insn_idx);
5254 print_verifier_state(env, caller);
5255 }
5256 /* clear everything in the callee */
5257 free_func_state(callee);
5258 state->frame[state->curframe + 1] = NULL;
5259 return 0;
5260 }
5261
5262 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5263 int func_id,
5264 struct bpf_call_arg_meta *meta)
5265 {
5266 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5267
5268 if (ret_type != RET_INTEGER ||
5269 (func_id != BPF_FUNC_get_stack &&
5270 func_id != BPF_FUNC_probe_read_str &&
5271 func_id != BPF_FUNC_probe_read_kernel_str &&
5272 func_id != BPF_FUNC_probe_read_user_str))
5273 return;
5274
5275 ret_reg->smax_value = meta->msize_max_value;
5276 ret_reg->s32_max_value = meta->msize_max_value;
5277 ret_reg->smin_value = -MAX_ERRNO;
5278 ret_reg->s32_min_value = -MAX_ERRNO;
5279 __reg_deduce_bounds(ret_reg);
5280 __reg_bound_offset(ret_reg);
5281 __update_reg_bounds(ret_reg);
5282 }
5283
5284 static int
5285 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5286 int func_id, int insn_idx)
5287 {
5288 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5289 struct bpf_map *map = meta->map_ptr;
5290
5291 if (func_id != BPF_FUNC_tail_call &&
5292 func_id != BPF_FUNC_map_lookup_elem &&
5293 func_id != BPF_FUNC_map_update_elem &&
5294 func_id != BPF_FUNC_map_delete_elem &&
5295 func_id != BPF_FUNC_map_push_elem &&
5296 func_id != BPF_FUNC_map_pop_elem &&
5297 func_id != BPF_FUNC_map_peek_elem)
5298 return 0;
5299
5300 if (map == NULL) {
5301 verbose(env, "kernel subsystem misconfigured verifier\n");
5302 return -EINVAL;
5303 }
5304
5305 /* In case of read-only, some additional restrictions
5306 * need to be applied in order to prevent altering the
5307 * state of the map from program side.
5308 */
5309 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5310 (func_id == BPF_FUNC_map_delete_elem ||
5311 func_id == BPF_FUNC_map_update_elem ||
5312 func_id == BPF_FUNC_map_push_elem ||
5313 func_id == BPF_FUNC_map_pop_elem)) {
5314 verbose(env, "write into map forbidden\n");
5315 return -EACCES;
5316 }
5317
5318 if (!BPF_MAP_PTR(aux->map_ptr_state))
5319 bpf_map_ptr_store(aux, meta->map_ptr,
5320 !meta->map_ptr->bypass_spec_v1);
5321 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5322 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5323 !meta->map_ptr->bypass_spec_v1);
5324 return 0;
5325 }
5326
5327 static int
5328 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5329 int func_id, int insn_idx)
5330 {
5331 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5332 struct bpf_reg_state *regs = cur_regs(env), *reg;
5333 struct bpf_map *map = meta->map_ptr;
5334 struct tnum range;
5335 u64 val;
5336 int err;
5337
5338 if (func_id != BPF_FUNC_tail_call)
5339 return 0;
5340 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5341 verbose(env, "kernel subsystem misconfigured verifier\n");
5342 return -EINVAL;
5343 }
5344
5345 range = tnum_range(0, map->max_entries - 1);
5346 reg = &regs[BPF_REG_3];
5347
5348 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5349 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5350 return 0;
5351 }
5352
5353 err = mark_chain_precision(env, BPF_REG_3);
5354 if (err)
5355 return err;
5356
5357 val = reg->var_off.value;
5358 if (bpf_map_key_unseen(aux))
5359 bpf_map_key_store(aux, val);
5360 else if (!bpf_map_key_poisoned(aux) &&
5361 bpf_map_key_immediate(aux) != val)
5362 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5363 return 0;
5364 }
5365
5366 static int check_reference_leak(struct bpf_verifier_env *env)
5367 {
5368 struct bpf_func_state *state = cur_func(env);
5369 int i;
5370
5371 for (i = 0; i < state->acquired_refs; i++) {
5372 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5373 state->refs[i].id, state->refs[i].insn_idx);
5374 }
5375 return state->acquired_refs ? -EINVAL : 0;
5376 }
5377
5378 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5379 {
5380 const struct bpf_func_proto *fn = NULL;
5381 struct bpf_reg_state *regs;
5382 struct bpf_call_arg_meta meta;
5383 bool changes_data;
5384 int i, err;
5385
5386 /* find function prototype */
5387 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5388 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5389 func_id);
5390 return -EINVAL;
5391 }
5392
5393 if (env->ops->get_func_proto)
5394 fn = env->ops->get_func_proto(func_id, env->prog);
5395 if (!fn) {
5396 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5397 func_id);
5398 return -EINVAL;
5399 }
5400
5401 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5402 if (!env->prog->gpl_compatible && fn->gpl_only) {
5403 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5404 return -EINVAL;
5405 }
5406
5407 if (fn->allowed && !fn->allowed(env->prog)) {
5408 verbose(env, "helper call is not allowed in probe\n");
5409 return -EINVAL;
5410 }
5411
5412 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5413 changes_data = bpf_helper_changes_pkt_data(fn->func);
5414 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5415 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5416 func_id_name(func_id), func_id);
5417 return -EINVAL;
5418 }
5419
5420 memset(&meta, 0, sizeof(meta));
5421 meta.pkt_access = fn->pkt_access;
5422
5423 err = check_func_proto(fn, func_id);
5424 if (err) {
5425 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5426 func_id_name(func_id), func_id);
5427 return err;
5428 }
5429
5430 meta.func_id = func_id;
5431 /* check args */
5432 for (i = 0; i < 5; i++) {
5433 err = check_func_arg(env, i, &meta, fn);
5434 if (err)
5435 return err;
5436 }
5437
5438 err = record_func_map(env, &meta, func_id, insn_idx);
5439 if (err)
5440 return err;
5441
5442 err = record_func_key(env, &meta, func_id, insn_idx);
5443 if (err)
5444 return err;
5445
5446 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5447 * is inferred from register state.
5448 */
5449 for (i = 0; i < meta.access_size; i++) {
5450 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5451 BPF_WRITE, -1, false);
5452 if (err)
5453 return err;
5454 }
5455
5456 if (func_id == BPF_FUNC_tail_call) {
5457 err = check_reference_leak(env);
5458 if (err) {
5459 verbose(env, "tail_call would lead to reference leak\n");
5460 return err;
5461 }
5462 } else if (is_release_function(func_id)) {
5463 err = release_reference(env, meta.ref_obj_id);
5464 if (err) {
5465 verbose(env, "func %s#%d reference has not been acquired before\n",
5466 func_id_name(func_id), func_id);
5467 return err;
5468 }
5469 }
5470
5471 regs = cur_regs(env);
5472
5473 /* check that flags argument in get_local_storage(map, flags) is 0,
5474 * this is required because get_local_storage() can't return an error.
5475 */
5476 if (func_id == BPF_FUNC_get_local_storage &&
5477 !register_is_null(&regs[BPF_REG_2])) {
5478 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5479 return -EINVAL;
5480 }
5481
5482 /* reset caller saved regs */
5483 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5484 mark_reg_not_init(env, regs, caller_saved[i]);
5485 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5486 }
5487
5488 /* helper call returns 64-bit value. */
5489 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5490
5491 /* update return register (already marked as written above) */
5492 if (fn->ret_type == RET_INTEGER) {
5493 /* sets type to SCALAR_VALUE */
5494 mark_reg_unknown(env, regs, BPF_REG_0);
5495 } else if (fn->ret_type == RET_VOID) {
5496 regs[BPF_REG_0].type = NOT_INIT;
5497 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5498 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5499 /* There is no offset yet applied, variable or fixed */
5500 mark_reg_known_zero(env, regs, BPF_REG_0);
5501 /* remember map_ptr, so that check_map_access()
5502 * can check 'value_size' boundary of memory access
5503 * to map element returned from bpf_map_lookup_elem()
5504 */
5505 if (meta.map_ptr == NULL) {
5506 verbose(env,
5507 "kernel subsystem misconfigured verifier\n");
5508 return -EINVAL;
5509 }
5510 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5511 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5512 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5513 if (map_value_has_spin_lock(meta.map_ptr))
5514 regs[BPF_REG_0].id = ++env->id_gen;
5515 } else {
5516 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5517 }
5518 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5519 mark_reg_known_zero(env, regs, BPF_REG_0);
5520 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5521 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5522 mark_reg_known_zero(env, regs, BPF_REG_0);
5523 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5524 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5525 mark_reg_known_zero(env, regs, BPF_REG_0);
5526 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5527 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5528 mark_reg_known_zero(env, regs, BPF_REG_0);
5529 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5530 regs[BPF_REG_0].mem_size = meta.mem_size;
5531 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5532 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5533 const struct btf_type *t;
5534
5535 mark_reg_known_zero(env, regs, BPF_REG_0);
5536 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
5537 if (!btf_type_is_struct(t)) {
5538 u32 tsize;
5539 const struct btf_type *ret;
5540 const char *tname;
5541
5542 /* resolve the type size of ksym. */
5543 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
5544 if (IS_ERR(ret)) {
5545 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
5546 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5547 tname, PTR_ERR(ret));
5548 return -EINVAL;
5549 }
5550 regs[BPF_REG_0].type =
5551 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5552 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5553 regs[BPF_REG_0].mem_size = tsize;
5554 } else {
5555 regs[BPF_REG_0].type =
5556 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5557 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5558 regs[BPF_REG_0].btf = meta.ret_btf;
5559 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5560 }
5561 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5562 fn->ret_type == RET_PTR_TO_BTF_ID) {
5563 int ret_btf_id;
5564
5565 mark_reg_known_zero(env, regs, BPF_REG_0);
5566 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5567 PTR_TO_BTF_ID :
5568 PTR_TO_BTF_ID_OR_NULL;
5569 ret_btf_id = *fn->ret_btf_id;
5570 if (ret_btf_id == 0) {
5571 verbose(env, "invalid return type %d of func %s#%d\n",
5572 fn->ret_type, func_id_name(func_id), func_id);
5573 return -EINVAL;
5574 }
5575 /* current BPF helper definitions are only coming from
5576 * built-in code with type IDs from vmlinux BTF
5577 */
5578 regs[BPF_REG_0].btf = btf_vmlinux;
5579 regs[BPF_REG_0].btf_id = ret_btf_id;
5580 } else {
5581 verbose(env, "unknown return type %d of func %s#%d\n",
5582 fn->ret_type, func_id_name(func_id), func_id);
5583 return -EINVAL;
5584 }
5585
5586 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5587 regs[BPF_REG_0].id = ++env->id_gen;
5588
5589 if (is_ptr_cast_function(func_id)) {
5590 /* For release_reference() */
5591 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5592 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5593 int id = acquire_reference_state(env, insn_idx);
5594
5595 if (id < 0)
5596 return id;
5597 /* For mark_ptr_or_null_reg() */
5598 regs[BPF_REG_0].id = id;
5599 /* For release_reference() */
5600 regs[BPF_REG_0].ref_obj_id = id;
5601 }
5602
5603 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5604
5605 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5606 if (err)
5607 return err;
5608
5609 if ((func_id == BPF_FUNC_get_stack ||
5610 func_id == BPF_FUNC_get_task_stack) &&
5611 !env->prog->has_callchain_buf) {
5612 const char *err_str;
5613
5614 #ifdef CONFIG_PERF_EVENTS
5615 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5616 err_str = "cannot get callchain buffer for func %s#%d\n";
5617 #else
5618 err = -ENOTSUPP;
5619 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5620 #endif
5621 if (err) {
5622 verbose(env, err_str, func_id_name(func_id), func_id);
5623 return err;
5624 }
5625
5626 env->prog->has_callchain_buf = true;
5627 }
5628
5629 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5630 env->prog->call_get_stack = true;
5631
5632 if (changes_data)
5633 clear_all_pkt_pointers(env);
5634 return 0;
5635 }
5636
5637 static bool signed_add_overflows(s64 a, s64 b)
5638 {
5639 /* Do the add in u64, where overflow is well-defined */
5640 s64 res = (s64)((u64)a + (u64)b);
5641
5642 if (b < 0)
5643 return res > a;
5644 return res < a;
5645 }
5646
5647 static bool signed_add32_overflows(s32 a, s32 b)
5648 {
5649 /* Do the add in u32, where overflow is well-defined */
5650 s32 res = (s32)((u32)a + (u32)b);
5651
5652 if (b < 0)
5653 return res > a;
5654 return res < a;
5655 }
5656
5657 static bool signed_sub_overflows(s64 a, s64 b)
5658 {
5659 /* Do the sub in u64, where overflow is well-defined */
5660 s64 res = (s64)((u64)a - (u64)b);
5661
5662 if (b < 0)
5663 return res < a;
5664 return res > a;
5665 }
5666
5667 static bool signed_sub32_overflows(s32 a, s32 b)
5668 {
5669 /* Do the sub in u32, where overflow is well-defined */
5670 s32 res = (s32)((u32)a - (u32)b);
5671
5672 if (b < 0)
5673 return res < a;
5674 return res > a;
5675 }
5676
5677 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5678 const struct bpf_reg_state *reg,
5679 enum bpf_reg_type type)
5680 {
5681 bool known = tnum_is_const(reg->var_off);
5682 s64 val = reg->var_off.value;
5683 s64 smin = reg->smin_value;
5684
5685 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5686 verbose(env, "math between %s pointer and %lld is not allowed\n",
5687 reg_type_str[type], val);
5688 return false;
5689 }
5690
5691 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5692 verbose(env, "%s pointer offset %d is not allowed\n",
5693 reg_type_str[type], reg->off);
5694 return false;
5695 }
5696
5697 if (smin == S64_MIN) {
5698 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5699 reg_type_str[type]);
5700 return false;
5701 }
5702
5703 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5704 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5705 smin, reg_type_str[type]);
5706 return false;
5707 }
5708
5709 return true;
5710 }
5711
5712 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5713 {
5714 return &env->insn_aux_data[env->insn_idx];
5715 }
5716
5717 enum {
5718 REASON_BOUNDS = -1,
5719 REASON_TYPE = -2,
5720 REASON_PATHS = -3,
5721 REASON_LIMIT = -4,
5722 REASON_STACK = -5,
5723 };
5724
5725 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5726 const struct bpf_reg_state *off_reg,
5727 u32 *alu_limit, u8 opcode)
5728 {
5729 bool off_is_neg = off_reg->smin_value < 0;
5730 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5731 (opcode == BPF_SUB && !off_is_neg);
5732 u32 max = 0, ptr_limit = 0;
5733
5734 if (!tnum_is_const(off_reg->var_off) &&
5735 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
5736 return REASON_BOUNDS;
5737
5738 switch (ptr_reg->type) {
5739 case PTR_TO_STACK:
5740 /* Offset 0 is out-of-bounds, but acceptable start for the
5741 * left direction, see BPF_REG_FP. Also, unknown scalar
5742 * offset where we would need to deal with min/max bounds is
5743 * currently prohibited for unprivileged.
5744 */
5745 max = MAX_BPF_STACK + mask_to_left;
5746 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5747 break;
5748 case PTR_TO_MAP_VALUE:
5749 max = ptr_reg->map_ptr->value_size;
5750 ptr_limit = (mask_to_left ?
5751 ptr_reg->smin_value :
5752 ptr_reg->umax_value) + ptr_reg->off;
5753 break;
5754 default:
5755 return REASON_TYPE;
5756 }
5757
5758 if (ptr_limit >= max)
5759 return REASON_LIMIT;
5760 *alu_limit = ptr_limit;
5761 return 0;
5762 }
5763
5764 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5765 const struct bpf_insn *insn)
5766 {
5767 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5768 }
5769
5770 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5771 u32 alu_state, u32 alu_limit)
5772 {
5773 /* If we arrived here from different branches with different
5774 * state or limits to sanitize, then this won't work.
5775 */
5776 if (aux->alu_state &&
5777 (aux->alu_state != alu_state ||
5778 aux->alu_limit != alu_limit))
5779 return REASON_PATHS;
5780
5781 /* Corresponding fixup done in fixup_bpf_calls(). */
5782 aux->alu_state = alu_state;
5783 aux->alu_limit = alu_limit;
5784 return 0;
5785 }
5786
5787 static int sanitize_val_alu(struct bpf_verifier_env *env,
5788 struct bpf_insn *insn)
5789 {
5790 struct bpf_insn_aux_data *aux = cur_aux(env);
5791
5792 if (can_skip_alu_sanitation(env, insn))
5793 return 0;
5794
5795 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5796 }
5797
5798 static bool sanitize_needed(u8 opcode)
5799 {
5800 return opcode == BPF_ADD || opcode == BPF_SUB;
5801 }
5802
5803 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5804 struct bpf_insn *insn,
5805 const struct bpf_reg_state *ptr_reg,
5806 const struct bpf_reg_state *off_reg,
5807 struct bpf_reg_state *dst_reg,
5808 struct bpf_insn_aux_data *tmp_aux,
5809 const bool commit_window)
5810 {
5811 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : tmp_aux;
5812 struct bpf_verifier_state *vstate = env->cur_state;
5813 bool off_is_imm = tnum_is_const(off_reg->var_off);
5814 bool off_is_neg = off_reg->smin_value < 0;
5815 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5816 u8 opcode = BPF_OP(insn->code);
5817 u32 alu_state, alu_limit;
5818 struct bpf_reg_state tmp;
5819 bool ret;
5820 int err;
5821
5822 if (can_skip_alu_sanitation(env, insn))
5823 return 0;
5824
5825 /* We already marked aux for masking from non-speculative
5826 * paths, thus we got here in the first place. We only care
5827 * to explore bad access from here.
5828 */
5829 if (vstate->speculative)
5830 goto do_sim;
5831
5832 err = retrieve_ptr_limit(ptr_reg, off_reg, &alu_limit, opcode);
5833 if (err < 0)
5834 return err;
5835
5836 if (commit_window) {
5837 /* In commit phase we narrow the masking window based on
5838 * the observed pointer move after the simulated operation.
5839 */
5840 alu_state = tmp_aux->alu_state;
5841 alu_limit = abs(tmp_aux->alu_limit - alu_limit);
5842 } else {
5843 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5844 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
5845 alu_state |= ptr_is_dst_reg ?
5846 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5847 }
5848
5849 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
5850 if (err < 0)
5851 return err;
5852 do_sim:
5853 /* If we're in commit phase, we're done here given we already
5854 * pushed the truncated dst_reg into the speculative verification
5855 * stack.
5856 */
5857 if (commit_window)
5858 return 0;
5859
5860 /* Simulate and find potential out-of-bounds access under
5861 * speculative execution from truncation as a result of
5862 * masking when off was not within expected range. If off
5863 * sits in dst, then we temporarily need to move ptr there
5864 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5865 * for cases where we use K-based arithmetic in one direction
5866 * and truncated reg-based in the other in order to explore
5867 * bad access.
5868 */
5869 if (!ptr_is_dst_reg) {
5870 tmp = *dst_reg;
5871 *dst_reg = *ptr_reg;
5872 }
5873 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
5874 if (!ptr_is_dst_reg && ret)
5875 *dst_reg = tmp;
5876 return !ret ? REASON_STACK : 0;
5877 }
5878
5879 static int sanitize_err(struct bpf_verifier_env *env,
5880 const struct bpf_insn *insn, int reason,
5881 const struct bpf_reg_state *off_reg,
5882 const struct bpf_reg_state *dst_reg)
5883 {
5884 static const char *err = "pointer arithmetic with it prohibited for !root";
5885 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
5886 u32 dst = insn->dst_reg, src = insn->src_reg;
5887
5888 switch (reason) {
5889 case REASON_BOUNDS:
5890 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
5891 off_reg == dst_reg ? dst : src, err);
5892 break;
5893 case REASON_TYPE:
5894 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
5895 off_reg == dst_reg ? src : dst, err);
5896 break;
5897 case REASON_PATHS:
5898 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
5899 dst, op, err);
5900 break;
5901 case REASON_LIMIT:
5902 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
5903 dst, op, err);
5904 break;
5905 case REASON_STACK:
5906 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
5907 dst, err);
5908 break;
5909 default:
5910 verbose(env, "verifier internal error: unknown reason (%d)\n",
5911 reason);
5912 break;
5913 }
5914
5915 return -EACCES;
5916 }
5917
5918 /* check that stack access falls within stack limits and that 'reg' doesn't
5919 * have a variable offset.
5920 *
5921 * Variable offset is prohibited for unprivileged mode for simplicity since it
5922 * requires corresponding support in Spectre masking for stack ALU. See also
5923 * retrieve_ptr_limit().
5924 *
5925 *
5926 * 'off' includes 'reg->off'.
5927 */
5928 static int check_stack_access_for_ptr_arithmetic(
5929 struct bpf_verifier_env *env,
5930 int regno,
5931 const struct bpf_reg_state *reg,
5932 int off)
5933 {
5934 if (!tnum_is_const(reg->var_off)) {
5935 char tn_buf[48];
5936
5937 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5938 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5939 regno, tn_buf, off);
5940 return -EACCES;
5941 }
5942
5943 if (off >= 0 || off < -MAX_BPF_STACK) {
5944 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5945 "prohibited for !root; off=%d\n", regno, off);
5946 return -EACCES;
5947 }
5948
5949 return 0;
5950 }
5951
5952 static int sanitize_check_bounds(struct bpf_verifier_env *env,
5953 const struct bpf_insn *insn,
5954 const struct bpf_reg_state *dst_reg)
5955 {
5956 u32 dst = insn->dst_reg;
5957
5958 /* For unprivileged we require that resulting offset must be in bounds
5959 * in order to be able to sanitize access later on.
5960 */
5961 if (env->bypass_spec_v1)
5962 return 0;
5963
5964 switch (dst_reg->type) {
5965 case PTR_TO_STACK:
5966 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
5967 dst_reg->off + dst_reg->var_off.value))
5968 return -EACCES;
5969 break;
5970 case PTR_TO_MAP_VALUE:
5971 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
5972 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
5973 "prohibited for !root\n", dst);
5974 return -EACCES;
5975 }
5976 break;
5977 default:
5978 break;
5979 }
5980
5981 return 0;
5982 }
5983
5984 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
5985 * Caller should also handle BPF_MOV case separately.
5986 * If we return -EACCES, caller may want to try again treating pointer as a
5987 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5988 */
5989 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5990 struct bpf_insn *insn,
5991 const struct bpf_reg_state *ptr_reg,
5992 const struct bpf_reg_state *off_reg)
5993 {
5994 struct bpf_verifier_state *vstate = env->cur_state;
5995 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5996 struct bpf_reg_state *regs = state->regs, *dst_reg;
5997 bool known = tnum_is_const(off_reg->var_off);
5998 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5999 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6000 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6001 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6002 struct bpf_insn_aux_data tmp_aux = {};
6003 u8 opcode = BPF_OP(insn->code);
6004 u32 dst = insn->dst_reg;
6005 int ret;
6006
6007 dst_reg = &regs[dst];
6008
6009 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6010 smin_val > smax_val || umin_val > umax_val) {
6011 /* Taint dst register if offset had invalid bounds derived from
6012 * e.g. dead branches.
6013 */
6014 __mark_reg_unknown(env, dst_reg);
6015 return 0;
6016 }
6017
6018 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6019 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6020 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6021 __mark_reg_unknown(env, dst_reg);
6022 return 0;
6023 }
6024
6025 verbose(env,
6026 "R%d 32-bit pointer arithmetic prohibited\n",
6027 dst);
6028 return -EACCES;
6029 }
6030
6031 switch (ptr_reg->type) {
6032 case PTR_TO_MAP_VALUE_OR_NULL:
6033 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6034 dst, reg_type_str[ptr_reg->type]);
6035 return -EACCES;
6036 case CONST_PTR_TO_MAP:
6037 /* smin_val represents the known value */
6038 if (known && smin_val == 0 && opcode == BPF_ADD)
6039 break;
6040 fallthrough;
6041 case PTR_TO_PACKET_END:
6042 case PTR_TO_SOCKET:
6043 case PTR_TO_SOCKET_OR_NULL:
6044 case PTR_TO_SOCK_COMMON:
6045 case PTR_TO_SOCK_COMMON_OR_NULL:
6046 case PTR_TO_TCP_SOCK:
6047 case PTR_TO_TCP_SOCK_OR_NULL:
6048 case PTR_TO_XDP_SOCK:
6049 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6050 dst, reg_type_str[ptr_reg->type]);
6051 return -EACCES;
6052 default:
6053 break;
6054 }
6055
6056 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6057 * The id may be overwritten later if we create a new variable offset.
6058 */
6059 dst_reg->type = ptr_reg->type;
6060 dst_reg->id = ptr_reg->id;
6061
6062 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6063 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6064 return -EINVAL;
6065
6066 /* pointer types do not carry 32-bit bounds at the moment. */
6067 __mark_reg32_unbounded(dst_reg);
6068
6069 if (sanitize_needed(opcode)) {
6070 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6071 &tmp_aux, false);
6072 if (ret < 0)
6073 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6074 }
6075
6076 switch (opcode) {
6077 case BPF_ADD:
6078 /* We can take a fixed offset as long as it doesn't overflow
6079 * the s32 'off' field
6080 */
6081 if (known && (ptr_reg->off + smin_val ==
6082 (s64)(s32)(ptr_reg->off + smin_val))) {
6083 /* pointer += K. Accumulate it into fixed offset */
6084 dst_reg->smin_value = smin_ptr;
6085 dst_reg->smax_value = smax_ptr;
6086 dst_reg->umin_value = umin_ptr;
6087 dst_reg->umax_value = umax_ptr;
6088 dst_reg->var_off = ptr_reg->var_off;
6089 dst_reg->off = ptr_reg->off + smin_val;
6090 dst_reg->raw = ptr_reg->raw;
6091 break;
6092 }
6093 /* A new variable offset is created. Note that off_reg->off
6094 * == 0, since it's a scalar.
6095 * dst_reg gets the pointer type and since some positive
6096 * integer value was added to the pointer, give it a new 'id'
6097 * if it's a PTR_TO_PACKET.
6098 * this creates a new 'base' pointer, off_reg (variable) gets
6099 * added into the variable offset, and we copy the fixed offset
6100 * from ptr_reg.
6101 */
6102 if (signed_add_overflows(smin_ptr, smin_val) ||
6103 signed_add_overflows(smax_ptr, smax_val)) {
6104 dst_reg->smin_value = S64_MIN;
6105 dst_reg->smax_value = S64_MAX;
6106 } else {
6107 dst_reg->smin_value = smin_ptr + smin_val;
6108 dst_reg->smax_value = smax_ptr + smax_val;
6109 }
6110 if (umin_ptr + umin_val < umin_ptr ||
6111 umax_ptr + umax_val < umax_ptr) {
6112 dst_reg->umin_value = 0;
6113 dst_reg->umax_value = U64_MAX;
6114 } else {
6115 dst_reg->umin_value = umin_ptr + umin_val;
6116 dst_reg->umax_value = umax_ptr + umax_val;
6117 }
6118 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6119 dst_reg->off = ptr_reg->off;
6120 dst_reg->raw = ptr_reg->raw;
6121 if (reg_is_pkt_pointer(ptr_reg)) {
6122 dst_reg->id = ++env->id_gen;
6123 /* something was added to pkt_ptr, set range to zero */
6124 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6125 }
6126 break;
6127 case BPF_SUB:
6128 if (dst_reg == off_reg) {
6129 /* scalar -= pointer. Creates an unknown scalar */
6130 verbose(env, "R%d tried to subtract pointer from scalar\n",
6131 dst);
6132 return -EACCES;
6133 }
6134 /* We don't allow subtraction from FP, because (according to
6135 * test_verifier.c test "invalid fp arithmetic", JITs might not
6136 * be able to deal with it.
6137 */
6138 if (ptr_reg->type == PTR_TO_STACK) {
6139 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6140 dst);
6141 return -EACCES;
6142 }
6143 if (known && (ptr_reg->off - smin_val ==
6144 (s64)(s32)(ptr_reg->off - smin_val))) {
6145 /* pointer -= K. Subtract it from fixed offset */
6146 dst_reg->smin_value = smin_ptr;
6147 dst_reg->smax_value = smax_ptr;
6148 dst_reg->umin_value = umin_ptr;
6149 dst_reg->umax_value = umax_ptr;
6150 dst_reg->var_off = ptr_reg->var_off;
6151 dst_reg->id = ptr_reg->id;
6152 dst_reg->off = ptr_reg->off - smin_val;
6153 dst_reg->raw = ptr_reg->raw;
6154 break;
6155 }
6156 /* A new variable offset is created. If the subtrahend is known
6157 * nonnegative, then any reg->range we had before is still good.
6158 */
6159 if (signed_sub_overflows(smin_ptr, smax_val) ||
6160 signed_sub_overflows(smax_ptr, smin_val)) {
6161 /* Overflow possible, we know nothing */
6162 dst_reg->smin_value = S64_MIN;
6163 dst_reg->smax_value = S64_MAX;
6164 } else {
6165 dst_reg->smin_value = smin_ptr - smax_val;
6166 dst_reg->smax_value = smax_ptr - smin_val;
6167 }
6168 if (umin_ptr < umax_val) {
6169 /* Overflow possible, we know nothing */
6170 dst_reg->umin_value = 0;
6171 dst_reg->umax_value = U64_MAX;
6172 } else {
6173 /* Cannot overflow (as long as bounds are consistent) */
6174 dst_reg->umin_value = umin_ptr - umax_val;
6175 dst_reg->umax_value = umax_ptr - umin_val;
6176 }
6177 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6178 dst_reg->off = ptr_reg->off;
6179 dst_reg->raw = ptr_reg->raw;
6180 if (reg_is_pkt_pointer(ptr_reg)) {
6181 dst_reg->id = ++env->id_gen;
6182 /* something was added to pkt_ptr, set range to zero */
6183 if (smin_val < 0)
6184 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
6185 }
6186 break;
6187 case BPF_AND:
6188 case BPF_OR:
6189 case BPF_XOR:
6190 /* bitwise ops on pointers are troublesome, prohibit. */
6191 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6192 dst, bpf_alu_string[opcode >> 4]);
6193 return -EACCES;
6194 default:
6195 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6196 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6197 dst, bpf_alu_string[opcode >> 4]);
6198 return -EACCES;
6199 }
6200
6201 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6202 return -EINVAL;
6203
6204 __update_reg_bounds(dst_reg);
6205 __reg_deduce_bounds(dst_reg);
6206 __reg_bound_offset(dst_reg);
6207
6208 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6209 return -EACCES;
6210 if (sanitize_needed(opcode)) {
6211 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6212 &tmp_aux, true);
6213 if (ret < 0)
6214 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6215 }
6216
6217 return 0;
6218 }
6219
6220 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6221 struct bpf_reg_state *src_reg)
6222 {
6223 s32 smin_val = src_reg->s32_min_value;
6224 s32 smax_val = src_reg->s32_max_value;
6225 u32 umin_val = src_reg->u32_min_value;
6226 u32 umax_val = src_reg->u32_max_value;
6227
6228 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6229 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6230 dst_reg->s32_min_value = S32_MIN;
6231 dst_reg->s32_max_value = S32_MAX;
6232 } else {
6233 dst_reg->s32_min_value += smin_val;
6234 dst_reg->s32_max_value += smax_val;
6235 }
6236 if (dst_reg->u32_min_value + umin_val < umin_val ||
6237 dst_reg->u32_max_value + umax_val < umax_val) {
6238 dst_reg->u32_min_value = 0;
6239 dst_reg->u32_max_value = U32_MAX;
6240 } else {
6241 dst_reg->u32_min_value += umin_val;
6242 dst_reg->u32_max_value += umax_val;
6243 }
6244 }
6245
6246 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6247 struct bpf_reg_state *src_reg)
6248 {
6249 s64 smin_val = src_reg->smin_value;
6250 s64 smax_val = src_reg->smax_value;
6251 u64 umin_val = src_reg->umin_value;
6252 u64 umax_val = src_reg->umax_value;
6253
6254 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6255 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6256 dst_reg->smin_value = S64_MIN;
6257 dst_reg->smax_value = S64_MAX;
6258 } else {
6259 dst_reg->smin_value += smin_val;
6260 dst_reg->smax_value += smax_val;
6261 }
6262 if (dst_reg->umin_value + umin_val < umin_val ||
6263 dst_reg->umax_value + umax_val < umax_val) {
6264 dst_reg->umin_value = 0;
6265 dst_reg->umax_value = U64_MAX;
6266 } else {
6267 dst_reg->umin_value += umin_val;
6268 dst_reg->umax_value += umax_val;
6269 }
6270 }
6271
6272 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6273 struct bpf_reg_state *src_reg)
6274 {
6275 s32 smin_val = src_reg->s32_min_value;
6276 s32 smax_val = src_reg->s32_max_value;
6277 u32 umin_val = src_reg->u32_min_value;
6278 u32 umax_val = src_reg->u32_max_value;
6279
6280 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6281 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6282 /* Overflow possible, we know nothing */
6283 dst_reg->s32_min_value = S32_MIN;
6284 dst_reg->s32_max_value = S32_MAX;
6285 } else {
6286 dst_reg->s32_min_value -= smax_val;
6287 dst_reg->s32_max_value -= smin_val;
6288 }
6289 if (dst_reg->u32_min_value < umax_val) {
6290 /* Overflow possible, we know nothing */
6291 dst_reg->u32_min_value = 0;
6292 dst_reg->u32_max_value = U32_MAX;
6293 } else {
6294 /* Cannot overflow (as long as bounds are consistent) */
6295 dst_reg->u32_min_value -= umax_val;
6296 dst_reg->u32_max_value -= umin_val;
6297 }
6298 }
6299
6300 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6301 struct bpf_reg_state *src_reg)
6302 {
6303 s64 smin_val = src_reg->smin_value;
6304 s64 smax_val = src_reg->smax_value;
6305 u64 umin_val = src_reg->umin_value;
6306 u64 umax_val = src_reg->umax_value;
6307
6308 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6309 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6310 /* Overflow possible, we know nothing */
6311 dst_reg->smin_value = S64_MIN;
6312 dst_reg->smax_value = S64_MAX;
6313 } else {
6314 dst_reg->smin_value -= smax_val;
6315 dst_reg->smax_value -= smin_val;
6316 }
6317 if (dst_reg->umin_value < umax_val) {
6318 /* Overflow possible, we know nothing */
6319 dst_reg->umin_value = 0;
6320 dst_reg->umax_value = U64_MAX;
6321 } else {
6322 /* Cannot overflow (as long as bounds are consistent) */
6323 dst_reg->umin_value -= umax_val;
6324 dst_reg->umax_value -= umin_val;
6325 }
6326 }
6327
6328 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6329 struct bpf_reg_state *src_reg)
6330 {
6331 s32 smin_val = src_reg->s32_min_value;
6332 u32 umin_val = src_reg->u32_min_value;
6333 u32 umax_val = src_reg->u32_max_value;
6334
6335 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6336 /* Ain't nobody got time to multiply that sign */
6337 __mark_reg32_unbounded(dst_reg);
6338 return;
6339 }
6340 /* Both values are positive, so we can work with unsigned and
6341 * copy the result to signed (unless it exceeds S32_MAX).
6342 */
6343 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6344 /* Potential overflow, we know nothing */
6345 __mark_reg32_unbounded(dst_reg);
6346 return;
6347 }
6348 dst_reg->u32_min_value *= umin_val;
6349 dst_reg->u32_max_value *= umax_val;
6350 if (dst_reg->u32_max_value > S32_MAX) {
6351 /* Overflow possible, we know nothing */
6352 dst_reg->s32_min_value = S32_MIN;
6353 dst_reg->s32_max_value = S32_MAX;
6354 } else {
6355 dst_reg->s32_min_value = dst_reg->u32_min_value;
6356 dst_reg->s32_max_value = dst_reg->u32_max_value;
6357 }
6358 }
6359
6360 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6361 struct bpf_reg_state *src_reg)
6362 {
6363 s64 smin_val = src_reg->smin_value;
6364 u64 umin_val = src_reg->umin_value;
6365 u64 umax_val = src_reg->umax_value;
6366
6367 if (smin_val < 0 || dst_reg->smin_value < 0) {
6368 /* Ain't nobody got time to multiply that sign */
6369 __mark_reg64_unbounded(dst_reg);
6370 return;
6371 }
6372 /* Both values are positive, so we can work with unsigned and
6373 * copy the result to signed (unless it exceeds S64_MAX).
6374 */
6375 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6376 /* Potential overflow, we know nothing */
6377 __mark_reg64_unbounded(dst_reg);
6378 return;
6379 }
6380 dst_reg->umin_value *= umin_val;
6381 dst_reg->umax_value *= umax_val;
6382 if (dst_reg->umax_value > S64_MAX) {
6383 /* Overflow possible, we know nothing */
6384 dst_reg->smin_value = S64_MIN;
6385 dst_reg->smax_value = S64_MAX;
6386 } else {
6387 dst_reg->smin_value = dst_reg->umin_value;
6388 dst_reg->smax_value = dst_reg->umax_value;
6389 }
6390 }
6391
6392 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6393 struct bpf_reg_state *src_reg)
6394 {
6395 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6396 s32 smin_val = src_reg->s32_min_value;
6397 u32 umax_val = src_reg->u32_max_value;
6398
6399 /* We get our minimum from the var_off, since that's inherently
6400 * bitwise. Our maximum is the minimum of the operands' maxima.
6401 */
6402 dst_reg->u32_min_value = var32_off.value;
6403 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6404 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6405 /* Lose signed bounds when ANDing negative numbers,
6406 * ain't nobody got time for that.
6407 */
6408 dst_reg->s32_min_value = S32_MIN;
6409 dst_reg->s32_max_value = S32_MAX;
6410 } else {
6411 /* ANDing two positives gives a positive, so safe to
6412 * cast result into s64.
6413 */
6414 dst_reg->s32_min_value = dst_reg->u32_min_value;
6415 dst_reg->s32_max_value = dst_reg->u32_max_value;
6416 }
6417
6418 }
6419
6420 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6421 struct bpf_reg_state *src_reg)
6422 {
6423 bool src_known = tnum_is_const(src_reg->var_off);
6424 bool dst_known = tnum_is_const(dst_reg->var_off);
6425 s64 smin_val = src_reg->smin_value;
6426 u64 umax_val = src_reg->umax_value;
6427
6428 if (src_known && dst_known) {
6429 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6430 return;
6431 }
6432
6433 /* We get our minimum from the var_off, since that's inherently
6434 * bitwise. Our maximum is the minimum of the operands' maxima.
6435 */
6436 dst_reg->umin_value = dst_reg->var_off.value;
6437 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6438 if (dst_reg->smin_value < 0 || smin_val < 0) {
6439 /* Lose signed bounds when ANDing negative numbers,
6440 * ain't nobody got time for that.
6441 */
6442 dst_reg->smin_value = S64_MIN;
6443 dst_reg->smax_value = S64_MAX;
6444 } else {
6445 /* ANDing two positives gives a positive, so safe to
6446 * cast result into s64.
6447 */
6448 dst_reg->smin_value = dst_reg->umin_value;
6449 dst_reg->smax_value = dst_reg->umax_value;
6450 }
6451 /* We may learn something more from the var_off */
6452 __update_reg_bounds(dst_reg);
6453 }
6454
6455 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6456 struct bpf_reg_state *src_reg)
6457 {
6458 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6459 s32 smin_val = src_reg->s32_min_value;
6460 u32 umin_val = src_reg->u32_min_value;
6461
6462 /* We get our maximum from the var_off, and our minimum is the
6463 * maximum of the operands' minima
6464 */
6465 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6466 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6467 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6468 /* Lose signed bounds when ORing negative numbers,
6469 * ain't nobody got time for that.
6470 */
6471 dst_reg->s32_min_value = S32_MIN;
6472 dst_reg->s32_max_value = S32_MAX;
6473 } else {
6474 /* ORing two positives gives a positive, so safe to
6475 * cast result into s64.
6476 */
6477 dst_reg->s32_min_value = dst_reg->u32_min_value;
6478 dst_reg->s32_max_value = dst_reg->u32_max_value;
6479 }
6480 }
6481
6482 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6483 struct bpf_reg_state *src_reg)
6484 {
6485 bool src_known = tnum_is_const(src_reg->var_off);
6486 bool dst_known = tnum_is_const(dst_reg->var_off);
6487 s64 smin_val = src_reg->smin_value;
6488 u64 umin_val = src_reg->umin_value;
6489
6490 if (src_known && dst_known) {
6491 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6492 return;
6493 }
6494
6495 /* We get our maximum from the var_off, and our minimum is the
6496 * maximum of the operands' minima
6497 */
6498 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6499 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6500 if (dst_reg->smin_value < 0 || smin_val < 0) {
6501 /* Lose signed bounds when ORing negative numbers,
6502 * ain't nobody got time for that.
6503 */
6504 dst_reg->smin_value = S64_MIN;
6505 dst_reg->smax_value = S64_MAX;
6506 } else {
6507 /* ORing two positives gives a positive, so safe to
6508 * cast result into s64.
6509 */
6510 dst_reg->smin_value = dst_reg->umin_value;
6511 dst_reg->smax_value = dst_reg->umax_value;
6512 }
6513 /* We may learn something more from the var_off */
6514 __update_reg_bounds(dst_reg);
6515 }
6516
6517 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6518 struct bpf_reg_state *src_reg)
6519 {
6520 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6521 s32 smin_val = src_reg->s32_min_value;
6522
6523 /* We get both minimum and maximum from the var32_off. */
6524 dst_reg->u32_min_value = var32_off.value;
6525 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6526
6527 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6528 /* XORing two positive sign numbers gives a positive,
6529 * so safe to cast u32 result into s32.
6530 */
6531 dst_reg->s32_min_value = dst_reg->u32_min_value;
6532 dst_reg->s32_max_value = dst_reg->u32_max_value;
6533 } else {
6534 dst_reg->s32_min_value = S32_MIN;
6535 dst_reg->s32_max_value = S32_MAX;
6536 }
6537 }
6538
6539 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6540 struct bpf_reg_state *src_reg)
6541 {
6542 bool src_known = tnum_is_const(src_reg->var_off);
6543 bool dst_known = tnum_is_const(dst_reg->var_off);
6544 s64 smin_val = src_reg->smin_value;
6545
6546 if (src_known && dst_known) {
6547 /* dst_reg->var_off.value has been updated earlier */
6548 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6549 return;
6550 }
6551
6552 /* We get both minimum and maximum from the var_off. */
6553 dst_reg->umin_value = dst_reg->var_off.value;
6554 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6555
6556 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6557 /* XORing two positive sign numbers gives a positive,
6558 * so safe to cast u64 result into s64.
6559 */
6560 dst_reg->smin_value = dst_reg->umin_value;
6561 dst_reg->smax_value = dst_reg->umax_value;
6562 } else {
6563 dst_reg->smin_value = S64_MIN;
6564 dst_reg->smax_value = S64_MAX;
6565 }
6566
6567 __update_reg_bounds(dst_reg);
6568 }
6569
6570 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6571 u64 umin_val, u64 umax_val)
6572 {
6573 /* We lose all sign bit information (except what we can pick
6574 * up from var_off)
6575 */
6576 dst_reg->s32_min_value = S32_MIN;
6577 dst_reg->s32_max_value = S32_MAX;
6578 /* If we might shift our top bit out, then we know nothing */
6579 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6580 dst_reg->u32_min_value = 0;
6581 dst_reg->u32_max_value = U32_MAX;
6582 } else {
6583 dst_reg->u32_min_value <<= umin_val;
6584 dst_reg->u32_max_value <<= umax_val;
6585 }
6586 }
6587
6588 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6589 struct bpf_reg_state *src_reg)
6590 {
6591 u32 umax_val = src_reg->u32_max_value;
6592 u32 umin_val = src_reg->u32_min_value;
6593 /* u32 alu operation will zext upper bits */
6594 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6595
6596 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6597 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6598 /* Not required but being careful mark reg64 bounds as unknown so
6599 * that we are forced to pick them up from tnum and zext later and
6600 * if some path skips this step we are still safe.
6601 */
6602 __mark_reg64_unbounded(dst_reg);
6603 __update_reg32_bounds(dst_reg);
6604 }
6605
6606 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6607 u64 umin_val, u64 umax_val)
6608 {
6609 /* Special case <<32 because it is a common compiler pattern to sign
6610 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6611 * positive we know this shift will also be positive so we can track
6612 * bounds correctly. Otherwise we lose all sign bit information except
6613 * what we can pick up from var_off. Perhaps we can generalize this
6614 * later to shifts of any length.
6615 */
6616 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6617 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6618 else
6619 dst_reg->smax_value = S64_MAX;
6620
6621 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6622 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6623 else
6624 dst_reg->smin_value = S64_MIN;
6625
6626 /* If we might shift our top bit out, then we know nothing */
6627 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6628 dst_reg->umin_value = 0;
6629 dst_reg->umax_value = U64_MAX;
6630 } else {
6631 dst_reg->umin_value <<= umin_val;
6632 dst_reg->umax_value <<= umax_val;
6633 }
6634 }
6635
6636 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6637 struct bpf_reg_state *src_reg)
6638 {
6639 u64 umax_val = src_reg->umax_value;
6640 u64 umin_val = src_reg->umin_value;
6641
6642 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6643 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6644 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6645
6646 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6647 /* We may learn something more from the var_off */
6648 __update_reg_bounds(dst_reg);
6649 }
6650
6651 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6652 struct bpf_reg_state *src_reg)
6653 {
6654 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6655 u32 umax_val = src_reg->u32_max_value;
6656 u32 umin_val = src_reg->u32_min_value;
6657
6658 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6659 * be negative, then either:
6660 * 1) src_reg might be zero, so the sign bit of the result is
6661 * unknown, so we lose our signed bounds
6662 * 2) it's known negative, thus the unsigned bounds capture the
6663 * signed bounds
6664 * 3) the signed bounds cross zero, so they tell us nothing
6665 * about the result
6666 * If the value in dst_reg is known nonnegative, then again the
6667 * unsigned bounts capture the signed bounds.
6668 * Thus, in all cases it suffices to blow away our signed bounds
6669 * and rely on inferring new ones from the unsigned bounds and
6670 * var_off of the result.
6671 */
6672 dst_reg->s32_min_value = S32_MIN;
6673 dst_reg->s32_max_value = S32_MAX;
6674
6675 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6676 dst_reg->u32_min_value >>= umax_val;
6677 dst_reg->u32_max_value >>= umin_val;
6678
6679 __mark_reg64_unbounded(dst_reg);
6680 __update_reg32_bounds(dst_reg);
6681 }
6682
6683 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6684 struct bpf_reg_state *src_reg)
6685 {
6686 u64 umax_val = src_reg->umax_value;
6687 u64 umin_val = src_reg->umin_value;
6688
6689 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6690 * be negative, then either:
6691 * 1) src_reg might be zero, so the sign bit of the result is
6692 * unknown, so we lose our signed bounds
6693 * 2) it's known negative, thus the unsigned bounds capture the
6694 * signed bounds
6695 * 3) the signed bounds cross zero, so they tell us nothing
6696 * about the result
6697 * If the value in dst_reg is known nonnegative, then again the
6698 * unsigned bounts capture the signed bounds.
6699 * Thus, in all cases it suffices to blow away our signed bounds
6700 * and rely on inferring new ones from the unsigned bounds and
6701 * var_off of the result.
6702 */
6703 dst_reg->smin_value = S64_MIN;
6704 dst_reg->smax_value = S64_MAX;
6705 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6706 dst_reg->umin_value >>= umax_val;
6707 dst_reg->umax_value >>= umin_val;
6708
6709 /* Its not easy to operate on alu32 bounds here because it depends
6710 * on bits being shifted in. Take easy way out and mark unbounded
6711 * so we can recalculate later from tnum.
6712 */
6713 __mark_reg32_unbounded(dst_reg);
6714 __update_reg_bounds(dst_reg);
6715 }
6716
6717 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6718 struct bpf_reg_state *src_reg)
6719 {
6720 u64 umin_val = src_reg->u32_min_value;
6721
6722 /* Upon reaching here, src_known is true and
6723 * umax_val is equal to umin_val.
6724 */
6725 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6726 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6727
6728 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6729
6730 /* blow away the dst_reg umin_value/umax_value and rely on
6731 * dst_reg var_off to refine the result.
6732 */
6733 dst_reg->u32_min_value = 0;
6734 dst_reg->u32_max_value = U32_MAX;
6735
6736 __mark_reg64_unbounded(dst_reg);
6737 __update_reg32_bounds(dst_reg);
6738 }
6739
6740 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6741 struct bpf_reg_state *src_reg)
6742 {
6743 u64 umin_val = src_reg->umin_value;
6744
6745 /* Upon reaching here, src_known is true and umax_val is equal
6746 * to umin_val.
6747 */
6748 dst_reg->smin_value >>= umin_val;
6749 dst_reg->smax_value >>= umin_val;
6750
6751 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6752
6753 /* blow away the dst_reg umin_value/umax_value and rely on
6754 * dst_reg var_off to refine the result.
6755 */
6756 dst_reg->umin_value = 0;
6757 dst_reg->umax_value = U64_MAX;
6758
6759 /* Its not easy to operate on alu32 bounds here because it depends
6760 * on bits being shifted in from upper 32-bits. Take easy way out
6761 * and mark unbounded so we can recalculate later from tnum.
6762 */
6763 __mark_reg32_unbounded(dst_reg);
6764 __update_reg_bounds(dst_reg);
6765 }
6766
6767 /* WARNING: This function does calculations on 64-bit values, but the actual
6768 * execution may occur on 32-bit values. Therefore, things like bitshifts
6769 * need extra checks in the 32-bit case.
6770 */
6771 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6772 struct bpf_insn *insn,
6773 struct bpf_reg_state *dst_reg,
6774 struct bpf_reg_state src_reg)
6775 {
6776 struct bpf_reg_state *regs = cur_regs(env);
6777 u8 opcode = BPF_OP(insn->code);
6778 bool src_known;
6779 s64 smin_val, smax_val;
6780 u64 umin_val, umax_val;
6781 s32 s32_min_val, s32_max_val;
6782 u32 u32_min_val, u32_max_val;
6783 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
6784 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
6785 int ret;
6786
6787 smin_val = src_reg.smin_value;
6788 smax_val = src_reg.smax_value;
6789 umin_val = src_reg.umin_value;
6790 umax_val = src_reg.umax_value;
6791
6792 s32_min_val = src_reg.s32_min_value;
6793 s32_max_val = src_reg.s32_max_value;
6794 u32_min_val = src_reg.u32_min_value;
6795 u32_max_val = src_reg.u32_max_value;
6796
6797 if (alu32) {
6798 src_known = tnum_subreg_is_const(src_reg.var_off);
6799 if ((src_known &&
6800 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6801 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6802 /* Taint dst register if offset had invalid bounds
6803 * derived from e.g. dead branches.
6804 */
6805 __mark_reg_unknown(env, dst_reg);
6806 return 0;
6807 }
6808 } else {
6809 src_known = tnum_is_const(src_reg.var_off);
6810 if ((src_known &&
6811 (smin_val != smax_val || umin_val != umax_val)) ||
6812 smin_val > smax_val || umin_val > umax_val) {
6813 /* Taint dst register if offset had invalid bounds
6814 * derived from e.g. dead branches.
6815 */
6816 __mark_reg_unknown(env, dst_reg);
6817 return 0;
6818 }
6819 }
6820
6821 if (!src_known &&
6822 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
6823 __mark_reg_unknown(env, dst_reg);
6824 return 0;
6825 }
6826
6827 if (sanitize_needed(opcode)) {
6828 ret = sanitize_val_alu(env, insn);
6829 if (ret < 0)
6830 return sanitize_err(env, insn, ret, NULL, NULL);
6831 }
6832
6833 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6834 * There are two classes of instructions: The first class we track both
6835 * alu32 and alu64 sign/unsigned bounds independently this provides the
6836 * greatest amount of precision when alu operations are mixed with jmp32
6837 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6838 * and BPF_OR. This is possible because these ops have fairly easy to
6839 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6840 * See alu32 verifier tests for examples. The second class of
6841 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6842 * with regards to tracking sign/unsigned bounds because the bits may
6843 * cross subreg boundaries in the alu64 case. When this happens we mark
6844 * the reg unbounded in the subreg bound space and use the resulting
6845 * tnum to calculate an approximation of the sign/unsigned bounds.
6846 */
6847 switch (opcode) {
6848 case BPF_ADD:
6849 scalar32_min_max_add(dst_reg, &src_reg);
6850 scalar_min_max_add(dst_reg, &src_reg);
6851 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
6852 break;
6853 case BPF_SUB:
6854 scalar32_min_max_sub(dst_reg, &src_reg);
6855 scalar_min_max_sub(dst_reg, &src_reg);
6856 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
6857 break;
6858 case BPF_MUL:
6859 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6860 scalar32_min_max_mul(dst_reg, &src_reg);
6861 scalar_min_max_mul(dst_reg, &src_reg);
6862 break;
6863 case BPF_AND:
6864 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6865 scalar32_min_max_and(dst_reg, &src_reg);
6866 scalar_min_max_and(dst_reg, &src_reg);
6867 break;
6868 case BPF_OR:
6869 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6870 scalar32_min_max_or(dst_reg, &src_reg);
6871 scalar_min_max_or(dst_reg, &src_reg);
6872 break;
6873 case BPF_XOR:
6874 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6875 scalar32_min_max_xor(dst_reg, &src_reg);
6876 scalar_min_max_xor(dst_reg, &src_reg);
6877 break;
6878 case BPF_LSH:
6879 if (umax_val >= insn_bitness) {
6880 /* Shifts greater than 31 or 63 are undefined.
6881 * This includes shifts by a negative number.
6882 */
6883 mark_reg_unknown(env, regs, insn->dst_reg);
6884 break;
6885 }
6886 if (alu32)
6887 scalar32_min_max_lsh(dst_reg, &src_reg);
6888 else
6889 scalar_min_max_lsh(dst_reg, &src_reg);
6890 break;
6891 case BPF_RSH:
6892 if (umax_val >= insn_bitness) {
6893 /* Shifts greater than 31 or 63 are undefined.
6894 * This includes shifts by a negative number.
6895 */
6896 mark_reg_unknown(env, regs, insn->dst_reg);
6897 break;
6898 }
6899 if (alu32)
6900 scalar32_min_max_rsh(dst_reg, &src_reg);
6901 else
6902 scalar_min_max_rsh(dst_reg, &src_reg);
6903 break;
6904 case BPF_ARSH:
6905 if (umax_val >= insn_bitness) {
6906 /* Shifts greater than 31 or 63 are undefined.
6907 * This includes shifts by a negative number.
6908 */
6909 mark_reg_unknown(env, regs, insn->dst_reg);
6910 break;
6911 }
6912 if (alu32)
6913 scalar32_min_max_arsh(dst_reg, &src_reg);
6914 else
6915 scalar_min_max_arsh(dst_reg, &src_reg);
6916 break;
6917 default:
6918 mark_reg_unknown(env, regs, insn->dst_reg);
6919 break;
6920 }
6921
6922 /* ALU32 ops are zero extended into 64bit register */
6923 if (alu32)
6924 zext_32_to_64(dst_reg);
6925
6926 __update_reg_bounds(dst_reg);
6927 __reg_deduce_bounds(dst_reg);
6928 __reg_bound_offset(dst_reg);
6929 return 0;
6930 }
6931
6932 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6933 * and var_off.
6934 */
6935 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6936 struct bpf_insn *insn)
6937 {
6938 struct bpf_verifier_state *vstate = env->cur_state;
6939 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6940 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
6941 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6942 u8 opcode = BPF_OP(insn->code);
6943 int err;
6944
6945 dst_reg = &regs[insn->dst_reg];
6946 src_reg = NULL;
6947 if (dst_reg->type != SCALAR_VALUE)
6948 ptr_reg = dst_reg;
6949 else
6950 /* Make sure ID is cleared otherwise dst_reg min/max could be
6951 * incorrectly propagated into other registers by find_equal_scalars()
6952 */
6953 dst_reg->id = 0;
6954 if (BPF_SRC(insn->code) == BPF_X) {
6955 src_reg = &regs[insn->src_reg];
6956 if (src_reg->type != SCALAR_VALUE) {
6957 if (dst_reg->type != SCALAR_VALUE) {
6958 /* Combining two pointers by any ALU op yields
6959 * an arbitrary scalar. Disallow all math except
6960 * pointer subtraction
6961 */
6962 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6963 mark_reg_unknown(env, regs, insn->dst_reg);
6964 return 0;
6965 }
6966 verbose(env, "R%d pointer %s pointer prohibited\n",
6967 insn->dst_reg,
6968 bpf_alu_string[opcode >> 4]);
6969 return -EACCES;
6970 } else {
6971 /* scalar += pointer
6972 * This is legal, but we have to reverse our
6973 * src/dest handling in computing the range
6974 */
6975 err = mark_chain_precision(env, insn->dst_reg);
6976 if (err)
6977 return err;
6978 return adjust_ptr_min_max_vals(env, insn,
6979 src_reg, dst_reg);
6980 }
6981 } else if (ptr_reg) {
6982 /* pointer += scalar */
6983 err = mark_chain_precision(env, insn->src_reg);
6984 if (err)
6985 return err;
6986 return adjust_ptr_min_max_vals(env, insn,
6987 dst_reg, src_reg);
6988 }
6989 } else {
6990 /* Pretend the src is a reg with a known value, since we only
6991 * need to be able to read from this state.
6992 */
6993 off_reg.type = SCALAR_VALUE;
6994 __mark_reg_known(&off_reg, insn->imm);
6995 src_reg = &off_reg;
6996 if (ptr_reg) /* pointer += K */
6997 return adjust_ptr_min_max_vals(env, insn,
6998 ptr_reg, src_reg);
6999 }
7000
7001 /* Got here implies adding two SCALAR_VALUEs */
7002 if (WARN_ON_ONCE(ptr_reg)) {
7003 print_verifier_state(env, state);
7004 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7005 return -EINVAL;
7006 }
7007 if (WARN_ON(!src_reg)) {
7008 print_verifier_state(env, state);
7009 verbose(env, "verifier internal error: no src_reg\n");
7010 return -EINVAL;
7011 }
7012 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7013 }
7014
7015 /* check validity of 32-bit and 64-bit arithmetic operations */
7016 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7017 {
7018 struct bpf_reg_state *regs = cur_regs(env);
7019 u8 opcode = BPF_OP(insn->code);
7020 int err;
7021
7022 if (opcode == BPF_END || opcode == BPF_NEG) {
7023 if (opcode == BPF_NEG) {
7024 if (BPF_SRC(insn->code) != 0 ||
7025 insn->src_reg != BPF_REG_0 ||
7026 insn->off != 0 || insn->imm != 0) {
7027 verbose(env, "BPF_NEG uses reserved fields\n");
7028 return -EINVAL;
7029 }
7030 } else {
7031 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7032 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7033 BPF_CLASS(insn->code) == BPF_ALU64) {
7034 verbose(env, "BPF_END uses reserved fields\n");
7035 return -EINVAL;
7036 }
7037 }
7038
7039 /* check src operand */
7040 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7041 if (err)
7042 return err;
7043
7044 if (is_pointer_value(env, insn->dst_reg)) {
7045 verbose(env, "R%d pointer arithmetic prohibited\n",
7046 insn->dst_reg);
7047 return -EACCES;
7048 }
7049
7050 /* check dest operand */
7051 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7052 if (err)
7053 return err;
7054
7055 } else if (opcode == BPF_MOV) {
7056
7057 if (BPF_SRC(insn->code) == BPF_X) {
7058 if (insn->imm != 0 || insn->off != 0) {
7059 verbose(env, "BPF_MOV uses reserved fields\n");
7060 return -EINVAL;
7061 }
7062
7063 /* check src operand */
7064 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7065 if (err)
7066 return err;
7067 } else {
7068 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7069 verbose(env, "BPF_MOV uses reserved fields\n");
7070 return -EINVAL;
7071 }
7072 }
7073
7074 /* check dest operand, mark as required later */
7075 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7076 if (err)
7077 return err;
7078
7079 if (BPF_SRC(insn->code) == BPF_X) {
7080 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7081 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7082
7083 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7084 /* case: R1 = R2
7085 * copy register state to dest reg
7086 */
7087 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7088 /* Assign src and dst registers the same ID
7089 * that will be used by find_equal_scalars()
7090 * to propagate min/max range.
7091 */
7092 src_reg->id = ++env->id_gen;
7093 *dst_reg = *src_reg;
7094 dst_reg->live |= REG_LIVE_WRITTEN;
7095 dst_reg->subreg_def = DEF_NOT_SUBREG;
7096 } else {
7097 /* R1 = (u32) R2 */
7098 if (is_pointer_value(env, insn->src_reg)) {
7099 verbose(env,
7100 "R%d partial copy of pointer\n",
7101 insn->src_reg);
7102 return -EACCES;
7103 } else if (src_reg->type == SCALAR_VALUE) {
7104 *dst_reg = *src_reg;
7105 /* Make sure ID is cleared otherwise
7106 * dst_reg min/max could be incorrectly
7107 * propagated into src_reg by find_equal_scalars()
7108 */
7109 dst_reg->id = 0;
7110 dst_reg->live |= REG_LIVE_WRITTEN;
7111 dst_reg->subreg_def = env->insn_idx + 1;
7112 } else {
7113 mark_reg_unknown(env, regs,
7114 insn->dst_reg);
7115 }
7116 zext_32_to_64(dst_reg);
7117 }
7118 } else {
7119 /* case: R = imm
7120 * remember the value we stored into this reg
7121 */
7122 /* clear any state __mark_reg_known doesn't set */
7123 mark_reg_unknown(env, regs, insn->dst_reg);
7124 regs[insn->dst_reg].type = SCALAR_VALUE;
7125 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7126 __mark_reg_known(regs + insn->dst_reg,
7127 insn->imm);
7128 } else {
7129 __mark_reg_known(regs + insn->dst_reg,
7130 (u32)insn->imm);
7131 }
7132 }
7133
7134 } else if (opcode > BPF_END) {
7135 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7136 return -EINVAL;
7137
7138 } else { /* all other ALU ops: and, sub, xor, add, ... */
7139
7140 if (BPF_SRC(insn->code) == BPF_X) {
7141 if (insn->imm != 0 || insn->off != 0) {
7142 verbose(env, "BPF_ALU uses reserved fields\n");
7143 return -EINVAL;
7144 }
7145 /* check src1 operand */
7146 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7147 if (err)
7148 return err;
7149 } else {
7150 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7151 verbose(env, "BPF_ALU uses reserved fields\n");
7152 return -EINVAL;
7153 }
7154 }
7155
7156 /* check src2 operand */
7157 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7158 if (err)
7159 return err;
7160
7161 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7162 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7163 verbose(env, "div by zero\n");
7164 return -EINVAL;
7165 }
7166
7167 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7168 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7169 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7170
7171 if (insn->imm < 0 || insn->imm >= size) {
7172 verbose(env, "invalid shift %d\n", insn->imm);
7173 return -EINVAL;
7174 }
7175 }
7176
7177 /* check dest operand */
7178 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7179 if (err)
7180 return err;
7181
7182 return adjust_reg_min_max_vals(env, insn);
7183 }
7184
7185 return 0;
7186 }
7187
7188 static void __find_good_pkt_pointers(struct bpf_func_state *state,
7189 struct bpf_reg_state *dst_reg,
7190 enum bpf_reg_type type, int new_range)
7191 {
7192 struct bpf_reg_state *reg;
7193 int i;
7194
7195 for (i = 0; i < MAX_BPF_REG; i++) {
7196 reg = &state->regs[i];
7197 if (reg->type == type && reg->id == dst_reg->id)
7198 /* keep the maximum range already checked */
7199 reg->range = max(reg->range, new_range);
7200 }
7201
7202 bpf_for_each_spilled_reg(i, state, reg) {
7203 if (!reg)
7204 continue;
7205 if (reg->type == type && reg->id == dst_reg->id)
7206 reg->range = max(reg->range, new_range);
7207 }
7208 }
7209
7210 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7211 struct bpf_reg_state *dst_reg,
7212 enum bpf_reg_type type,
7213 bool range_right_open)
7214 {
7215 int new_range, i;
7216
7217 if (dst_reg->off < 0 ||
7218 (dst_reg->off == 0 && range_right_open))
7219 /* This doesn't give us any range */
7220 return;
7221
7222 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7223 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7224 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7225 * than pkt_end, but that's because it's also less than pkt.
7226 */
7227 return;
7228
7229 new_range = dst_reg->off;
7230 if (range_right_open)
7231 new_range--;
7232
7233 /* Examples for register markings:
7234 *
7235 * pkt_data in dst register:
7236 *
7237 * r2 = r3;
7238 * r2 += 8;
7239 * if (r2 > pkt_end) goto <handle exception>
7240 * <access okay>
7241 *
7242 * r2 = r3;
7243 * r2 += 8;
7244 * if (r2 < pkt_end) goto <access okay>
7245 * <handle exception>
7246 *
7247 * Where:
7248 * r2 == dst_reg, pkt_end == src_reg
7249 * r2=pkt(id=n,off=8,r=0)
7250 * r3=pkt(id=n,off=0,r=0)
7251 *
7252 * pkt_data in src register:
7253 *
7254 * r2 = r3;
7255 * r2 += 8;
7256 * if (pkt_end >= r2) goto <access okay>
7257 * <handle exception>
7258 *
7259 * r2 = r3;
7260 * r2 += 8;
7261 * if (pkt_end <= r2) goto <handle exception>
7262 * <access okay>
7263 *
7264 * Where:
7265 * pkt_end == dst_reg, r2 == src_reg
7266 * r2=pkt(id=n,off=8,r=0)
7267 * r3=pkt(id=n,off=0,r=0)
7268 *
7269 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7270 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7271 * and [r3, r3 + 8-1) respectively is safe to access depending on
7272 * the check.
7273 */
7274
7275 /* If our ids match, then we must have the same max_value. And we
7276 * don't care about the other reg's fixed offset, since if it's too big
7277 * the range won't allow anything.
7278 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7279 */
7280 for (i = 0; i <= vstate->curframe; i++)
7281 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7282 new_range);
7283 }
7284
7285 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7286 {
7287 struct tnum subreg = tnum_subreg(reg->var_off);
7288 s32 sval = (s32)val;
7289
7290 switch (opcode) {
7291 case BPF_JEQ:
7292 if (tnum_is_const(subreg))
7293 return !!tnum_equals_const(subreg, val);
7294 break;
7295 case BPF_JNE:
7296 if (tnum_is_const(subreg))
7297 return !tnum_equals_const(subreg, val);
7298 break;
7299 case BPF_JSET:
7300 if ((~subreg.mask & subreg.value) & val)
7301 return 1;
7302 if (!((subreg.mask | subreg.value) & val))
7303 return 0;
7304 break;
7305 case BPF_JGT:
7306 if (reg->u32_min_value > val)
7307 return 1;
7308 else if (reg->u32_max_value <= val)
7309 return 0;
7310 break;
7311 case BPF_JSGT:
7312 if (reg->s32_min_value > sval)
7313 return 1;
7314 else if (reg->s32_max_value <= sval)
7315 return 0;
7316 break;
7317 case BPF_JLT:
7318 if (reg->u32_max_value < val)
7319 return 1;
7320 else if (reg->u32_min_value >= val)
7321 return 0;
7322 break;
7323 case BPF_JSLT:
7324 if (reg->s32_max_value < sval)
7325 return 1;
7326 else if (reg->s32_min_value >= sval)
7327 return 0;
7328 break;
7329 case BPF_JGE:
7330 if (reg->u32_min_value >= val)
7331 return 1;
7332 else if (reg->u32_max_value < val)
7333 return 0;
7334 break;
7335 case BPF_JSGE:
7336 if (reg->s32_min_value >= sval)
7337 return 1;
7338 else if (reg->s32_max_value < sval)
7339 return 0;
7340 break;
7341 case BPF_JLE:
7342 if (reg->u32_max_value <= val)
7343 return 1;
7344 else if (reg->u32_min_value > val)
7345 return 0;
7346 break;
7347 case BPF_JSLE:
7348 if (reg->s32_max_value <= sval)
7349 return 1;
7350 else if (reg->s32_min_value > sval)
7351 return 0;
7352 break;
7353 }
7354
7355 return -1;
7356 }
7357
7358
7359 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7360 {
7361 s64 sval = (s64)val;
7362
7363 switch (opcode) {
7364 case BPF_JEQ:
7365 if (tnum_is_const(reg->var_off))
7366 return !!tnum_equals_const(reg->var_off, val);
7367 break;
7368 case BPF_JNE:
7369 if (tnum_is_const(reg->var_off))
7370 return !tnum_equals_const(reg->var_off, val);
7371 break;
7372 case BPF_JSET:
7373 if ((~reg->var_off.mask & reg->var_off.value) & val)
7374 return 1;
7375 if (!((reg->var_off.mask | reg->var_off.value) & val))
7376 return 0;
7377 break;
7378 case BPF_JGT:
7379 if (reg->umin_value > val)
7380 return 1;
7381 else if (reg->umax_value <= val)
7382 return 0;
7383 break;
7384 case BPF_JSGT:
7385 if (reg->smin_value > sval)
7386 return 1;
7387 else if (reg->smax_value <= sval)
7388 return 0;
7389 break;
7390 case BPF_JLT:
7391 if (reg->umax_value < val)
7392 return 1;
7393 else if (reg->umin_value >= val)
7394 return 0;
7395 break;
7396 case BPF_JSLT:
7397 if (reg->smax_value < sval)
7398 return 1;
7399 else if (reg->smin_value >= sval)
7400 return 0;
7401 break;
7402 case BPF_JGE:
7403 if (reg->umin_value >= val)
7404 return 1;
7405 else if (reg->umax_value < val)
7406 return 0;
7407 break;
7408 case BPF_JSGE:
7409 if (reg->smin_value >= sval)
7410 return 1;
7411 else if (reg->smax_value < sval)
7412 return 0;
7413 break;
7414 case BPF_JLE:
7415 if (reg->umax_value <= val)
7416 return 1;
7417 else if (reg->umin_value > val)
7418 return 0;
7419 break;
7420 case BPF_JSLE:
7421 if (reg->smax_value <= sval)
7422 return 1;
7423 else if (reg->smin_value > sval)
7424 return 0;
7425 break;
7426 }
7427
7428 return -1;
7429 }
7430
7431 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7432 * and return:
7433 * 1 - branch will be taken and "goto target" will be executed
7434 * 0 - branch will not be taken and fall-through to next insn
7435 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7436 * range [0,10]
7437 */
7438 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7439 bool is_jmp32)
7440 {
7441 if (__is_pointer_value(false, reg)) {
7442 if (!reg_type_not_null(reg->type))
7443 return -1;
7444
7445 /* If pointer is valid tests against zero will fail so we can
7446 * use this to direct branch taken.
7447 */
7448 if (val != 0)
7449 return -1;
7450
7451 switch (opcode) {
7452 case BPF_JEQ:
7453 return 0;
7454 case BPF_JNE:
7455 return 1;
7456 default:
7457 return -1;
7458 }
7459 }
7460
7461 if (is_jmp32)
7462 return is_branch32_taken(reg, val, opcode);
7463 return is_branch64_taken(reg, val, opcode);
7464 }
7465
7466 static int flip_opcode(u32 opcode)
7467 {
7468 /* How can we transform "a <op> b" into "b <op> a"? */
7469 static const u8 opcode_flip[16] = {
7470 /* these stay the same */
7471 [BPF_JEQ >> 4] = BPF_JEQ,
7472 [BPF_JNE >> 4] = BPF_JNE,
7473 [BPF_JSET >> 4] = BPF_JSET,
7474 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7475 [BPF_JGE >> 4] = BPF_JLE,
7476 [BPF_JGT >> 4] = BPF_JLT,
7477 [BPF_JLE >> 4] = BPF_JGE,
7478 [BPF_JLT >> 4] = BPF_JGT,
7479 [BPF_JSGE >> 4] = BPF_JSLE,
7480 [BPF_JSGT >> 4] = BPF_JSLT,
7481 [BPF_JSLE >> 4] = BPF_JSGE,
7482 [BPF_JSLT >> 4] = BPF_JSGT
7483 };
7484 return opcode_flip[opcode >> 4];
7485 }
7486
7487 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7488 struct bpf_reg_state *src_reg,
7489 u8 opcode)
7490 {
7491 struct bpf_reg_state *pkt;
7492
7493 if (src_reg->type == PTR_TO_PACKET_END) {
7494 pkt = dst_reg;
7495 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7496 pkt = src_reg;
7497 opcode = flip_opcode(opcode);
7498 } else {
7499 return -1;
7500 }
7501
7502 if (pkt->range >= 0)
7503 return -1;
7504
7505 switch (opcode) {
7506 case BPF_JLE:
7507 /* pkt <= pkt_end */
7508 fallthrough;
7509 case BPF_JGT:
7510 /* pkt > pkt_end */
7511 if (pkt->range == BEYOND_PKT_END)
7512 /* pkt has at last one extra byte beyond pkt_end */
7513 return opcode == BPF_JGT;
7514 break;
7515 case BPF_JLT:
7516 /* pkt < pkt_end */
7517 fallthrough;
7518 case BPF_JGE:
7519 /* pkt >= pkt_end */
7520 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7521 return opcode == BPF_JGE;
7522 break;
7523 }
7524 return -1;
7525 }
7526
7527 /* Adjusts the register min/max values in the case that the dst_reg is the
7528 * variable register that we are working on, and src_reg is a constant or we're
7529 * simply doing a BPF_K check.
7530 * In JEQ/JNE cases we also adjust the var_off values.
7531 */
7532 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7533 struct bpf_reg_state *false_reg,
7534 u64 val, u32 val32,
7535 u8 opcode, bool is_jmp32)
7536 {
7537 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7538 struct tnum false_64off = false_reg->var_off;
7539 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7540 struct tnum true_64off = true_reg->var_off;
7541 s64 sval = (s64)val;
7542 s32 sval32 = (s32)val32;
7543
7544 /* If the dst_reg is a pointer, we can't learn anything about its
7545 * variable offset from the compare (unless src_reg were a pointer into
7546 * the same object, but we don't bother with that.
7547 * Since false_reg and true_reg have the same type by construction, we
7548 * only need to check one of them for pointerness.
7549 */
7550 if (__is_pointer_value(false, false_reg))
7551 return;
7552
7553 switch (opcode) {
7554 case BPF_JEQ:
7555 case BPF_JNE:
7556 {
7557 struct bpf_reg_state *reg =
7558 opcode == BPF_JEQ ? true_reg : false_reg;
7559
7560 /* JEQ/JNE comparison doesn't change the register equivalence.
7561 * r1 = r2;
7562 * if (r1 == 42) goto label;
7563 * ...
7564 * label: // here both r1 and r2 are known to be 42.
7565 *
7566 * Hence when marking register as known preserve it's ID.
7567 */
7568 if (is_jmp32)
7569 __mark_reg32_known(reg, val32);
7570 else
7571 ___mark_reg_known(reg, val);
7572 break;
7573 }
7574 case BPF_JSET:
7575 if (is_jmp32) {
7576 false_32off = tnum_and(false_32off, tnum_const(~val32));
7577 if (is_power_of_2(val32))
7578 true_32off = tnum_or(true_32off,
7579 tnum_const(val32));
7580 } else {
7581 false_64off = tnum_and(false_64off, tnum_const(~val));
7582 if (is_power_of_2(val))
7583 true_64off = tnum_or(true_64off,
7584 tnum_const(val));
7585 }
7586 break;
7587 case BPF_JGE:
7588 case BPF_JGT:
7589 {
7590 if (is_jmp32) {
7591 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7592 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7593
7594 false_reg->u32_max_value = min(false_reg->u32_max_value,
7595 false_umax);
7596 true_reg->u32_min_value = max(true_reg->u32_min_value,
7597 true_umin);
7598 } else {
7599 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7600 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7601
7602 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7603 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7604 }
7605 break;
7606 }
7607 case BPF_JSGE:
7608 case BPF_JSGT:
7609 {
7610 if (is_jmp32) {
7611 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7612 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7613
7614 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7615 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7616 } else {
7617 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7618 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7619
7620 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7621 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7622 }
7623 break;
7624 }
7625 case BPF_JLE:
7626 case BPF_JLT:
7627 {
7628 if (is_jmp32) {
7629 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7630 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7631
7632 false_reg->u32_min_value = max(false_reg->u32_min_value,
7633 false_umin);
7634 true_reg->u32_max_value = min(true_reg->u32_max_value,
7635 true_umax);
7636 } else {
7637 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7638 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7639
7640 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7641 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7642 }
7643 break;
7644 }
7645 case BPF_JSLE:
7646 case BPF_JSLT:
7647 {
7648 if (is_jmp32) {
7649 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7650 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7651
7652 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7653 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7654 } else {
7655 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7656 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7657
7658 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7659 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7660 }
7661 break;
7662 }
7663 default:
7664 return;
7665 }
7666
7667 if (is_jmp32) {
7668 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7669 tnum_subreg(false_32off));
7670 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7671 tnum_subreg(true_32off));
7672 __reg_combine_32_into_64(false_reg);
7673 __reg_combine_32_into_64(true_reg);
7674 } else {
7675 false_reg->var_off = false_64off;
7676 true_reg->var_off = true_64off;
7677 __reg_combine_64_into_32(false_reg);
7678 __reg_combine_64_into_32(true_reg);
7679 }
7680 }
7681
7682 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7683 * the variable reg.
7684 */
7685 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7686 struct bpf_reg_state *false_reg,
7687 u64 val, u32 val32,
7688 u8 opcode, bool is_jmp32)
7689 {
7690 opcode = flip_opcode(opcode);
7691 /* This uses zero as "not present in table"; luckily the zero opcode,
7692 * BPF_JA, can't get here.
7693 */
7694 if (opcode)
7695 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7696 }
7697
7698 /* Regs are known to be equal, so intersect their min/max/var_off */
7699 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7700 struct bpf_reg_state *dst_reg)
7701 {
7702 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7703 dst_reg->umin_value);
7704 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7705 dst_reg->umax_value);
7706 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7707 dst_reg->smin_value);
7708 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7709 dst_reg->smax_value);
7710 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7711 dst_reg->var_off);
7712 /* We might have learned new bounds from the var_off. */
7713 __update_reg_bounds(src_reg);
7714 __update_reg_bounds(dst_reg);
7715 /* We might have learned something about the sign bit. */
7716 __reg_deduce_bounds(src_reg);
7717 __reg_deduce_bounds(dst_reg);
7718 /* We might have learned some bits from the bounds. */
7719 __reg_bound_offset(src_reg);
7720 __reg_bound_offset(dst_reg);
7721 /* Intersecting with the old var_off might have improved our bounds
7722 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7723 * then new var_off is (0; 0x7f...fc) which improves our umax.
7724 */
7725 __update_reg_bounds(src_reg);
7726 __update_reg_bounds(dst_reg);
7727 }
7728
7729 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7730 struct bpf_reg_state *true_dst,
7731 struct bpf_reg_state *false_src,
7732 struct bpf_reg_state *false_dst,
7733 u8 opcode)
7734 {
7735 switch (opcode) {
7736 case BPF_JEQ:
7737 __reg_combine_min_max(true_src, true_dst);
7738 break;
7739 case BPF_JNE:
7740 __reg_combine_min_max(false_src, false_dst);
7741 break;
7742 }
7743 }
7744
7745 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7746 struct bpf_reg_state *reg, u32 id,
7747 bool is_null)
7748 {
7749 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7750 !WARN_ON_ONCE(!reg->id)) {
7751 /* Old offset (both fixed and variable parts) should
7752 * have been known-zero, because we don't allow pointer
7753 * arithmetic on pointers that might be NULL.
7754 */
7755 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7756 !tnum_equals_const(reg->var_off, 0) ||
7757 reg->off)) {
7758 __mark_reg_known_zero(reg);
7759 reg->off = 0;
7760 }
7761 if (is_null) {
7762 reg->type = SCALAR_VALUE;
7763 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7764 const struct bpf_map *map = reg->map_ptr;
7765
7766 if (map->inner_map_meta) {
7767 reg->type = CONST_PTR_TO_MAP;
7768 reg->map_ptr = map->inner_map_meta;
7769 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7770 reg->type = PTR_TO_XDP_SOCK;
7771 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7772 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7773 reg->type = PTR_TO_SOCKET;
7774 } else {
7775 reg->type = PTR_TO_MAP_VALUE;
7776 }
7777 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7778 reg->type = PTR_TO_SOCKET;
7779 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7780 reg->type = PTR_TO_SOCK_COMMON;
7781 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7782 reg->type = PTR_TO_TCP_SOCK;
7783 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7784 reg->type = PTR_TO_BTF_ID;
7785 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7786 reg->type = PTR_TO_MEM;
7787 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7788 reg->type = PTR_TO_RDONLY_BUF;
7789 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
7790 reg->type = PTR_TO_RDWR_BUF;
7791 }
7792 if (is_null) {
7793 /* We don't need id and ref_obj_id from this point
7794 * onwards anymore, thus we should better reset it,
7795 * so that state pruning has chances to take effect.
7796 */
7797 reg->id = 0;
7798 reg->ref_obj_id = 0;
7799 } else if (!reg_may_point_to_spin_lock(reg)) {
7800 /* For not-NULL ptr, reg->ref_obj_id will be reset
7801 * in release_reg_references().
7802 *
7803 * reg->id is still used by spin_lock ptr. Other
7804 * than spin_lock ptr type, reg->id can be reset.
7805 */
7806 reg->id = 0;
7807 }
7808 }
7809 }
7810
7811 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7812 bool is_null)
7813 {
7814 struct bpf_reg_state *reg;
7815 int i;
7816
7817 for (i = 0; i < MAX_BPF_REG; i++)
7818 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7819
7820 bpf_for_each_spilled_reg(i, state, reg) {
7821 if (!reg)
7822 continue;
7823 mark_ptr_or_null_reg(state, reg, id, is_null);
7824 }
7825 }
7826
7827 /* The logic is similar to find_good_pkt_pointers(), both could eventually
7828 * be folded together at some point.
7829 */
7830 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7831 bool is_null)
7832 {
7833 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7834 struct bpf_reg_state *regs = state->regs;
7835 u32 ref_obj_id = regs[regno].ref_obj_id;
7836 u32 id = regs[regno].id;
7837 int i;
7838
7839 if (ref_obj_id && ref_obj_id == id && is_null)
7840 /* regs[regno] is in the " == NULL" branch.
7841 * No one could have freed the reference state before
7842 * doing the NULL check.
7843 */
7844 WARN_ON_ONCE(release_reference_state(state, id));
7845
7846 for (i = 0; i <= vstate->curframe; i++)
7847 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
7848 }
7849
7850 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7851 struct bpf_reg_state *dst_reg,
7852 struct bpf_reg_state *src_reg,
7853 struct bpf_verifier_state *this_branch,
7854 struct bpf_verifier_state *other_branch)
7855 {
7856 if (BPF_SRC(insn->code) != BPF_X)
7857 return false;
7858
7859 /* Pointers are always 64-bit. */
7860 if (BPF_CLASS(insn->code) == BPF_JMP32)
7861 return false;
7862
7863 switch (BPF_OP(insn->code)) {
7864 case BPF_JGT:
7865 if ((dst_reg->type == PTR_TO_PACKET &&
7866 src_reg->type == PTR_TO_PACKET_END) ||
7867 (dst_reg->type == PTR_TO_PACKET_META &&
7868 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7869 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7870 find_good_pkt_pointers(this_branch, dst_reg,
7871 dst_reg->type, false);
7872 mark_pkt_end(other_branch, insn->dst_reg, true);
7873 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7874 src_reg->type == PTR_TO_PACKET) ||
7875 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7876 src_reg->type == PTR_TO_PACKET_META)) {
7877 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7878 find_good_pkt_pointers(other_branch, src_reg,
7879 src_reg->type, true);
7880 mark_pkt_end(this_branch, insn->src_reg, false);
7881 } else {
7882 return false;
7883 }
7884 break;
7885 case BPF_JLT:
7886 if ((dst_reg->type == PTR_TO_PACKET &&
7887 src_reg->type == PTR_TO_PACKET_END) ||
7888 (dst_reg->type == PTR_TO_PACKET_META &&
7889 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7890 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7891 find_good_pkt_pointers(other_branch, dst_reg,
7892 dst_reg->type, true);
7893 mark_pkt_end(this_branch, insn->dst_reg, false);
7894 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7895 src_reg->type == PTR_TO_PACKET) ||
7896 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7897 src_reg->type == PTR_TO_PACKET_META)) {
7898 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7899 find_good_pkt_pointers(this_branch, src_reg,
7900 src_reg->type, false);
7901 mark_pkt_end(other_branch, insn->src_reg, true);
7902 } else {
7903 return false;
7904 }
7905 break;
7906 case BPF_JGE:
7907 if ((dst_reg->type == PTR_TO_PACKET &&
7908 src_reg->type == PTR_TO_PACKET_END) ||
7909 (dst_reg->type == PTR_TO_PACKET_META &&
7910 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7911 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7912 find_good_pkt_pointers(this_branch, dst_reg,
7913 dst_reg->type, true);
7914 mark_pkt_end(other_branch, insn->dst_reg, false);
7915 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7916 src_reg->type == PTR_TO_PACKET) ||
7917 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7918 src_reg->type == PTR_TO_PACKET_META)) {
7919 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7920 find_good_pkt_pointers(other_branch, src_reg,
7921 src_reg->type, false);
7922 mark_pkt_end(this_branch, insn->src_reg, true);
7923 } else {
7924 return false;
7925 }
7926 break;
7927 case BPF_JLE:
7928 if ((dst_reg->type == PTR_TO_PACKET &&
7929 src_reg->type == PTR_TO_PACKET_END) ||
7930 (dst_reg->type == PTR_TO_PACKET_META &&
7931 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7932 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7933 find_good_pkt_pointers(other_branch, dst_reg,
7934 dst_reg->type, false);
7935 mark_pkt_end(this_branch, insn->dst_reg, true);
7936 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7937 src_reg->type == PTR_TO_PACKET) ||
7938 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7939 src_reg->type == PTR_TO_PACKET_META)) {
7940 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7941 find_good_pkt_pointers(this_branch, src_reg,
7942 src_reg->type, true);
7943 mark_pkt_end(other_branch, insn->src_reg, false);
7944 } else {
7945 return false;
7946 }
7947 break;
7948 default:
7949 return false;
7950 }
7951
7952 return true;
7953 }
7954
7955 static void find_equal_scalars(struct bpf_verifier_state *vstate,
7956 struct bpf_reg_state *known_reg)
7957 {
7958 struct bpf_func_state *state;
7959 struct bpf_reg_state *reg;
7960 int i, j;
7961
7962 for (i = 0; i <= vstate->curframe; i++) {
7963 state = vstate->frame[i];
7964 for (j = 0; j < MAX_BPF_REG; j++) {
7965 reg = &state->regs[j];
7966 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7967 *reg = *known_reg;
7968 }
7969
7970 bpf_for_each_spilled_reg(j, state, reg) {
7971 if (!reg)
7972 continue;
7973 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7974 *reg = *known_reg;
7975 }
7976 }
7977 }
7978
7979 static int check_cond_jmp_op(struct bpf_verifier_env *env,
7980 struct bpf_insn *insn, int *insn_idx)
7981 {
7982 struct bpf_verifier_state *this_branch = env->cur_state;
7983 struct bpf_verifier_state *other_branch;
7984 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
7985 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
7986 u8 opcode = BPF_OP(insn->code);
7987 bool is_jmp32;
7988 int pred = -1;
7989 int err;
7990
7991 /* Only conditional jumps are expected to reach here. */
7992 if (opcode == BPF_JA || opcode > BPF_JSLE) {
7993 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
7994 return -EINVAL;
7995 }
7996
7997 if (BPF_SRC(insn->code) == BPF_X) {
7998 if (insn->imm != 0) {
7999 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8000 return -EINVAL;
8001 }
8002
8003 /* check src1 operand */
8004 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8005 if (err)
8006 return err;
8007
8008 if (is_pointer_value(env, insn->src_reg)) {
8009 verbose(env, "R%d pointer comparison prohibited\n",
8010 insn->src_reg);
8011 return -EACCES;
8012 }
8013 src_reg = &regs[insn->src_reg];
8014 } else {
8015 if (insn->src_reg != BPF_REG_0) {
8016 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8017 return -EINVAL;
8018 }
8019 }
8020
8021 /* check src2 operand */
8022 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8023 if (err)
8024 return err;
8025
8026 dst_reg = &regs[insn->dst_reg];
8027 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8028
8029 if (BPF_SRC(insn->code) == BPF_K) {
8030 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8031 } else if (src_reg->type == SCALAR_VALUE &&
8032 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8033 pred = is_branch_taken(dst_reg,
8034 tnum_subreg(src_reg->var_off).value,
8035 opcode,
8036 is_jmp32);
8037 } else if (src_reg->type == SCALAR_VALUE &&
8038 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8039 pred = is_branch_taken(dst_reg,
8040 src_reg->var_off.value,
8041 opcode,
8042 is_jmp32);
8043 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8044 reg_is_pkt_pointer_any(src_reg) &&
8045 !is_jmp32) {
8046 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8047 }
8048
8049 if (pred >= 0) {
8050 /* If we get here with a dst_reg pointer type it is because
8051 * above is_branch_taken() special cased the 0 comparison.
8052 */
8053 if (!__is_pointer_value(false, dst_reg))
8054 err = mark_chain_precision(env, insn->dst_reg);
8055 if (BPF_SRC(insn->code) == BPF_X && !err &&
8056 !__is_pointer_value(false, src_reg))
8057 err = mark_chain_precision(env, insn->src_reg);
8058 if (err)
8059 return err;
8060 }
8061 if (pred == 1) {
8062 /* only follow the goto, ignore fall-through */
8063 *insn_idx += insn->off;
8064 return 0;
8065 } else if (pred == 0) {
8066 /* only follow fall-through branch, since
8067 * that's where the program will go
8068 */
8069 return 0;
8070 }
8071
8072 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8073 false);
8074 if (!other_branch)
8075 return -EFAULT;
8076 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8077
8078 /* detect if we are comparing against a constant value so we can adjust
8079 * our min/max values for our dst register.
8080 * this is only legit if both are scalars (or pointers to the same
8081 * object, I suppose, but we don't support that right now), because
8082 * otherwise the different base pointers mean the offsets aren't
8083 * comparable.
8084 */
8085 if (BPF_SRC(insn->code) == BPF_X) {
8086 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
8087
8088 if (dst_reg->type == SCALAR_VALUE &&
8089 src_reg->type == SCALAR_VALUE) {
8090 if (tnum_is_const(src_reg->var_off) ||
8091 (is_jmp32 &&
8092 tnum_is_const(tnum_subreg(src_reg->var_off))))
8093 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8094 dst_reg,
8095 src_reg->var_off.value,
8096 tnum_subreg(src_reg->var_off).value,
8097 opcode, is_jmp32);
8098 else if (tnum_is_const(dst_reg->var_off) ||
8099 (is_jmp32 &&
8100 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8101 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8102 src_reg,
8103 dst_reg->var_off.value,
8104 tnum_subreg(dst_reg->var_off).value,
8105 opcode, is_jmp32);
8106 else if (!is_jmp32 &&
8107 (opcode == BPF_JEQ || opcode == BPF_JNE))
8108 /* Comparing for equality, we can combine knowledge */
8109 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8110 &other_branch_regs[insn->dst_reg],
8111 src_reg, dst_reg, opcode);
8112 if (src_reg->id &&
8113 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8114 find_equal_scalars(this_branch, src_reg);
8115 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8116 }
8117
8118 }
8119 } else if (dst_reg->type == SCALAR_VALUE) {
8120 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8121 dst_reg, insn->imm, (u32)insn->imm,
8122 opcode, is_jmp32);
8123 }
8124
8125 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8126 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8127 find_equal_scalars(this_branch, dst_reg);
8128 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8129 }
8130
8131 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8132 * NOTE: these optimizations below are related with pointer comparison
8133 * which will never be JMP32.
8134 */
8135 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8136 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8137 reg_type_may_be_null(dst_reg->type)) {
8138 /* Mark all identical registers in each branch as either
8139 * safe or unknown depending R == 0 or R != 0 conditional.
8140 */
8141 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8142 opcode == BPF_JNE);
8143 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8144 opcode == BPF_JEQ);
8145 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8146 this_branch, other_branch) &&
8147 is_pointer_value(env, insn->dst_reg)) {
8148 verbose(env, "R%d pointer comparison prohibited\n",
8149 insn->dst_reg);
8150 return -EACCES;
8151 }
8152 if (env->log.level & BPF_LOG_LEVEL)
8153 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8154 return 0;
8155 }
8156
8157 /* verify BPF_LD_IMM64 instruction */
8158 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8159 {
8160 struct bpf_insn_aux_data *aux = cur_aux(env);
8161 struct bpf_reg_state *regs = cur_regs(env);
8162 struct bpf_reg_state *dst_reg;
8163 struct bpf_map *map;
8164 int err;
8165
8166 if (BPF_SIZE(insn->code) != BPF_DW) {
8167 verbose(env, "invalid BPF_LD_IMM insn\n");
8168 return -EINVAL;
8169 }
8170 if (insn->off != 0) {
8171 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8172 return -EINVAL;
8173 }
8174
8175 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8176 if (err)
8177 return err;
8178
8179 dst_reg = &regs[insn->dst_reg];
8180 if (insn->src_reg == 0) {
8181 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8182
8183 dst_reg->type = SCALAR_VALUE;
8184 __mark_reg_known(&regs[insn->dst_reg], imm);
8185 return 0;
8186 }
8187
8188 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8189 mark_reg_known_zero(env, regs, insn->dst_reg);
8190
8191 dst_reg->type = aux->btf_var.reg_type;
8192 switch (dst_reg->type) {
8193 case PTR_TO_MEM:
8194 dst_reg->mem_size = aux->btf_var.mem_size;
8195 break;
8196 case PTR_TO_BTF_ID:
8197 case PTR_TO_PERCPU_BTF_ID:
8198 dst_reg->btf = aux->btf_var.btf;
8199 dst_reg->btf_id = aux->btf_var.btf_id;
8200 break;
8201 default:
8202 verbose(env, "bpf verifier is misconfigured\n");
8203 return -EFAULT;
8204 }
8205 return 0;
8206 }
8207
8208 map = env->used_maps[aux->map_index];
8209 mark_reg_known_zero(env, regs, insn->dst_reg);
8210 dst_reg->map_ptr = map;
8211
8212 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8213 dst_reg->type = PTR_TO_MAP_VALUE;
8214 dst_reg->off = aux->map_off;
8215 if (map_value_has_spin_lock(map))
8216 dst_reg->id = ++env->id_gen;
8217 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8218 dst_reg->type = CONST_PTR_TO_MAP;
8219 } else {
8220 verbose(env, "bpf verifier is misconfigured\n");
8221 return -EINVAL;
8222 }
8223
8224 return 0;
8225 }
8226
8227 static bool may_access_skb(enum bpf_prog_type type)
8228 {
8229 switch (type) {
8230 case BPF_PROG_TYPE_SOCKET_FILTER:
8231 case BPF_PROG_TYPE_SCHED_CLS:
8232 case BPF_PROG_TYPE_SCHED_ACT:
8233 return true;
8234 default:
8235 return false;
8236 }
8237 }
8238
8239 /* verify safety of LD_ABS|LD_IND instructions:
8240 * - they can only appear in the programs where ctx == skb
8241 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8242 * preserve R6-R9, and store return value into R0
8243 *
8244 * Implicit input:
8245 * ctx == skb == R6 == CTX
8246 *
8247 * Explicit input:
8248 * SRC == any register
8249 * IMM == 32-bit immediate
8250 *
8251 * Output:
8252 * R0 - 8/16/32-bit skb data converted to cpu endianness
8253 */
8254 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8255 {
8256 struct bpf_reg_state *regs = cur_regs(env);
8257 static const int ctx_reg = BPF_REG_6;
8258 u8 mode = BPF_MODE(insn->code);
8259 int i, err;
8260
8261 if (!may_access_skb(resolve_prog_type(env->prog))) {
8262 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8263 return -EINVAL;
8264 }
8265
8266 if (!env->ops->gen_ld_abs) {
8267 verbose(env, "bpf verifier is misconfigured\n");
8268 return -EINVAL;
8269 }
8270
8271 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8272 BPF_SIZE(insn->code) == BPF_DW ||
8273 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8274 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8275 return -EINVAL;
8276 }
8277
8278 /* check whether implicit source operand (register R6) is readable */
8279 err = check_reg_arg(env, ctx_reg, SRC_OP);
8280 if (err)
8281 return err;
8282
8283 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8284 * gen_ld_abs() may terminate the program at runtime, leading to
8285 * reference leak.
8286 */
8287 err = check_reference_leak(env);
8288 if (err) {
8289 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8290 return err;
8291 }
8292
8293 if (env->cur_state->active_spin_lock) {
8294 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8295 return -EINVAL;
8296 }
8297
8298 if (regs[ctx_reg].type != PTR_TO_CTX) {
8299 verbose(env,
8300 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8301 return -EINVAL;
8302 }
8303
8304 if (mode == BPF_IND) {
8305 /* check explicit source operand */
8306 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8307 if (err)
8308 return err;
8309 }
8310
8311 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8312 if (err < 0)
8313 return err;
8314
8315 /* reset caller saved regs to unreadable */
8316 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8317 mark_reg_not_init(env, regs, caller_saved[i]);
8318 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8319 }
8320
8321 /* mark destination R0 register as readable, since it contains
8322 * the value fetched from the packet.
8323 * Already marked as written above.
8324 */
8325 mark_reg_unknown(env, regs, BPF_REG_0);
8326 /* ld_abs load up to 32-bit skb data. */
8327 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8328 return 0;
8329 }
8330
8331 static int check_return_code(struct bpf_verifier_env *env)
8332 {
8333 struct tnum enforce_attach_type_range = tnum_unknown;
8334 const struct bpf_prog *prog = env->prog;
8335 struct bpf_reg_state *reg;
8336 struct tnum range = tnum_range(0, 1);
8337 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8338 int err;
8339 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8340
8341 /* LSM and struct_ops func-ptr's return type could be "void" */
8342 if (!is_subprog &&
8343 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8344 prog_type == BPF_PROG_TYPE_LSM) &&
8345 !prog->aux->attach_func_proto->type)
8346 return 0;
8347
8348 /* eBPF calling convetion is such that R0 is used
8349 * to return the value from eBPF program.
8350 * Make sure that it's readable at this time
8351 * of bpf_exit, which means that program wrote
8352 * something into it earlier
8353 */
8354 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8355 if (err)
8356 return err;
8357
8358 if (is_pointer_value(env, BPF_REG_0)) {
8359 verbose(env, "R0 leaks addr as return value\n");
8360 return -EACCES;
8361 }
8362
8363 reg = cur_regs(env) + BPF_REG_0;
8364 if (is_subprog) {
8365 if (reg->type != SCALAR_VALUE) {
8366 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8367 reg_type_str[reg->type]);
8368 return -EINVAL;
8369 }
8370 return 0;
8371 }
8372
8373 switch (prog_type) {
8374 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8375 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8376 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8377 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8378 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8379 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8380 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8381 range = tnum_range(1, 1);
8382 break;
8383 case BPF_PROG_TYPE_CGROUP_SKB:
8384 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8385 range = tnum_range(0, 3);
8386 enforce_attach_type_range = tnum_range(2, 3);
8387 }
8388 break;
8389 case BPF_PROG_TYPE_CGROUP_SOCK:
8390 case BPF_PROG_TYPE_SOCK_OPS:
8391 case BPF_PROG_TYPE_CGROUP_DEVICE:
8392 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8393 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8394 break;
8395 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8396 if (!env->prog->aux->attach_btf_id)
8397 return 0;
8398 range = tnum_const(0);
8399 break;
8400 case BPF_PROG_TYPE_TRACING:
8401 switch (env->prog->expected_attach_type) {
8402 case BPF_TRACE_FENTRY:
8403 case BPF_TRACE_FEXIT:
8404 range = tnum_const(0);
8405 break;
8406 case BPF_TRACE_RAW_TP:
8407 case BPF_MODIFY_RETURN:
8408 return 0;
8409 case BPF_TRACE_ITER:
8410 break;
8411 default:
8412 return -ENOTSUPP;
8413 }
8414 break;
8415 case BPF_PROG_TYPE_SK_LOOKUP:
8416 range = tnum_range(SK_DROP, SK_PASS);
8417 break;
8418 case BPF_PROG_TYPE_EXT:
8419 /* freplace program can return anything as its return value
8420 * depends on the to-be-replaced kernel func or bpf program.
8421 */
8422 default:
8423 return 0;
8424 }
8425
8426 if (reg->type != SCALAR_VALUE) {
8427 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8428 reg_type_str[reg->type]);
8429 return -EINVAL;
8430 }
8431
8432 if (!tnum_in(range, reg->var_off)) {
8433 char tn_buf[48];
8434
8435 verbose(env, "At program exit the register R0 ");
8436 if (!tnum_is_unknown(reg->var_off)) {
8437 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8438 verbose(env, "has value %s", tn_buf);
8439 } else {
8440 verbose(env, "has unknown scalar value");
8441 }
8442 tnum_strn(tn_buf, sizeof(tn_buf), range);
8443 verbose(env, " should have been in %s\n", tn_buf);
8444 return -EINVAL;
8445 }
8446
8447 if (!tnum_is_unknown(enforce_attach_type_range) &&
8448 tnum_in(enforce_attach_type_range, reg->var_off))
8449 env->prog->enforce_expected_attach_type = 1;
8450 return 0;
8451 }
8452
8453 /* non-recursive DFS pseudo code
8454 * 1 procedure DFS-iterative(G,v):
8455 * 2 label v as discovered
8456 * 3 let S be a stack
8457 * 4 S.push(v)
8458 * 5 while S is not empty
8459 * 6 t <- S.pop()
8460 * 7 if t is what we're looking for:
8461 * 8 return t
8462 * 9 for all edges e in G.adjacentEdges(t) do
8463 * 10 if edge e is already labelled
8464 * 11 continue with the next edge
8465 * 12 w <- G.adjacentVertex(t,e)
8466 * 13 if vertex w is not discovered and not explored
8467 * 14 label e as tree-edge
8468 * 15 label w as discovered
8469 * 16 S.push(w)
8470 * 17 continue at 5
8471 * 18 else if vertex w is discovered
8472 * 19 label e as back-edge
8473 * 20 else
8474 * 21 // vertex w is explored
8475 * 22 label e as forward- or cross-edge
8476 * 23 label t as explored
8477 * 24 S.pop()
8478 *
8479 * convention:
8480 * 0x10 - discovered
8481 * 0x11 - discovered and fall-through edge labelled
8482 * 0x12 - discovered and fall-through and branch edges labelled
8483 * 0x20 - explored
8484 */
8485
8486 enum {
8487 DISCOVERED = 0x10,
8488 EXPLORED = 0x20,
8489 FALLTHROUGH = 1,
8490 BRANCH = 2,
8491 };
8492
8493 static u32 state_htab_size(struct bpf_verifier_env *env)
8494 {
8495 return env->prog->len;
8496 }
8497
8498 static struct bpf_verifier_state_list **explored_state(
8499 struct bpf_verifier_env *env,
8500 int idx)
8501 {
8502 struct bpf_verifier_state *cur = env->cur_state;
8503 struct bpf_func_state *state = cur->frame[cur->curframe];
8504
8505 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8506 }
8507
8508 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8509 {
8510 env->insn_aux_data[idx].prune_point = true;
8511 }
8512
8513 enum {
8514 DONE_EXPLORING = 0,
8515 KEEP_EXPLORING = 1,
8516 };
8517
8518 /* t, w, e - match pseudo-code above:
8519 * t - index of current instruction
8520 * w - next instruction
8521 * e - edge
8522 */
8523 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8524 bool loop_ok)
8525 {
8526 int *insn_stack = env->cfg.insn_stack;
8527 int *insn_state = env->cfg.insn_state;
8528
8529 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8530 return DONE_EXPLORING;
8531
8532 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8533 return DONE_EXPLORING;
8534
8535 if (w < 0 || w >= env->prog->len) {
8536 verbose_linfo(env, t, "%d: ", t);
8537 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8538 return -EINVAL;
8539 }
8540
8541 if (e == BRANCH)
8542 /* mark branch target for state pruning */
8543 init_explored_state(env, w);
8544
8545 if (insn_state[w] == 0) {
8546 /* tree-edge */
8547 insn_state[t] = DISCOVERED | e;
8548 insn_state[w] = DISCOVERED;
8549 if (env->cfg.cur_stack >= env->prog->len)
8550 return -E2BIG;
8551 insn_stack[env->cfg.cur_stack++] = w;
8552 return KEEP_EXPLORING;
8553 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8554 if (loop_ok && env->bpf_capable)
8555 return DONE_EXPLORING;
8556 verbose_linfo(env, t, "%d: ", t);
8557 verbose_linfo(env, w, "%d: ", w);
8558 verbose(env, "back-edge from insn %d to %d\n", t, w);
8559 return -EINVAL;
8560 } else if (insn_state[w] == EXPLORED) {
8561 /* forward- or cross-edge */
8562 insn_state[t] = DISCOVERED | e;
8563 } else {
8564 verbose(env, "insn state internal bug\n");
8565 return -EFAULT;
8566 }
8567 return DONE_EXPLORING;
8568 }
8569
8570 /* Visits the instruction at index t and returns one of the following:
8571 * < 0 - an error occurred
8572 * DONE_EXPLORING - the instruction was fully explored
8573 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8574 */
8575 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8576 {
8577 struct bpf_insn *insns = env->prog->insnsi;
8578 int ret;
8579
8580 /* All non-branch instructions have a single fall-through edge. */
8581 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8582 BPF_CLASS(insns[t].code) != BPF_JMP32)
8583 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8584
8585 switch (BPF_OP(insns[t].code)) {
8586 case BPF_EXIT:
8587 return DONE_EXPLORING;
8588
8589 case BPF_CALL:
8590 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8591 if (ret)
8592 return ret;
8593
8594 if (t + 1 < insn_cnt)
8595 init_explored_state(env, t + 1);
8596 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8597 init_explored_state(env, t);
8598 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8599 env, false);
8600 }
8601 return ret;
8602
8603 case BPF_JA:
8604 if (BPF_SRC(insns[t].code) != BPF_K)
8605 return -EINVAL;
8606
8607 /* unconditional jump with single edge */
8608 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8609 true);
8610 if (ret)
8611 return ret;
8612
8613 /* unconditional jmp is not a good pruning point,
8614 * but it's marked, since backtracking needs
8615 * to record jmp history in is_state_visited().
8616 */
8617 init_explored_state(env, t + insns[t].off + 1);
8618 /* tell verifier to check for equivalent states
8619 * after every call and jump
8620 */
8621 if (t + 1 < insn_cnt)
8622 init_explored_state(env, t + 1);
8623
8624 return ret;
8625
8626 default:
8627 /* conditional jump with two edges */
8628 init_explored_state(env, t);
8629 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8630 if (ret)
8631 return ret;
8632
8633 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8634 }
8635 }
8636
8637 /* non-recursive depth-first-search to detect loops in BPF program
8638 * loop == back-edge in directed graph
8639 */
8640 static int check_cfg(struct bpf_verifier_env *env)
8641 {
8642 int insn_cnt = env->prog->len;
8643 int *insn_stack, *insn_state;
8644 int ret = 0;
8645 int i;
8646
8647 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8648 if (!insn_state)
8649 return -ENOMEM;
8650
8651 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8652 if (!insn_stack) {
8653 kvfree(insn_state);
8654 return -ENOMEM;
8655 }
8656
8657 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8658 insn_stack[0] = 0; /* 0 is the first instruction */
8659 env->cfg.cur_stack = 1;
8660
8661 while (env->cfg.cur_stack > 0) {
8662 int t = insn_stack[env->cfg.cur_stack - 1];
8663
8664 ret = visit_insn(t, insn_cnt, env);
8665 switch (ret) {
8666 case DONE_EXPLORING:
8667 insn_state[t] = EXPLORED;
8668 env->cfg.cur_stack--;
8669 break;
8670 case KEEP_EXPLORING:
8671 break;
8672 default:
8673 if (ret > 0) {
8674 verbose(env, "visit_insn internal bug\n");
8675 ret = -EFAULT;
8676 }
8677 goto err_free;
8678 }
8679 }
8680
8681 if (env->cfg.cur_stack < 0) {
8682 verbose(env, "pop stack internal bug\n");
8683 ret = -EFAULT;
8684 goto err_free;
8685 }
8686
8687 for (i = 0; i < insn_cnt; i++) {
8688 if (insn_state[i] != EXPLORED) {
8689 verbose(env, "unreachable insn %d\n", i);
8690 ret = -EINVAL;
8691 goto err_free;
8692 }
8693 }
8694 ret = 0; /* cfg looks good */
8695
8696 err_free:
8697 kvfree(insn_state);
8698 kvfree(insn_stack);
8699 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8700 return ret;
8701 }
8702
8703 static int check_abnormal_return(struct bpf_verifier_env *env)
8704 {
8705 int i;
8706
8707 for (i = 1; i < env->subprog_cnt; i++) {
8708 if (env->subprog_info[i].has_ld_abs) {
8709 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8710 return -EINVAL;
8711 }
8712 if (env->subprog_info[i].has_tail_call) {
8713 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8714 return -EINVAL;
8715 }
8716 }
8717 return 0;
8718 }
8719
8720 /* The minimum supported BTF func info size */
8721 #define MIN_BPF_FUNCINFO_SIZE 8
8722 #define MAX_FUNCINFO_REC_SIZE 252
8723
8724 static int check_btf_func(struct bpf_verifier_env *env,
8725 const union bpf_attr *attr,
8726 union bpf_attr __user *uattr)
8727 {
8728 const struct btf_type *type, *func_proto, *ret_type;
8729 u32 i, nfuncs, urec_size, min_size;
8730 u32 krec_size = sizeof(struct bpf_func_info);
8731 struct bpf_func_info *krecord;
8732 struct bpf_func_info_aux *info_aux = NULL;
8733 struct bpf_prog *prog;
8734 const struct btf *btf;
8735 void __user *urecord;
8736 u32 prev_offset = 0;
8737 bool scalar_return;
8738 int ret = -ENOMEM;
8739
8740 nfuncs = attr->func_info_cnt;
8741 if (!nfuncs) {
8742 if (check_abnormal_return(env))
8743 return -EINVAL;
8744 return 0;
8745 }
8746
8747 if (nfuncs != env->subprog_cnt) {
8748 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8749 return -EINVAL;
8750 }
8751
8752 urec_size = attr->func_info_rec_size;
8753 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8754 urec_size > MAX_FUNCINFO_REC_SIZE ||
8755 urec_size % sizeof(u32)) {
8756 verbose(env, "invalid func info rec size %u\n", urec_size);
8757 return -EINVAL;
8758 }
8759
8760 prog = env->prog;
8761 btf = prog->aux->btf;
8762
8763 urecord = u64_to_user_ptr(attr->func_info);
8764 min_size = min_t(u32, krec_size, urec_size);
8765
8766 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8767 if (!krecord)
8768 return -ENOMEM;
8769 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8770 if (!info_aux)
8771 goto err_free;
8772
8773 for (i = 0; i < nfuncs; i++) {
8774 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8775 if (ret) {
8776 if (ret == -E2BIG) {
8777 verbose(env, "nonzero tailing record in func info");
8778 /* set the size kernel expects so loader can zero
8779 * out the rest of the record.
8780 */
8781 if (put_user(min_size, &uattr->func_info_rec_size))
8782 ret = -EFAULT;
8783 }
8784 goto err_free;
8785 }
8786
8787 if (copy_from_user(&krecord[i], urecord, min_size)) {
8788 ret = -EFAULT;
8789 goto err_free;
8790 }
8791
8792 /* check insn_off */
8793 ret = -EINVAL;
8794 if (i == 0) {
8795 if (krecord[i].insn_off) {
8796 verbose(env,
8797 "nonzero insn_off %u for the first func info record",
8798 krecord[i].insn_off);
8799 goto err_free;
8800 }
8801 } else if (krecord[i].insn_off <= prev_offset) {
8802 verbose(env,
8803 "same or smaller insn offset (%u) than previous func info record (%u)",
8804 krecord[i].insn_off, prev_offset);
8805 goto err_free;
8806 }
8807
8808 if (env->subprog_info[i].start != krecord[i].insn_off) {
8809 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8810 goto err_free;
8811 }
8812
8813 /* check type_id */
8814 type = btf_type_by_id(btf, krecord[i].type_id);
8815 if (!type || !btf_type_is_func(type)) {
8816 verbose(env, "invalid type id %d in func info",
8817 krecord[i].type_id);
8818 goto err_free;
8819 }
8820 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
8821
8822 func_proto = btf_type_by_id(btf, type->type);
8823 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8824 /* btf_func_check() already verified it during BTF load */
8825 goto err_free;
8826 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8827 scalar_return =
8828 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8829 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8830 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8831 goto err_free;
8832 }
8833 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8834 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8835 goto err_free;
8836 }
8837
8838 prev_offset = krecord[i].insn_off;
8839 urecord += urec_size;
8840 }
8841
8842 prog->aux->func_info = krecord;
8843 prog->aux->func_info_cnt = nfuncs;
8844 prog->aux->func_info_aux = info_aux;
8845 return 0;
8846
8847 err_free:
8848 kvfree(krecord);
8849 kfree(info_aux);
8850 return ret;
8851 }
8852
8853 static void adjust_btf_func(struct bpf_verifier_env *env)
8854 {
8855 struct bpf_prog_aux *aux = env->prog->aux;
8856 int i;
8857
8858 if (!aux->func_info)
8859 return;
8860
8861 for (i = 0; i < env->subprog_cnt; i++)
8862 aux->func_info[i].insn_off = env->subprog_info[i].start;
8863 }
8864
8865 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8866 sizeof(((struct bpf_line_info *)(0))->line_col))
8867 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8868
8869 static int check_btf_line(struct bpf_verifier_env *env,
8870 const union bpf_attr *attr,
8871 union bpf_attr __user *uattr)
8872 {
8873 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8874 struct bpf_subprog_info *sub;
8875 struct bpf_line_info *linfo;
8876 struct bpf_prog *prog;
8877 const struct btf *btf;
8878 void __user *ulinfo;
8879 int err;
8880
8881 nr_linfo = attr->line_info_cnt;
8882 if (!nr_linfo)
8883 return 0;
8884
8885 rec_size = attr->line_info_rec_size;
8886 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8887 rec_size > MAX_LINEINFO_REC_SIZE ||
8888 rec_size & (sizeof(u32) - 1))
8889 return -EINVAL;
8890
8891 /* Need to zero it in case the userspace may
8892 * pass in a smaller bpf_line_info object.
8893 */
8894 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8895 GFP_KERNEL | __GFP_NOWARN);
8896 if (!linfo)
8897 return -ENOMEM;
8898
8899 prog = env->prog;
8900 btf = prog->aux->btf;
8901
8902 s = 0;
8903 sub = env->subprog_info;
8904 ulinfo = u64_to_user_ptr(attr->line_info);
8905 expected_size = sizeof(struct bpf_line_info);
8906 ncopy = min_t(u32, expected_size, rec_size);
8907 for (i = 0; i < nr_linfo; i++) {
8908 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8909 if (err) {
8910 if (err == -E2BIG) {
8911 verbose(env, "nonzero tailing record in line_info");
8912 if (put_user(expected_size,
8913 &uattr->line_info_rec_size))
8914 err = -EFAULT;
8915 }
8916 goto err_free;
8917 }
8918
8919 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8920 err = -EFAULT;
8921 goto err_free;
8922 }
8923
8924 /*
8925 * Check insn_off to ensure
8926 * 1) strictly increasing AND
8927 * 2) bounded by prog->len
8928 *
8929 * The linfo[0].insn_off == 0 check logically falls into
8930 * the later "missing bpf_line_info for func..." case
8931 * because the first linfo[0].insn_off must be the
8932 * first sub also and the first sub must have
8933 * subprog_info[0].start == 0.
8934 */
8935 if ((i && linfo[i].insn_off <= prev_offset) ||
8936 linfo[i].insn_off >= prog->len) {
8937 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8938 i, linfo[i].insn_off, prev_offset,
8939 prog->len);
8940 err = -EINVAL;
8941 goto err_free;
8942 }
8943
8944 if (!prog->insnsi[linfo[i].insn_off].code) {
8945 verbose(env,
8946 "Invalid insn code at line_info[%u].insn_off\n",
8947 i);
8948 err = -EINVAL;
8949 goto err_free;
8950 }
8951
8952 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8953 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
8954 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8955 err = -EINVAL;
8956 goto err_free;
8957 }
8958
8959 if (s != env->subprog_cnt) {
8960 if (linfo[i].insn_off == sub[s].start) {
8961 sub[s].linfo_idx = i;
8962 s++;
8963 } else if (sub[s].start < linfo[i].insn_off) {
8964 verbose(env, "missing bpf_line_info for func#%u\n", s);
8965 err = -EINVAL;
8966 goto err_free;
8967 }
8968 }
8969
8970 prev_offset = linfo[i].insn_off;
8971 ulinfo += rec_size;
8972 }
8973
8974 if (s != env->subprog_cnt) {
8975 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
8976 env->subprog_cnt - s, s);
8977 err = -EINVAL;
8978 goto err_free;
8979 }
8980
8981 prog->aux->linfo = linfo;
8982 prog->aux->nr_linfo = nr_linfo;
8983
8984 return 0;
8985
8986 err_free:
8987 kvfree(linfo);
8988 return err;
8989 }
8990
8991 static int check_btf_info(struct bpf_verifier_env *env,
8992 const union bpf_attr *attr,
8993 union bpf_attr __user *uattr)
8994 {
8995 struct btf *btf;
8996 int err;
8997
8998 if (!attr->func_info_cnt && !attr->line_info_cnt) {
8999 if (check_abnormal_return(env))
9000 return -EINVAL;
9001 return 0;
9002 }
9003
9004 btf = btf_get_by_fd(attr->prog_btf_fd);
9005 if (IS_ERR(btf))
9006 return PTR_ERR(btf);
9007 if (btf_is_kernel(btf)) {
9008 btf_put(btf);
9009 return -EACCES;
9010 }
9011 env->prog->aux->btf = btf;
9012
9013 err = check_btf_func(env, attr, uattr);
9014 if (err)
9015 return err;
9016
9017 err = check_btf_line(env, attr, uattr);
9018 if (err)
9019 return err;
9020
9021 return 0;
9022 }
9023
9024 /* check %cur's range satisfies %old's */
9025 static bool range_within(struct bpf_reg_state *old,
9026 struct bpf_reg_state *cur)
9027 {
9028 return old->umin_value <= cur->umin_value &&
9029 old->umax_value >= cur->umax_value &&
9030 old->smin_value <= cur->smin_value &&
9031 old->smax_value >= cur->smax_value &&
9032 old->u32_min_value <= cur->u32_min_value &&
9033 old->u32_max_value >= cur->u32_max_value &&
9034 old->s32_min_value <= cur->s32_min_value &&
9035 old->s32_max_value >= cur->s32_max_value;
9036 }
9037
9038 /* Maximum number of register states that can exist at once */
9039 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9040 struct idpair {
9041 u32 old;
9042 u32 cur;
9043 };
9044
9045 /* If in the old state two registers had the same id, then they need to have
9046 * the same id in the new state as well. But that id could be different from
9047 * the old state, so we need to track the mapping from old to new ids.
9048 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9049 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9050 * regs with a different old id could still have new id 9, we don't care about
9051 * that.
9052 * So we look through our idmap to see if this old id has been seen before. If
9053 * so, we require the new id to match; otherwise, we add the id pair to the map.
9054 */
9055 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9056 {
9057 unsigned int i;
9058
9059 for (i = 0; i < ID_MAP_SIZE; i++) {
9060 if (!idmap[i].old) {
9061 /* Reached an empty slot; haven't seen this id before */
9062 idmap[i].old = old_id;
9063 idmap[i].cur = cur_id;
9064 return true;
9065 }
9066 if (idmap[i].old == old_id)
9067 return idmap[i].cur == cur_id;
9068 }
9069 /* We ran out of idmap slots, which should be impossible */
9070 WARN_ON_ONCE(1);
9071 return false;
9072 }
9073
9074 static void clean_func_state(struct bpf_verifier_env *env,
9075 struct bpf_func_state *st)
9076 {
9077 enum bpf_reg_liveness live;
9078 int i, j;
9079
9080 for (i = 0; i < BPF_REG_FP; i++) {
9081 live = st->regs[i].live;
9082 /* liveness must not touch this register anymore */
9083 st->regs[i].live |= REG_LIVE_DONE;
9084 if (!(live & REG_LIVE_READ))
9085 /* since the register is unused, clear its state
9086 * to make further comparison simpler
9087 */
9088 __mark_reg_not_init(env, &st->regs[i]);
9089 }
9090
9091 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9092 live = st->stack[i].spilled_ptr.live;
9093 /* liveness must not touch this stack slot anymore */
9094 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9095 if (!(live & REG_LIVE_READ)) {
9096 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9097 for (j = 0; j < BPF_REG_SIZE; j++)
9098 st->stack[i].slot_type[j] = STACK_INVALID;
9099 }
9100 }
9101 }
9102
9103 static void clean_verifier_state(struct bpf_verifier_env *env,
9104 struct bpf_verifier_state *st)
9105 {
9106 int i;
9107
9108 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9109 /* all regs in this state in all frames were already marked */
9110 return;
9111
9112 for (i = 0; i <= st->curframe; i++)
9113 clean_func_state(env, st->frame[i]);
9114 }
9115
9116 /* the parentage chains form a tree.
9117 * the verifier states are added to state lists at given insn and
9118 * pushed into state stack for future exploration.
9119 * when the verifier reaches bpf_exit insn some of the verifer states
9120 * stored in the state lists have their final liveness state already,
9121 * but a lot of states will get revised from liveness point of view when
9122 * the verifier explores other branches.
9123 * Example:
9124 * 1: r0 = 1
9125 * 2: if r1 == 100 goto pc+1
9126 * 3: r0 = 2
9127 * 4: exit
9128 * when the verifier reaches exit insn the register r0 in the state list of
9129 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9130 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9131 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9132 *
9133 * Since the verifier pushes the branch states as it sees them while exploring
9134 * the program the condition of walking the branch instruction for the second
9135 * time means that all states below this branch were already explored and
9136 * their final liveness markes are already propagated.
9137 * Hence when the verifier completes the search of state list in is_state_visited()
9138 * we can call this clean_live_states() function to mark all liveness states
9139 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9140 * will not be used.
9141 * This function also clears the registers and stack for states that !READ
9142 * to simplify state merging.
9143 *
9144 * Important note here that walking the same branch instruction in the callee
9145 * doesn't meant that the states are DONE. The verifier has to compare
9146 * the callsites
9147 */
9148 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9149 struct bpf_verifier_state *cur)
9150 {
9151 struct bpf_verifier_state_list *sl;
9152 int i;
9153
9154 sl = *explored_state(env, insn);
9155 while (sl) {
9156 if (sl->state.branches)
9157 goto next;
9158 if (sl->state.insn_idx != insn ||
9159 sl->state.curframe != cur->curframe)
9160 goto next;
9161 for (i = 0; i <= cur->curframe; i++)
9162 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9163 goto next;
9164 clean_verifier_state(env, &sl->state);
9165 next:
9166 sl = sl->next;
9167 }
9168 }
9169
9170 /* Returns true if (rold safe implies rcur safe) */
9171 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9172 struct idpair *idmap)
9173 {
9174 bool equal;
9175
9176 if (!(rold->live & REG_LIVE_READ))
9177 /* explored state didn't use this */
9178 return true;
9179
9180 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9181
9182 if (rold->type == PTR_TO_STACK)
9183 /* two stack pointers are equal only if they're pointing to
9184 * the same stack frame, since fp-8 in foo != fp-8 in bar
9185 */
9186 return equal && rold->frameno == rcur->frameno;
9187
9188 if (equal)
9189 return true;
9190
9191 if (rold->type == NOT_INIT)
9192 /* explored state can't have used this */
9193 return true;
9194 if (rcur->type == NOT_INIT)
9195 return false;
9196 switch (rold->type) {
9197 case SCALAR_VALUE:
9198 if (rcur->type == SCALAR_VALUE) {
9199 if (!rold->precise && !rcur->precise)
9200 return true;
9201 /* new val must satisfy old val knowledge */
9202 return range_within(rold, rcur) &&
9203 tnum_in(rold->var_off, rcur->var_off);
9204 } else {
9205 /* We're trying to use a pointer in place of a scalar.
9206 * Even if the scalar was unbounded, this could lead to
9207 * pointer leaks because scalars are allowed to leak
9208 * while pointers are not. We could make this safe in
9209 * special cases if root is calling us, but it's
9210 * probably not worth the hassle.
9211 */
9212 return false;
9213 }
9214 case PTR_TO_MAP_VALUE:
9215 /* If the new min/max/var_off satisfy the old ones and
9216 * everything else matches, we are OK.
9217 * 'id' is not compared, since it's only used for maps with
9218 * bpf_spin_lock inside map element and in such cases if
9219 * the rest of the prog is valid for one map element then
9220 * it's valid for all map elements regardless of the key
9221 * used in bpf_map_lookup()
9222 */
9223 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9224 range_within(rold, rcur) &&
9225 tnum_in(rold->var_off, rcur->var_off);
9226 case PTR_TO_MAP_VALUE_OR_NULL:
9227 /* a PTR_TO_MAP_VALUE could be safe to use as a
9228 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9229 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9230 * checked, doing so could have affected others with the same
9231 * id, and we can't check for that because we lost the id when
9232 * we converted to a PTR_TO_MAP_VALUE.
9233 */
9234 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9235 return false;
9236 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9237 return false;
9238 /* Check our ids match any regs they're supposed to */
9239 return check_ids(rold->id, rcur->id, idmap);
9240 case PTR_TO_PACKET_META:
9241 case PTR_TO_PACKET:
9242 if (rcur->type != rold->type)
9243 return false;
9244 /* We must have at least as much range as the old ptr
9245 * did, so that any accesses which were safe before are
9246 * still safe. This is true even if old range < old off,
9247 * since someone could have accessed through (ptr - k), or
9248 * even done ptr -= k in a register, to get a safe access.
9249 */
9250 if (rold->range > rcur->range)
9251 return false;
9252 /* If the offsets don't match, we can't trust our alignment;
9253 * nor can we be sure that we won't fall out of range.
9254 */
9255 if (rold->off != rcur->off)
9256 return false;
9257 /* id relations must be preserved */
9258 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9259 return false;
9260 /* new val must satisfy old val knowledge */
9261 return range_within(rold, rcur) &&
9262 tnum_in(rold->var_off, rcur->var_off);
9263 case PTR_TO_CTX:
9264 case CONST_PTR_TO_MAP:
9265 case PTR_TO_PACKET_END:
9266 case PTR_TO_FLOW_KEYS:
9267 case PTR_TO_SOCKET:
9268 case PTR_TO_SOCKET_OR_NULL:
9269 case PTR_TO_SOCK_COMMON:
9270 case PTR_TO_SOCK_COMMON_OR_NULL:
9271 case PTR_TO_TCP_SOCK:
9272 case PTR_TO_TCP_SOCK_OR_NULL:
9273 case PTR_TO_XDP_SOCK:
9274 /* Only valid matches are exact, which memcmp() above
9275 * would have accepted
9276 */
9277 default:
9278 /* Don't know what's going on, just say it's not safe */
9279 return false;
9280 }
9281
9282 /* Shouldn't get here; if we do, say it's not safe */
9283 WARN_ON_ONCE(1);
9284 return false;
9285 }
9286
9287 static bool stacksafe(struct bpf_func_state *old,
9288 struct bpf_func_state *cur,
9289 struct idpair *idmap)
9290 {
9291 int i, spi;
9292
9293 /* walk slots of the explored stack and ignore any additional
9294 * slots in the current stack, since explored(safe) state
9295 * didn't use them
9296 */
9297 for (i = 0; i < old->allocated_stack; i++) {
9298 spi = i / BPF_REG_SIZE;
9299
9300 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9301 i += BPF_REG_SIZE - 1;
9302 /* explored state didn't use this */
9303 continue;
9304 }
9305
9306 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9307 continue;
9308
9309 /* explored stack has more populated slots than current stack
9310 * and these slots were used
9311 */
9312 if (i >= cur->allocated_stack)
9313 return false;
9314
9315 /* if old state was safe with misc data in the stack
9316 * it will be safe with zero-initialized stack.
9317 * The opposite is not true
9318 */
9319 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9320 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9321 continue;
9322 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9323 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9324 /* Ex: old explored (safe) state has STACK_SPILL in
9325 * this stack slot, but current has STACK_MISC ->
9326 * this verifier states are not equivalent,
9327 * return false to continue verification of this path
9328 */
9329 return false;
9330 if (i % BPF_REG_SIZE)
9331 continue;
9332 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9333 continue;
9334 if (!regsafe(&old->stack[spi].spilled_ptr,
9335 &cur->stack[spi].spilled_ptr,
9336 idmap))
9337 /* when explored and current stack slot are both storing
9338 * spilled registers, check that stored pointers types
9339 * are the same as well.
9340 * Ex: explored safe path could have stored
9341 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9342 * but current path has stored:
9343 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9344 * such verifier states are not equivalent.
9345 * return false to continue verification of this path
9346 */
9347 return false;
9348 }
9349 return true;
9350 }
9351
9352 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9353 {
9354 if (old->acquired_refs != cur->acquired_refs)
9355 return false;
9356 return !memcmp(old->refs, cur->refs,
9357 sizeof(*old->refs) * old->acquired_refs);
9358 }
9359
9360 /* compare two verifier states
9361 *
9362 * all states stored in state_list are known to be valid, since
9363 * verifier reached 'bpf_exit' instruction through them
9364 *
9365 * this function is called when verifier exploring different branches of
9366 * execution popped from the state stack. If it sees an old state that has
9367 * more strict register state and more strict stack state then this execution
9368 * branch doesn't need to be explored further, since verifier already
9369 * concluded that more strict state leads to valid finish.
9370 *
9371 * Therefore two states are equivalent if register state is more conservative
9372 * and explored stack state is more conservative than the current one.
9373 * Example:
9374 * explored current
9375 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9376 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9377 *
9378 * In other words if current stack state (one being explored) has more
9379 * valid slots than old one that already passed validation, it means
9380 * the verifier can stop exploring and conclude that current state is valid too
9381 *
9382 * Similarly with registers. If explored state has register type as invalid
9383 * whereas register type in current state is meaningful, it means that
9384 * the current state will reach 'bpf_exit' instruction safely
9385 */
9386 static bool func_states_equal(struct bpf_func_state *old,
9387 struct bpf_func_state *cur)
9388 {
9389 struct idpair *idmap;
9390 bool ret = false;
9391 int i;
9392
9393 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9394 /* If we failed to allocate the idmap, just say it's not safe */
9395 if (!idmap)
9396 return false;
9397
9398 for (i = 0; i < MAX_BPF_REG; i++) {
9399 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
9400 goto out_free;
9401 }
9402
9403 if (!stacksafe(old, cur, idmap))
9404 goto out_free;
9405
9406 if (!refsafe(old, cur))
9407 goto out_free;
9408 ret = true;
9409 out_free:
9410 kfree(idmap);
9411 return ret;
9412 }
9413
9414 static bool states_equal(struct bpf_verifier_env *env,
9415 struct bpf_verifier_state *old,
9416 struct bpf_verifier_state *cur)
9417 {
9418 int i;
9419
9420 if (old->curframe != cur->curframe)
9421 return false;
9422
9423 /* Verification state from speculative execution simulation
9424 * must never prune a non-speculative execution one.
9425 */
9426 if (old->speculative && !cur->speculative)
9427 return false;
9428
9429 if (old->active_spin_lock != cur->active_spin_lock)
9430 return false;
9431
9432 /* for states to be equal callsites have to be the same
9433 * and all frame states need to be equivalent
9434 */
9435 for (i = 0; i <= old->curframe; i++) {
9436 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9437 return false;
9438 if (!func_states_equal(old->frame[i], cur->frame[i]))
9439 return false;
9440 }
9441 return true;
9442 }
9443
9444 /* Return 0 if no propagation happened. Return negative error code if error
9445 * happened. Otherwise, return the propagated bit.
9446 */
9447 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9448 struct bpf_reg_state *reg,
9449 struct bpf_reg_state *parent_reg)
9450 {
9451 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9452 u8 flag = reg->live & REG_LIVE_READ;
9453 int err;
9454
9455 /* When comes here, read flags of PARENT_REG or REG could be any of
9456 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9457 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9458 */
9459 if (parent_flag == REG_LIVE_READ64 ||
9460 /* Or if there is no read flag from REG. */
9461 !flag ||
9462 /* Or if the read flag from REG is the same as PARENT_REG. */
9463 parent_flag == flag)
9464 return 0;
9465
9466 err = mark_reg_read(env, reg, parent_reg, flag);
9467 if (err)
9468 return err;
9469
9470 return flag;
9471 }
9472
9473 /* A write screens off any subsequent reads; but write marks come from the
9474 * straight-line code between a state and its parent. When we arrive at an
9475 * equivalent state (jump target or such) we didn't arrive by the straight-line
9476 * code, so read marks in the state must propagate to the parent regardless
9477 * of the state's write marks. That's what 'parent == state->parent' comparison
9478 * in mark_reg_read() is for.
9479 */
9480 static int propagate_liveness(struct bpf_verifier_env *env,
9481 const struct bpf_verifier_state *vstate,
9482 struct bpf_verifier_state *vparent)
9483 {
9484 struct bpf_reg_state *state_reg, *parent_reg;
9485 struct bpf_func_state *state, *parent;
9486 int i, frame, err = 0;
9487
9488 if (vparent->curframe != vstate->curframe) {
9489 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9490 vparent->curframe, vstate->curframe);
9491 return -EFAULT;
9492 }
9493 /* Propagate read liveness of registers... */
9494 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9495 for (frame = 0; frame <= vstate->curframe; frame++) {
9496 parent = vparent->frame[frame];
9497 state = vstate->frame[frame];
9498 parent_reg = parent->regs;
9499 state_reg = state->regs;
9500 /* We don't need to worry about FP liveness, it's read-only */
9501 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9502 err = propagate_liveness_reg(env, &state_reg[i],
9503 &parent_reg[i]);
9504 if (err < 0)
9505 return err;
9506 if (err == REG_LIVE_READ64)
9507 mark_insn_zext(env, &parent_reg[i]);
9508 }
9509
9510 /* Propagate stack slots. */
9511 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9512 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9513 parent_reg = &parent->stack[i].spilled_ptr;
9514 state_reg = &state->stack[i].spilled_ptr;
9515 err = propagate_liveness_reg(env, state_reg,
9516 parent_reg);
9517 if (err < 0)
9518 return err;
9519 }
9520 }
9521 return 0;
9522 }
9523
9524 /* find precise scalars in the previous equivalent state and
9525 * propagate them into the current state
9526 */
9527 static int propagate_precision(struct bpf_verifier_env *env,
9528 const struct bpf_verifier_state *old)
9529 {
9530 struct bpf_reg_state *state_reg;
9531 struct bpf_func_state *state;
9532 int i, err = 0;
9533
9534 state = old->frame[old->curframe];
9535 state_reg = state->regs;
9536 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9537 if (state_reg->type != SCALAR_VALUE ||
9538 !state_reg->precise)
9539 continue;
9540 if (env->log.level & BPF_LOG_LEVEL2)
9541 verbose(env, "propagating r%d\n", i);
9542 err = mark_chain_precision(env, i);
9543 if (err < 0)
9544 return err;
9545 }
9546
9547 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9548 if (state->stack[i].slot_type[0] != STACK_SPILL)
9549 continue;
9550 state_reg = &state->stack[i].spilled_ptr;
9551 if (state_reg->type != SCALAR_VALUE ||
9552 !state_reg->precise)
9553 continue;
9554 if (env->log.level & BPF_LOG_LEVEL2)
9555 verbose(env, "propagating fp%d\n",
9556 (-i - 1) * BPF_REG_SIZE);
9557 err = mark_chain_precision_stack(env, i);
9558 if (err < 0)
9559 return err;
9560 }
9561 return 0;
9562 }
9563
9564 static bool states_maybe_looping(struct bpf_verifier_state *old,
9565 struct bpf_verifier_state *cur)
9566 {
9567 struct bpf_func_state *fold, *fcur;
9568 int i, fr = cur->curframe;
9569
9570 if (old->curframe != fr)
9571 return false;
9572
9573 fold = old->frame[fr];
9574 fcur = cur->frame[fr];
9575 for (i = 0; i < MAX_BPF_REG; i++)
9576 if (memcmp(&fold->regs[i], &fcur->regs[i],
9577 offsetof(struct bpf_reg_state, parent)))
9578 return false;
9579 return true;
9580 }
9581
9582
9583 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9584 {
9585 struct bpf_verifier_state_list *new_sl;
9586 struct bpf_verifier_state_list *sl, **pprev;
9587 struct bpf_verifier_state *cur = env->cur_state, *new;
9588 int i, j, err, states_cnt = 0;
9589 bool add_new_state = env->test_state_freq ? true : false;
9590
9591 cur->last_insn_idx = env->prev_insn_idx;
9592 if (!env->insn_aux_data[insn_idx].prune_point)
9593 /* this 'insn_idx' instruction wasn't marked, so we will not
9594 * be doing state search here
9595 */
9596 return 0;
9597
9598 /* bpf progs typically have pruning point every 4 instructions
9599 * http://vger.kernel.org/bpfconf2019.html#session-1
9600 * Do not add new state for future pruning if the verifier hasn't seen
9601 * at least 2 jumps and at least 8 instructions.
9602 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9603 * In tests that amounts to up to 50% reduction into total verifier
9604 * memory consumption and 20% verifier time speedup.
9605 */
9606 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9607 env->insn_processed - env->prev_insn_processed >= 8)
9608 add_new_state = true;
9609
9610 pprev = explored_state(env, insn_idx);
9611 sl = *pprev;
9612
9613 clean_live_states(env, insn_idx, cur);
9614
9615 while (sl) {
9616 states_cnt++;
9617 if (sl->state.insn_idx != insn_idx)
9618 goto next;
9619 if (sl->state.branches) {
9620 if (states_maybe_looping(&sl->state, cur) &&
9621 states_equal(env, &sl->state, cur)) {
9622 verbose_linfo(env, insn_idx, "; ");
9623 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9624 return -EINVAL;
9625 }
9626 /* if the verifier is processing a loop, avoid adding new state
9627 * too often, since different loop iterations have distinct
9628 * states and may not help future pruning.
9629 * This threshold shouldn't be too low to make sure that
9630 * a loop with large bound will be rejected quickly.
9631 * The most abusive loop will be:
9632 * r1 += 1
9633 * if r1 < 1000000 goto pc-2
9634 * 1M insn_procssed limit / 100 == 10k peak states.
9635 * This threshold shouldn't be too high either, since states
9636 * at the end of the loop are likely to be useful in pruning.
9637 */
9638 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9639 env->insn_processed - env->prev_insn_processed < 100)
9640 add_new_state = false;
9641 goto miss;
9642 }
9643 if (states_equal(env, &sl->state, cur)) {
9644 sl->hit_cnt++;
9645 /* reached equivalent register/stack state,
9646 * prune the search.
9647 * Registers read by the continuation are read by us.
9648 * If we have any write marks in env->cur_state, they
9649 * will prevent corresponding reads in the continuation
9650 * from reaching our parent (an explored_state). Our
9651 * own state will get the read marks recorded, but
9652 * they'll be immediately forgotten as we're pruning
9653 * this state and will pop a new one.
9654 */
9655 err = propagate_liveness(env, &sl->state, cur);
9656
9657 /* if previous state reached the exit with precision and
9658 * current state is equivalent to it (except precsion marks)
9659 * the precision needs to be propagated back in
9660 * the current state.
9661 */
9662 err = err ? : push_jmp_history(env, cur);
9663 err = err ? : propagate_precision(env, &sl->state);
9664 if (err)
9665 return err;
9666 return 1;
9667 }
9668 miss:
9669 /* when new state is not going to be added do not increase miss count.
9670 * Otherwise several loop iterations will remove the state
9671 * recorded earlier. The goal of these heuristics is to have
9672 * states from some iterations of the loop (some in the beginning
9673 * and some at the end) to help pruning.
9674 */
9675 if (add_new_state)
9676 sl->miss_cnt++;
9677 /* heuristic to determine whether this state is beneficial
9678 * to keep checking from state equivalence point of view.
9679 * Higher numbers increase max_states_per_insn and verification time,
9680 * but do not meaningfully decrease insn_processed.
9681 */
9682 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9683 /* the state is unlikely to be useful. Remove it to
9684 * speed up verification
9685 */
9686 *pprev = sl->next;
9687 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9688 u32 br = sl->state.branches;
9689
9690 WARN_ONCE(br,
9691 "BUG live_done but branches_to_explore %d\n",
9692 br);
9693 free_verifier_state(&sl->state, false);
9694 kfree(sl);
9695 env->peak_states--;
9696 } else {
9697 /* cannot free this state, since parentage chain may
9698 * walk it later. Add it for free_list instead to
9699 * be freed at the end of verification
9700 */
9701 sl->next = env->free_list;
9702 env->free_list = sl;
9703 }
9704 sl = *pprev;
9705 continue;
9706 }
9707 next:
9708 pprev = &sl->next;
9709 sl = *pprev;
9710 }
9711
9712 if (env->max_states_per_insn < states_cnt)
9713 env->max_states_per_insn = states_cnt;
9714
9715 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9716 return push_jmp_history(env, cur);
9717
9718 if (!add_new_state)
9719 return push_jmp_history(env, cur);
9720
9721 /* There were no equivalent states, remember the current one.
9722 * Technically the current state is not proven to be safe yet,
9723 * but it will either reach outer most bpf_exit (which means it's safe)
9724 * or it will be rejected. When there are no loops the verifier won't be
9725 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9726 * again on the way to bpf_exit.
9727 * When looping the sl->state.branches will be > 0 and this state
9728 * will not be considered for equivalence until branches == 0.
9729 */
9730 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9731 if (!new_sl)
9732 return -ENOMEM;
9733 env->total_states++;
9734 env->peak_states++;
9735 env->prev_jmps_processed = env->jmps_processed;
9736 env->prev_insn_processed = env->insn_processed;
9737
9738 /* add new state to the head of linked list */
9739 new = &new_sl->state;
9740 err = copy_verifier_state(new, cur);
9741 if (err) {
9742 free_verifier_state(new, false);
9743 kfree(new_sl);
9744 return err;
9745 }
9746 new->insn_idx = insn_idx;
9747 WARN_ONCE(new->branches != 1,
9748 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9749
9750 cur->parent = new;
9751 cur->first_insn_idx = insn_idx;
9752 clear_jmp_history(cur);
9753 new_sl->next = *explored_state(env, insn_idx);
9754 *explored_state(env, insn_idx) = new_sl;
9755 /* connect new state to parentage chain. Current frame needs all
9756 * registers connected. Only r6 - r9 of the callers are alive (pushed
9757 * to the stack implicitly by JITs) so in callers' frames connect just
9758 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9759 * the state of the call instruction (with WRITTEN set), and r0 comes
9760 * from callee with its full parentage chain, anyway.
9761 */
9762 /* clear write marks in current state: the writes we did are not writes
9763 * our child did, so they don't screen off its reads from us.
9764 * (There are no read marks in current state, because reads always mark
9765 * their parent and current state never has children yet. Only
9766 * explored_states can get read marks.)
9767 */
9768 for (j = 0; j <= cur->curframe; j++) {
9769 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9770 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9771 for (i = 0; i < BPF_REG_FP; i++)
9772 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9773 }
9774
9775 /* all stack frames are accessible from callee, clear them all */
9776 for (j = 0; j <= cur->curframe; j++) {
9777 struct bpf_func_state *frame = cur->frame[j];
9778 struct bpf_func_state *newframe = new->frame[j];
9779
9780 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9781 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9782 frame->stack[i].spilled_ptr.parent =
9783 &newframe->stack[i].spilled_ptr;
9784 }
9785 }
9786 return 0;
9787 }
9788
9789 /* Return true if it's OK to have the same insn return a different type. */
9790 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9791 {
9792 switch (type) {
9793 case PTR_TO_CTX:
9794 case PTR_TO_SOCKET:
9795 case PTR_TO_SOCKET_OR_NULL:
9796 case PTR_TO_SOCK_COMMON:
9797 case PTR_TO_SOCK_COMMON_OR_NULL:
9798 case PTR_TO_TCP_SOCK:
9799 case PTR_TO_TCP_SOCK_OR_NULL:
9800 case PTR_TO_XDP_SOCK:
9801 case PTR_TO_BTF_ID:
9802 case PTR_TO_BTF_ID_OR_NULL:
9803 return false;
9804 default:
9805 return true;
9806 }
9807 }
9808
9809 /* If an instruction was previously used with particular pointer types, then we
9810 * need to be careful to avoid cases such as the below, where it may be ok
9811 * for one branch accessing the pointer, but not ok for the other branch:
9812 *
9813 * R1 = sock_ptr
9814 * goto X;
9815 * ...
9816 * R1 = some_other_valid_ptr;
9817 * goto X;
9818 * ...
9819 * R2 = *(u32 *)(R1 + 0);
9820 */
9821 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9822 {
9823 return src != prev && (!reg_type_mismatch_ok(src) ||
9824 !reg_type_mismatch_ok(prev));
9825 }
9826
9827 static int do_check(struct bpf_verifier_env *env)
9828 {
9829 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
9830 struct bpf_verifier_state *state = env->cur_state;
9831 struct bpf_insn *insns = env->prog->insnsi;
9832 struct bpf_reg_state *regs;
9833 int insn_cnt = env->prog->len;
9834 bool do_print_state = false;
9835 int prev_insn_idx = -1;
9836
9837 for (;;) {
9838 struct bpf_insn *insn;
9839 u8 class;
9840 int err;
9841
9842 env->prev_insn_idx = prev_insn_idx;
9843 if (env->insn_idx >= insn_cnt) {
9844 verbose(env, "invalid insn idx %d insn_cnt %d\n",
9845 env->insn_idx, insn_cnt);
9846 return -EFAULT;
9847 }
9848
9849 insn = &insns[env->insn_idx];
9850 class = BPF_CLASS(insn->code);
9851
9852 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
9853 verbose(env,
9854 "BPF program is too large. Processed %d insn\n",
9855 env->insn_processed);
9856 return -E2BIG;
9857 }
9858
9859 err = is_state_visited(env, env->insn_idx);
9860 if (err < 0)
9861 return err;
9862 if (err == 1) {
9863 /* found equivalent state, can prune the search */
9864 if (env->log.level & BPF_LOG_LEVEL) {
9865 if (do_print_state)
9866 verbose(env, "\nfrom %d to %d%s: safe\n",
9867 env->prev_insn_idx, env->insn_idx,
9868 env->cur_state->speculative ?
9869 " (speculative execution)" : "");
9870 else
9871 verbose(env, "%d: safe\n", env->insn_idx);
9872 }
9873 goto process_bpf_exit;
9874 }
9875
9876 if (signal_pending(current))
9877 return -EAGAIN;
9878
9879 if (need_resched())
9880 cond_resched();
9881
9882 if (env->log.level & BPF_LOG_LEVEL2 ||
9883 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9884 if (env->log.level & BPF_LOG_LEVEL2)
9885 verbose(env, "%d:", env->insn_idx);
9886 else
9887 verbose(env, "\nfrom %d to %d%s:",
9888 env->prev_insn_idx, env->insn_idx,
9889 env->cur_state->speculative ?
9890 " (speculative execution)" : "");
9891 print_verifier_state(env, state->frame[state->curframe]);
9892 do_print_state = false;
9893 }
9894
9895 if (env->log.level & BPF_LOG_LEVEL) {
9896 const struct bpf_insn_cbs cbs = {
9897 .cb_print = verbose,
9898 .private_data = env,
9899 };
9900
9901 verbose_linfo(env, env->insn_idx, "; ");
9902 verbose(env, "%d: ", env->insn_idx);
9903 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
9904 }
9905
9906 if (bpf_prog_is_dev_bound(env->prog->aux)) {
9907 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9908 env->prev_insn_idx);
9909 if (err)
9910 return err;
9911 }
9912
9913 regs = cur_regs(env);
9914 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
9915 prev_insn_idx = env->insn_idx;
9916
9917 if (class == BPF_ALU || class == BPF_ALU64) {
9918 err = check_alu_op(env, insn);
9919 if (err)
9920 return err;
9921
9922 } else if (class == BPF_LDX) {
9923 enum bpf_reg_type *prev_src_type, src_reg_type;
9924
9925 /* check for reserved fields is already done */
9926
9927 /* check src operand */
9928 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9929 if (err)
9930 return err;
9931
9932 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
9933 if (err)
9934 return err;
9935
9936 src_reg_type = regs[insn->src_reg].type;
9937
9938 /* check that memory (src_reg + off) is readable,
9939 * the state of dst_reg will be updated by this func
9940 */
9941 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9942 insn->off, BPF_SIZE(insn->code),
9943 BPF_READ, insn->dst_reg, false);
9944 if (err)
9945 return err;
9946
9947 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9948
9949 if (*prev_src_type == NOT_INIT) {
9950 /* saw a valid insn
9951 * dst_reg = *(u32 *)(src_reg + off)
9952 * save type to validate intersecting paths
9953 */
9954 *prev_src_type = src_reg_type;
9955
9956 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9957 /* ABuser program is trying to use the same insn
9958 * dst_reg = *(u32*) (src_reg + off)
9959 * with different pointer types:
9960 * src_reg == ctx in one branch and
9961 * src_reg == stack|map in some other branch.
9962 * Reject it.
9963 */
9964 verbose(env, "same insn cannot be used with different pointers\n");
9965 return -EINVAL;
9966 }
9967
9968 } else if (class == BPF_STX) {
9969 enum bpf_reg_type *prev_dst_type, dst_reg_type;
9970
9971 if (BPF_MODE(insn->code) == BPF_XADD) {
9972 err = check_xadd(env, env->insn_idx, insn);
9973 if (err)
9974 return err;
9975 env->insn_idx++;
9976 continue;
9977 }
9978
9979 /* check src1 operand */
9980 err = check_reg_arg(env, insn->src_reg, SRC_OP);
9981 if (err)
9982 return err;
9983 /* check src2 operand */
9984 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
9985 if (err)
9986 return err;
9987
9988 dst_reg_type = regs[insn->dst_reg].type;
9989
9990 /* check that memory (dst_reg + off) is writeable */
9991 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
9992 insn->off, BPF_SIZE(insn->code),
9993 BPF_WRITE, insn->src_reg, false);
9994 if (err)
9995 return err;
9996
9997 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
9998
9999 if (*prev_dst_type == NOT_INIT) {
10000 *prev_dst_type = dst_reg_type;
10001 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10002 verbose(env, "same insn cannot be used with different pointers\n");
10003 return -EINVAL;
10004 }
10005
10006 } else if (class == BPF_ST) {
10007 if (BPF_MODE(insn->code) != BPF_MEM ||
10008 insn->src_reg != BPF_REG_0) {
10009 verbose(env, "BPF_ST uses reserved fields\n");
10010 return -EINVAL;
10011 }
10012 /* check src operand */
10013 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10014 if (err)
10015 return err;
10016
10017 if (is_ctx_reg(env, insn->dst_reg)) {
10018 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10019 insn->dst_reg,
10020 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10021 return -EACCES;
10022 }
10023
10024 /* check that memory (dst_reg + off) is writeable */
10025 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10026 insn->off, BPF_SIZE(insn->code),
10027 BPF_WRITE, -1, false);
10028 if (err)
10029 return err;
10030
10031 } else if (class == BPF_JMP || class == BPF_JMP32) {
10032 u8 opcode = BPF_OP(insn->code);
10033
10034 env->jmps_processed++;
10035 if (opcode == BPF_CALL) {
10036 if (BPF_SRC(insn->code) != BPF_K ||
10037 insn->off != 0 ||
10038 (insn->src_reg != BPF_REG_0 &&
10039 insn->src_reg != BPF_PSEUDO_CALL) ||
10040 insn->dst_reg != BPF_REG_0 ||
10041 class == BPF_JMP32) {
10042 verbose(env, "BPF_CALL uses reserved fields\n");
10043 return -EINVAL;
10044 }
10045
10046 if (env->cur_state->active_spin_lock &&
10047 (insn->src_reg == BPF_PSEUDO_CALL ||
10048 insn->imm != BPF_FUNC_spin_unlock)) {
10049 verbose(env, "function calls are not allowed while holding a lock\n");
10050 return -EINVAL;
10051 }
10052 if (insn->src_reg == BPF_PSEUDO_CALL)
10053 err = check_func_call(env, insn, &env->insn_idx);
10054 else
10055 err = check_helper_call(env, insn->imm, env->insn_idx);
10056 if (err)
10057 return err;
10058
10059 } else if (opcode == BPF_JA) {
10060 if (BPF_SRC(insn->code) != BPF_K ||
10061 insn->imm != 0 ||
10062 insn->src_reg != BPF_REG_0 ||
10063 insn->dst_reg != BPF_REG_0 ||
10064 class == BPF_JMP32) {
10065 verbose(env, "BPF_JA uses reserved fields\n");
10066 return -EINVAL;
10067 }
10068
10069 env->insn_idx += insn->off + 1;
10070 continue;
10071
10072 } else if (opcode == BPF_EXIT) {
10073 if (BPF_SRC(insn->code) != BPF_K ||
10074 insn->imm != 0 ||
10075 insn->src_reg != BPF_REG_0 ||
10076 insn->dst_reg != BPF_REG_0 ||
10077 class == BPF_JMP32) {
10078 verbose(env, "BPF_EXIT uses reserved fields\n");
10079 return -EINVAL;
10080 }
10081
10082 if (env->cur_state->active_spin_lock) {
10083 verbose(env, "bpf_spin_unlock is missing\n");
10084 return -EINVAL;
10085 }
10086
10087 if (state->curframe) {
10088 /* exit from nested function */
10089 err = prepare_func_exit(env, &env->insn_idx);
10090 if (err)
10091 return err;
10092 do_print_state = true;
10093 continue;
10094 }
10095
10096 err = check_reference_leak(env);
10097 if (err)
10098 return err;
10099
10100 err = check_return_code(env);
10101 if (err)
10102 return err;
10103 process_bpf_exit:
10104 update_branch_counts(env, env->cur_state);
10105 err = pop_stack(env, &prev_insn_idx,
10106 &env->insn_idx, pop_log);
10107 if (err < 0) {
10108 if (err != -ENOENT)
10109 return err;
10110 break;
10111 } else {
10112 do_print_state = true;
10113 continue;
10114 }
10115 } else {
10116 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10117 if (err)
10118 return err;
10119 }
10120 } else if (class == BPF_LD) {
10121 u8 mode = BPF_MODE(insn->code);
10122
10123 if (mode == BPF_ABS || mode == BPF_IND) {
10124 err = check_ld_abs(env, insn);
10125 if (err)
10126 return err;
10127
10128 } else if (mode == BPF_IMM) {
10129 err = check_ld_imm(env, insn);
10130 if (err)
10131 return err;
10132
10133 env->insn_idx++;
10134 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
10135 } else {
10136 verbose(env, "invalid BPF_LD mode\n");
10137 return -EINVAL;
10138 }
10139 } else {
10140 verbose(env, "unknown insn class %d\n", class);
10141 return -EINVAL;
10142 }
10143
10144 env->insn_idx++;
10145 }
10146
10147 return 0;
10148 }
10149
10150 /* replace pseudo btf_id with kernel symbol address */
10151 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10152 struct bpf_insn *insn,
10153 struct bpf_insn_aux_data *aux)
10154 {
10155 const struct btf_var_secinfo *vsi;
10156 const struct btf_type *datasec;
10157 const struct btf_type *t;
10158 const char *sym_name;
10159 bool percpu = false;
10160 u32 type, id = insn->imm;
10161 s32 datasec_id;
10162 u64 addr;
10163 int i;
10164
10165 if (!btf_vmlinux) {
10166 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10167 return -EINVAL;
10168 }
10169
10170 if (insn[1].imm != 0) {
10171 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10172 return -EINVAL;
10173 }
10174
10175 t = btf_type_by_id(btf_vmlinux, id);
10176 if (!t) {
10177 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10178 return -ENOENT;
10179 }
10180
10181 if (!btf_type_is_var(t)) {
10182 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10183 id);
10184 return -EINVAL;
10185 }
10186
10187 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10188 addr = kallsyms_lookup_name(sym_name);
10189 if (!addr) {
10190 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10191 sym_name);
10192 return -ENOENT;
10193 }
10194
10195 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10196 BTF_KIND_DATASEC);
10197 if (datasec_id > 0) {
10198 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10199 for_each_vsi(i, datasec, vsi) {
10200 if (vsi->type == id) {
10201 percpu = true;
10202 break;
10203 }
10204 }
10205 }
10206
10207 insn[0].imm = (u32)addr;
10208 insn[1].imm = addr >> 32;
10209
10210 type = t->type;
10211 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10212 if (percpu) {
10213 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10214 aux->btf_var.btf = btf_vmlinux;
10215 aux->btf_var.btf_id = type;
10216 } else if (!btf_type_is_struct(t)) {
10217 const struct btf_type *ret;
10218 const char *tname;
10219 u32 tsize;
10220
10221 /* resolve the type size of ksym. */
10222 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10223 if (IS_ERR(ret)) {
10224 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10225 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10226 tname, PTR_ERR(ret));
10227 return -EINVAL;
10228 }
10229 aux->btf_var.reg_type = PTR_TO_MEM;
10230 aux->btf_var.mem_size = tsize;
10231 } else {
10232 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10233 aux->btf_var.btf = btf_vmlinux;
10234 aux->btf_var.btf_id = type;
10235 }
10236 return 0;
10237 }
10238
10239 static int check_map_prealloc(struct bpf_map *map)
10240 {
10241 return (map->map_type != BPF_MAP_TYPE_HASH &&
10242 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10243 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10244 !(map->map_flags & BPF_F_NO_PREALLOC);
10245 }
10246
10247 static bool is_tracing_prog_type(enum bpf_prog_type type)
10248 {
10249 switch (type) {
10250 case BPF_PROG_TYPE_KPROBE:
10251 case BPF_PROG_TYPE_TRACEPOINT:
10252 case BPF_PROG_TYPE_PERF_EVENT:
10253 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10254 return true;
10255 default:
10256 return false;
10257 }
10258 }
10259
10260 static bool is_preallocated_map(struct bpf_map *map)
10261 {
10262 if (!check_map_prealloc(map))
10263 return false;
10264 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10265 return false;
10266 return true;
10267 }
10268
10269 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10270 struct bpf_map *map,
10271 struct bpf_prog *prog)
10272
10273 {
10274 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10275 /*
10276 * Validate that trace type programs use preallocated hash maps.
10277 *
10278 * For programs attached to PERF events this is mandatory as the
10279 * perf NMI can hit any arbitrary code sequence.
10280 *
10281 * All other trace types using preallocated hash maps are unsafe as
10282 * well because tracepoint or kprobes can be inside locked regions
10283 * of the memory allocator or at a place where a recursion into the
10284 * memory allocator would see inconsistent state.
10285 *
10286 * On RT enabled kernels run-time allocation of all trace type
10287 * programs is strictly prohibited due to lock type constraints. On
10288 * !RT kernels it is allowed for backwards compatibility reasons for
10289 * now, but warnings are emitted so developers are made aware of
10290 * the unsafety and can fix their programs before this is enforced.
10291 */
10292 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10293 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10294 verbose(env, "perf_event programs can only use preallocated hash map\n");
10295 return -EINVAL;
10296 }
10297 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10298 verbose(env, "trace type programs can only use preallocated hash map\n");
10299 return -EINVAL;
10300 }
10301 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10302 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10303 }
10304
10305 if (map_value_has_spin_lock(map)) {
10306 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10307 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10308 return -EINVAL;
10309 }
10310
10311 if (is_tracing_prog_type(prog_type)) {
10312 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10313 return -EINVAL;
10314 }
10315
10316 if (prog->aux->sleepable) {
10317 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10318 return -EINVAL;
10319 }
10320 }
10321
10322 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10323 !bpf_offload_prog_map_match(prog, map)) {
10324 verbose(env, "offload device mismatch between prog and map\n");
10325 return -EINVAL;
10326 }
10327
10328 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10329 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10330 return -EINVAL;
10331 }
10332
10333 if (prog->aux->sleepable)
10334 switch (map->map_type) {
10335 case BPF_MAP_TYPE_HASH:
10336 case BPF_MAP_TYPE_LRU_HASH:
10337 case BPF_MAP_TYPE_ARRAY:
10338 if (!is_preallocated_map(map)) {
10339 verbose(env,
10340 "Sleepable programs can only use preallocated hash maps\n");
10341 return -EINVAL;
10342 }
10343 break;
10344 default:
10345 verbose(env,
10346 "Sleepable programs can only use array and hash maps\n");
10347 return -EINVAL;
10348 }
10349
10350 return 0;
10351 }
10352
10353 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10354 {
10355 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10356 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10357 }
10358
10359 /* find and rewrite pseudo imm in ld_imm64 instructions:
10360 *
10361 * 1. if it accesses map FD, replace it with actual map pointer.
10362 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10363 *
10364 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10365 */
10366 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10367 {
10368 struct bpf_insn *insn = env->prog->insnsi;
10369 int insn_cnt = env->prog->len;
10370 int i, j, err;
10371
10372 err = bpf_prog_calc_tag(env->prog);
10373 if (err)
10374 return err;
10375
10376 for (i = 0; i < insn_cnt; i++, insn++) {
10377 if (BPF_CLASS(insn->code) == BPF_LDX &&
10378 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10379 verbose(env, "BPF_LDX uses reserved fields\n");
10380 return -EINVAL;
10381 }
10382
10383 if (BPF_CLASS(insn->code) == BPF_STX &&
10384 ((BPF_MODE(insn->code) != BPF_MEM &&
10385 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10386 verbose(env, "BPF_STX uses reserved fields\n");
10387 return -EINVAL;
10388 }
10389
10390 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10391 struct bpf_insn_aux_data *aux;
10392 struct bpf_map *map;
10393 struct fd f;
10394 u64 addr;
10395
10396 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10397 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10398 insn[1].off != 0) {
10399 verbose(env, "invalid bpf_ld_imm64 insn\n");
10400 return -EINVAL;
10401 }
10402
10403 if (insn[0].src_reg == 0)
10404 /* valid generic load 64-bit imm */
10405 goto next_insn;
10406
10407 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10408 aux = &env->insn_aux_data[i];
10409 err = check_pseudo_btf_id(env, insn, aux);
10410 if (err)
10411 return err;
10412 goto next_insn;
10413 }
10414
10415 /* In final convert_pseudo_ld_imm64() step, this is
10416 * converted into regular 64-bit imm load insn.
10417 */
10418 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10419 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10420 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10421 insn[1].imm != 0)) {
10422 verbose(env,
10423 "unrecognized bpf_ld_imm64 insn\n");
10424 return -EINVAL;
10425 }
10426
10427 f = fdget(insn[0].imm);
10428 map = __bpf_map_get(f);
10429 if (IS_ERR(map)) {
10430 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10431 insn[0].imm);
10432 return PTR_ERR(map);
10433 }
10434
10435 err = check_map_prog_compatibility(env, map, env->prog);
10436 if (err) {
10437 fdput(f);
10438 return err;
10439 }
10440
10441 aux = &env->insn_aux_data[i];
10442 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10443 addr = (unsigned long)map;
10444 } else {
10445 u32 off = insn[1].imm;
10446
10447 if (off >= BPF_MAX_VAR_OFF) {
10448 verbose(env, "direct value offset of %u is not allowed\n", off);
10449 fdput(f);
10450 return -EINVAL;
10451 }
10452
10453 if (!map->ops->map_direct_value_addr) {
10454 verbose(env, "no direct value access support for this map type\n");
10455 fdput(f);
10456 return -EINVAL;
10457 }
10458
10459 err = map->ops->map_direct_value_addr(map, &addr, off);
10460 if (err) {
10461 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10462 map->value_size, off);
10463 fdput(f);
10464 return err;
10465 }
10466
10467 aux->map_off = off;
10468 addr += off;
10469 }
10470
10471 insn[0].imm = (u32)addr;
10472 insn[1].imm = addr >> 32;
10473
10474 /* check whether we recorded this map already */
10475 for (j = 0; j < env->used_map_cnt; j++) {
10476 if (env->used_maps[j] == map) {
10477 aux->map_index = j;
10478 fdput(f);
10479 goto next_insn;
10480 }
10481 }
10482
10483 if (env->used_map_cnt >= MAX_USED_MAPS) {
10484 fdput(f);
10485 return -E2BIG;
10486 }
10487
10488 /* hold the map. If the program is rejected by verifier,
10489 * the map will be released by release_maps() or it
10490 * will be used by the valid program until it's unloaded
10491 * and all maps are released in free_used_maps()
10492 */
10493 bpf_map_inc(map);
10494
10495 aux->map_index = env->used_map_cnt;
10496 env->used_maps[env->used_map_cnt++] = map;
10497
10498 if (bpf_map_is_cgroup_storage(map) &&
10499 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10500 verbose(env, "only one cgroup storage of each type is allowed\n");
10501 fdput(f);
10502 return -EBUSY;
10503 }
10504
10505 fdput(f);
10506 next_insn:
10507 insn++;
10508 i++;
10509 continue;
10510 }
10511
10512 /* Basic sanity check before we invest more work here. */
10513 if (!bpf_opcode_in_insntable(insn->code)) {
10514 verbose(env, "unknown opcode %02x\n", insn->code);
10515 return -EINVAL;
10516 }
10517 }
10518
10519 /* now all pseudo BPF_LD_IMM64 instructions load valid
10520 * 'struct bpf_map *' into a register instead of user map_fd.
10521 * These pointers will be used later by verifier to validate map access.
10522 */
10523 return 0;
10524 }
10525
10526 /* drop refcnt of maps used by the rejected program */
10527 static void release_maps(struct bpf_verifier_env *env)
10528 {
10529 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10530 env->used_map_cnt);
10531 }
10532
10533 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
10534 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10535 {
10536 struct bpf_insn *insn = env->prog->insnsi;
10537 int insn_cnt = env->prog->len;
10538 int i;
10539
10540 for (i = 0; i < insn_cnt; i++, insn++)
10541 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10542 insn->src_reg = 0;
10543 }
10544
10545 /* single env->prog->insni[off] instruction was replaced with the range
10546 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10547 * [0, off) and [off, end) to new locations, so the patched range stays zero
10548 */
10549 static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10550 struct bpf_prog *new_prog, u32 off, u32 cnt)
10551 {
10552 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
10553 struct bpf_insn *insn = new_prog->insnsi;
10554 u32 prog_len;
10555 int i;
10556
10557 /* aux info at OFF always needs adjustment, no matter fast path
10558 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10559 * original insn at old prog.
10560 */
10561 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10562
10563 if (cnt == 1)
10564 return 0;
10565 prog_len = new_prog->len;
10566 new_data = vzalloc(array_size(prog_len,
10567 sizeof(struct bpf_insn_aux_data)));
10568 if (!new_data)
10569 return -ENOMEM;
10570 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10571 memcpy(new_data + off + cnt - 1, old_data + off,
10572 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10573 for (i = off; i < off + cnt - 1; i++) {
10574 new_data[i].seen = env->pass_cnt;
10575 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10576 }
10577 env->insn_aux_data = new_data;
10578 vfree(old_data);
10579 return 0;
10580 }
10581
10582 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10583 {
10584 int i;
10585
10586 if (len == 1)
10587 return;
10588 /* NOTE: fake 'exit' subprog should be updated as well. */
10589 for (i = 0; i <= env->subprog_cnt; i++) {
10590 if (env->subprog_info[i].start <= off)
10591 continue;
10592 env->subprog_info[i].start += len - 1;
10593 }
10594 }
10595
10596 static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10597 {
10598 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10599 int i, sz = prog->aux->size_poke_tab;
10600 struct bpf_jit_poke_descriptor *desc;
10601
10602 for (i = 0; i < sz; i++) {
10603 desc = &tab[i];
10604 desc->insn_idx += len - 1;
10605 }
10606 }
10607
10608 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10609 const struct bpf_insn *patch, u32 len)
10610 {
10611 struct bpf_prog *new_prog;
10612
10613 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10614 if (IS_ERR(new_prog)) {
10615 if (PTR_ERR(new_prog) == -ERANGE)
10616 verbose(env,
10617 "insn %d cannot be patched due to 16-bit range\n",
10618 env->insn_aux_data[off].orig_idx);
10619 return NULL;
10620 }
10621 if (adjust_insn_aux_data(env, new_prog, off, len))
10622 return NULL;
10623 adjust_subprog_starts(env, off, len);
10624 adjust_poke_descs(new_prog, len);
10625 return new_prog;
10626 }
10627
10628 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10629 u32 off, u32 cnt)
10630 {
10631 int i, j;
10632
10633 /* find first prog starting at or after off (first to remove) */
10634 for (i = 0; i < env->subprog_cnt; i++)
10635 if (env->subprog_info[i].start >= off)
10636 break;
10637 /* find first prog starting at or after off + cnt (first to stay) */
10638 for (j = i; j < env->subprog_cnt; j++)
10639 if (env->subprog_info[j].start >= off + cnt)
10640 break;
10641 /* if j doesn't start exactly at off + cnt, we are just removing
10642 * the front of previous prog
10643 */
10644 if (env->subprog_info[j].start != off + cnt)
10645 j--;
10646
10647 if (j > i) {
10648 struct bpf_prog_aux *aux = env->prog->aux;
10649 int move;
10650
10651 /* move fake 'exit' subprog as well */
10652 move = env->subprog_cnt + 1 - j;
10653
10654 memmove(env->subprog_info + i,
10655 env->subprog_info + j,
10656 sizeof(*env->subprog_info) * move);
10657 env->subprog_cnt -= j - i;
10658
10659 /* remove func_info */
10660 if (aux->func_info) {
10661 move = aux->func_info_cnt - j;
10662
10663 memmove(aux->func_info + i,
10664 aux->func_info + j,
10665 sizeof(*aux->func_info) * move);
10666 aux->func_info_cnt -= j - i;
10667 /* func_info->insn_off is set after all code rewrites,
10668 * in adjust_btf_func() - no need to adjust
10669 */
10670 }
10671 } else {
10672 /* convert i from "first prog to remove" to "first to adjust" */
10673 if (env->subprog_info[i].start == off)
10674 i++;
10675 }
10676
10677 /* update fake 'exit' subprog as well */
10678 for (; i <= env->subprog_cnt; i++)
10679 env->subprog_info[i].start -= cnt;
10680
10681 return 0;
10682 }
10683
10684 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10685 u32 cnt)
10686 {
10687 struct bpf_prog *prog = env->prog;
10688 u32 i, l_off, l_cnt, nr_linfo;
10689 struct bpf_line_info *linfo;
10690
10691 nr_linfo = prog->aux->nr_linfo;
10692 if (!nr_linfo)
10693 return 0;
10694
10695 linfo = prog->aux->linfo;
10696
10697 /* find first line info to remove, count lines to be removed */
10698 for (i = 0; i < nr_linfo; i++)
10699 if (linfo[i].insn_off >= off)
10700 break;
10701
10702 l_off = i;
10703 l_cnt = 0;
10704 for (; i < nr_linfo; i++)
10705 if (linfo[i].insn_off < off + cnt)
10706 l_cnt++;
10707 else
10708 break;
10709
10710 /* First live insn doesn't match first live linfo, it needs to "inherit"
10711 * last removed linfo. prog is already modified, so prog->len == off
10712 * means no live instructions after (tail of the program was removed).
10713 */
10714 if (prog->len != off && l_cnt &&
10715 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10716 l_cnt--;
10717 linfo[--i].insn_off = off + cnt;
10718 }
10719
10720 /* remove the line info which refer to the removed instructions */
10721 if (l_cnt) {
10722 memmove(linfo + l_off, linfo + i,
10723 sizeof(*linfo) * (nr_linfo - i));
10724
10725 prog->aux->nr_linfo -= l_cnt;
10726 nr_linfo = prog->aux->nr_linfo;
10727 }
10728
10729 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10730 for (i = l_off; i < nr_linfo; i++)
10731 linfo[i].insn_off -= cnt;
10732
10733 /* fix up all subprogs (incl. 'exit') which start >= off */
10734 for (i = 0; i <= env->subprog_cnt; i++)
10735 if (env->subprog_info[i].linfo_idx > l_off) {
10736 /* program may have started in the removed region but
10737 * may not be fully removed
10738 */
10739 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10740 env->subprog_info[i].linfo_idx -= l_cnt;
10741 else
10742 env->subprog_info[i].linfo_idx = l_off;
10743 }
10744
10745 return 0;
10746 }
10747
10748 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10749 {
10750 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10751 unsigned int orig_prog_len = env->prog->len;
10752 int err;
10753
10754 if (bpf_prog_is_dev_bound(env->prog->aux))
10755 bpf_prog_offload_remove_insns(env, off, cnt);
10756
10757 err = bpf_remove_insns(env->prog, off, cnt);
10758 if (err)
10759 return err;
10760
10761 err = adjust_subprog_starts_after_remove(env, off, cnt);
10762 if (err)
10763 return err;
10764
10765 err = bpf_adj_linfo_after_remove(env, off, cnt);
10766 if (err)
10767 return err;
10768
10769 memmove(aux_data + off, aux_data + off + cnt,
10770 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10771
10772 return 0;
10773 }
10774
10775 /* The verifier does more data flow analysis than llvm and will not
10776 * explore branches that are dead at run time. Malicious programs can
10777 * have dead code too. Therefore replace all dead at-run-time code
10778 * with 'ja -1'.
10779 *
10780 * Just nops are not optimal, e.g. if they would sit at the end of the
10781 * program and through another bug we would manage to jump there, then
10782 * we'd execute beyond program memory otherwise. Returning exception
10783 * code also wouldn't work since we can have subprogs where the dead
10784 * code could be located.
10785 */
10786 static void sanitize_dead_code(struct bpf_verifier_env *env)
10787 {
10788 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10789 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10790 struct bpf_insn *insn = env->prog->insnsi;
10791 const int insn_cnt = env->prog->len;
10792 int i;
10793
10794 for (i = 0; i < insn_cnt; i++) {
10795 if (aux_data[i].seen)
10796 continue;
10797 memcpy(insn + i, &trap, sizeof(trap));
10798 }
10799 }
10800
10801 static bool insn_is_cond_jump(u8 code)
10802 {
10803 u8 op;
10804
10805 if (BPF_CLASS(code) == BPF_JMP32)
10806 return true;
10807
10808 if (BPF_CLASS(code) != BPF_JMP)
10809 return false;
10810
10811 op = BPF_OP(code);
10812 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10813 }
10814
10815 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10816 {
10817 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10818 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10819 struct bpf_insn *insn = env->prog->insnsi;
10820 const int insn_cnt = env->prog->len;
10821 int i;
10822
10823 for (i = 0; i < insn_cnt; i++, insn++) {
10824 if (!insn_is_cond_jump(insn->code))
10825 continue;
10826
10827 if (!aux_data[i + 1].seen)
10828 ja.off = insn->off;
10829 else if (!aux_data[i + 1 + insn->off].seen)
10830 ja.off = 0;
10831 else
10832 continue;
10833
10834 if (bpf_prog_is_dev_bound(env->prog->aux))
10835 bpf_prog_offload_replace_insn(env, i, &ja);
10836
10837 memcpy(insn, &ja, sizeof(ja));
10838 }
10839 }
10840
10841 static int opt_remove_dead_code(struct bpf_verifier_env *env)
10842 {
10843 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10844 int insn_cnt = env->prog->len;
10845 int i, err;
10846
10847 for (i = 0; i < insn_cnt; i++) {
10848 int j;
10849
10850 j = 0;
10851 while (i + j < insn_cnt && !aux_data[i + j].seen)
10852 j++;
10853 if (!j)
10854 continue;
10855
10856 err = verifier_remove_insns(env, i, j);
10857 if (err)
10858 return err;
10859 insn_cnt = env->prog->len;
10860 }
10861
10862 return 0;
10863 }
10864
10865 static int opt_remove_nops(struct bpf_verifier_env *env)
10866 {
10867 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10868 struct bpf_insn *insn = env->prog->insnsi;
10869 int insn_cnt = env->prog->len;
10870 int i, err;
10871
10872 for (i = 0; i < insn_cnt; i++) {
10873 if (memcmp(&insn[i], &ja, sizeof(ja)))
10874 continue;
10875
10876 err = verifier_remove_insns(env, i, 1);
10877 if (err)
10878 return err;
10879 insn_cnt--;
10880 i--;
10881 }
10882
10883 return 0;
10884 }
10885
10886 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10887 const union bpf_attr *attr)
10888 {
10889 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
10890 struct bpf_insn_aux_data *aux = env->insn_aux_data;
10891 int i, patch_len, delta = 0, len = env->prog->len;
10892 struct bpf_insn *insns = env->prog->insnsi;
10893 struct bpf_prog *new_prog;
10894 bool rnd_hi32;
10895
10896 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
10897 zext_patch[1] = BPF_ZEXT_REG(0);
10898 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10899 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
10900 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
10901 for (i = 0; i < len; i++) {
10902 int adj_idx = i + delta;
10903 struct bpf_insn insn;
10904
10905 insn = insns[adj_idx];
10906 if (!aux[adj_idx].zext_dst) {
10907 u8 code, class;
10908 u32 imm_rnd;
10909
10910 if (!rnd_hi32)
10911 continue;
10912
10913 code = insn.code;
10914 class = BPF_CLASS(code);
10915 if (insn_no_def(&insn))
10916 continue;
10917
10918 /* NOTE: arg "reg" (the fourth one) is only used for
10919 * BPF_STX which has been ruled out in above
10920 * check, it is safe to pass NULL here.
10921 */
10922 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
10923 if (class == BPF_LD &&
10924 BPF_MODE(code) == BPF_IMM)
10925 i++;
10926 continue;
10927 }
10928
10929 /* ctx load could be transformed into wider load. */
10930 if (class == BPF_LDX &&
10931 aux[adj_idx].ptr_type == PTR_TO_CTX)
10932 continue;
10933
10934 imm_rnd = get_random_int();
10935 rnd_hi32_patch[0] = insn;
10936 rnd_hi32_patch[1].imm = imm_rnd;
10937 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
10938 patch = rnd_hi32_patch;
10939 patch_len = 4;
10940 goto apply_patch_buffer;
10941 }
10942
10943 if (!bpf_jit_needs_zext())
10944 continue;
10945
10946 zext_patch[0] = insn;
10947 zext_patch[1].dst_reg = insn.dst_reg;
10948 zext_patch[1].src_reg = insn.dst_reg;
10949 patch = zext_patch;
10950 patch_len = 2;
10951 apply_patch_buffer:
10952 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
10953 if (!new_prog)
10954 return -ENOMEM;
10955 env->prog = new_prog;
10956 insns = new_prog->insnsi;
10957 aux = env->insn_aux_data;
10958 delta += patch_len - 1;
10959 }
10960
10961 return 0;
10962 }
10963
10964 /* convert load instructions that access fields of a context type into a
10965 * sequence of instructions that access fields of the underlying structure:
10966 * struct __sk_buff -> struct sk_buff
10967 * struct bpf_sock_ops -> struct sock
10968 */
10969 static int convert_ctx_accesses(struct bpf_verifier_env *env)
10970 {
10971 const struct bpf_verifier_ops *ops = env->ops;
10972 int i, cnt, size, ctx_field_size, delta = 0;
10973 const int insn_cnt = env->prog->len;
10974 struct bpf_insn insn_buf[16], *insn;
10975 u32 target_size, size_default, off;
10976 struct bpf_prog *new_prog;
10977 enum bpf_access_type type;
10978 bool is_narrower_load;
10979
10980 if (ops->gen_prologue || env->seen_direct_write) {
10981 if (!ops->gen_prologue) {
10982 verbose(env, "bpf verifier is misconfigured\n");
10983 return -EINVAL;
10984 }
10985 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
10986 env->prog);
10987 if (cnt >= ARRAY_SIZE(insn_buf)) {
10988 verbose(env, "bpf verifier is misconfigured\n");
10989 return -EINVAL;
10990 } else if (cnt) {
10991 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
10992 if (!new_prog)
10993 return -ENOMEM;
10994
10995 env->prog = new_prog;
10996 delta += cnt - 1;
10997 }
10998 }
10999
11000 if (bpf_prog_is_dev_bound(env->prog->aux))
11001 return 0;
11002
11003 insn = env->prog->insnsi + delta;
11004
11005 for (i = 0; i < insn_cnt; i++, insn++) {
11006 bpf_convert_ctx_access_t convert_ctx_access;
11007
11008 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11009 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11010 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11011 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
11012 type = BPF_READ;
11013 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11014 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11015 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11016 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
11017 type = BPF_WRITE;
11018 else
11019 continue;
11020
11021 if (type == BPF_WRITE &&
11022 env->insn_aux_data[i + delta].sanitize_stack_off) {
11023 struct bpf_insn patch[] = {
11024 /* Sanitize suspicious stack slot with zero.
11025 * There are no memory dependencies for this store,
11026 * since it's only using frame pointer and immediate
11027 * constant of zero
11028 */
11029 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11030 env->insn_aux_data[i + delta].sanitize_stack_off,
11031 0),
11032 /* the original STX instruction will immediately
11033 * overwrite the same stack slot with appropriate value
11034 */
11035 *insn,
11036 };
11037
11038 cnt = ARRAY_SIZE(patch);
11039 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11040 if (!new_prog)
11041 return -ENOMEM;
11042
11043 delta += cnt - 1;
11044 env->prog = new_prog;
11045 insn = new_prog->insnsi + i + delta;
11046 continue;
11047 }
11048
11049 switch (env->insn_aux_data[i + delta].ptr_type) {
11050 case PTR_TO_CTX:
11051 if (!ops->convert_ctx_access)
11052 continue;
11053 convert_ctx_access = ops->convert_ctx_access;
11054 break;
11055 case PTR_TO_SOCKET:
11056 case PTR_TO_SOCK_COMMON:
11057 convert_ctx_access = bpf_sock_convert_ctx_access;
11058 break;
11059 case PTR_TO_TCP_SOCK:
11060 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11061 break;
11062 case PTR_TO_XDP_SOCK:
11063 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11064 break;
11065 case PTR_TO_BTF_ID:
11066 if (type == BPF_READ) {
11067 insn->code = BPF_LDX | BPF_PROBE_MEM |
11068 BPF_SIZE((insn)->code);
11069 env->prog->aux->num_exentries++;
11070 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11071 verbose(env, "Writes through BTF pointers are not allowed\n");
11072 return -EINVAL;
11073 }
11074 continue;
11075 default:
11076 continue;
11077 }
11078
11079 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11080 size = BPF_LDST_BYTES(insn);
11081
11082 /* If the read access is a narrower load of the field,
11083 * convert to a 4/8-byte load, to minimum program type specific
11084 * convert_ctx_access changes. If conversion is successful,
11085 * we will apply proper mask to the result.
11086 */
11087 is_narrower_load = size < ctx_field_size;
11088 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11089 off = insn->off;
11090 if (is_narrower_load) {
11091 u8 size_code;
11092
11093 if (type == BPF_WRITE) {
11094 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11095 return -EINVAL;
11096 }
11097
11098 size_code = BPF_H;
11099 if (ctx_field_size == 4)
11100 size_code = BPF_W;
11101 else if (ctx_field_size == 8)
11102 size_code = BPF_DW;
11103
11104 insn->off = off & ~(size_default - 1);
11105 insn->code = BPF_LDX | BPF_MEM | size_code;
11106 }
11107
11108 target_size = 0;
11109 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11110 &target_size);
11111 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11112 (ctx_field_size && !target_size)) {
11113 verbose(env, "bpf verifier is misconfigured\n");
11114 return -EINVAL;
11115 }
11116
11117 if (is_narrower_load && size < target_size) {
11118 u8 shift = bpf_ctx_narrow_access_offset(
11119 off, size, size_default) * 8;
11120 if (ctx_field_size <= 4) {
11121 if (shift)
11122 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11123 insn->dst_reg,
11124 shift);
11125 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11126 (1 << size * 8) - 1);
11127 } else {
11128 if (shift)
11129 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11130 insn->dst_reg,
11131 shift);
11132 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
11133 (1ULL << size * 8) - 1);
11134 }
11135 }
11136
11137 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11138 if (!new_prog)
11139 return -ENOMEM;
11140
11141 delta += cnt - 1;
11142
11143 /* keep walking new program and skip insns we just inserted */
11144 env->prog = new_prog;
11145 insn = new_prog->insnsi + i + delta;
11146 }
11147
11148 return 0;
11149 }
11150
11151 static int jit_subprogs(struct bpf_verifier_env *env)
11152 {
11153 struct bpf_prog *prog = env->prog, **func, *tmp;
11154 int i, j, subprog_start, subprog_end = 0, len, subprog;
11155 struct bpf_map *map_ptr;
11156 struct bpf_insn *insn;
11157 void *old_bpf_func;
11158 int err, num_exentries;
11159
11160 if (env->subprog_cnt <= 1)
11161 return 0;
11162
11163 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11164 if (insn->code != (BPF_JMP | BPF_CALL) ||
11165 insn->src_reg != BPF_PSEUDO_CALL)
11166 continue;
11167 /* Upon error here we cannot fall back to interpreter but
11168 * need a hard reject of the program. Thus -EFAULT is
11169 * propagated in any case.
11170 */
11171 subprog = find_subprog(env, i + insn->imm + 1);
11172 if (subprog < 0) {
11173 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11174 i + insn->imm + 1);
11175 return -EFAULT;
11176 }
11177 /* temporarily remember subprog id inside insn instead of
11178 * aux_data, since next loop will split up all insns into funcs
11179 */
11180 insn->off = subprog;
11181 /* remember original imm in case JIT fails and fallback
11182 * to interpreter will be needed
11183 */
11184 env->insn_aux_data[i].call_imm = insn->imm;
11185 /* point imm to __bpf_call_base+1 from JITs point of view */
11186 insn->imm = 1;
11187 }
11188
11189 err = bpf_prog_alloc_jited_linfo(prog);
11190 if (err)
11191 goto out_undo_insn;
11192
11193 err = -ENOMEM;
11194 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11195 if (!func)
11196 goto out_undo_insn;
11197
11198 for (i = 0; i < env->subprog_cnt; i++) {
11199 subprog_start = subprog_end;
11200 subprog_end = env->subprog_info[i + 1].start;
11201
11202 len = subprog_end - subprog_start;
11203 /* BPF_PROG_RUN doesn't call subprogs directly,
11204 * hence main prog stats include the runtime of subprogs.
11205 * subprogs don't have IDs and not reachable via prog_get_next_id
11206 * func[i]->aux->stats will never be accessed and stays NULL
11207 */
11208 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11209 if (!func[i])
11210 goto out_free;
11211 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11212 len * sizeof(struct bpf_insn));
11213 func[i]->type = prog->type;
11214 func[i]->len = len;
11215 if (bpf_prog_calc_tag(func[i]))
11216 goto out_free;
11217 func[i]->is_func = 1;
11218 func[i]->aux->func_idx = i;
11219 /* the btf and func_info will be freed only at prog->aux */
11220 func[i]->aux->btf = prog->aux->btf;
11221 func[i]->aux->func_info = prog->aux->func_info;
11222
11223 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11224 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11225 int ret;
11226
11227 if (!(insn_idx >= subprog_start &&
11228 insn_idx <= subprog_end))
11229 continue;
11230
11231 ret = bpf_jit_add_poke_descriptor(func[i],
11232 &prog->aux->poke_tab[j]);
11233 if (ret < 0) {
11234 verbose(env, "adding tail call poke descriptor failed\n");
11235 goto out_free;
11236 }
11237
11238 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11239
11240 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11241 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11242 if (ret < 0) {
11243 verbose(env, "tracking tail call prog failed\n");
11244 goto out_free;
11245 }
11246 }
11247
11248 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11249 * Long term would need debug info to populate names
11250 */
11251 func[i]->aux->name[0] = 'F';
11252 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11253 func[i]->jit_requested = 1;
11254 func[i]->aux->linfo = prog->aux->linfo;
11255 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11256 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11257 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11258 num_exentries = 0;
11259 insn = func[i]->insnsi;
11260 for (j = 0; j < func[i]->len; j++, insn++) {
11261 if (BPF_CLASS(insn->code) == BPF_LDX &&
11262 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11263 num_exentries++;
11264 }
11265 func[i]->aux->num_exentries = num_exentries;
11266 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11267 func[i] = bpf_int_jit_compile(func[i]);
11268 if (!func[i]->jited) {
11269 err = -ENOTSUPP;
11270 goto out_free;
11271 }
11272 cond_resched();
11273 }
11274
11275 /* Untrack main program's aux structs so that during map_poke_run()
11276 * we will not stumble upon the unfilled poke descriptors; each
11277 * of the main program's poke descs got distributed across subprogs
11278 * and got tracked onto map, so we are sure that none of them will
11279 * be missed after the operation below
11280 */
11281 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11282 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11283
11284 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11285 }
11286
11287 /* at this point all bpf functions were successfully JITed
11288 * now populate all bpf_calls with correct addresses and
11289 * run last pass of JIT
11290 */
11291 for (i = 0; i < env->subprog_cnt; i++) {
11292 insn = func[i]->insnsi;
11293 for (j = 0; j < func[i]->len; j++, insn++) {
11294 if (insn->code != (BPF_JMP | BPF_CALL) ||
11295 insn->src_reg != BPF_PSEUDO_CALL)
11296 continue;
11297 subprog = insn->off;
11298 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11299 __bpf_call_base;
11300 }
11301
11302 /* we use the aux data to keep a list of the start addresses
11303 * of the JITed images for each function in the program
11304 *
11305 * for some architectures, such as powerpc64, the imm field
11306 * might not be large enough to hold the offset of the start
11307 * address of the callee's JITed image from __bpf_call_base
11308 *
11309 * in such cases, we can lookup the start address of a callee
11310 * by using its subprog id, available from the off field of
11311 * the call instruction, as an index for this list
11312 */
11313 func[i]->aux->func = func;
11314 func[i]->aux->func_cnt = env->subprog_cnt;
11315 }
11316 for (i = 0; i < env->subprog_cnt; i++) {
11317 old_bpf_func = func[i]->bpf_func;
11318 tmp = bpf_int_jit_compile(func[i]);
11319 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11320 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11321 err = -ENOTSUPP;
11322 goto out_free;
11323 }
11324 cond_resched();
11325 }
11326
11327 /* finally lock prog and jit images for all functions and
11328 * populate kallsysm
11329 */
11330 for (i = 0; i < env->subprog_cnt; i++) {
11331 bpf_prog_lock_ro(func[i]);
11332 bpf_prog_kallsyms_add(func[i]);
11333 }
11334
11335 /* Last step: make now unused interpreter insns from main
11336 * prog consistent for later dump requests, so they can
11337 * later look the same as if they were interpreted only.
11338 */
11339 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11340 if (insn->code != (BPF_JMP | BPF_CALL) ||
11341 insn->src_reg != BPF_PSEUDO_CALL)
11342 continue;
11343 insn->off = env->insn_aux_data[i].call_imm;
11344 subprog = find_subprog(env, i + insn->off + 1);
11345 insn->imm = subprog;
11346 }
11347
11348 prog->jited = 1;
11349 prog->bpf_func = func[0]->bpf_func;
11350 prog->aux->func = func;
11351 prog->aux->func_cnt = env->subprog_cnt;
11352 bpf_prog_free_unused_jited_linfo(prog);
11353 return 0;
11354 out_free:
11355 for (i = 0; i < env->subprog_cnt; i++) {
11356 if (!func[i])
11357 continue;
11358
11359 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11360 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11361 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11362 }
11363 bpf_jit_free(func[i]);
11364 }
11365 kfree(func);
11366 out_undo_insn:
11367 /* cleanup main prog to be interpreted */
11368 prog->jit_requested = 0;
11369 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11370 if (insn->code != (BPF_JMP | BPF_CALL) ||
11371 insn->src_reg != BPF_PSEUDO_CALL)
11372 continue;
11373 insn->off = 0;
11374 insn->imm = env->insn_aux_data[i].call_imm;
11375 }
11376 bpf_prog_free_jited_linfo(prog);
11377 return err;
11378 }
11379
11380 static int fixup_call_args(struct bpf_verifier_env *env)
11381 {
11382 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11383 struct bpf_prog *prog = env->prog;
11384 struct bpf_insn *insn = prog->insnsi;
11385 int i, depth;
11386 #endif
11387 int err = 0;
11388
11389 if (env->prog->jit_requested &&
11390 !bpf_prog_is_dev_bound(env->prog->aux)) {
11391 err = jit_subprogs(env);
11392 if (err == 0)
11393 return 0;
11394 if (err == -EFAULT)
11395 return err;
11396 }
11397 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11398 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11399 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11400 * have to be rejected, since interpreter doesn't support them yet.
11401 */
11402 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11403 return -EINVAL;
11404 }
11405 for (i = 0; i < prog->len; i++, insn++) {
11406 if (insn->code != (BPF_JMP | BPF_CALL) ||
11407 insn->src_reg != BPF_PSEUDO_CALL)
11408 continue;
11409 depth = get_callee_stack_depth(env, insn, i);
11410 if (depth < 0)
11411 return depth;
11412 bpf_patch_call_args(insn, depth);
11413 }
11414 err = 0;
11415 #endif
11416 return err;
11417 }
11418
11419 /* fixup insn->imm field of bpf_call instructions
11420 * and inline eligible helpers as explicit sequence of BPF instructions
11421 *
11422 * this function is called after eBPF program passed verification
11423 */
11424 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11425 {
11426 struct bpf_prog *prog = env->prog;
11427 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11428 struct bpf_insn *insn = prog->insnsi;
11429 const struct bpf_func_proto *fn;
11430 const int insn_cnt = prog->len;
11431 const struct bpf_map_ops *ops;
11432 struct bpf_insn_aux_data *aux;
11433 struct bpf_insn insn_buf[16];
11434 struct bpf_prog *new_prog;
11435 struct bpf_map *map_ptr;
11436 int i, ret, cnt, delta = 0;
11437
11438 for (i = 0; i < insn_cnt; i++, insn++) {
11439 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11440 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11441 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11442 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11443 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11444 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11445 struct bpf_insn *patchlet;
11446 struct bpf_insn chk_and_div[] = {
11447 /* [R,W]x div 0 -> 0 */
11448 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11449 BPF_JNE | BPF_K, insn->src_reg,
11450 0, 2, 0),
11451 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11452 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11453 *insn,
11454 };
11455 struct bpf_insn chk_and_mod[] = {
11456 /* [R,W]x mod 0 -> [R,W]x */
11457 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11458 BPF_JEQ | BPF_K, insn->src_reg,
11459 0, 1 + (is64 ? 0 : 1), 0),
11460 *insn,
11461 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11462 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11463 };
11464
11465 patchlet = isdiv ? chk_and_div : chk_and_mod;
11466 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11467 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11468
11469 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11470 if (!new_prog)
11471 return -ENOMEM;
11472
11473 delta += cnt - 1;
11474 env->prog = prog = new_prog;
11475 insn = new_prog->insnsi + i + delta;
11476 continue;
11477 }
11478
11479 if (BPF_CLASS(insn->code) == BPF_LD &&
11480 (BPF_MODE(insn->code) == BPF_ABS ||
11481 BPF_MODE(insn->code) == BPF_IND)) {
11482 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11483 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11484 verbose(env, "bpf verifier is misconfigured\n");
11485 return -EINVAL;
11486 }
11487
11488 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11489 if (!new_prog)
11490 return -ENOMEM;
11491
11492 delta += cnt - 1;
11493 env->prog = prog = new_prog;
11494 insn = new_prog->insnsi + i + delta;
11495 continue;
11496 }
11497
11498 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11499 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11500 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11501 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11502 struct bpf_insn insn_buf[16];
11503 struct bpf_insn *patch = &insn_buf[0];
11504 bool issrc, isneg, isimm;
11505 u32 off_reg;
11506
11507 aux = &env->insn_aux_data[i + delta];
11508 if (!aux->alu_state ||
11509 aux->alu_state == BPF_ALU_NON_POINTER)
11510 continue;
11511
11512 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11513 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11514 BPF_ALU_SANITIZE_SRC;
11515 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11516
11517 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11518 if (isimm) {
11519 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11520 } else {
11521 if (isneg)
11522 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11523 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11524 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11525 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11526 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11527 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11528 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11529 }
11530 if (!issrc)
11531 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11532 insn->src_reg = BPF_REG_AX;
11533 if (isneg)
11534 insn->code = insn->code == code_add ?
11535 code_sub : code_add;
11536 *patch++ = *insn;
11537 if (issrc && isneg && !isimm)
11538 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11539 cnt = patch - insn_buf;
11540
11541 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11542 if (!new_prog)
11543 return -ENOMEM;
11544
11545 delta += cnt - 1;
11546 env->prog = prog = new_prog;
11547 insn = new_prog->insnsi + i + delta;
11548 continue;
11549 }
11550
11551 if (insn->code != (BPF_JMP | BPF_CALL))
11552 continue;
11553 if (insn->src_reg == BPF_PSEUDO_CALL)
11554 continue;
11555
11556 if (insn->imm == BPF_FUNC_get_route_realm)
11557 prog->dst_needed = 1;
11558 if (insn->imm == BPF_FUNC_get_prandom_u32)
11559 bpf_user_rnd_init_once();
11560 if (insn->imm == BPF_FUNC_override_return)
11561 prog->kprobe_override = 1;
11562 if (insn->imm == BPF_FUNC_tail_call) {
11563 /* If we tail call into other programs, we
11564 * cannot make any assumptions since they can
11565 * be replaced dynamically during runtime in
11566 * the program array.
11567 */
11568 prog->cb_access = 1;
11569 if (!allow_tail_call_in_subprogs(env))
11570 prog->aux->stack_depth = MAX_BPF_STACK;
11571 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11572
11573 /* mark bpf_tail_call as different opcode to avoid
11574 * conditional branch in the interpeter for every normal
11575 * call and to prevent accidental JITing by JIT compiler
11576 * that doesn't support bpf_tail_call yet
11577 */
11578 insn->imm = 0;
11579 insn->code = BPF_JMP | BPF_TAIL_CALL;
11580
11581 aux = &env->insn_aux_data[i + delta];
11582 if (env->bpf_capable && !expect_blinding &&
11583 prog->jit_requested &&
11584 !bpf_map_key_poisoned(aux) &&
11585 !bpf_map_ptr_poisoned(aux) &&
11586 !bpf_map_ptr_unpriv(aux)) {
11587 struct bpf_jit_poke_descriptor desc = {
11588 .reason = BPF_POKE_REASON_TAIL_CALL,
11589 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11590 .tail_call.key = bpf_map_key_immediate(aux),
11591 .insn_idx = i + delta,
11592 };
11593
11594 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11595 if (ret < 0) {
11596 verbose(env, "adding tail call poke descriptor failed\n");
11597 return ret;
11598 }
11599
11600 insn->imm = ret + 1;
11601 continue;
11602 }
11603
11604 if (!bpf_map_ptr_unpriv(aux))
11605 continue;
11606
11607 /* instead of changing every JIT dealing with tail_call
11608 * emit two extra insns:
11609 * if (index >= max_entries) goto out;
11610 * index &= array->index_mask;
11611 * to avoid out-of-bounds cpu speculation
11612 */
11613 if (bpf_map_ptr_poisoned(aux)) {
11614 verbose(env, "tail_call abusing map_ptr\n");
11615 return -EINVAL;
11616 }
11617
11618 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11619 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11620 map_ptr->max_entries, 2);
11621 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11622 container_of(map_ptr,
11623 struct bpf_array,
11624 map)->index_mask);
11625 insn_buf[2] = *insn;
11626 cnt = 3;
11627 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11628 if (!new_prog)
11629 return -ENOMEM;
11630
11631 delta += cnt - 1;
11632 env->prog = prog = new_prog;
11633 insn = new_prog->insnsi + i + delta;
11634 continue;
11635 }
11636
11637 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11638 * and other inlining handlers are currently limited to 64 bit
11639 * only.
11640 */
11641 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11642 (insn->imm == BPF_FUNC_map_lookup_elem ||
11643 insn->imm == BPF_FUNC_map_update_elem ||
11644 insn->imm == BPF_FUNC_map_delete_elem ||
11645 insn->imm == BPF_FUNC_map_push_elem ||
11646 insn->imm == BPF_FUNC_map_pop_elem ||
11647 insn->imm == BPF_FUNC_map_peek_elem)) {
11648 aux = &env->insn_aux_data[i + delta];
11649 if (bpf_map_ptr_poisoned(aux))
11650 goto patch_call_imm;
11651
11652 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11653 ops = map_ptr->ops;
11654 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11655 ops->map_gen_lookup) {
11656 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11657 if (cnt == -EOPNOTSUPP)
11658 goto patch_map_ops_generic;
11659 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11660 verbose(env, "bpf verifier is misconfigured\n");
11661 return -EINVAL;
11662 }
11663
11664 new_prog = bpf_patch_insn_data(env, i + delta,
11665 insn_buf, cnt);
11666 if (!new_prog)
11667 return -ENOMEM;
11668
11669 delta += cnt - 1;
11670 env->prog = prog = new_prog;
11671 insn = new_prog->insnsi + i + delta;
11672 continue;
11673 }
11674
11675 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11676 (void *(*)(struct bpf_map *map, void *key))NULL));
11677 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11678 (int (*)(struct bpf_map *map, void *key))NULL));
11679 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11680 (int (*)(struct bpf_map *map, void *key, void *value,
11681 u64 flags))NULL));
11682 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11683 (int (*)(struct bpf_map *map, void *value,
11684 u64 flags))NULL));
11685 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11686 (int (*)(struct bpf_map *map, void *value))NULL));
11687 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11688 (int (*)(struct bpf_map *map, void *value))NULL));
11689 patch_map_ops_generic:
11690 switch (insn->imm) {
11691 case BPF_FUNC_map_lookup_elem:
11692 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11693 __bpf_call_base;
11694 continue;
11695 case BPF_FUNC_map_update_elem:
11696 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11697 __bpf_call_base;
11698 continue;
11699 case BPF_FUNC_map_delete_elem:
11700 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11701 __bpf_call_base;
11702 continue;
11703 case BPF_FUNC_map_push_elem:
11704 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11705 __bpf_call_base;
11706 continue;
11707 case BPF_FUNC_map_pop_elem:
11708 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11709 __bpf_call_base;
11710 continue;
11711 case BPF_FUNC_map_peek_elem:
11712 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11713 __bpf_call_base;
11714 continue;
11715 }
11716
11717 goto patch_call_imm;
11718 }
11719
11720 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11721 insn->imm == BPF_FUNC_jiffies64) {
11722 struct bpf_insn ld_jiffies_addr[2] = {
11723 BPF_LD_IMM64(BPF_REG_0,
11724 (unsigned long)&jiffies),
11725 };
11726
11727 insn_buf[0] = ld_jiffies_addr[0];
11728 insn_buf[1] = ld_jiffies_addr[1];
11729 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11730 BPF_REG_0, 0);
11731 cnt = 3;
11732
11733 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11734 cnt);
11735 if (!new_prog)
11736 return -ENOMEM;
11737
11738 delta += cnt - 1;
11739 env->prog = prog = new_prog;
11740 insn = new_prog->insnsi + i + delta;
11741 continue;
11742 }
11743
11744 patch_call_imm:
11745 fn = env->ops->get_func_proto(insn->imm, env->prog);
11746 /* all functions that have prototype and verifier allowed
11747 * programs to call them, must be real in-kernel functions
11748 */
11749 if (!fn->func) {
11750 verbose(env,
11751 "kernel subsystem misconfigured func %s#%d\n",
11752 func_id_name(insn->imm), insn->imm);
11753 return -EFAULT;
11754 }
11755 insn->imm = fn->func - __bpf_call_base;
11756 }
11757
11758 /* Since poke tab is now finalized, publish aux to tracker. */
11759 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11760 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11761 if (!map_ptr->ops->map_poke_track ||
11762 !map_ptr->ops->map_poke_untrack ||
11763 !map_ptr->ops->map_poke_run) {
11764 verbose(env, "bpf verifier is misconfigured\n");
11765 return -EINVAL;
11766 }
11767
11768 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11769 if (ret < 0) {
11770 verbose(env, "tracking tail call prog failed\n");
11771 return ret;
11772 }
11773 }
11774
11775 return 0;
11776 }
11777
11778 static void free_states(struct bpf_verifier_env *env)
11779 {
11780 struct bpf_verifier_state_list *sl, *sln;
11781 int i;
11782
11783 sl = env->free_list;
11784 while (sl) {
11785 sln = sl->next;
11786 free_verifier_state(&sl->state, false);
11787 kfree(sl);
11788 sl = sln;
11789 }
11790 env->free_list = NULL;
11791
11792 if (!env->explored_states)
11793 return;
11794
11795 for (i = 0; i < state_htab_size(env); i++) {
11796 sl = env->explored_states[i];
11797
11798 while (sl) {
11799 sln = sl->next;
11800 free_verifier_state(&sl->state, false);
11801 kfree(sl);
11802 sl = sln;
11803 }
11804 env->explored_states[i] = NULL;
11805 }
11806 }
11807
11808 /* The verifier is using insn_aux_data[] to store temporary data during
11809 * verification and to store information for passes that run after the
11810 * verification like dead code sanitization. do_check_common() for subprogram N
11811 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11812 * temporary data after do_check_common() finds that subprogram N cannot be
11813 * verified independently. pass_cnt counts the number of times
11814 * do_check_common() was run and insn->aux->seen tells the pass number
11815 * insn_aux_data was touched. These variables are compared to clear temporary
11816 * data from failed pass. For testing and experiments do_check_common() can be
11817 * run multiple times even when prior attempt to verify is unsuccessful.
11818 */
11819 static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11820 {
11821 struct bpf_insn *insn = env->prog->insnsi;
11822 struct bpf_insn_aux_data *aux;
11823 int i, class;
11824
11825 for (i = 0; i < env->prog->len; i++) {
11826 class = BPF_CLASS(insn[i].code);
11827 if (class != BPF_LDX && class != BPF_STX)
11828 continue;
11829 aux = &env->insn_aux_data[i];
11830 if (aux->seen != env->pass_cnt)
11831 continue;
11832 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11833 }
11834 }
11835
11836 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11837 {
11838 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11839 struct bpf_verifier_state *state;
11840 struct bpf_reg_state *regs;
11841 int ret, i;
11842
11843 env->prev_linfo = NULL;
11844 env->pass_cnt++;
11845
11846 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11847 if (!state)
11848 return -ENOMEM;
11849 state->curframe = 0;
11850 state->speculative = false;
11851 state->branches = 1;
11852 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11853 if (!state->frame[0]) {
11854 kfree(state);
11855 return -ENOMEM;
11856 }
11857 env->cur_state = state;
11858 init_func_state(env, state->frame[0],
11859 BPF_MAIN_FUNC /* callsite */,
11860 0 /* frameno */,
11861 subprog);
11862
11863 regs = state->frame[state->curframe]->regs;
11864 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
11865 ret = btf_prepare_func_args(env, subprog, regs);
11866 if (ret)
11867 goto out;
11868 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11869 if (regs[i].type == PTR_TO_CTX)
11870 mark_reg_known_zero(env, regs, i);
11871 else if (regs[i].type == SCALAR_VALUE)
11872 mark_reg_unknown(env, regs, i);
11873 }
11874 } else {
11875 /* 1st arg to a function */
11876 regs[BPF_REG_1].type = PTR_TO_CTX;
11877 mark_reg_known_zero(env, regs, BPF_REG_1);
11878 ret = btf_check_func_arg_match(env, subprog, regs);
11879 if (ret == -EFAULT)
11880 /* unlikely verifier bug. abort.
11881 * ret == 0 and ret < 0 are sadly acceptable for
11882 * main() function due to backward compatibility.
11883 * Like socket filter program may be written as:
11884 * int bpf_prog(struct pt_regs *ctx)
11885 * and never dereference that ctx in the program.
11886 * 'struct pt_regs' is a type mismatch for socket
11887 * filter that should be using 'struct __sk_buff'.
11888 */
11889 goto out;
11890 }
11891
11892 ret = do_check(env);
11893 out:
11894 /* check for NULL is necessary, since cur_state can be freed inside
11895 * do_check() under memory pressure.
11896 */
11897 if (env->cur_state) {
11898 free_verifier_state(env->cur_state, true);
11899 env->cur_state = NULL;
11900 }
11901 while (!pop_stack(env, NULL, NULL, false));
11902 if (!ret && pop_log)
11903 bpf_vlog_reset(&env->log, 0);
11904 free_states(env);
11905 if (ret)
11906 /* clean aux data in case subprog was rejected */
11907 sanitize_insn_aux_data(env);
11908 return ret;
11909 }
11910
11911 /* Verify all global functions in a BPF program one by one based on their BTF.
11912 * All global functions must pass verification. Otherwise the whole program is rejected.
11913 * Consider:
11914 * int bar(int);
11915 * int foo(int f)
11916 * {
11917 * return bar(f);
11918 * }
11919 * int bar(int b)
11920 * {
11921 * ...
11922 * }
11923 * foo() will be verified first for R1=any_scalar_value. During verification it
11924 * will be assumed that bar() already verified successfully and call to bar()
11925 * from foo() will be checked for type match only. Later bar() will be verified
11926 * independently to check that it's safe for R1=any_scalar_value.
11927 */
11928 static int do_check_subprogs(struct bpf_verifier_env *env)
11929 {
11930 struct bpf_prog_aux *aux = env->prog->aux;
11931 int i, ret;
11932
11933 if (!aux->func_info)
11934 return 0;
11935
11936 for (i = 1; i < env->subprog_cnt; i++) {
11937 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
11938 continue;
11939 env->insn_idx = env->subprog_info[i].start;
11940 WARN_ON_ONCE(env->insn_idx == 0);
11941 ret = do_check_common(env, i);
11942 if (ret) {
11943 return ret;
11944 } else if (env->log.level & BPF_LOG_LEVEL) {
11945 verbose(env,
11946 "Func#%d is safe for any args that match its prototype\n",
11947 i);
11948 }
11949 }
11950 return 0;
11951 }
11952
11953 static int do_check_main(struct bpf_verifier_env *env)
11954 {
11955 int ret;
11956
11957 env->insn_idx = 0;
11958 ret = do_check_common(env, 0);
11959 if (!ret)
11960 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
11961 return ret;
11962 }
11963
11964
11965 static void print_verification_stats(struct bpf_verifier_env *env)
11966 {
11967 int i;
11968
11969 if (env->log.level & BPF_LOG_STATS) {
11970 verbose(env, "verification time %lld usec\n",
11971 div_u64(env->verification_time, 1000));
11972 verbose(env, "stack depth ");
11973 for (i = 0; i < env->subprog_cnt; i++) {
11974 u32 depth = env->subprog_info[i].stack_depth;
11975
11976 verbose(env, "%d", depth);
11977 if (i + 1 < env->subprog_cnt)
11978 verbose(env, "+");
11979 }
11980 verbose(env, "\n");
11981 }
11982 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
11983 "total_states %d peak_states %d mark_read %d\n",
11984 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
11985 env->max_states_per_insn, env->total_states,
11986 env->peak_states, env->longest_mark_read_walk);
11987 }
11988
11989 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
11990 {
11991 const struct btf_type *t, *func_proto;
11992 const struct bpf_struct_ops *st_ops;
11993 const struct btf_member *member;
11994 struct bpf_prog *prog = env->prog;
11995 u32 btf_id, member_idx;
11996 const char *mname;
11997
11998 if (!prog->gpl_compatible) {
11999 verbose(env, "struct ops programs must have a GPL compatible license\n");
12000 return -EINVAL;
12001 }
12002
12003 btf_id = prog->aux->attach_btf_id;
12004 st_ops = bpf_struct_ops_find(btf_id);
12005 if (!st_ops) {
12006 verbose(env, "attach_btf_id %u is not a supported struct\n",
12007 btf_id);
12008 return -ENOTSUPP;
12009 }
12010
12011 t = st_ops->type;
12012 member_idx = prog->expected_attach_type;
12013 if (member_idx >= btf_type_vlen(t)) {
12014 verbose(env, "attach to invalid member idx %u of struct %s\n",
12015 member_idx, st_ops->name);
12016 return -EINVAL;
12017 }
12018
12019 member = &btf_type_member(t)[member_idx];
12020 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12021 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12022 NULL);
12023 if (!func_proto) {
12024 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12025 mname, member_idx, st_ops->name);
12026 return -EINVAL;
12027 }
12028
12029 if (st_ops->check_member) {
12030 int err = st_ops->check_member(t, member);
12031
12032 if (err) {
12033 verbose(env, "attach to unsupported member %s of struct %s\n",
12034 mname, st_ops->name);
12035 return err;
12036 }
12037 }
12038
12039 prog->aux->attach_func_proto = func_proto;
12040 prog->aux->attach_func_name = mname;
12041 env->ops = st_ops->verifier_ops;
12042
12043 return 0;
12044 }
12045 #define SECURITY_PREFIX "security_"
12046
12047 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12048 {
12049 if (within_error_injection_list(addr) ||
12050 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12051 return 0;
12052
12053 return -EINVAL;
12054 }
12055
12056 /* list of non-sleepable functions that are otherwise on
12057 * ALLOW_ERROR_INJECTION list
12058 */
12059 BTF_SET_START(btf_non_sleepable_error_inject)
12060 /* Three functions below can be called from sleepable and non-sleepable context.
12061 * Assume non-sleepable from bpf safety point of view.
12062 */
12063 BTF_ID(func, __add_to_page_cache_locked)
12064 BTF_ID(func, should_fail_alloc_page)
12065 BTF_ID(func, should_failslab)
12066 BTF_SET_END(btf_non_sleepable_error_inject)
12067
12068 static int check_non_sleepable_error_inject(u32 btf_id)
12069 {
12070 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12071 }
12072
12073 int bpf_check_attach_target(struct bpf_verifier_log *log,
12074 const struct bpf_prog *prog,
12075 const struct bpf_prog *tgt_prog,
12076 u32 btf_id,
12077 struct bpf_attach_target_info *tgt_info)
12078 {
12079 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12080 const char prefix[] = "btf_trace_";
12081 int ret = 0, subprog = -1, i;
12082 const struct btf_type *t;
12083 bool conservative = true;
12084 const char *tname;
12085 struct btf *btf;
12086 long addr = 0;
12087
12088 if (!btf_id) {
12089 bpf_log(log, "Tracing programs must provide btf_id\n");
12090 return -EINVAL;
12091 }
12092 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
12093 if (!btf) {
12094 bpf_log(log,
12095 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12096 return -EINVAL;
12097 }
12098 t = btf_type_by_id(btf, btf_id);
12099 if (!t) {
12100 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12101 return -EINVAL;
12102 }
12103 tname = btf_name_by_offset(btf, t->name_off);
12104 if (!tname) {
12105 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12106 return -EINVAL;
12107 }
12108 if (tgt_prog) {
12109 struct bpf_prog_aux *aux = tgt_prog->aux;
12110
12111 for (i = 0; i < aux->func_info_cnt; i++)
12112 if (aux->func_info[i].type_id == btf_id) {
12113 subprog = i;
12114 break;
12115 }
12116 if (subprog == -1) {
12117 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12118 return -EINVAL;
12119 }
12120 conservative = aux->func_info_aux[subprog].unreliable;
12121 if (prog_extension) {
12122 if (conservative) {
12123 bpf_log(log,
12124 "Cannot replace static functions\n");
12125 return -EINVAL;
12126 }
12127 if (!prog->jit_requested) {
12128 bpf_log(log,
12129 "Extension programs should be JITed\n");
12130 return -EINVAL;
12131 }
12132 }
12133 if (!tgt_prog->jited) {
12134 bpf_log(log, "Can attach to only JITed progs\n");
12135 return -EINVAL;
12136 }
12137 if (tgt_prog->type == prog->type) {
12138 /* Cannot fentry/fexit another fentry/fexit program.
12139 * Cannot attach program extension to another extension.
12140 * It's ok to attach fentry/fexit to extension program.
12141 */
12142 bpf_log(log, "Cannot recursively attach\n");
12143 return -EINVAL;
12144 }
12145 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12146 prog_extension &&
12147 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12148 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12149 /* Program extensions can extend all program types
12150 * except fentry/fexit. The reason is the following.
12151 * The fentry/fexit programs are used for performance
12152 * analysis, stats and can be attached to any program
12153 * type except themselves. When extension program is
12154 * replacing XDP function it is necessary to allow
12155 * performance analysis of all functions. Both original
12156 * XDP program and its program extension. Hence
12157 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12158 * allowed. If extending of fentry/fexit was allowed it
12159 * would be possible to create long call chain
12160 * fentry->extension->fentry->extension beyond
12161 * reasonable stack size. Hence extending fentry is not
12162 * allowed.
12163 */
12164 bpf_log(log, "Cannot extend fentry/fexit\n");
12165 return -EINVAL;
12166 }
12167 } else {
12168 if (prog_extension) {
12169 bpf_log(log, "Cannot replace kernel functions\n");
12170 return -EINVAL;
12171 }
12172 }
12173
12174 switch (prog->expected_attach_type) {
12175 case BPF_TRACE_RAW_TP:
12176 if (tgt_prog) {
12177 bpf_log(log,
12178 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12179 return -EINVAL;
12180 }
12181 if (!btf_type_is_typedef(t)) {
12182 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12183 btf_id);
12184 return -EINVAL;
12185 }
12186 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12187 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12188 btf_id, tname);
12189 return -EINVAL;
12190 }
12191 tname += sizeof(prefix) - 1;
12192 t = btf_type_by_id(btf, t->type);
12193 if (!btf_type_is_ptr(t))
12194 /* should never happen in valid vmlinux build */
12195 return -EINVAL;
12196 t = btf_type_by_id(btf, t->type);
12197 if (!btf_type_is_func_proto(t))
12198 /* should never happen in valid vmlinux build */
12199 return -EINVAL;
12200
12201 break;
12202 case BPF_TRACE_ITER:
12203 if (!btf_type_is_func(t)) {
12204 bpf_log(log, "attach_btf_id %u is not a function\n",
12205 btf_id);
12206 return -EINVAL;
12207 }
12208 t = btf_type_by_id(btf, t->type);
12209 if (!btf_type_is_func_proto(t))
12210 return -EINVAL;
12211 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12212 if (ret)
12213 return ret;
12214 break;
12215 default:
12216 if (!prog_extension)
12217 return -EINVAL;
12218 fallthrough;
12219 case BPF_MODIFY_RETURN:
12220 case BPF_LSM_MAC:
12221 case BPF_TRACE_FENTRY:
12222 case BPF_TRACE_FEXIT:
12223 if (!btf_type_is_func(t)) {
12224 bpf_log(log, "attach_btf_id %u is not a function\n",
12225 btf_id);
12226 return -EINVAL;
12227 }
12228 if (prog_extension &&
12229 btf_check_type_match(log, prog, btf, t))
12230 return -EINVAL;
12231 t = btf_type_by_id(btf, t->type);
12232 if (!btf_type_is_func_proto(t))
12233 return -EINVAL;
12234
12235 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12236 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12237 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12238 return -EINVAL;
12239
12240 if (tgt_prog && conservative)
12241 t = NULL;
12242
12243 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12244 if (ret < 0)
12245 return ret;
12246
12247 if (tgt_prog) {
12248 if (subprog == 0)
12249 addr = (long) tgt_prog->bpf_func;
12250 else
12251 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12252 } else {
12253 addr = kallsyms_lookup_name(tname);
12254 if (!addr) {
12255 bpf_log(log,
12256 "The address of function %s cannot be found\n",
12257 tname);
12258 return -ENOENT;
12259 }
12260 }
12261
12262 if (prog->aux->sleepable) {
12263 ret = -EINVAL;
12264 switch (prog->type) {
12265 case BPF_PROG_TYPE_TRACING:
12266 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12267 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12268 */
12269 if (!check_non_sleepable_error_inject(btf_id) &&
12270 within_error_injection_list(addr))
12271 ret = 0;
12272 break;
12273 case BPF_PROG_TYPE_LSM:
12274 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12275 * Only some of them are sleepable.
12276 */
12277 if (bpf_lsm_is_sleepable_hook(btf_id))
12278 ret = 0;
12279 break;
12280 default:
12281 break;
12282 }
12283 if (ret) {
12284 bpf_log(log, "%s is not sleepable\n", tname);
12285 return ret;
12286 }
12287 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12288 if (tgt_prog) {
12289 bpf_log(log, "can't modify return codes of BPF programs\n");
12290 return -EINVAL;
12291 }
12292 ret = check_attach_modify_return(addr, tname);
12293 if (ret) {
12294 bpf_log(log, "%s() is not modifiable\n", tname);
12295 return ret;
12296 }
12297 }
12298
12299 break;
12300 }
12301 tgt_info->tgt_addr = addr;
12302 tgt_info->tgt_name = tname;
12303 tgt_info->tgt_type = t;
12304 return 0;
12305 }
12306
12307 static int check_attach_btf_id(struct bpf_verifier_env *env)
12308 {
12309 struct bpf_prog *prog = env->prog;
12310 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12311 struct bpf_attach_target_info tgt_info = {};
12312 u32 btf_id = prog->aux->attach_btf_id;
12313 struct bpf_trampoline *tr;
12314 int ret;
12315 u64 key;
12316
12317 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12318 prog->type != BPF_PROG_TYPE_LSM) {
12319 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12320 return -EINVAL;
12321 }
12322
12323 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12324 return check_struct_ops_btf_id(env);
12325
12326 if (prog->type != BPF_PROG_TYPE_TRACING &&
12327 prog->type != BPF_PROG_TYPE_LSM &&
12328 prog->type != BPF_PROG_TYPE_EXT)
12329 return 0;
12330
12331 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12332 if (ret)
12333 return ret;
12334
12335 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12336 /* to make freplace equivalent to their targets, they need to
12337 * inherit env->ops and expected_attach_type for the rest of the
12338 * verification
12339 */
12340 env->ops = bpf_verifier_ops[tgt_prog->type];
12341 prog->expected_attach_type = tgt_prog->expected_attach_type;
12342 }
12343
12344 /* store info about the attachment target that will be used later */
12345 prog->aux->attach_func_proto = tgt_info.tgt_type;
12346 prog->aux->attach_func_name = tgt_info.tgt_name;
12347
12348 if (tgt_prog) {
12349 prog->aux->saved_dst_prog_type = tgt_prog->type;
12350 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12351 }
12352
12353 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12354 prog->aux->attach_btf_trace = true;
12355 return 0;
12356 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12357 if (!bpf_iter_prog_supported(prog))
12358 return -EINVAL;
12359 return 0;
12360 }
12361
12362 if (prog->type == BPF_PROG_TYPE_LSM) {
12363 ret = bpf_lsm_verify_prog(&env->log, prog);
12364 if (ret < 0)
12365 return ret;
12366 }
12367
12368 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
12369 tr = bpf_trampoline_get(key, &tgt_info);
12370 if (!tr)
12371 return -ENOMEM;
12372
12373 prog->aux->dst_trampoline = tr;
12374 return 0;
12375 }
12376
12377 struct btf *bpf_get_btf_vmlinux(void)
12378 {
12379 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12380 mutex_lock(&bpf_verifier_lock);
12381 if (!btf_vmlinux)
12382 btf_vmlinux = btf_parse_vmlinux();
12383 mutex_unlock(&bpf_verifier_lock);
12384 }
12385 return btf_vmlinux;
12386 }
12387
12388 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12389 union bpf_attr __user *uattr)
12390 {
12391 u64 start_time = ktime_get_ns();
12392 struct bpf_verifier_env *env;
12393 struct bpf_verifier_log *log;
12394 int i, len, ret = -EINVAL;
12395 bool is_priv;
12396
12397 /* no program is valid */
12398 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12399 return -EINVAL;
12400
12401 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12402 * allocate/free it every time bpf_check() is called
12403 */
12404 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12405 if (!env)
12406 return -ENOMEM;
12407 log = &env->log;
12408
12409 len = (*prog)->len;
12410 env->insn_aux_data =
12411 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12412 ret = -ENOMEM;
12413 if (!env->insn_aux_data)
12414 goto err_free_env;
12415 for (i = 0; i < len; i++)
12416 env->insn_aux_data[i].orig_idx = i;
12417 env->prog = *prog;
12418 env->ops = bpf_verifier_ops[env->prog->type];
12419 is_priv = bpf_capable();
12420
12421 bpf_get_btf_vmlinux();
12422
12423 /* grab the mutex to protect few globals used by verifier */
12424 if (!is_priv)
12425 mutex_lock(&bpf_verifier_lock);
12426
12427 if (attr->log_level || attr->log_buf || attr->log_size) {
12428 /* user requested verbose verifier output
12429 * and supplied buffer to store the verification trace
12430 */
12431 log->level = attr->log_level;
12432 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12433 log->len_total = attr->log_size;
12434
12435 ret = -EINVAL;
12436 /* log attributes have to be sane */
12437 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
12438 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
12439 goto err_unlock;
12440 }
12441
12442 if (IS_ERR(btf_vmlinux)) {
12443 /* Either gcc or pahole or kernel are broken. */
12444 verbose(env, "in-kernel BTF is malformed\n");
12445 ret = PTR_ERR(btf_vmlinux);
12446 goto skip_full_check;
12447 }
12448
12449 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12450 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12451 env->strict_alignment = true;
12452 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12453 env->strict_alignment = false;
12454
12455 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12456 env->allow_uninit_stack = bpf_allow_uninit_stack();
12457 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12458 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12459 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12460 env->bpf_capable = bpf_capable();
12461
12462 if (is_priv)
12463 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12464
12465 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12466 ret = bpf_prog_offload_verifier_prep(env->prog);
12467 if (ret)
12468 goto skip_full_check;
12469 }
12470
12471 env->explored_states = kvcalloc(state_htab_size(env),
12472 sizeof(struct bpf_verifier_state_list *),
12473 GFP_USER);
12474 ret = -ENOMEM;
12475 if (!env->explored_states)
12476 goto skip_full_check;
12477
12478 ret = check_subprogs(env);
12479 if (ret < 0)
12480 goto skip_full_check;
12481
12482 ret = check_btf_info(env, attr, uattr);
12483 if (ret < 0)
12484 goto skip_full_check;
12485
12486 ret = check_attach_btf_id(env);
12487 if (ret)
12488 goto skip_full_check;
12489
12490 ret = resolve_pseudo_ldimm64(env);
12491 if (ret < 0)
12492 goto skip_full_check;
12493
12494 ret = check_cfg(env);
12495 if (ret < 0)
12496 goto skip_full_check;
12497
12498 ret = do_check_subprogs(env);
12499 ret = ret ?: do_check_main(env);
12500
12501 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12502 ret = bpf_prog_offload_finalize(env);
12503
12504 skip_full_check:
12505 kvfree(env->explored_states);
12506
12507 if (ret == 0)
12508 ret = check_max_stack_depth(env);
12509
12510 /* instruction rewrites happen after this point */
12511 if (is_priv) {
12512 if (ret == 0)
12513 opt_hard_wire_dead_code_branches(env);
12514 if (ret == 0)
12515 ret = opt_remove_dead_code(env);
12516 if (ret == 0)
12517 ret = opt_remove_nops(env);
12518 } else {
12519 if (ret == 0)
12520 sanitize_dead_code(env);
12521 }
12522
12523 if (ret == 0)
12524 /* program is valid, convert *(u32*)(ctx + off) accesses */
12525 ret = convert_ctx_accesses(env);
12526
12527 if (ret == 0)
12528 ret = fixup_bpf_calls(env);
12529
12530 /* do 32-bit optimization after insn patching has done so those patched
12531 * insns could be handled correctly.
12532 */
12533 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12534 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12535 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12536 : false;
12537 }
12538
12539 if (ret == 0)
12540 ret = fixup_call_args(env);
12541
12542 env->verification_time = ktime_get_ns() - start_time;
12543 print_verification_stats(env);
12544
12545 if (log->level && bpf_verifier_log_full(log))
12546 ret = -ENOSPC;
12547 if (log->level && !log->ubuf) {
12548 ret = -EFAULT;
12549 goto err_release_maps;
12550 }
12551
12552 if (ret == 0 && env->used_map_cnt) {
12553 /* if program passed verifier, update used_maps in bpf_prog_info */
12554 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12555 sizeof(env->used_maps[0]),
12556 GFP_KERNEL);
12557
12558 if (!env->prog->aux->used_maps) {
12559 ret = -ENOMEM;
12560 goto err_release_maps;
12561 }
12562
12563 memcpy(env->prog->aux->used_maps, env->used_maps,
12564 sizeof(env->used_maps[0]) * env->used_map_cnt);
12565 env->prog->aux->used_map_cnt = env->used_map_cnt;
12566
12567 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12568 * bpf_ld_imm64 instructions
12569 */
12570 convert_pseudo_ld_imm64(env);
12571 }
12572
12573 if (ret == 0)
12574 adjust_btf_func(env);
12575
12576 err_release_maps:
12577 if (!env->prog->aux->used_maps)
12578 /* if we didn't copy map pointers into bpf_prog_info, release
12579 * them now. Otherwise free_used_maps() will release them.
12580 */
12581 release_maps(env);
12582
12583 /* extension progs temporarily inherit the attach_type of their targets
12584 for verification purposes, so set it back to zero before returning
12585 */
12586 if (env->prog->type == BPF_PROG_TYPE_EXT)
12587 env->prog->expected_attach_type = 0;
12588
12589 *prog = env->prog;
12590 err_unlock:
12591 if (!is_priv)
12592 mutex_unlock(&bpf_verifier_lock);
12593 vfree(env->insn_aux_data);
12594 err_free_env:
12595 kfree(env);
12596 return ret;
12597 }