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