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
565 /* The reg state of a pointer or a bounded scalar was saved when
566 * it was spilled to the stack.
567 */
is_spilled_reg(const struct bpf_stack_state * stack)568 static bool is_spilled_reg(const struct bpf_stack_state *stack)
569 {
570 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
571 }
572
scrub_spilled_slot(u8 * stype)573 static void scrub_spilled_slot(u8 *stype)
574 {
575 if (*stype != STACK_INVALID)
576 *stype = STACK_MISC;
577 }
578
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)579 static void print_verifier_state(struct bpf_verifier_env *env,
580 const struct bpf_func_state *state)
581 {
582 const struct bpf_reg_state *reg;
583 enum bpf_reg_type t;
584 int i;
585
586 if (state->frameno)
587 verbose(env, " frame%d:", state->frameno);
588 for (i = 0; i < MAX_BPF_REG; i++) {
589 reg = &state->regs[i];
590 t = reg->type;
591 if (t == NOT_INIT)
592 continue;
593 verbose(env, " R%d", i);
594 print_liveness(env, reg->live);
595 verbose(env, "=%s", reg_type_str[t]);
596 if (t == SCALAR_VALUE && reg->precise)
597 verbose(env, "P");
598 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
599 tnum_is_const(reg->var_off)) {
600 /* reg->off should be 0 for SCALAR_VALUE */
601 verbose(env, "%lld", reg->var_off.value + reg->off);
602 } else {
603 if (t == PTR_TO_BTF_ID ||
604 t == PTR_TO_BTF_ID_OR_NULL ||
605 t == PTR_TO_PERCPU_BTF_ID)
606 verbose(env, "%s", kernel_type_name(reg->btf_id));
607 verbose(env, "(id=%d", reg->id);
608 if (reg_type_may_be_refcounted_or_null(t))
609 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
610 if (t != SCALAR_VALUE)
611 verbose(env, ",off=%d", reg->off);
612 if (type_is_pkt_pointer(t))
613 verbose(env, ",r=%d", reg->range);
614 else if (t == CONST_PTR_TO_MAP ||
615 t == PTR_TO_MAP_VALUE ||
616 t == PTR_TO_MAP_VALUE_OR_NULL)
617 verbose(env, ",ks=%d,vs=%d",
618 reg->map_ptr->key_size,
619 reg->map_ptr->value_size);
620 if (tnum_is_const(reg->var_off)) {
621 /* Typically an immediate SCALAR_VALUE, but
622 * could be a pointer whose offset is too big
623 * for reg->off
624 */
625 verbose(env, ",imm=%llx", reg->var_off.value);
626 } else {
627 if (reg->smin_value != reg->umin_value &&
628 reg->smin_value != S64_MIN)
629 verbose(env, ",smin_value=%lld",
630 (long long)reg->smin_value);
631 if (reg->smax_value != reg->umax_value &&
632 reg->smax_value != S64_MAX)
633 verbose(env, ",smax_value=%lld",
634 (long long)reg->smax_value);
635 if (reg->umin_value != 0)
636 verbose(env, ",umin_value=%llu",
637 (unsigned long long)reg->umin_value);
638 if (reg->umax_value != U64_MAX)
639 verbose(env, ",umax_value=%llu",
640 (unsigned long long)reg->umax_value);
641 if (!tnum_is_unknown(reg->var_off)) {
642 char tn_buf[48];
643
644 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
645 verbose(env, ",var_off=%s", tn_buf);
646 }
647 if (reg->s32_min_value != reg->smin_value &&
648 reg->s32_min_value != S32_MIN)
649 verbose(env, ",s32_min_value=%d",
650 (int)(reg->s32_min_value));
651 if (reg->s32_max_value != reg->smax_value &&
652 reg->s32_max_value != S32_MAX)
653 verbose(env, ",s32_max_value=%d",
654 (int)(reg->s32_max_value));
655 if (reg->u32_min_value != reg->umin_value &&
656 reg->u32_min_value != U32_MIN)
657 verbose(env, ",u32_min_value=%d",
658 (int)(reg->u32_min_value));
659 if (reg->u32_max_value != reg->umax_value &&
660 reg->u32_max_value != U32_MAX)
661 verbose(env, ",u32_max_value=%d",
662 (int)(reg->u32_max_value));
663 }
664 verbose(env, ")");
665 }
666 }
667 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
668 char types_buf[BPF_REG_SIZE + 1];
669 bool valid = false;
670 int j;
671
672 for (j = 0; j < BPF_REG_SIZE; j++) {
673 if (state->stack[i].slot_type[j] != STACK_INVALID)
674 valid = true;
675 types_buf[j] = slot_type_char[
676 state->stack[i].slot_type[j]];
677 }
678 types_buf[BPF_REG_SIZE] = 0;
679 if (!valid)
680 continue;
681 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
682 print_liveness(env, state->stack[i].spilled_ptr.live);
683 if (is_spilled_reg(&state->stack[i])) {
684 reg = &state->stack[i].spilled_ptr;
685 t = reg->type;
686 verbose(env, "=%s", reg_type_str[t]);
687 if (t == SCALAR_VALUE && reg->precise)
688 verbose(env, "P");
689 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
690 verbose(env, "%lld", reg->var_off.value + reg->off);
691 } else {
692 verbose(env, "=%s", types_buf);
693 }
694 }
695 if (state->acquired_refs && state->refs[0].id) {
696 verbose(env, " refs=%d", state->refs[0].id);
697 for (i = 1; i < state->acquired_refs; i++)
698 if (state->refs[i].id)
699 verbose(env, ",%d", state->refs[i].id);
700 }
701 verbose(env, "\n");
702 }
703
704 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
705 static int copy_##NAME##_state(struct bpf_func_state *dst, \
706 const struct bpf_func_state *src) \
707 { \
708 if (!src->FIELD) \
709 return 0; \
710 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
711 /* internal bug, make state invalid to reject the program */ \
712 memset(dst, 0, sizeof(*dst)); \
713 return -EFAULT; \
714 } \
715 memcpy(dst->FIELD, src->FIELD, \
716 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
717 return 0; \
718 }
719 /* copy_reference_state() */
720 COPY_STATE_FN(reference, acquired_refs, refs, 1)
721 /* copy_stack_state() */
COPY_STATE_FN(stack,allocated_stack,stack,BPF_REG_SIZE)722 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
723 #undef COPY_STATE_FN
724
725 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
726 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
727 bool copy_old) \
728 { \
729 u32 old_size = state->COUNT; \
730 struct bpf_##NAME##_state *new_##FIELD; \
731 int slot = size / SIZE; \
732 \
733 if (size <= old_size || !size) { \
734 if (copy_old) \
735 return 0; \
736 state->COUNT = slot * SIZE; \
737 if (!size && old_size) { \
738 kfree(state->FIELD); \
739 state->FIELD = NULL; \
740 } \
741 return 0; \
742 } \
743 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
744 GFP_KERNEL); \
745 if (!new_##FIELD) \
746 return -ENOMEM; \
747 if (copy_old) { \
748 if (state->FIELD) \
749 memcpy(new_##FIELD, state->FIELD, \
750 sizeof(*new_##FIELD) * (old_size / SIZE)); \
751 memset(new_##FIELD + old_size / SIZE, 0, \
752 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
753 } \
754 state->COUNT = slot * SIZE; \
755 kfree(state->FIELD); \
756 state->FIELD = new_##FIELD; \
757 return 0; \
758 }
759 /* realloc_reference_state() */
760 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
761 /* realloc_stack_state() */
762 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
763 #undef REALLOC_STATE_FN
764
765 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
766 * make it consume minimal amount of memory. check_stack_write() access from
767 * the program calls into realloc_func_state() to grow the stack size.
768 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
769 * which realloc_stack_state() copies over. It points to previous
770 * bpf_verifier_state which is never reallocated.
771 */
772 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
773 int refs_size, bool copy_old)
774 {
775 int err = realloc_reference_state(state, refs_size, copy_old);
776 if (err)
777 return err;
778 return realloc_stack_state(state, stack_size, copy_old);
779 }
780
781 /* Acquire a pointer id from the env and update the state->refs to include
782 * this new pointer reference.
783 * On success, returns a valid pointer id to associate with the register
784 * On failure, returns a negative errno.
785 */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)786 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
787 {
788 struct bpf_func_state *state = cur_func(env);
789 int new_ofs = state->acquired_refs;
790 int id, err;
791
792 err = realloc_reference_state(state, state->acquired_refs + 1, true);
793 if (err)
794 return err;
795 id = ++env->id_gen;
796 state->refs[new_ofs].id = id;
797 state->refs[new_ofs].insn_idx = insn_idx;
798
799 return id;
800 }
801
802 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)803 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
804 {
805 int i, last_idx;
806
807 last_idx = state->acquired_refs - 1;
808 for (i = 0; i < state->acquired_refs; i++) {
809 if (state->refs[i].id == ptr_id) {
810 if (last_idx && i != last_idx)
811 memcpy(&state->refs[i], &state->refs[last_idx],
812 sizeof(*state->refs));
813 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
814 state->acquired_refs--;
815 return 0;
816 }
817 }
818 return -EINVAL;
819 }
820
transfer_reference_state(struct bpf_func_state * dst,struct bpf_func_state * src)821 static int transfer_reference_state(struct bpf_func_state *dst,
822 struct bpf_func_state *src)
823 {
824 int err = realloc_reference_state(dst, src->acquired_refs, false);
825 if (err)
826 return err;
827 err = copy_reference_state(dst, src);
828 if (err)
829 return err;
830 return 0;
831 }
832
free_func_state(struct bpf_func_state * state)833 static void free_func_state(struct bpf_func_state *state)
834 {
835 if (!state)
836 return;
837 kfree(state->refs);
838 kfree(state->stack);
839 kfree(state);
840 }
841
clear_jmp_history(struct bpf_verifier_state * state)842 static void clear_jmp_history(struct bpf_verifier_state *state)
843 {
844 kfree(state->jmp_history);
845 state->jmp_history = NULL;
846 state->jmp_history_cnt = 0;
847 }
848
free_verifier_state(struct bpf_verifier_state * state,bool free_self)849 static void free_verifier_state(struct bpf_verifier_state *state,
850 bool free_self)
851 {
852 int i;
853
854 for (i = 0; i <= state->curframe; i++) {
855 free_func_state(state->frame[i]);
856 state->frame[i] = NULL;
857 }
858 clear_jmp_history(state);
859 if (free_self)
860 kfree(state);
861 }
862
863 /* copy verifier state from src to dst growing dst stack space
864 * when necessary to accommodate larger src stack
865 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)866 static int copy_func_state(struct bpf_func_state *dst,
867 const struct bpf_func_state *src)
868 {
869 int err;
870
871 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
872 false);
873 if (err)
874 return err;
875 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
876 err = copy_reference_state(dst, src);
877 if (err)
878 return err;
879 return copy_stack_state(dst, src);
880 }
881
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)882 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
883 const struct bpf_verifier_state *src)
884 {
885 struct bpf_func_state *dst;
886 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
887 int i, err;
888
889 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
890 kfree(dst_state->jmp_history);
891 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
892 if (!dst_state->jmp_history)
893 return -ENOMEM;
894 }
895 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
896 dst_state->jmp_history_cnt = src->jmp_history_cnt;
897
898 /* if dst has more stack frames then src frame, free them */
899 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
900 free_func_state(dst_state->frame[i]);
901 dst_state->frame[i] = NULL;
902 }
903 dst_state->speculative = src->speculative;
904 dst_state->curframe = src->curframe;
905 dst_state->active_spin_lock = src->active_spin_lock;
906 dst_state->branches = src->branches;
907 dst_state->parent = src->parent;
908 dst_state->first_insn_idx = src->first_insn_idx;
909 dst_state->last_insn_idx = src->last_insn_idx;
910 for (i = 0; i <= src->curframe; i++) {
911 dst = dst_state->frame[i];
912 if (!dst) {
913 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
914 if (!dst)
915 return -ENOMEM;
916 dst_state->frame[i] = dst;
917 }
918 err = copy_func_state(dst, src->frame[i]);
919 if (err)
920 return err;
921 }
922 return 0;
923 }
924
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)925 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
926 {
927 while (st) {
928 u32 br = --st->branches;
929
930 /* WARN_ON(br > 1) technically makes sense here,
931 * but see comment in push_stack(), hence:
932 */
933 WARN_ONCE((int)br < 0,
934 "BUG update_branch_counts:branches_to_explore=%d\n",
935 br);
936 if (br)
937 break;
938 st = st->parent;
939 }
940 }
941
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx,bool pop_log)942 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
943 int *insn_idx, bool pop_log)
944 {
945 struct bpf_verifier_state *cur = env->cur_state;
946 struct bpf_verifier_stack_elem *elem, *head = env->head;
947 int err;
948
949 if (env->head == NULL)
950 return -ENOENT;
951
952 if (cur) {
953 err = copy_verifier_state(cur, &head->st);
954 if (err)
955 return err;
956 }
957 if (pop_log)
958 bpf_vlog_reset(&env->log, head->log_pos);
959 if (insn_idx)
960 *insn_idx = head->insn_idx;
961 if (prev_insn_idx)
962 *prev_insn_idx = head->prev_insn_idx;
963 elem = head->next;
964 free_verifier_state(&head->st, false);
965 kfree(head);
966 env->head = elem;
967 env->stack_size--;
968 return 0;
969 }
970
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)971 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
972 int insn_idx, int prev_insn_idx,
973 bool speculative)
974 {
975 struct bpf_verifier_state *cur = env->cur_state;
976 struct bpf_verifier_stack_elem *elem;
977 int err;
978
979 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
980 if (!elem)
981 goto err;
982
983 elem->insn_idx = insn_idx;
984 elem->prev_insn_idx = prev_insn_idx;
985 elem->next = env->head;
986 elem->log_pos = env->log.len_used;
987 env->head = elem;
988 env->stack_size++;
989 err = copy_verifier_state(&elem->st, cur);
990 if (err)
991 goto err;
992 elem->st.speculative |= speculative;
993 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
994 verbose(env, "The sequence of %d jumps is too complex.\n",
995 env->stack_size);
996 goto err;
997 }
998 if (elem->st.parent) {
999 ++elem->st.parent->branches;
1000 /* WARN_ON(branches > 2) technically makes sense here,
1001 * but
1002 * 1. speculative states will bump 'branches' for non-branch
1003 * instructions
1004 * 2. is_state_visited() heuristics may decide not to create
1005 * a new state for a sequence of branches and all such current
1006 * and cloned states will be pointing to a single parent state
1007 * which might have large 'branches' count.
1008 */
1009 }
1010 return &elem->st;
1011 err:
1012 free_verifier_state(env->cur_state, true);
1013 env->cur_state = NULL;
1014 /* pop all elements and return */
1015 while (!pop_stack(env, NULL, NULL, false));
1016 return NULL;
1017 }
1018
1019 #define CALLER_SAVED_REGS 6
1020 static const int caller_saved[CALLER_SAVED_REGS] = {
1021 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1022 };
1023
1024 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1025 struct bpf_reg_state *reg);
1026
1027 /* This helper doesn't clear reg->id */
___mark_reg_known(struct bpf_reg_state * reg,u64 imm)1028 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1029 {
1030 reg->var_off = tnum_const(imm);
1031 reg->smin_value = (s64)imm;
1032 reg->smax_value = (s64)imm;
1033 reg->umin_value = imm;
1034 reg->umax_value = imm;
1035
1036 reg->s32_min_value = (s32)imm;
1037 reg->s32_max_value = (s32)imm;
1038 reg->u32_min_value = (u32)imm;
1039 reg->u32_max_value = (u32)imm;
1040 }
1041
1042 /* Mark the unknown part of a register (variable offset or scalar value) as
1043 * known to have the value @imm.
1044 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)1045 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1046 {
1047 /* Clear id, off, and union(map_ptr, range) */
1048 memset(((u8 *)reg) + sizeof(reg->type), 0,
1049 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1050 ___mark_reg_known(reg, imm);
1051 }
1052
__mark_reg32_known(struct bpf_reg_state * reg,u64 imm)1053 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1054 {
1055 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1056 reg->s32_min_value = (s32)imm;
1057 reg->s32_max_value = (s32)imm;
1058 reg->u32_min_value = (u32)imm;
1059 reg->u32_max_value = (u32)imm;
1060 }
1061
1062 /* Mark the 'variable offset' part of a register as zero. This should be
1063 * used only on registers holding a pointer type.
1064 */
__mark_reg_known_zero(struct bpf_reg_state * reg)1065 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1066 {
1067 __mark_reg_known(reg, 0);
1068 }
1069
__mark_reg_const_zero(struct bpf_reg_state * reg)1070 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1071 {
1072 __mark_reg_known(reg, 0);
1073 reg->type = SCALAR_VALUE;
1074 }
1075
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1076 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1077 struct bpf_reg_state *regs, u32 regno)
1078 {
1079 if (WARN_ON(regno >= MAX_BPF_REG)) {
1080 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1081 /* Something bad happened, let's kill all regs */
1082 for (regno = 0; regno < MAX_BPF_REG; regno++)
1083 __mark_reg_not_init(env, regs + regno);
1084 return;
1085 }
1086 __mark_reg_known_zero(regs + regno);
1087 }
1088
reg_is_pkt_pointer(const struct bpf_reg_state * reg)1089 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1090 {
1091 return type_is_pkt_pointer(reg->type);
1092 }
1093
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)1094 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1095 {
1096 return reg_is_pkt_pointer(reg) ||
1097 reg->type == PTR_TO_PACKET_END;
1098 }
1099
1100 /* 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)1101 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1102 enum bpf_reg_type which)
1103 {
1104 /* The register can already have a range from prior markings.
1105 * This is fine as long as it hasn't been advanced from its
1106 * origin.
1107 */
1108 return reg->type == which &&
1109 reg->id == 0 &&
1110 reg->off == 0 &&
1111 tnum_equals_const(reg->var_off, 0);
1112 }
1113
1114 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)1115 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1116 {
1117 reg->smin_value = S64_MIN;
1118 reg->smax_value = S64_MAX;
1119 reg->umin_value = 0;
1120 reg->umax_value = U64_MAX;
1121
1122 reg->s32_min_value = S32_MIN;
1123 reg->s32_max_value = S32_MAX;
1124 reg->u32_min_value = 0;
1125 reg->u32_max_value = U32_MAX;
1126 }
1127
__mark_reg64_unbounded(struct bpf_reg_state * reg)1128 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1129 {
1130 reg->smin_value = S64_MIN;
1131 reg->smax_value = S64_MAX;
1132 reg->umin_value = 0;
1133 reg->umax_value = U64_MAX;
1134 }
1135
__mark_reg32_unbounded(struct bpf_reg_state * reg)1136 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1137 {
1138 reg->s32_min_value = S32_MIN;
1139 reg->s32_max_value = S32_MAX;
1140 reg->u32_min_value = 0;
1141 reg->u32_max_value = U32_MAX;
1142 }
1143
__update_reg32_bounds(struct bpf_reg_state * reg)1144 static void __update_reg32_bounds(struct bpf_reg_state *reg)
1145 {
1146 struct tnum var32_off = tnum_subreg(reg->var_off);
1147
1148 /* min signed is max(sign bit) | min(other bits) */
1149 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1150 var32_off.value | (var32_off.mask & S32_MIN));
1151 /* max signed is min(sign bit) | max(other bits) */
1152 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1153 var32_off.value | (var32_off.mask & S32_MAX));
1154 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1155 reg->u32_max_value = min(reg->u32_max_value,
1156 (u32)(var32_off.value | var32_off.mask));
1157 }
1158
__update_reg64_bounds(struct bpf_reg_state * reg)1159 static void __update_reg64_bounds(struct bpf_reg_state *reg)
1160 {
1161 /* min signed is max(sign bit) | min(other bits) */
1162 reg->smin_value = max_t(s64, reg->smin_value,
1163 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1164 /* max signed is min(sign bit) | max(other bits) */
1165 reg->smax_value = min_t(s64, reg->smax_value,
1166 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1167 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1168 reg->umax_value = min(reg->umax_value,
1169 reg->var_off.value | reg->var_off.mask);
1170 }
1171
__update_reg_bounds(struct bpf_reg_state * reg)1172 static void __update_reg_bounds(struct bpf_reg_state *reg)
1173 {
1174 __update_reg32_bounds(reg);
1175 __update_reg64_bounds(reg);
1176 }
1177
1178 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg32_deduce_bounds(struct bpf_reg_state * reg)1179 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1180 {
1181 /* Learn sign from signed bounds.
1182 * If we cannot cross the sign boundary, then signed and unsigned bounds
1183 * are the same, so combine. This works even in the negative case, e.g.
1184 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1185 */
1186 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1187 reg->s32_min_value = reg->u32_min_value =
1188 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1189 reg->s32_max_value = reg->u32_max_value =
1190 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1191 return;
1192 }
1193 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1194 * boundary, so we must be careful.
1195 */
1196 if ((s32)reg->u32_max_value >= 0) {
1197 /* Positive. We can't learn anything from the smin, but smax
1198 * is positive, hence safe.
1199 */
1200 reg->s32_min_value = reg->u32_min_value;
1201 reg->s32_max_value = reg->u32_max_value =
1202 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1203 } else if ((s32)reg->u32_min_value < 0) {
1204 /* Negative. We can't learn anything from the smax, but smin
1205 * is negative, hence safe.
1206 */
1207 reg->s32_min_value = reg->u32_min_value =
1208 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1209 reg->s32_max_value = reg->u32_max_value;
1210 }
1211 }
1212
__reg64_deduce_bounds(struct bpf_reg_state * reg)1213 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
1214 {
1215 /* Learn sign from signed bounds.
1216 * If we cannot cross the sign boundary, then signed and unsigned bounds
1217 * are the same, so combine. This works even in the negative case, e.g.
1218 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1219 */
1220 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1221 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1222 reg->umin_value);
1223 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1224 reg->umax_value);
1225 return;
1226 }
1227 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1228 * boundary, so we must be careful.
1229 */
1230 if ((s64)reg->umax_value >= 0) {
1231 /* Positive. We can't learn anything from the smin, but smax
1232 * is positive, hence safe.
1233 */
1234 reg->smin_value = reg->umin_value;
1235 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1236 reg->umax_value);
1237 } else if ((s64)reg->umin_value < 0) {
1238 /* Negative. We can't learn anything from the smax, but smin
1239 * is negative, hence safe.
1240 */
1241 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1242 reg->umin_value);
1243 reg->smax_value = reg->umax_value;
1244 }
1245 }
1246
__reg_deduce_bounds(struct bpf_reg_state * reg)1247 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1248 {
1249 __reg32_deduce_bounds(reg);
1250 __reg64_deduce_bounds(reg);
1251 }
1252
1253 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)1254 static void __reg_bound_offset(struct bpf_reg_state *reg)
1255 {
1256 struct tnum var64_off = tnum_intersect(reg->var_off,
1257 tnum_range(reg->umin_value,
1258 reg->umax_value));
1259 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1260 tnum_range(reg->u32_min_value,
1261 reg->u32_max_value));
1262
1263 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
1264 }
1265
reg_bounds_sync(struct bpf_reg_state * reg)1266 static void reg_bounds_sync(struct bpf_reg_state *reg)
1267 {
1268 /* We might have learned new bounds from the var_off. */
1269 __update_reg_bounds(reg);
1270 /* We might have learned something about the sign bit. */
1271 __reg_deduce_bounds(reg);
1272 /* We might have learned some bits from the bounds. */
1273 __reg_bound_offset(reg);
1274 /* Intersecting with the old var_off might have improved our bounds
1275 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1276 * then new var_off is (0; 0x7f...fc) which improves our umax.
1277 */
1278 __update_reg_bounds(reg);
1279 }
1280
__reg32_bound_s64(s32 a)1281 static bool __reg32_bound_s64(s32 a)
1282 {
1283 return a >= 0 && a <= S32_MAX;
1284 }
1285
__reg_assign_32_into_64(struct bpf_reg_state * reg)1286 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
1287 {
1288 reg->umin_value = reg->u32_min_value;
1289 reg->umax_value = reg->u32_max_value;
1290
1291 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
1292 * be positive otherwise set to worse case bounds and refine later
1293 * from tnum.
1294 */
1295 if (__reg32_bound_s64(reg->s32_min_value) &&
1296 __reg32_bound_s64(reg->s32_max_value)) {
1297 reg->smin_value = reg->s32_min_value;
1298 reg->smax_value = reg->s32_max_value;
1299 } else {
1300 reg->smin_value = 0;
1301 reg->smax_value = U32_MAX;
1302 }
1303 }
1304
__reg_combine_32_into_64(struct bpf_reg_state * reg)1305 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1306 {
1307 /* special case when 64-bit register has upper 32-bit register
1308 * zeroed. Typically happens after zext or <<32, >>32 sequence
1309 * allowing us to use 32-bit bounds directly,
1310 */
1311 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1312 __reg_assign_32_into_64(reg);
1313 } else {
1314 /* Otherwise the best we can do is push lower 32bit known and
1315 * unknown bits into register (var_off set from jmp logic)
1316 * then learn as much as possible from the 64-bit tnum
1317 * known and unknown bits. The previous smin/smax bounds are
1318 * invalid here because of jmp32 compare so mark them unknown
1319 * so they do not impact tnum bounds calculation.
1320 */
1321 __mark_reg64_unbounded(reg);
1322 }
1323 reg_bounds_sync(reg);
1324 }
1325
__reg64_bound_s32(s64 a)1326 static bool __reg64_bound_s32(s64 a)
1327 {
1328 return a >= S32_MIN && a <= S32_MAX;
1329 }
1330
__reg64_bound_u32(u64 a)1331 static bool __reg64_bound_u32(u64 a)
1332 {
1333 return a >= U32_MIN && a <= U32_MAX;
1334 }
1335
__reg_combine_64_into_32(struct bpf_reg_state * reg)1336 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1337 {
1338 __mark_reg32_unbounded(reg);
1339 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
1340 reg->s32_min_value = (s32)reg->smin_value;
1341 reg->s32_max_value = (s32)reg->smax_value;
1342 }
1343 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
1344 reg->u32_min_value = (u32)reg->umin_value;
1345 reg->u32_max_value = (u32)reg->umax_value;
1346 }
1347 reg_bounds_sync(reg);
1348 }
1349
1350 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1351 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1352 struct bpf_reg_state *reg)
1353 {
1354 /*
1355 * Clear type, id, off, and union(map_ptr, range) and
1356 * padding between 'type' and union
1357 */
1358 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
1359 reg->type = SCALAR_VALUE;
1360 reg->var_off = tnum_unknown;
1361 reg->frameno = 0;
1362 reg->precise = !env->bpf_capable;
1363 __mark_reg_unbounded(reg);
1364 }
1365
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1366 static void mark_reg_unknown(struct bpf_verifier_env *env,
1367 struct bpf_reg_state *regs, u32 regno)
1368 {
1369 if (WARN_ON(regno >= MAX_BPF_REG)) {
1370 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1371 /* Something bad happened, let's kill all regs except FP */
1372 for (regno = 0; regno < BPF_REG_FP; regno++)
1373 __mark_reg_not_init(env, regs + regno);
1374 return;
1375 }
1376 __mark_reg_unknown(env, regs + regno);
1377 }
1378
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1379 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1380 struct bpf_reg_state *reg)
1381 {
1382 __mark_reg_unknown(env, reg);
1383 reg->type = NOT_INIT;
1384 }
1385
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1386 static void mark_reg_not_init(struct bpf_verifier_env *env,
1387 struct bpf_reg_state *regs, u32 regno)
1388 {
1389 if (WARN_ON(regno >= MAX_BPF_REG)) {
1390 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1391 /* Something bad happened, let's kill all regs except FP */
1392 for (regno = 0; regno < BPF_REG_FP; regno++)
1393 __mark_reg_not_init(env, regs + regno);
1394 return;
1395 }
1396 __mark_reg_not_init(env, regs + regno);
1397 }
1398
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)1399 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1400 struct bpf_reg_state *regs, u32 regno,
1401 enum bpf_reg_type reg_type, u32 btf_id)
1402 {
1403 if (reg_type == SCALAR_VALUE) {
1404 mark_reg_unknown(env, regs, regno);
1405 return;
1406 }
1407 mark_reg_known_zero(env, regs, regno);
1408 regs[regno].type = PTR_TO_BTF_ID;
1409 regs[regno].btf_id = btf_id;
1410 }
1411
1412 #define DEF_NOT_SUBREG (0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1413 static void init_reg_state(struct bpf_verifier_env *env,
1414 struct bpf_func_state *state)
1415 {
1416 struct bpf_reg_state *regs = state->regs;
1417 int i;
1418
1419 for (i = 0; i < MAX_BPF_REG; i++) {
1420 mark_reg_not_init(env, regs, i);
1421 regs[i].live = REG_LIVE_NONE;
1422 regs[i].parent = NULL;
1423 regs[i].subreg_def = DEF_NOT_SUBREG;
1424 }
1425
1426 /* frame pointer */
1427 regs[BPF_REG_FP].type = PTR_TO_STACK;
1428 mark_reg_known_zero(env, regs, BPF_REG_FP);
1429 regs[BPF_REG_FP].frameno = state->frameno;
1430 }
1431
1432 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1433 static void init_func_state(struct bpf_verifier_env *env,
1434 struct bpf_func_state *state,
1435 int callsite, int frameno, int subprogno)
1436 {
1437 state->callsite = callsite;
1438 state->frameno = frameno;
1439 state->subprogno = subprogno;
1440 init_reg_state(env, state);
1441 }
1442
1443 enum reg_arg_type {
1444 SRC_OP, /* register is used as source operand */
1445 DST_OP, /* register is used as destination operand */
1446 DST_OP_NO_MARK /* same as above, check only, don't mark */
1447 };
1448
cmp_subprogs(const void * a,const void * b)1449 static int cmp_subprogs(const void *a, const void *b)
1450 {
1451 return ((struct bpf_subprog_info *)a)->start -
1452 ((struct bpf_subprog_info *)b)->start;
1453 }
1454
find_subprog(struct bpf_verifier_env * env,int off)1455 static int find_subprog(struct bpf_verifier_env *env, int off)
1456 {
1457 struct bpf_subprog_info *p;
1458
1459 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1460 sizeof(env->subprog_info[0]), cmp_subprogs);
1461 if (!p)
1462 return -ENOENT;
1463 return p - env->subprog_info;
1464
1465 }
1466
add_subprog(struct bpf_verifier_env * env,int off)1467 static int add_subprog(struct bpf_verifier_env *env, int off)
1468 {
1469 int insn_cnt = env->prog->len;
1470 int ret;
1471
1472 if (off >= insn_cnt || off < 0) {
1473 verbose(env, "call to invalid destination\n");
1474 return -EINVAL;
1475 }
1476 ret = find_subprog(env, off);
1477 if (ret >= 0)
1478 return 0;
1479 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1480 verbose(env, "too many subprograms\n");
1481 return -E2BIG;
1482 }
1483 env->subprog_info[env->subprog_cnt++].start = off;
1484 sort(env->subprog_info, env->subprog_cnt,
1485 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1486 return 0;
1487 }
1488
check_subprogs(struct bpf_verifier_env * env)1489 static int check_subprogs(struct bpf_verifier_env *env)
1490 {
1491 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1492 struct bpf_subprog_info *subprog = env->subprog_info;
1493 struct bpf_insn *insn = env->prog->insnsi;
1494 int insn_cnt = env->prog->len;
1495
1496 /* Add entry function. */
1497 ret = add_subprog(env, 0);
1498 if (ret < 0)
1499 return ret;
1500
1501 /* determine subprog starts. The end is one before the next starts */
1502 for (i = 0; i < insn_cnt; i++) {
1503 if (insn[i].code != (BPF_JMP | BPF_CALL))
1504 continue;
1505 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1506 continue;
1507 if (!env->bpf_capable) {
1508 verbose(env,
1509 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1510 return -EPERM;
1511 }
1512 ret = add_subprog(env, i + insn[i].imm + 1);
1513 if (ret < 0)
1514 return ret;
1515 }
1516
1517 /* Add a fake 'exit' subprog which could simplify subprog iteration
1518 * logic. 'subprog_cnt' should not be increased.
1519 */
1520 subprog[env->subprog_cnt].start = insn_cnt;
1521
1522 if (env->log.level & BPF_LOG_LEVEL2)
1523 for (i = 0; i < env->subprog_cnt; i++)
1524 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1525
1526 /* now check that all jumps are within the same subprog */
1527 subprog_start = subprog[cur_subprog].start;
1528 subprog_end = subprog[cur_subprog + 1].start;
1529 for (i = 0; i < insn_cnt; i++) {
1530 u8 code = insn[i].code;
1531
1532 if (code == (BPF_JMP | BPF_CALL) &&
1533 insn[i].imm == BPF_FUNC_tail_call &&
1534 insn[i].src_reg != BPF_PSEUDO_CALL)
1535 subprog[cur_subprog].has_tail_call = true;
1536 if (BPF_CLASS(code) == BPF_LD &&
1537 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1538 subprog[cur_subprog].has_ld_abs = true;
1539 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1540 goto next;
1541 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1542 goto next;
1543 off = i + insn[i].off + 1;
1544 if (off < subprog_start || off >= subprog_end) {
1545 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1546 return -EINVAL;
1547 }
1548 next:
1549 if (i == subprog_end - 1) {
1550 /* to avoid fall-through from one subprog into another
1551 * the last insn of the subprog should be either exit
1552 * or unconditional jump back
1553 */
1554 if (code != (BPF_JMP | BPF_EXIT) &&
1555 code != (BPF_JMP | BPF_JA)) {
1556 verbose(env, "last insn is not an exit or jmp\n");
1557 return -EINVAL;
1558 }
1559 subprog_start = subprog_end;
1560 cur_subprog++;
1561 if (cur_subprog < env->subprog_cnt)
1562 subprog_end = subprog[cur_subprog + 1].start;
1563 }
1564 }
1565 return 0;
1566 }
1567
1568 /* Parentage chain of this register (or stack slot) should take care of all
1569 * issues like callee-saved registers, stack slot allocation time, etc.
1570 */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1571 static int mark_reg_read(struct bpf_verifier_env *env,
1572 const struct bpf_reg_state *state,
1573 struct bpf_reg_state *parent, u8 flag)
1574 {
1575 bool writes = parent == state->parent; /* Observe write marks */
1576 int cnt = 0;
1577
1578 while (parent) {
1579 /* if read wasn't screened by an earlier write ... */
1580 if (writes && state->live & REG_LIVE_WRITTEN)
1581 break;
1582 if (parent->live & REG_LIVE_DONE) {
1583 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1584 reg_type_str[parent->type],
1585 parent->var_off.value, parent->off);
1586 return -EFAULT;
1587 }
1588 /* The first condition is more likely to be true than the
1589 * second, checked it first.
1590 */
1591 if ((parent->live & REG_LIVE_READ) == flag ||
1592 parent->live & REG_LIVE_READ64)
1593 /* The parentage chain never changes and
1594 * this parent was already marked as LIVE_READ.
1595 * There is no need to keep walking the chain again and
1596 * keep re-marking all parents as LIVE_READ.
1597 * This case happens when the same register is read
1598 * multiple times without writes into it in-between.
1599 * Also, if parent has the stronger REG_LIVE_READ64 set,
1600 * then no need to set the weak REG_LIVE_READ32.
1601 */
1602 break;
1603 /* ... then we depend on parent's value */
1604 parent->live |= flag;
1605 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1606 if (flag == REG_LIVE_READ64)
1607 parent->live &= ~REG_LIVE_READ32;
1608 state = parent;
1609 parent = state->parent;
1610 writes = true;
1611 cnt++;
1612 }
1613
1614 if (env->longest_mark_read_walk < cnt)
1615 env->longest_mark_read_walk = cnt;
1616 return 0;
1617 }
1618
1619 /* This function is supposed to be used by the following 32-bit optimization
1620 * code only. It returns TRUE if the source or destination register operates
1621 * on 64-bit, otherwise return FALSE.
1622 */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1623 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1624 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1625 {
1626 u8 code, class, op;
1627
1628 code = insn->code;
1629 class = BPF_CLASS(code);
1630 op = BPF_OP(code);
1631 if (class == BPF_JMP) {
1632 /* BPF_EXIT for "main" will reach here. Return TRUE
1633 * conservatively.
1634 */
1635 if (op == BPF_EXIT)
1636 return true;
1637 if (op == BPF_CALL) {
1638 /* BPF to BPF call will reach here because of marking
1639 * caller saved clobber with DST_OP_NO_MARK for which we
1640 * don't care the register def because they are anyway
1641 * marked as NOT_INIT already.
1642 */
1643 if (insn->src_reg == BPF_PSEUDO_CALL)
1644 return false;
1645 /* Helper call will reach here because of arg type
1646 * check, conservatively return TRUE.
1647 */
1648 if (t == SRC_OP)
1649 return true;
1650
1651 return false;
1652 }
1653 }
1654
1655 if (class == BPF_ALU64 || class == BPF_JMP ||
1656 /* BPF_END always use BPF_ALU class. */
1657 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1658 return true;
1659
1660 if (class == BPF_ALU || class == BPF_JMP32)
1661 return false;
1662
1663 if (class == BPF_LDX) {
1664 if (t != SRC_OP)
1665 return BPF_SIZE(code) == BPF_DW;
1666 /* LDX source must be ptr. */
1667 return true;
1668 }
1669
1670 if (class == BPF_STX) {
1671 if (reg->type != SCALAR_VALUE)
1672 return true;
1673 return BPF_SIZE(code) == BPF_DW;
1674 }
1675
1676 if (class == BPF_LD) {
1677 u8 mode = BPF_MODE(code);
1678
1679 /* LD_IMM64 */
1680 if (mode == BPF_IMM)
1681 return true;
1682
1683 /* Both LD_IND and LD_ABS return 32-bit data. */
1684 if (t != SRC_OP)
1685 return false;
1686
1687 /* Implicit ctx ptr. */
1688 if (regno == BPF_REG_6)
1689 return true;
1690
1691 /* Explicit source could be any width. */
1692 return true;
1693 }
1694
1695 if (class == BPF_ST)
1696 /* The only source register for BPF_ST is a ptr. */
1697 return true;
1698
1699 /* Conservatively return true at default. */
1700 return true;
1701 }
1702
1703 /* Return TRUE if INSN doesn't have explicit value define. */
insn_no_def(struct bpf_insn * insn)1704 static bool insn_no_def(struct bpf_insn *insn)
1705 {
1706 u8 class = BPF_CLASS(insn->code);
1707
1708 return (class == BPF_JMP || class == BPF_JMP32 ||
1709 class == BPF_STX || class == BPF_ST);
1710 }
1711
1712 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)1713 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1714 {
1715 if (insn_no_def(insn))
1716 return false;
1717
1718 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1719 }
1720
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1721 static void mark_insn_zext(struct bpf_verifier_env *env,
1722 struct bpf_reg_state *reg)
1723 {
1724 s32 def_idx = reg->subreg_def;
1725
1726 if (def_idx == DEF_NOT_SUBREG)
1727 return;
1728
1729 env->insn_aux_data[def_idx - 1].zext_dst = true;
1730 /* The dst will be zero extended, so won't be sub-register anymore. */
1731 reg->subreg_def = DEF_NOT_SUBREG;
1732 }
1733
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)1734 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1735 enum reg_arg_type t)
1736 {
1737 struct bpf_verifier_state *vstate = env->cur_state;
1738 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1739 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1740 struct bpf_reg_state *reg, *regs = state->regs;
1741 bool rw64;
1742
1743 if (regno >= MAX_BPF_REG) {
1744 verbose(env, "R%d is invalid\n", regno);
1745 return -EINVAL;
1746 }
1747
1748 reg = ®s[regno];
1749 rw64 = is_reg64(env, insn, regno, reg, t);
1750 if (t == SRC_OP) {
1751 /* check whether register used as source operand can be read */
1752 if (reg->type == NOT_INIT) {
1753 verbose(env, "R%d !read_ok\n", regno);
1754 return -EACCES;
1755 }
1756 /* We don't need to worry about FP liveness because it's read-only */
1757 if (regno == BPF_REG_FP)
1758 return 0;
1759
1760 if (rw64)
1761 mark_insn_zext(env, reg);
1762
1763 return mark_reg_read(env, reg, reg->parent,
1764 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1765 } else {
1766 /* check whether register used as dest operand can be written to */
1767 if (regno == BPF_REG_FP) {
1768 verbose(env, "frame pointer is read only\n");
1769 return -EACCES;
1770 }
1771 reg->live |= REG_LIVE_WRITTEN;
1772 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1773 if (t == DST_OP)
1774 mark_reg_unknown(env, regs, regno);
1775 }
1776 return 0;
1777 }
1778
1779 /* 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)1780 static int push_jmp_history(struct bpf_verifier_env *env,
1781 struct bpf_verifier_state *cur)
1782 {
1783 u32 cnt = cur->jmp_history_cnt;
1784 struct bpf_idx_pair *p;
1785
1786 cnt++;
1787 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1788 if (!p)
1789 return -ENOMEM;
1790 p[cnt - 1].idx = env->insn_idx;
1791 p[cnt - 1].prev_idx = env->prev_insn_idx;
1792 cur->jmp_history = p;
1793 cur->jmp_history_cnt = cnt;
1794 return 0;
1795 }
1796
1797 /* Backtrack one insn at a time. If idx is not at the top of recorded
1798 * history then previous instruction came from straight line execution.
1799 */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)1800 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1801 u32 *history)
1802 {
1803 u32 cnt = *history;
1804
1805 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1806 i = st->jmp_history[cnt - 1].prev_idx;
1807 (*history)--;
1808 } else {
1809 i--;
1810 }
1811 return i;
1812 }
1813
1814 /* For given verifier state backtrack_insn() is called from the last insn to
1815 * the first insn. Its purpose is to compute a bitmask of registers and
1816 * stack slots that needs precision in the parent verifier state.
1817 */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)1818 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1819 u32 *reg_mask, u64 *stack_mask)
1820 {
1821 const struct bpf_insn_cbs cbs = {
1822 .cb_print = verbose,
1823 .private_data = env,
1824 };
1825 struct bpf_insn *insn = env->prog->insnsi + idx;
1826 u8 class = BPF_CLASS(insn->code);
1827 u8 opcode = BPF_OP(insn->code);
1828 u8 mode = BPF_MODE(insn->code);
1829 u32 dreg = 1u << insn->dst_reg;
1830 u32 sreg = 1u << insn->src_reg;
1831 u32 spi;
1832
1833 if (insn->code == 0)
1834 return 0;
1835 if (env->log.level & BPF_LOG_LEVEL) {
1836 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1837 verbose(env, "%d: ", idx);
1838 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1839 }
1840
1841 if (class == BPF_ALU || class == BPF_ALU64) {
1842 if (!(*reg_mask & dreg))
1843 return 0;
1844 if (opcode == BPF_END || opcode == BPF_NEG) {
1845 /* sreg is reserved and unused
1846 * dreg still need precision before this insn
1847 */
1848 return 0;
1849 } else if (opcode == BPF_MOV) {
1850 if (BPF_SRC(insn->code) == BPF_X) {
1851 /* dreg = sreg
1852 * dreg needs precision after this insn
1853 * sreg needs precision before this insn
1854 */
1855 *reg_mask &= ~dreg;
1856 *reg_mask |= sreg;
1857 } else {
1858 /* dreg = K
1859 * dreg needs precision after this insn.
1860 * Corresponding register is already marked
1861 * as precise=true in this verifier state.
1862 * No further markings in parent are necessary
1863 */
1864 *reg_mask &= ~dreg;
1865 }
1866 } else {
1867 if (BPF_SRC(insn->code) == BPF_X) {
1868 /* dreg += sreg
1869 * both dreg and sreg need precision
1870 * before this insn
1871 */
1872 *reg_mask |= sreg;
1873 } /* else dreg += K
1874 * dreg still needs precision before this insn
1875 */
1876 }
1877 } else if (class == BPF_LDX) {
1878 if (!(*reg_mask & dreg))
1879 return 0;
1880 *reg_mask &= ~dreg;
1881
1882 /* scalars can only be spilled into stack w/o losing precision.
1883 * Load from any other memory can be zero extended.
1884 * The desire to keep that precision is already indicated
1885 * by 'precise' mark in corresponding register of this state.
1886 * No further tracking necessary.
1887 */
1888 if (insn->src_reg != BPF_REG_FP)
1889 return 0;
1890
1891 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1892 * that [fp - off] slot contains scalar that needs to be
1893 * tracked with precision
1894 */
1895 spi = (-insn->off - 1) / BPF_REG_SIZE;
1896 if (spi >= 64) {
1897 verbose(env, "BUG spi %d\n", spi);
1898 WARN_ONCE(1, "verifier backtracking bug");
1899 return -EFAULT;
1900 }
1901 *stack_mask |= 1ull << spi;
1902 } else if (class == BPF_STX || class == BPF_ST) {
1903 if (*reg_mask & dreg)
1904 /* stx & st shouldn't be using _scalar_ dst_reg
1905 * to access memory. It means backtracking
1906 * encountered a case of pointer subtraction.
1907 */
1908 return -ENOTSUPP;
1909 /* scalars can only be spilled into stack */
1910 if (insn->dst_reg != BPF_REG_FP)
1911 return 0;
1912 spi = (-insn->off - 1) / BPF_REG_SIZE;
1913 if (spi >= 64) {
1914 verbose(env, "BUG spi %d\n", spi);
1915 WARN_ONCE(1, "verifier backtracking bug");
1916 return -EFAULT;
1917 }
1918 if (!(*stack_mask & (1ull << spi)))
1919 return 0;
1920 *stack_mask &= ~(1ull << spi);
1921 if (class == BPF_STX)
1922 *reg_mask |= sreg;
1923 } else if (class == BPF_JMP || class == BPF_JMP32) {
1924 if (opcode == BPF_CALL) {
1925 if (insn->src_reg == BPF_PSEUDO_CALL)
1926 return -ENOTSUPP;
1927 /* regular helper call sets R0 */
1928 *reg_mask &= ~1;
1929 if (*reg_mask & 0x3f) {
1930 /* if backtracing was looking for registers R1-R5
1931 * they should have been found already.
1932 */
1933 verbose(env, "BUG regs %x\n", *reg_mask);
1934 WARN_ONCE(1, "verifier backtracking bug");
1935 return -EFAULT;
1936 }
1937 } else if (opcode == BPF_EXIT) {
1938 return -ENOTSUPP;
1939 } else if (BPF_SRC(insn->code) == BPF_X) {
1940 if (!(*reg_mask & (dreg | sreg)))
1941 return 0;
1942 /* dreg <cond> sreg
1943 * Both dreg and sreg need precision before
1944 * this insn. If only sreg was marked precise
1945 * before it would be equally necessary to
1946 * propagate it to dreg.
1947 */
1948 *reg_mask |= (sreg | dreg);
1949 /* else dreg <cond> K
1950 * Only dreg still needs precision before
1951 * this insn, so for the K-based conditional
1952 * there is nothing new to be marked.
1953 */
1954 }
1955 } else if (class == BPF_LD) {
1956 if (!(*reg_mask & dreg))
1957 return 0;
1958 *reg_mask &= ~dreg;
1959 /* It's ld_imm64 or ld_abs or ld_ind.
1960 * For ld_imm64 no further tracking of precision
1961 * into parent is necessary
1962 */
1963 if (mode == BPF_IND || mode == BPF_ABS)
1964 /* to be analyzed */
1965 return -ENOTSUPP;
1966 }
1967 return 0;
1968 }
1969
1970 /* the scalar precision tracking algorithm:
1971 * . at the start all registers have precise=false.
1972 * . scalar ranges are tracked as normal through alu and jmp insns.
1973 * . once precise value of the scalar register is used in:
1974 * . ptr + scalar alu
1975 * . if (scalar cond K|scalar)
1976 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1977 * backtrack through the verifier states and mark all registers and
1978 * stack slots with spilled constants that these scalar regisers
1979 * should be precise.
1980 * . during state pruning two registers (or spilled stack slots)
1981 * are equivalent if both are not precise.
1982 *
1983 * Note the verifier cannot simply walk register parentage chain,
1984 * since many different registers and stack slots could have been
1985 * used to compute single precise scalar.
1986 *
1987 * The approach of starting with precise=true for all registers and then
1988 * backtrack to mark a register as not precise when the verifier detects
1989 * that program doesn't care about specific value (e.g., when helper
1990 * takes register as ARG_ANYTHING parameter) is not safe.
1991 *
1992 * It's ok to walk single parentage chain of the verifier states.
1993 * It's possible that this backtracking will go all the way till 1st insn.
1994 * All other branches will be explored for needing precision later.
1995 *
1996 * The backtracking needs to deal with cases like:
1997 * 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)
1998 * r9 -= r8
1999 * r5 = r9
2000 * if r5 > 0x79f goto pc+7
2001 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2002 * r5 += 1
2003 * ...
2004 * call bpf_perf_event_output#25
2005 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2006 *
2007 * and this case:
2008 * r6 = 1
2009 * call foo // uses callee's r6 inside to compute r0
2010 * r0 += r6
2011 * if r0 == 0 goto
2012 *
2013 * to track above reg_mask/stack_mask needs to be independent for each frame.
2014 *
2015 * Also if parent's curframe > frame where backtracking started,
2016 * the verifier need to mark registers in both frames, otherwise callees
2017 * may incorrectly prune callers. This is similar to
2018 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2019 *
2020 * For now backtracking falls back into conservative marking.
2021 */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2022 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2023 struct bpf_verifier_state *st)
2024 {
2025 struct bpf_func_state *func;
2026 struct bpf_reg_state *reg;
2027 int i, j;
2028
2029 /* big hammer: mark all scalars precise in this path.
2030 * pop_stack may still get !precise scalars.
2031 * We also skip current state and go straight to first parent state,
2032 * because precision markings in current non-checkpointed state are
2033 * not needed. See why in the comment in __mark_chain_precision below.
2034 */
2035 for (st = st->parent; st; st = st->parent) {
2036 for (i = 0; i <= st->curframe; i++) {
2037 func = st->frame[i];
2038 for (j = 0; j < BPF_REG_FP; j++) {
2039 reg = &func->regs[j];
2040 if (reg->type != SCALAR_VALUE)
2041 continue;
2042 reg->precise = true;
2043 }
2044 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2045 if (!is_spilled_reg(&func->stack[j]))
2046 continue;
2047 reg = &func->stack[j].spilled_ptr;
2048 if (reg->type != SCALAR_VALUE)
2049 continue;
2050 reg->precise = true;
2051 }
2052 }
2053 }
2054 }
2055
mark_all_scalars_imprecise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)2056 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2057 {
2058 struct bpf_func_state *func;
2059 struct bpf_reg_state *reg;
2060 int i, j;
2061
2062 for (i = 0; i <= st->curframe; i++) {
2063 func = st->frame[i];
2064 for (j = 0; j < BPF_REG_FP; j++) {
2065 reg = &func->regs[j];
2066 if (reg->type != SCALAR_VALUE)
2067 continue;
2068 reg->precise = false;
2069 }
2070 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2071 if (!is_spilled_reg(&func->stack[j]))
2072 continue;
2073 reg = &func->stack[j].spilled_ptr;
2074 if (reg->type != SCALAR_VALUE)
2075 continue;
2076 reg->precise = false;
2077 }
2078 }
2079 }
2080
2081 /*
2082 * __mark_chain_precision() backtracks BPF program instruction sequence and
2083 * chain of verifier states making sure that register *regno* (if regno >= 0)
2084 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
2085 * SCALARS, as well as any other registers and slots that contribute to
2086 * a tracked state of given registers/stack slots, depending on specific BPF
2087 * assembly instructions (see backtrack_insns() for exact instruction handling
2088 * logic). This backtracking relies on recorded jmp_history and is able to
2089 * traverse entire chain of parent states. This process ends only when all the
2090 * necessary registers/slots and their transitive dependencies are marked as
2091 * precise.
2092 *
2093 * One important and subtle aspect is that precise marks *do not matter* in
2094 * the currently verified state (current state). It is important to understand
2095 * why this is the case.
2096 *
2097 * First, note that current state is the state that is not yet "checkpointed",
2098 * i.e., it is not yet put into env->explored_states, and it has no children
2099 * states as well. It's ephemeral, and can end up either a) being discarded if
2100 * compatible explored state is found at some point or BPF_EXIT instruction is
2101 * reached or b) checkpointed and put into env->explored_states, branching out
2102 * into one or more children states.
2103 *
2104 * In the former case, precise markings in current state are completely
2105 * ignored by state comparison code (see regsafe() for details). Only
2106 * checkpointed ("old") state precise markings are important, and if old
2107 * state's register/slot is precise, regsafe() assumes current state's
2108 * register/slot as precise and checks value ranges exactly and precisely. If
2109 * states turn out to be compatible, current state's necessary precise
2110 * markings and any required parent states' precise markings are enforced
2111 * after the fact with propagate_precision() logic, after the fact. But it's
2112 * important to realize that in this case, even after marking current state
2113 * registers/slots as precise, we immediately discard current state. So what
2114 * actually matters is any of the precise markings propagated into current
2115 * state's parent states, which are always checkpointed (due to b) case above).
2116 * As such, for scenario a) it doesn't matter if current state has precise
2117 * markings set or not.
2118 *
2119 * Now, for the scenario b), checkpointing and forking into child(ren)
2120 * state(s). Note that before current state gets to checkpointing step, any
2121 * processed instruction always assumes precise SCALAR register/slot
2122 * knowledge: if precise value or range is useful to prune jump branch, BPF
2123 * verifier takes this opportunity enthusiastically. Similarly, when
2124 * register's value is used to calculate offset or memory address, exact
2125 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
2126 * what we mentioned above about state comparison ignoring precise markings
2127 * during state comparison, BPF verifier ignores and also assumes precise
2128 * markings *at will* during instruction verification process. But as verifier
2129 * assumes precision, it also propagates any precision dependencies across
2130 * parent states, which are not yet finalized, so can be further restricted
2131 * based on new knowledge gained from restrictions enforced by their children
2132 * states. This is so that once those parent states are finalized, i.e., when
2133 * they have no more active children state, state comparison logic in
2134 * is_state_visited() would enforce strict and precise SCALAR ranges, if
2135 * required for correctness.
2136 *
2137 * To build a bit more intuition, note also that once a state is checkpointed,
2138 * the path we took to get to that state is not important. This is crucial
2139 * property for state pruning. When state is checkpointed and finalized at
2140 * some instruction index, it can be correctly and safely used to "short
2141 * circuit" any *compatible* state that reaches exactly the same instruction
2142 * index. I.e., if we jumped to that instruction from a completely different
2143 * code path than original finalized state was derived from, it doesn't
2144 * matter, current state can be discarded because from that instruction
2145 * forward having a compatible state will ensure we will safely reach the
2146 * exit. States describe preconditions for further exploration, but completely
2147 * forget the history of how we got here.
2148 *
2149 * This also means that even if we needed precise SCALAR range to get to
2150 * finalized state, but from that point forward *that same* SCALAR register is
2151 * never used in a precise context (i.e., it's precise value is not needed for
2152 * correctness), it's correct and safe to mark such register as "imprecise"
2153 * (i.e., precise marking set to false). This is what we rely on when we do
2154 * not set precise marking in current state. If no child state requires
2155 * precision for any given SCALAR register, it's safe to dictate that it can
2156 * be imprecise. If any child state does require this register to be precise,
2157 * we'll mark it precise later retroactively during precise markings
2158 * propagation from child state to parent states.
2159 *
2160 * Skipping precise marking setting in current state is a mild version of
2161 * relying on the above observation. But we can utilize this property even
2162 * more aggressively by proactively forgetting any precise marking in the
2163 * current state (which we inherited from the parent state), right before we
2164 * checkpoint it and branch off into new child state. This is done by
2165 * mark_all_scalars_imprecise() to hopefully get more permissive and generic
2166 * finalized states which help in short circuiting more future states.
2167 */
__mark_chain_precision(struct bpf_verifier_env * env,int frame,int regno,int spi)2168 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno,
2169 int spi)
2170 {
2171 struct bpf_verifier_state *st = env->cur_state;
2172 int first_idx = st->first_insn_idx;
2173 int last_idx = env->insn_idx;
2174 struct bpf_func_state *func;
2175 struct bpf_reg_state *reg;
2176 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2177 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
2178 bool skip_first = true;
2179 bool new_marks = false;
2180 int i, err;
2181
2182 if (!env->bpf_capable)
2183 return 0;
2184
2185 /* Do sanity checks against current state of register and/or stack
2186 * slot, but don't set precise flag in current state, as precision
2187 * tracking in the current state is unnecessary.
2188 */
2189 func = st->frame[frame];
2190 if (regno >= 0) {
2191 reg = &func->regs[regno];
2192 if (reg->type != SCALAR_VALUE) {
2193 WARN_ONCE(1, "backtracing misuse");
2194 return -EFAULT;
2195 }
2196 new_marks = true;
2197 }
2198
2199 while (spi >= 0) {
2200 if (!is_spilled_reg(&func->stack[spi])) {
2201 stack_mask = 0;
2202 break;
2203 }
2204 reg = &func->stack[spi].spilled_ptr;
2205 if (reg->type != SCALAR_VALUE) {
2206 stack_mask = 0;
2207 break;
2208 }
2209 new_marks = true;
2210 break;
2211 }
2212
2213 if (!new_marks)
2214 return 0;
2215 if (!reg_mask && !stack_mask)
2216 return 0;
2217
2218 for (;;) {
2219 DECLARE_BITMAP(mask, 64);
2220 u32 history = st->jmp_history_cnt;
2221
2222 if (env->log.level & BPF_LOG_LEVEL)
2223 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2224
2225 if (last_idx < 0) {
2226 /* we are at the entry into subprog, which
2227 * is expected for global funcs, but only if
2228 * requested precise registers are R1-R5
2229 * (which are global func's input arguments)
2230 */
2231 if (st->curframe == 0 &&
2232 st->frame[0]->subprogno > 0 &&
2233 st->frame[0]->callsite == BPF_MAIN_FUNC &&
2234 stack_mask == 0 && (reg_mask & ~0x3e) == 0) {
2235 bitmap_from_u64(mask, reg_mask);
2236 for_each_set_bit(i, mask, 32) {
2237 reg = &st->frame[0]->regs[i];
2238 if (reg->type != SCALAR_VALUE) {
2239 reg_mask &= ~(1u << i);
2240 continue;
2241 }
2242 reg->precise = true;
2243 }
2244 return 0;
2245 }
2246
2247 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n",
2248 st->frame[0]->subprogno, reg_mask, stack_mask);
2249 WARN_ONCE(1, "verifier backtracking bug");
2250 return -EFAULT;
2251 }
2252
2253 for (i = last_idx;;) {
2254 if (skip_first) {
2255 err = 0;
2256 skip_first = false;
2257 } else {
2258 err = backtrack_insn(env, i, ®_mask, &stack_mask);
2259 }
2260 if (err == -ENOTSUPP) {
2261 mark_all_scalars_precise(env, st);
2262 return 0;
2263 } else if (err) {
2264 return err;
2265 }
2266 if (!reg_mask && !stack_mask)
2267 /* Found assignment(s) into tracked register in this state.
2268 * Since this state is already marked, just return.
2269 * Nothing to be tracked further in the parent state.
2270 */
2271 return 0;
2272 if (i == first_idx)
2273 break;
2274 i = get_prev_insn_idx(st, i, &history);
2275 if (i >= env->prog->len) {
2276 /* This can happen if backtracking reached insn 0
2277 * and there are still reg_mask or stack_mask
2278 * to backtrack.
2279 * It means the backtracking missed the spot where
2280 * particular register was initialized with a constant.
2281 */
2282 verbose(env, "BUG backtracking idx %d\n", i);
2283 WARN_ONCE(1, "verifier backtracking bug");
2284 return -EFAULT;
2285 }
2286 }
2287 st = st->parent;
2288 if (!st)
2289 break;
2290
2291 new_marks = false;
2292 func = st->frame[frame];
2293 bitmap_from_u64(mask, reg_mask);
2294 for_each_set_bit(i, mask, 32) {
2295 reg = &func->regs[i];
2296 if (reg->type != SCALAR_VALUE) {
2297 reg_mask &= ~(1u << i);
2298 continue;
2299 }
2300 if (!reg->precise)
2301 new_marks = true;
2302 reg->precise = true;
2303 }
2304
2305 bitmap_from_u64(mask, stack_mask);
2306 for_each_set_bit(i, mask, 64) {
2307 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2308 /* the sequence of instructions:
2309 * 2: (bf) r3 = r10
2310 * 3: (7b) *(u64 *)(r3 -8) = r0
2311 * 4: (79) r4 = *(u64 *)(r10 -8)
2312 * doesn't contain jmps. It's backtracked
2313 * as a single block.
2314 * During backtracking insn 3 is not recognized as
2315 * stack access, so at the end of backtracking
2316 * stack slot fp-8 is still marked in stack_mask.
2317 * However the parent state may not have accessed
2318 * fp-8 and it's "unallocated" stack space.
2319 * In such case fallback to conservative.
2320 */
2321 mark_all_scalars_precise(env, st);
2322 return 0;
2323 }
2324
2325 if (!is_spilled_reg(&func->stack[i])) {
2326 stack_mask &= ~(1ull << i);
2327 continue;
2328 }
2329 reg = &func->stack[i].spilled_ptr;
2330 if (reg->type != SCALAR_VALUE) {
2331 stack_mask &= ~(1ull << i);
2332 continue;
2333 }
2334 if (!reg->precise)
2335 new_marks = true;
2336 reg->precise = true;
2337 }
2338 if (env->log.level & BPF_LOG_LEVEL) {
2339 print_verifier_state(env, func);
2340 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2341 new_marks ? "didn't have" : "already had",
2342 reg_mask, stack_mask);
2343 }
2344
2345 if (!reg_mask && !stack_mask)
2346 break;
2347 if (!new_marks)
2348 break;
2349
2350 last_idx = st->last_insn_idx;
2351 first_idx = st->first_insn_idx;
2352 }
2353 return 0;
2354 }
2355
mark_chain_precision(struct bpf_verifier_env * env,int regno)2356 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2357 {
2358 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1);
2359 }
2360
mark_chain_precision_frame(struct bpf_verifier_env * env,int frame,int regno)2361 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno)
2362 {
2363 return __mark_chain_precision(env, frame, regno, -1);
2364 }
2365
mark_chain_precision_stack_frame(struct bpf_verifier_env * env,int frame,int spi)2366 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi)
2367 {
2368 return __mark_chain_precision(env, frame, -1, spi);
2369 }
2370
is_spillable_regtype(enum bpf_reg_type type)2371 static bool is_spillable_regtype(enum bpf_reg_type type)
2372 {
2373 switch (type) {
2374 case PTR_TO_MAP_VALUE:
2375 case PTR_TO_MAP_VALUE_OR_NULL:
2376 case PTR_TO_STACK:
2377 case PTR_TO_CTX:
2378 case PTR_TO_PACKET:
2379 case PTR_TO_PACKET_META:
2380 case PTR_TO_PACKET_END:
2381 case PTR_TO_FLOW_KEYS:
2382 case CONST_PTR_TO_MAP:
2383 case PTR_TO_SOCKET:
2384 case PTR_TO_SOCKET_OR_NULL:
2385 case PTR_TO_SOCK_COMMON:
2386 case PTR_TO_SOCK_COMMON_OR_NULL:
2387 case PTR_TO_TCP_SOCK:
2388 case PTR_TO_TCP_SOCK_OR_NULL:
2389 case PTR_TO_XDP_SOCK:
2390 case PTR_TO_BTF_ID:
2391 case PTR_TO_BTF_ID_OR_NULL:
2392 case PTR_TO_RDONLY_BUF:
2393 case PTR_TO_RDONLY_BUF_OR_NULL:
2394 case PTR_TO_RDWR_BUF:
2395 case PTR_TO_RDWR_BUF_OR_NULL:
2396 case PTR_TO_PERCPU_BTF_ID:
2397 case PTR_TO_MEM:
2398 case PTR_TO_MEM_OR_NULL:
2399 return true;
2400 default:
2401 return false;
2402 }
2403 }
2404
2405 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)2406 static bool register_is_null(struct bpf_reg_state *reg)
2407 {
2408 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2409 }
2410
register_is_const(struct bpf_reg_state * reg)2411 static bool register_is_const(struct bpf_reg_state *reg)
2412 {
2413 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2414 }
2415
__is_scalar_unbounded(struct bpf_reg_state * reg)2416 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2417 {
2418 return tnum_is_unknown(reg->var_off) &&
2419 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2420 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2421 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2422 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2423 }
2424
register_is_bounded(struct bpf_reg_state * reg)2425 static bool register_is_bounded(struct bpf_reg_state *reg)
2426 {
2427 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2428 }
2429
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)2430 static bool __is_pointer_value(bool allow_ptr_leaks,
2431 const struct bpf_reg_state *reg)
2432 {
2433 if (allow_ptr_leaks)
2434 return false;
2435
2436 return reg->type != SCALAR_VALUE;
2437 }
2438
2439 /* Copy src state preserving dst->parent and dst->live fields */
copy_register_state(struct bpf_reg_state * dst,const struct bpf_reg_state * src)2440 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
2441 {
2442 struct bpf_reg_state *parent = dst->parent;
2443 enum bpf_reg_liveness live = dst->live;
2444
2445 *dst = *src;
2446 dst->parent = parent;
2447 dst->live = live;
2448 }
2449
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg,int size)2450 static void save_register_state(struct bpf_func_state *state,
2451 int spi, struct bpf_reg_state *reg,
2452 int size)
2453 {
2454 int i;
2455
2456 copy_register_state(&state->stack[spi].spilled_ptr, reg);
2457 if (size == BPF_REG_SIZE)
2458 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2459
2460 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2461 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2462
2463 /* size < 8 bytes spill */
2464 for (; i; i--)
2465 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
2466 }
2467
is_bpf_st_mem(struct bpf_insn * insn)2468 static bool is_bpf_st_mem(struct bpf_insn *insn)
2469 {
2470 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
2471 }
2472
2473 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
2474 * stack boundary and alignment are checked in check_mem_access()
2475 */
check_stack_write_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)2476 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2477 /* stack frame we're writing to */
2478 struct bpf_func_state *state,
2479 int off, int size, int value_regno,
2480 int insn_idx)
2481 {
2482 struct bpf_func_state *cur; /* state of the current function */
2483 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
2484 struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
2485 struct bpf_reg_state *reg = NULL;
2486 u32 dst_reg = insn->dst_reg;
2487
2488 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
2489 state->acquired_refs, true);
2490 if (err)
2491 return err;
2492 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2493 * so it's aligned access and [off, off + size) are within stack limits
2494 */
2495 if (!env->allow_ptr_leaks &&
2496 is_spilled_reg(&state->stack[spi]) &&
2497 size != BPF_REG_SIZE) {
2498 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2499 return -EACCES;
2500 }
2501
2502 cur = env->cur_state->frame[env->cur_state->curframe];
2503 if (value_regno >= 0)
2504 reg = &cur->regs[value_regno];
2505 if (!env->bypass_spec_v4) {
2506 bool sanitize = reg && is_spillable_regtype(reg->type);
2507
2508 for (i = 0; i < size; i++) {
2509 u8 type = state->stack[spi].slot_type[i];
2510
2511 if (type != STACK_MISC && type != STACK_ZERO) {
2512 sanitize = true;
2513 break;
2514 }
2515 }
2516
2517 if (sanitize)
2518 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2519 }
2520
2521 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
2522 !register_is_null(reg) && env->bpf_capable) {
2523 if (dst_reg != BPF_REG_FP) {
2524 /* The backtracking logic can only recognize explicit
2525 * stack slot address like [fp - 8]. Other spill of
2526 * scalar via different register has to be conervative.
2527 * Backtrack from here and mark all registers as precise
2528 * that contributed into 'reg' being a constant.
2529 */
2530 err = mark_chain_precision(env, value_regno);
2531 if (err)
2532 return err;
2533 }
2534 save_register_state(state, spi, reg, size);
2535 /* Break the relation on a narrowing spill. */
2536 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
2537 state->stack[spi].spilled_ptr.id = 0;
2538 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
2539 insn->imm != 0 && env->bpf_capable) {
2540 struct bpf_reg_state fake_reg = {};
2541
2542 __mark_reg_known(&fake_reg, insn->imm);
2543 fake_reg.type = SCALAR_VALUE;
2544 save_register_state(state, spi, &fake_reg, size);
2545 } else if (reg && is_spillable_regtype(reg->type)) {
2546 /* register containing pointer is being spilled into stack */
2547 if (size != BPF_REG_SIZE) {
2548 verbose_linfo(env, insn_idx, "; ");
2549 verbose(env, "invalid size of register spill\n");
2550 return -EACCES;
2551 }
2552 if (state != cur && reg->type == PTR_TO_STACK) {
2553 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2554 return -EINVAL;
2555 }
2556 save_register_state(state, spi, reg, size);
2557 } else {
2558 u8 type = STACK_MISC;
2559
2560 /* regular write of data into stack destroys any spilled ptr */
2561 state->stack[spi].spilled_ptr.type = NOT_INIT;
2562 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2563 if (is_spilled_reg(&state->stack[spi]))
2564 for (i = 0; i < BPF_REG_SIZE; i++)
2565 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
2566
2567 /* only mark the slot as written if all 8 bytes were written
2568 * otherwise read propagation may incorrectly stop too soon
2569 * when stack slots are partially written.
2570 * This heuristic means that read propagation will be
2571 * conservative, since it will add reg_live_read marks
2572 * to stack slots all the way to first state when programs
2573 * writes+reads less than 8 bytes
2574 */
2575 if (size == BPF_REG_SIZE)
2576 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2577
2578 /* when we zero initialize stack slots mark them as such */
2579 if ((reg && register_is_null(reg)) ||
2580 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
2581 /* backtracking doesn't work for STACK_ZERO yet. */
2582 err = mark_chain_precision(env, value_regno);
2583 if (err)
2584 return err;
2585 type = STACK_ZERO;
2586 }
2587
2588 /* Mark slots affected by this stack write. */
2589 for (i = 0; i < size; i++)
2590 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2591 type;
2592 }
2593 return 0;
2594 }
2595
2596 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2597 * known to contain a variable offset.
2598 * This function checks whether the write is permitted and conservatively
2599 * tracks the effects of the write, considering that each stack slot in the
2600 * dynamic range is potentially written to.
2601 *
2602 * 'off' includes 'regno->off'.
2603 * 'value_regno' can be -1, meaning that an unknown value is being written to
2604 * the stack.
2605 *
2606 * Spilled pointers in range are not marked as written because we don't know
2607 * what's going to be actually written. This means that read propagation for
2608 * future reads cannot be terminated by this write.
2609 *
2610 * For privileged programs, uninitialized stack slots are considered
2611 * initialized by this write (even though we don't know exactly what offsets
2612 * are going to be written to). The idea is that we don't want the verifier to
2613 * reject future reads that access slots written to through variable offsets.
2614 */
check_stack_write_var_off(struct bpf_verifier_env * env,struct bpf_func_state * state,int ptr_regno,int off,int size,int value_regno,int insn_idx)2615 static int check_stack_write_var_off(struct bpf_verifier_env *env,
2616 /* func where register points to */
2617 struct bpf_func_state *state,
2618 int ptr_regno, int off, int size,
2619 int value_regno, int insn_idx)
2620 {
2621 struct bpf_func_state *cur; /* state of the current function */
2622 int min_off, max_off;
2623 int i, err;
2624 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2625 bool writing_zero = false;
2626 /* set if the fact that we're writing a zero is used to let any
2627 * stack slots remain STACK_ZERO
2628 */
2629 bool zero_used = false;
2630
2631 cur = env->cur_state->frame[env->cur_state->curframe];
2632 ptr_reg = &cur->regs[ptr_regno];
2633 min_off = ptr_reg->smin_value + off;
2634 max_off = ptr_reg->smax_value + off + size;
2635 if (value_regno >= 0)
2636 value_reg = &cur->regs[value_regno];
2637 if (value_reg && register_is_null(value_reg))
2638 writing_zero = true;
2639
2640 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2641 state->acquired_refs, true);
2642 if (err)
2643 return err;
2644
2645
2646 /* Variable offset writes destroy any spilled pointers in range. */
2647 for (i = min_off; i < max_off; i++) {
2648 u8 new_type, *stype;
2649 int slot, spi;
2650
2651 slot = -i - 1;
2652 spi = slot / BPF_REG_SIZE;
2653 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2654
2655 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
2656 /* Reject the write if range we may write to has not
2657 * been initialized beforehand. If we didn't reject
2658 * here, the ptr status would be erased below (even
2659 * though not all slots are actually overwritten),
2660 * possibly opening the door to leaks.
2661 *
2662 * We do however catch STACK_INVALID case below, and
2663 * only allow reading possibly uninitialized memory
2664 * later for CAP_PERFMON, as the write may not happen to
2665 * that slot.
2666 */
2667 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2668 insn_idx, i);
2669 return -EINVAL;
2670 }
2671
2672 /* Erase all spilled pointers. */
2673 state->stack[spi].spilled_ptr.type = NOT_INIT;
2674
2675 /* Update the slot type. */
2676 new_type = STACK_MISC;
2677 if (writing_zero && *stype == STACK_ZERO) {
2678 new_type = STACK_ZERO;
2679 zero_used = true;
2680 }
2681 /* If the slot is STACK_INVALID, we check whether it's OK to
2682 * pretend that it will be initialized by this write. The slot
2683 * might not actually be written to, and so if we mark it as
2684 * initialized future reads might leak uninitialized memory.
2685 * For privileged programs, we will accept such reads to slots
2686 * that may or may not be written because, if we're reject
2687 * them, the error would be too confusing.
2688 */
2689 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2690 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2691 insn_idx, i);
2692 return -EINVAL;
2693 }
2694 *stype = new_type;
2695 }
2696 if (zero_used) {
2697 /* backtracking doesn't work for STACK_ZERO yet. */
2698 err = mark_chain_precision(env, value_regno);
2699 if (err)
2700 return err;
2701 }
2702 return 0;
2703 }
2704
2705 /* When register 'dst_regno' is assigned some values from stack[min_off,
2706 * max_off), we set the register's type according to the types of the
2707 * respective stack slots. If all the stack values are known to be zeros, then
2708 * so is the destination reg. Otherwise, the register is considered to be
2709 * SCALAR. This function does not deal with register filling; the caller must
2710 * ensure that all spilled registers in the stack range have been marked as
2711 * read.
2712 */
mark_reg_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * ptr_state,int min_off,int max_off,int dst_regno)2713 static void mark_reg_stack_read(struct bpf_verifier_env *env,
2714 /* func where src register points to */
2715 struct bpf_func_state *ptr_state,
2716 int min_off, int max_off, int dst_regno)
2717 {
2718 struct bpf_verifier_state *vstate = env->cur_state;
2719 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2720 int i, slot, spi;
2721 u8 *stype;
2722 int zeros = 0;
2723
2724 for (i = min_off; i < max_off; i++) {
2725 slot = -i - 1;
2726 spi = slot / BPF_REG_SIZE;
2727 stype = ptr_state->stack[spi].slot_type;
2728 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2729 break;
2730 zeros++;
2731 }
2732 if (zeros == max_off - min_off) {
2733 /* any access_size read into register is zero extended,
2734 * so the whole register == const_zero
2735 */
2736 __mark_reg_const_zero(&state->regs[dst_regno]);
2737 /* backtracking doesn't support STACK_ZERO yet,
2738 * so mark it precise here, so that later
2739 * backtracking can stop here.
2740 * Backtracking may not need this if this register
2741 * doesn't participate in pointer adjustment.
2742 * Forward propagation of precise flag is not
2743 * necessary either. This mark is only to stop
2744 * backtracking. Any register that contributed
2745 * to const 0 was marked precise before spill.
2746 */
2747 state->regs[dst_regno].precise = true;
2748 } else {
2749 /* have read misc data from the stack */
2750 mark_reg_unknown(env, state->regs, dst_regno);
2751 }
2752 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2753 }
2754
2755 /* Read the stack at 'off' and put the results into the register indicated by
2756 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2757 * spilled reg.
2758 *
2759 * 'dst_regno' can be -1, meaning that the read value is not going to a
2760 * register.
2761 *
2762 * The access is assumed to be within the current stack bounds.
2763 */
check_stack_read_fixed_off(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int dst_regno)2764 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2765 /* func where src register points to */
2766 struct bpf_func_state *reg_state,
2767 int off, int size, int dst_regno)
2768 {
2769 struct bpf_verifier_state *vstate = env->cur_state;
2770 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2771 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2772 struct bpf_reg_state *reg;
2773 u8 *stype, type;
2774
2775 stype = reg_state->stack[spi].slot_type;
2776 reg = ®_state->stack[spi].spilled_ptr;
2777
2778 if (is_spilled_reg(®_state->stack[spi])) {
2779 u8 spill_size = 1;
2780
2781 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
2782 spill_size++;
2783
2784 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
2785 if (reg->type != SCALAR_VALUE) {
2786 verbose_linfo(env, env->insn_idx, "; ");
2787 verbose(env, "invalid size of register fill\n");
2788 return -EACCES;
2789 }
2790
2791 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2792 if (dst_regno < 0)
2793 return 0;
2794
2795 if (!(off % BPF_REG_SIZE) && size == spill_size) {
2796 /* The earlier check_reg_arg() has decided the
2797 * subreg_def for this insn. Save it first.
2798 */
2799 s32 subreg_def = state->regs[dst_regno].subreg_def;
2800
2801 copy_register_state(&state->regs[dst_regno], reg);
2802 state->regs[dst_regno].subreg_def = subreg_def;
2803 } else {
2804 for (i = 0; i < size; i++) {
2805 type = stype[(slot - i) % BPF_REG_SIZE];
2806 if (type == STACK_SPILL)
2807 continue;
2808 if (type == STACK_MISC)
2809 continue;
2810 verbose(env, "invalid read from stack off %d+%d size %d\n",
2811 off, i, size);
2812 return -EACCES;
2813 }
2814 mark_reg_unknown(env, state->regs, dst_regno);
2815 }
2816 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2817 return 0;
2818 }
2819
2820 if (dst_regno >= 0) {
2821 /* restore register state from stack */
2822 copy_register_state(&state->regs[dst_regno], reg);
2823 /* mark reg as written since spilled pointer state likely
2824 * has its liveness marks cleared by is_state_visited()
2825 * which resets stack/reg liveness for state transitions
2826 */
2827 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2828 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2829 /* If dst_regno==-1, the caller is asking us whether
2830 * it is acceptable to use this value as a SCALAR_VALUE
2831 * (e.g. for XADD).
2832 * We must not allow unprivileged callers to do that
2833 * with spilled pointers.
2834 */
2835 verbose(env, "leaking pointer from stack off %d\n",
2836 off);
2837 return -EACCES;
2838 }
2839 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2840 } else {
2841 for (i = 0; i < size; i++) {
2842 type = stype[(slot - i) % BPF_REG_SIZE];
2843 if (type == STACK_MISC)
2844 continue;
2845 if (type == STACK_ZERO)
2846 continue;
2847 verbose(env, "invalid read from stack off %d+%d size %d\n",
2848 off, i, size);
2849 return -EACCES;
2850 }
2851 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2852 if (dst_regno >= 0)
2853 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
2854 }
2855 return 0;
2856 }
2857
2858 enum stack_access_src {
2859 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2860 ACCESS_HELPER = 2, /* the access is performed by a helper */
2861 };
2862
2863 static int check_stack_range_initialized(struct bpf_verifier_env *env,
2864 int regno, int off, int access_size,
2865 bool zero_size_allowed,
2866 enum stack_access_src type,
2867 struct bpf_call_arg_meta *meta);
2868
reg_state(struct bpf_verifier_env * env,int regno)2869 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2870 {
2871 return cur_regs(env) + regno;
2872 }
2873
2874 /* Read the stack at 'ptr_regno + off' and put the result into the register
2875 * 'dst_regno'.
2876 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2877 * but not its variable offset.
2878 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2879 *
2880 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2881 * filling registers (i.e. reads of spilled register cannot be detected when
2882 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2883 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2884 * offset; for a fixed offset check_stack_read_fixed_off should be used
2885 * instead.
2886 */
check_stack_read_var_off(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2887 static int check_stack_read_var_off(struct bpf_verifier_env *env,
2888 int ptr_regno, int off, int size, int dst_regno)
2889 {
2890 /* The state of the source register. */
2891 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2892 struct bpf_func_state *ptr_state = func(env, reg);
2893 int err;
2894 int min_off, max_off;
2895
2896 /* Note that we pass a NULL meta, so raw access will not be permitted.
2897 */
2898 err = check_stack_range_initialized(env, ptr_regno, off, size,
2899 false, ACCESS_DIRECT, NULL);
2900 if (err)
2901 return err;
2902
2903 min_off = reg->smin_value + off;
2904 max_off = reg->smax_value + off;
2905 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2906 return 0;
2907 }
2908
2909 /* check_stack_read dispatches to check_stack_read_fixed_off or
2910 * check_stack_read_var_off.
2911 *
2912 * The caller must ensure that the offset falls within the allocated stack
2913 * bounds.
2914 *
2915 * 'dst_regno' is a register which will receive the value from the stack. It
2916 * can be -1, meaning that the read value is not going to a register.
2917 */
check_stack_read(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int dst_regno)2918 static int check_stack_read(struct bpf_verifier_env *env,
2919 int ptr_regno, int off, int size,
2920 int dst_regno)
2921 {
2922 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2923 struct bpf_func_state *state = func(env, reg);
2924 int err;
2925 /* Some accesses are only permitted with a static offset. */
2926 bool var_off = !tnum_is_const(reg->var_off);
2927
2928 /* The offset is required to be static when reads don't go to a
2929 * register, in order to not leak pointers (see
2930 * check_stack_read_fixed_off).
2931 */
2932 if (dst_regno < 0 && var_off) {
2933 char tn_buf[48];
2934
2935 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2936 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
2937 tn_buf, off, size);
2938 return -EACCES;
2939 }
2940 /* Variable offset is prohibited for unprivileged mode for simplicity
2941 * since it requires corresponding support in Spectre masking for stack
2942 * ALU. See also retrieve_ptr_limit(). The check in
2943 * check_stack_access_for_ptr_arithmetic() called by
2944 * adjust_ptr_min_max_vals() prevents users from creating stack pointers
2945 * with variable offsets, therefore no check is required here. Further,
2946 * just checking it here would be insufficient as speculative stack
2947 * writes could still lead to unsafe speculative behaviour.
2948 */
2949 if (!var_off) {
2950 off += reg->var_off.value;
2951 err = check_stack_read_fixed_off(env, state, off, size,
2952 dst_regno);
2953 } else {
2954 /* Variable offset stack reads need more conservative handling
2955 * than fixed offset ones. Note that dst_regno >= 0 on this
2956 * branch.
2957 */
2958 err = check_stack_read_var_off(env, ptr_regno, off, size,
2959 dst_regno);
2960 }
2961 return err;
2962 }
2963
2964
2965 /* check_stack_write dispatches to check_stack_write_fixed_off or
2966 * check_stack_write_var_off.
2967 *
2968 * 'ptr_regno' is the register used as a pointer into the stack.
2969 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2970 * 'value_regno' is the register whose value we're writing to the stack. It can
2971 * be -1, meaning that we're not writing from a register.
2972 *
2973 * The caller must ensure that the offset falls within the maximum stack size.
2974 */
check_stack_write(struct bpf_verifier_env * env,int ptr_regno,int off,int size,int value_regno,int insn_idx)2975 static int check_stack_write(struct bpf_verifier_env *env,
2976 int ptr_regno, int off, int size,
2977 int value_regno, int insn_idx)
2978 {
2979 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2980 struct bpf_func_state *state = func(env, reg);
2981 int err;
2982
2983 if (tnum_is_const(reg->var_off)) {
2984 off += reg->var_off.value;
2985 err = check_stack_write_fixed_off(env, state, off, size,
2986 value_regno, insn_idx);
2987 } else {
2988 /* Variable offset stack reads need more conservative handling
2989 * than fixed offset ones.
2990 */
2991 err = check_stack_write_var_off(env, state,
2992 ptr_regno, off, size,
2993 value_regno, insn_idx);
2994 }
2995 return err;
2996 }
2997
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)2998 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2999 int off, int size, enum bpf_access_type type)
3000 {
3001 struct bpf_reg_state *regs = cur_regs(env);
3002 struct bpf_map *map = regs[regno].map_ptr;
3003 u32 cap = bpf_map_flags_to_cap(map);
3004
3005 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3006 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3007 map->value_size, off, size);
3008 return -EACCES;
3009 }
3010
3011 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3012 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3013 map->value_size, off, size);
3014 return -EACCES;
3015 }
3016
3017 return 0;
3018 }
3019
3020 /* 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)3021 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3022 int off, int size, u32 mem_size,
3023 bool zero_size_allowed)
3024 {
3025 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3026 struct bpf_reg_state *reg;
3027
3028 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3029 return 0;
3030
3031 reg = &cur_regs(env)[regno];
3032 switch (reg->type) {
3033 case PTR_TO_MAP_VALUE:
3034 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
3035 mem_size, off, size);
3036 break;
3037 case PTR_TO_PACKET:
3038 case PTR_TO_PACKET_META:
3039 case PTR_TO_PACKET_END:
3040 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3041 off, size, regno, reg->id, off, mem_size);
3042 break;
3043 case PTR_TO_MEM:
3044 default:
3045 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3046 mem_size, off, size);
3047 }
3048
3049 return -EACCES;
3050 }
3051
3052 /* 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)3053 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3054 int off, int size, u32 mem_size,
3055 bool zero_size_allowed)
3056 {
3057 struct bpf_verifier_state *vstate = env->cur_state;
3058 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3059 struct bpf_reg_state *reg = &state->regs[regno];
3060 int err;
3061
3062 /* We may have adjusted the register pointing to memory region, so we
3063 * need to try adding each of min_value and max_value to off
3064 * to make sure our theoretical access will be safe.
3065 */
3066 if (env->log.level & BPF_LOG_LEVEL)
3067 print_verifier_state(env, state);
3068
3069 /* The minimum value is only important with signed
3070 * comparisons where we can't assume the floor of a
3071 * value is 0. If we are using signed variables for our
3072 * index'es we need to make sure that whatever we use
3073 * will have a set floor within our range.
3074 */
3075 if (reg->smin_value < 0 &&
3076 (reg->smin_value == S64_MIN ||
3077 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3078 reg->smin_value + off < 0)) {
3079 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3080 regno);
3081 return -EACCES;
3082 }
3083 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3084 mem_size, zero_size_allowed);
3085 if (err) {
3086 verbose(env, "R%d min value is outside of the allowed memory range\n",
3087 regno);
3088 return err;
3089 }
3090
3091 /* If we haven't set a max value then we need to bail since we can't be
3092 * sure we won't do bad things.
3093 * If reg->umax_value + off could overflow, treat that as unbounded too.
3094 */
3095 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
3096 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
3097 regno);
3098 return -EACCES;
3099 }
3100 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3101 mem_size, zero_size_allowed);
3102 if (err) {
3103 verbose(env, "R%d max value is outside of the allowed memory range\n",
3104 regno);
3105 return err;
3106 }
3107
3108 return 0;
3109 }
3110
3111 /* 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)3112 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3113 int off, int size, bool zero_size_allowed)
3114 {
3115 struct bpf_verifier_state *vstate = env->cur_state;
3116 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3117 struct bpf_reg_state *reg = &state->regs[regno];
3118 struct bpf_map *map = reg->map_ptr;
3119 int err;
3120
3121 err = check_mem_region_access(env, regno, off, size, map->value_size,
3122 zero_size_allowed);
3123 if (err)
3124 return err;
3125
3126 if (map_value_has_spin_lock(map)) {
3127 u32 lock = map->spin_lock_off;
3128
3129 /* if any part of struct bpf_spin_lock can be touched by
3130 * load/store reject this program.
3131 * To check that [x1, x2) overlaps with [y1, y2)
3132 * it is sufficient to check x1 < y2 && y1 < x2.
3133 */
3134 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3135 lock < reg->umax_value + off + size) {
3136 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3137 return -EACCES;
3138 }
3139 }
3140 return err;
3141 }
3142
3143 #define MAX_PACKET_OFF 0xffff
3144
resolve_prog_type(struct bpf_prog * prog)3145 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3146 {
3147 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
3148 }
3149
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)3150 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3151 const struct bpf_call_arg_meta *meta,
3152 enum bpf_access_type t)
3153 {
3154 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3155
3156 switch (prog_type) {
3157 /* Program types only with direct read access go here! */
3158 case BPF_PROG_TYPE_LWT_IN:
3159 case BPF_PROG_TYPE_LWT_OUT:
3160 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
3161 case BPF_PROG_TYPE_SK_REUSEPORT:
3162 case BPF_PROG_TYPE_FLOW_DISSECTOR:
3163 case BPF_PROG_TYPE_CGROUP_SKB:
3164 if (t == BPF_WRITE)
3165 return false;
3166 fallthrough;
3167
3168 /* Program types with direct read + write access go here! */
3169 case BPF_PROG_TYPE_SCHED_CLS:
3170 case BPF_PROG_TYPE_SCHED_ACT:
3171 case BPF_PROG_TYPE_XDP:
3172 case BPF_PROG_TYPE_LWT_XMIT:
3173 case BPF_PROG_TYPE_SK_SKB:
3174 case BPF_PROG_TYPE_SK_MSG:
3175 if (meta)
3176 return meta->pkt_access;
3177
3178 env->seen_direct_write = true;
3179 return true;
3180
3181 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3182 if (t == BPF_WRITE)
3183 env->seen_direct_write = true;
3184
3185 return true;
3186
3187 default:
3188 return false;
3189 }
3190 }
3191
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)3192 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
3193 int size, bool zero_size_allowed)
3194 {
3195 struct bpf_reg_state *regs = cur_regs(env);
3196 struct bpf_reg_state *reg = ®s[regno];
3197 int err;
3198
3199 /* We may have added a variable offset to the packet pointer; but any
3200 * reg->range we have comes after that. We are only checking the fixed
3201 * offset.
3202 */
3203
3204 /* We don't allow negative numbers, because we aren't tracking enough
3205 * detail to prove they're safe.
3206 */
3207 if (reg->smin_value < 0) {
3208 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3209 regno);
3210 return -EACCES;
3211 }
3212
3213 err = reg->range < 0 ? -EINVAL :
3214 __check_mem_access(env, regno, off, size, reg->range,
3215 zero_size_allowed);
3216 if (err) {
3217 verbose(env, "R%d offset is outside of the packet\n", regno);
3218 return err;
3219 }
3220
3221 /* __check_mem_access has made sure "off + size - 1" is within u16.
3222 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3223 * otherwise find_good_pkt_pointers would have refused to set range info
3224 * that __check_mem_access would have rejected this pkt access.
3225 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3226 */
3227 env->prog->aux->max_pkt_offset =
3228 max_t(u32, env->prog->aux->max_pkt_offset,
3229 off + reg->umax_value + size - 1);
3230
3231 return err;
3232 }
3233
3234 /* 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)3235 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
3236 enum bpf_access_type t, enum bpf_reg_type *reg_type,
3237 u32 *btf_id)
3238 {
3239 struct bpf_insn_access_aux info = {
3240 .reg_type = *reg_type,
3241 .log = &env->log,
3242 };
3243
3244 if (env->ops->is_valid_access &&
3245 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
3246 /* A non zero info.ctx_field_size indicates that this field is a
3247 * candidate for later verifier transformation to load the whole
3248 * field and then apply a mask when accessed with a narrower
3249 * access than actual ctx access size. A zero info.ctx_field_size
3250 * will only allow for whole field access and rejects any other
3251 * type of narrower access.
3252 */
3253 *reg_type = info.reg_type;
3254
3255 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL)
3256 *btf_id = info.btf_id;
3257 else
3258 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
3259 /* remember the offset of last byte accessed in ctx */
3260 if (env->prog->aux->max_ctx_offset < off + size)
3261 env->prog->aux->max_ctx_offset = off + size;
3262 return 0;
3263 }
3264
3265 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
3266 return -EACCES;
3267 }
3268
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)3269 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3270 int size)
3271 {
3272 if (size < 0 || off < 0 ||
3273 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3274 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3275 off, size);
3276 return -EACCES;
3277 }
3278 return 0;
3279 }
3280
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)3281 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3282 u32 regno, int off, int size,
3283 enum bpf_access_type t)
3284 {
3285 struct bpf_reg_state *regs = cur_regs(env);
3286 struct bpf_reg_state *reg = ®s[regno];
3287 struct bpf_insn_access_aux info = {};
3288 bool valid;
3289
3290 if (reg->smin_value < 0) {
3291 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3292 regno);
3293 return -EACCES;
3294 }
3295
3296 switch (reg->type) {
3297 case PTR_TO_SOCK_COMMON:
3298 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3299 break;
3300 case PTR_TO_SOCKET:
3301 valid = bpf_sock_is_valid_access(off, size, t, &info);
3302 break;
3303 case PTR_TO_TCP_SOCK:
3304 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3305 break;
3306 case PTR_TO_XDP_SOCK:
3307 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3308 break;
3309 default:
3310 valid = false;
3311 }
3312
3313
3314 if (valid) {
3315 env->insn_aux_data[insn_idx].ctx_field_size =
3316 info.ctx_field_size;
3317 return 0;
3318 }
3319
3320 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3321 regno, reg_type_str[reg->type], off, size);
3322
3323 return -EACCES;
3324 }
3325
is_pointer_value(struct bpf_verifier_env * env,int regno)3326 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3327 {
3328 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
3329 }
3330
is_ctx_reg(struct bpf_verifier_env * env,int regno)3331 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3332 {
3333 const struct bpf_reg_state *reg = reg_state(env, regno);
3334
3335 return reg->type == PTR_TO_CTX;
3336 }
3337
is_sk_reg(struct bpf_verifier_env * env,int regno)3338 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3339 {
3340 const struct bpf_reg_state *reg = reg_state(env, regno);
3341
3342 return type_is_sk_pointer(reg->type);
3343 }
3344
is_pkt_reg(struct bpf_verifier_env * env,int regno)3345 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3346 {
3347 const struct bpf_reg_state *reg = reg_state(env, regno);
3348
3349 return type_is_pkt_pointer(reg->type);
3350 }
3351
is_flow_key_reg(struct bpf_verifier_env * env,int regno)3352 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3353 {
3354 const struct bpf_reg_state *reg = reg_state(env, regno);
3355
3356 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3357 return reg->type == PTR_TO_FLOW_KEYS;
3358 }
3359
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)3360 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3361 const struct bpf_reg_state *reg,
3362 int off, int size, bool strict)
3363 {
3364 struct tnum reg_off;
3365 int ip_align;
3366
3367 /* Byte size accesses are always allowed. */
3368 if (!strict || size == 1)
3369 return 0;
3370
3371 /* For platforms that do not have a Kconfig enabling
3372 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3373 * NET_IP_ALIGN is universally set to '2'. And on platforms
3374 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3375 * to this code only in strict mode where we want to emulate
3376 * the NET_IP_ALIGN==2 checking. Therefore use an
3377 * unconditional IP align value of '2'.
3378 */
3379 ip_align = 2;
3380
3381 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3382 if (!tnum_is_aligned(reg_off, size)) {
3383 char tn_buf[48];
3384
3385 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3386 verbose(env,
3387 "misaligned packet access off %d+%s+%d+%d size %d\n",
3388 ip_align, tn_buf, reg->off, off, size);
3389 return -EACCES;
3390 }
3391
3392 return 0;
3393 }
3394
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)3395 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3396 const struct bpf_reg_state *reg,
3397 const char *pointer_desc,
3398 int off, int size, bool strict)
3399 {
3400 struct tnum reg_off;
3401
3402 /* Byte size accesses are always allowed. */
3403 if (!strict || size == 1)
3404 return 0;
3405
3406 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3407 if (!tnum_is_aligned(reg_off, size)) {
3408 char tn_buf[48];
3409
3410 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3411 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
3412 pointer_desc, tn_buf, reg->off, off, size);
3413 return -EACCES;
3414 }
3415
3416 return 0;
3417 }
3418
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)3419 static int check_ptr_alignment(struct bpf_verifier_env *env,
3420 const struct bpf_reg_state *reg, int off,
3421 int size, bool strict_alignment_once)
3422 {
3423 bool strict = env->strict_alignment || strict_alignment_once;
3424 const char *pointer_desc = "";
3425
3426 switch (reg->type) {
3427 case PTR_TO_PACKET:
3428 case PTR_TO_PACKET_META:
3429 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3430 * right in front, treat it the very same way.
3431 */
3432 return check_pkt_ptr_alignment(env, reg, off, size, strict);
3433 case PTR_TO_FLOW_KEYS:
3434 pointer_desc = "flow keys ";
3435 break;
3436 case PTR_TO_MAP_VALUE:
3437 pointer_desc = "value ";
3438 break;
3439 case PTR_TO_CTX:
3440 pointer_desc = "context ";
3441 break;
3442 case PTR_TO_STACK:
3443 pointer_desc = "stack ";
3444 /* The stack spill tracking logic in check_stack_write_fixed_off()
3445 * and check_stack_read_fixed_off() relies on stack accesses being
3446 * aligned.
3447 */
3448 strict = true;
3449 break;
3450 case PTR_TO_SOCKET:
3451 pointer_desc = "sock ";
3452 break;
3453 case PTR_TO_SOCK_COMMON:
3454 pointer_desc = "sock_common ";
3455 break;
3456 case PTR_TO_TCP_SOCK:
3457 pointer_desc = "tcp_sock ";
3458 break;
3459 case PTR_TO_XDP_SOCK:
3460 pointer_desc = "xdp_sock ";
3461 break;
3462 default:
3463 break;
3464 }
3465 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3466 strict);
3467 }
3468
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)3469 static int update_stack_depth(struct bpf_verifier_env *env,
3470 const struct bpf_func_state *func,
3471 int off)
3472 {
3473 u16 stack = env->subprog_info[func->subprogno].stack_depth;
3474
3475 if (stack >= -off)
3476 return 0;
3477
3478 /* update known max for given subprogram */
3479 env->subprog_info[func->subprogno].stack_depth = -off;
3480 return 0;
3481 }
3482
3483 /* starting from main bpf function walk all instructions of the function
3484 * and recursively walk all callees that given function can call.
3485 * Ignore jump and exit insns.
3486 * Since recursion is prevented by check_cfg() this algorithm
3487 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3488 */
check_max_stack_depth(struct bpf_verifier_env * env)3489 static int check_max_stack_depth(struct bpf_verifier_env *env)
3490 {
3491 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3492 struct bpf_subprog_info *subprog = env->subprog_info;
3493 struct bpf_insn *insn = env->prog->insnsi;
3494 bool tail_call_reachable = false;
3495 int ret_insn[MAX_CALL_FRAMES];
3496 int ret_prog[MAX_CALL_FRAMES];
3497 int j;
3498
3499 process_func:
3500 /* protect against potential stack overflow that might happen when
3501 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3502 * depth for such case down to 256 so that the worst case scenario
3503 * would result in 8k stack size (32 which is tailcall limit * 256 =
3504 * 8k).
3505 *
3506 * To get the idea what might happen, see an example:
3507 * func1 -> sub rsp, 128
3508 * subfunc1 -> sub rsp, 256
3509 * tailcall1 -> add rsp, 256
3510 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3511 * subfunc2 -> sub rsp, 64
3512 * subfunc22 -> sub rsp, 128
3513 * tailcall2 -> add rsp, 128
3514 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3515 *
3516 * tailcall will unwind the current stack frame but it will not get rid
3517 * of caller's stack as shown on the example above.
3518 */
3519 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3520 verbose(env,
3521 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3522 depth);
3523 return -EACCES;
3524 }
3525 /* round up to 32-bytes, since this is granularity
3526 * of interpreter stack size
3527 */
3528 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3529 if (depth > MAX_BPF_STACK) {
3530 verbose(env, "combined stack size of %d calls is %d. Too large\n",
3531 frame + 1, depth);
3532 return -EACCES;
3533 }
3534 continue_func:
3535 subprog_end = subprog[idx + 1].start;
3536 for (; i < subprog_end; i++) {
3537 if (insn[i].code != (BPF_JMP | BPF_CALL))
3538 continue;
3539 if (insn[i].src_reg != BPF_PSEUDO_CALL)
3540 continue;
3541 /* remember insn and function to return to */
3542 ret_insn[frame] = i + 1;
3543 ret_prog[frame] = idx;
3544
3545 /* find the callee */
3546 i = i + insn[i].imm + 1;
3547 idx = find_subprog(env, i);
3548 if (idx < 0) {
3549 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3550 i);
3551 return -EFAULT;
3552 }
3553
3554 if (subprog[idx].has_tail_call)
3555 tail_call_reachable = true;
3556
3557 frame++;
3558 if (frame >= MAX_CALL_FRAMES) {
3559 verbose(env, "the call stack of %d frames is too deep !\n",
3560 frame);
3561 return -E2BIG;
3562 }
3563 goto process_func;
3564 }
3565 /* if tail call got detected across bpf2bpf calls then mark each of the
3566 * currently present subprog frames as tail call reachable subprogs;
3567 * this info will be utilized by JIT so that we will be preserving the
3568 * tail call counter throughout bpf2bpf calls combined with tailcalls
3569 */
3570 if (tail_call_reachable)
3571 for (j = 0; j < frame; j++)
3572 subprog[ret_prog[j]].tail_call_reachable = true;
3573 if (subprog[0].tail_call_reachable)
3574 env->prog->aux->tail_call_reachable = true;
3575
3576 /* end of for() loop means the last insn of the 'subprog'
3577 * was reached. Doesn't matter whether it was JA or EXIT
3578 */
3579 if (frame == 0)
3580 return 0;
3581 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
3582 frame--;
3583 i = ret_insn[frame];
3584 idx = ret_prog[frame];
3585 goto continue_func;
3586 }
3587
3588 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)3589 static int get_callee_stack_depth(struct bpf_verifier_env *env,
3590 const struct bpf_insn *insn, int idx)
3591 {
3592 int start = idx + insn->imm + 1, subprog;
3593
3594 subprog = find_subprog(env, start);
3595 if (subprog < 0) {
3596 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3597 start);
3598 return -EFAULT;
3599 }
3600 return env->subprog_info[subprog].stack_depth;
3601 }
3602 #endif
3603
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)3604 int check_ctx_reg(struct bpf_verifier_env *env,
3605 const struct bpf_reg_state *reg, int regno)
3606 {
3607 /* Access to ctx or passing it to a helper is only allowed in
3608 * its original, unmodified form.
3609 */
3610
3611 if (reg->off) {
3612 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3613 regno, reg->off);
3614 return -EACCES;
3615 }
3616
3617 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3618 char tn_buf[48];
3619
3620 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3621 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3622 return -EACCES;
3623 }
3624
3625 return 0;
3626 }
3627
__check_buffer_access(struct bpf_verifier_env * env,const char * buf_info,const struct bpf_reg_state * reg,int regno,int off,int size)3628 static int __check_buffer_access(struct bpf_verifier_env *env,
3629 const char *buf_info,
3630 const struct bpf_reg_state *reg,
3631 int regno, int off, int size)
3632 {
3633 if (off < 0) {
3634 verbose(env,
3635 "R%d invalid %s buffer access: off=%d, size=%d\n",
3636 regno, buf_info, off, size);
3637 return -EACCES;
3638 }
3639 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3640 char tn_buf[48];
3641
3642 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3643 verbose(env,
3644 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
3645 regno, off, tn_buf);
3646 return -EACCES;
3647 }
3648
3649 return 0;
3650 }
3651
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)3652 static int check_tp_buffer_access(struct bpf_verifier_env *env,
3653 const struct bpf_reg_state *reg,
3654 int regno, int off, int size)
3655 {
3656 int err;
3657
3658 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3659 if (err)
3660 return err;
3661
3662 if (off + size > env->prog->aux->max_tp_access)
3663 env->prog->aux->max_tp_access = off + size;
3664
3665 return 0;
3666 }
3667
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)3668 static int check_buffer_access(struct bpf_verifier_env *env,
3669 const struct bpf_reg_state *reg,
3670 int regno, int off, int size,
3671 bool zero_size_allowed,
3672 const char *buf_info,
3673 u32 *max_access)
3674 {
3675 int err;
3676
3677 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3678 if (err)
3679 return err;
3680
3681 if (off + size > *max_access)
3682 *max_access = off + size;
3683
3684 return 0;
3685 }
3686
3687 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
zext_32_to_64(struct bpf_reg_state * reg)3688 static void zext_32_to_64(struct bpf_reg_state *reg)
3689 {
3690 reg->var_off = tnum_subreg(reg->var_off);
3691 __reg_assign_32_into_64(reg);
3692 }
3693
3694 /* truncate register to smaller size (in bytes)
3695 * must be called with size < BPF_REG_SIZE
3696 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)3697 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3698 {
3699 u64 mask;
3700
3701 /* clear high bits in bit representation */
3702 reg->var_off = tnum_cast(reg->var_off, size);
3703
3704 /* fix arithmetic bounds */
3705 mask = ((u64)1 << (size * 8)) - 1;
3706 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3707 reg->umin_value &= mask;
3708 reg->umax_value &= mask;
3709 } else {
3710 reg->umin_value = 0;
3711 reg->umax_value = mask;
3712 }
3713 reg->smin_value = reg->umin_value;
3714 reg->smax_value = reg->umax_value;
3715
3716 /* If size is smaller than 32bit register the 32bit register
3717 * values are also truncated so we push 64-bit bounds into
3718 * 32-bit bounds. Above were truncated < 32-bits already.
3719 */
3720 if (size >= 4)
3721 return;
3722 __reg_combine_64_into_32(reg);
3723 }
3724
bpf_map_is_rdonly(const struct bpf_map * map)3725 static bool bpf_map_is_rdonly(const struct bpf_map *map)
3726 {
3727 /* A map is considered read-only if the following condition are true:
3728 *
3729 * 1) BPF program side cannot change any of the map content. The
3730 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
3731 * and was set at map creation time.
3732 * 2) The map value(s) have been initialized from user space by a
3733 * loader and then "frozen", such that no new map update/delete
3734 * operations from syscall side are possible for the rest of
3735 * the map's lifetime from that point onwards.
3736 * 3) Any parallel/pending map update/delete operations from syscall
3737 * side have been completed. Only after that point, it's safe to
3738 * assume that map value(s) are immutable.
3739 */
3740 return (map->map_flags & BPF_F_RDONLY_PROG) &&
3741 READ_ONCE(map->frozen) &&
3742 !bpf_map_write_active(map);
3743 }
3744
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)3745 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3746 {
3747 void *ptr;
3748 u64 addr;
3749 int err;
3750
3751 err = map->ops->map_direct_value_addr(map, &addr, off);
3752 if (err)
3753 return err;
3754 ptr = (void *)(long)addr + off;
3755
3756 switch (size) {
3757 case sizeof(u8):
3758 *val = (u64)*(u8 *)ptr;
3759 break;
3760 case sizeof(u16):
3761 *val = (u64)*(u16 *)ptr;
3762 break;
3763 case sizeof(u32):
3764 *val = (u64)*(u32 *)ptr;
3765 break;
3766 case sizeof(u64):
3767 *val = *(u64 *)ptr;
3768 break;
3769 default:
3770 return -EINVAL;
3771 }
3772 return 0;
3773 }
3774
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)3775 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3776 struct bpf_reg_state *regs,
3777 int regno, int off, int size,
3778 enum bpf_access_type atype,
3779 int value_regno)
3780 {
3781 struct bpf_reg_state *reg = regs + regno;
3782 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id);
3783 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3784 u32 btf_id;
3785 int ret;
3786
3787 if (off < 0) {
3788 verbose(env,
3789 "R%d is ptr_%s invalid negative access: off=%d\n",
3790 regno, tname, off);
3791 return -EACCES;
3792 }
3793 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3794 char tn_buf[48];
3795
3796 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3797 verbose(env,
3798 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3799 regno, tname, off, tn_buf);
3800 return -EACCES;
3801 }
3802
3803 if (env->ops->btf_struct_access) {
3804 ret = env->ops->btf_struct_access(&env->log, t, off, size,
3805 atype, &btf_id);
3806 } else {
3807 if (atype != BPF_READ) {
3808 verbose(env, "only read is supported\n");
3809 return -EACCES;
3810 }
3811
3812 ret = btf_struct_access(&env->log, t, off, size, atype,
3813 &btf_id);
3814 }
3815
3816 if (ret < 0)
3817 return ret;
3818
3819 if (atype == BPF_READ && value_regno >= 0)
3820 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3821
3822 return 0;
3823 }
3824
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)3825 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3826 struct bpf_reg_state *regs,
3827 int regno, int off, int size,
3828 enum bpf_access_type atype,
3829 int value_regno)
3830 {
3831 struct bpf_reg_state *reg = regs + regno;
3832 struct bpf_map *map = reg->map_ptr;
3833 const struct btf_type *t;
3834 const char *tname;
3835 u32 btf_id;
3836 int ret;
3837
3838 if (!btf_vmlinux) {
3839 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3840 return -ENOTSUPP;
3841 }
3842
3843 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3844 verbose(env, "map_ptr access not supported for map type %d\n",
3845 map->map_type);
3846 return -ENOTSUPP;
3847 }
3848
3849 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3850 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3851
3852 if (!env->allow_ptr_to_map_access) {
3853 verbose(env,
3854 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3855 tname);
3856 return -EPERM;
3857 }
3858
3859 if (off < 0) {
3860 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3861 regno, tname, off);
3862 return -EACCES;
3863 }
3864
3865 if (atype != BPF_READ) {
3866 verbose(env, "only read from %s is supported\n", tname);
3867 return -EACCES;
3868 }
3869
3870 ret = btf_struct_access(&env->log, t, off, size, atype, &btf_id);
3871 if (ret < 0)
3872 return ret;
3873
3874 if (value_regno >= 0)
3875 mark_btf_ld_reg(env, regs, value_regno, ret, btf_id);
3876
3877 return 0;
3878 }
3879
3880 /* Check that the stack access at the given offset is within bounds. The
3881 * maximum valid offset is -1.
3882 *
3883 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3884 * -state->allocated_stack for reads.
3885 */
check_stack_slot_within_bounds(int off,struct bpf_func_state * state,enum bpf_access_type t)3886 static int check_stack_slot_within_bounds(int off,
3887 struct bpf_func_state *state,
3888 enum bpf_access_type t)
3889 {
3890 int min_valid_off;
3891
3892 if (t == BPF_WRITE)
3893 min_valid_off = -MAX_BPF_STACK;
3894 else
3895 min_valid_off = -state->allocated_stack;
3896
3897 if (off < min_valid_off || off > -1)
3898 return -EACCES;
3899 return 0;
3900 }
3901
3902 /* Check that the stack access at 'regno + off' falls within the maximum stack
3903 * bounds.
3904 *
3905 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3906 */
check_stack_access_within_bounds(struct bpf_verifier_env * env,int regno,int off,int access_size,enum stack_access_src src,enum bpf_access_type type)3907 static int check_stack_access_within_bounds(
3908 struct bpf_verifier_env *env,
3909 int regno, int off, int access_size,
3910 enum stack_access_src src, enum bpf_access_type type)
3911 {
3912 struct bpf_reg_state *regs = cur_regs(env);
3913 struct bpf_reg_state *reg = regs + regno;
3914 struct bpf_func_state *state = func(env, reg);
3915 int min_off, max_off;
3916 int err;
3917 char *err_extra;
3918
3919 if (src == ACCESS_HELPER)
3920 /* We don't know if helpers are reading or writing (or both). */
3921 err_extra = " indirect access to";
3922 else if (type == BPF_READ)
3923 err_extra = " read from";
3924 else
3925 err_extra = " write to";
3926
3927 if (tnum_is_const(reg->var_off)) {
3928 min_off = reg->var_off.value + off;
3929 max_off = min_off + access_size;
3930 } else {
3931 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3932 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3933 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3934 err_extra, regno);
3935 return -EACCES;
3936 }
3937 min_off = reg->smin_value + off;
3938 max_off = reg->smax_value + off + access_size;
3939 }
3940
3941 err = check_stack_slot_within_bounds(min_off, state, type);
3942 if (!err && max_off > 0)
3943 err = -EINVAL; /* out of stack access into non-negative offsets */
3944
3945 if (err) {
3946 if (tnum_is_const(reg->var_off)) {
3947 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3948 err_extra, regno, off, access_size);
3949 } else {
3950 char tn_buf[48];
3951
3952 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3953 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3954 err_extra, regno, tn_buf, access_size);
3955 }
3956 }
3957 return err;
3958 }
3959
3960 /* check whether memory at (regno + off) is accessible for t = (read | write)
3961 * if t==write, value_regno is a register which value is stored into memory
3962 * if t==read, value_regno is a register which will receive the value from memory
3963 * if t==write && value_regno==-1, some unknown value is stored into memory
3964 * if t==read && value_regno==-1, don't care what we read from memory
3965 */
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)3966 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3967 int off, int bpf_size, enum bpf_access_type t,
3968 int value_regno, bool strict_alignment_once)
3969 {
3970 struct bpf_reg_state *regs = cur_regs(env);
3971 struct bpf_reg_state *reg = regs + regno;
3972 struct bpf_func_state *state;
3973 int size, err = 0;
3974
3975 size = bpf_size_to_bytes(bpf_size);
3976 if (size < 0)
3977 return size;
3978
3979 /* alignment checks will add in reg->off themselves */
3980 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
3981 if (err)
3982 return err;
3983
3984 /* for access checks, reg->off is just part of off */
3985 off += reg->off;
3986
3987 if (reg->type == PTR_TO_MAP_VALUE) {
3988 if (t == BPF_WRITE && value_regno >= 0 &&
3989 is_pointer_value(env, value_regno)) {
3990 verbose(env, "R%d leaks addr into map\n", value_regno);
3991 return -EACCES;
3992 }
3993 err = check_map_access_type(env, regno, off, size, t);
3994 if (err)
3995 return err;
3996 err = check_map_access(env, regno, off, size, false);
3997 if (!err && t == BPF_READ && value_regno >= 0) {
3998 struct bpf_map *map = reg->map_ptr;
3999
4000 /* if map is read-only, track its contents as scalars */
4001 if (tnum_is_const(reg->var_off) &&
4002 bpf_map_is_rdonly(map) &&
4003 map->ops->map_direct_value_addr) {
4004 int map_off = off + reg->var_off.value;
4005 u64 val = 0;
4006
4007 err = bpf_map_direct_read(map, map_off, size,
4008 &val);
4009 if (err)
4010 return err;
4011
4012 regs[value_regno].type = SCALAR_VALUE;
4013 __mark_reg_known(®s[value_regno], val);
4014 } else {
4015 mark_reg_unknown(env, regs, value_regno);
4016 }
4017 }
4018 } else if (reg->type == PTR_TO_MEM) {
4019 if (t == BPF_WRITE && value_regno >= 0 &&
4020 is_pointer_value(env, value_regno)) {
4021 verbose(env, "R%d leaks addr into mem\n", value_regno);
4022 return -EACCES;
4023 }
4024 err = check_mem_region_access(env, regno, off, size,
4025 reg->mem_size, false);
4026 if (!err && t == BPF_READ && value_regno >= 0)
4027 mark_reg_unknown(env, regs, value_regno);
4028 } else if (reg->type == PTR_TO_CTX) {
4029 enum bpf_reg_type reg_type = SCALAR_VALUE;
4030 u32 btf_id = 0;
4031
4032 if (t == BPF_WRITE && value_regno >= 0 &&
4033 is_pointer_value(env, value_regno)) {
4034 verbose(env, "R%d leaks addr into ctx\n", value_regno);
4035 return -EACCES;
4036 }
4037
4038 err = check_ctx_reg(env, reg, regno);
4039 if (err < 0)
4040 return err;
4041
4042 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf_id);
4043 if (err)
4044 verbose_linfo(env, insn_idx, "; ");
4045 if (!err && t == BPF_READ && value_regno >= 0) {
4046 /* ctx access returns either a scalar, or a
4047 * PTR_TO_PACKET[_META,_END]. In the latter
4048 * case, we know the offset is zero.
4049 */
4050 if (reg_type == SCALAR_VALUE) {
4051 mark_reg_unknown(env, regs, value_regno);
4052 } else {
4053 mark_reg_known_zero(env, regs,
4054 value_regno);
4055 if (reg_type_may_be_null(reg_type))
4056 regs[value_regno].id = ++env->id_gen;
4057 /* A load of ctx field could have different
4058 * actual load size with the one encoded in the
4059 * insn. When the dst is PTR, it is for sure not
4060 * a sub-register.
4061 */
4062 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
4063 if (reg_type == PTR_TO_BTF_ID ||
4064 reg_type == PTR_TO_BTF_ID_OR_NULL)
4065 regs[value_regno].btf_id = btf_id;
4066 }
4067 regs[value_regno].type = reg_type;
4068 }
4069
4070 } else if (reg->type == PTR_TO_STACK) {
4071 /* Basic bounds checks. */
4072 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
4073 if (err)
4074 return err;
4075
4076 state = func(env, reg);
4077 err = update_stack_depth(env, state, off);
4078 if (err)
4079 return err;
4080
4081 if (t == BPF_READ)
4082 err = check_stack_read(env, regno, off, size,
4083 value_regno);
4084 else
4085 err = check_stack_write(env, regno, off, size,
4086 value_regno, insn_idx);
4087 } else if (reg_is_pkt_pointer(reg)) {
4088 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
4089 verbose(env, "cannot write into packet\n");
4090 return -EACCES;
4091 }
4092 if (t == BPF_WRITE && value_regno >= 0 &&
4093 is_pointer_value(env, value_regno)) {
4094 verbose(env, "R%d leaks addr into packet\n",
4095 value_regno);
4096 return -EACCES;
4097 }
4098 err = check_packet_access(env, regno, off, size, false);
4099 if (!err && t == BPF_READ && value_regno >= 0)
4100 mark_reg_unknown(env, regs, value_regno);
4101 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4102 if (t == BPF_WRITE && value_regno >= 0 &&
4103 is_pointer_value(env, value_regno)) {
4104 verbose(env, "R%d leaks addr into flow keys\n",
4105 value_regno);
4106 return -EACCES;
4107 }
4108
4109 err = check_flow_keys_access(env, off, size);
4110 if (!err && t == BPF_READ && value_regno >= 0)
4111 mark_reg_unknown(env, regs, value_regno);
4112 } else if (type_is_sk_pointer(reg->type)) {
4113 if (t == BPF_WRITE) {
4114 verbose(env, "R%d cannot write into %s\n",
4115 regno, reg_type_str[reg->type]);
4116 return -EACCES;
4117 }
4118 err = check_sock_access(env, insn_idx, regno, off, size, t);
4119 if (!err && value_regno >= 0)
4120 mark_reg_unknown(env, regs, value_regno);
4121 } else if (reg->type == PTR_TO_TP_BUFFER) {
4122 err = check_tp_buffer_access(env, reg, regno, off, size);
4123 if (!err && t == BPF_READ && value_regno >= 0)
4124 mark_reg_unknown(env, regs, value_regno);
4125 } else if (reg->type == PTR_TO_BTF_ID) {
4126 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4127 value_regno);
4128 } else if (reg->type == CONST_PTR_TO_MAP) {
4129 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4130 value_regno);
4131 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4132 if (t == BPF_WRITE) {
4133 verbose(env, "R%d cannot write into %s\n",
4134 regno, reg_type_str[reg->type]);
4135 return -EACCES;
4136 }
4137 err = check_buffer_access(env, reg, regno, off, size, false,
4138 "rdonly",
4139 &env->prog->aux->max_rdonly_access);
4140 if (!err && value_regno >= 0)
4141 mark_reg_unknown(env, regs, value_regno);
4142 } else if (reg->type == PTR_TO_RDWR_BUF) {
4143 err = check_buffer_access(env, reg, regno, off, size, false,
4144 "rdwr",
4145 &env->prog->aux->max_rdwr_access);
4146 if (!err && t == BPF_READ && value_regno >= 0)
4147 mark_reg_unknown(env, regs, value_regno);
4148 } else {
4149 verbose(env, "R%d invalid mem access '%s'\n", regno,
4150 reg_type_str[reg->type]);
4151 return -EACCES;
4152 }
4153
4154 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
4155 regs[value_regno].type == SCALAR_VALUE) {
4156 /* b/h/w load zero-extends, mark upper bits as known 0 */
4157 coerce_reg_to_size(®s[value_regno], size);
4158 }
4159 return err;
4160 }
4161
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)4162 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
4163 {
4164 int err;
4165
4166 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
4167 insn->imm != 0) {
4168 verbose(env, "BPF_XADD uses reserved fields\n");
4169 return -EINVAL;
4170 }
4171
4172 /* check src1 operand */
4173 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4174 if (err)
4175 return err;
4176
4177 /* check src2 operand */
4178 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4179 if (err)
4180 return err;
4181
4182 if (is_pointer_value(env, insn->src_reg)) {
4183 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
4184 return -EACCES;
4185 }
4186
4187 if (is_ctx_reg(env, insn->dst_reg) ||
4188 is_pkt_reg(env, insn->dst_reg) ||
4189 is_flow_key_reg(env, insn->dst_reg) ||
4190 is_sk_reg(env, insn->dst_reg)) {
4191 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
4192 insn->dst_reg,
4193 reg_type_str[reg_state(env, insn->dst_reg)->type]);
4194 return -EACCES;
4195 }
4196
4197 /* check whether atomic_add can read the memory */
4198 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4199 BPF_SIZE(insn->code), BPF_READ, -1, true);
4200 if (err)
4201 return err;
4202
4203 /* check whether atomic_add can write into the same memory */
4204 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4205 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4206 }
4207
4208 /* When register 'regno' is used to read the stack (either directly or through
4209 * a helper function) make sure that it's within stack boundary and, depending
4210 * on the access type, that all elements of the stack are initialized.
4211 *
4212 * 'off' includes 'regno->off', but not its dynamic part (if any).
4213 *
4214 * All registers that have been spilled on the stack in the slots within the
4215 * read offsets are marked as read.
4216 */
check_stack_range_initialized(struct bpf_verifier_env * env,int regno,int off,int access_size,bool zero_size_allowed,enum stack_access_src type,struct bpf_call_arg_meta * meta)4217 static int check_stack_range_initialized(
4218 struct bpf_verifier_env *env, int regno, int off,
4219 int access_size, bool zero_size_allowed,
4220 enum stack_access_src type, struct bpf_call_arg_meta *meta)
4221 {
4222 struct bpf_reg_state *reg = reg_state(env, regno);
4223 struct bpf_func_state *state = func(env, reg);
4224 int err, min_off, max_off, i, j, slot, spi;
4225 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4226 enum bpf_access_type bounds_check_type;
4227 /* Some accesses can write anything into the stack, others are
4228 * read-only.
4229 */
4230 bool clobber = false;
4231
4232 if (access_size == 0 && !zero_size_allowed) {
4233 verbose(env, "invalid zero-sized read\n");
4234 return -EACCES;
4235 }
4236
4237 if (type == ACCESS_HELPER) {
4238 /* The bounds checks for writes are more permissive than for
4239 * reads. However, if raw_mode is not set, we'll do extra
4240 * checks below.
4241 */
4242 bounds_check_type = BPF_WRITE;
4243 clobber = true;
4244 } else {
4245 bounds_check_type = BPF_READ;
4246 }
4247 err = check_stack_access_within_bounds(env, regno, off, access_size,
4248 type, bounds_check_type);
4249 if (err)
4250 return err;
4251
4252
4253 if (tnum_is_const(reg->var_off)) {
4254 min_off = max_off = reg->var_off.value + off;
4255 } else {
4256 /* Variable offset is prohibited for unprivileged mode for
4257 * simplicity since it requires corresponding support in
4258 * Spectre masking for stack ALU.
4259 * See also retrieve_ptr_limit().
4260 */
4261 if (!env->bypass_spec_v1) {
4262 char tn_buf[48];
4263
4264 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4265 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4266 regno, err_extra, tn_buf);
4267 return -EACCES;
4268 }
4269 /* Only initialized buffer on stack is allowed to be accessed
4270 * with variable offset. With uninitialized buffer it's hard to
4271 * guarantee that whole memory is marked as initialized on
4272 * helper return since specific bounds are unknown what may
4273 * cause uninitialized stack leaking.
4274 */
4275 if (meta && meta->raw_mode)
4276 meta = NULL;
4277
4278 min_off = reg->smin_value + off;
4279 max_off = reg->smax_value + off;
4280 }
4281
4282 if (meta && meta->raw_mode) {
4283 meta->access_size = access_size;
4284 meta->regno = regno;
4285 return 0;
4286 }
4287
4288 for (i = min_off; i < max_off + access_size; i++) {
4289 u8 *stype;
4290
4291 slot = -i - 1;
4292 spi = slot / BPF_REG_SIZE;
4293 if (state->allocated_stack <= slot)
4294 goto err;
4295 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4296 if (*stype == STACK_MISC)
4297 goto mark;
4298 if (*stype == STACK_ZERO) {
4299 if (clobber) {
4300 /* helper can write anything into the stack */
4301 *stype = STACK_MISC;
4302 }
4303 goto mark;
4304 }
4305
4306 if (is_spilled_reg(&state->stack[spi]) &&
4307 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4308 goto mark;
4309
4310 if (is_spilled_reg(&state->stack[spi]) &&
4311 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4312 env->allow_ptr_leaks)) {
4313 if (clobber) {
4314 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4315 for (j = 0; j < BPF_REG_SIZE; j++)
4316 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
4317 }
4318 goto mark;
4319 }
4320
4321 err:
4322 if (tnum_is_const(reg->var_off)) {
4323 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4324 err_extra, regno, min_off, i - min_off, access_size);
4325 } else {
4326 char tn_buf[48];
4327
4328 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4329 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4330 err_extra, regno, tn_buf, i - min_off, access_size);
4331 }
4332 return -EACCES;
4333 mark:
4334 /* reading any byte out of 8-byte 'spill_slot' will cause
4335 * the whole slot to be marked as 'read'
4336 */
4337 mark_reg_read(env, &state->stack[spi].spilled_ptr,
4338 state->stack[spi].spilled_ptr.parent,
4339 REG_LIVE_READ64);
4340 }
4341 return update_stack_depth(env, state, min_off);
4342 }
4343
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)4344 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4345 int access_size, bool zero_size_allowed,
4346 struct bpf_call_arg_meta *meta)
4347 {
4348 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4349
4350 switch (reg->type) {
4351 case PTR_TO_PACKET:
4352 case PTR_TO_PACKET_META:
4353 return check_packet_access(env, regno, reg->off, access_size,
4354 zero_size_allowed);
4355 case PTR_TO_MAP_VALUE:
4356 if (check_map_access_type(env, regno, reg->off, access_size,
4357 meta && meta->raw_mode ? BPF_WRITE :
4358 BPF_READ))
4359 return -EACCES;
4360 return check_map_access(env, regno, reg->off, access_size,
4361 zero_size_allowed);
4362 case PTR_TO_MEM:
4363 return check_mem_region_access(env, regno, reg->off,
4364 access_size, reg->mem_size,
4365 zero_size_allowed);
4366 case PTR_TO_RDONLY_BUF:
4367 if (meta && meta->raw_mode)
4368 return -EACCES;
4369 return check_buffer_access(env, reg, regno, reg->off,
4370 access_size, zero_size_allowed,
4371 "rdonly",
4372 &env->prog->aux->max_rdonly_access);
4373 case PTR_TO_RDWR_BUF:
4374 return check_buffer_access(env, reg, regno, reg->off,
4375 access_size, zero_size_allowed,
4376 "rdwr",
4377 &env->prog->aux->max_rdwr_access);
4378 case PTR_TO_STACK:
4379 return check_stack_range_initialized(
4380 env,
4381 regno, reg->off, access_size,
4382 zero_size_allowed, ACCESS_HELPER, meta);
4383 default: /* scalar_value or invalid ptr */
4384 /* Allow zero-byte read from NULL, regardless of pointer type */
4385 if (zero_size_allowed && access_size == 0 &&
4386 register_is_null(reg))
4387 return 0;
4388
4389 verbose(env, "R%d type=%s expected=%s\n", regno,
4390 reg_type_str[reg->type],
4391 reg_type_str[PTR_TO_STACK]);
4392 return -EACCES;
4393 }
4394 }
4395
4396 /* Implementation details:
4397 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4398 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4399 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4400 * value_or_null->value transition, since the verifier only cares about
4401 * the range of access to valid map value pointer and doesn't care about actual
4402 * address of the map element.
4403 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4404 * reg->id > 0 after value_or_null->value transition. By doing so
4405 * two bpf_map_lookups will be considered two different pointers that
4406 * point to different bpf_spin_locks.
4407 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4408 * dead-locks.
4409 * Since only one bpf_spin_lock is allowed the checks are simpler than
4410 * reg_is_refcounted() logic. The verifier needs to remember only
4411 * one spin_lock instead of array of acquired_refs.
4412 * cur_state->active_spin_lock remembers which map value element got locked
4413 * and clears it after bpf_spin_unlock.
4414 */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)4415 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4416 bool is_lock)
4417 {
4418 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4419 struct bpf_verifier_state *cur = env->cur_state;
4420 bool is_const = tnum_is_const(reg->var_off);
4421 struct bpf_map *map = reg->map_ptr;
4422 u64 val = reg->var_off.value;
4423
4424 if (!is_const) {
4425 verbose(env,
4426 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4427 regno);
4428 return -EINVAL;
4429 }
4430 if (!map->btf) {
4431 verbose(env,
4432 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4433 map->name);
4434 return -EINVAL;
4435 }
4436 if (!map_value_has_spin_lock(map)) {
4437 if (map->spin_lock_off == -E2BIG)
4438 verbose(env,
4439 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4440 map->name);
4441 else if (map->spin_lock_off == -ENOENT)
4442 verbose(env,
4443 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4444 map->name);
4445 else
4446 verbose(env,
4447 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4448 map->name);
4449 return -EINVAL;
4450 }
4451 if (map->spin_lock_off != val + reg->off) {
4452 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4453 val + reg->off);
4454 return -EINVAL;
4455 }
4456 if (is_lock) {
4457 if (cur->active_spin_lock) {
4458 verbose(env,
4459 "Locking two bpf_spin_locks are not allowed\n");
4460 return -EINVAL;
4461 }
4462 cur->active_spin_lock = reg->id;
4463 } else {
4464 if (!cur->active_spin_lock) {
4465 verbose(env, "bpf_spin_unlock without taking a lock\n");
4466 return -EINVAL;
4467 }
4468 if (cur->active_spin_lock != reg->id) {
4469 verbose(env, "bpf_spin_unlock of different lock\n");
4470 return -EINVAL;
4471 }
4472 cur->active_spin_lock = 0;
4473 }
4474 return 0;
4475 }
4476
arg_type_is_mem_ptr(enum bpf_arg_type type)4477 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4478 {
4479 return type == ARG_PTR_TO_MEM ||
4480 type == ARG_PTR_TO_MEM_OR_NULL ||
4481 type == ARG_PTR_TO_UNINIT_MEM;
4482 }
4483
arg_type_is_mem_size(enum bpf_arg_type type)4484 static bool arg_type_is_mem_size(enum bpf_arg_type type)
4485 {
4486 return type == ARG_CONST_SIZE ||
4487 type == ARG_CONST_SIZE_OR_ZERO;
4488 }
4489
arg_type_is_alloc_size(enum bpf_arg_type type)4490 static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4491 {
4492 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4493 }
4494
arg_type_is_int_ptr(enum bpf_arg_type type)4495 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4496 {
4497 return type == ARG_PTR_TO_INT ||
4498 type == ARG_PTR_TO_LONG;
4499 }
4500
int_ptr_type_to_size(enum bpf_arg_type type)4501 static int int_ptr_type_to_size(enum bpf_arg_type type)
4502 {
4503 if (type == ARG_PTR_TO_INT)
4504 return sizeof(u32);
4505 else if (type == ARG_PTR_TO_LONG)
4506 return sizeof(u64);
4507
4508 return -EINVAL;
4509 }
4510
resolve_map_arg_type(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_arg_type * arg_type)4511 static int resolve_map_arg_type(struct bpf_verifier_env *env,
4512 const struct bpf_call_arg_meta *meta,
4513 enum bpf_arg_type *arg_type)
4514 {
4515 if (!meta->map_ptr) {
4516 /* kernel subsystem misconfigured verifier */
4517 verbose(env, "invalid map_ptr to access map->type\n");
4518 return -EACCES;
4519 }
4520
4521 switch (meta->map_ptr->map_type) {
4522 case BPF_MAP_TYPE_SOCKMAP:
4523 case BPF_MAP_TYPE_SOCKHASH:
4524 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
4525 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
4526 } else {
4527 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4528 return -EINVAL;
4529 }
4530 break;
4531
4532 default:
4533 break;
4534 }
4535 return 0;
4536 }
4537
4538 struct bpf_reg_types {
4539 const enum bpf_reg_type types[10];
4540 u32 *btf_id;
4541 };
4542
4543 static const struct bpf_reg_types map_key_value_types = {
4544 .types = {
4545 PTR_TO_STACK,
4546 PTR_TO_PACKET,
4547 PTR_TO_PACKET_META,
4548 PTR_TO_MAP_VALUE,
4549 },
4550 };
4551
4552 static const struct bpf_reg_types sock_types = {
4553 .types = {
4554 PTR_TO_SOCK_COMMON,
4555 PTR_TO_SOCKET,
4556 PTR_TO_TCP_SOCK,
4557 PTR_TO_XDP_SOCK,
4558 },
4559 };
4560
4561 #ifdef CONFIG_NET
4562 static const struct bpf_reg_types btf_id_sock_common_types = {
4563 .types = {
4564 PTR_TO_SOCK_COMMON,
4565 PTR_TO_SOCKET,
4566 PTR_TO_TCP_SOCK,
4567 PTR_TO_XDP_SOCK,
4568 PTR_TO_BTF_ID,
4569 },
4570 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4571 };
4572 #endif
4573
4574 static const struct bpf_reg_types mem_types = {
4575 .types = {
4576 PTR_TO_STACK,
4577 PTR_TO_PACKET,
4578 PTR_TO_PACKET_META,
4579 PTR_TO_MAP_VALUE,
4580 PTR_TO_MEM,
4581 PTR_TO_RDONLY_BUF,
4582 PTR_TO_RDWR_BUF,
4583 },
4584 };
4585
4586 static const struct bpf_reg_types int_ptr_types = {
4587 .types = {
4588 PTR_TO_STACK,
4589 PTR_TO_PACKET,
4590 PTR_TO_PACKET_META,
4591 PTR_TO_MAP_VALUE,
4592 },
4593 };
4594
4595 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4596 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4597 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4598 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4599 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4600 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4601 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
4602 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
4603
4604 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
4605 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4606 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4607 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4608 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4609 [ARG_CONST_SIZE] = &scalar_types,
4610 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4611 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4612 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4613 [ARG_PTR_TO_CTX] = &context_types,
4614 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4615 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
4616 #ifdef CONFIG_NET
4617 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
4618 #endif
4619 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4620 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4621 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4622 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4623 [ARG_PTR_TO_MEM] = &mem_types,
4624 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4625 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4626 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4627 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4628 [ARG_PTR_TO_INT] = &int_ptr_types,
4629 [ARG_PTR_TO_LONG] = &int_ptr_types,
4630 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
4631 };
4632
check_reg_type(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,const u32 * arg_btf_id)4633 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
4634 enum bpf_arg_type arg_type,
4635 const u32 *arg_btf_id)
4636 {
4637 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4638 enum bpf_reg_type expected, type = reg->type;
4639 const struct bpf_reg_types *compatible;
4640 int i, j;
4641
4642 compatible = compatible_reg_types[arg_type];
4643 if (!compatible) {
4644 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4645 return -EFAULT;
4646 }
4647
4648 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4649 expected = compatible->types[i];
4650 if (expected == NOT_INIT)
4651 break;
4652
4653 if (type == expected)
4654 goto found;
4655 }
4656
4657 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4658 for (j = 0; j + 1 < i; j++)
4659 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4660 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4661 return -EACCES;
4662
4663 found:
4664 if (type == PTR_TO_BTF_ID) {
4665 if (!arg_btf_id) {
4666 if (!compatible->btf_id) {
4667 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4668 return -EFAULT;
4669 }
4670 arg_btf_id = compatible->btf_id;
4671 }
4672
4673 if (!btf_struct_ids_match(&env->log, reg->off, reg->btf_id,
4674 *arg_btf_id)) {
4675 verbose(env, "R%d is of type %s but %s is expected\n",
4676 regno, kernel_type_name(reg->btf_id),
4677 kernel_type_name(*arg_btf_id));
4678 return -EACCES;
4679 }
4680
4681 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4682 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4683 regno);
4684 return -EACCES;
4685 }
4686 }
4687
4688 return 0;
4689 }
4690
check_func_arg(struct bpf_verifier_env * env,u32 arg,struct bpf_call_arg_meta * meta,const struct bpf_func_proto * fn)4691 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4692 struct bpf_call_arg_meta *meta,
4693 const struct bpf_func_proto *fn)
4694 {
4695 u32 regno = BPF_REG_1 + arg;
4696 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
4697 enum bpf_arg_type arg_type = fn->arg_type[arg];
4698 enum bpf_reg_type type = reg->type;
4699 int err = 0;
4700
4701 if (arg_type == ARG_DONTCARE)
4702 return 0;
4703
4704 err = check_reg_arg(env, regno, SRC_OP);
4705 if (err)
4706 return err;
4707
4708 if (arg_type == ARG_ANYTHING) {
4709 if (is_pointer_value(env, regno)) {
4710 verbose(env, "R%d leaks addr into helper function\n",
4711 regno);
4712 return -EACCES;
4713 }
4714 return 0;
4715 }
4716
4717 if (type_is_pkt_pointer(type) &&
4718 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
4719 verbose(env, "helper access to the packet is not allowed\n");
4720 return -EACCES;
4721 }
4722
4723 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4724 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4725 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4726 err = resolve_map_arg_type(env, meta, &arg_type);
4727 if (err)
4728 return err;
4729 }
4730
4731 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4732 /* A NULL register has a SCALAR_VALUE type, so skip
4733 * type checking.
4734 */
4735 goto skip_type_check;
4736
4737 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
4738 if (err)
4739 return err;
4740
4741 if (type == PTR_TO_CTX) {
4742 err = check_ctx_reg(env, reg, regno);
4743 if (err < 0)
4744 return err;
4745 }
4746
4747 skip_type_check:
4748 if (reg->ref_obj_id) {
4749 if (meta->ref_obj_id) {
4750 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4751 regno, reg->ref_obj_id,
4752 meta->ref_obj_id);
4753 return -EFAULT;
4754 }
4755 meta->ref_obj_id = reg->ref_obj_id;
4756 }
4757
4758 if (arg_type == ARG_CONST_MAP_PTR) {
4759 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
4760 meta->map_ptr = reg->map_ptr;
4761 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4762 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4763 * check that [key, key + map->key_size) are within
4764 * stack limits and initialized
4765 */
4766 if (!meta->map_ptr) {
4767 /* in function declaration map_ptr must come before
4768 * map_key, so that it's verified and known before
4769 * we have to check map_key here. Otherwise it means
4770 * that kernel subsystem misconfigured verifier
4771 */
4772 verbose(env, "invalid map_ptr to access map->key\n");
4773 return -EACCES;
4774 }
4775 err = check_helper_mem_access(env, regno,
4776 meta->map_ptr->key_size, false,
4777 NULL);
4778 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4779 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4780 !register_is_null(reg)) ||
4781 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
4782 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4783 * check [value, value + map->value_size) validity
4784 */
4785 if (!meta->map_ptr) {
4786 /* kernel subsystem misconfigured verifier */
4787 verbose(env, "invalid map_ptr to access map->value\n");
4788 return -EACCES;
4789 }
4790 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
4791 err = check_helper_mem_access(env, regno,
4792 meta->map_ptr->value_size, false,
4793 meta);
4794 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4795 if (!reg->btf_id) {
4796 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4797 return -EACCES;
4798 }
4799 meta->ret_btf_id = reg->btf_id;
4800 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4801 if (meta->func_id == BPF_FUNC_spin_lock) {
4802 if (process_spin_lock(env, regno, true))
4803 return -EACCES;
4804 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4805 if (process_spin_lock(env, regno, false))
4806 return -EACCES;
4807 } else {
4808 verbose(env, "verifier internal error\n");
4809 return -EFAULT;
4810 }
4811 } else if (arg_type_is_mem_ptr(arg_type)) {
4812 /* The access to this pointer is only checked when we hit the
4813 * next is_mem_size argument below.
4814 */
4815 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
4816 } else if (arg_type_is_mem_size(arg_type)) {
4817 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
4818
4819 /* This is used to refine r0 return value bounds for helpers
4820 * that enforce this value as an upper bound on return values.
4821 * See do_refine_retval_range() for helpers that can refine
4822 * the return value. C type of helper is u32 so we pull register
4823 * bound from umax_value however, if negative verifier errors
4824 * out. Only upper bounds can be learned because retval is an
4825 * int type and negative retvals are allowed.
4826 */
4827 meta->msize_max_value = reg->umax_value;
4828
4829 /* The register is SCALAR_VALUE; the access check
4830 * happens using its boundaries.
4831 */
4832 if (!tnum_is_const(reg->var_off))
4833 /* For unprivileged variable accesses, disable raw
4834 * mode so that the program is required to
4835 * initialize all the memory that the helper could
4836 * just partially fill up.
4837 */
4838 meta = NULL;
4839
4840 if (reg->smin_value < 0) {
4841 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
4842 regno);
4843 return -EACCES;
4844 }
4845
4846 if (reg->umin_value == 0) {
4847 err = check_helper_mem_access(env, regno - 1, 0,
4848 zero_size_allowed,
4849 meta);
4850 if (err)
4851 return err;
4852 }
4853
4854 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
4855 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
4856 regno);
4857 return -EACCES;
4858 }
4859 err = check_helper_mem_access(env, regno - 1,
4860 reg->umax_value,
4861 zero_size_allowed, meta);
4862 if (!err)
4863 err = mark_chain_precision(env, regno);
4864 } else if (arg_type_is_alloc_size(arg_type)) {
4865 if (!tnum_is_const(reg->var_off)) {
4866 verbose(env, "R%d unbounded size, use 'var &= const' or 'if (var < const)'\n",
4867 regno);
4868 return -EACCES;
4869 }
4870 meta->mem_size = reg->var_off.value;
4871 } else if (arg_type_is_int_ptr(arg_type)) {
4872 int size = int_ptr_type_to_size(arg_type);
4873
4874 err = check_helper_mem_access(env, regno, size, false, meta);
4875 if (err)
4876 return err;
4877 err = check_ptr_alignment(env, reg, 0, size, true);
4878 }
4879
4880 return err;
4881 }
4882
may_update_sockmap(struct bpf_verifier_env * env,int func_id)4883 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4884 {
4885 enum bpf_attach_type eatype = env->prog->expected_attach_type;
4886 enum bpf_prog_type type = resolve_prog_type(env->prog);
4887
4888 if (func_id != BPF_FUNC_map_update_elem)
4889 return false;
4890
4891 /* It's not possible to get access to a locked struct sock in these
4892 * contexts, so updating is safe.
4893 */
4894 switch (type) {
4895 case BPF_PROG_TYPE_TRACING:
4896 if (eatype == BPF_TRACE_ITER)
4897 return true;
4898 break;
4899 case BPF_PROG_TYPE_SOCKET_FILTER:
4900 case BPF_PROG_TYPE_SCHED_CLS:
4901 case BPF_PROG_TYPE_SCHED_ACT:
4902 case BPF_PROG_TYPE_XDP:
4903 case BPF_PROG_TYPE_SK_REUSEPORT:
4904 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4905 case BPF_PROG_TYPE_SK_LOOKUP:
4906 return true;
4907 default:
4908 break;
4909 }
4910
4911 verbose(env, "cannot update sockmap in this context\n");
4912 return false;
4913 }
4914
allow_tail_call_in_subprogs(struct bpf_verifier_env * env)4915 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4916 {
4917 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4918 }
4919
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)4920 static int check_map_func_compatibility(struct bpf_verifier_env *env,
4921 struct bpf_map *map, int func_id)
4922 {
4923 if (!map)
4924 return 0;
4925
4926 /* We need a two way check, first is from map perspective ... */
4927 switch (map->map_type) {
4928 case BPF_MAP_TYPE_PROG_ARRAY:
4929 if (func_id != BPF_FUNC_tail_call)
4930 goto error;
4931 break;
4932 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4933 if (func_id != BPF_FUNC_perf_event_read &&
4934 func_id != BPF_FUNC_perf_event_output &&
4935 func_id != BPF_FUNC_skb_output &&
4936 func_id != BPF_FUNC_perf_event_read_value &&
4937 func_id != BPF_FUNC_xdp_output)
4938 goto error;
4939 break;
4940 case BPF_MAP_TYPE_RINGBUF:
4941 if (func_id != BPF_FUNC_ringbuf_output &&
4942 func_id != BPF_FUNC_ringbuf_reserve &&
4943 func_id != BPF_FUNC_ringbuf_query)
4944 goto error;
4945 break;
4946 case BPF_MAP_TYPE_STACK_TRACE:
4947 if (func_id != BPF_FUNC_get_stackid)
4948 goto error;
4949 break;
4950 case BPF_MAP_TYPE_CGROUP_ARRAY:
4951 if (func_id != BPF_FUNC_skb_under_cgroup &&
4952 func_id != BPF_FUNC_current_task_under_cgroup)
4953 goto error;
4954 break;
4955 case BPF_MAP_TYPE_CGROUP_STORAGE:
4956 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4957 if (func_id != BPF_FUNC_get_local_storage)
4958 goto error;
4959 break;
4960 case BPF_MAP_TYPE_DEVMAP:
4961 case BPF_MAP_TYPE_DEVMAP_HASH:
4962 if (func_id != BPF_FUNC_redirect_map &&
4963 func_id != BPF_FUNC_map_lookup_elem)
4964 goto error;
4965 break;
4966 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4967 * appear.
4968 */
4969 case BPF_MAP_TYPE_CPUMAP:
4970 if (func_id != BPF_FUNC_redirect_map)
4971 goto error;
4972 break;
4973 case BPF_MAP_TYPE_XSKMAP:
4974 if (func_id != BPF_FUNC_redirect_map &&
4975 func_id != BPF_FUNC_map_lookup_elem)
4976 goto error;
4977 break;
4978 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
4979 case BPF_MAP_TYPE_HASH_OF_MAPS:
4980 if (func_id != BPF_FUNC_map_lookup_elem)
4981 goto error;
4982 break;
4983 case BPF_MAP_TYPE_SOCKMAP:
4984 if (func_id != BPF_FUNC_sk_redirect_map &&
4985 func_id != BPF_FUNC_sock_map_update &&
4986 func_id != BPF_FUNC_map_delete_elem &&
4987 func_id != BPF_FUNC_msg_redirect_map &&
4988 func_id != BPF_FUNC_sk_select_reuseport &&
4989 func_id != BPF_FUNC_map_lookup_elem &&
4990 !may_update_sockmap(env, func_id))
4991 goto error;
4992 break;
4993 case BPF_MAP_TYPE_SOCKHASH:
4994 if (func_id != BPF_FUNC_sk_redirect_hash &&
4995 func_id != BPF_FUNC_sock_hash_update &&
4996 func_id != BPF_FUNC_map_delete_elem &&
4997 func_id != BPF_FUNC_msg_redirect_hash &&
4998 func_id != BPF_FUNC_sk_select_reuseport &&
4999 func_id != BPF_FUNC_map_lookup_elem &&
5000 !may_update_sockmap(env, func_id))
5001 goto error;
5002 break;
5003 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5004 if (func_id != BPF_FUNC_sk_select_reuseport)
5005 goto error;
5006 break;
5007 case BPF_MAP_TYPE_QUEUE:
5008 case BPF_MAP_TYPE_STACK:
5009 if (func_id != BPF_FUNC_map_peek_elem &&
5010 func_id != BPF_FUNC_map_pop_elem &&
5011 func_id != BPF_FUNC_map_push_elem)
5012 goto error;
5013 break;
5014 case BPF_MAP_TYPE_SK_STORAGE:
5015 if (func_id != BPF_FUNC_sk_storage_get &&
5016 func_id != BPF_FUNC_sk_storage_delete)
5017 goto error;
5018 break;
5019 case BPF_MAP_TYPE_INODE_STORAGE:
5020 if (func_id != BPF_FUNC_inode_storage_get &&
5021 func_id != BPF_FUNC_inode_storage_delete)
5022 goto error;
5023 break;
5024 default:
5025 break;
5026 }
5027
5028 /* ... and second from the function itself. */
5029 switch (func_id) {
5030 case BPF_FUNC_tail_call:
5031 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5032 goto error;
5033 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5034 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
5035 return -EINVAL;
5036 }
5037 break;
5038 case BPF_FUNC_perf_event_read:
5039 case BPF_FUNC_perf_event_output:
5040 case BPF_FUNC_perf_event_read_value:
5041 case BPF_FUNC_skb_output:
5042 case BPF_FUNC_xdp_output:
5043 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5044 goto error;
5045 break;
5046 case BPF_FUNC_ringbuf_output:
5047 case BPF_FUNC_ringbuf_reserve:
5048 case BPF_FUNC_ringbuf_query:
5049 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5050 goto error;
5051 break;
5052 case BPF_FUNC_get_stackid:
5053 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5054 goto error;
5055 break;
5056 case BPF_FUNC_current_task_under_cgroup:
5057 case BPF_FUNC_skb_under_cgroup:
5058 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5059 goto error;
5060 break;
5061 case BPF_FUNC_redirect_map:
5062 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
5063 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
5064 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5065 map->map_type != BPF_MAP_TYPE_XSKMAP)
5066 goto error;
5067 break;
5068 case BPF_FUNC_sk_redirect_map:
5069 case BPF_FUNC_msg_redirect_map:
5070 case BPF_FUNC_sock_map_update:
5071 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5072 goto error;
5073 break;
5074 case BPF_FUNC_sk_redirect_hash:
5075 case BPF_FUNC_msg_redirect_hash:
5076 case BPF_FUNC_sock_hash_update:
5077 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
5078 goto error;
5079 break;
5080 case BPF_FUNC_get_local_storage:
5081 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5082 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
5083 goto error;
5084 break;
5085 case BPF_FUNC_sk_select_reuseport:
5086 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5087 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5088 map->map_type != BPF_MAP_TYPE_SOCKHASH)
5089 goto error;
5090 break;
5091 case BPF_FUNC_map_peek_elem:
5092 case BPF_FUNC_map_pop_elem:
5093 case BPF_FUNC_map_push_elem:
5094 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5095 map->map_type != BPF_MAP_TYPE_STACK)
5096 goto error;
5097 break;
5098 case BPF_FUNC_sk_storage_get:
5099 case BPF_FUNC_sk_storage_delete:
5100 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5101 goto error;
5102 break;
5103 case BPF_FUNC_inode_storage_get:
5104 case BPF_FUNC_inode_storage_delete:
5105 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5106 goto error;
5107 break;
5108 default:
5109 break;
5110 }
5111
5112 return 0;
5113 error:
5114 verbose(env, "cannot pass map_type %d into func %s#%d\n",
5115 map->map_type, func_id_name(func_id), func_id);
5116 return -EINVAL;
5117 }
5118
check_raw_mode_ok(const struct bpf_func_proto * fn)5119 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
5120 {
5121 int count = 0;
5122
5123 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
5124 count++;
5125 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
5126 count++;
5127 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
5128 count++;
5129 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
5130 count++;
5131 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
5132 count++;
5133
5134 /* We only support one arg being in raw mode at the moment,
5135 * which is sufficient for the helper functions we have
5136 * right now.
5137 */
5138 return count <= 1;
5139 }
5140
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)5141 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5142 enum bpf_arg_type arg_next)
5143 {
5144 return (arg_type_is_mem_ptr(arg_curr) &&
5145 !arg_type_is_mem_size(arg_next)) ||
5146 (!arg_type_is_mem_ptr(arg_curr) &&
5147 arg_type_is_mem_size(arg_next));
5148 }
5149
check_arg_pair_ok(const struct bpf_func_proto * fn)5150 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5151 {
5152 /* bpf_xxx(..., buf, len) call will access 'len'
5153 * bytes from memory 'buf'. Both arg types need
5154 * to be paired, so make sure there's no buggy
5155 * helper function specification.
5156 */
5157 if (arg_type_is_mem_size(fn->arg1_type) ||
5158 arg_type_is_mem_ptr(fn->arg5_type) ||
5159 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5160 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5161 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5162 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5163 return false;
5164
5165 return true;
5166 }
5167
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)5168 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
5169 {
5170 int count = 0;
5171
5172 if (arg_type_may_be_refcounted(fn->arg1_type))
5173 count++;
5174 if (arg_type_may_be_refcounted(fn->arg2_type))
5175 count++;
5176 if (arg_type_may_be_refcounted(fn->arg3_type))
5177 count++;
5178 if (arg_type_may_be_refcounted(fn->arg4_type))
5179 count++;
5180 if (arg_type_may_be_refcounted(fn->arg5_type))
5181 count++;
5182
5183 /* A reference acquiring function cannot acquire
5184 * another refcounted ptr.
5185 */
5186 if (may_be_acquire_function(func_id) && count)
5187 return false;
5188
5189 /* We only support one arg being unreferenced at the moment,
5190 * which is sufficient for the helper functions we have right now.
5191 */
5192 return count <= 1;
5193 }
5194
check_btf_id_ok(const struct bpf_func_proto * fn)5195 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5196 {
5197 int i;
5198
5199 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
5200 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5201 return false;
5202
5203 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5204 return false;
5205 }
5206
5207 return true;
5208 }
5209
check_func_proto(const struct bpf_func_proto * fn,int func_id)5210 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
5211 {
5212 return check_raw_mode_ok(fn) &&
5213 check_arg_pair_ok(fn) &&
5214 check_btf_id_ok(fn) &&
5215 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
5216 }
5217
5218 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5219 * are now invalid, so turn them into unknown SCALAR_VALUE.
5220 */
clear_all_pkt_pointers(struct bpf_verifier_env * env)5221 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5222 {
5223 struct bpf_func_state *state;
5224 struct bpf_reg_state *reg;
5225
5226 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5227 if (reg_is_pkt_pointer_any(reg))
5228 __mark_reg_unknown(env, reg);
5229 }));
5230 }
5231
5232 enum {
5233 AT_PKT_END = -1,
5234 BEYOND_PKT_END = -2,
5235 };
5236
mark_pkt_end(struct bpf_verifier_state * vstate,int regn,bool range_open)5237 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5238 {
5239 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5240 struct bpf_reg_state *reg = &state->regs[regn];
5241
5242 if (reg->type != PTR_TO_PACKET)
5243 /* PTR_TO_PACKET_META is not supported yet */
5244 return;
5245
5246 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5247 * How far beyond pkt_end it goes is unknown.
5248 * if (!range_open) it's the case of pkt >= pkt_end
5249 * if (range_open) it's the case of pkt > pkt_end
5250 * hence this pointer is at least 1 byte bigger than pkt_end
5251 */
5252 if (range_open)
5253 reg->range = BEYOND_PKT_END;
5254 else
5255 reg->range = AT_PKT_END;
5256 }
5257
5258 /* The pointer with the specified id has released its reference to kernel
5259 * resources. Identify all copies of the same pointer and clear the reference.
5260 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)5261 static int release_reference(struct bpf_verifier_env *env,
5262 int ref_obj_id)
5263 {
5264 struct bpf_func_state *state;
5265 struct bpf_reg_state *reg;
5266 int err;
5267
5268 err = release_reference_state(cur_func(env), ref_obj_id);
5269 if (err)
5270 return err;
5271
5272 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
5273 if (reg->ref_obj_id == ref_obj_id) {
5274 if (!env->allow_ptr_leaks)
5275 __mark_reg_not_init(env, reg);
5276 else
5277 __mark_reg_unknown(env, reg);
5278 }
5279 }));
5280
5281 return 0;
5282 }
5283
clear_caller_saved_regs(struct bpf_verifier_env * env,struct bpf_reg_state * regs)5284 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5285 struct bpf_reg_state *regs)
5286 {
5287 int i;
5288
5289 /* after the call registers r0 - r5 were scratched */
5290 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5291 mark_reg_not_init(env, regs, caller_saved[i]);
5292 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5293 }
5294 }
5295
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)5296 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5297 int *insn_idx)
5298 {
5299 struct bpf_verifier_state *state = env->cur_state;
5300 struct bpf_func_info_aux *func_info_aux;
5301 struct bpf_func_state *caller, *callee;
5302 int i, err, subprog, target_insn;
5303 bool is_global = false;
5304
5305 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
5306 verbose(env, "the call stack of %d frames is too deep\n",
5307 state->curframe + 2);
5308 return -E2BIG;
5309 }
5310
5311 target_insn = *insn_idx + insn->imm;
5312 subprog = find_subprog(env, target_insn + 1);
5313 if (subprog < 0) {
5314 verbose(env, "verifier bug. No program starts at insn %d\n",
5315 target_insn + 1);
5316 return -EFAULT;
5317 }
5318
5319 caller = state->frame[state->curframe];
5320 if (state->frame[state->curframe + 1]) {
5321 verbose(env, "verifier bug. Frame %d already allocated\n",
5322 state->curframe + 1);
5323 return -EFAULT;
5324 }
5325
5326 func_info_aux = env->prog->aux->func_info_aux;
5327 if (func_info_aux)
5328 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5329 err = btf_check_func_arg_match(env, subprog, caller->regs);
5330 if (err == -EFAULT)
5331 return err;
5332 if (is_global) {
5333 if (err) {
5334 verbose(env, "Caller passes invalid args into func#%d\n",
5335 subprog);
5336 return err;
5337 } else {
5338 if (env->log.level & BPF_LOG_LEVEL)
5339 verbose(env,
5340 "Func#%d is global and valid. Skipping.\n",
5341 subprog);
5342 clear_caller_saved_regs(env, caller->regs);
5343
5344 /* All global functions return a 64-bit SCALAR_VALUE */
5345 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5346 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5347
5348 /* continue with next insn after call */
5349 return 0;
5350 }
5351 }
5352
5353 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5354 if (!callee)
5355 return -ENOMEM;
5356 state->frame[state->curframe + 1] = callee;
5357
5358 /* callee cannot access r0, r6 - r9 for reading and has to write
5359 * into its own stack before reading from it.
5360 * callee can read/write into caller's stack
5361 */
5362 init_func_state(env, callee,
5363 /* remember the callsite, it will be used by bpf_exit */
5364 *insn_idx /* callsite */,
5365 state->curframe + 1 /* frameno within this callchain */,
5366 subprog /* subprog number within this prog */);
5367
5368 /* Transfer references to the callee */
5369 err = transfer_reference_state(callee, caller);
5370 if (err)
5371 return err;
5372
5373 /* copy r1 - r5 args that callee can access. The copy includes parent
5374 * pointers, which connects us up to the liveness chain
5375 */
5376 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5377 callee->regs[i] = caller->regs[i];
5378
5379 clear_caller_saved_regs(env, caller->regs);
5380
5381 /* only increment it after check_reg_arg() finished */
5382 state->curframe++;
5383
5384 /* and go analyze first insn of the callee */
5385 *insn_idx = target_insn;
5386
5387 if (env->log.level & BPF_LOG_LEVEL) {
5388 verbose(env, "caller:\n");
5389 print_verifier_state(env, caller);
5390 verbose(env, "callee:\n");
5391 print_verifier_state(env, callee);
5392 }
5393 return 0;
5394 }
5395
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)5396 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5397 {
5398 struct bpf_verifier_state *state = env->cur_state;
5399 struct bpf_func_state *caller, *callee;
5400 struct bpf_reg_state *r0;
5401 int err;
5402
5403 callee = state->frame[state->curframe];
5404 r0 = &callee->regs[BPF_REG_0];
5405 if (r0->type == PTR_TO_STACK) {
5406 /* technically it's ok to return caller's stack pointer
5407 * (or caller's caller's pointer) back to the caller,
5408 * since these pointers are valid. Only current stack
5409 * pointer will be invalid as soon as function exits,
5410 * but let's be conservative
5411 */
5412 verbose(env, "cannot return stack pointer to the caller\n");
5413 return -EINVAL;
5414 }
5415
5416 state->curframe--;
5417 caller = state->frame[state->curframe];
5418 /* return to the caller whatever r0 had in the callee */
5419 caller->regs[BPF_REG_0] = *r0;
5420
5421 /* Transfer references to the caller */
5422 err = transfer_reference_state(caller, callee);
5423 if (err)
5424 return err;
5425
5426 *insn_idx = callee->callsite + 1;
5427 if (env->log.level & BPF_LOG_LEVEL) {
5428 verbose(env, "returning from callee:\n");
5429 print_verifier_state(env, callee);
5430 verbose(env, "to caller at %d:\n", *insn_idx);
5431 print_verifier_state(env, caller);
5432 }
5433 /* clear everything in the callee */
5434 free_func_state(callee);
5435 state->frame[state->curframe + 1] = NULL;
5436 return 0;
5437 }
5438
do_refine_retval_range(struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)5439 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5440 int func_id,
5441 struct bpf_call_arg_meta *meta)
5442 {
5443 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
5444
5445 if (ret_type != RET_INTEGER ||
5446 (func_id != BPF_FUNC_get_stack &&
5447 func_id != BPF_FUNC_probe_read_str &&
5448 func_id != BPF_FUNC_probe_read_kernel_str &&
5449 func_id != BPF_FUNC_probe_read_user_str))
5450 return;
5451
5452 ret_reg->smax_value = meta->msize_max_value;
5453 ret_reg->s32_max_value = meta->msize_max_value;
5454 ret_reg->smin_value = -MAX_ERRNO;
5455 ret_reg->s32_min_value = -MAX_ERRNO;
5456 reg_bounds_sync(ret_reg);
5457 }
5458
5459 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5460 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5461 int func_id, int insn_idx)
5462 {
5463 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5464 struct bpf_map *map = meta->map_ptr;
5465
5466 if (func_id != BPF_FUNC_tail_call &&
5467 func_id != BPF_FUNC_map_lookup_elem &&
5468 func_id != BPF_FUNC_map_update_elem &&
5469 func_id != BPF_FUNC_map_delete_elem &&
5470 func_id != BPF_FUNC_map_push_elem &&
5471 func_id != BPF_FUNC_map_pop_elem &&
5472 func_id != BPF_FUNC_map_peek_elem)
5473 return 0;
5474
5475 if (map == NULL) {
5476 verbose(env, "kernel subsystem misconfigured verifier\n");
5477 return -EINVAL;
5478 }
5479
5480 /* In case of read-only, some additional restrictions
5481 * need to be applied in order to prevent altering the
5482 * state of the map from program side.
5483 */
5484 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5485 (func_id == BPF_FUNC_map_delete_elem ||
5486 func_id == BPF_FUNC_map_update_elem ||
5487 func_id == BPF_FUNC_map_push_elem ||
5488 func_id == BPF_FUNC_map_pop_elem)) {
5489 verbose(env, "write into map forbidden\n");
5490 return -EACCES;
5491 }
5492
5493 if (!BPF_MAP_PTR(aux->map_ptr_state))
5494 bpf_map_ptr_store(aux, meta->map_ptr,
5495 !meta->map_ptr->bypass_spec_v1);
5496 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
5497 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
5498 !meta->map_ptr->bypass_spec_v1);
5499 return 0;
5500 }
5501
5502 static int
record_func_key(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)5503 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5504 int func_id, int insn_idx)
5505 {
5506 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5507 struct bpf_reg_state *regs = cur_regs(env), *reg;
5508 struct bpf_map *map = meta->map_ptr;
5509 u64 val, max;
5510 int err;
5511
5512 if (func_id != BPF_FUNC_tail_call)
5513 return 0;
5514 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5515 verbose(env, "kernel subsystem misconfigured verifier\n");
5516 return -EINVAL;
5517 }
5518
5519 reg = ®s[BPF_REG_3];
5520 val = reg->var_off.value;
5521 max = map->max_entries;
5522
5523 if (!(register_is_const(reg) && val < max)) {
5524 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5525 return 0;
5526 }
5527
5528 err = mark_chain_precision(env, BPF_REG_3);
5529 if (err)
5530 return err;
5531 if (bpf_map_key_unseen(aux))
5532 bpf_map_key_store(aux, val);
5533 else if (!bpf_map_key_poisoned(aux) &&
5534 bpf_map_key_immediate(aux) != val)
5535 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5536 return 0;
5537 }
5538
check_reference_leak(struct bpf_verifier_env * env)5539 static int check_reference_leak(struct bpf_verifier_env *env)
5540 {
5541 struct bpf_func_state *state = cur_func(env);
5542 int i;
5543
5544 for (i = 0; i < state->acquired_refs; i++) {
5545 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5546 state->refs[i].id, state->refs[i].insn_idx);
5547 }
5548 return state->acquired_refs ? -EINVAL : 0;
5549 }
5550
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)5551 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
5552 {
5553 const struct bpf_func_proto *fn = NULL;
5554 struct bpf_reg_state *regs;
5555 struct bpf_call_arg_meta meta;
5556 bool changes_data;
5557 int i, err;
5558
5559 /* find function prototype */
5560 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
5561 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5562 func_id);
5563 return -EINVAL;
5564 }
5565
5566 if (env->ops->get_func_proto)
5567 fn = env->ops->get_func_proto(func_id, env->prog);
5568 if (!fn) {
5569 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5570 func_id);
5571 return -EINVAL;
5572 }
5573
5574 /* eBPF programs must be GPL compatible to use GPL-ed functions */
5575 if (!env->prog->gpl_compatible && fn->gpl_only) {
5576 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
5577 return -EINVAL;
5578 }
5579
5580 if (fn->allowed && !fn->allowed(env->prog)) {
5581 verbose(env, "helper call is not allowed in probe\n");
5582 return -EINVAL;
5583 }
5584
5585 /* With LD_ABS/IND some JITs save/restore skb from r1. */
5586 changes_data = bpf_helper_changes_pkt_data(fn->func);
5587 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5588 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5589 func_id_name(func_id), func_id);
5590 return -EINVAL;
5591 }
5592
5593 memset(&meta, 0, sizeof(meta));
5594 meta.pkt_access = fn->pkt_access;
5595
5596 err = check_func_proto(fn, func_id);
5597 if (err) {
5598 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
5599 func_id_name(func_id), func_id);
5600 return err;
5601 }
5602
5603 meta.func_id = func_id;
5604 /* check args */
5605 for (i = 0; i < 5; i++) {
5606 err = check_func_arg(env, i, &meta, fn);
5607 if (err)
5608 return err;
5609 }
5610
5611 err = record_func_map(env, &meta, func_id, insn_idx);
5612 if (err)
5613 return err;
5614
5615 err = record_func_key(env, &meta, func_id, insn_idx);
5616 if (err)
5617 return err;
5618
5619 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5620 * is inferred from register state.
5621 */
5622 for (i = 0; i < meta.access_size; i++) {
5623 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5624 BPF_WRITE, -1, false);
5625 if (err)
5626 return err;
5627 }
5628
5629 if (func_id == BPF_FUNC_tail_call) {
5630 err = check_reference_leak(env);
5631 if (err) {
5632 verbose(env, "tail_call would lead to reference leak\n");
5633 return err;
5634 }
5635 } else if (is_release_function(func_id)) {
5636 err = release_reference(env, meta.ref_obj_id);
5637 if (err) {
5638 verbose(env, "func %s#%d reference has not been acquired before\n",
5639 func_id_name(func_id), func_id);
5640 return err;
5641 }
5642 }
5643
5644 regs = cur_regs(env);
5645
5646 /* check that flags argument in get_local_storage(map, flags) is 0,
5647 * this is required because get_local_storage() can't return an error.
5648 */
5649 if (func_id == BPF_FUNC_get_local_storage &&
5650 !register_is_null(®s[BPF_REG_2])) {
5651 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5652 return -EINVAL;
5653 }
5654
5655 /* reset caller saved regs */
5656 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5657 mark_reg_not_init(env, regs, caller_saved[i]);
5658 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5659 }
5660
5661 /* helper call returns 64-bit value. */
5662 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5663
5664 /* update return register (already marked as written above) */
5665 if (fn->ret_type == RET_INTEGER) {
5666 /* sets type to SCALAR_VALUE */
5667 mark_reg_unknown(env, regs, BPF_REG_0);
5668 } else if (fn->ret_type == RET_VOID) {
5669 regs[BPF_REG_0].type = NOT_INIT;
5670 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5671 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5672 /* There is no offset yet applied, variable or fixed */
5673 mark_reg_known_zero(env, regs, BPF_REG_0);
5674 /* remember map_ptr, so that check_map_access()
5675 * can check 'value_size' boundary of memory access
5676 * to map element returned from bpf_map_lookup_elem()
5677 */
5678 if (meta.map_ptr == NULL) {
5679 verbose(env,
5680 "kernel subsystem misconfigured verifier\n");
5681 return -EINVAL;
5682 }
5683 regs[BPF_REG_0].map_ptr = meta.map_ptr;
5684 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5685 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
5686 if (map_value_has_spin_lock(meta.map_ptr))
5687 regs[BPF_REG_0].id = ++env->id_gen;
5688 } else {
5689 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
5690 }
5691 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5692 mark_reg_known_zero(env, regs, BPF_REG_0);
5693 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
5694 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5695 mark_reg_known_zero(env, regs, BPF_REG_0);
5696 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
5697 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5698 mark_reg_known_zero(env, regs, BPF_REG_0);
5699 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
5700 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5701 mark_reg_known_zero(env, regs, BPF_REG_0);
5702 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
5703 regs[BPF_REG_0].mem_size = meta.mem_size;
5704 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5705 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
5706 const struct btf_type *t;
5707
5708 mark_reg_known_zero(env, regs, BPF_REG_0);
5709 t = btf_type_skip_modifiers(btf_vmlinux, meta.ret_btf_id, NULL);
5710 if (!btf_type_is_struct(t)) {
5711 u32 tsize;
5712 const struct btf_type *ret;
5713 const char *tname;
5714
5715 /* resolve the type size of ksym. */
5716 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
5717 if (IS_ERR(ret)) {
5718 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
5719 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5720 tname, PTR_ERR(ret));
5721 return -EINVAL;
5722 }
5723 regs[BPF_REG_0].type =
5724 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5725 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
5726 regs[BPF_REG_0].mem_size = tsize;
5727 } else {
5728 regs[BPF_REG_0].type =
5729 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5730 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
5731 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5732 }
5733 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL) {
5734 int ret_btf_id;
5735
5736 mark_reg_known_zero(env, regs, BPF_REG_0);
5737 regs[BPF_REG_0].type = PTR_TO_BTF_ID_OR_NULL;
5738 ret_btf_id = *fn->ret_btf_id;
5739 if (ret_btf_id == 0) {
5740 verbose(env, "invalid return type %d of func %s#%d\n",
5741 fn->ret_type, func_id_name(func_id), func_id);
5742 return -EINVAL;
5743 }
5744 regs[BPF_REG_0].btf_id = ret_btf_id;
5745 } else {
5746 verbose(env, "unknown return type %d of func %s#%d\n",
5747 fn->ret_type, func_id_name(func_id), func_id);
5748 return -EINVAL;
5749 }
5750
5751 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5752 regs[BPF_REG_0].id = ++env->id_gen;
5753
5754 if (is_ptr_cast_function(func_id)) {
5755 /* For release_reference() */
5756 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
5757 } else if (is_acquire_function(func_id, meta.map_ptr)) {
5758 int id = acquire_reference_state(env, insn_idx);
5759
5760 if (id < 0)
5761 return id;
5762 /* For mark_ptr_or_null_reg() */
5763 regs[BPF_REG_0].id = id;
5764 /* For release_reference() */
5765 regs[BPF_REG_0].ref_obj_id = id;
5766 }
5767
5768 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5769
5770 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
5771 if (err)
5772 return err;
5773
5774 if ((func_id == BPF_FUNC_get_stack ||
5775 func_id == BPF_FUNC_get_task_stack) &&
5776 !env->prog->has_callchain_buf) {
5777 const char *err_str;
5778
5779 #ifdef CONFIG_PERF_EVENTS
5780 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5781 err_str = "cannot get callchain buffer for func %s#%d\n";
5782 #else
5783 err = -ENOTSUPP;
5784 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5785 #endif
5786 if (err) {
5787 verbose(env, err_str, func_id_name(func_id), func_id);
5788 return err;
5789 }
5790
5791 env->prog->has_callchain_buf = true;
5792 }
5793
5794 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5795 env->prog->call_get_stack = true;
5796
5797 if (changes_data)
5798 clear_all_pkt_pointers(env);
5799 return 0;
5800 }
5801
signed_add_overflows(s64 a,s64 b)5802 static bool signed_add_overflows(s64 a, s64 b)
5803 {
5804 /* Do the add in u64, where overflow is well-defined */
5805 s64 res = (s64)((u64)a + (u64)b);
5806
5807 if (b < 0)
5808 return res > a;
5809 return res < a;
5810 }
5811
signed_add32_overflows(s32 a,s32 b)5812 static bool signed_add32_overflows(s32 a, s32 b)
5813 {
5814 /* Do the add in u32, where overflow is well-defined */
5815 s32 res = (s32)((u32)a + (u32)b);
5816
5817 if (b < 0)
5818 return res > a;
5819 return res < a;
5820 }
5821
signed_sub_overflows(s64 a,s64 b)5822 static bool signed_sub_overflows(s64 a, s64 b)
5823 {
5824 /* Do the sub in u64, where overflow is well-defined */
5825 s64 res = (s64)((u64)a - (u64)b);
5826
5827 if (b < 0)
5828 return res < a;
5829 return res > a;
5830 }
5831
signed_sub32_overflows(s32 a,s32 b)5832 static bool signed_sub32_overflows(s32 a, s32 b)
5833 {
5834 /* Do the sub in u32, where overflow is well-defined */
5835 s32 res = (s32)((u32)a - (u32)b);
5836
5837 if (b < 0)
5838 return res < a;
5839 return res > a;
5840 }
5841
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)5842 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5843 const struct bpf_reg_state *reg,
5844 enum bpf_reg_type type)
5845 {
5846 bool known = tnum_is_const(reg->var_off);
5847 s64 val = reg->var_off.value;
5848 s64 smin = reg->smin_value;
5849
5850 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5851 verbose(env, "math between %s pointer and %lld is not allowed\n",
5852 reg_type_str[type], val);
5853 return false;
5854 }
5855
5856 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5857 verbose(env, "%s pointer offset %d is not allowed\n",
5858 reg_type_str[type], reg->off);
5859 return false;
5860 }
5861
5862 if (smin == S64_MIN) {
5863 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5864 reg_type_str[type]);
5865 return false;
5866 }
5867
5868 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5869 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5870 smin, reg_type_str[type]);
5871 return false;
5872 }
5873
5874 return true;
5875 }
5876
cur_aux(struct bpf_verifier_env * env)5877 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5878 {
5879 return &env->insn_aux_data[env->insn_idx];
5880 }
5881
5882 enum {
5883 REASON_BOUNDS = -1,
5884 REASON_TYPE = -2,
5885 REASON_PATHS = -3,
5886 REASON_LIMIT = -4,
5887 REASON_STACK = -5,
5888 };
5889
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)5890 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5891 u32 *alu_limit, bool mask_to_left)
5892 {
5893 u32 max = 0, ptr_limit = 0;
5894
5895 switch (ptr_reg->type) {
5896 case PTR_TO_STACK:
5897 /* Offset 0 is out-of-bounds, but acceptable start for the
5898 * left direction, see BPF_REG_FP. Also, unknown scalar
5899 * offset where we would need to deal with min/max bounds is
5900 * currently prohibited for unprivileged.
5901 */
5902 max = MAX_BPF_STACK + mask_to_left;
5903 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
5904 break;
5905 case PTR_TO_MAP_VALUE:
5906 max = ptr_reg->map_ptr->value_size;
5907 ptr_limit = (mask_to_left ?
5908 ptr_reg->smin_value :
5909 ptr_reg->umax_value) + ptr_reg->off;
5910 break;
5911 default:
5912 return REASON_TYPE;
5913 }
5914
5915 if (ptr_limit >= max)
5916 return REASON_LIMIT;
5917 *alu_limit = ptr_limit;
5918 return 0;
5919 }
5920
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)5921 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5922 const struct bpf_insn *insn)
5923 {
5924 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
5925 }
5926
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)5927 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5928 u32 alu_state, u32 alu_limit)
5929 {
5930 /* If we arrived here from different branches with different
5931 * state or limits to sanitize, then this won't work.
5932 */
5933 if (aux->alu_state &&
5934 (aux->alu_state != alu_state ||
5935 aux->alu_limit != alu_limit))
5936 return REASON_PATHS;
5937
5938 /* Corresponding fixup done in fixup_bpf_calls(). */
5939 aux->alu_state = alu_state;
5940 aux->alu_limit = alu_limit;
5941 return 0;
5942 }
5943
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)5944 static int sanitize_val_alu(struct bpf_verifier_env *env,
5945 struct bpf_insn *insn)
5946 {
5947 struct bpf_insn_aux_data *aux = cur_aux(env);
5948
5949 if (can_skip_alu_sanitation(env, insn))
5950 return 0;
5951
5952 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5953 }
5954
sanitize_needed(u8 opcode)5955 static bool sanitize_needed(u8 opcode)
5956 {
5957 return opcode == BPF_ADD || opcode == BPF_SUB;
5958 }
5959
5960 struct bpf_sanitize_info {
5961 struct bpf_insn_aux_data aux;
5962 bool mask_to_left;
5963 };
5964
5965 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)5966 sanitize_speculative_path(struct bpf_verifier_env *env,
5967 const struct bpf_insn *insn,
5968 u32 next_idx, u32 curr_idx)
5969 {
5970 struct bpf_verifier_state *branch;
5971 struct bpf_reg_state *regs;
5972
5973 branch = push_stack(env, next_idx, curr_idx, true);
5974 if (branch && insn) {
5975 regs = branch->frame[branch->curframe]->regs;
5976 if (BPF_SRC(insn->code) == BPF_K) {
5977 mark_reg_unknown(env, regs, insn->dst_reg);
5978 } else if (BPF_SRC(insn->code) == BPF_X) {
5979 mark_reg_unknown(env, regs, insn->dst_reg);
5980 mark_reg_unknown(env, regs, insn->src_reg);
5981 }
5982 }
5983 return branch;
5984 }
5985
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg,struct bpf_reg_state * dst_reg,struct bpf_sanitize_info * info,const bool commit_window)5986 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5987 struct bpf_insn *insn,
5988 const struct bpf_reg_state *ptr_reg,
5989 const struct bpf_reg_state *off_reg,
5990 struct bpf_reg_state *dst_reg,
5991 struct bpf_sanitize_info *info,
5992 const bool commit_window)
5993 {
5994 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
5995 struct bpf_verifier_state *vstate = env->cur_state;
5996 bool off_is_imm = tnum_is_const(off_reg->var_off);
5997 bool off_is_neg = off_reg->smin_value < 0;
5998 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5999 u8 opcode = BPF_OP(insn->code);
6000 u32 alu_state, alu_limit;
6001 struct bpf_reg_state tmp;
6002 bool ret;
6003 int err;
6004
6005 if (can_skip_alu_sanitation(env, insn))
6006 return 0;
6007
6008 /* We already marked aux for masking from non-speculative
6009 * paths, thus we got here in the first place. We only care
6010 * to explore bad access from here.
6011 */
6012 if (vstate->speculative)
6013 goto do_sim;
6014
6015 if (!commit_window) {
6016 if (!tnum_is_const(off_reg->var_off) &&
6017 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6018 return REASON_BOUNDS;
6019
6020 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6021 (opcode == BPF_SUB && !off_is_neg);
6022 }
6023
6024 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
6025 if (err < 0)
6026 return err;
6027
6028 if (commit_window) {
6029 /* In commit phase we narrow the masking window based on
6030 * the observed pointer move after the simulated operation.
6031 */
6032 alu_state = info->aux.alu_state;
6033 alu_limit = abs(info->aux.alu_limit - alu_limit);
6034 } else {
6035 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6036 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
6037 alu_state |= ptr_is_dst_reg ?
6038 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6039
6040 /* Limit pruning on unknown scalars to enable deep search for
6041 * potential masking differences from other program paths.
6042 */
6043 if (!off_is_imm)
6044 env->explore_alu_limits = true;
6045 }
6046
6047 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6048 if (err < 0)
6049 return err;
6050 do_sim:
6051 /* If we're in commit phase, we're done here given we already
6052 * pushed the truncated dst_reg into the speculative verification
6053 * stack.
6054 *
6055 * Also, when register is a known constant, we rewrite register-based
6056 * operation to immediate-based, and thus do not need masking (and as
6057 * a consequence, do not need to simulate the zero-truncation either).
6058 */
6059 if (commit_window || off_is_imm)
6060 return 0;
6061
6062 /* Simulate and find potential out-of-bounds access under
6063 * speculative execution from truncation as a result of
6064 * masking when off was not within expected range. If off
6065 * sits in dst, then we temporarily need to move ptr there
6066 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6067 * for cases where we use K-based arithmetic in one direction
6068 * and truncated reg-based in the other in order to explore
6069 * bad access.
6070 */
6071 if (!ptr_is_dst_reg) {
6072 tmp = *dst_reg;
6073 copy_register_state(dst_reg, ptr_reg);
6074 }
6075 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6076 env->insn_idx);
6077 if (!ptr_is_dst_reg && ret)
6078 *dst_reg = tmp;
6079 return !ret ? REASON_STACK : 0;
6080 }
6081
sanitize_mark_insn_seen(struct bpf_verifier_env * env)6082 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6083 {
6084 struct bpf_verifier_state *vstate = env->cur_state;
6085
6086 /* If we simulate paths under speculation, we don't update the
6087 * insn as 'seen' such that when we verify unreachable paths in
6088 * the non-speculative domain, sanitize_dead_code() can still
6089 * rewrite/sanitize them.
6090 */
6091 if (!vstate->speculative)
6092 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6093 }
6094
sanitize_err(struct bpf_verifier_env * env,const struct bpf_insn * insn,int reason,const struct bpf_reg_state * off_reg,const struct bpf_reg_state * dst_reg)6095 static int sanitize_err(struct bpf_verifier_env *env,
6096 const struct bpf_insn *insn, int reason,
6097 const struct bpf_reg_state *off_reg,
6098 const struct bpf_reg_state *dst_reg)
6099 {
6100 static const char *err = "pointer arithmetic with it prohibited for !root";
6101 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6102 u32 dst = insn->dst_reg, src = insn->src_reg;
6103
6104 switch (reason) {
6105 case REASON_BOUNDS:
6106 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6107 off_reg == dst_reg ? dst : src, err);
6108 break;
6109 case REASON_TYPE:
6110 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6111 off_reg == dst_reg ? src : dst, err);
6112 break;
6113 case REASON_PATHS:
6114 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6115 dst, op, err);
6116 break;
6117 case REASON_LIMIT:
6118 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6119 dst, op, err);
6120 break;
6121 case REASON_STACK:
6122 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6123 dst, err);
6124 break;
6125 default:
6126 verbose(env, "verifier internal error: unknown reason (%d)\n",
6127 reason);
6128 break;
6129 }
6130
6131 return -EACCES;
6132 }
6133
6134 /* check that stack access falls within stack limits and that 'reg' doesn't
6135 * have a variable offset.
6136 *
6137 * Variable offset is prohibited for unprivileged mode for simplicity since it
6138 * requires corresponding support in Spectre masking for stack ALU. See also
6139 * retrieve_ptr_limit().
6140 *
6141 *
6142 * 'off' includes 'reg->off'.
6143 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)6144 static int check_stack_access_for_ptr_arithmetic(
6145 struct bpf_verifier_env *env,
6146 int regno,
6147 const struct bpf_reg_state *reg,
6148 int off)
6149 {
6150 if (!tnum_is_const(reg->var_off)) {
6151 char tn_buf[48];
6152
6153 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6154 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6155 regno, tn_buf, off);
6156 return -EACCES;
6157 }
6158
6159 if (off >= 0 || off < -MAX_BPF_STACK) {
6160 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6161 "prohibited for !root; off=%d\n", regno, off);
6162 return -EACCES;
6163 }
6164
6165 return 0;
6166 }
6167
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)6168 static int sanitize_check_bounds(struct bpf_verifier_env *env,
6169 const struct bpf_insn *insn,
6170 const struct bpf_reg_state *dst_reg)
6171 {
6172 u32 dst = insn->dst_reg;
6173
6174 /* For unprivileged we require that resulting offset must be in bounds
6175 * in order to be able to sanitize access later on.
6176 */
6177 if (env->bypass_spec_v1)
6178 return 0;
6179
6180 switch (dst_reg->type) {
6181 case PTR_TO_STACK:
6182 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6183 dst_reg->off + dst_reg->var_off.value))
6184 return -EACCES;
6185 break;
6186 case PTR_TO_MAP_VALUE:
6187 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6188 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6189 "prohibited for !root\n", dst);
6190 return -EACCES;
6191 }
6192 break;
6193 default:
6194 break;
6195 }
6196
6197 return 0;
6198 }
6199
6200 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
6201 * Caller should also handle BPF_MOV case separately.
6202 * If we return -EACCES, caller may want to try again treating pointer as a
6203 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6204 */
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)6205 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6206 struct bpf_insn *insn,
6207 const struct bpf_reg_state *ptr_reg,
6208 const struct bpf_reg_state *off_reg)
6209 {
6210 struct bpf_verifier_state *vstate = env->cur_state;
6211 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6212 struct bpf_reg_state *regs = state->regs, *dst_reg;
6213 bool known = tnum_is_const(off_reg->var_off);
6214 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6215 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6216 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6217 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
6218 struct bpf_sanitize_info info = {};
6219 u8 opcode = BPF_OP(insn->code);
6220 u32 dst = insn->dst_reg;
6221 int ret;
6222
6223 dst_reg = ®s[dst];
6224
6225 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6226 smin_val > smax_val || umin_val > umax_val) {
6227 /* Taint dst register if offset had invalid bounds derived from
6228 * e.g. dead branches.
6229 */
6230 __mark_reg_unknown(env, dst_reg);
6231 return 0;
6232 }
6233
6234 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6235 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6236 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6237 __mark_reg_unknown(env, dst_reg);
6238 return 0;
6239 }
6240
6241 verbose(env,
6242 "R%d 32-bit pointer arithmetic prohibited\n",
6243 dst);
6244 return -EACCES;
6245 }
6246
6247 switch (ptr_reg->type) {
6248 case PTR_TO_MAP_VALUE_OR_NULL:
6249 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6250 dst, reg_type_str[ptr_reg->type]);
6251 return -EACCES;
6252 case CONST_PTR_TO_MAP:
6253 /* smin_val represents the known value */
6254 if (known && smin_val == 0 && opcode == BPF_ADD)
6255 break;
6256 fallthrough;
6257 case PTR_TO_PACKET_END:
6258 case PTR_TO_SOCKET:
6259 case PTR_TO_SOCK_COMMON:
6260 case PTR_TO_TCP_SOCK:
6261 case PTR_TO_XDP_SOCK:
6262 reject:
6263 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6264 dst, reg_type_str[ptr_reg->type]);
6265 return -EACCES;
6266 default:
6267 if (reg_type_may_be_null(ptr_reg->type))
6268 goto reject;
6269 break;
6270 }
6271
6272 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6273 * The id may be overwritten later if we create a new variable offset.
6274 */
6275 dst_reg->type = ptr_reg->type;
6276 dst_reg->id = ptr_reg->id;
6277
6278 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6279 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6280 return -EINVAL;
6281
6282 /* pointer types do not carry 32-bit bounds at the moment. */
6283 __mark_reg32_unbounded(dst_reg);
6284
6285 if (sanitize_needed(opcode)) {
6286 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
6287 &info, false);
6288 if (ret < 0)
6289 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6290 }
6291
6292 switch (opcode) {
6293 case BPF_ADD:
6294 /* We can take a fixed offset as long as it doesn't overflow
6295 * the s32 'off' field
6296 */
6297 if (known && (ptr_reg->off + smin_val ==
6298 (s64)(s32)(ptr_reg->off + smin_val))) {
6299 /* pointer += K. Accumulate it into fixed offset */
6300 dst_reg->smin_value = smin_ptr;
6301 dst_reg->smax_value = smax_ptr;
6302 dst_reg->umin_value = umin_ptr;
6303 dst_reg->umax_value = umax_ptr;
6304 dst_reg->var_off = ptr_reg->var_off;
6305 dst_reg->off = ptr_reg->off + smin_val;
6306 dst_reg->raw = ptr_reg->raw;
6307 break;
6308 }
6309 /* A new variable offset is created. Note that off_reg->off
6310 * == 0, since it's a scalar.
6311 * dst_reg gets the pointer type and since some positive
6312 * integer value was added to the pointer, give it a new 'id'
6313 * if it's a PTR_TO_PACKET.
6314 * this creates a new 'base' pointer, off_reg (variable) gets
6315 * added into the variable offset, and we copy the fixed offset
6316 * from ptr_reg.
6317 */
6318 if (signed_add_overflows(smin_ptr, smin_val) ||
6319 signed_add_overflows(smax_ptr, smax_val)) {
6320 dst_reg->smin_value = S64_MIN;
6321 dst_reg->smax_value = S64_MAX;
6322 } else {
6323 dst_reg->smin_value = smin_ptr + smin_val;
6324 dst_reg->smax_value = smax_ptr + smax_val;
6325 }
6326 if (umin_ptr + umin_val < umin_ptr ||
6327 umax_ptr + umax_val < umax_ptr) {
6328 dst_reg->umin_value = 0;
6329 dst_reg->umax_value = U64_MAX;
6330 } else {
6331 dst_reg->umin_value = umin_ptr + umin_val;
6332 dst_reg->umax_value = umax_ptr + umax_val;
6333 }
6334 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6335 dst_reg->off = ptr_reg->off;
6336 dst_reg->raw = ptr_reg->raw;
6337 if (reg_is_pkt_pointer(ptr_reg)) {
6338 dst_reg->id = ++env->id_gen;
6339 /* something was added to pkt_ptr, set range to zero */
6340 dst_reg->raw = 0;
6341 }
6342 break;
6343 case BPF_SUB:
6344 if (dst_reg == off_reg) {
6345 /* scalar -= pointer. Creates an unknown scalar */
6346 verbose(env, "R%d tried to subtract pointer from scalar\n",
6347 dst);
6348 return -EACCES;
6349 }
6350 /* We don't allow subtraction from FP, because (according to
6351 * test_verifier.c test "invalid fp arithmetic", JITs might not
6352 * be able to deal with it.
6353 */
6354 if (ptr_reg->type == PTR_TO_STACK) {
6355 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6356 dst);
6357 return -EACCES;
6358 }
6359 if (known && (ptr_reg->off - smin_val ==
6360 (s64)(s32)(ptr_reg->off - smin_val))) {
6361 /* pointer -= K. Subtract it from fixed offset */
6362 dst_reg->smin_value = smin_ptr;
6363 dst_reg->smax_value = smax_ptr;
6364 dst_reg->umin_value = umin_ptr;
6365 dst_reg->umax_value = umax_ptr;
6366 dst_reg->var_off = ptr_reg->var_off;
6367 dst_reg->id = ptr_reg->id;
6368 dst_reg->off = ptr_reg->off - smin_val;
6369 dst_reg->raw = ptr_reg->raw;
6370 break;
6371 }
6372 /* A new variable offset is created. If the subtrahend is known
6373 * nonnegative, then any reg->range we had before is still good.
6374 */
6375 if (signed_sub_overflows(smin_ptr, smax_val) ||
6376 signed_sub_overflows(smax_ptr, smin_val)) {
6377 /* Overflow possible, we know nothing */
6378 dst_reg->smin_value = S64_MIN;
6379 dst_reg->smax_value = S64_MAX;
6380 } else {
6381 dst_reg->smin_value = smin_ptr - smax_val;
6382 dst_reg->smax_value = smax_ptr - smin_val;
6383 }
6384 if (umin_ptr < umax_val) {
6385 /* Overflow possible, we know nothing */
6386 dst_reg->umin_value = 0;
6387 dst_reg->umax_value = U64_MAX;
6388 } else {
6389 /* Cannot overflow (as long as bounds are consistent) */
6390 dst_reg->umin_value = umin_ptr - umax_val;
6391 dst_reg->umax_value = umax_ptr - umin_val;
6392 }
6393 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6394 dst_reg->off = ptr_reg->off;
6395 dst_reg->raw = ptr_reg->raw;
6396 if (reg_is_pkt_pointer(ptr_reg)) {
6397 dst_reg->id = ++env->id_gen;
6398 /* something was added to pkt_ptr, set range to zero */
6399 if (smin_val < 0)
6400 dst_reg->raw = 0;
6401 }
6402 break;
6403 case BPF_AND:
6404 case BPF_OR:
6405 case BPF_XOR:
6406 /* bitwise ops on pointers are troublesome, prohibit. */
6407 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6408 dst, bpf_alu_string[opcode >> 4]);
6409 return -EACCES;
6410 default:
6411 /* other operators (e.g. MUL,LSH) produce non-pointer results */
6412 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6413 dst, bpf_alu_string[opcode >> 4]);
6414 return -EACCES;
6415 }
6416
6417 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6418 return -EINVAL;
6419 reg_bounds_sync(dst_reg);
6420 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6421 return -EACCES;
6422 if (sanitize_needed(opcode)) {
6423 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
6424 &info, true);
6425 if (ret < 0)
6426 return sanitize_err(env, insn, ret, off_reg, dst_reg);
6427 }
6428
6429 return 0;
6430 }
6431
scalar32_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6432 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6433 struct bpf_reg_state *src_reg)
6434 {
6435 s32 smin_val = src_reg->s32_min_value;
6436 s32 smax_val = src_reg->s32_max_value;
6437 u32 umin_val = src_reg->u32_min_value;
6438 u32 umax_val = src_reg->u32_max_value;
6439
6440 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6441 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6442 dst_reg->s32_min_value = S32_MIN;
6443 dst_reg->s32_max_value = S32_MAX;
6444 } else {
6445 dst_reg->s32_min_value += smin_val;
6446 dst_reg->s32_max_value += smax_val;
6447 }
6448 if (dst_reg->u32_min_value + umin_val < umin_val ||
6449 dst_reg->u32_max_value + umax_val < umax_val) {
6450 dst_reg->u32_min_value = 0;
6451 dst_reg->u32_max_value = U32_MAX;
6452 } else {
6453 dst_reg->u32_min_value += umin_val;
6454 dst_reg->u32_max_value += umax_val;
6455 }
6456 }
6457
scalar_min_max_add(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6458 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6459 struct bpf_reg_state *src_reg)
6460 {
6461 s64 smin_val = src_reg->smin_value;
6462 s64 smax_val = src_reg->smax_value;
6463 u64 umin_val = src_reg->umin_value;
6464 u64 umax_val = src_reg->umax_value;
6465
6466 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6467 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6468 dst_reg->smin_value = S64_MIN;
6469 dst_reg->smax_value = S64_MAX;
6470 } else {
6471 dst_reg->smin_value += smin_val;
6472 dst_reg->smax_value += smax_val;
6473 }
6474 if (dst_reg->umin_value + umin_val < umin_val ||
6475 dst_reg->umax_value + umax_val < umax_val) {
6476 dst_reg->umin_value = 0;
6477 dst_reg->umax_value = U64_MAX;
6478 } else {
6479 dst_reg->umin_value += umin_val;
6480 dst_reg->umax_value += umax_val;
6481 }
6482 }
6483
scalar32_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6484 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6485 struct bpf_reg_state *src_reg)
6486 {
6487 s32 smin_val = src_reg->s32_min_value;
6488 s32 smax_val = src_reg->s32_max_value;
6489 u32 umin_val = src_reg->u32_min_value;
6490 u32 umax_val = src_reg->u32_max_value;
6491
6492 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6493 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6494 /* Overflow possible, we know nothing */
6495 dst_reg->s32_min_value = S32_MIN;
6496 dst_reg->s32_max_value = S32_MAX;
6497 } else {
6498 dst_reg->s32_min_value -= smax_val;
6499 dst_reg->s32_max_value -= smin_val;
6500 }
6501 if (dst_reg->u32_min_value < umax_val) {
6502 /* Overflow possible, we know nothing */
6503 dst_reg->u32_min_value = 0;
6504 dst_reg->u32_max_value = U32_MAX;
6505 } else {
6506 /* Cannot overflow (as long as bounds are consistent) */
6507 dst_reg->u32_min_value -= umax_val;
6508 dst_reg->u32_max_value -= umin_val;
6509 }
6510 }
6511
scalar_min_max_sub(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6512 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6513 struct bpf_reg_state *src_reg)
6514 {
6515 s64 smin_val = src_reg->smin_value;
6516 s64 smax_val = src_reg->smax_value;
6517 u64 umin_val = src_reg->umin_value;
6518 u64 umax_val = src_reg->umax_value;
6519
6520 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6521 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6522 /* Overflow possible, we know nothing */
6523 dst_reg->smin_value = S64_MIN;
6524 dst_reg->smax_value = S64_MAX;
6525 } else {
6526 dst_reg->smin_value -= smax_val;
6527 dst_reg->smax_value -= smin_val;
6528 }
6529 if (dst_reg->umin_value < umax_val) {
6530 /* Overflow possible, we know nothing */
6531 dst_reg->umin_value = 0;
6532 dst_reg->umax_value = U64_MAX;
6533 } else {
6534 /* Cannot overflow (as long as bounds are consistent) */
6535 dst_reg->umin_value -= umax_val;
6536 dst_reg->umax_value -= umin_val;
6537 }
6538 }
6539
scalar32_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6540 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6541 struct bpf_reg_state *src_reg)
6542 {
6543 s32 smin_val = src_reg->s32_min_value;
6544 u32 umin_val = src_reg->u32_min_value;
6545 u32 umax_val = src_reg->u32_max_value;
6546
6547 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6548 /* Ain't nobody got time to multiply that sign */
6549 __mark_reg32_unbounded(dst_reg);
6550 return;
6551 }
6552 /* Both values are positive, so we can work with unsigned and
6553 * copy the result to signed (unless it exceeds S32_MAX).
6554 */
6555 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6556 /* Potential overflow, we know nothing */
6557 __mark_reg32_unbounded(dst_reg);
6558 return;
6559 }
6560 dst_reg->u32_min_value *= umin_val;
6561 dst_reg->u32_max_value *= umax_val;
6562 if (dst_reg->u32_max_value > S32_MAX) {
6563 /* Overflow possible, we know nothing */
6564 dst_reg->s32_min_value = S32_MIN;
6565 dst_reg->s32_max_value = S32_MAX;
6566 } else {
6567 dst_reg->s32_min_value = dst_reg->u32_min_value;
6568 dst_reg->s32_max_value = dst_reg->u32_max_value;
6569 }
6570 }
6571
scalar_min_max_mul(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6572 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6573 struct bpf_reg_state *src_reg)
6574 {
6575 s64 smin_val = src_reg->smin_value;
6576 u64 umin_val = src_reg->umin_value;
6577 u64 umax_val = src_reg->umax_value;
6578
6579 if (smin_val < 0 || dst_reg->smin_value < 0) {
6580 /* Ain't nobody got time to multiply that sign */
6581 __mark_reg64_unbounded(dst_reg);
6582 return;
6583 }
6584 /* Both values are positive, so we can work with unsigned and
6585 * copy the result to signed (unless it exceeds S64_MAX).
6586 */
6587 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6588 /* Potential overflow, we know nothing */
6589 __mark_reg64_unbounded(dst_reg);
6590 return;
6591 }
6592 dst_reg->umin_value *= umin_val;
6593 dst_reg->umax_value *= umax_val;
6594 if (dst_reg->umax_value > S64_MAX) {
6595 /* Overflow possible, we know nothing */
6596 dst_reg->smin_value = S64_MIN;
6597 dst_reg->smax_value = S64_MAX;
6598 } else {
6599 dst_reg->smin_value = dst_reg->umin_value;
6600 dst_reg->smax_value = dst_reg->umax_value;
6601 }
6602 }
6603
scalar32_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6604 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6605 struct bpf_reg_state *src_reg)
6606 {
6607 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6608 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6609 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6610 s32 smin_val = src_reg->s32_min_value;
6611 u32 umax_val = src_reg->u32_max_value;
6612
6613 if (src_known && dst_known) {
6614 __mark_reg32_known(dst_reg, var32_off.value);
6615 return;
6616 }
6617
6618 /* We get our minimum from the var_off, since that's inherently
6619 * bitwise. Our maximum is the minimum of the operands' maxima.
6620 */
6621 dst_reg->u32_min_value = var32_off.value;
6622 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6623 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6624 /* Lose signed bounds when ANDing negative numbers,
6625 * ain't nobody got time for that.
6626 */
6627 dst_reg->s32_min_value = S32_MIN;
6628 dst_reg->s32_max_value = S32_MAX;
6629 } else {
6630 /* ANDing two positives gives a positive, so safe to
6631 * cast result into s64.
6632 */
6633 dst_reg->s32_min_value = dst_reg->u32_min_value;
6634 dst_reg->s32_max_value = dst_reg->u32_max_value;
6635 }
6636 }
6637
scalar_min_max_and(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6638 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6639 struct bpf_reg_state *src_reg)
6640 {
6641 bool src_known = tnum_is_const(src_reg->var_off);
6642 bool dst_known = tnum_is_const(dst_reg->var_off);
6643 s64 smin_val = src_reg->smin_value;
6644 u64 umax_val = src_reg->umax_value;
6645
6646 if (src_known && dst_known) {
6647 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6648 return;
6649 }
6650
6651 /* We get our minimum from the var_off, since that's inherently
6652 * bitwise. Our maximum is the minimum of the operands' maxima.
6653 */
6654 dst_reg->umin_value = dst_reg->var_off.value;
6655 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6656 if (dst_reg->smin_value < 0 || smin_val < 0) {
6657 /* Lose signed bounds when ANDing negative numbers,
6658 * ain't nobody got time for that.
6659 */
6660 dst_reg->smin_value = S64_MIN;
6661 dst_reg->smax_value = S64_MAX;
6662 } else {
6663 /* ANDing two positives gives a positive, so safe to
6664 * cast result into s64.
6665 */
6666 dst_reg->smin_value = dst_reg->umin_value;
6667 dst_reg->smax_value = dst_reg->umax_value;
6668 }
6669 /* We may learn something more from the var_off */
6670 __update_reg_bounds(dst_reg);
6671 }
6672
scalar32_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6673 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6674 struct bpf_reg_state *src_reg)
6675 {
6676 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6677 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6678 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6679 s32 smin_val = src_reg->s32_min_value;
6680 u32 umin_val = src_reg->u32_min_value;
6681
6682 if (src_known && dst_known) {
6683 __mark_reg32_known(dst_reg, var32_off.value);
6684 return;
6685 }
6686
6687 /* We get our maximum from the var_off, and our minimum is the
6688 * maximum of the operands' minima
6689 */
6690 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6691 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6692 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6693 /* Lose signed bounds when ORing negative numbers,
6694 * ain't nobody got time for that.
6695 */
6696 dst_reg->s32_min_value = S32_MIN;
6697 dst_reg->s32_max_value = S32_MAX;
6698 } else {
6699 /* ORing two positives gives a positive, so safe to
6700 * cast result into s64.
6701 */
6702 dst_reg->s32_min_value = dst_reg->u32_min_value;
6703 dst_reg->s32_max_value = dst_reg->u32_max_value;
6704 }
6705 }
6706
scalar_min_max_or(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6707 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6708 struct bpf_reg_state *src_reg)
6709 {
6710 bool src_known = tnum_is_const(src_reg->var_off);
6711 bool dst_known = tnum_is_const(dst_reg->var_off);
6712 s64 smin_val = src_reg->smin_value;
6713 u64 umin_val = src_reg->umin_value;
6714
6715 if (src_known && dst_known) {
6716 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6717 return;
6718 }
6719
6720 /* We get our maximum from the var_off, and our minimum is the
6721 * maximum of the operands' minima
6722 */
6723 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6724 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6725 if (dst_reg->smin_value < 0 || smin_val < 0) {
6726 /* Lose signed bounds when ORing negative numbers,
6727 * ain't nobody got time for that.
6728 */
6729 dst_reg->smin_value = S64_MIN;
6730 dst_reg->smax_value = S64_MAX;
6731 } else {
6732 /* ORing two positives gives a positive, so safe to
6733 * cast result into s64.
6734 */
6735 dst_reg->smin_value = dst_reg->umin_value;
6736 dst_reg->smax_value = dst_reg->umax_value;
6737 }
6738 /* We may learn something more from the var_off */
6739 __update_reg_bounds(dst_reg);
6740 }
6741
scalar32_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6742 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6743 struct bpf_reg_state *src_reg)
6744 {
6745 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6746 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6747 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6748 s32 smin_val = src_reg->s32_min_value;
6749
6750 if (src_known && dst_known) {
6751 __mark_reg32_known(dst_reg, var32_off.value);
6752 return;
6753 }
6754
6755 /* We get both minimum and maximum from the var32_off. */
6756 dst_reg->u32_min_value = var32_off.value;
6757 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6758
6759 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6760 /* XORing two positive sign numbers gives a positive,
6761 * so safe to cast u32 result into s32.
6762 */
6763 dst_reg->s32_min_value = dst_reg->u32_min_value;
6764 dst_reg->s32_max_value = dst_reg->u32_max_value;
6765 } else {
6766 dst_reg->s32_min_value = S32_MIN;
6767 dst_reg->s32_max_value = S32_MAX;
6768 }
6769 }
6770
scalar_min_max_xor(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6771 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6772 struct bpf_reg_state *src_reg)
6773 {
6774 bool src_known = tnum_is_const(src_reg->var_off);
6775 bool dst_known = tnum_is_const(dst_reg->var_off);
6776 s64 smin_val = src_reg->smin_value;
6777
6778 if (src_known && dst_known) {
6779 /* dst_reg->var_off.value has been updated earlier */
6780 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6781 return;
6782 }
6783
6784 /* We get both minimum and maximum from the var_off. */
6785 dst_reg->umin_value = dst_reg->var_off.value;
6786 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6787
6788 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6789 /* XORing two positive sign numbers gives a positive,
6790 * so safe to cast u64 result into s64.
6791 */
6792 dst_reg->smin_value = dst_reg->umin_value;
6793 dst_reg->smax_value = dst_reg->umax_value;
6794 } else {
6795 dst_reg->smin_value = S64_MIN;
6796 dst_reg->smax_value = S64_MAX;
6797 }
6798
6799 __update_reg_bounds(dst_reg);
6800 }
6801
__scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6802 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6803 u64 umin_val, u64 umax_val)
6804 {
6805 /* We lose all sign bit information (except what we can pick
6806 * up from var_off)
6807 */
6808 dst_reg->s32_min_value = S32_MIN;
6809 dst_reg->s32_max_value = S32_MAX;
6810 /* If we might shift our top bit out, then we know nothing */
6811 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6812 dst_reg->u32_min_value = 0;
6813 dst_reg->u32_max_value = U32_MAX;
6814 } else {
6815 dst_reg->u32_min_value <<= umin_val;
6816 dst_reg->u32_max_value <<= umax_val;
6817 }
6818 }
6819
scalar32_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6820 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6821 struct bpf_reg_state *src_reg)
6822 {
6823 u32 umax_val = src_reg->u32_max_value;
6824 u32 umin_val = src_reg->u32_min_value;
6825 /* u32 alu operation will zext upper bits */
6826 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6827
6828 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6829 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6830 /* Not required but being careful mark reg64 bounds as unknown so
6831 * that we are forced to pick them up from tnum and zext later and
6832 * if some path skips this step we are still safe.
6833 */
6834 __mark_reg64_unbounded(dst_reg);
6835 __update_reg32_bounds(dst_reg);
6836 }
6837
__scalar64_min_max_lsh(struct bpf_reg_state * dst_reg,u64 umin_val,u64 umax_val)6838 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6839 u64 umin_val, u64 umax_val)
6840 {
6841 /* Special case <<32 because it is a common compiler pattern to sign
6842 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6843 * positive we know this shift will also be positive so we can track
6844 * bounds correctly. Otherwise we lose all sign bit information except
6845 * what we can pick up from var_off. Perhaps we can generalize this
6846 * later to shifts of any length.
6847 */
6848 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6849 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6850 else
6851 dst_reg->smax_value = S64_MAX;
6852
6853 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6854 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6855 else
6856 dst_reg->smin_value = S64_MIN;
6857
6858 /* If we might shift our top bit out, then we know nothing */
6859 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6860 dst_reg->umin_value = 0;
6861 dst_reg->umax_value = U64_MAX;
6862 } else {
6863 dst_reg->umin_value <<= umin_val;
6864 dst_reg->umax_value <<= umax_val;
6865 }
6866 }
6867
scalar_min_max_lsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6868 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6869 struct bpf_reg_state *src_reg)
6870 {
6871 u64 umax_val = src_reg->umax_value;
6872 u64 umin_val = src_reg->umin_value;
6873
6874 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6875 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6876 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6877
6878 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6879 /* We may learn something more from the var_off */
6880 __update_reg_bounds(dst_reg);
6881 }
6882
scalar32_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6883 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6884 struct bpf_reg_state *src_reg)
6885 {
6886 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6887 u32 umax_val = src_reg->u32_max_value;
6888 u32 umin_val = src_reg->u32_min_value;
6889
6890 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6891 * be negative, then either:
6892 * 1) src_reg might be zero, so the sign bit of the result is
6893 * unknown, so we lose our signed bounds
6894 * 2) it's known negative, thus the unsigned bounds capture the
6895 * signed bounds
6896 * 3) the signed bounds cross zero, so they tell us nothing
6897 * about the result
6898 * If the value in dst_reg is known nonnegative, then again the
6899 * unsigned bounts capture the signed bounds.
6900 * Thus, in all cases it suffices to blow away our signed bounds
6901 * and rely on inferring new ones from the unsigned bounds and
6902 * var_off of the result.
6903 */
6904 dst_reg->s32_min_value = S32_MIN;
6905 dst_reg->s32_max_value = S32_MAX;
6906
6907 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6908 dst_reg->u32_min_value >>= umax_val;
6909 dst_reg->u32_max_value >>= umin_val;
6910
6911 __mark_reg64_unbounded(dst_reg);
6912 __update_reg32_bounds(dst_reg);
6913 }
6914
scalar_min_max_rsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6915 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6916 struct bpf_reg_state *src_reg)
6917 {
6918 u64 umax_val = src_reg->umax_value;
6919 u64 umin_val = src_reg->umin_value;
6920
6921 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6922 * be negative, then either:
6923 * 1) src_reg might be zero, so the sign bit of the result is
6924 * unknown, so we lose our signed bounds
6925 * 2) it's known negative, thus the unsigned bounds capture the
6926 * signed bounds
6927 * 3) the signed bounds cross zero, so they tell us nothing
6928 * about the result
6929 * If the value in dst_reg is known nonnegative, then again the
6930 * unsigned bounts capture the signed bounds.
6931 * Thus, in all cases it suffices to blow away our signed bounds
6932 * and rely on inferring new ones from the unsigned bounds and
6933 * var_off of the result.
6934 */
6935 dst_reg->smin_value = S64_MIN;
6936 dst_reg->smax_value = S64_MAX;
6937 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6938 dst_reg->umin_value >>= umax_val;
6939 dst_reg->umax_value >>= umin_val;
6940
6941 /* Its not easy to operate on alu32 bounds here because it depends
6942 * on bits being shifted in. Take easy way out and mark unbounded
6943 * so we can recalculate later from tnum.
6944 */
6945 __mark_reg32_unbounded(dst_reg);
6946 __update_reg_bounds(dst_reg);
6947 }
6948
scalar32_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6949 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6950 struct bpf_reg_state *src_reg)
6951 {
6952 u64 umin_val = src_reg->u32_min_value;
6953
6954 /* Upon reaching here, src_known is true and
6955 * umax_val is equal to umin_val.
6956 */
6957 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6958 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
6959
6960 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6961
6962 /* blow away the dst_reg umin_value/umax_value and rely on
6963 * dst_reg var_off to refine the result.
6964 */
6965 dst_reg->u32_min_value = 0;
6966 dst_reg->u32_max_value = U32_MAX;
6967
6968 __mark_reg64_unbounded(dst_reg);
6969 __update_reg32_bounds(dst_reg);
6970 }
6971
scalar_min_max_arsh(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg)6972 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6973 struct bpf_reg_state *src_reg)
6974 {
6975 u64 umin_val = src_reg->umin_value;
6976
6977 /* Upon reaching here, src_known is true and umax_val is equal
6978 * to umin_val.
6979 */
6980 dst_reg->smin_value >>= umin_val;
6981 dst_reg->smax_value >>= umin_val;
6982
6983 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
6984
6985 /* blow away the dst_reg umin_value/umax_value and rely on
6986 * dst_reg var_off to refine the result.
6987 */
6988 dst_reg->umin_value = 0;
6989 dst_reg->umax_value = U64_MAX;
6990
6991 /* Its not easy to operate on alu32 bounds here because it depends
6992 * on bits being shifted in from upper 32-bits. Take easy way out
6993 * and mark unbounded so we can recalculate later from tnum.
6994 */
6995 __mark_reg32_unbounded(dst_reg);
6996 __update_reg_bounds(dst_reg);
6997 }
6998
6999 /* WARNING: This function does calculations on 64-bit values, but the actual
7000 * execution may occur on 32-bit values. Therefore, things like bitshifts
7001 * need extra checks in the 32-bit case.
7002 */
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)7003 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7004 struct bpf_insn *insn,
7005 struct bpf_reg_state *dst_reg,
7006 struct bpf_reg_state src_reg)
7007 {
7008 struct bpf_reg_state *regs = cur_regs(env);
7009 u8 opcode = BPF_OP(insn->code);
7010 bool src_known;
7011 s64 smin_val, smax_val;
7012 u64 umin_val, umax_val;
7013 s32 s32_min_val, s32_max_val;
7014 u32 u32_min_val, u32_max_val;
7015 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
7016 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
7017 int ret;
7018
7019 smin_val = src_reg.smin_value;
7020 smax_val = src_reg.smax_value;
7021 umin_val = src_reg.umin_value;
7022 umax_val = src_reg.umax_value;
7023
7024 s32_min_val = src_reg.s32_min_value;
7025 s32_max_val = src_reg.s32_max_value;
7026 u32_min_val = src_reg.u32_min_value;
7027 u32_max_val = src_reg.u32_max_value;
7028
7029 if (alu32) {
7030 src_known = tnum_subreg_is_const(src_reg.var_off);
7031 if ((src_known &&
7032 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7033 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7034 /* Taint dst register if offset had invalid bounds
7035 * derived from e.g. dead branches.
7036 */
7037 __mark_reg_unknown(env, dst_reg);
7038 return 0;
7039 }
7040 } else {
7041 src_known = tnum_is_const(src_reg.var_off);
7042 if ((src_known &&
7043 (smin_val != smax_val || umin_val != umax_val)) ||
7044 smin_val > smax_val || umin_val > umax_val) {
7045 /* Taint dst register if offset had invalid bounds
7046 * derived from e.g. dead branches.
7047 */
7048 __mark_reg_unknown(env, dst_reg);
7049 return 0;
7050 }
7051 }
7052
7053 if (!src_known &&
7054 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
7055 __mark_reg_unknown(env, dst_reg);
7056 return 0;
7057 }
7058
7059 if (sanitize_needed(opcode)) {
7060 ret = sanitize_val_alu(env, insn);
7061 if (ret < 0)
7062 return sanitize_err(env, insn, ret, NULL, NULL);
7063 }
7064
7065 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7066 * There are two classes of instructions: The first class we track both
7067 * alu32 and alu64 sign/unsigned bounds independently this provides the
7068 * greatest amount of precision when alu operations are mixed with jmp32
7069 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7070 * and BPF_OR. This is possible because these ops have fairly easy to
7071 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7072 * See alu32 verifier tests for examples. The second class of
7073 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7074 * with regards to tracking sign/unsigned bounds because the bits may
7075 * cross subreg boundaries in the alu64 case. When this happens we mark
7076 * the reg unbounded in the subreg bound space and use the resulting
7077 * tnum to calculate an approximation of the sign/unsigned bounds.
7078 */
7079 switch (opcode) {
7080 case BPF_ADD:
7081 scalar32_min_max_add(dst_reg, &src_reg);
7082 scalar_min_max_add(dst_reg, &src_reg);
7083 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
7084 break;
7085 case BPF_SUB:
7086 scalar32_min_max_sub(dst_reg, &src_reg);
7087 scalar_min_max_sub(dst_reg, &src_reg);
7088 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
7089 break;
7090 case BPF_MUL:
7091 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7092 scalar32_min_max_mul(dst_reg, &src_reg);
7093 scalar_min_max_mul(dst_reg, &src_reg);
7094 break;
7095 case BPF_AND:
7096 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7097 scalar32_min_max_and(dst_reg, &src_reg);
7098 scalar_min_max_and(dst_reg, &src_reg);
7099 break;
7100 case BPF_OR:
7101 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7102 scalar32_min_max_or(dst_reg, &src_reg);
7103 scalar_min_max_or(dst_reg, &src_reg);
7104 break;
7105 case BPF_XOR:
7106 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7107 scalar32_min_max_xor(dst_reg, &src_reg);
7108 scalar_min_max_xor(dst_reg, &src_reg);
7109 break;
7110 case BPF_LSH:
7111 if (umax_val >= insn_bitness) {
7112 /* Shifts greater than 31 or 63 are undefined.
7113 * This includes shifts by a negative number.
7114 */
7115 mark_reg_unknown(env, regs, insn->dst_reg);
7116 break;
7117 }
7118 if (alu32)
7119 scalar32_min_max_lsh(dst_reg, &src_reg);
7120 else
7121 scalar_min_max_lsh(dst_reg, &src_reg);
7122 break;
7123 case BPF_RSH:
7124 if (umax_val >= insn_bitness) {
7125 /* Shifts greater than 31 or 63 are undefined.
7126 * This includes shifts by a negative number.
7127 */
7128 mark_reg_unknown(env, regs, insn->dst_reg);
7129 break;
7130 }
7131 if (alu32)
7132 scalar32_min_max_rsh(dst_reg, &src_reg);
7133 else
7134 scalar_min_max_rsh(dst_reg, &src_reg);
7135 break;
7136 case BPF_ARSH:
7137 if (umax_val >= insn_bitness) {
7138 /* Shifts greater than 31 or 63 are undefined.
7139 * This includes shifts by a negative number.
7140 */
7141 mark_reg_unknown(env, regs, insn->dst_reg);
7142 break;
7143 }
7144 if (alu32)
7145 scalar32_min_max_arsh(dst_reg, &src_reg);
7146 else
7147 scalar_min_max_arsh(dst_reg, &src_reg);
7148 break;
7149 default:
7150 mark_reg_unknown(env, regs, insn->dst_reg);
7151 break;
7152 }
7153
7154 /* ALU32 ops are zero extended into 64bit register */
7155 if (alu32)
7156 zext_32_to_64(dst_reg);
7157 reg_bounds_sync(dst_reg);
7158 return 0;
7159 }
7160
7161 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7162 * and var_off.
7163 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)7164 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7165 struct bpf_insn *insn)
7166 {
7167 struct bpf_verifier_state *vstate = env->cur_state;
7168 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7169 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
7170 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7171 u8 opcode = BPF_OP(insn->code);
7172 int err;
7173
7174 dst_reg = ®s[insn->dst_reg];
7175 src_reg = NULL;
7176 if (dst_reg->type != SCALAR_VALUE)
7177 ptr_reg = dst_reg;
7178 else
7179 /* Make sure ID is cleared otherwise dst_reg min/max could be
7180 * incorrectly propagated into other registers by find_equal_scalars()
7181 */
7182 dst_reg->id = 0;
7183 if (BPF_SRC(insn->code) == BPF_X) {
7184 src_reg = ®s[insn->src_reg];
7185 if (src_reg->type != SCALAR_VALUE) {
7186 if (dst_reg->type != SCALAR_VALUE) {
7187 /* Combining two pointers by any ALU op yields
7188 * an arbitrary scalar. Disallow all math except
7189 * pointer subtraction
7190 */
7191 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7192 mark_reg_unknown(env, regs, insn->dst_reg);
7193 return 0;
7194 }
7195 verbose(env, "R%d pointer %s pointer prohibited\n",
7196 insn->dst_reg,
7197 bpf_alu_string[opcode >> 4]);
7198 return -EACCES;
7199 } else {
7200 /* scalar += pointer
7201 * This is legal, but we have to reverse our
7202 * src/dest handling in computing the range
7203 */
7204 err = mark_chain_precision(env, insn->dst_reg);
7205 if (err)
7206 return err;
7207 return adjust_ptr_min_max_vals(env, insn,
7208 src_reg, dst_reg);
7209 }
7210 } else if (ptr_reg) {
7211 /* pointer += scalar */
7212 err = mark_chain_precision(env, insn->src_reg);
7213 if (err)
7214 return err;
7215 return adjust_ptr_min_max_vals(env, insn,
7216 dst_reg, src_reg);
7217 } else if (dst_reg->precise) {
7218 /* if dst_reg is precise, src_reg should be precise as well */
7219 err = mark_chain_precision(env, insn->src_reg);
7220 if (err)
7221 return err;
7222 }
7223 } else {
7224 /* Pretend the src is a reg with a known value, since we only
7225 * need to be able to read from this state.
7226 */
7227 off_reg.type = SCALAR_VALUE;
7228 __mark_reg_known(&off_reg, insn->imm);
7229 src_reg = &off_reg;
7230 if (ptr_reg) /* pointer += K */
7231 return adjust_ptr_min_max_vals(env, insn,
7232 ptr_reg, src_reg);
7233 }
7234
7235 /* Got here implies adding two SCALAR_VALUEs */
7236 if (WARN_ON_ONCE(ptr_reg)) {
7237 print_verifier_state(env, state);
7238 verbose(env, "verifier internal error: unexpected ptr_reg\n");
7239 return -EINVAL;
7240 }
7241 if (WARN_ON(!src_reg)) {
7242 print_verifier_state(env, state);
7243 verbose(env, "verifier internal error: no src_reg\n");
7244 return -EINVAL;
7245 }
7246 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
7247 }
7248
7249 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)7250 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
7251 {
7252 struct bpf_reg_state *regs = cur_regs(env);
7253 u8 opcode = BPF_OP(insn->code);
7254 int err;
7255
7256 if (opcode == BPF_END || opcode == BPF_NEG) {
7257 if (opcode == BPF_NEG) {
7258 if (BPF_SRC(insn->code) != 0 ||
7259 insn->src_reg != BPF_REG_0 ||
7260 insn->off != 0 || insn->imm != 0) {
7261 verbose(env, "BPF_NEG uses reserved fields\n");
7262 return -EINVAL;
7263 }
7264 } else {
7265 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
7266 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7267 BPF_CLASS(insn->code) == BPF_ALU64) {
7268 verbose(env, "BPF_END uses reserved fields\n");
7269 return -EINVAL;
7270 }
7271 }
7272
7273 /* check src operand */
7274 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7275 if (err)
7276 return err;
7277
7278 if (is_pointer_value(env, insn->dst_reg)) {
7279 verbose(env, "R%d pointer arithmetic prohibited\n",
7280 insn->dst_reg);
7281 return -EACCES;
7282 }
7283
7284 /* check dest operand */
7285 err = check_reg_arg(env, insn->dst_reg, DST_OP);
7286 if (err)
7287 return err;
7288
7289 } else if (opcode == BPF_MOV) {
7290
7291 if (BPF_SRC(insn->code) == BPF_X) {
7292 if (insn->imm != 0 || insn->off != 0) {
7293 verbose(env, "BPF_MOV uses reserved fields\n");
7294 return -EINVAL;
7295 }
7296
7297 /* check src operand */
7298 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7299 if (err)
7300 return err;
7301 } else {
7302 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7303 verbose(env, "BPF_MOV uses reserved fields\n");
7304 return -EINVAL;
7305 }
7306 }
7307
7308 /* check dest operand, mark as required later */
7309 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7310 if (err)
7311 return err;
7312
7313 if (BPF_SRC(insn->code) == BPF_X) {
7314 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7315 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7316
7317 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7318 /* case: R1 = R2
7319 * copy register state to dest reg
7320 */
7321 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7322 /* Assign src and dst registers the same ID
7323 * that will be used by find_equal_scalars()
7324 * to propagate min/max range.
7325 */
7326 src_reg->id = ++env->id_gen;
7327 copy_register_state(dst_reg, src_reg);
7328 dst_reg->live |= REG_LIVE_WRITTEN;
7329 dst_reg->subreg_def = DEF_NOT_SUBREG;
7330 } else {
7331 /* R1 = (u32) R2 */
7332 if (is_pointer_value(env, insn->src_reg)) {
7333 verbose(env,
7334 "R%d partial copy of pointer\n",
7335 insn->src_reg);
7336 return -EACCES;
7337 } else if (src_reg->type == SCALAR_VALUE) {
7338 copy_register_state(dst_reg, src_reg);
7339 /* Make sure ID is cleared otherwise
7340 * dst_reg min/max could be incorrectly
7341 * propagated into src_reg by find_equal_scalars()
7342 */
7343 dst_reg->id = 0;
7344 dst_reg->live |= REG_LIVE_WRITTEN;
7345 dst_reg->subreg_def = env->insn_idx + 1;
7346 } else {
7347 mark_reg_unknown(env, regs,
7348 insn->dst_reg);
7349 }
7350 zext_32_to_64(dst_reg);
7351 reg_bounds_sync(dst_reg);
7352 }
7353 } else {
7354 /* case: R = imm
7355 * remember the value we stored into this reg
7356 */
7357 /* clear any state __mark_reg_known doesn't set */
7358 mark_reg_unknown(env, regs, insn->dst_reg);
7359 regs[insn->dst_reg].type = SCALAR_VALUE;
7360 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7361 __mark_reg_known(regs + insn->dst_reg,
7362 insn->imm);
7363 } else {
7364 __mark_reg_known(regs + insn->dst_reg,
7365 (u32)insn->imm);
7366 }
7367 }
7368
7369 } else if (opcode > BPF_END) {
7370 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
7371 return -EINVAL;
7372
7373 } else { /* all other ALU ops: and, sub, xor, add, ... */
7374
7375 if (BPF_SRC(insn->code) == BPF_X) {
7376 if (insn->imm != 0 || insn->off != 0) {
7377 verbose(env, "BPF_ALU uses reserved fields\n");
7378 return -EINVAL;
7379 }
7380 /* check src1 operand */
7381 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7382 if (err)
7383 return err;
7384 } else {
7385 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
7386 verbose(env, "BPF_ALU uses reserved fields\n");
7387 return -EINVAL;
7388 }
7389 }
7390
7391 /* check src2 operand */
7392 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7393 if (err)
7394 return err;
7395
7396 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7397 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
7398 verbose(env, "div by zero\n");
7399 return -EINVAL;
7400 }
7401
7402 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7403 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7404 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7405
7406 if (insn->imm < 0 || insn->imm >= size) {
7407 verbose(env, "invalid shift %d\n", insn->imm);
7408 return -EINVAL;
7409 }
7410 }
7411
7412 /* check dest operand */
7413 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7414 if (err)
7415 return err;
7416
7417 return adjust_reg_min_max_vals(env, insn);
7418 }
7419
7420 return 0;
7421 }
7422
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)7423 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
7424 struct bpf_reg_state *dst_reg,
7425 enum bpf_reg_type type,
7426 bool range_right_open)
7427 {
7428 struct bpf_func_state *state;
7429 struct bpf_reg_state *reg;
7430 int new_range;
7431
7432 if (dst_reg->off < 0 ||
7433 (dst_reg->off == 0 && range_right_open))
7434 /* This doesn't give us any range */
7435 return;
7436
7437 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7438 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
7439 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7440 * than pkt_end, but that's because it's also less than pkt.
7441 */
7442 return;
7443
7444 new_range = dst_reg->off;
7445 if (range_right_open)
7446 new_range++;
7447
7448 /* Examples for register markings:
7449 *
7450 * pkt_data in dst register:
7451 *
7452 * r2 = r3;
7453 * r2 += 8;
7454 * if (r2 > pkt_end) goto <handle exception>
7455 * <access okay>
7456 *
7457 * r2 = r3;
7458 * r2 += 8;
7459 * if (r2 < pkt_end) goto <access okay>
7460 * <handle exception>
7461 *
7462 * Where:
7463 * r2 == dst_reg, pkt_end == src_reg
7464 * r2=pkt(id=n,off=8,r=0)
7465 * r3=pkt(id=n,off=0,r=0)
7466 *
7467 * pkt_data in src register:
7468 *
7469 * r2 = r3;
7470 * r2 += 8;
7471 * if (pkt_end >= r2) goto <access okay>
7472 * <handle exception>
7473 *
7474 * r2 = r3;
7475 * r2 += 8;
7476 * if (pkt_end <= r2) goto <handle exception>
7477 * <access okay>
7478 *
7479 * Where:
7480 * pkt_end == dst_reg, r2 == src_reg
7481 * r2=pkt(id=n,off=8,r=0)
7482 * r3=pkt(id=n,off=0,r=0)
7483 *
7484 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
7485 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7486 * and [r3, r3 + 8-1) respectively is safe to access depending on
7487 * the check.
7488 */
7489
7490 /* If our ids match, then we must have the same max_value. And we
7491 * don't care about the other reg's fixed offset, since if it's too big
7492 * the range won't allow anything.
7493 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7494 */
7495 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
7496 if (reg->type == type && reg->id == dst_reg->id)
7497 /* keep the maximum range already checked */
7498 reg->range = max(reg->range, new_range);
7499 }));
7500 }
7501
is_branch32_taken(struct bpf_reg_state * reg,u32 val,u8 opcode)7502 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
7503 {
7504 struct tnum subreg = tnum_subreg(reg->var_off);
7505 s32 sval = (s32)val;
7506
7507 switch (opcode) {
7508 case BPF_JEQ:
7509 if (tnum_is_const(subreg))
7510 return !!tnum_equals_const(subreg, val);
7511 break;
7512 case BPF_JNE:
7513 if (tnum_is_const(subreg))
7514 return !tnum_equals_const(subreg, val);
7515 break;
7516 case BPF_JSET:
7517 if ((~subreg.mask & subreg.value) & val)
7518 return 1;
7519 if (!((subreg.mask | subreg.value) & val))
7520 return 0;
7521 break;
7522 case BPF_JGT:
7523 if (reg->u32_min_value > val)
7524 return 1;
7525 else if (reg->u32_max_value <= val)
7526 return 0;
7527 break;
7528 case BPF_JSGT:
7529 if (reg->s32_min_value > sval)
7530 return 1;
7531 else if (reg->s32_max_value <= sval)
7532 return 0;
7533 break;
7534 case BPF_JLT:
7535 if (reg->u32_max_value < val)
7536 return 1;
7537 else if (reg->u32_min_value >= val)
7538 return 0;
7539 break;
7540 case BPF_JSLT:
7541 if (reg->s32_max_value < sval)
7542 return 1;
7543 else if (reg->s32_min_value >= sval)
7544 return 0;
7545 break;
7546 case BPF_JGE:
7547 if (reg->u32_min_value >= val)
7548 return 1;
7549 else if (reg->u32_max_value < val)
7550 return 0;
7551 break;
7552 case BPF_JSGE:
7553 if (reg->s32_min_value >= sval)
7554 return 1;
7555 else if (reg->s32_max_value < sval)
7556 return 0;
7557 break;
7558 case BPF_JLE:
7559 if (reg->u32_max_value <= val)
7560 return 1;
7561 else if (reg->u32_min_value > val)
7562 return 0;
7563 break;
7564 case BPF_JSLE:
7565 if (reg->s32_max_value <= sval)
7566 return 1;
7567 else if (reg->s32_min_value > sval)
7568 return 0;
7569 break;
7570 }
7571
7572 return -1;
7573 }
7574
7575
is_branch64_taken(struct bpf_reg_state * reg,u64 val,u8 opcode)7576 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7577 {
7578 s64 sval = (s64)val;
7579
7580 switch (opcode) {
7581 case BPF_JEQ:
7582 if (tnum_is_const(reg->var_off))
7583 return !!tnum_equals_const(reg->var_off, val);
7584 break;
7585 case BPF_JNE:
7586 if (tnum_is_const(reg->var_off))
7587 return !tnum_equals_const(reg->var_off, val);
7588 break;
7589 case BPF_JSET:
7590 if ((~reg->var_off.mask & reg->var_off.value) & val)
7591 return 1;
7592 if (!((reg->var_off.mask | reg->var_off.value) & val))
7593 return 0;
7594 break;
7595 case BPF_JGT:
7596 if (reg->umin_value > val)
7597 return 1;
7598 else if (reg->umax_value <= val)
7599 return 0;
7600 break;
7601 case BPF_JSGT:
7602 if (reg->smin_value > sval)
7603 return 1;
7604 else if (reg->smax_value <= sval)
7605 return 0;
7606 break;
7607 case BPF_JLT:
7608 if (reg->umax_value < val)
7609 return 1;
7610 else if (reg->umin_value >= val)
7611 return 0;
7612 break;
7613 case BPF_JSLT:
7614 if (reg->smax_value < sval)
7615 return 1;
7616 else if (reg->smin_value >= sval)
7617 return 0;
7618 break;
7619 case BPF_JGE:
7620 if (reg->umin_value >= val)
7621 return 1;
7622 else if (reg->umax_value < val)
7623 return 0;
7624 break;
7625 case BPF_JSGE:
7626 if (reg->smin_value >= sval)
7627 return 1;
7628 else if (reg->smax_value < sval)
7629 return 0;
7630 break;
7631 case BPF_JLE:
7632 if (reg->umax_value <= val)
7633 return 1;
7634 else if (reg->umin_value > val)
7635 return 0;
7636 break;
7637 case BPF_JSLE:
7638 if (reg->smax_value <= sval)
7639 return 1;
7640 else if (reg->smin_value > sval)
7641 return 0;
7642 break;
7643 }
7644
7645 return -1;
7646 }
7647
7648 /* compute branch direction of the expression "if (reg opcode val) goto target;"
7649 * and return:
7650 * 1 - branch will be taken and "goto target" will be executed
7651 * 0 - branch will not be taken and fall-through to next insn
7652 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7653 * range [0,10]
7654 */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)7655 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7656 bool is_jmp32)
7657 {
7658 if (__is_pointer_value(false, reg)) {
7659 if (!reg_type_not_null(reg->type))
7660 return -1;
7661
7662 /* If pointer is valid tests against zero will fail so we can
7663 * use this to direct branch taken.
7664 */
7665 if (val != 0)
7666 return -1;
7667
7668 switch (opcode) {
7669 case BPF_JEQ:
7670 return 0;
7671 case BPF_JNE:
7672 return 1;
7673 default:
7674 return -1;
7675 }
7676 }
7677
7678 if (is_jmp32)
7679 return is_branch32_taken(reg, val, opcode);
7680 return is_branch64_taken(reg, val, opcode);
7681 }
7682
flip_opcode(u32 opcode)7683 static int flip_opcode(u32 opcode)
7684 {
7685 /* How can we transform "a <op> b" into "b <op> a"? */
7686 static const u8 opcode_flip[16] = {
7687 /* these stay the same */
7688 [BPF_JEQ >> 4] = BPF_JEQ,
7689 [BPF_JNE >> 4] = BPF_JNE,
7690 [BPF_JSET >> 4] = BPF_JSET,
7691 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7692 [BPF_JGE >> 4] = BPF_JLE,
7693 [BPF_JGT >> 4] = BPF_JLT,
7694 [BPF_JLE >> 4] = BPF_JGE,
7695 [BPF_JLT >> 4] = BPF_JGT,
7696 [BPF_JSGE >> 4] = BPF_JSLE,
7697 [BPF_JSGT >> 4] = BPF_JSLT,
7698 [BPF_JSLE >> 4] = BPF_JSGE,
7699 [BPF_JSLT >> 4] = BPF_JSGT
7700 };
7701 return opcode_flip[opcode >> 4];
7702 }
7703
is_pkt_ptr_branch_taken(struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,u8 opcode)7704 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7705 struct bpf_reg_state *src_reg,
7706 u8 opcode)
7707 {
7708 struct bpf_reg_state *pkt;
7709
7710 if (src_reg->type == PTR_TO_PACKET_END) {
7711 pkt = dst_reg;
7712 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7713 pkt = src_reg;
7714 opcode = flip_opcode(opcode);
7715 } else {
7716 return -1;
7717 }
7718
7719 if (pkt->range >= 0)
7720 return -1;
7721
7722 switch (opcode) {
7723 case BPF_JLE:
7724 /* pkt <= pkt_end */
7725 fallthrough;
7726 case BPF_JGT:
7727 /* pkt > pkt_end */
7728 if (pkt->range == BEYOND_PKT_END)
7729 /* pkt has at last one extra byte beyond pkt_end */
7730 return opcode == BPF_JGT;
7731 break;
7732 case BPF_JLT:
7733 /* pkt < pkt_end */
7734 fallthrough;
7735 case BPF_JGE:
7736 /* pkt >= pkt_end */
7737 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7738 return opcode == BPF_JGE;
7739 break;
7740 }
7741 return -1;
7742 }
7743
7744 /* Adjusts the register min/max values in the case that the dst_reg is the
7745 * variable register that we are working on, and src_reg is a constant or we're
7746 * simply doing a BPF_K check.
7747 * In JEQ/JNE cases we also adjust the var_off values.
7748 */
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)7749 static void reg_set_min_max(struct bpf_reg_state *true_reg,
7750 struct bpf_reg_state *false_reg,
7751 u64 val, u32 val32,
7752 u8 opcode, bool is_jmp32)
7753 {
7754 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7755 struct tnum false_64off = false_reg->var_off;
7756 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7757 struct tnum true_64off = true_reg->var_off;
7758 s64 sval = (s64)val;
7759 s32 sval32 = (s32)val32;
7760
7761 /* If the dst_reg is a pointer, we can't learn anything about its
7762 * variable offset from the compare (unless src_reg were a pointer into
7763 * the same object, but we don't bother with that.
7764 * Since false_reg and true_reg have the same type by construction, we
7765 * only need to check one of them for pointerness.
7766 */
7767 if (__is_pointer_value(false, false_reg))
7768 return;
7769
7770 switch (opcode) {
7771 /* JEQ/JNE comparison doesn't change the register equivalence.
7772 *
7773 * r1 = r2;
7774 * if (r1 == 42) goto label;
7775 * ...
7776 * label: // here both r1 and r2 are known to be 42.
7777 *
7778 * Hence when marking register as known preserve it's ID.
7779 */
7780 case BPF_JEQ:
7781 if (is_jmp32) {
7782 __mark_reg32_known(true_reg, val32);
7783 true_32off = tnum_subreg(true_reg->var_off);
7784 } else {
7785 ___mark_reg_known(true_reg, val);
7786 true_64off = true_reg->var_off;
7787 }
7788 break;
7789 case BPF_JNE:
7790 if (is_jmp32) {
7791 __mark_reg32_known(false_reg, val32);
7792 false_32off = tnum_subreg(false_reg->var_off);
7793 } else {
7794 ___mark_reg_known(false_reg, val);
7795 false_64off = false_reg->var_off;
7796 }
7797 break;
7798 case BPF_JSET:
7799 if (is_jmp32) {
7800 false_32off = tnum_and(false_32off, tnum_const(~val32));
7801 if (is_power_of_2(val32))
7802 true_32off = tnum_or(true_32off,
7803 tnum_const(val32));
7804 } else {
7805 false_64off = tnum_and(false_64off, tnum_const(~val));
7806 if (is_power_of_2(val))
7807 true_64off = tnum_or(true_64off,
7808 tnum_const(val));
7809 }
7810 break;
7811 case BPF_JGE:
7812 case BPF_JGT:
7813 {
7814 if (is_jmp32) {
7815 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7816 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7817
7818 false_reg->u32_max_value = min(false_reg->u32_max_value,
7819 false_umax);
7820 true_reg->u32_min_value = max(true_reg->u32_min_value,
7821 true_umin);
7822 } else {
7823 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7824 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7825
7826 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7827 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7828 }
7829 break;
7830 }
7831 case BPF_JSGE:
7832 case BPF_JSGT:
7833 {
7834 if (is_jmp32) {
7835 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7836 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
7837
7838 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7839 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7840 } else {
7841 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7842 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7843
7844 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7845 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7846 }
7847 break;
7848 }
7849 case BPF_JLE:
7850 case BPF_JLT:
7851 {
7852 if (is_jmp32) {
7853 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7854 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7855
7856 false_reg->u32_min_value = max(false_reg->u32_min_value,
7857 false_umin);
7858 true_reg->u32_max_value = min(true_reg->u32_max_value,
7859 true_umax);
7860 } else {
7861 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7862 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7863
7864 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7865 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7866 }
7867 break;
7868 }
7869 case BPF_JSLE:
7870 case BPF_JSLT:
7871 {
7872 if (is_jmp32) {
7873 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7874 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
7875
7876 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7877 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7878 } else {
7879 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7880 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7881
7882 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7883 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7884 }
7885 break;
7886 }
7887 default:
7888 return;
7889 }
7890
7891 if (is_jmp32) {
7892 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7893 tnum_subreg(false_32off));
7894 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7895 tnum_subreg(true_32off));
7896 __reg_combine_32_into_64(false_reg);
7897 __reg_combine_32_into_64(true_reg);
7898 } else {
7899 false_reg->var_off = false_64off;
7900 true_reg->var_off = true_64off;
7901 __reg_combine_64_into_32(false_reg);
7902 __reg_combine_64_into_32(true_reg);
7903 }
7904 }
7905
7906 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
7907 * the variable reg.
7908 */
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)7909 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
7910 struct bpf_reg_state *false_reg,
7911 u64 val, u32 val32,
7912 u8 opcode, bool is_jmp32)
7913 {
7914 opcode = flip_opcode(opcode);
7915 /* This uses zero as "not present in table"; luckily the zero opcode,
7916 * BPF_JA, can't get here.
7917 */
7918 if (opcode)
7919 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
7920 }
7921
7922 /* 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)7923 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7924 struct bpf_reg_state *dst_reg)
7925 {
7926 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7927 dst_reg->umin_value);
7928 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7929 dst_reg->umax_value);
7930 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7931 dst_reg->smin_value);
7932 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7933 dst_reg->smax_value);
7934 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7935 dst_reg->var_off);
7936 reg_bounds_sync(src_reg);
7937 reg_bounds_sync(dst_reg);
7938 }
7939
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)7940 static void reg_combine_min_max(struct bpf_reg_state *true_src,
7941 struct bpf_reg_state *true_dst,
7942 struct bpf_reg_state *false_src,
7943 struct bpf_reg_state *false_dst,
7944 u8 opcode)
7945 {
7946 switch (opcode) {
7947 case BPF_JEQ:
7948 __reg_combine_min_max(true_src, true_dst);
7949 break;
7950 case BPF_JNE:
7951 __reg_combine_min_max(false_src, false_dst);
7952 break;
7953 }
7954 }
7955
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)7956 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7957 struct bpf_reg_state *reg, u32 id,
7958 bool is_null)
7959 {
7960 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7961 !WARN_ON_ONCE(!reg->id)) {
7962 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7963 !tnum_equals_const(reg->var_off, 0) ||
7964 reg->off)) {
7965 /* Old offset (both fixed and variable parts) should
7966 * have been known-zero, because we don't allow pointer
7967 * arithmetic on pointers that might be NULL. If we
7968 * see this happening, don't convert the register.
7969 */
7970 return;
7971 }
7972 if (is_null) {
7973 reg->type = SCALAR_VALUE;
7974 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
7975 const struct bpf_map *map = reg->map_ptr;
7976
7977 if (map->inner_map_meta) {
7978 reg->type = CONST_PTR_TO_MAP;
7979 reg->map_ptr = map->inner_map_meta;
7980 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
7981 reg->type = PTR_TO_XDP_SOCK;
7982 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
7983 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
7984 reg->type = PTR_TO_SOCKET;
7985 } else {
7986 reg->type = PTR_TO_MAP_VALUE;
7987 }
7988 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
7989 reg->type = PTR_TO_SOCKET;
7990 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
7991 reg->type = PTR_TO_SOCK_COMMON;
7992 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
7993 reg->type = PTR_TO_TCP_SOCK;
7994 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) {
7995 reg->type = PTR_TO_BTF_ID;
7996 } else if (reg->type == PTR_TO_MEM_OR_NULL) {
7997 reg->type = PTR_TO_MEM;
7998 } else if (reg->type == PTR_TO_RDONLY_BUF_OR_NULL) {
7999 reg->type = PTR_TO_RDONLY_BUF;
8000 } else if (reg->type == PTR_TO_RDWR_BUF_OR_NULL) {
8001 reg->type = PTR_TO_RDWR_BUF;
8002 }
8003 if (is_null) {
8004 /* We don't need id and ref_obj_id from this point
8005 * onwards anymore, thus we should better reset it,
8006 * so that state pruning has chances to take effect.
8007 */
8008 reg->id = 0;
8009 reg->ref_obj_id = 0;
8010 } else if (!reg_may_point_to_spin_lock(reg)) {
8011 /* For not-NULL ptr, reg->ref_obj_id will be reset
8012 * in release_reference().
8013 *
8014 * reg->id is still used by spin_lock ptr. Other
8015 * than spin_lock ptr type, reg->id can be reset.
8016 */
8017 reg->id = 0;
8018 }
8019 }
8020 }
8021
8022 /* The logic is similar to find_good_pkt_pointers(), both could eventually
8023 * be folded together at some point.
8024 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)8025 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8026 bool is_null)
8027 {
8028 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8029 struct bpf_reg_state *regs = state->regs, *reg;
8030 u32 ref_obj_id = regs[regno].ref_obj_id;
8031 u32 id = regs[regno].id;
8032
8033 if (ref_obj_id && ref_obj_id == id && is_null)
8034 /* regs[regno] is in the " == NULL" branch.
8035 * No one could have freed the reference state before
8036 * doing the NULL check.
8037 */
8038 WARN_ON_ONCE(release_reference_state(state, id));
8039
8040 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8041 mark_ptr_or_null_reg(state, reg, id, is_null);
8042 }));
8043 }
8044
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)8045 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8046 struct bpf_reg_state *dst_reg,
8047 struct bpf_reg_state *src_reg,
8048 struct bpf_verifier_state *this_branch,
8049 struct bpf_verifier_state *other_branch)
8050 {
8051 if (BPF_SRC(insn->code) != BPF_X)
8052 return false;
8053
8054 /* Pointers are always 64-bit. */
8055 if (BPF_CLASS(insn->code) == BPF_JMP32)
8056 return false;
8057
8058 switch (BPF_OP(insn->code)) {
8059 case BPF_JGT:
8060 if ((dst_reg->type == PTR_TO_PACKET &&
8061 src_reg->type == PTR_TO_PACKET_END) ||
8062 (dst_reg->type == PTR_TO_PACKET_META &&
8063 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8064 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8065 find_good_pkt_pointers(this_branch, dst_reg,
8066 dst_reg->type, false);
8067 mark_pkt_end(other_branch, insn->dst_reg, true);
8068 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8069 src_reg->type == PTR_TO_PACKET) ||
8070 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8071 src_reg->type == PTR_TO_PACKET_META)) {
8072 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8073 find_good_pkt_pointers(other_branch, src_reg,
8074 src_reg->type, true);
8075 mark_pkt_end(this_branch, insn->src_reg, false);
8076 } else {
8077 return false;
8078 }
8079 break;
8080 case BPF_JLT:
8081 if ((dst_reg->type == PTR_TO_PACKET &&
8082 src_reg->type == PTR_TO_PACKET_END) ||
8083 (dst_reg->type == PTR_TO_PACKET_META &&
8084 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8085 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8086 find_good_pkt_pointers(other_branch, dst_reg,
8087 dst_reg->type, true);
8088 mark_pkt_end(this_branch, insn->dst_reg, false);
8089 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8090 src_reg->type == PTR_TO_PACKET) ||
8091 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8092 src_reg->type == PTR_TO_PACKET_META)) {
8093 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8094 find_good_pkt_pointers(this_branch, src_reg,
8095 src_reg->type, false);
8096 mark_pkt_end(other_branch, insn->src_reg, true);
8097 } else {
8098 return false;
8099 }
8100 break;
8101 case BPF_JGE:
8102 if ((dst_reg->type == PTR_TO_PACKET &&
8103 src_reg->type == PTR_TO_PACKET_END) ||
8104 (dst_reg->type == PTR_TO_PACKET_META &&
8105 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8106 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8107 find_good_pkt_pointers(this_branch, dst_reg,
8108 dst_reg->type, true);
8109 mark_pkt_end(other_branch, insn->dst_reg, false);
8110 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8111 src_reg->type == PTR_TO_PACKET) ||
8112 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8113 src_reg->type == PTR_TO_PACKET_META)) {
8114 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8115 find_good_pkt_pointers(other_branch, src_reg,
8116 src_reg->type, false);
8117 mark_pkt_end(this_branch, insn->src_reg, true);
8118 } else {
8119 return false;
8120 }
8121 break;
8122 case BPF_JLE:
8123 if ((dst_reg->type == PTR_TO_PACKET &&
8124 src_reg->type == PTR_TO_PACKET_END) ||
8125 (dst_reg->type == PTR_TO_PACKET_META &&
8126 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8127 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8128 find_good_pkt_pointers(other_branch, dst_reg,
8129 dst_reg->type, false);
8130 mark_pkt_end(this_branch, insn->dst_reg, true);
8131 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8132 src_reg->type == PTR_TO_PACKET) ||
8133 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8134 src_reg->type == PTR_TO_PACKET_META)) {
8135 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8136 find_good_pkt_pointers(this_branch, src_reg,
8137 src_reg->type, true);
8138 mark_pkt_end(other_branch, insn->src_reg, false);
8139 } else {
8140 return false;
8141 }
8142 break;
8143 default:
8144 return false;
8145 }
8146
8147 return true;
8148 }
8149
find_equal_scalars(struct bpf_verifier_state * vstate,struct bpf_reg_state * known_reg)8150 static void find_equal_scalars(struct bpf_verifier_state *vstate,
8151 struct bpf_reg_state *known_reg)
8152 {
8153 struct bpf_func_state *state;
8154 struct bpf_reg_state *reg;
8155
8156 bpf_for_each_reg_in_vstate(vstate, state, reg, ({
8157 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8158 copy_register_state(reg, known_reg);
8159 }));
8160 }
8161
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)8162 static int check_cond_jmp_op(struct bpf_verifier_env *env,
8163 struct bpf_insn *insn, int *insn_idx)
8164 {
8165 struct bpf_verifier_state *this_branch = env->cur_state;
8166 struct bpf_verifier_state *other_branch;
8167 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
8168 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
8169 u8 opcode = BPF_OP(insn->code);
8170 bool is_jmp32;
8171 int pred = -1;
8172 int err;
8173
8174 /* Only conditional jumps are expected to reach here. */
8175 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8176 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
8177 return -EINVAL;
8178 }
8179
8180 if (BPF_SRC(insn->code) == BPF_X) {
8181 if (insn->imm != 0) {
8182 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8183 return -EINVAL;
8184 }
8185
8186 /* check src1 operand */
8187 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8188 if (err)
8189 return err;
8190
8191 if (is_pointer_value(env, insn->src_reg)) {
8192 verbose(env, "R%d pointer comparison prohibited\n",
8193 insn->src_reg);
8194 return -EACCES;
8195 }
8196 src_reg = ®s[insn->src_reg];
8197 } else {
8198 if (insn->src_reg != BPF_REG_0) {
8199 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
8200 return -EINVAL;
8201 }
8202 }
8203
8204 /* check src2 operand */
8205 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
8206 if (err)
8207 return err;
8208
8209 dst_reg = ®s[insn->dst_reg];
8210 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
8211
8212 if (BPF_SRC(insn->code) == BPF_K) {
8213 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8214 } else if (src_reg->type == SCALAR_VALUE &&
8215 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8216 pred = is_branch_taken(dst_reg,
8217 tnum_subreg(src_reg->var_off).value,
8218 opcode,
8219 is_jmp32);
8220 } else if (src_reg->type == SCALAR_VALUE &&
8221 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8222 pred = is_branch_taken(dst_reg,
8223 src_reg->var_off.value,
8224 opcode,
8225 is_jmp32);
8226 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8227 reg_is_pkt_pointer_any(src_reg) &&
8228 !is_jmp32) {
8229 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
8230 }
8231
8232 if (pred >= 0) {
8233 /* If we get here with a dst_reg pointer type it is because
8234 * above is_branch_taken() special cased the 0 comparison.
8235 */
8236 if (!__is_pointer_value(false, dst_reg))
8237 err = mark_chain_precision(env, insn->dst_reg);
8238 if (BPF_SRC(insn->code) == BPF_X && !err &&
8239 !__is_pointer_value(false, src_reg))
8240 err = mark_chain_precision(env, insn->src_reg);
8241 if (err)
8242 return err;
8243 }
8244
8245 if (pred == 1) {
8246 /* Only follow the goto, ignore fall-through. If needed, push
8247 * the fall-through branch for simulation under speculative
8248 * execution.
8249 */
8250 if (!env->bypass_spec_v1 &&
8251 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8252 *insn_idx))
8253 return -EFAULT;
8254 *insn_idx += insn->off;
8255 return 0;
8256 } else if (pred == 0) {
8257 /* Only follow the fall-through branch, since that's where the
8258 * program will go. If needed, push the goto branch for
8259 * simulation under speculative execution.
8260 */
8261 if (!env->bypass_spec_v1 &&
8262 !sanitize_speculative_path(env, insn,
8263 *insn_idx + insn->off + 1,
8264 *insn_idx))
8265 return -EFAULT;
8266 return 0;
8267 }
8268
8269 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8270 false);
8271 if (!other_branch)
8272 return -EFAULT;
8273 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
8274
8275 /* detect if we are comparing against a constant value so we can adjust
8276 * our min/max values for our dst register.
8277 * this is only legit if both are scalars (or pointers to the same
8278 * object, I suppose, but we don't support that right now), because
8279 * otherwise the different base pointers mean the offsets aren't
8280 * comparable.
8281 */
8282 if (BPF_SRC(insn->code) == BPF_X) {
8283 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
8284
8285 if (dst_reg->type == SCALAR_VALUE &&
8286 src_reg->type == SCALAR_VALUE) {
8287 if (tnum_is_const(src_reg->var_off) ||
8288 (is_jmp32 &&
8289 tnum_is_const(tnum_subreg(src_reg->var_off))))
8290 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8291 dst_reg,
8292 src_reg->var_off.value,
8293 tnum_subreg(src_reg->var_off).value,
8294 opcode, is_jmp32);
8295 else if (tnum_is_const(dst_reg->var_off) ||
8296 (is_jmp32 &&
8297 tnum_is_const(tnum_subreg(dst_reg->var_off))))
8298 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
8299 src_reg,
8300 dst_reg->var_off.value,
8301 tnum_subreg(dst_reg->var_off).value,
8302 opcode, is_jmp32);
8303 else if (!is_jmp32 &&
8304 (opcode == BPF_JEQ || opcode == BPF_JNE))
8305 /* Comparing for equality, we can combine knowledge */
8306 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8307 &other_branch_regs[insn->dst_reg],
8308 src_reg, dst_reg, opcode);
8309 if (src_reg->id &&
8310 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
8311 find_equal_scalars(this_branch, src_reg);
8312 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8313 }
8314
8315 }
8316 } else if (dst_reg->type == SCALAR_VALUE) {
8317 reg_set_min_max(&other_branch_regs[insn->dst_reg],
8318 dst_reg, insn->imm, (u32)insn->imm,
8319 opcode, is_jmp32);
8320 }
8321
8322 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8323 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
8324 find_equal_scalars(this_branch, dst_reg);
8325 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8326 }
8327
8328 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8329 * NOTE: these optimizations below are related with pointer comparison
8330 * which will never be JMP32.
8331 */
8332 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
8333 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
8334 reg_type_may_be_null(dst_reg->type)) {
8335 /* Mark all identical registers in each branch as either
8336 * safe or unknown depending R == 0 or R != 0 conditional.
8337 */
8338 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8339 opcode == BPF_JNE);
8340 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8341 opcode == BPF_JEQ);
8342 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
8343 this_branch, other_branch) &&
8344 is_pointer_value(env, insn->dst_reg)) {
8345 verbose(env, "R%d pointer comparison prohibited\n",
8346 insn->dst_reg);
8347 return -EACCES;
8348 }
8349 if (env->log.level & BPF_LOG_LEVEL)
8350 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
8351 return 0;
8352 }
8353
8354 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)8355 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
8356 {
8357 struct bpf_insn_aux_data *aux = cur_aux(env);
8358 struct bpf_reg_state *regs = cur_regs(env);
8359 struct bpf_reg_state *dst_reg;
8360 struct bpf_map *map;
8361 int err;
8362
8363 if (BPF_SIZE(insn->code) != BPF_DW) {
8364 verbose(env, "invalid BPF_LD_IMM insn\n");
8365 return -EINVAL;
8366 }
8367 if (insn->off != 0) {
8368 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
8369 return -EINVAL;
8370 }
8371
8372 err = check_reg_arg(env, insn->dst_reg, DST_OP);
8373 if (err)
8374 return err;
8375
8376 dst_reg = ®s[insn->dst_reg];
8377 if (insn->src_reg == 0) {
8378 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8379
8380 dst_reg->type = SCALAR_VALUE;
8381 __mark_reg_known(®s[insn->dst_reg], imm);
8382 return 0;
8383 }
8384
8385 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8386 mark_reg_known_zero(env, regs, insn->dst_reg);
8387
8388 dst_reg->type = aux->btf_var.reg_type;
8389 switch (dst_reg->type) {
8390 case PTR_TO_MEM:
8391 dst_reg->mem_size = aux->btf_var.mem_size;
8392 break;
8393 case PTR_TO_BTF_ID:
8394 case PTR_TO_PERCPU_BTF_ID:
8395 dst_reg->btf_id = aux->btf_var.btf_id;
8396 break;
8397 default:
8398 verbose(env, "bpf verifier is misconfigured\n");
8399 return -EFAULT;
8400 }
8401 return 0;
8402 }
8403
8404 map = env->used_maps[aux->map_index];
8405 mark_reg_known_zero(env, regs, insn->dst_reg);
8406 dst_reg->map_ptr = map;
8407
8408 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
8409 dst_reg->type = PTR_TO_MAP_VALUE;
8410 dst_reg->off = aux->map_off;
8411 if (map_value_has_spin_lock(map))
8412 dst_reg->id = ++env->id_gen;
8413 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8414 dst_reg->type = CONST_PTR_TO_MAP;
8415 } else {
8416 verbose(env, "bpf verifier is misconfigured\n");
8417 return -EINVAL;
8418 }
8419
8420 return 0;
8421 }
8422
may_access_skb(enum bpf_prog_type type)8423 static bool may_access_skb(enum bpf_prog_type type)
8424 {
8425 switch (type) {
8426 case BPF_PROG_TYPE_SOCKET_FILTER:
8427 case BPF_PROG_TYPE_SCHED_CLS:
8428 case BPF_PROG_TYPE_SCHED_ACT:
8429 return true;
8430 default:
8431 return false;
8432 }
8433 }
8434
8435 /* verify safety of LD_ABS|LD_IND instructions:
8436 * - they can only appear in the programs where ctx == skb
8437 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8438 * preserve R6-R9, and store return value into R0
8439 *
8440 * Implicit input:
8441 * ctx == skb == R6 == CTX
8442 *
8443 * Explicit input:
8444 * SRC == any register
8445 * IMM == 32-bit immediate
8446 *
8447 * Output:
8448 * R0 - 8/16/32-bit skb data converted to cpu endianness
8449 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)8450 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
8451 {
8452 struct bpf_reg_state *regs = cur_regs(env);
8453 static const int ctx_reg = BPF_REG_6;
8454 u8 mode = BPF_MODE(insn->code);
8455 int i, err;
8456
8457 if (!may_access_skb(resolve_prog_type(env->prog))) {
8458 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
8459 return -EINVAL;
8460 }
8461
8462 if (!env->ops->gen_ld_abs) {
8463 verbose(env, "bpf verifier is misconfigured\n");
8464 return -EINVAL;
8465 }
8466
8467 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
8468 BPF_SIZE(insn->code) == BPF_DW ||
8469 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
8470 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
8471 return -EINVAL;
8472 }
8473
8474 /* check whether implicit source operand (register R6) is readable */
8475 err = check_reg_arg(env, ctx_reg, SRC_OP);
8476 if (err)
8477 return err;
8478
8479 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8480 * gen_ld_abs() may terminate the program at runtime, leading to
8481 * reference leak.
8482 */
8483 err = check_reference_leak(env);
8484 if (err) {
8485 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8486 return err;
8487 }
8488
8489 if (env->cur_state->active_spin_lock) {
8490 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8491 return -EINVAL;
8492 }
8493
8494 if (regs[ctx_reg].type != PTR_TO_CTX) {
8495 verbose(env,
8496 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
8497 return -EINVAL;
8498 }
8499
8500 if (mode == BPF_IND) {
8501 /* check explicit source operand */
8502 err = check_reg_arg(env, insn->src_reg, SRC_OP);
8503 if (err)
8504 return err;
8505 }
8506
8507 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
8508 if (err < 0)
8509 return err;
8510
8511 /* reset caller saved regs to unreadable */
8512 for (i = 0; i < CALLER_SAVED_REGS; i++) {
8513 mark_reg_not_init(env, regs, caller_saved[i]);
8514 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8515 }
8516
8517 /* mark destination R0 register as readable, since it contains
8518 * the value fetched from the packet.
8519 * Already marked as written above.
8520 */
8521 mark_reg_unknown(env, regs, BPF_REG_0);
8522 /* ld_abs load up to 32-bit skb data. */
8523 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
8524 return 0;
8525 }
8526
check_return_code(struct bpf_verifier_env * env)8527 static int check_return_code(struct bpf_verifier_env *env)
8528 {
8529 struct tnum enforce_attach_type_range = tnum_unknown;
8530 const struct bpf_prog *prog = env->prog;
8531 struct bpf_reg_state *reg;
8532 struct tnum range = tnum_range(0, 1);
8533 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
8534 int err;
8535 const bool is_subprog = env->cur_state->frame[0]->subprogno;
8536
8537 /* LSM and struct_ops func-ptr's return type could be "void" */
8538 if (!is_subprog &&
8539 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
8540 prog_type == BPF_PROG_TYPE_LSM) &&
8541 !prog->aux->attach_func_proto->type)
8542 return 0;
8543
8544 /* eBPF calling convetion is such that R0 is used
8545 * to return the value from eBPF program.
8546 * Make sure that it's readable at this time
8547 * of bpf_exit, which means that program wrote
8548 * something into it earlier
8549 */
8550 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8551 if (err)
8552 return err;
8553
8554 if (is_pointer_value(env, BPF_REG_0)) {
8555 verbose(env, "R0 leaks addr as return value\n");
8556 return -EACCES;
8557 }
8558
8559 reg = cur_regs(env) + BPF_REG_0;
8560 if (is_subprog) {
8561 if (reg->type != SCALAR_VALUE) {
8562 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8563 reg_type_str[reg->type]);
8564 return -EINVAL;
8565 }
8566 return 0;
8567 }
8568
8569 switch (prog_type) {
8570 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8571 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
8572 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8573 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8574 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8575 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8576 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
8577 range = tnum_range(1, 1);
8578 break;
8579 case BPF_PROG_TYPE_CGROUP_SKB:
8580 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8581 range = tnum_range(0, 3);
8582 enforce_attach_type_range = tnum_range(2, 3);
8583 }
8584 break;
8585 case BPF_PROG_TYPE_CGROUP_SOCK:
8586 case BPF_PROG_TYPE_SOCK_OPS:
8587 case BPF_PROG_TYPE_CGROUP_DEVICE:
8588 case BPF_PROG_TYPE_CGROUP_SYSCTL:
8589 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
8590 break;
8591 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8592 if (!env->prog->aux->attach_btf_id)
8593 return 0;
8594 range = tnum_const(0);
8595 break;
8596 case BPF_PROG_TYPE_TRACING:
8597 switch (env->prog->expected_attach_type) {
8598 case BPF_TRACE_FENTRY:
8599 case BPF_TRACE_FEXIT:
8600 range = tnum_const(0);
8601 break;
8602 case BPF_TRACE_RAW_TP:
8603 case BPF_MODIFY_RETURN:
8604 return 0;
8605 case BPF_TRACE_ITER:
8606 break;
8607 default:
8608 return -ENOTSUPP;
8609 }
8610 break;
8611 case BPF_PROG_TYPE_SK_LOOKUP:
8612 range = tnum_range(SK_DROP, SK_PASS);
8613 break;
8614 case BPF_PROG_TYPE_EXT:
8615 /* freplace program can return anything as its return value
8616 * depends on the to-be-replaced kernel func or bpf program.
8617 */
8618 default:
8619 return 0;
8620 }
8621
8622 if (reg->type != SCALAR_VALUE) {
8623 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
8624 reg_type_str[reg->type]);
8625 return -EINVAL;
8626 }
8627
8628 if (!tnum_in(range, reg->var_off)) {
8629 char tn_buf[48];
8630
8631 verbose(env, "At program exit the register R0 ");
8632 if (!tnum_is_unknown(reg->var_off)) {
8633 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
8634 verbose(env, "has value %s", tn_buf);
8635 } else {
8636 verbose(env, "has unknown scalar value");
8637 }
8638 tnum_strn(tn_buf, sizeof(tn_buf), range);
8639 verbose(env, " should have been in %s\n", tn_buf);
8640 return -EINVAL;
8641 }
8642
8643 if (!tnum_is_unknown(enforce_attach_type_range) &&
8644 tnum_in(enforce_attach_type_range, reg->var_off))
8645 env->prog->enforce_expected_attach_type = 1;
8646 return 0;
8647 }
8648
8649 /* non-recursive DFS pseudo code
8650 * 1 procedure DFS-iterative(G,v):
8651 * 2 label v as discovered
8652 * 3 let S be a stack
8653 * 4 S.push(v)
8654 * 5 while S is not empty
8655 * 6 t <- S.pop()
8656 * 7 if t is what we're looking for:
8657 * 8 return t
8658 * 9 for all edges e in G.adjacentEdges(t) do
8659 * 10 if edge e is already labelled
8660 * 11 continue with the next edge
8661 * 12 w <- G.adjacentVertex(t,e)
8662 * 13 if vertex w is not discovered and not explored
8663 * 14 label e as tree-edge
8664 * 15 label w as discovered
8665 * 16 S.push(w)
8666 * 17 continue at 5
8667 * 18 else if vertex w is discovered
8668 * 19 label e as back-edge
8669 * 20 else
8670 * 21 // vertex w is explored
8671 * 22 label e as forward- or cross-edge
8672 * 23 label t as explored
8673 * 24 S.pop()
8674 *
8675 * convention:
8676 * 0x10 - discovered
8677 * 0x11 - discovered and fall-through edge labelled
8678 * 0x12 - discovered and fall-through and branch edges labelled
8679 * 0x20 - explored
8680 */
8681
8682 enum {
8683 DISCOVERED = 0x10,
8684 EXPLORED = 0x20,
8685 FALLTHROUGH = 1,
8686 BRANCH = 2,
8687 };
8688
state_htab_size(struct bpf_verifier_env * env)8689 static u32 state_htab_size(struct bpf_verifier_env *env)
8690 {
8691 return env->prog->len;
8692 }
8693
explored_state(struct bpf_verifier_env * env,int idx)8694 static struct bpf_verifier_state_list **explored_state(
8695 struct bpf_verifier_env *env,
8696 int idx)
8697 {
8698 struct bpf_verifier_state *cur = env->cur_state;
8699 struct bpf_func_state *state = cur->frame[cur->curframe];
8700
8701 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
8702 }
8703
init_explored_state(struct bpf_verifier_env * env,int idx)8704 static void init_explored_state(struct bpf_verifier_env *env, int idx)
8705 {
8706 env->insn_aux_data[idx].prune_point = true;
8707 }
8708
8709 /* t, w, e - match pseudo-code above:
8710 * t - index of current instruction
8711 * w - next instruction
8712 * e - edge
8713 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)8714 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8715 bool loop_ok)
8716 {
8717 int *insn_stack = env->cfg.insn_stack;
8718 int *insn_state = env->cfg.insn_state;
8719
8720 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
8721 return 0;
8722
8723 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
8724 return 0;
8725
8726 if (w < 0 || w >= env->prog->len) {
8727 verbose_linfo(env, t, "%d: ", t);
8728 verbose(env, "jump out of range from insn %d to %d\n", t, w);
8729 return -EINVAL;
8730 }
8731
8732 if (e == BRANCH)
8733 /* mark branch target for state pruning */
8734 init_explored_state(env, w);
8735
8736 if (insn_state[w] == 0) {
8737 /* tree-edge */
8738 insn_state[t] = DISCOVERED | e;
8739 insn_state[w] = DISCOVERED;
8740 if (env->cfg.cur_stack >= env->prog->len)
8741 return -E2BIG;
8742 insn_stack[env->cfg.cur_stack++] = w;
8743 return 1;
8744 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
8745 if (loop_ok && env->bpf_capable)
8746 return 0;
8747 verbose_linfo(env, t, "%d: ", t);
8748 verbose_linfo(env, w, "%d: ", w);
8749 verbose(env, "back-edge from insn %d to %d\n", t, w);
8750 return -EINVAL;
8751 } else if (insn_state[w] == EXPLORED) {
8752 /* forward- or cross-edge */
8753 insn_state[t] = DISCOVERED | e;
8754 } else {
8755 verbose(env, "insn state internal bug\n");
8756 return -EFAULT;
8757 }
8758 return 0;
8759 }
8760
8761 /* non-recursive depth-first-search to detect loops in BPF program
8762 * loop == back-edge in directed graph
8763 */
check_cfg(struct bpf_verifier_env * env)8764 static int check_cfg(struct bpf_verifier_env *env)
8765 {
8766 struct bpf_insn *insns = env->prog->insnsi;
8767 int insn_cnt = env->prog->len;
8768 int *insn_stack, *insn_state;
8769 int ret = 0;
8770 int i, t;
8771
8772 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8773 if (!insn_state)
8774 return -ENOMEM;
8775
8776 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
8777 if (!insn_stack) {
8778 kvfree(insn_state);
8779 return -ENOMEM;
8780 }
8781
8782 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8783 insn_stack[0] = 0; /* 0 is the first instruction */
8784 env->cfg.cur_stack = 1;
8785
8786 peek_stack:
8787 if (env->cfg.cur_stack == 0)
8788 goto check_state;
8789 t = insn_stack[env->cfg.cur_stack - 1];
8790
8791 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
8792 BPF_CLASS(insns[t].code) == BPF_JMP32) {
8793 u8 opcode = BPF_OP(insns[t].code);
8794
8795 if (opcode == BPF_EXIT) {
8796 goto mark_explored;
8797 } else if (opcode == BPF_CALL) {
8798 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8799 if (ret == 1)
8800 goto peek_stack;
8801 else if (ret < 0)
8802 goto err_free;
8803 if (t + 1 < insn_cnt)
8804 init_explored_state(env, t + 1);
8805 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8806 init_explored_state(env, t);
8807 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8808 env, false);
8809 if (ret == 1)
8810 goto peek_stack;
8811 else if (ret < 0)
8812 goto err_free;
8813 }
8814 } else if (opcode == BPF_JA) {
8815 if (BPF_SRC(insns[t].code) != BPF_K) {
8816 ret = -EINVAL;
8817 goto err_free;
8818 }
8819 /* unconditional jump with single edge */
8820 ret = push_insn(t, t + insns[t].off + 1,
8821 FALLTHROUGH, env, true);
8822 if (ret == 1)
8823 goto peek_stack;
8824 else if (ret < 0)
8825 goto err_free;
8826 /* unconditional jmp is not a good pruning point,
8827 * but it's marked, since backtracking needs
8828 * to record jmp history in is_state_visited().
8829 */
8830 init_explored_state(env, t + insns[t].off + 1);
8831 /* tell verifier to check for equivalent states
8832 * after every call and jump
8833 */
8834 if (t + 1 < insn_cnt)
8835 init_explored_state(env, t + 1);
8836 } else {
8837 /* conditional jump with two edges */
8838 init_explored_state(env, t);
8839 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8840 if (ret == 1)
8841 goto peek_stack;
8842 else if (ret < 0)
8843 goto err_free;
8844
8845 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8846 if (ret == 1)
8847 goto peek_stack;
8848 else if (ret < 0)
8849 goto err_free;
8850 }
8851 } else {
8852 /* all other non-branch instructions with single
8853 * fall-through edge
8854 */
8855 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8856 if (ret == 1)
8857 goto peek_stack;
8858 else if (ret < 0)
8859 goto err_free;
8860 }
8861
8862 mark_explored:
8863 insn_state[t] = EXPLORED;
8864 if (env->cfg.cur_stack-- <= 0) {
8865 verbose(env, "pop stack internal bug\n");
8866 ret = -EFAULT;
8867 goto err_free;
8868 }
8869 goto peek_stack;
8870
8871 check_state:
8872 for (i = 0; i < insn_cnt; i++) {
8873 if (insn_state[i] != EXPLORED) {
8874 verbose(env, "unreachable insn %d\n", i);
8875 ret = -EINVAL;
8876 goto err_free;
8877 }
8878 }
8879 ret = 0; /* cfg looks good */
8880
8881 err_free:
8882 kvfree(insn_state);
8883 kvfree(insn_stack);
8884 env->cfg.insn_state = env->cfg.insn_stack = NULL;
8885 return ret;
8886 }
8887
check_abnormal_return(struct bpf_verifier_env * env)8888 static int check_abnormal_return(struct bpf_verifier_env *env)
8889 {
8890 int i;
8891
8892 for (i = 1; i < env->subprog_cnt; i++) {
8893 if (env->subprog_info[i].has_ld_abs) {
8894 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8895 return -EINVAL;
8896 }
8897 if (env->subprog_info[i].has_tail_call) {
8898 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8899 return -EINVAL;
8900 }
8901 }
8902 return 0;
8903 }
8904
8905 /* The minimum supported BTF func info size */
8906 #define MIN_BPF_FUNCINFO_SIZE 8
8907 #define MAX_FUNCINFO_REC_SIZE 252
8908
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)8909 static int check_btf_func(struct bpf_verifier_env *env,
8910 const union bpf_attr *attr,
8911 union bpf_attr __user *uattr)
8912 {
8913 const struct btf_type *type, *func_proto, *ret_type;
8914 u32 i, nfuncs, urec_size, min_size;
8915 u32 krec_size = sizeof(struct bpf_func_info);
8916 struct bpf_func_info *krecord;
8917 struct bpf_func_info_aux *info_aux = NULL;
8918 struct bpf_prog *prog;
8919 const struct btf *btf;
8920 void __user *urecord;
8921 u32 prev_offset = 0;
8922 bool scalar_return;
8923 int ret = -ENOMEM;
8924
8925 nfuncs = attr->func_info_cnt;
8926 if (!nfuncs) {
8927 if (check_abnormal_return(env))
8928 return -EINVAL;
8929 return 0;
8930 }
8931
8932 if (nfuncs != env->subprog_cnt) {
8933 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8934 return -EINVAL;
8935 }
8936
8937 urec_size = attr->func_info_rec_size;
8938 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8939 urec_size > MAX_FUNCINFO_REC_SIZE ||
8940 urec_size % sizeof(u32)) {
8941 verbose(env, "invalid func info rec size %u\n", urec_size);
8942 return -EINVAL;
8943 }
8944
8945 prog = env->prog;
8946 btf = prog->aux->btf;
8947
8948 urecord = u64_to_user_ptr(attr->func_info);
8949 min_size = min_t(u32, krec_size, urec_size);
8950
8951 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
8952 if (!krecord)
8953 return -ENOMEM;
8954 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8955 if (!info_aux)
8956 goto err_free;
8957
8958 for (i = 0; i < nfuncs; i++) {
8959 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8960 if (ret) {
8961 if (ret == -E2BIG) {
8962 verbose(env, "nonzero tailing record in func info");
8963 /* set the size kernel expects so loader can zero
8964 * out the rest of the record.
8965 */
8966 if (put_user(min_size, &uattr->func_info_rec_size))
8967 ret = -EFAULT;
8968 }
8969 goto err_free;
8970 }
8971
8972 if (copy_from_user(&krecord[i], urecord, min_size)) {
8973 ret = -EFAULT;
8974 goto err_free;
8975 }
8976
8977 /* check insn_off */
8978 ret = -EINVAL;
8979 if (i == 0) {
8980 if (krecord[i].insn_off) {
8981 verbose(env,
8982 "nonzero insn_off %u for the first func info record",
8983 krecord[i].insn_off);
8984 goto err_free;
8985 }
8986 } else if (krecord[i].insn_off <= prev_offset) {
8987 verbose(env,
8988 "same or smaller insn offset (%u) than previous func info record (%u)",
8989 krecord[i].insn_off, prev_offset);
8990 goto err_free;
8991 }
8992
8993 if (env->subprog_info[i].start != krecord[i].insn_off) {
8994 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
8995 goto err_free;
8996 }
8997
8998 /* check type_id */
8999 type = btf_type_by_id(btf, krecord[i].type_id);
9000 if (!type || !btf_type_is_func(type)) {
9001 verbose(env, "invalid type id %d in func info",
9002 krecord[i].type_id);
9003 goto err_free;
9004 }
9005 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
9006
9007 func_proto = btf_type_by_id(btf, type->type);
9008 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9009 /* btf_func_check() already verified it during BTF load */
9010 goto err_free;
9011 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9012 scalar_return =
9013 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9014 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9015 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9016 goto err_free;
9017 }
9018 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9019 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9020 goto err_free;
9021 }
9022
9023 prev_offset = krecord[i].insn_off;
9024 urecord += urec_size;
9025 }
9026
9027 prog->aux->func_info = krecord;
9028 prog->aux->func_info_cnt = nfuncs;
9029 prog->aux->func_info_aux = info_aux;
9030 return 0;
9031
9032 err_free:
9033 kvfree(krecord);
9034 kfree(info_aux);
9035 return ret;
9036 }
9037
adjust_btf_func(struct bpf_verifier_env * env)9038 static void adjust_btf_func(struct bpf_verifier_env *env)
9039 {
9040 struct bpf_prog_aux *aux = env->prog->aux;
9041 int i;
9042
9043 if (!aux->func_info)
9044 return;
9045
9046 for (i = 0; i < env->subprog_cnt; i++)
9047 aux->func_info[i].insn_off = env->subprog_info[i].start;
9048 }
9049
9050 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9051 sizeof(((struct bpf_line_info *)(0))->line_col))
9052 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9053
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9054 static int check_btf_line(struct bpf_verifier_env *env,
9055 const union bpf_attr *attr,
9056 union bpf_attr __user *uattr)
9057 {
9058 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9059 struct bpf_subprog_info *sub;
9060 struct bpf_line_info *linfo;
9061 struct bpf_prog *prog;
9062 const struct btf *btf;
9063 void __user *ulinfo;
9064 int err;
9065
9066 nr_linfo = attr->line_info_cnt;
9067 if (!nr_linfo)
9068 return 0;
9069 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
9070 return -EINVAL;
9071
9072 rec_size = attr->line_info_rec_size;
9073 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9074 rec_size > MAX_LINEINFO_REC_SIZE ||
9075 rec_size & (sizeof(u32) - 1))
9076 return -EINVAL;
9077
9078 /* Need to zero it in case the userspace may
9079 * pass in a smaller bpf_line_info object.
9080 */
9081 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9082 GFP_KERNEL | __GFP_NOWARN);
9083 if (!linfo)
9084 return -ENOMEM;
9085
9086 prog = env->prog;
9087 btf = prog->aux->btf;
9088
9089 s = 0;
9090 sub = env->subprog_info;
9091 ulinfo = u64_to_user_ptr(attr->line_info);
9092 expected_size = sizeof(struct bpf_line_info);
9093 ncopy = min_t(u32, expected_size, rec_size);
9094 for (i = 0; i < nr_linfo; i++) {
9095 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9096 if (err) {
9097 if (err == -E2BIG) {
9098 verbose(env, "nonzero tailing record in line_info");
9099 if (put_user(expected_size,
9100 &uattr->line_info_rec_size))
9101 err = -EFAULT;
9102 }
9103 goto err_free;
9104 }
9105
9106 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9107 err = -EFAULT;
9108 goto err_free;
9109 }
9110
9111 /*
9112 * Check insn_off to ensure
9113 * 1) strictly increasing AND
9114 * 2) bounded by prog->len
9115 *
9116 * The linfo[0].insn_off == 0 check logically falls into
9117 * the later "missing bpf_line_info for func..." case
9118 * because the first linfo[0].insn_off must be the
9119 * first sub also and the first sub must have
9120 * subprog_info[0].start == 0.
9121 */
9122 if ((i && linfo[i].insn_off <= prev_offset) ||
9123 linfo[i].insn_off >= prog->len) {
9124 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9125 i, linfo[i].insn_off, prev_offset,
9126 prog->len);
9127 err = -EINVAL;
9128 goto err_free;
9129 }
9130
9131 if (!prog->insnsi[linfo[i].insn_off].code) {
9132 verbose(env,
9133 "Invalid insn code at line_info[%u].insn_off\n",
9134 i);
9135 err = -EINVAL;
9136 goto err_free;
9137 }
9138
9139 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9140 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
9141 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9142 err = -EINVAL;
9143 goto err_free;
9144 }
9145
9146 if (s != env->subprog_cnt) {
9147 if (linfo[i].insn_off == sub[s].start) {
9148 sub[s].linfo_idx = i;
9149 s++;
9150 } else if (sub[s].start < linfo[i].insn_off) {
9151 verbose(env, "missing bpf_line_info for func#%u\n", s);
9152 err = -EINVAL;
9153 goto err_free;
9154 }
9155 }
9156
9157 prev_offset = linfo[i].insn_off;
9158 ulinfo += rec_size;
9159 }
9160
9161 if (s != env->subprog_cnt) {
9162 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9163 env->subprog_cnt - s, s);
9164 err = -EINVAL;
9165 goto err_free;
9166 }
9167
9168 prog->aux->linfo = linfo;
9169 prog->aux->nr_linfo = nr_linfo;
9170
9171 return 0;
9172
9173 err_free:
9174 kvfree(linfo);
9175 return err;
9176 }
9177
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)9178 static int check_btf_info(struct bpf_verifier_env *env,
9179 const union bpf_attr *attr,
9180 union bpf_attr __user *uattr)
9181 {
9182 struct btf *btf;
9183 int err;
9184
9185 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9186 if (check_abnormal_return(env))
9187 return -EINVAL;
9188 return 0;
9189 }
9190
9191 btf = btf_get_by_fd(attr->prog_btf_fd);
9192 if (IS_ERR(btf))
9193 return PTR_ERR(btf);
9194 env->prog->aux->btf = btf;
9195
9196 err = check_btf_func(env, attr, uattr);
9197 if (err)
9198 return err;
9199
9200 err = check_btf_line(env, attr, uattr);
9201 if (err)
9202 return err;
9203
9204 return 0;
9205 }
9206
9207 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)9208 static bool range_within(struct bpf_reg_state *old,
9209 struct bpf_reg_state *cur)
9210 {
9211 return old->umin_value <= cur->umin_value &&
9212 old->umax_value >= cur->umax_value &&
9213 old->smin_value <= cur->smin_value &&
9214 old->smax_value >= cur->smax_value &&
9215 old->u32_min_value <= cur->u32_min_value &&
9216 old->u32_max_value >= cur->u32_max_value &&
9217 old->s32_min_value <= cur->s32_min_value &&
9218 old->s32_max_value >= cur->s32_max_value;
9219 }
9220
9221 /* If in the old state two registers had the same id, then they need to have
9222 * the same id in the new state as well. But that id could be different from
9223 * the old state, so we need to track the mapping from old to new ids.
9224 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9225 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9226 * regs with a different old id could still have new id 9, we don't care about
9227 * that.
9228 * So we look through our idmap to see if this old id has been seen before. If
9229 * so, we require the new id to match; otherwise, we add the id pair to the map.
9230 */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)9231 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
9232 {
9233 unsigned int i;
9234
9235 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
9236 if (!idmap[i].old) {
9237 /* Reached an empty slot; haven't seen this id before */
9238 idmap[i].old = old_id;
9239 idmap[i].cur = cur_id;
9240 return true;
9241 }
9242 if (idmap[i].old == old_id)
9243 return idmap[i].cur == cur_id;
9244 }
9245 /* We ran out of idmap slots, which should be impossible */
9246 WARN_ON_ONCE(1);
9247 return false;
9248 }
9249
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)9250 static void clean_func_state(struct bpf_verifier_env *env,
9251 struct bpf_func_state *st)
9252 {
9253 enum bpf_reg_liveness live;
9254 int i, j;
9255
9256 for (i = 0; i < BPF_REG_FP; i++) {
9257 live = st->regs[i].live;
9258 /* liveness must not touch this register anymore */
9259 st->regs[i].live |= REG_LIVE_DONE;
9260 if (!(live & REG_LIVE_READ))
9261 /* since the register is unused, clear its state
9262 * to make further comparison simpler
9263 */
9264 __mark_reg_not_init(env, &st->regs[i]);
9265 }
9266
9267 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9268 live = st->stack[i].spilled_ptr.live;
9269 /* liveness must not touch this stack slot anymore */
9270 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9271 if (!(live & REG_LIVE_READ)) {
9272 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9273 for (j = 0; j < BPF_REG_SIZE; j++)
9274 st->stack[i].slot_type[j] = STACK_INVALID;
9275 }
9276 }
9277 }
9278
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)9279 static void clean_verifier_state(struct bpf_verifier_env *env,
9280 struct bpf_verifier_state *st)
9281 {
9282 int i;
9283
9284 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9285 /* all regs in this state in all frames were already marked */
9286 return;
9287
9288 for (i = 0; i <= st->curframe; i++)
9289 clean_func_state(env, st->frame[i]);
9290 }
9291
9292 /* the parentage chains form a tree.
9293 * the verifier states are added to state lists at given insn and
9294 * pushed into state stack for future exploration.
9295 * when the verifier reaches bpf_exit insn some of the verifer states
9296 * stored in the state lists have their final liveness state already,
9297 * but a lot of states will get revised from liveness point of view when
9298 * the verifier explores other branches.
9299 * Example:
9300 * 1: r0 = 1
9301 * 2: if r1 == 100 goto pc+1
9302 * 3: r0 = 2
9303 * 4: exit
9304 * when the verifier reaches exit insn the register r0 in the state list of
9305 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9306 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9307 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9308 *
9309 * Since the verifier pushes the branch states as it sees them while exploring
9310 * the program the condition of walking the branch instruction for the second
9311 * time means that all states below this branch were already explored and
9312 * their final liveness markes are already propagated.
9313 * Hence when the verifier completes the search of state list in is_state_visited()
9314 * we can call this clean_live_states() function to mark all liveness states
9315 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9316 * will not be used.
9317 * This function also clears the registers and stack for states that !READ
9318 * to simplify state merging.
9319 *
9320 * Important note here that walking the same branch instruction in the callee
9321 * doesn't meant that the states are DONE. The verifier has to compare
9322 * the callsites
9323 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)9324 static void clean_live_states(struct bpf_verifier_env *env, int insn,
9325 struct bpf_verifier_state *cur)
9326 {
9327 struct bpf_verifier_state_list *sl;
9328 int i;
9329
9330 sl = *explored_state(env, insn);
9331 while (sl) {
9332 if (sl->state.branches)
9333 goto next;
9334 if (sl->state.insn_idx != insn ||
9335 sl->state.curframe != cur->curframe)
9336 goto next;
9337 for (i = 0; i <= cur->curframe; i++)
9338 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9339 goto next;
9340 clean_verifier_state(env, &sl->state);
9341 next:
9342 sl = sl->next;
9343 }
9344 }
9345
9346 /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_verifier_env * env,struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct bpf_id_pair * idmap)9347 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9348 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
9349 {
9350 bool equal;
9351
9352 if (!(rold->live & REG_LIVE_READ))
9353 /* explored state didn't use this */
9354 return true;
9355
9356 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
9357
9358 if (rold->type == PTR_TO_STACK)
9359 /* two stack pointers are equal only if they're pointing to
9360 * the same stack frame, since fp-8 in foo != fp-8 in bar
9361 */
9362 return equal && rold->frameno == rcur->frameno;
9363
9364 if (equal)
9365 return true;
9366
9367 if (rold->type == NOT_INIT)
9368 /* explored state can't have used this */
9369 return true;
9370 if (rcur->type == NOT_INIT)
9371 return false;
9372 switch (rold->type) {
9373 case SCALAR_VALUE:
9374 if (env->explore_alu_limits)
9375 return false;
9376 if (rcur->type == SCALAR_VALUE) {
9377 if (!rold->precise)
9378 return true;
9379 /* new val must satisfy old val knowledge */
9380 return range_within(rold, rcur) &&
9381 tnum_in(rold->var_off, rcur->var_off);
9382 } else {
9383 /* We're trying to use a pointer in place of a scalar.
9384 * Even if the scalar was unbounded, this could lead to
9385 * pointer leaks because scalars are allowed to leak
9386 * while pointers are not. We could make this safe in
9387 * special cases if root is calling us, but it's
9388 * probably not worth the hassle.
9389 */
9390 return false;
9391 }
9392 case PTR_TO_MAP_VALUE:
9393 /* If the new min/max/var_off satisfy the old ones and
9394 * everything else matches, we are OK.
9395 * 'id' is not compared, since it's only used for maps with
9396 * bpf_spin_lock inside map element and in such cases if
9397 * the rest of the prog is valid for one map element then
9398 * it's valid for all map elements regardless of the key
9399 * used in bpf_map_lookup()
9400 */
9401 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9402 range_within(rold, rcur) &&
9403 tnum_in(rold->var_off, rcur->var_off);
9404 case PTR_TO_MAP_VALUE_OR_NULL:
9405 /* a PTR_TO_MAP_VALUE could be safe to use as a
9406 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9407 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9408 * checked, doing so could have affected others with the same
9409 * id, and we can't check for that because we lost the id when
9410 * we converted to a PTR_TO_MAP_VALUE.
9411 */
9412 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9413 return false;
9414 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9415 return false;
9416 /* Check our ids match any regs they're supposed to */
9417 return check_ids(rold->id, rcur->id, idmap);
9418 case PTR_TO_PACKET_META:
9419 case PTR_TO_PACKET:
9420 if (rcur->type != rold->type)
9421 return false;
9422 /* We must have at least as much range as the old ptr
9423 * did, so that any accesses which were safe before are
9424 * still safe. This is true even if old range < old off,
9425 * since someone could have accessed through (ptr - k), or
9426 * even done ptr -= k in a register, to get a safe access.
9427 */
9428 if (rold->range > rcur->range)
9429 return false;
9430 /* If the offsets don't match, we can't trust our alignment;
9431 * nor can we be sure that we won't fall out of range.
9432 */
9433 if (rold->off != rcur->off)
9434 return false;
9435 /* id relations must be preserved */
9436 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9437 return false;
9438 /* new val must satisfy old val knowledge */
9439 return range_within(rold, rcur) &&
9440 tnum_in(rold->var_off, rcur->var_off);
9441 case PTR_TO_CTX:
9442 case CONST_PTR_TO_MAP:
9443 case PTR_TO_PACKET_END:
9444 case PTR_TO_FLOW_KEYS:
9445 case PTR_TO_SOCKET:
9446 case PTR_TO_SOCKET_OR_NULL:
9447 case PTR_TO_SOCK_COMMON:
9448 case PTR_TO_SOCK_COMMON_OR_NULL:
9449 case PTR_TO_TCP_SOCK:
9450 case PTR_TO_TCP_SOCK_OR_NULL:
9451 case PTR_TO_XDP_SOCK:
9452 /* Only valid matches are exact, which memcmp() above
9453 * would have accepted
9454 */
9455 default:
9456 /* Don't know what's going on, just say it's not safe */
9457 return false;
9458 }
9459
9460 /* Shouldn't get here; if we do, say it's not safe */
9461 WARN_ON_ONCE(1);
9462 return false;
9463 }
9464
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)9465 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
9466 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
9467 {
9468 int i, spi;
9469
9470 /* walk slots of the explored stack and ignore any additional
9471 * slots in the current stack, since explored(safe) state
9472 * didn't use them
9473 */
9474 for (i = 0; i < old->allocated_stack; i++) {
9475 spi = i / BPF_REG_SIZE;
9476
9477 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9478 i += BPF_REG_SIZE - 1;
9479 /* explored state didn't use this */
9480 continue;
9481 }
9482
9483 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9484 continue;
9485
9486 /* explored stack has more populated slots than current stack
9487 * and these slots were used
9488 */
9489 if (i >= cur->allocated_stack)
9490 return false;
9491
9492 /* if old state was safe with misc data in the stack
9493 * it will be safe with zero-initialized stack.
9494 * The opposite is not true
9495 */
9496 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9497 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9498 continue;
9499 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9500 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9501 /* Ex: old explored (safe) state has STACK_SPILL in
9502 * this stack slot, but current has STACK_MISC ->
9503 * this verifier states are not equivalent,
9504 * return false to continue verification of this path
9505 */
9506 return false;
9507 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
9508 continue;
9509 if (!is_spilled_reg(&old->stack[spi]))
9510 continue;
9511 if (!regsafe(env, &old->stack[spi].spilled_ptr,
9512 &cur->stack[spi].spilled_ptr, idmap))
9513 /* when explored and current stack slot are both storing
9514 * spilled registers, check that stored pointers types
9515 * are the same as well.
9516 * Ex: explored safe path could have stored
9517 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9518 * but current path has stored:
9519 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9520 * such verifier states are not equivalent.
9521 * return false to continue verification of this path
9522 */
9523 return false;
9524 }
9525 return true;
9526 }
9527
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)9528 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9529 {
9530 if (old->acquired_refs != cur->acquired_refs)
9531 return false;
9532 return !memcmp(old->refs, cur->refs,
9533 sizeof(*old->refs) * old->acquired_refs);
9534 }
9535
9536 /* compare two verifier states
9537 *
9538 * all states stored in state_list are known to be valid, since
9539 * verifier reached 'bpf_exit' instruction through them
9540 *
9541 * this function is called when verifier exploring different branches of
9542 * execution popped from the state stack. If it sees an old state that has
9543 * more strict register state and more strict stack state then this execution
9544 * branch doesn't need to be explored further, since verifier already
9545 * concluded that more strict state leads to valid finish.
9546 *
9547 * Therefore two states are equivalent if register state is more conservative
9548 * and explored stack state is more conservative than the current one.
9549 * Example:
9550 * explored current
9551 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9552 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9553 *
9554 * In other words if current stack state (one being explored) has more
9555 * valid slots than old one that already passed validation, it means
9556 * the verifier can stop exploring and conclude that current state is valid too
9557 *
9558 * Similarly with registers. If explored state has register type as invalid
9559 * whereas register type in current state is meaningful, it means that
9560 * the current state will reach 'bpf_exit' instruction safely
9561 */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)9562 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
9563 struct bpf_func_state *cur)
9564 {
9565 int i;
9566
9567 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
9568 for (i = 0; i < MAX_BPF_REG; i++)
9569 if (!regsafe(env, &old->regs[i], &cur->regs[i],
9570 env->idmap_scratch))
9571 return false;
9572
9573 if (!stacksafe(env, old, cur, env->idmap_scratch))
9574 return false;
9575
9576 if (!refsafe(old, cur))
9577 return false;
9578
9579 return true;
9580 }
9581
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9582 static bool states_equal(struct bpf_verifier_env *env,
9583 struct bpf_verifier_state *old,
9584 struct bpf_verifier_state *cur)
9585 {
9586 int i;
9587
9588 if (old->curframe != cur->curframe)
9589 return false;
9590
9591 /* Verification state from speculative execution simulation
9592 * must never prune a non-speculative execution one.
9593 */
9594 if (old->speculative && !cur->speculative)
9595 return false;
9596
9597 if (old->active_spin_lock != cur->active_spin_lock)
9598 return false;
9599
9600 /* for states to be equal callsites have to be the same
9601 * and all frame states need to be equivalent
9602 */
9603 for (i = 0; i <= old->curframe; i++) {
9604 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9605 return false;
9606 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
9607 return false;
9608 }
9609 return true;
9610 }
9611
9612 /* Return 0 if no propagation happened. Return negative error code if error
9613 * happened. Otherwise, return the propagated bit.
9614 */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)9615 static int propagate_liveness_reg(struct bpf_verifier_env *env,
9616 struct bpf_reg_state *reg,
9617 struct bpf_reg_state *parent_reg)
9618 {
9619 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9620 u8 flag = reg->live & REG_LIVE_READ;
9621 int err;
9622
9623 /* When comes here, read flags of PARENT_REG or REG could be any of
9624 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9625 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9626 */
9627 if (parent_flag == REG_LIVE_READ64 ||
9628 /* Or if there is no read flag from REG. */
9629 !flag ||
9630 /* Or if the read flag from REG is the same as PARENT_REG. */
9631 parent_flag == flag)
9632 return 0;
9633
9634 err = mark_reg_read(env, reg, parent_reg, flag);
9635 if (err)
9636 return err;
9637
9638 return flag;
9639 }
9640
9641 /* A write screens off any subsequent reads; but write marks come from the
9642 * straight-line code between a state and its parent. When we arrive at an
9643 * equivalent state (jump target or such) we didn't arrive by the straight-line
9644 * code, so read marks in the state must propagate to the parent regardless
9645 * of the state's write marks. That's what 'parent == state->parent' comparison
9646 * in mark_reg_read() is for.
9647 */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)9648 static int propagate_liveness(struct bpf_verifier_env *env,
9649 const struct bpf_verifier_state *vstate,
9650 struct bpf_verifier_state *vparent)
9651 {
9652 struct bpf_reg_state *state_reg, *parent_reg;
9653 struct bpf_func_state *state, *parent;
9654 int i, frame, err = 0;
9655
9656 if (vparent->curframe != vstate->curframe) {
9657 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9658 vparent->curframe, vstate->curframe);
9659 return -EFAULT;
9660 }
9661 /* Propagate read liveness of registers... */
9662 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
9663 for (frame = 0; frame <= vstate->curframe; frame++) {
9664 parent = vparent->frame[frame];
9665 state = vstate->frame[frame];
9666 parent_reg = parent->regs;
9667 state_reg = state->regs;
9668 /* We don't need to worry about FP liveness, it's read-only */
9669 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
9670 err = propagate_liveness_reg(env, &state_reg[i],
9671 &parent_reg[i]);
9672 if (err < 0)
9673 return err;
9674 if (err == REG_LIVE_READ64)
9675 mark_insn_zext(env, &parent_reg[i]);
9676 }
9677
9678 /* Propagate stack slots. */
9679 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9680 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
9681 parent_reg = &parent->stack[i].spilled_ptr;
9682 state_reg = &state->stack[i].spilled_ptr;
9683 err = propagate_liveness_reg(env, state_reg,
9684 parent_reg);
9685 if (err < 0)
9686 return err;
9687 }
9688 }
9689 return 0;
9690 }
9691
9692 /* find precise scalars in the previous equivalent state and
9693 * propagate them into the current state
9694 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)9695 static int propagate_precision(struct bpf_verifier_env *env,
9696 const struct bpf_verifier_state *old)
9697 {
9698 struct bpf_reg_state *state_reg;
9699 struct bpf_func_state *state;
9700 int i, err = 0, fr;
9701
9702 for (fr = old->curframe; fr >= 0; fr--) {
9703 state = old->frame[fr];
9704 state_reg = state->regs;
9705 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9706 if (state_reg->type != SCALAR_VALUE ||
9707 !state_reg->precise ||
9708 !(state_reg->live & REG_LIVE_READ))
9709 continue;
9710 if (env->log.level & BPF_LOG_LEVEL2)
9711 verbose(env, "frame %d: propagating r%d\n", fr, i);
9712 err = mark_chain_precision_frame(env, fr, i);
9713 if (err < 0)
9714 return err;
9715 }
9716
9717 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9718 if (!is_spilled_reg(&state->stack[i]))
9719 continue;
9720 state_reg = &state->stack[i].spilled_ptr;
9721 if (state_reg->type != SCALAR_VALUE ||
9722 !state_reg->precise ||
9723 !(state_reg->live & REG_LIVE_READ))
9724 continue;
9725 if (env->log.level & BPF_LOG_LEVEL2)
9726 verbose(env, "frame %d: propagating fp%d\n",
9727 fr, (-i - 1) * BPF_REG_SIZE);
9728 err = mark_chain_precision_stack_frame(env, fr, i);
9729 if (err < 0)
9730 return err;
9731 }
9732 }
9733 return 0;
9734 }
9735
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)9736 static bool states_maybe_looping(struct bpf_verifier_state *old,
9737 struct bpf_verifier_state *cur)
9738 {
9739 struct bpf_func_state *fold, *fcur;
9740 int i, fr = cur->curframe;
9741
9742 if (old->curframe != fr)
9743 return false;
9744
9745 fold = old->frame[fr];
9746 fcur = cur->frame[fr];
9747 for (i = 0; i < MAX_BPF_REG; i++)
9748 if (memcmp(&fold->regs[i], &fcur->regs[i],
9749 offsetof(struct bpf_reg_state, parent)))
9750 return false;
9751 return true;
9752 }
9753
9754
is_state_visited(struct bpf_verifier_env * env,int insn_idx)9755 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
9756 {
9757 struct bpf_verifier_state_list *new_sl;
9758 struct bpf_verifier_state_list *sl, **pprev;
9759 struct bpf_verifier_state *cur = env->cur_state, *new;
9760 int i, j, err, states_cnt = 0;
9761 bool add_new_state = env->test_state_freq ? true : false;
9762
9763 cur->last_insn_idx = env->prev_insn_idx;
9764 if (!env->insn_aux_data[insn_idx].prune_point)
9765 /* this 'insn_idx' instruction wasn't marked, so we will not
9766 * be doing state search here
9767 */
9768 return 0;
9769
9770 /* bpf progs typically have pruning point every 4 instructions
9771 * http://vger.kernel.org/bpfconf2019.html#session-1
9772 * Do not add new state for future pruning if the verifier hasn't seen
9773 * at least 2 jumps and at least 8 instructions.
9774 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9775 * In tests that amounts to up to 50% reduction into total verifier
9776 * memory consumption and 20% verifier time speedup.
9777 */
9778 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9779 env->insn_processed - env->prev_insn_processed >= 8)
9780 add_new_state = true;
9781
9782 pprev = explored_state(env, insn_idx);
9783 sl = *pprev;
9784
9785 clean_live_states(env, insn_idx, cur);
9786
9787 while (sl) {
9788 states_cnt++;
9789 if (sl->state.insn_idx != insn_idx)
9790 goto next;
9791 if (sl->state.branches) {
9792 if (states_maybe_looping(&sl->state, cur) &&
9793 states_equal(env, &sl->state, cur)) {
9794 verbose_linfo(env, insn_idx, "; ");
9795 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9796 return -EINVAL;
9797 }
9798 /* if the verifier is processing a loop, avoid adding new state
9799 * too often, since different loop iterations have distinct
9800 * states and may not help future pruning.
9801 * This threshold shouldn't be too low to make sure that
9802 * a loop with large bound will be rejected quickly.
9803 * The most abusive loop will be:
9804 * r1 += 1
9805 * if r1 < 1000000 goto pc-2
9806 * 1M insn_procssed limit / 100 == 10k peak states.
9807 * This threshold shouldn't be too high either, since states
9808 * at the end of the loop are likely to be useful in pruning.
9809 */
9810 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9811 env->insn_processed - env->prev_insn_processed < 100)
9812 add_new_state = false;
9813 goto miss;
9814 }
9815 if (states_equal(env, &sl->state, cur)) {
9816 sl->hit_cnt++;
9817 /* reached equivalent register/stack state,
9818 * prune the search.
9819 * Registers read by the continuation are read by us.
9820 * If we have any write marks in env->cur_state, they
9821 * will prevent corresponding reads in the continuation
9822 * from reaching our parent (an explored_state). Our
9823 * own state will get the read marks recorded, but
9824 * they'll be immediately forgotten as we're pruning
9825 * this state and will pop a new one.
9826 */
9827 err = propagate_liveness(env, &sl->state, cur);
9828
9829 /* if previous state reached the exit with precision and
9830 * current state is equivalent to it (except precsion marks)
9831 * the precision needs to be propagated back in
9832 * the current state.
9833 */
9834 err = err ? : push_jmp_history(env, cur);
9835 err = err ? : propagate_precision(env, &sl->state);
9836 if (err)
9837 return err;
9838 return 1;
9839 }
9840 miss:
9841 /* when new state is not going to be added do not increase miss count.
9842 * Otherwise several loop iterations will remove the state
9843 * recorded earlier. The goal of these heuristics is to have
9844 * states from some iterations of the loop (some in the beginning
9845 * and some at the end) to help pruning.
9846 */
9847 if (add_new_state)
9848 sl->miss_cnt++;
9849 /* heuristic to determine whether this state is beneficial
9850 * to keep checking from state equivalence point of view.
9851 * Higher numbers increase max_states_per_insn and verification time,
9852 * but do not meaningfully decrease insn_processed.
9853 */
9854 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9855 /* the state is unlikely to be useful. Remove it to
9856 * speed up verification
9857 */
9858 *pprev = sl->next;
9859 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
9860 u32 br = sl->state.branches;
9861
9862 WARN_ONCE(br,
9863 "BUG live_done but branches_to_explore %d\n",
9864 br);
9865 free_verifier_state(&sl->state, false);
9866 kfree(sl);
9867 env->peak_states--;
9868 } else {
9869 /* cannot free this state, since parentage chain may
9870 * walk it later. Add it for free_list instead to
9871 * be freed at the end of verification
9872 */
9873 sl->next = env->free_list;
9874 env->free_list = sl;
9875 }
9876 sl = *pprev;
9877 continue;
9878 }
9879 next:
9880 pprev = &sl->next;
9881 sl = *pprev;
9882 }
9883
9884 if (env->max_states_per_insn < states_cnt)
9885 env->max_states_per_insn = states_cnt;
9886
9887 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
9888 return push_jmp_history(env, cur);
9889
9890 if (!add_new_state)
9891 return push_jmp_history(env, cur);
9892
9893 /* There were no equivalent states, remember the current one.
9894 * Technically the current state is not proven to be safe yet,
9895 * but it will either reach outer most bpf_exit (which means it's safe)
9896 * or it will be rejected. When there are no loops the verifier won't be
9897 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
9898 * again on the way to bpf_exit.
9899 * When looping the sl->state.branches will be > 0 and this state
9900 * will not be considered for equivalence until branches == 0.
9901 */
9902 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
9903 if (!new_sl)
9904 return -ENOMEM;
9905 env->total_states++;
9906 env->peak_states++;
9907 env->prev_jmps_processed = env->jmps_processed;
9908 env->prev_insn_processed = env->insn_processed;
9909
9910 /* forget precise markings we inherited, see __mark_chain_precision */
9911 if (env->bpf_capable)
9912 mark_all_scalars_imprecise(env, cur);
9913
9914 /* add new state to the head of linked list */
9915 new = &new_sl->state;
9916 err = copy_verifier_state(new, cur);
9917 if (err) {
9918 free_verifier_state(new, false);
9919 kfree(new_sl);
9920 return err;
9921 }
9922 new->insn_idx = insn_idx;
9923 WARN_ONCE(new->branches != 1,
9924 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
9925
9926 cur->parent = new;
9927 cur->first_insn_idx = insn_idx;
9928 clear_jmp_history(cur);
9929 new_sl->next = *explored_state(env, insn_idx);
9930 *explored_state(env, insn_idx) = new_sl;
9931 /* connect new state to parentage chain. Current frame needs all
9932 * registers connected. Only r6 - r9 of the callers are alive (pushed
9933 * to the stack implicitly by JITs) so in callers' frames connect just
9934 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9935 * the state of the call instruction (with WRITTEN set), and r0 comes
9936 * from callee with its full parentage chain, anyway.
9937 */
9938 /* clear write marks in current state: the writes we did are not writes
9939 * our child did, so they don't screen off its reads from us.
9940 * (There are no read marks in current state, because reads always mark
9941 * their parent and current state never has children yet. Only
9942 * explored_states can get read marks.)
9943 */
9944 for (j = 0; j <= cur->curframe; j++) {
9945 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9946 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9947 for (i = 0; i < BPF_REG_FP; i++)
9948 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9949 }
9950
9951 /* all stack frames are accessible from callee, clear them all */
9952 for (j = 0; j <= cur->curframe; j++) {
9953 struct bpf_func_state *frame = cur->frame[j];
9954 struct bpf_func_state *newframe = new->frame[j];
9955
9956 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
9957 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
9958 frame->stack[i].spilled_ptr.parent =
9959 &newframe->stack[i].spilled_ptr;
9960 }
9961 }
9962 return 0;
9963 }
9964
9965 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)9966 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9967 {
9968 switch (type) {
9969 case PTR_TO_CTX:
9970 case PTR_TO_SOCKET:
9971 case PTR_TO_SOCKET_OR_NULL:
9972 case PTR_TO_SOCK_COMMON:
9973 case PTR_TO_SOCK_COMMON_OR_NULL:
9974 case PTR_TO_TCP_SOCK:
9975 case PTR_TO_TCP_SOCK_OR_NULL:
9976 case PTR_TO_XDP_SOCK:
9977 case PTR_TO_BTF_ID:
9978 case PTR_TO_BTF_ID_OR_NULL:
9979 return false;
9980 default:
9981 return true;
9982 }
9983 }
9984
9985 /* If an instruction was previously used with particular pointer types, then we
9986 * need to be careful to avoid cases such as the below, where it may be ok
9987 * for one branch accessing the pointer, but not ok for the other branch:
9988 *
9989 * R1 = sock_ptr
9990 * goto X;
9991 * ...
9992 * R1 = some_other_valid_ptr;
9993 * goto X;
9994 * ...
9995 * R2 = *(u32 *)(R1 + 0);
9996 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)9997 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9998 {
9999 return src != prev && (!reg_type_mismatch_ok(src) ||
10000 !reg_type_mismatch_ok(prev));
10001 }
10002
do_check(struct bpf_verifier_env * env)10003 static int do_check(struct bpf_verifier_env *env)
10004 {
10005 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
10006 struct bpf_verifier_state *state = env->cur_state;
10007 struct bpf_insn *insns = env->prog->insnsi;
10008 struct bpf_reg_state *regs;
10009 int insn_cnt = env->prog->len;
10010 bool do_print_state = false;
10011 int prev_insn_idx = -1;
10012
10013 for (;;) {
10014 struct bpf_insn *insn;
10015 u8 class;
10016 int err;
10017
10018 env->prev_insn_idx = prev_insn_idx;
10019 if (env->insn_idx >= insn_cnt) {
10020 verbose(env, "invalid insn idx %d insn_cnt %d\n",
10021 env->insn_idx, insn_cnt);
10022 return -EFAULT;
10023 }
10024
10025 insn = &insns[env->insn_idx];
10026 class = BPF_CLASS(insn->code);
10027
10028 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
10029 verbose(env,
10030 "BPF program is too large. Processed %d insn\n",
10031 env->insn_processed);
10032 return -E2BIG;
10033 }
10034
10035 err = is_state_visited(env, env->insn_idx);
10036 if (err < 0)
10037 return err;
10038 if (err == 1) {
10039 /* found equivalent state, can prune the search */
10040 if (env->log.level & BPF_LOG_LEVEL) {
10041 if (do_print_state)
10042 verbose(env, "\nfrom %d to %d%s: safe\n",
10043 env->prev_insn_idx, env->insn_idx,
10044 env->cur_state->speculative ?
10045 " (speculative execution)" : "");
10046 else
10047 verbose(env, "%d: safe\n", env->insn_idx);
10048 }
10049 goto process_bpf_exit;
10050 }
10051
10052 if (signal_pending(current))
10053 return -EAGAIN;
10054
10055 if (need_resched())
10056 cond_resched();
10057
10058 if (env->log.level & BPF_LOG_LEVEL2 ||
10059 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10060 if (env->log.level & BPF_LOG_LEVEL2)
10061 verbose(env, "%d:", env->insn_idx);
10062 else
10063 verbose(env, "\nfrom %d to %d%s:",
10064 env->prev_insn_idx, env->insn_idx,
10065 env->cur_state->speculative ?
10066 " (speculative execution)" : "");
10067 print_verifier_state(env, state->frame[state->curframe]);
10068 do_print_state = false;
10069 }
10070
10071 if (env->log.level & BPF_LOG_LEVEL) {
10072 const struct bpf_insn_cbs cbs = {
10073 .cb_print = verbose,
10074 .private_data = env,
10075 };
10076
10077 verbose_linfo(env, env->insn_idx, "; ");
10078 verbose(env, "%d: ", env->insn_idx);
10079 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
10080 }
10081
10082 if (bpf_prog_is_dev_bound(env->prog->aux)) {
10083 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10084 env->prev_insn_idx);
10085 if (err)
10086 return err;
10087 }
10088
10089 regs = cur_regs(env);
10090 sanitize_mark_insn_seen(env);
10091 prev_insn_idx = env->insn_idx;
10092
10093 if (class == BPF_ALU || class == BPF_ALU64) {
10094 err = check_alu_op(env, insn);
10095 if (err)
10096 return err;
10097
10098 } else if (class == BPF_LDX) {
10099 enum bpf_reg_type *prev_src_type, src_reg_type;
10100
10101 /* check for reserved fields is already done */
10102
10103 /* check src operand */
10104 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10105 if (err)
10106 return err;
10107
10108 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
10109 if (err)
10110 return err;
10111
10112 src_reg_type = regs[insn->src_reg].type;
10113
10114 /* check that memory (src_reg + off) is readable,
10115 * the state of dst_reg will be updated by this func
10116 */
10117 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10118 insn->off, BPF_SIZE(insn->code),
10119 BPF_READ, insn->dst_reg, false);
10120 if (err)
10121 return err;
10122
10123 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10124
10125 if (*prev_src_type == NOT_INIT) {
10126 /* saw a valid insn
10127 * dst_reg = *(u32 *)(src_reg + off)
10128 * save type to validate intersecting paths
10129 */
10130 *prev_src_type = src_reg_type;
10131
10132 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
10133 /* ABuser program is trying to use the same insn
10134 * dst_reg = *(u32*) (src_reg + off)
10135 * with different pointer types:
10136 * src_reg == ctx in one branch and
10137 * src_reg == stack|map in some other branch.
10138 * Reject it.
10139 */
10140 verbose(env, "same insn cannot be used with different pointers\n");
10141 return -EINVAL;
10142 }
10143
10144 } else if (class == BPF_STX) {
10145 enum bpf_reg_type *prev_dst_type, dst_reg_type;
10146
10147 if (BPF_MODE(insn->code) == BPF_XADD) {
10148 err = check_xadd(env, env->insn_idx, insn);
10149 if (err)
10150 return err;
10151 env->insn_idx++;
10152 continue;
10153 }
10154
10155 /* check src1 operand */
10156 err = check_reg_arg(env, insn->src_reg, SRC_OP);
10157 if (err)
10158 return err;
10159 /* check src2 operand */
10160 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10161 if (err)
10162 return err;
10163
10164 dst_reg_type = regs[insn->dst_reg].type;
10165
10166 /* check that memory (dst_reg + off) is writeable */
10167 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10168 insn->off, BPF_SIZE(insn->code),
10169 BPF_WRITE, insn->src_reg, false);
10170 if (err)
10171 return err;
10172
10173 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
10174
10175 if (*prev_dst_type == NOT_INIT) {
10176 *prev_dst_type = dst_reg_type;
10177 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
10178 verbose(env, "same insn cannot be used with different pointers\n");
10179 return -EINVAL;
10180 }
10181
10182 } else if (class == BPF_ST) {
10183 if (BPF_MODE(insn->code) != BPF_MEM ||
10184 insn->src_reg != BPF_REG_0) {
10185 verbose(env, "BPF_ST uses reserved fields\n");
10186 return -EINVAL;
10187 }
10188 /* check src operand */
10189 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
10190 if (err)
10191 return err;
10192
10193 if (is_ctx_reg(env, insn->dst_reg)) {
10194 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
10195 insn->dst_reg,
10196 reg_type_str[reg_state(env, insn->dst_reg)->type]);
10197 return -EACCES;
10198 }
10199
10200 /* check that memory (dst_reg + off) is writeable */
10201 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10202 insn->off, BPF_SIZE(insn->code),
10203 BPF_WRITE, -1, false);
10204 if (err)
10205 return err;
10206
10207 } else if (class == BPF_JMP || class == BPF_JMP32) {
10208 u8 opcode = BPF_OP(insn->code);
10209
10210 env->jmps_processed++;
10211 if (opcode == BPF_CALL) {
10212 if (BPF_SRC(insn->code) != BPF_K ||
10213 insn->off != 0 ||
10214 (insn->src_reg != BPF_REG_0 &&
10215 insn->src_reg != BPF_PSEUDO_CALL) ||
10216 insn->dst_reg != BPF_REG_0 ||
10217 class == BPF_JMP32) {
10218 verbose(env, "BPF_CALL uses reserved fields\n");
10219 return -EINVAL;
10220 }
10221
10222 if (env->cur_state->active_spin_lock &&
10223 (insn->src_reg == BPF_PSEUDO_CALL ||
10224 insn->imm != BPF_FUNC_spin_unlock)) {
10225 verbose(env, "function calls are not allowed while holding a lock\n");
10226 return -EINVAL;
10227 }
10228 if (insn->src_reg == BPF_PSEUDO_CALL)
10229 err = check_func_call(env, insn, &env->insn_idx);
10230 else
10231 err = check_helper_call(env, insn->imm, env->insn_idx);
10232 if (err)
10233 return err;
10234
10235 } else if (opcode == BPF_JA) {
10236 if (BPF_SRC(insn->code) != BPF_K ||
10237 insn->imm != 0 ||
10238 insn->src_reg != BPF_REG_0 ||
10239 insn->dst_reg != BPF_REG_0 ||
10240 class == BPF_JMP32) {
10241 verbose(env, "BPF_JA uses reserved fields\n");
10242 return -EINVAL;
10243 }
10244
10245 env->insn_idx += insn->off + 1;
10246 continue;
10247
10248 } else if (opcode == BPF_EXIT) {
10249 if (BPF_SRC(insn->code) != BPF_K ||
10250 insn->imm != 0 ||
10251 insn->src_reg != BPF_REG_0 ||
10252 insn->dst_reg != BPF_REG_0 ||
10253 class == BPF_JMP32) {
10254 verbose(env, "BPF_EXIT uses reserved fields\n");
10255 return -EINVAL;
10256 }
10257
10258 if (env->cur_state->active_spin_lock) {
10259 verbose(env, "bpf_spin_unlock is missing\n");
10260 return -EINVAL;
10261 }
10262
10263 if (state->curframe) {
10264 /* exit from nested function */
10265 err = prepare_func_exit(env, &env->insn_idx);
10266 if (err)
10267 return err;
10268 do_print_state = true;
10269 continue;
10270 }
10271
10272 err = check_reference_leak(env);
10273 if (err)
10274 return err;
10275
10276 err = check_return_code(env);
10277 if (err)
10278 return err;
10279 process_bpf_exit:
10280 update_branch_counts(env, env->cur_state);
10281 err = pop_stack(env, &prev_insn_idx,
10282 &env->insn_idx, pop_log);
10283 if (err < 0) {
10284 if (err != -ENOENT)
10285 return err;
10286 break;
10287 } else {
10288 do_print_state = true;
10289 continue;
10290 }
10291 } else {
10292 err = check_cond_jmp_op(env, insn, &env->insn_idx);
10293 if (err)
10294 return err;
10295 }
10296 } else if (class == BPF_LD) {
10297 u8 mode = BPF_MODE(insn->code);
10298
10299 if (mode == BPF_ABS || mode == BPF_IND) {
10300 err = check_ld_abs(env, insn);
10301 if (err)
10302 return err;
10303
10304 } else if (mode == BPF_IMM) {
10305 err = check_ld_imm(env, insn);
10306 if (err)
10307 return err;
10308
10309 env->insn_idx++;
10310 sanitize_mark_insn_seen(env);
10311 } else {
10312 verbose(env, "invalid BPF_LD mode\n");
10313 return -EINVAL;
10314 }
10315 } else {
10316 verbose(env, "unknown insn class %d\n", class);
10317 return -EINVAL;
10318 }
10319
10320 env->insn_idx++;
10321 }
10322
10323 return 0;
10324 }
10325
10326 /* 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)10327 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10328 struct bpf_insn *insn,
10329 struct bpf_insn_aux_data *aux)
10330 {
10331 const struct btf_var_secinfo *vsi;
10332 const struct btf_type *datasec;
10333 const struct btf_type *t;
10334 const char *sym_name;
10335 bool percpu = false;
10336 u32 type, id = insn->imm;
10337 s32 datasec_id;
10338 u64 addr;
10339 int i;
10340
10341 if (!btf_vmlinux) {
10342 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10343 return -EINVAL;
10344 }
10345
10346 if (insn[1].imm != 0) {
10347 verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
10348 return -EINVAL;
10349 }
10350
10351 t = btf_type_by_id(btf_vmlinux, id);
10352 if (!t) {
10353 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
10354 return -ENOENT;
10355 }
10356
10357 if (!btf_type_is_var(t)) {
10358 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
10359 id);
10360 return -EINVAL;
10361 }
10362
10363 sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
10364 addr = kallsyms_lookup_name(sym_name);
10365 if (!addr) {
10366 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10367 sym_name);
10368 return -ENOENT;
10369 }
10370
10371 datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
10372 BTF_KIND_DATASEC);
10373 if (datasec_id > 0) {
10374 datasec = btf_type_by_id(btf_vmlinux, datasec_id);
10375 for_each_vsi(i, datasec, vsi) {
10376 if (vsi->type == id) {
10377 percpu = true;
10378 break;
10379 }
10380 }
10381 }
10382
10383 insn[0].imm = (u32)addr;
10384 insn[1].imm = addr >> 32;
10385
10386 type = t->type;
10387 t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
10388 if (percpu) {
10389 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
10390 aux->btf_var.btf_id = type;
10391 } else if (!btf_type_is_struct(t)) {
10392 const struct btf_type *ret;
10393 const char *tname;
10394 u32 tsize;
10395
10396 /* resolve the type size of ksym. */
10397 ret = btf_resolve_size(btf_vmlinux, t, &tsize);
10398 if (IS_ERR(ret)) {
10399 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
10400 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10401 tname, PTR_ERR(ret));
10402 return -EINVAL;
10403 }
10404 aux->btf_var.reg_type = PTR_TO_MEM;
10405 aux->btf_var.mem_size = tsize;
10406 } else {
10407 aux->btf_var.reg_type = PTR_TO_BTF_ID;
10408 aux->btf_var.btf_id = type;
10409 }
10410 return 0;
10411 }
10412
check_map_prealloc(struct bpf_map * map)10413 static int check_map_prealloc(struct bpf_map *map)
10414 {
10415 return (map->map_type != BPF_MAP_TYPE_HASH &&
10416 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10417 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
10418 !(map->map_flags & BPF_F_NO_PREALLOC);
10419 }
10420
is_tracing_prog_type(enum bpf_prog_type type)10421 static bool is_tracing_prog_type(enum bpf_prog_type type)
10422 {
10423 switch (type) {
10424 case BPF_PROG_TYPE_KPROBE:
10425 case BPF_PROG_TYPE_TRACEPOINT:
10426 case BPF_PROG_TYPE_PERF_EVENT:
10427 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10428 return true;
10429 default:
10430 return false;
10431 }
10432 }
10433
is_preallocated_map(struct bpf_map * map)10434 static bool is_preallocated_map(struct bpf_map *map)
10435 {
10436 if (!check_map_prealloc(map))
10437 return false;
10438 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10439 return false;
10440 return true;
10441 }
10442
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)10443 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10444 struct bpf_map *map,
10445 struct bpf_prog *prog)
10446
10447 {
10448 enum bpf_prog_type prog_type = resolve_prog_type(prog);
10449 /*
10450 * Validate that trace type programs use preallocated hash maps.
10451 *
10452 * For programs attached to PERF events this is mandatory as the
10453 * perf NMI can hit any arbitrary code sequence.
10454 *
10455 * All other trace types using preallocated hash maps are unsafe as
10456 * well because tracepoint or kprobes can be inside locked regions
10457 * of the memory allocator or at a place where a recursion into the
10458 * memory allocator would see inconsistent state.
10459 *
10460 * On RT enabled kernels run-time allocation of all trace type
10461 * programs is strictly prohibited due to lock type constraints. On
10462 * !RT kernels it is allowed for backwards compatibility reasons for
10463 * now, but warnings are emitted so developers are made aware of
10464 * the unsafety and can fix their programs before this is enforced.
10465 */
10466 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10467 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
10468 verbose(env, "perf_event programs can only use preallocated hash map\n");
10469 return -EINVAL;
10470 }
10471 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10472 verbose(env, "trace type programs can only use preallocated hash map\n");
10473 return -EINVAL;
10474 }
10475 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10476 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
10477 }
10478
10479 if ((is_tracing_prog_type(prog_type) ||
10480 prog_type == BPF_PROG_TYPE_SOCKET_FILTER) &&
10481 map_value_has_spin_lock(map)) {
10482 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10483 return -EINVAL;
10484 }
10485
10486 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
10487 !bpf_offload_prog_map_match(prog, map)) {
10488 verbose(env, "offload device mismatch between prog and map\n");
10489 return -EINVAL;
10490 }
10491
10492 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10493 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10494 return -EINVAL;
10495 }
10496
10497 if (prog->aux->sleepable)
10498 switch (map->map_type) {
10499 case BPF_MAP_TYPE_HASH:
10500 case BPF_MAP_TYPE_LRU_HASH:
10501 case BPF_MAP_TYPE_ARRAY:
10502 if (!is_preallocated_map(map)) {
10503 verbose(env,
10504 "Sleepable programs can only use preallocated hash maps\n");
10505 return -EINVAL;
10506 }
10507 break;
10508 default:
10509 verbose(env,
10510 "Sleepable programs can only use array and hash maps\n");
10511 return -EINVAL;
10512 }
10513
10514 return 0;
10515 }
10516
bpf_map_is_cgroup_storage(struct bpf_map * map)10517 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10518 {
10519 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10520 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10521 }
10522
10523 /* find and rewrite pseudo imm in ld_imm64 instructions:
10524 *
10525 * 1. if it accesses map FD, replace it with actual map pointer.
10526 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10527 *
10528 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
10529 */
resolve_pseudo_ldimm64(struct bpf_verifier_env * env)10530 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
10531 {
10532 struct bpf_insn *insn = env->prog->insnsi;
10533 int insn_cnt = env->prog->len;
10534 int i, j, err;
10535
10536 err = bpf_prog_calc_tag(env->prog);
10537 if (err)
10538 return err;
10539
10540 for (i = 0; i < insn_cnt; i++, insn++) {
10541 if (BPF_CLASS(insn->code) == BPF_LDX &&
10542 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
10543 verbose(env, "BPF_LDX uses reserved fields\n");
10544 return -EINVAL;
10545 }
10546
10547 if (BPF_CLASS(insn->code) == BPF_STX &&
10548 ((BPF_MODE(insn->code) != BPF_MEM &&
10549 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
10550 verbose(env, "BPF_STX uses reserved fields\n");
10551 return -EINVAL;
10552 }
10553
10554 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
10555 struct bpf_insn_aux_data *aux;
10556 struct bpf_map *map;
10557 struct fd f;
10558 u64 addr;
10559
10560 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10561 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10562 insn[1].off != 0) {
10563 verbose(env, "invalid bpf_ld_imm64 insn\n");
10564 return -EINVAL;
10565 }
10566
10567 if (insn[0].src_reg == 0)
10568 /* valid generic load 64-bit imm */
10569 goto next_insn;
10570
10571 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10572 aux = &env->insn_aux_data[i];
10573 err = check_pseudo_btf_id(env, insn, aux);
10574 if (err)
10575 return err;
10576 goto next_insn;
10577 }
10578
10579 /* In final convert_pseudo_ld_imm64() step, this is
10580 * converted into regular 64-bit imm load insn.
10581 */
10582 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10583 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10584 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10585 insn[1].imm != 0)) {
10586 verbose(env,
10587 "unrecognized bpf_ld_imm64 insn\n");
10588 return -EINVAL;
10589 }
10590
10591 f = fdget(insn[0].imm);
10592 map = __bpf_map_get(f);
10593 if (IS_ERR(map)) {
10594 verbose(env, "fd %d is not pointing to valid bpf_map\n",
10595 insn[0].imm);
10596 return PTR_ERR(map);
10597 }
10598
10599 err = check_map_prog_compatibility(env, map, env->prog);
10600 if (err) {
10601 fdput(f);
10602 return err;
10603 }
10604
10605 aux = &env->insn_aux_data[i];
10606 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10607 addr = (unsigned long)map;
10608 } else {
10609 u32 off = insn[1].imm;
10610
10611 if (off >= BPF_MAX_VAR_OFF) {
10612 verbose(env, "direct value offset of %u is not allowed\n", off);
10613 fdput(f);
10614 return -EINVAL;
10615 }
10616
10617 if (!map->ops->map_direct_value_addr) {
10618 verbose(env, "no direct value access support for this map type\n");
10619 fdput(f);
10620 return -EINVAL;
10621 }
10622
10623 err = map->ops->map_direct_value_addr(map, &addr, off);
10624 if (err) {
10625 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10626 map->value_size, off);
10627 fdput(f);
10628 return err;
10629 }
10630
10631 aux->map_off = off;
10632 addr += off;
10633 }
10634
10635 insn[0].imm = (u32)addr;
10636 insn[1].imm = addr >> 32;
10637
10638 /* check whether we recorded this map already */
10639 for (j = 0; j < env->used_map_cnt; j++) {
10640 if (env->used_maps[j] == map) {
10641 aux->map_index = j;
10642 fdput(f);
10643 goto next_insn;
10644 }
10645 }
10646
10647 if (env->used_map_cnt >= MAX_USED_MAPS) {
10648 fdput(f);
10649 return -E2BIG;
10650 }
10651
10652 /* hold the map. If the program is rejected by verifier,
10653 * the map will be released by release_maps() or it
10654 * will be used by the valid program until it's unloaded
10655 * and all maps are released in free_used_maps()
10656 */
10657 bpf_map_inc(map);
10658
10659 aux->map_index = env->used_map_cnt;
10660 env->used_maps[env->used_map_cnt++] = map;
10661
10662 if (bpf_map_is_cgroup_storage(map) &&
10663 bpf_cgroup_storage_assign(env->prog->aux, map)) {
10664 verbose(env, "only one cgroup storage of each type is allowed\n");
10665 fdput(f);
10666 return -EBUSY;
10667 }
10668
10669 fdput(f);
10670 next_insn:
10671 insn++;
10672 i++;
10673 continue;
10674 }
10675
10676 /* Basic sanity check before we invest more work here. */
10677 if (!bpf_opcode_in_insntable(insn->code)) {
10678 verbose(env, "unknown opcode %02x\n", insn->code);
10679 return -EINVAL;
10680 }
10681 }
10682
10683 /* now all pseudo BPF_LD_IMM64 instructions load valid
10684 * 'struct bpf_map *' into a register instead of user map_fd.
10685 * These pointers will be used later by verifier to validate map access.
10686 */
10687 return 0;
10688 }
10689
10690 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)10691 static void release_maps(struct bpf_verifier_env *env)
10692 {
10693 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10694 env->used_map_cnt);
10695 }
10696
10697 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)10698 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
10699 {
10700 struct bpf_insn *insn = env->prog->insnsi;
10701 int insn_cnt = env->prog->len;
10702 int i;
10703
10704 for (i = 0; i < insn_cnt; i++, insn++)
10705 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10706 insn->src_reg = 0;
10707 }
10708
10709 /* single env->prog->insni[off] instruction was replaced with the range
10710 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10711 * [0, off) and [off, end) to new locations, so the patched range stays zero
10712 */
adjust_insn_aux_data(struct bpf_verifier_env * env,struct bpf_insn_aux_data * new_data,struct bpf_prog * new_prog,u32 off,u32 cnt)10713 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
10714 struct bpf_insn_aux_data *new_data,
10715 struct bpf_prog *new_prog, u32 off, u32 cnt)
10716 {
10717 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
10718 struct bpf_insn *insn = new_prog->insnsi;
10719 u32 old_seen = old_data[off].seen;
10720 u32 prog_len;
10721 int i;
10722
10723 /* aux info at OFF always needs adjustment, no matter fast path
10724 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10725 * original insn at old prog.
10726 */
10727 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10728
10729 if (cnt == 1)
10730 return;
10731 prog_len = new_prog->len;
10732
10733 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10734 memcpy(new_data + off + cnt - 1, old_data + off,
10735 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
10736 for (i = off; i < off + cnt - 1; i++) {
10737 /* Expand insni[off]'s seen count to the patched range. */
10738 new_data[i].seen = old_seen;
10739 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10740 }
10741 env->insn_aux_data = new_data;
10742 vfree(old_data);
10743 }
10744
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)10745 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10746 {
10747 int i;
10748
10749 if (len == 1)
10750 return;
10751 /* NOTE: fake 'exit' subprog should be updated as well. */
10752 for (i = 0; i <= env->subprog_cnt; i++) {
10753 if (env->subprog_info[i].start <= off)
10754 continue;
10755 env->subprog_info[i].start += len - 1;
10756 }
10757 }
10758
adjust_poke_descs(struct bpf_prog * prog,u32 off,u32 len)10759 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
10760 {
10761 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10762 int i, sz = prog->aux->size_poke_tab;
10763 struct bpf_jit_poke_descriptor *desc;
10764
10765 for (i = 0; i < sz; i++) {
10766 desc = &tab[i];
10767 if (desc->insn_idx <= off)
10768 continue;
10769 desc->insn_idx += len - 1;
10770 }
10771 }
10772
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)10773 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10774 const struct bpf_insn *patch, u32 len)
10775 {
10776 struct bpf_prog *new_prog;
10777 struct bpf_insn_aux_data *new_data = NULL;
10778
10779 if (len > 1) {
10780 new_data = vzalloc(array_size(env->prog->len + len - 1,
10781 sizeof(struct bpf_insn_aux_data)));
10782 if (!new_data)
10783 return NULL;
10784 }
10785
10786 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
10787 if (IS_ERR(new_prog)) {
10788 if (PTR_ERR(new_prog) == -ERANGE)
10789 verbose(env,
10790 "insn %d cannot be patched due to 16-bit range\n",
10791 env->insn_aux_data[off].orig_idx);
10792 vfree(new_data);
10793 return NULL;
10794 }
10795 adjust_insn_aux_data(env, new_data, new_prog, off, len);
10796 adjust_subprog_starts(env, off, len);
10797 adjust_poke_descs(new_prog, off, len);
10798 return new_prog;
10799 }
10800
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10801 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10802 u32 off, u32 cnt)
10803 {
10804 int i, j;
10805
10806 /* find first prog starting at or after off (first to remove) */
10807 for (i = 0; i < env->subprog_cnt; i++)
10808 if (env->subprog_info[i].start >= off)
10809 break;
10810 /* find first prog starting at or after off + cnt (first to stay) */
10811 for (j = i; j < env->subprog_cnt; j++)
10812 if (env->subprog_info[j].start >= off + cnt)
10813 break;
10814 /* if j doesn't start exactly at off + cnt, we are just removing
10815 * the front of previous prog
10816 */
10817 if (env->subprog_info[j].start != off + cnt)
10818 j--;
10819
10820 if (j > i) {
10821 struct bpf_prog_aux *aux = env->prog->aux;
10822 int move;
10823
10824 /* move fake 'exit' subprog as well */
10825 move = env->subprog_cnt + 1 - j;
10826
10827 memmove(env->subprog_info + i,
10828 env->subprog_info + j,
10829 sizeof(*env->subprog_info) * move);
10830 env->subprog_cnt -= j - i;
10831
10832 /* remove func_info */
10833 if (aux->func_info) {
10834 move = aux->func_info_cnt - j;
10835
10836 memmove(aux->func_info + i,
10837 aux->func_info + j,
10838 sizeof(*aux->func_info) * move);
10839 aux->func_info_cnt -= j - i;
10840 /* func_info->insn_off is set after all code rewrites,
10841 * in adjust_btf_func() - no need to adjust
10842 */
10843 }
10844 } else {
10845 /* convert i from "first prog to remove" to "first to adjust" */
10846 if (env->subprog_info[i].start == off)
10847 i++;
10848 }
10849
10850 /* update fake 'exit' subprog as well */
10851 for (; i <= env->subprog_cnt; i++)
10852 env->subprog_info[i].start -= cnt;
10853
10854 return 0;
10855 }
10856
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)10857 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10858 u32 cnt)
10859 {
10860 struct bpf_prog *prog = env->prog;
10861 u32 i, l_off, l_cnt, nr_linfo;
10862 struct bpf_line_info *linfo;
10863
10864 nr_linfo = prog->aux->nr_linfo;
10865 if (!nr_linfo)
10866 return 0;
10867
10868 linfo = prog->aux->linfo;
10869
10870 /* find first line info to remove, count lines to be removed */
10871 for (i = 0; i < nr_linfo; i++)
10872 if (linfo[i].insn_off >= off)
10873 break;
10874
10875 l_off = i;
10876 l_cnt = 0;
10877 for (; i < nr_linfo; i++)
10878 if (linfo[i].insn_off < off + cnt)
10879 l_cnt++;
10880 else
10881 break;
10882
10883 /* First live insn doesn't match first live linfo, it needs to "inherit"
10884 * last removed linfo. prog is already modified, so prog->len == off
10885 * means no live instructions after (tail of the program was removed).
10886 */
10887 if (prog->len != off && l_cnt &&
10888 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10889 l_cnt--;
10890 linfo[--i].insn_off = off + cnt;
10891 }
10892
10893 /* remove the line info which refer to the removed instructions */
10894 if (l_cnt) {
10895 memmove(linfo + l_off, linfo + i,
10896 sizeof(*linfo) * (nr_linfo - i));
10897
10898 prog->aux->nr_linfo -= l_cnt;
10899 nr_linfo = prog->aux->nr_linfo;
10900 }
10901
10902 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10903 for (i = l_off; i < nr_linfo; i++)
10904 linfo[i].insn_off -= cnt;
10905
10906 /* fix up all subprogs (incl. 'exit') which start >= off */
10907 for (i = 0; i <= env->subprog_cnt; i++)
10908 if (env->subprog_info[i].linfo_idx > l_off) {
10909 /* program may have started in the removed region but
10910 * may not be fully removed
10911 */
10912 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10913 env->subprog_info[i].linfo_idx -= l_cnt;
10914 else
10915 env->subprog_info[i].linfo_idx = l_off;
10916 }
10917
10918 return 0;
10919 }
10920
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)10921 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10922 {
10923 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10924 unsigned int orig_prog_len = env->prog->len;
10925 int err;
10926
10927 if (bpf_prog_is_dev_bound(env->prog->aux))
10928 bpf_prog_offload_remove_insns(env, off, cnt);
10929
10930 err = bpf_remove_insns(env->prog, off, cnt);
10931 if (err)
10932 return err;
10933
10934 err = adjust_subprog_starts_after_remove(env, off, cnt);
10935 if (err)
10936 return err;
10937
10938 err = bpf_adj_linfo_after_remove(env, off, cnt);
10939 if (err)
10940 return err;
10941
10942 memmove(aux_data + off, aux_data + off + cnt,
10943 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10944
10945 return 0;
10946 }
10947
10948 /* The verifier does more data flow analysis than llvm and will not
10949 * explore branches that are dead at run time. Malicious programs can
10950 * have dead code too. Therefore replace all dead at-run-time code
10951 * with 'ja -1'.
10952 *
10953 * Just nops are not optimal, e.g. if they would sit at the end of the
10954 * program and through another bug we would manage to jump there, then
10955 * we'd execute beyond program memory otherwise. Returning exception
10956 * code also wouldn't work since we can have subprogs where the dead
10957 * code could be located.
10958 */
sanitize_dead_code(struct bpf_verifier_env * env)10959 static void sanitize_dead_code(struct bpf_verifier_env *env)
10960 {
10961 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10962 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
10963 struct bpf_insn *insn = env->prog->insnsi;
10964 const int insn_cnt = env->prog->len;
10965 int i;
10966
10967 for (i = 0; i < insn_cnt; i++) {
10968 if (aux_data[i].seen)
10969 continue;
10970 memcpy(insn + i, &trap, sizeof(trap));
10971 aux_data[i].zext_dst = false;
10972 }
10973 }
10974
insn_is_cond_jump(u8 code)10975 static bool insn_is_cond_jump(u8 code)
10976 {
10977 u8 op;
10978
10979 if (BPF_CLASS(code) == BPF_JMP32)
10980 return true;
10981
10982 if (BPF_CLASS(code) != BPF_JMP)
10983 return false;
10984
10985 op = BPF_OP(code);
10986 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10987 }
10988
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)10989 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10990 {
10991 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10992 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10993 struct bpf_insn *insn = env->prog->insnsi;
10994 const int insn_cnt = env->prog->len;
10995 int i;
10996
10997 for (i = 0; i < insn_cnt; i++, insn++) {
10998 if (!insn_is_cond_jump(insn->code))
10999 continue;
11000
11001 if (!aux_data[i + 1].seen)
11002 ja.off = insn->off;
11003 else if (!aux_data[i + 1 + insn->off].seen)
11004 ja.off = 0;
11005 else
11006 continue;
11007
11008 if (bpf_prog_is_dev_bound(env->prog->aux))
11009 bpf_prog_offload_replace_insn(env, i, &ja);
11010
11011 memcpy(insn, &ja, sizeof(ja));
11012 }
11013 }
11014
opt_remove_dead_code(struct bpf_verifier_env * env)11015 static int opt_remove_dead_code(struct bpf_verifier_env *env)
11016 {
11017 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11018 int insn_cnt = env->prog->len;
11019 int i, err;
11020
11021 for (i = 0; i < insn_cnt; i++) {
11022 int j;
11023
11024 j = 0;
11025 while (i + j < insn_cnt && !aux_data[i + j].seen)
11026 j++;
11027 if (!j)
11028 continue;
11029
11030 err = verifier_remove_insns(env, i, j);
11031 if (err)
11032 return err;
11033 insn_cnt = env->prog->len;
11034 }
11035
11036 return 0;
11037 }
11038
opt_remove_nops(struct bpf_verifier_env * env)11039 static int opt_remove_nops(struct bpf_verifier_env *env)
11040 {
11041 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11042 struct bpf_insn *insn = env->prog->insnsi;
11043 int insn_cnt = env->prog->len;
11044 int i, err;
11045
11046 for (i = 0; i < insn_cnt; i++) {
11047 if (memcmp(&insn[i], &ja, sizeof(ja)))
11048 continue;
11049
11050 err = verifier_remove_insns(env, i, 1);
11051 if (err)
11052 return err;
11053 insn_cnt--;
11054 i--;
11055 }
11056
11057 return 0;
11058 }
11059
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)11060 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11061 const union bpf_attr *attr)
11062 {
11063 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
11064 struct bpf_insn_aux_data *aux = env->insn_aux_data;
11065 int i, patch_len, delta = 0, len = env->prog->len;
11066 struct bpf_insn *insns = env->prog->insnsi;
11067 struct bpf_prog *new_prog;
11068 bool rnd_hi32;
11069
11070 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
11071 zext_patch[1] = BPF_ZEXT_REG(0);
11072 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11073 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11074 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
11075 for (i = 0; i < len; i++) {
11076 int adj_idx = i + delta;
11077 struct bpf_insn insn;
11078
11079 insn = insns[adj_idx];
11080 if (!aux[adj_idx].zext_dst) {
11081 u8 code, class;
11082 u32 imm_rnd;
11083
11084 if (!rnd_hi32)
11085 continue;
11086
11087 code = insn.code;
11088 class = BPF_CLASS(code);
11089 if (insn_no_def(&insn))
11090 continue;
11091
11092 /* NOTE: arg "reg" (the fourth one) is only used for
11093 * BPF_STX which has been ruled out in above
11094 * check, it is safe to pass NULL here.
11095 */
11096 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11097 if (class == BPF_LD &&
11098 BPF_MODE(code) == BPF_IMM)
11099 i++;
11100 continue;
11101 }
11102
11103 /* ctx load could be transformed into wider load. */
11104 if (class == BPF_LDX &&
11105 aux[adj_idx].ptr_type == PTR_TO_CTX)
11106 continue;
11107
11108 imm_rnd = get_random_int();
11109 rnd_hi32_patch[0] = insn;
11110 rnd_hi32_patch[1].imm = imm_rnd;
11111 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11112 patch = rnd_hi32_patch;
11113 patch_len = 4;
11114 goto apply_patch_buffer;
11115 }
11116
11117 if (!bpf_jit_needs_zext())
11118 continue;
11119
11120 zext_patch[0] = insn;
11121 zext_patch[1].dst_reg = insn.dst_reg;
11122 zext_patch[1].src_reg = insn.dst_reg;
11123 patch = zext_patch;
11124 patch_len = 2;
11125 apply_patch_buffer:
11126 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
11127 if (!new_prog)
11128 return -ENOMEM;
11129 env->prog = new_prog;
11130 insns = new_prog->insnsi;
11131 aux = env->insn_aux_data;
11132 delta += patch_len - 1;
11133 }
11134
11135 return 0;
11136 }
11137
11138 /* convert load instructions that access fields of a context type into a
11139 * sequence of instructions that access fields of the underlying structure:
11140 * struct __sk_buff -> struct sk_buff
11141 * struct bpf_sock_ops -> struct sock
11142 */
convert_ctx_accesses(struct bpf_verifier_env * env)11143 static int convert_ctx_accesses(struct bpf_verifier_env *env)
11144 {
11145 const struct bpf_verifier_ops *ops = env->ops;
11146 int i, cnt, size, ctx_field_size, delta = 0;
11147 const int insn_cnt = env->prog->len;
11148 struct bpf_insn insn_buf[16], *insn;
11149 u32 target_size, size_default, off;
11150 struct bpf_prog *new_prog;
11151 enum bpf_access_type type;
11152 bool is_narrower_load;
11153
11154 if (ops->gen_prologue || env->seen_direct_write) {
11155 if (!ops->gen_prologue) {
11156 verbose(env, "bpf verifier is misconfigured\n");
11157 return -EINVAL;
11158 }
11159 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11160 env->prog);
11161 if (cnt >= ARRAY_SIZE(insn_buf)) {
11162 verbose(env, "bpf verifier is misconfigured\n");
11163 return -EINVAL;
11164 } else if (cnt) {
11165 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
11166 if (!new_prog)
11167 return -ENOMEM;
11168
11169 env->prog = new_prog;
11170 delta += cnt - 1;
11171 }
11172 }
11173
11174 if (bpf_prog_is_dev_bound(env->prog->aux))
11175 return 0;
11176
11177 insn = env->prog->insnsi + delta;
11178
11179 for (i = 0; i < insn_cnt; i++, insn++) {
11180 bpf_convert_ctx_access_t convert_ctx_access;
11181 bool ctx_access;
11182
11183 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11184 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11185 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
11186 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
11187 type = BPF_READ;
11188 ctx_access = true;
11189 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11190 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11191 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11192 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11193 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11194 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11195 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11196 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
11197 type = BPF_WRITE;
11198 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11199 } else {
11200 continue;
11201 }
11202
11203 if (type == BPF_WRITE &&
11204 env->insn_aux_data[i + delta].sanitize_stack_spill) {
11205 struct bpf_insn patch[] = {
11206 *insn,
11207 BPF_ST_NOSPEC(),
11208 };
11209
11210 cnt = ARRAY_SIZE(patch);
11211 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11212 if (!new_prog)
11213 return -ENOMEM;
11214
11215 delta += cnt - 1;
11216 env->prog = new_prog;
11217 insn = new_prog->insnsi + i + delta;
11218 continue;
11219 }
11220
11221 if (!ctx_access)
11222 continue;
11223
11224 switch (env->insn_aux_data[i + delta].ptr_type) {
11225 case PTR_TO_CTX:
11226 if (!ops->convert_ctx_access)
11227 continue;
11228 convert_ctx_access = ops->convert_ctx_access;
11229 break;
11230 case PTR_TO_SOCKET:
11231 case PTR_TO_SOCK_COMMON:
11232 convert_ctx_access = bpf_sock_convert_ctx_access;
11233 break;
11234 case PTR_TO_TCP_SOCK:
11235 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11236 break;
11237 case PTR_TO_XDP_SOCK:
11238 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11239 break;
11240 case PTR_TO_BTF_ID:
11241 if (type == BPF_READ) {
11242 insn->code = BPF_LDX | BPF_PROBE_MEM |
11243 BPF_SIZE((insn)->code);
11244 env->prog->aux->num_exentries++;
11245 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
11246 verbose(env, "Writes through BTF pointers are not allowed\n");
11247 return -EINVAL;
11248 }
11249 continue;
11250 default:
11251 continue;
11252 }
11253
11254 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
11255 size = BPF_LDST_BYTES(insn);
11256
11257 /* If the read access is a narrower load of the field,
11258 * convert to a 4/8-byte load, to minimum program type specific
11259 * convert_ctx_access changes. If conversion is successful,
11260 * we will apply proper mask to the result.
11261 */
11262 is_narrower_load = size < ctx_field_size;
11263 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11264 off = insn->off;
11265 if (is_narrower_load) {
11266 u8 size_code;
11267
11268 if (type == BPF_WRITE) {
11269 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
11270 return -EINVAL;
11271 }
11272
11273 size_code = BPF_H;
11274 if (ctx_field_size == 4)
11275 size_code = BPF_W;
11276 else if (ctx_field_size == 8)
11277 size_code = BPF_DW;
11278
11279 insn->off = off & ~(size_default - 1);
11280 insn->code = BPF_LDX | BPF_MEM | size_code;
11281 }
11282
11283 target_size = 0;
11284 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11285 &target_size);
11286 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11287 (ctx_field_size && !target_size)) {
11288 verbose(env, "bpf verifier is misconfigured\n");
11289 return -EINVAL;
11290 }
11291
11292 if (is_narrower_load && size < target_size) {
11293 u8 shift = bpf_ctx_narrow_access_offset(
11294 off, size, size_default) * 8;
11295 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
11296 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
11297 return -EINVAL;
11298 }
11299 if (ctx_field_size <= 4) {
11300 if (shift)
11301 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11302 insn->dst_reg,
11303 shift);
11304 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11305 (1 << size * 8) - 1);
11306 } else {
11307 if (shift)
11308 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11309 insn->dst_reg,
11310 shift);
11311 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
11312 (1ULL << size * 8) - 1);
11313 }
11314 }
11315
11316 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11317 if (!new_prog)
11318 return -ENOMEM;
11319
11320 delta += cnt - 1;
11321
11322 /* keep walking new program and skip insns we just inserted */
11323 env->prog = new_prog;
11324 insn = new_prog->insnsi + i + delta;
11325 }
11326
11327 return 0;
11328 }
11329
jit_subprogs(struct bpf_verifier_env * env)11330 static int jit_subprogs(struct bpf_verifier_env *env)
11331 {
11332 struct bpf_prog *prog = env->prog, **func, *tmp;
11333 int i, j, subprog_start, subprog_end = 0, len, subprog;
11334 struct bpf_map *map_ptr;
11335 struct bpf_insn *insn;
11336 void *old_bpf_func;
11337 int err, num_exentries;
11338
11339 if (env->subprog_cnt <= 1)
11340 return 0;
11341
11342 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11343 if (insn->code != (BPF_JMP | BPF_CALL) ||
11344 insn->src_reg != BPF_PSEUDO_CALL)
11345 continue;
11346 /* Upon error here we cannot fall back to interpreter but
11347 * need a hard reject of the program. Thus -EFAULT is
11348 * propagated in any case.
11349 */
11350 subprog = find_subprog(env, i + insn->imm + 1);
11351 if (subprog < 0) {
11352 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11353 i + insn->imm + 1);
11354 return -EFAULT;
11355 }
11356 /* temporarily remember subprog id inside insn instead of
11357 * aux_data, since next loop will split up all insns into funcs
11358 */
11359 insn->off = subprog;
11360 /* remember original imm in case JIT fails and fallback
11361 * to interpreter will be needed
11362 */
11363 env->insn_aux_data[i].call_imm = insn->imm;
11364 /* point imm to __bpf_call_base+1 from JITs point of view */
11365 insn->imm = 1;
11366 }
11367
11368 err = bpf_prog_alloc_jited_linfo(prog);
11369 if (err)
11370 goto out_undo_insn;
11371
11372 err = -ENOMEM;
11373 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
11374 if (!func)
11375 goto out_undo_insn;
11376
11377 for (i = 0; i < env->subprog_cnt; i++) {
11378 subprog_start = subprog_end;
11379 subprog_end = env->subprog_info[i + 1].start;
11380
11381 len = subprog_end - subprog_start;
11382 /* BPF_PROG_RUN doesn't call subprogs directly,
11383 * hence main prog stats include the runtime of subprogs.
11384 * subprogs don't have IDs and not reachable via prog_get_next_id
11385 * func[i]->aux->stats will never be accessed and stays NULL
11386 */
11387 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
11388 if (!func[i])
11389 goto out_free;
11390 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11391 len * sizeof(struct bpf_insn));
11392 func[i]->type = prog->type;
11393 func[i]->len = len;
11394 if (bpf_prog_calc_tag(func[i]))
11395 goto out_free;
11396 func[i]->is_func = 1;
11397 func[i]->aux->func_idx = i;
11398 /* the btf and func_info will be freed only at prog->aux */
11399 func[i]->aux->btf = prog->aux->btf;
11400 func[i]->aux->func_info = prog->aux->func_info;
11401 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
11402
11403 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11404 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11405 int ret;
11406
11407 if (!(insn_idx >= subprog_start &&
11408 insn_idx <= subprog_end))
11409 continue;
11410
11411 ret = bpf_jit_add_poke_descriptor(func[i],
11412 &prog->aux->poke_tab[j]);
11413 if (ret < 0) {
11414 verbose(env, "adding tail call poke descriptor failed\n");
11415 goto out_free;
11416 }
11417
11418 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11419
11420 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11421 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11422 if (ret < 0) {
11423 verbose(env, "tracking tail call prog failed\n");
11424 goto out_free;
11425 }
11426 }
11427
11428 func[i]->aux->name[0] = 'F';
11429 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
11430 func[i]->jit_requested = 1;
11431 func[i]->aux->linfo = prog->aux->linfo;
11432 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11433 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11434 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
11435 num_exentries = 0;
11436 insn = func[i]->insnsi;
11437 for (j = 0; j < func[i]->len; j++, insn++) {
11438 if (BPF_CLASS(insn->code) == BPF_LDX &&
11439 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11440 num_exentries++;
11441 }
11442 func[i]->aux->num_exentries = num_exentries;
11443 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
11444 func[i] = bpf_int_jit_compile(func[i]);
11445 if (!func[i]->jited) {
11446 err = -ENOTSUPP;
11447 goto out_free;
11448 }
11449 cond_resched();
11450 }
11451
11452 /* Untrack main program's aux structs so that during map_poke_run()
11453 * we will not stumble upon the unfilled poke descriptors; each
11454 * of the main program's poke descs got distributed across subprogs
11455 * and got tracked onto map, so we are sure that none of them will
11456 * be missed after the operation below
11457 */
11458 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11459 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11460
11461 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11462 }
11463
11464 /* at this point all bpf functions were successfully JITed
11465 * now populate all bpf_calls with correct addresses and
11466 * run last pass of JIT
11467 */
11468 for (i = 0; i < env->subprog_cnt; i++) {
11469 insn = func[i]->insnsi;
11470 for (j = 0; j < func[i]->len; j++, insn++) {
11471 if (insn->code != (BPF_JMP | BPF_CALL) ||
11472 insn->src_reg != BPF_PSEUDO_CALL)
11473 continue;
11474 subprog = insn->off;
11475 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11476 __bpf_call_base;
11477 }
11478
11479 /* we use the aux data to keep a list of the start addresses
11480 * of the JITed images for each function in the program
11481 *
11482 * for some architectures, such as powerpc64, the imm field
11483 * might not be large enough to hold the offset of the start
11484 * address of the callee's JITed image from __bpf_call_base
11485 *
11486 * in such cases, we can lookup the start address of a callee
11487 * by using its subprog id, available from the off field of
11488 * the call instruction, as an index for this list
11489 */
11490 func[i]->aux->func = func;
11491 func[i]->aux->func_cnt = env->subprog_cnt;
11492 }
11493 for (i = 0; i < env->subprog_cnt; i++) {
11494 old_bpf_func = func[i]->bpf_func;
11495 tmp = bpf_int_jit_compile(func[i]);
11496 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11497 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
11498 err = -ENOTSUPP;
11499 goto out_free;
11500 }
11501 cond_resched();
11502 }
11503
11504 /* finally lock prog and jit images for all functions and
11505 * populate kallsysm
11506 */
11507 for (i = 0; i < env->subprog_cnt; i++) {
11508 bpf_prog_lock_ro(func[i]);
11509 bpf_prog_kallsyms_add(func[i]);
11510 }
11511
11512 /* Last step: make now unused interpreter insns from main
11513 * prog consistent for later dump requests, so they can
11514 * later look the same as if they were interpreted only.
11515 */
11516 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11517 if (insn->code != (BPF_JMP | BPF_CALL) ||
11518 insn->src_reg != BPF_PSEUDO_CALL)
11519 continue;
11520 insn->off = env->insn_aux_data[i].call_imm;
11521 subprog = find_subprog(env, i + insn->off + 1);
11522 insn->imm = subprog;
11523 }
11524
11525 prog->jited = 1;
11526 prog->bpf_func = func[0]->bpf_func;
11527 prog->aux->func = func;
11528 prog->aux->func_cnt = env->subprog_cnt;
11529 bpf_prog_free_unused_jited_linfo(prog);
11530 return 0;
11531 out_free:
11532 for (i = 0; i < env->subprog_cnt; i++) {
11533 if (!func[i])
11534 continue;
11535
11536 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11537 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11538 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11539 }
11540 bpf_jit_free(func[i]);
11541 }
11542 kfree(func);
11543 out_undo_insn:
11544 /* cleanup main prog to be interpreted */
11545 prog->jit_requested = 0;
11546 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
11547 if (insn->code != (BPF_JMP | BPF_CALL) ||
11548 insn->src_reg != BPF_PSEUDO_CALL)
11549 continue;
11550 insn->off = 0;
11551 insn->imm = env->insn_aux_data[i].call_imm;
11552 }
11553 bpf_prog_free_jited_linfo(prog);
11554 return err;
11555 }
11556
fixup_call_args(struct bpf_verifier_env * env)11557 static int fixup_call_args(struct bpf_verifier_env *env)
11558 {
11559 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11560 struct bpf_prog *prog = env->prog;
11561 struct bpf_insn *insn = prog->insnsi;
11562 int i, depth;
11563 #endif
11564 int err = 0;
11565
11566 if (env->prog->jit_requested &&
11567 !bpf_prog_is_dev_bound(env->prog->aux)) {
11568 err = jit_subprogs(env);
11569 if (err == 0)
11570 return 0;
11571 if (err == -EFAULT)
11572 return err;
11573 }
11574 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
11575 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11576 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11577 * have to be rejected, since interpreter doesn't support them yet.
11578 */
11579 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11580 return -EINVAL;
11581 }
11582 for (i = 0; i < prog->len; i++, insn++) {
11583 if (insn->code != (BPF_JMP | BPF_CALL) ||
11584 insn->src_reg != BPF_PSEUDO_CALL)
11585 continue;
11586 depth = get_callee_stack_depth(env, insn, i);
11587 if (depth < 0)
11588 return depth;
11589 bpf_patch_call_args(insn, depth);
11590 }
11591 err = 0;
11592 #endif
11593 return err;
11594 }
11595
11596 /* fixup insn->imm field of bpf_call instructions
11597 * and inline eligible helpers as explicit sequence of BPF instructions
11598 *
11599 * this function is called after eBPF program passed verification
11600 */
fixup_bpf_calls(struct bpf_verifier_env * env)11601 static int fixup_bpf_calls(struct bpf_verifier_env *env)
11602 {
11603 struct bpf_prog *prog = env->prog;
11604 bool expect_blinding = bpf_jit_blinding_enabled(prog);
11605 struct bpf_insn *insn = prog->insnsi;
11606 const struct bpf_func_proto *fn;
11607 const int insn_cnt = prog->len;
11608 const struct bpf_map_ops *ops;
11609 struct bpf_insn_aux_data *aux;
11610 struct bpf_insn insn_buf[16];
11611 struct bpf_prog *new_prog;
11612 struct bpf_map *map_ptr;
11613 int i, ret, cnt, delta = 0;
11614
11615 for (i = 0; i < insn_cnt; i++, insn++) {
11616 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11617 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11618 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
11619 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11620 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11621 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11622 struct bpf_insn *patchlet;
11623 struct bpf_insn chk_and_div[] = {
11624 /* [R,W]x div 0 -> 0 */
11625 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11626 BPF_JNE | BPF_K, insn->src_reg,
11627 0, 2, 0),
11628 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11629 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11630 *insn,
11631 };
11632 struct bpf_insn chk_and_mod[] = {
11633 /* [R,W]x mod 0 -> [R,W]x */
11634 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11635 BPF_JEQ | BPF_K, insn->src_reg,
11636 0, 1 + (is64 ? 0 : 1), 0),
11637 *insn,
11638 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11639 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
11640 };
11641
11642 patchlet = isdiv ? chk_and_div : chk_and_mod;
11643 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
11644 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
11645
11646 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
11647 if (!new_prog)
11648 return -ENOMEM;
11649
11650 delta += cnt - 1;
11651 env->prog = prog = new_prog;
11652 insn = new_prog->insnsi + i + delta;
11653 continue;
11654 }
11655
11656 if (BPF_CLASS(insn->code) == BPF_LD &&
11657 (BPF_MODE(insn->code) == BPF_ABS ||
11658 BPF_MODE(insn->code) == BPF_IND)) {
11659 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11660 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11661 verbose(env, "bpf verifier is misconfigured\n");
11662 return -EINVAL;
11663 }
11664
11665 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11666 if (!new_prog)
11667 return -ENOMEM;
11668
11669 delta += cnt - 1;
11670 env->prog = prog = new_prog;
11671 insn = new_prog->insnsi + i + delta;
11672 continue;
11673 }
11674
11675 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11676 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11677 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11678 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11679 struct bpf_insn insn_buf[16];
11680 struct bpf_insn *patch = &insn_buf[0];
11681 bool issrc, isneg, isimm;
11682 u32 off_reg;
11683
11684 aux = &env->insn_aux_data[i + delta];
11685 if (!aux->alu_state ||
11686 aux->alu_state == BPF_ALU_NON_POINTER)
11687 continue;
11688
11689 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11690 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11691 BPF_ALU_SANITIZE_SRC;
11692 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
11693
11694 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11695 if (isimm) {
11696 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11697 } else {
11698 if (isneg)
11699 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11700 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
11701 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11702 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11703 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11704 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11705 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
11706 }
11707 if (!issrc)
11708 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
11709 insn->src_reg = BPF_REG_AX;
11710 if (isneg)
11711 insn->code = insn->code == code_add ?
11712 code_sub : code_add;
11713 *patch++ = *insn;
11714 if (issrc && isneg && !isimm)
11715 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11716 cnt = patch - insn_buf;
11717
11718 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11719 if (!new_prog)
11720 return -ENOMEM;
11721
11722 delta += cnt - 1;
11723 env->prog = prog = new_prog;
11724 insn = new_prog->insnsi + i + delta;
11725 continue;
11726 }
11727
11728 if (insn->code != (BPF_JMP | BPF_CALL))
11729 continue;
11730 if (insn->src_reg == BPF_PSEUDO_CALL)
11731 continue;
11732
11733 if (insn->imm == BPF_FUNC_get_route_realm)
11734 prog->dst_needed = 1;
11735 if (insn->imm == BPF_FUNC_get_prandom_u32)
11736 bpf_user_rnd_init_once();
11737 if (insn->imm == BPF_FUNC_override_return)
11738 prog->kprobe_override = 1;
11739 if (insn->imm == BPF_FUNC_tail_call) {
11740 /* If we tail call into other programs, we
11741 * cannot make any assumptions since they can
11742 * be replaced dynamically during runtime in
11743 * the program array.
11744 */
11745 prog->cb_access = 1;
11746 if (!allow_tail_call_in_subprogs(env))
11747 prog->aux->stack_depth = MAX_BPF_STACK;
11748 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
11749
11750 /* mark bpf_tail_call as different opcode to avoid
11751 * conditional branch in the interpeter for every normal
11752 * call and to prevent accidental JITing by JIT compiler
11753 * that doesn't support bpf_tail_call yet
11754 */
11755 insn->imm = 0;
11756 insn->code = BPF_JMP | BPF_TAIL_CALL;
11757
11758 aux = &env->insn_aux_data[i + delta];
11759 if (env->bpf_capable && !expect_blinding &&
11760 prog->jit_requested &&
11761 !bpf_map_key_poisoned(aux) &&
11762 !bpf_map_ptr_poisoned(aux) &&
11763 !bpf_map_ptr_unpriv(aux)) {
11764 struct bpf_jit_poke_descriptor desc = {
11765 .reason = BPF_POKE_REASON_TAIL_CALL,
11766 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11767 .tail_call.key = bpf_map_key_immediate(aux),
11768 .insn_idx = i + delta,
11769 };
11770
11771 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11772 if (ret < 0) {
11773 verbose(env, "adding tail call poke descriptor failed\n");
11774 return ret;
11775 }
11776
11777 insn->imm = ret + 1;
11778 continue;
11779 }
11780
11781 if (!bpf_map_ptr_unpriv(aux))
11782 continue;
11783
11784 /* instead of changing every JIT dealing with tail_call
11785 * emit two extra insns:
11786 * if (index >= max_entries) goto out;
11787 * index &= array->index_mask;
11788 * to avoid out-of-bounds cpu speculation
11789 */
11790 if (bpf_map_ptr_poisoned(aux)) {
11791 verbose(env, "tail_call abusing map_ptr\n");
11792 return -EINVAL;
11793 }
11794
11795 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11796 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11797 map_ptr->max_entries, 2);
11798 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11799 container_of(map_ptr,
11800 struct bpf_array,
11801 map)->index_mask);
11802 insn_buf[2] = *insn;
11803 cnt = 3;
11804 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11805 if (!new_prog)
11806 return -ENOMEM;
11807
11808 delta += cnt - 1;
11809 env->prog = prog = new_prog;
11810 insn = new_prog->insnsi + i + delta;
11811 continue;
11812 }
11813
11814 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
11815 * and other inlining handlers are currently limited to 64 bit
11816 * only.
11817 */
11818 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11819 (insn->imm == BPF_FUNC_map_lookup_elem ||
11820 insn->imm == BPF_FUNC_map_update_elem ||
11821 insn->imm == BPF_FUNC_map_delete_elem ||
11822 insn->imm == BPF_FUNC_map_push_elem ||
11823 insn->imm == BPF_FUNC_map_pop_elem ||
11824 insn->imm == BPF_FUNC_map_peek_elem)) {
11825 aux = &env->insn_aux_data[i + delta];
11826 if (bpf_map_ptr_poisoned(aux))
11827 goto patch_call_imm;
11828
11829 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
11830 ops = map_ptr->ops;
11831 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11832 ops->map_gen_lookup) {
11833 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
11834 if (cnt == -EOPNOTSUPP)
11835 goto patch_map_ops_generic;
11836 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11837 verbose(env, "bpf verifier is misconfigured\n");
11838 return -EINVAL;
11839 }
11840
11841 new_prog = bpf_patch_insn_data(env, i + delta,
11842 insn_buf, cnt);
11843 if (!new_prog)
11844 return -ENOMEM;
11845
11846 delta += cnt - 1;
11847 env->prog = prog = new_prog;
11848 insn = new_prog->insnsi + i + delta;
11849 continue;
11850 }
11851
11852 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11853 (void *(*)(struct bpf_map *map, void *key))NULL));
11854 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11855 (int (*)(struct bpf_map *map, void *key))NULL));
11856 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11857 (int (*)(struct bpf_map *map, void *key, void *value,
11858 u64 flags))NULL));
11859 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11860 (int (*)(struct bpf_map *map, void *value,
11861 u64 flags))NULL));
11862 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11863 (int (*)(struct bpf_map *map, void *value))NULL));
11864 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11865 (int (*)(struct bpf_map *map, void *value))NULL));
11866 patch_map_ops_generic:
11867 switch (insn->imm) {
11868 case BPF_FUNC_map_lookup_elem:
11869 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11870 __bpf_call_base;
11871 continue;
11872 case BPF_FUNC_map_update_elem:
11873 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11874 __bpf_call_base;
11875 continue;
11876 case BPF_FUNC_map_delete_elem:
11877 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11878 __bpf_call_base;
11879 continue;
11880 case BPF_FUNC_map_push_elem:
11881 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11882 __bpf_call_base;
11883 continue;
11884 case BPF_FUNC_map_pop_elem:
11885 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11886 __bpf_call_base;
11887 continue;
11888 case BPF_FUNC_map_peek_elem:
11889 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11890 __bpf_call_base;
11891 continue;
11892 }
11893
11894 goto patch_call_imm;
11895 }
11896
11897 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11898 insn->imm == BPF_FUNC_jiffies64) {
11899 struct bpf_insn ld_jiffies_addr[2] = {
11900 BPF_LD_IMM64(BPF_REG_0,
11901 (unsigned long)&jiffies),
11902 };
11903
11904 insn_buf[0] = ld_jiffies_addr[0];
11905 insn_buf[1] = ld_jiffies_addr[1];
11906 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11907 BPF_REG_0, 0);
11908 cnt = 3;
11909
11910 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11911 cnt);
11912 if (!new_prog)
11913 return -ENOMEM;
11914
11915 delta += cnt - 1;
11916 env->prog = prog = new_prog;
11917 insn = new_prog->insnsi + i + delta;
11918 continue;
11919 }
11920
11921 patch_call_imm:
11922 fn = env->ops->get_func_proto(insn->imm, env->prog);
11923 /* all functions that have prototype and verifier allowed
11924 * programs to call them, must be real in-kernel functions
11925 */
11926 if (!fn->func) {
11927 verbose(env,
11928 "kernel subsystem misconfigured func %s#%d\n",
11929 func_id_name(insn->imm), insn->imm);
11930 return -EFAULT;
11931 }
11932 insn->imm = fn->func - __bpf_call_base;
11933 }
11934
11935 /* Since poke tab is now finalized, publish aux to tracker. */
11936 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11937 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11938 if (!map_ptr->ops->map_poke_track ||
11939 !map_ptr->ops->map_poke_untrack ||
11940 !map_ptr->ops->map_poke_run) {
11941 verbose(env, "bpf verifier is misconfigured\n");
11942 return -EINVAL;
11943 }
11944
11945 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11946 if (ret < 0) {
11947 verbose(env, "tracking tail call prog failed\n");
11948 return ret;
11949 }
11950 }
11951
11952 return 0;
11953 }
11954
free_states(struct bpf_verifier_env * env)11955 static void free_states(struct bpf_verifier_env *env)
11956 {
11957 struct bpf_verifier_state_list *sl, *sln;
11958 int i;
11959
11960 sl = env->free_list;
11961 while (sl) {
11962 sln = sl->next;
11963 free_verifier_state(&sl->state, false);
11964 kfree(sl);
11965 sl = sln;
11966 }
11967 env->free_list = NULL;
11968
11969 if (!env->explored_states)
11970 return;
11971
11972 for (i = 0; i < state_htab_size(env); i++) {
11973 sl = env->explored_states[i];
11974
11975 while (sl) {
11976 sln = sl->next;
11977 free_verifier_state(&sl->state, false);
11978 kfree(sl);
11979 sl = sln;
11980 }
11981 env->explored_states[i] = NULL;
11982 }
11983 }
11984
do_check_common(struct bpf_verifier_env * env,int subprog)11985 static int do_check_common(struct bpf_verifier_env *env, int subprog)
11986 {
11987 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
11988 struct bpf_verifier_state *state;
11989 struct bpf_reg_state *regs;
11990 int ret, i;
11991
11992 env->prev_linfo = NULL;
11993 env->pass_cnt++;
11994
11995 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11996 if (!state)
11997 return -ENOMEM;
11998 state->curframe = 0;
11999 state->speculative = false;
12000 state->branches = 1;
12001 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12002 if (!state->frame[0]) {
12003 kfree(state);
12004 return -ENOMEM;
12005 }
12006 env->cur_state = state;
12007 init_func_state(env, state->frame[0],
12008 BPF_MAIN_FUNC /* callsite */,
12009 0 /* frameno */,
12010 subprog);
12011
12012 state->first_insn_idx = env->subprog_info[subprog].start;
12013 state->last_insn_idx = -1;
12014
12015 regs = state->frame[state->curframe]->regs;
12016 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
12017 ret = btf_prepare_func_args(env, subprog, regs);
12018 if (ret)
12019 goto out;
12020 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12021 if (regs[i].type == PTR_TO_CTX)
12022 mark_reg_known_zero(env, regs, i);
12023 else if (regs[i].type == SCALAR_VALUE)
12024 mark_reg_unknown(env, regs, i);
12025 }
12026 } else {
12027 /* 1st arg to a function */
12028 regs[BPF_REG_1].type = PTR_TO_CTX;
12029 mark_reg_known_zero(env, regs, BPF_REG_1);
12030 ret = btf_check_func_arg_match(env, subprog, regs);
12031 if (ret == -EFAULT)
12032 /* unlikely verifier bug. abort.
12033 * ret == 0 and ret < 0 are sadly acceptable for
12034 * main() function due to backward compatibility.
12035 * Like socket filter program may be written as:
12036 * int bpf_prog(struct pt_regs *ctx)
12037 * and never dereference that ctx in the program.
12038 * 'struct pt_regs' is a type mismatch for socket
12039 * filter that should be using 'struct __sk_buff'.
12040 */
12041 goto out;
12042 }
12043
12044 ret = do_check(env);
12045 out:
12046 /* check for NULL is necessary, since cur_state can be freed inside
12047 * do_check() under memory pressure.
12048 */
12049 if (env->cur_state) {
12050 free_verifier_state(env->cur_state, true);
12051 env->cur_state = NULL;
12052 }
12053 while (!pop_stack(env, NULL, NULL, false));
12054 if (!ret && pop_log)
12055 bpf_vlog_reset(&env->log, 0);
12056 free_states(env);
12057 return ret;
12058 }
12059
12060 /* Verify all global functions in a BPF program one by one based on their BTF.
12061 * All global functions must pass verification. Otherwise the whole program is rejected.
12062 * Consider:
12063 * int bar(int);
12064 * int foo(int f)
12065 * {
12066 * return bar(f);
12067 * }
12068 * int bar(int b)
12069 * {
12070 * ...
12071 * }
12072 * foo() will be verified first for R1=any_scalar_value. During verification it
12073 * will be assumed that bar() already verified successfully and call to bar()
12074 * from foo() will be checked for type match only. Later bar() will be verified
12075 * independently to check that it's safe for R1=any_scalar_value.
12076 */
do_check_subprogs(struct bpf_verifier_env * env)12077 static int do_check_subprogs(struct bpf_verifier_env *env)
12078 {
12079 struct bpf_prog_aux *aux = env->prog->aux;
12080 int i, ret;
12081
12082 if (!aux->func_info)
12083 return 0;
12084
12085 for (i = 1; i < env->subprog_cnt; i++) {
12086 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12087 continue;
12088 env->insn_idx = env->subprog_info[i].start;
12089 WARN_ON_ONCE(env->insn_idx == 0);
12090 ret = do_check_common(env, i);
12091 if (ret) {
12092 return ret;
12093 } else if (env->log.level & BPF_LOG_LEVEL) {
12094 verbose(env,
12095 "Func#%d is safe for any args that match its prototype\n",
12096 i);
12097 }
12098 }
12099 return 0;
12100 }
12101
do_check_main(struct bpf_verifier_env * env)12102 static int do_check_main(struct bpf_verifier_env *env)
12103 {
12104 int ret;
12105
12106 env->insn_idx = 0;
12107 ret = do_check_common(env, 0);
12108 if (!ret)
12109 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12110 return ret;
12111 }
12112
12113
print_verification_stats(struct bpf_verifier_env * env)12114 static void print_verification_stats(struct bpf_verifier_env *env)
12115 {
12116 int i;
12117
12118 if (env->log.level & BPF_LOG_STATS) {
12119 verbose(env, "verification time %lld usec\n",
12120 div_u64(env->verification_time, 1000));
12121 verbose(env, "stack depth ");
12122 for (i = 0; i < env->subprog_cnt; i++) {
12123 u32 depth = env->subprog_info[i].stack_depth;
12124
12125 verbose(env, "%d", depth);
12126 if (i + 1 < env->subprog_cnt)
12127 verbose(env, "+");
12128 }
12129 verbose(env, "\n");
12130 }
12131 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12132 "total_states %d peak_states %d mark_read %d\n",
12133 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12134 env->max_states_per_insn, env->total_states,
12135 env->peak_states, env->longest_mark_read_walk);
12136 }
12137
check_struct_ops_btf_id(struct bpf_verifier_env * env)12138 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12139 {
12140 const struct btf_type *t, *func_proto;
12141 const struct bpf_struct_ops *st_ops;
12142 const struct btf_member *member;
12143 struct bpf_prog *prog = env->prog;
12144 u32 btf_id, member_idx;
12145 const char *mname;
12146
12147 if (!prog->gpl_compatible) {
12148 verbose(env, "struct ops programs must have a GPL compatible license\n");
12149 return -EINVAL;
12150 }
12151
12152 btf_id = prog->aux->attach_btf_id;
12153 st_ops = bpf_struct_ops_find(btf_id);
12154 if (!st_ops) {
12155 verbose(env, "attach_btf_id %u is not a supported struct\n",
12156 btf_id);
12157 return -ENOTSUPP;
12158 }
12159
12160 t = st_ops->type;
12161 member_idx = prog->expected_attach_type;
12162 if (member_idx >= btf_type_vlen(t)) {
12163 verbose(env, "attach to invalid member idx %u of struct %s\n",
12164 member_idx, st_ops->name);
12165 return -EINVAL;
12166 }
12167
12168 member = &btf_type_member(t)[member_idx];
12169 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12170 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12171 NULL);
12172 if (!func_proto) {
12173 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12174 mname, member_idx, st_ops->name);
12175 return -EINVAL;
12176 }
12177
12178 if (st_ops->check_member) {
12179 int err = st_ops->check_member(t, member);
12180
12181 if (err) {
12182 verbose(env, "attach to unsupported member %s of struct %s\n",
12183 mname, st_ops->name);
12184 return err;
12185 }
12186 }
12187
12188 prog->aux->attach_func_proto = func_proto;
12189 prog->aux->attach_func_name = mname;
12190 env->ops = st_ops->verifier_ops;
12191
12192 return 0;
12193 }
12194 #define SECURITY_PREFIX "security_"
12195
check_attach_modify_return(unsigned long addr,const char * func_name)12196 static int check_attach_modify_return(unsigned long addr, const char *func_name)
12197 {
12198 if (within_error_injection_list(addr) ||
12199 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
12200 return 0;
12201
12202 return -EINVAL;
12203 }
12204
12205 /* non exhaustive list of sleepable bpf_lsm_*() functions */
12206 BTF_SET_START(btf_sleepable_lsm_hooks)
12207 #ifdef CONFIG_BPF_LSM
BTF_ID(func,bpf_lsm_bprm_committed_creds)12208 BTF_ID(func, bpf_lsm_bprm_committed_creds)
12209 #else
12210 BTF_ID_UNUSED
12211 #endif
12212 BTF_SET_END(btf_sleepable_lsm_hooks)
12213
12214 static int check_sleepable_lsm_hook(u32 btf_id)
12215 {
12216 return btf_id_set_contains(&btf_sleepable_lsm_hooks, btf_id);
12217 }
12218
12219 /* list of non-sleepable functions that are otherwise on
12220 * ALLOW_ERROR_INJECTION list
12221 */
12222 BTF_SET_START(btf_non_sleepable_error_inject)
12223 /* Three functions below can be called from sleepable and non-sleepable context.
12224 * Assume non-sleepable from bpf safety point of view.
12225 */
BTF_ID(func,__add_to_page_cache_locked)12226 BTF_ID(func, __add_to_page_cache_locked)
12227 BTF_ID(func, should_fail_alloc_page)
12228 BTF_ID(func, should_failslab)
12229 BTF_SET_END(btf_non_sleepable_error_inject)
12230
12231 static int check_non_sleepable_error_inject(u32 btf_id)
12232 {
12233 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12234 }
12235
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)12236 int bpf_check_attach_target(struct bpf_verifier_log *log,
12237 const struct bpf_prog *prog,
12238 const struct bpf_prog *tgt_prog,
12239 u32 btf_id,
12240 struct bpf_attach_target_info *tgt_info)
12241 {
12242 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
12243 const char prefix[] = "btf_trace_";
12244 int ret = 0, subprog = -1, i;
12245 const struct btf_type *t;
12246 bool conservative = true;
12247 const char *tname;
12248 struct btf *btf;
12249 long addr = 0;
12250
12251 if (!btf_id) {
12252 bpf_log(log, "Tracing programs must provide btf_id\n");
12253 return -EINVAL;
12254 }
12255 btf = tgt_prog ? tgt_prog->aux->btf : btf_vmlinux;
12256 if (!btf) {
12257 bpf_log(log,
12258 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12259 return -EINVAL;
12260 }
12261 t = btf_type_by_id(btf, btf_id);
12262 if (!t) {
12263 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
12264 return -EINVAL;
12265 }
12266 tname = btf_name_by_offset(btf, t->name_off);
12267 if (!tname) {
12268 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
12269 return -EINVAL;
12270 }
12271 if (tgt_prog) {
12272 struct bpf_prog_aux *aux = tgt_prog->aux;
12273
12274 for (i = 0; i < aux->func_info_cnt; i++)
12275 if (aux->func_info[i].type_id == btf_id) {
12276 subprog = i;
12277 break;
12278 }
12279 if (subprog == -1) {
12280 bpf_log(log, "Subprog %s doesn't exist\n", tname);
12281 return -EINVAL;
12282 }
12283 conservative = aux->func_info_aux[subprog].unreliable;
12284 if (prog_extension) {
12285 if (conservative) {
12286 bpf_log(log,
12287 "Cannot replace static functions\n");
12288 return -EINVAL;
12289 }
12290 if (!prog->jit_requested) {
12291 bpf_log(log,
12292 "Extension programs should be JITed\n");
12293 return -EINVAL;
12294 }
12295 }
12296 if (!tgt_prog->jited) {
12297 bpf_log(log, "Can attach to only JITed progs\n");
12298 return -EINVAL;
12299 }
12300 if (tgt_prog->type == prog->type) {
12301 /* Cannot fentry/fexit another fentry/fexit program.
12302 * Cannot attach program extension to another extension.
12303 * It's ok to attach fentry/fexit to extension program.
12304 */
12305 bpf_log(log, "Cannot recursively attach\n");
12306 return -EINVAL;
12307 }
12308 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12309 prog_extension &&
12310 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12311 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12312 /* Program extensions can extend all program types
12313 * except fentry/fexit. The reason is the following.
12314 * The fentry/fexit programs are used for performance
12315 * analysis, stats and can be attached to any program
12316 * type except themselves. When extension program is
12317 * replacing XDP function it is necessary to allow
12318 * performance analysis of all functions. Both original
12319 * XDP program and its program extension. Hence
12320 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12321 * allowed. If extending of fentry/fexit was allowed it
12322 * would be possible to create long call chain
12323 * fentry->extension->fentry->extension beyond
12324 * reasonable stack size. Hence extending fentry is not
12325 * allowed.
12326 */
12327 bpf_log(log, "Cannot extend fentry/fexit\n");
12328 return -EINVAL;
12329 }
12330 } else {
12331 if (prog_extension) {
12332 bpf_log(log, "Cannot replace kernel functions\n");
12333 return -EINVAL;
12334 }
12335 }
12336
12337 switch (prog->expected_attach_type) {
12338 case BPF_TRACE_RAW_TP:
12339 if (tgt_prog) {
12340 bpf_log(log,
12341 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12342 return -EINVAL;
12343 }
12344 if (!btf_type_is_typedef(t)) {
12345 bpf_log(log, "attach_btf_id %u is not a typedef\n",
12346 btf_id);
12347 return -EINVAL;
12348 }
12349 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
12350 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
12351 btf_id, tname);
12352 return -EINVAL;
12353 }
12354 tname += sizeof(prefix) - 1;
12355 t = btf_type_by_id(btf, t->type);
12356 if (!btf_type_is_ptr(t))
12357 /* should never happen in valid vmlinux build */
12358 return -EINVAL;
12359 t = btf_type_by_id(btf, t->type);
12360 if (!btf_type_is_func_proto(t))
12361 /* should never happen in valid vmlinux build */
12362 return -EINVAL;
12363
12364 break;
12365 case BPF_TRACE_ITER:
12366 if (!btf_type_is_func(t)) {
12367 bpf_log(log, "attach_btf_id %u is not a function\n",
12368 btf_id);
12369 return -EINVAL;
12370 }
12371 t = btf_type_by_id(btf, t->type);
12372 if (!btf_type_is_func_proto(t))
12373 return -EINVAL;
12374 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12375 if (ret)
12376 return ret;
12377 break;
12378 default:
12379 if (!prog_extension)
12380 return -EINVAL;
12381 fallthrough;
12382 case BPF_MODIFY_RETURN:
12383 case BPF_LSM_MAC:
12384 case BPF_TRACE_FENTRY:
12385 case BPF_TRACE_FEXIT:
12386 if (!btf_type_is_func(t)) {
12387 bpf_log(log, "attach_btf_id %u is not a function\n",
12388 btf_id);
12389 return -EINVAL;
12390 }
12391 if (prog_extension &&
12392 btf_check_type_match(log, prog, btf, t))
12393 return -EINVAL;
12394 t = btf_type_by_id(btf, t->type);
12395 if (!btf_type_is_func_proto(t))
12396 return -EINVAL;
12397
12398 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12399 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12400 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12401 return -EINVAL;
12402
12403 if (tgt_prog && conservative)
12404 t = NULL;
12405
12406 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12407 if (ret < 0)
12408 return ret;
12409
12410 if (tgt_prog) {
12411 if (subprog == 0)
12412 addr = (long) tgt_prog->bpf_func;
12413 else
12414 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
12415 } else {
12416 addr = kallsyms_lookup_name(tname);
12417 if (!addr) {
12418 bpf_log(log,
12419 "The address of function %s cannot be found\n",
12420 tname);
12421 return -ENOENT;
12422 }
12423 }
12424
12425 if (prog->aux->sleepable) {
12426 ret = -EINVAL;
12427 switch (prog->type) {
12428 case BPF_PROG_TYPE_TRACING:
12429 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12430 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12431 */
12432 if (!check_non_sleepable_error_inject(btf_id) &&
12433 within_error_injection_list(addr))
12434 ret = 0;
12435 break;
12436 case BPF_PROG_TYPE_LSM:
12437 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12438 * Only some of them are sleepable.
12439 */
12440 if (check_sleepable_lsm_hook(btf_id))
12441 ret = 0;
12442 break;
12443 default:
12444 break;
12445 }
12446 if (ret) {
12447 bpf_log(log, "%s is not sleepable\n", tname);
12448 return ret;
12449 }
12450 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
12451 if (tgt_prog) {
12452 bpf_log(log, "can't modify return codes of BPF programs\n");
12453 return -EINVAL;
12454 }
12455 ret = check_attach_modify_return(addr, tname);
12456 if (ret) {
12457 bpf_log(log, "%s() is not modifiable\n", tname);
12458 return ret;
12459 }
12460 }
12461
12462 break;
12463 }
12464 tgt_info->tgt_addr = addr;
12465 tgt_info->tgt_name = tname;
12466 tgt_info->tgt_type = t;
12467 return 0;
12468 }
12469
check_attach_btf_id(struct bpf_verifier_env * env)12470 static int check_attach_btf_id(struct bpf_verifier_env *env)
12471 {
12472 struct bpf_prog *prog = env->prog;
12473 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
12474 struct bpf_attach_target_info tgt_info = {};
12475 u32 btf_id = prog->aux->attach_btf_id;
12476 struct bpf_trampoline *tr;
12477 int ret;
12478 u64 key;
12479
12480 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12481 prog->type != BPF_PROG_TYPE_LSM) {
12482 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12483 return -EINVAL;
12484 }
12485
12486 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12487 return check_struct_ops_btf_id(env);
12488
12489 if (prog->type != BPF_PROG_TYPE_TRACING &&
12490 prog->type != BPF_PROG_TYPE_LSM &&
12491 prog->type != BPF_PROG_TYPE_EXT)
12492 return 0;
12493
12494 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12495 if (ret)
12496 return ret;
12497
12498 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
12499 /* to make freplace equivalent to their targets, they need to
12500 * inherit env->ops and expected_attach_type for the rest of the
12501 * verification
12502 */
12503 env->ops = bpf_verifier_ops[tgt_prog->type];
12504 prog->expected_attach_type = tgt_prog->expected_attach_type;
12505 }
12506
12507 /* store info about the attachment target that will be used later */
12508 prog->aux->attach_func_proto = tgt_info.tgt_type;
12509 prog->aux->attach_func_name = tgt_info.tgt_name;
12510
12511 if (tgt_prog) {
12512 prog->aux->saved_dst_prog_type = tgt_prog->type;
12513 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12514 }
12515
12516 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12517 prog->aux->attach_btf_trace = true;
12518 return 0;
12519 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12520 if (!bpf_iter_prog_supported(prog))
12521 return -EINVAL;
12522 return 0;
12523 }
12524
12525 if (prog->type == BPF_PROG_TYPE_LSM) {
12526 ret = bpf_lsm_verify_prog(&env->log, prog);
12527 if (ret < 0)
12528 return ret;
12529 }
12530
12531 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
12532 tr = bpf_trampoline_get(key, &tgt_info);
12533 if (!tr)
12534 return -ENOMEM;
12535
12536 prog->aux->dst_trampoline = tr;
12537 return 0;
12538 }
12539
bpf_get_btf_vmlinux(void)12540 struct btf *bpf_get_btf_vmlinux(void)
12541 {
12542 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12543 mutex_lock(&bpf_verifier_lock);
12544 if (!btf_vmlinux)
12545 btf_vmlinux = btf_parse_vmlinux();
12546 mutex_unlock(&bpf_verifier_lock);
12547 }
12548 return btf_vmlinux;
12549 }
12550
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)12551 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12552 union bpf_attr __user *uattr)
12553 {
12554 u64 start_time = ktime_get_ns();
12555 struct bpf_verifier_env *env;
12556 struct bpf_verifier_log *log;
12557 int i, len, ret = -EINVAL;
12558 bool is_priv;
12559
12560 /* no program is valid */
12561 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12562 return -EINVAL;
12563
12564 /* 'struct bpf_verifier_env' can be global, but since it's not small,
12565 * allocate/free it every time bpf_check() is called
12566 */
12567 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
12568 if (!env)
12569 return -ENOMEM;
12570 log = &env->log;
12571
12572 len = (*prog)->len;
12573 env->insn_aux_data =
12574 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
12575 ret = -ENOMEM;
12576 if (!env->insn_aux_data)
12577 goto err_free_env;
12578 for (i = 0; i < len; i++)
12579 env->insn_aux_data[i].orig_idx = i;
12580 env->prog = *prog;
12581 env->ops = bpf_verifier_ops[env->prog->type];
12582 is_priv = bpf_capable();
12583
12584 bpf_get_btf_vmlinux();
12585
12586 /* grab the mutex to protect few globals used by verifier */
12587 if (!is_priv)
12588 mutex_lock(&bpf_verifier_lock);
12589
12590 if (attr->log_level || attr->log_buf || attr->log_size) {
12591 /* user requested verbose verifier output
12592 * and supplied buffer to store the verification trace
12593 */
12594 log->level = attr->log_level;
12595 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12596 log->len_total = attr->log_size;
12597
12598 /* log attributes have to be sane */
12599 if (!bpf_verifier_log_attr_valid(log)) {
12600 ret = -EINVAL;
12601 goto err_unlock;
12602 }
12603 }
12604
12605 if (IS_ERR(btf_vmlinux)) {
12606 /* Either gcc or pahole or kernel are broken. */
12607 verbose(env, "in-kernel BTF is malformed\n");
12608 ret = PTR_ERR(btf_vmlinux);
12609 goto skip_full_check;
12610 }
12611
12612 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12613 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
12614 env->strict_alignment = true;
12615 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12616 env->strict_alignment = false;
12617
12618 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
12619 env->allow_uninit_stack = bpf_allow_uninit_stack();
12620 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
12621 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12622 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12623 env->bpf_capable = bpf_capable();
12624
12625 if (is_priv)
12626 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12627
12628 env->explored_states = kvcalloc(state_htab_size(env),
12629 sizeof(struct bpf_verifier_state_list *),
12630 GFP_USER);
12631 ret = -ENOMEM;
12632 if (!env->explored_states)
12633 goto skip_full_check;
12634
12635 ret = check_subprogs(env);
12636 if (ret < 0)
12637 goto skip_full_check;
12638
12639 ret = check_btf_info(env, attr, uattr);
12640 if (ret < 0)
12641 goto skip_full_check;
12642
12643 ret = check_attach_btf_id(env);
12644 if (ret)
12645 goto skip_full_check;
12646
12647 ret = resolve_pseudo_ldimm64(env);
12648 if (ret < 0)
12649 goto skip_full_check;
12650
12651 if (bpf_prog_is_dev_bound(env->prog->aux)) {
12652 ret = bpf_prog_offload_verifier_prep(env->prog);
12653 if (ret)
12654 goto skip_full_check;
12655 }
12656
12657 ret = check_cfg(env);
12658 if (ret < 0)
12659 goto skip_full_check;
12660
12661 ret = do_check_subprogs(env);
12662 ret = ret ?: do_check_main(env);
12663
12664 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12665 ret = bpf_prog_offload_finalize(env);
12666
12667 skip_full_check:
12668 kvfree(env->explored_states);
12669
12670 if (ret == 0)
12671 ret = check_max_stack_depth(env);
12672
12673 /* instruction rewrites happen after this point */
12674 if (is_priv) {
12675 if (ret == 0)
12676 opt_hard_wire_dead_code_branches(env);
12677 if (ret == 0)
12678 ret = opt_remove_dead_code(env);
12679 if (ret == 0)
12680 ret = opt_remove_nops(env);
12681 } else {
12682 if (ret == 0)
12683 sanitize_dead_code(env);
12684 }
12685
12686 if (ret == 0)
12687 /* program is valid, convert *(u32*)(ctx + off) accesses */
12688 ret = convert_ctx_accesses(env);
12689
12690 if (ret == 0)
12691 ret = fixup_bpf_calls(env);
12692
12693 /* do 32-bit optimization after insn patching has done so those patched
12694 * insns could be handled correctly.
12695 */
12696 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12697 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12698 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12699 : false;
12700 }
12701
12702 if (ret == 0)
12703 ret = fixup_call_args(env);
12704
12705 env->verification_time = ktime_get_ns() - start_time;
12706 print_verification_stats(env);
12707
12708 if (log->level && bpf_verifier_log_full(log))
12709 ret = -ENOSPC;
12710 if (log->level && !log->ubuf) {
12711 ret = -EFAULT;
12712 goto err_release_maps;
12713 }
12714
12715 if (ret == 0 && env->used_map_cnt) {
12716 /* if program passed verifier, update used_maps in bpf_prog_info */
12717 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12718 sizeof(env->used_maps[0]),
12719 GFP_KERNEL);
12720
12721 if (!env->prog->aux->used_maps) {
12722 ret = -ENOMEM;
12723 goto err_release_maps;
12724 }
12725
12726 memcpy(env->prog->aux->used_maps, env->used_maps,
12727 sizeof(env->used_maps[0]) * env->used_map_cnt);
12728 env->prog->aux->used_map_cnt = env->used_map_cnt;
12729
12730 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12731 * bpf_ld_imm64 instructions
12732 */
12733 convert_pseudo_ld_imm64(env);
12734 }
12735
12736 if (ret == 0)
12737 adjust_btf_func(env);
12738
12739 err_release_maps:
12740 if (!env->prog->aux->used_maps)
12741 /* if we didn't copy map pointers into bpf_prog_info, release
12742 * them now. Otherwise free_used_maps() will release them.
12743 */
12744 release_maps(env);
12745
12746 /* extension progs temporarily inherit the attach_type of their targets
12747 for verification purposes, so set it back to zero before returning
12748 */
12749 if (env->prog->type == BPF_PROG_TYPE_EXT)
12750 env->prog->expected_attach_type = 0;
12751
12752 *prog = env->prog;
12753 err_unlock:
12754 if (!is_priv)
12755 mutex_unlock(&bpf_verifier_lock);
12756 vfree(env->insn_aux_data);
12757 err_free_env:
12758 kfree(env);
12759 return ret;
12760 }
12761