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
23 #include "disasm.h"
24
25 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
26 #define BPF_PROG_TYPE(_id, _name) \
27 [_id] = & _name ## _verifier_ops,
28 #define BPF_MAP_TYPE(_id, _ops)
29 #include <linux/bpf_types.h>
30 #undef BPF_PROG_TYPE
31 #undef BPF_MAP_TYPE
32 };
33
34 /* bpf_check() is a static code analyzer that walks eBPF program
35 * instruction by instruction and updates register/stack state.
36 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
37 *
38 * The first pass is depth-first-search to check that the program is a DAG.
39 * It rejects the following programs:
40 * - larger than BPF_MAXINSNS insns
41 * - if loop is present (detected via back-edge)
42 * - unreachable insns exist (shouldn't be a forest. program = one function)
43 * - out of bounds or malformed jumps
44 * The second pass is all possible path descent from the 1st insn.
45 * Since it's analyzing all pathes through the program, the length of the
46 * analysis is limited to 64k insn, which may be hit even if total number of
47 * insn is less then 4K, but there are too many branches that change stack/regs.
48 * Number of 'branches to be analyzed' is limited to 1k
49 *
50 * On entry to each instruction, each register has a type, and the instruction
51 * changes the types of the registers depending on instruction semantics.
52 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
53 * copied to R1.
54 *
55 * All registers are 64-bit.
56 * R0 - return register
57 * R1-R5 argument passing registers
58 * R6-R9 callee saved registers
59 * R10 - frame pointer read-only
60 *
61 * At the start of BPF program the register R1 contains a pointer to bpf_context
62 * and has type PTR_TO_CTX.
63 *
64 * Verifier tracks arithmetic operations on pointers in case:
65 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
66 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
67 * 1st insn copies R10 (which has FRAME_PTR) type into R1
68 * and 2nd arithmetic instruction is pattern matched to recognize
69 * that it wants to construct a pointer to some element within stack.
70 * So after 2nd insn, the register R1 has type PTR_TO_STACK
71 * (and -20 constant is saved for further stack bounds checking).
72 * Meaning that this reg is a pointer to stack plus known immediate constant.
73 *
74 * Most of the time the registers have SCALAR_VALUE type, which
75 * means the register has some value, but it's not a valid pointer.
76 * (like pointer plus pointer becomes SCALAR_VALUE type)
77 *
78 * When verifier sees load or store instructions the type of base register
79 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
80 * four pointer types recognized by check_mem_access() function.
81 *
82 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
83 * and the range of [ptr, ptr + map's value_size) is accessible.
84 *
85 * registers used to pass values to function calls are checked against
86 * function argument constraints.
87 *
88 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
89 * It means that the register type passed to this function must be
90 * PTR_TO_STACK and it will be used inside the function as
91 * 'pointer to map element key'
92 *
93 * For example the argument constraints for bpf_map_lookup_elem():
94 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
95 * .arg1_type = ARG_CONST_MAP_PTR,
96 * .arg2_type = ARG_PTR_TO_MAP_KEY,
97 *
98 * ret_type says that this function returns 'pointer to map elem value or null'
99 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
100 * 2nd argument should be a pointer to stack, which will be used inside
101 * the helper function as a pointer to map element key.
102 *
103 * On the kernel side the helper function looks like:
104 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
105 * {
106 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
107 * void *key = (void *) (unsigned long) r2;
108 * void *value;
109 *
110 * here kernel can access 'key' and 'map' pointers safely, knowing that
111 * [key, key + map->key_size) bytes are valid and were initialized on
112 * the stack of eBPF program.
113 * }
114 *
115 * Corresponding eBPF program may look like:
116 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
117 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
118 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
119 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
120 * here verifier looks at prototype of map_lookup_elem() and sees:
121 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
122 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
123 *
124 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
125 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
126 * and were initialized prior to this call.
127 * If it's ok, then verifier allows this BPF_CALL insn and looks at
128 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
129 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
130 * returns ether pointer to map value or NULL.
131 *
132 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
133 * insn, the register holding that pointer in the true branch changes state to
134 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
135 * branch. See check_cond_jmp_op().
136 *
137 * After the call R0 is set to return type of the function and registers R1-R5
138 * are set to NOT_INIT to indicate that they are no longer readable.
139 *
140 * The following reference types represent a potential reference to a kernel
141 * resource which, after first being allocated, must be checked and freed by
142 * the BPF program:
143 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
144 *
145 * When the verifier sees a helper call return a reference type, it allocates a
146 * pointer id for the reference and stores it in the current function state.
147 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
148 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
149 * passes through a NULL-check conditional. For the branch wherein the state is
150 * changed to CONST_IMM, the verifier releases the reference.
151 *
152 * For each helper function that allocates a reference, such as
153 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
154 * bpf_sk_release(). When a reference type passes into the release function,
155 * the verifier also releases the reference. If any unchecked or unreleased
156 * reference remains at the end of the program, the verifier rejects it.
157 */
158
159 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
160 struct bpf_verifier_stack_elem {
161 /* verifer state is 'st'
162 * before processing instruction 'insn_idx'
163 * and after processing instruction 'prev_insn_idx'
164 */
165 struct bpf_verifier_state st;
166 int insn_idx;
167 int prev_insn_idx;
168 struct bpf_verifier_stack_elem *next;
169 };
170
171 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
172 #define BPF_COMPLEXITY_LIMIT_STATES 64
173
174 #define BPF_MAP_PTR_UNPRIV 1UL
175 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
176 POISON_POINTER_DELTA))
177 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
178
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)179 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
180 {
181 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
182 }
183
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)184 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
185 {
186 return aux->map_state & BPF_MAP_PTR_UNPRIV;
187 }
188
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)189 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
190 const struct bpf_map *map, bool unpriv)
191 {
192 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
193 unpriv |= bpf_map_ptr_unpriv(aux);
194 aux->map_state = (unsigned long)map |
195 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
196 }
197
198 struct bpf_call_arg_meta {
199 struct bpf_map *map_ptr;
200 bool raw_mode;
201 bool pkt_access;
202 int regno;
203 int access_size;
204 u64 msize_max_value;
205 int ref_obj_id;
206 int func_id;
207 };
208
209 static DEFINE_MUTEX(bpf_verifier_lock);
210
211 static const struct bpf_line_info *
find_linfo(const struct bpf_verifier_env * env,u32 insn_off)212 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
213 {
214 const struct bpf_line_info *linfo;
215 const struct bpf_prog *prog;
216 u32 i, nr_linfo;
217
218 prog = env->prog;
219 nr_linfo = prog->aux->nr_linfo;
220
221 if (!nr_linfo || insn_off >= prog->len)
222 return NULL;
223
224 linfo = prog->aux->linfo;
225 for (i = 1; i < nr_linfo; i++)
226 if (insn_off < linfo[i].insn_off)
227 break;
228
229 return &linfo[i - 1];
230 }
231
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)232 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
233 va_list args)
234 {
235 unsigned int n;
236
237 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
238
239 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
240 "verifier log line truncated - local buffer too short\n");
241
242 n = min(log->len_total - log->len_used - 1, n);
243 log->kbuf[n] = '\0';
244
245 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
246 log->len_used += n;
247 else
248 log->ubuf = NULL;
249 }
250
251 /* log_level controls verbosity level of eBPF verifier.
252 * bpf_verifier_log_write() is used to dump the verification trace to the log,
253 * so the user can figure out what's wrong with the program
254 */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)255 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
256 const char *fmt, ...)
257 {
258 va_list args;
259
260 if (!bpf_verifier_log_needed(&env->log))
261 return;
262
263 va_start(args, fmt);
264 bpf_verifier_vlog(&env->log, fmt, args);
265 va_end(args);
266 }
267 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
268
verbose(void * private_data,const char * fmt,...)269 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
270 {
271 struct bpf_verifier_env *env = private_data;
272 va_list args;
273
274 if (!bpf_verifier_log_needed(&env->log))
275 return;
276
277 va_start(args, fmt);
278 bpf_verifier_vlog(&env->log, fmt, args);
279 va_end(args);
280 }
281
ltrim(const char * s)282 static const char *ltrim(const char *s)
283 {
284 while (isspace(*s))
285 s++;
286
287 return s;
288 }
289
verbose_linfo(struct bpf_verifier_env * env,u32 insn_off,const char * prefix_fmt,...)290 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
291 u32 insn_off,
292 const char *prefix_fmt, ...)
293 {
294 const struct bpf_line_info *linfo;
295
296 if (!bpf_verifier_log_needed(&env->log))
297 return;
298
299 linfo = find_linfo(env, insn_off);
300 if (!linfo || linfo == env->prev_linfo)
301 return;
302
303 if (prefix_fmt) {
304 va_list args;
305
306 va_start(args, prefix_fmt);
307 bpf_verifier_vlog(&env->log, prefix_fmt, args);
308 va_end(args);
309 }
310
311 verbose(env, "%s\n",
312 ltrim(btf_name_by_offset(env->prog->aux->btf,
313 linfo->line_off)));
314
315 env->prev_linfo = linfo;
316 }
317
type_is_pkt_pointer(enum bpf_reg_type type)318 static bool type_is_pkt_pointer(enum bpf_reg_type type)
319 {
320 return type == PTR_TO_PACKET ||
321 type == PTR_TO_PACKET_META;
322 }
323
type_is_sk_pointer(enum bpf_reg_type type)324 static bool type_is_sk_pointer(enum bpf_reg_type type)
325 {
326 return type == PTR_TO_SOCKET ||
327 type == PTR_TO_SOCK_COMMON ||
328 type == PTR_TO_TCP_SOCK ||
329 type == PTR_TO_XDP_SOCK;
330 }
331
reg_type_may_be_null(enum bpf_reg_type type)332 static bool reg_type_may_be_null(enum bpf_reg_type type)
333 {
334 return type == PTR_TO_MAP_VALUE_OR_NULL ||
335 type == PTR_TO_SOCKET_OR_NULL ||
336 type == PTR_TO_SOCK_COMMON_OR_NULL ||
337 type == PTR_TO_TCP_SOCK_OR_NULL;
338 }
339
reg_may_point_to_spin_lock(const struct bpf_reg_state * reg)340 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
341 {
342 return reg->type == PTR_TO_MAP_VALUE &&
343 map_value_has_spin_lock(reg->map_ptr);
344 }
345
reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)346 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
347 {
348 return type == PTR_TO_SOCKET ||
349 type == PTR_TO_SOCKET_OR_NULL ||
350 type == PTR_TO_TCP_SOCK ||
351 type == PTR_TO_TCP_SOCK_OR_NULL;
352 }
353
arg_type_may_be_refcounted(enum bpf_arg_type type)354 static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
355 {
356 return type == ARG_PTR_TO_SOCK_COMMON;
357 }
358
359 /* Determine whether the function releases some resources allocated by another
360 * function call. The first reference type argument will be assumed to be
361 * released by release_reference().
362 */
is_release_function(enum bpf_func_id func_id)363 static bool is_release_function(enum bpf_func_id func_id)
364 {
365 return func_id == BPF_FUNC_sk_release;
366 }
367
is_acquire_function(enum bpf_func_id func_id)368 static bool is_acquire_function(enum bpf_func_id func_id)
369 {
370 return func_id == BPF_FUNC_sk_lookup_tcp ||
371 func_id == BPF_FUNC_sk_lookup_udp ||
372 func_id == BPF_FUNC_skc_lookup_tcp;
373 }
374
is_ptr_cast_function(enum bpf_func_id func_id)375 static bool is_ptr_cast_function(enum bpf_func_id func_id)
376 {
377 return func_id == BPF_FUNC_tcp_sock ||
378 func_id == BPF_FUNC_sk_fullsock;
379 }
380
381 /* string representation of 'enum bpf_reg_type' */
382 static const char * const reg_type_str[] = {
383 [NOT_INIT] = "?",
384 [SCALAR_VALUE] = "inv",
385 [PTR_TO_CTX] = "ctx",
386 [CONST_PTR_TO_MAP] = "map_ptr",
387 [PTR_TO_MAP_VALUE] = "map_value",
388 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
389 [PTR_TO_STACK] = "fp",
390 [PTR_TO_PACKET] = "pkt",
391 [PTR_TO_PACKET_META] = "pkt_meta",
392 [PTR_TO_PACKET_END] = "pkt_end",
393 [PTR_TO_FLOW_KEYS] = "flow_keys",
394 [PTR_TO_SOCKET] = "sock",
395 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
396 [PTR_TO_SOCK_COMMON] = "sock_common",
397 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
398 [PTR_TO_TCP_SOCK] = "tcp_sock",
399 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
400 [PTR_TO_TP_BUFFER] = "tp_buffer",
401 [PTR_TO_XDP_SOCK] = "xdp_sock",
402 };
403
404 static char slot_type_char[] = {
405 [STACK_INVALID] = '?',
406 [STACK_SPILL] = 'r',
407 [STACK_MISC] = 'm',
408 [STACK_ZERO] = '0',
409 };
410
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)411 static void print_liveness(struct bpf_verifier_env *env,
412 enum bpf_reg_liveness live)
413 {
414 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
415 verbose(env, "_");
416 if (live & REG_LIVE_READ)
417 verbose(env, "r");
418 if (live & REG_LIVE_WRITTEN)
419 verbose(env, "w");
420 if (live & REG_LIVE_DONE)
421 verbose(env, "D");
422 }
423
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)424 static struct bpf_func_state *func(struct bpf_verifier_env *env,
425 const struct bpf_reg_state *reg)
426 {
427 struct bpf_verifier_state *cur = env->cur_state;
428
429 return cur->frame[reg->frameno];
430 }
431
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)432 static void print_verifier_state(struct bpf_verifier_env *env,
433 const struct bpf_func_state *state)
434 {
435 const struct bpf_reg_state *reg;
436 enum bpf_reg_type t;
437 int i;
438
439 if (state->frameno)
440 verbose(env, " frame%d:", state->frameno);
441 for (i = 0; i < MAX_BPF_REG; i++) {
442 reg = &state->regs[i];
443 t = reg->type;
444 if (t == NOT_INIT)
445 continue;
446 verbose(env, " R%d", i);
447 print_liveness(env, reg->live);
448 verbose(env, "=%s", reg_type_str[t]);
449 if (t == SCALAR_VALUE && reg->precise)
450 verbose(env, "P");
451 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
452 tnum_is_const(reg->var_off)) {
453 /* reg->off should be 0 for SCALAR_VALUE */
454 verbose(env, "%lld", reg->var_off.value + reg->off);
455 } else {
456 verbose(env, "(id=%d", reg->id);
457 if (reg_type_may_be_refcounted_or_null(t))
458 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
459 if (t != SCALAR_VALUE)
460 verbose(env, ",off=%d", reg->off);
461 if (type_is_pkt_pointer(t))
462 verbose(env, ",r=%d", reg->range);
463 else if (t == CONST_PTR_TO_MAP ||
464 t == PTR_TO_MAP_VALUE ||
465 t == PTR_TO_MAP_VALUE_OR_NULL)
466 verbose(env, ",ks=%d,vs=%d",
467 reg->map_ptr->key_size,
468 reg->map_ptr->value_size);
469 if (tnum_is_const(reg->var_off)) {
470 /* Typically an immediate SCALAR_VALUE, but
471 * could be a pointer whose offset is too big
472 * for reg->off
473 */
474 verbose(env, ",imm=%llx", reg->var_off.value);
475 } else {
476 if (reg->smin_value != reg->umin_value &&
477 reg->smin_value != S64_MIN)
478 verbose(env, ",smin_value=%lld",
479 (long long)reg->smin_value);
480 if (reg->smax_value != reg->umax_value &&
481 reg->smax_value != S64_MAX)
482 verbose(env, ",smax_value=%lld",
483 (long long)reg->smax_value);
484 if (reg->umin_value != 0)
485 verbose(env, ",umin_value=%llu",
486 (unsigned long long)reg->umin_value);
487 if (reg->umax_value != U64_MAX)
488 verbose(env, ",umax_value=%llu",
489 (unsigned long long)reg->umax_value);
490 if (!tnum_is_unknown(reg->var_off)) {
491 char tn_buf[48];
492
493 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
494 verbose(env, ",var_off=%s", tn_buf);
495 }
496 }
497 verbose(env, ")");
498 }
499 }
500 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
501 char types_buf[BPF_REG_SIZE + 1];
502 bool valid = false;
503 int j;
504
505 for (j = 0; j < BPF_REG_SIZE; j++) {
506 if (state->stack[i].slot_type[j] != STACK_INVALID)
507 valid = true;
508 types_buf[j] = slot_type_char[
509 state->stack[i].slot_type[j]];
510 }
511 types_buf[BPF_REG_SIZE] = 0;
512 if (!valid)
513 continue;
514 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
515 print_liveness(env, state->stack[i].spilled_ptr.live);
516 if (state->stack[i].slot_type[0] == STACK_SPILL) {
517 reg = &state->stack[i].spilled_ptr;
518 t = reg->type;
519 verbose(env, "=%s", reg_type_str[t]);
520 if (t == SCALAR_VALUE && reg->precise)
521 verbose(env, "P");
522 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
523 verbose(env, "%lld", reg->var_off.value + reg->off);
524 } else {
525 verbose(env, "=%s", types_buf);
526 }
527 }
528 if (state->acquired_refs && state->refs[0].id) {
529 verbose(env, " refs=%d", state->refs[0].id);
530 for (i = 1; i < state->acquired_refs; i++)
531 if (state->refs[i].id)
532 verbose(env, ",%d", state->refs[i].id);
533 }
534 verbose(env, "\n");
535 }
536
537 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
538 static int copy_##NAME##_state(struct bpf_func_state *dst, \
539 const struct bpf_func_state *src) \
540 { \
541 if (!src->FIELD) \
542 return 0; \
543 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
544 /* internal bug, make state invalid to reject the program */ \
545 memset(dst, 0, sizeof(*dst)); \
546 return -EFAULT; \
547 } \
548 memcpy(dst->FIELD, src->FIELD, \
549 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
550 return 0; \
551 }
552 /* copy_reference_state() */
553 COPY_STATE_FN(reference, acquired_refs, refs, 1)
554 /* copy_stack_state() */
COPY_STATE_FN(stack,allocated_stack,stack,BPF_REG_SIZE)555 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
556 #undef COPY_STATE_FN
557
558 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
559 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
560 bool copy_old) \
561 { \
562 u32 old_size = state->COUNT; \
563 struct bpf_##NAME##_state *new_##FIELD; \
564 int slot = size / SIZE; \
565 \
566 if (size <= old_size || !size) { \
567 if (copy_old) \
568 return 0; \
569 state->COUNT = slot * SIZE; \
570 if (!size && old_size) { \
571 kfree(state->FIELD); \
572 state->FIELD = NULL; \
573 } \
574 return 0; \
575 } \
576 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
577 GFP_KERNEL); \
578 if (!new_##FIELD) \
579 return -ENOMEM; \
580 if (copy_old) { \
581 if (state->FIELD) \
582 memcpy(new_##FIELD, state->FIELD, \
583 sizeof(*new_##FIELD) * (old_size / SIZE)); \
584 memset(new_##FIELD + old_size / SIZE, 0, \
585 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
586 } \
587 state->COUNT = slot * SIZE; \
588 kfree(state->FIELD); \
589 state->FIELD = new_##FIELD; \
590 return 0; \
591 }
592 /* realloc_reference_state() */
593 REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
594 /* realloc_stack_state() */
595 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
596 #undef REALLOC_STATE_FN
597
598 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
599 * make it consume minimal amount of memory. check_stack_write() access from
600 * the program calls into realloc_func_state() to grow the stack size.
601 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
602 * which realloc_stack_state() copies over. It points to previous
603 * bpf_verifier_state which is never reallocated.
604 */
605 static int realloc_func_state(struct bpf_func_state *state, int stack_size,
606 int refs_size, bool copy_old)
607 {
608 int err = realloc_reference_state(state, refs_size, copy_old);
609 if (err)
610 return err;
611 return realloc_stack_state(state, stack_size, copy_old);
612 }
613
614 /* Acquire a pointer id from the env and update the state->refs to include
615 * this new pointer reference.
616 * On success, returns a valid pointer id to associate with the register
617 * On failure, returns a negative errno.
618 */
acquire_reference_state(struct bpf_verifier_env * env,int insn_idx)619 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
620 {
621 struct bpf_func_state *state = cur_func(env);
622 int new_ofs = state->acquired_refs;
623 int id, err;
624
625 err = realloc_reference_state(state, state->acquired_refs + 1, true);
626 if (err)
627 return err;
628 id = ++env->id_gen;
629 state->refs[new_ofs].id = id;
630 state->refs[new_ofs].insn_idx = insn_idx;
631
632 return id;
633 }
634
635 /* release function corresponding to acquire_reference_state(). Idempotent. */
release_reference_state(struct bpf_func_state * state,int ptr_id)636 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
637 {
638 int i, last_idx;
639
640 last_idx = state->acquired_refs - 1;
641 for (i = 0; i < state->acquired_refs; i++) {
642 if (state->refs[i].id == ptr_id) {
643 if (last_idx && i != last_idx)
644 memcpy(&state->refs[i], &state->refs[last_idx],
645 sizeof(*state->refs));
646 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
647 state->acquired_refs--;
648 return 0;
649 }
650 }
651 return -EINVAL;
652 }
653
transfer_reference_state(struct bpf_func_state * dst,struct bpf_func_state * src)654 static int transfer_reference_state(struct bpf_func_state *dst,
655 struct bpf_func_state *src)
656 {
657 int err = realloc_reference_state(dst, src->acquired_refs, false);
658 if (err)
659 return err;
660 err = copy_reference_state(dst, src);
661 if (err)
662 return err;
663 return 0;
664 }
665
free_func_state(struct bpf_func_state * state)666 static void free_func_state(struct bpf_func_state *state)
667 {
668 if (!state)
669 return;
670 kfree(state->refs);
671 kfree(state->stack);
672 kfree(state);
673 }
674
clear_jmp_history(struct bpf_verifier_state * state)675 static void clear_jmp_history(struct bpf_verifier_state *state)
676 {
677 kfree(state->jmp_history);
678 state->jmp_history = NULL;
679 state->jmp_history_cnt = 0;
680 }
681
free_verifier_state(struct bpf_verifier_state * state,bool free_self)682 static void free_verifier_state(struct bpf_verifier_state *state,
683 bool free_self)
684 {
685 int i;
686
687 for (i = 0; i <= state->curframe; i++) {
688 free_func_state(state->frame[i]);
689 state->frame[i] = NULL;
690 }
691 clear_jmp_history(state);
692 if (free_self)
693 kfree(state);
694 }
695
696 /* copy verifier state from src to dst growing dst stack space
697 * when necessary to accommodate larger src stack
698 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)699 static int copy_func_state(struct bpf_func_state *dst,
700 const struct bpf_func_state *src)
701 {
702 int err;
703
704 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
705 false);
706 if (err)
707 return err;
708 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
709 err = copy_reference_state(dst, src);
710 if (err)
711 return err;
712 return copy_stack_state(dst, src);
713 }
714
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)715 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
716 const struct bpf_verifier_state *src)
717 {
718 struct bpf_func_state *dst;
719 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
720 int i, err;
721
722 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
723 kfree(dst_state->jmp_history);
724 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
725 if (!dst_state->jmp_history)
726 return -ENOMEM;
727 }
728 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
729 dst_state->jmp_history_cnt = src->jmp_history_cnt;
730
731 /* if dst has more stack frames then src frame, free them */
732 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
733 free_func_state(dst_state->frame[i]);
734 dst_state->frame[i] = NULL;
735 }
736 dst_state->speculative = src->speculative;
737 dst_state->curframe = src->curframe;
738 dst_state->active_spin_lock = src->active_spin_lock;
739 dst_state->branches = src->branches;
740 dst_state->parent = src->parent;
741 dst_state->first_insn_idx = src->first_insn_idx;
742 dst_state->last_insn_idx = src->last_insn_idx;
743 for (i = 0; i <= src->curframe; i++) {
744 dst = dst_state->frame[i];
745 if (!dst) {
746 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
747 if (!dst)
748 return -ENOMEM;
749 dst_state->frame[i] = dst;
750 }
751 err = copy_func_state(dst, src->frame[i]);
752 if (err)
753 return err;
754 }
755 return 0;
756 }
757
update_branch_counts(struct bpf_verifier_env * env,struct bpf_verifier_state * st)758 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
759 {
760 while (st) {
761 u32 br = --st->branches;
762
763 /* WARN_ON(br > 1) technically makes sense here,
764 * but see comment in push_stack(), hence:
765 */
766 WARN_ONCE((int)br < 0,
767 "BUG update_branch_counts:branches_to_explore=%d\n",
768 br);
769 if (br)
770 break;
771 st = st->parent;
772 }
773 }
774
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx)775 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
776 int *insn_idx)
777 {
778 struct bpf_verifier_state *cur = env->cur_state;
779 struct bpf_verifier_stack_elem *elem, *head = env->head;
780 int err;
781
782 if (env->head == NULL)
783 return -ENOENT;
784
785 if (cur) {
786 err = copy_verifier_state(cur, &head->st);
787 if (err)
788 return err;
789 }
790 if (insn_idx)
791 *insn_idx = head->insn_idx;
792 if (prev_insn_idx)
793 *prev_insn_idx = head->prev_insn_idx;
794 elem = head->next;
795 free_verifier_state(&head->st, false);
796 kfree(head);
797 env->head = elem;
798 env->stack_size--;
799 return 0;
800 }
801
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)802 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
803 int insn_idx, int prev_insn_idx,
804 bool speculative)
805 {
806 struct bpf_verifier_state *cur = env->cur_state;
807 struct bpf_verifier_stack_elem *elem;
808 int err;
809
810 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
811 if (!elem)
812 goto err;
813
814 elem->insn_idx = insn_idx;
815 elem->prev_insn_idx = prev_insn_idx;
816 elem->next = env->head;
817 env->head = elem;
818 env->stack_size++;
819 err = copy_verifier_state(&elem->st, cur);
820 if (err)
821 goto err;
822 elem->st.speculative |= speculative;
823 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
824 verbose(env, "The sequence of %d jumps is too complex.\n",
825 env->stack_size);
826 goto err;
827 }
828 if (elem->st.parent) {
829 ++elem->st.parent->branches;
830 /* WARN_ON(branches > 2) technically makes sense here,
831 * but
832 * 1. speculative states will bump 'branches' for non-branch
833 * instructions
834 * 2. is_state_visited() heuristics may decide not to create
835 * a new state for a sequence of branches and all such current
836 * and cloned states will be pointing to a single parent state
837 * which might have large 'branches' count.
838 */
839 }
840 return &elem->st;
841 err:
842 free_verifier_state(env->cur_state, true);
843 env->cur_state = NULL;
844 /* pop all elements and return */
845 while (!pop_stack(env, NULL, NULL));
846 return NULL;
847 }
848
849 #define CALLER_SAVED_REGS 6
850 static const int caller_saved[CALLER_SAVED_REGS] = {
851 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
852 };
853
854 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
855 struct bpf_reg_state *reg);
856
857 /* Mark the unknown part of a register (variable offset or scalar value) as
858 * known to have the value @imm.
859 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)860 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
861 {
862 /* Clear id, off, and union(map_ptr, range) */
863 memset(((u8 *)reg) + sizeof(reg->type), 0,
864 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
865 reg->var_off = tnum_const(imm);
866 reg->smin_value = (s64)imm;
867 reg->smax_value = (s64)imm;
868 reg->umin_value = imm;
869 reg->umax_value = imm;
870 }
871
872 /* Mark the 'variable offset' part of a register as zero. This should be
873 * used only on registers holding a pointer type.
874 */
__mark_reg_known_zero(struct bpf_reg_state * reg)875 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
876 {
877 __mark_reg_known(reg, 0);
878 }
879
__mark_reg_const_zero(struct bpf_reg_state * reg)880 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
881 {
882 __mark_reg_known(reg, 0);
883 reg->type = SCALAR_VALUE;
884 }
885
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)886 static void mark_reg_known_zero(struct bpf_verifier_env *env,
887 struct bpf_reg_state *regs, u32 regno)
888 {
889 if (WARN_ON(regno >= MAX_BPF_REG)) {
890 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
891 /* Something bad happened, let's kill all regs */
892 for (regno = 0; regno < MAX_BPF_REG; regno++)
893 __mark_reg_not_init(env, regs + regno);
894 return;
895 }
896 __mark_reg_known_zero(regs + regno);
897 }
898
reg_is_pkt_pointer(const struct bpf_reg_state * reg)899 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
900 {
901 return type_is_pkt_pointer(reg->type);
902 }
903
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)904 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
905 {
906 return reg_is_pkt_pointer(reg) ||
907 reg->type == PTR_TO_PACKET_END;
908 }
909
910 /* 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)911 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
912 enum bpf_reg_type which)
913 {
914 /* The register can already have a range from prior markings.
915 * This is fine as long as it hasn't been advanced from its
916 * origin.
917 */
918 return reg->type == which &&
919 reg->id == 0 &&
920 reg->off == 0 &&
921 tnum_equals_const(reg->var_off, 0);
922 }
923
924 /* Attempts to improve min/max values based on var_off information */
__update_reg_bounds(struct bpf_reg_state * reg)925 static void __update_reg_bounds(struct bpf_reg_state *reg)
926 {
927 /* min signed is max(sign bit) | min(other bits) */
928 reg->smin_value = max_t(s64, reg->smin_value,
929 reg->var_off.value | (reg->var_off.mask & S64_MIN));
930 /* max signed is min(sign bit) | max(other bits) */
931 reg->smax_value = min_t(s64, reg->smax_value,
932 reg->var_off.value | (reg->var_off.mask & S64_MAX));
933 reg->umin_value = max(reg->umin_value, reg->var_off.value);
934 reg->umax_value = min(reg->umax_value,
935 reg->var_off.value | reg->var_off.mask);
936 }
937
938 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg_deduce_bounds(struct bpf_reg_state * reg)939 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
940 {
941 /* Learn sign from signed bounds.
942 * If we cannot cross the sign boundary, then signed and unsigned bounds
943 * are the same, so combine. This works even in the negative case, e.g.
944 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
945 */
946 if (reg->smin_value >= 0 || reg->smax_value < 0) {
947 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
948 reg->umin_value);
949 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
950 reg->umax_value);
951 return;
952 }
953 /* Learn sign from unsigned bounds. Signed bounds cross the sign
954 * boundary, so we must be careful.
955 */
956 if ((s64)reg->umax_value >= 0) {
957 /* Positive. We can't learn anything from the smin, but smax
958 * is positive, hence safe.
959 */
960 reg->smin_value = reg->umin_value;
961 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
962 reg->umax_value);
963 } else if ((s64)reg->umin_value < 0) {
964 /* Negative. We can't learn anything from the smax, but smin
965 * is negative, hence safe.
966 */
967 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
968 reg->umin_value);
969 reg->smax_value = reg->umax_value;
970 }
971 }
972
973 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)974 static void __reg_bound_offset(struct bpf_reg_state *reg)
975 {
976 reg->var_off = tnum_intersect(reg->var_off,
977 tnum_range(reg->umin_value,
978 reg->umax_value));
979 }
980
981 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)982 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
983 {
984 reg->smin_value = S64_MIN;
985 reg->smax_value = S64_MAX;
986 reg->umin_value = 0;
987 reg->umax_value = U64_MAX;
988 }
989
990 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)991 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
992 struct bpf_reg_state *reg)
993 {
994 /*
995 * Clear type, id, off, and union(map_ptr, range) and
996 * padding between 'type' and union
997 */
998 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
999 reg->type = SCALAR_VALUE;
1000 reg->var_off = tnum_unknown;
1001 reg->frameno = 0;
1002 reg->precise = env->subprog_cnt > 1 || !env->allow_ptr_leaks ?
1003 true : false;
1004 __mark_reg_unbounded(reg);
1005 }
1006
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1007 static void mark_reg_unknown(struct bpf_verifier_env *env,
1008 struct bpf_reg_state *regs, u32 regno)
1009 {
1010 if (WARN_ON(regno >= MAX_BPF_REG)) {
1011 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
1012 /* Something bad happened, let's kill all regs except FP */
1013 for (regno = 0; regno < BPF_REG_FP; regno++)
1014 __mark_reg_not_init(env, regs + regno);
1015 return;
1016 }
1017 __mark_reg_unknown(env, regs + regno);
1018 }
1019
__mark_reg_not_init(const struct bpf_verifier_env * env,struct bpf_reg_state * reg)1020 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1021 struct bpf_reg_state *reg)
1022 {
1023 __mark_reg_unknown(env, reg);
1024 reg->type = NOT_INIT;
1025 }
1026
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)1027 static void mark_reg_not_init(struct bpf_verifier_env *env,
1028 struct bpf_reg_state *regs, u32 regno)
1029 {
1030 if (WARN_ON(regno >= MAX_BPF_REG)) {
1031 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
1032 /* Something bad happened, let's kill all regs except FP */
1033 for (regno = 0; regno < BPF_REG_FP; regno++)
1034 __mark_reg_not_init(env, regs + regno);
1035 return;
1036 }
1037 __mark_reg_not_init(env, regs + regno);
1038 }
1039
1040 #define DEF_NOT_SUBREG (0)
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)1041 static void init_reg_state(struct bpf_verifier_env *env,
1042 struct bpf_func_state *state)
1043 {
1044 struct bpf_reg_state *regs = state->regs;
1045 int i;
1046
1047 for (i = 0; i < MAX_BPF_REG; i++) {
1048 mark_reg_not_init(env, regs, i);
1049 regs[i].live = REG_LIVE_NONE;
1050 regs[i].parent = NULL;
1051 regs[i].subreg_def = DEF_NOT_SUBREG;
1052 }
1053
1054 /* frame pointer */
1055 regs[BPF_REG_FP].type = PTR_TO_STACK;
1056 mark_reg_known_zero(env, regs, BPF_REG_FP);
1057 regs[BPF_REG_FP].frameno = state->frameno;
1058
1059 /* 1st arg to a function */
1060 regs[BPF_REG_1].type = PTR_TO_CTX;
1061 mark_reg_known_zero(env, regs, BPF_REG_1);
1062 }
1063
1064 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)1065 static void init_func_state(struct bpf_verifier_env *env,
1066 struct bpf_func_state *state,
1067 int callsite, int frameno, int subprogno)
1068 {
1069 state->callsite = callsite;
1070 state->frameno = frameno;
1071 state->subprogno = subprogno;
1072 init_reg_state(env, state);
1073 }
1074
1075 enum reg_arg_type {
1076 SRC_OP, /* register is used as source operand */
1077 DST_OP, /* register is used as destination operand */
1078 DST_OP_NO_MARK /* same as above, check only, don't mark */
1079 };
1080
cmp_subprogs(const void * a,const void * b)1081 static int cmp_subprogs(const void *a, const void *b)
1082 {
1083 return ((struct bpf_subprog_info *)a)->start -
1084 ((struct bpf_subprog_info *)b)->start;
1085 }
1086
find_subprog(struct bpf_verifier_env * env,int off)1087 static int find_subprog(struct bpf_verifier_env *env, int off)
1088 {
1089 struct bpf_subprog_info *p;
1090
1091 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1092 sizeof(env->subprog_info[0]), cmp_subprogs);
1093 if (!p)
1094 return -ENOENT;
1095 return p - env->subprog_info;
1096
1097 }
1098
add_subprog(struct bpf_verifier_env * env,int off)1099 static int add_subprog(struct bpf_verifier_env *env, int off)
1100 {
1101 int insn_cnt = env->prog->len;
1102 int ret;
1103
1104 if (off >= insn_cnt || off < 0) {
1105 verbose(env, "call to invalid destination\n");
1106 return -EINVAL;
1107 }
1108 ret = find_subprog(env, off);
1109 if (ret >= 0)
1110 return 0;
1111 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
1112 verbose(env, "too many subprograms\n");
1113 return -E2BIG;
1114 }
1115 env->subprog_info[env->subprog_cnt++].start = off;
1116 sort(env->subprog_info, env->subprog_cnt,
1117 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
1118 return 0;
1119 }
1120
check_subprogs(struct bpf_verifier_env * env)1121 static int check_subprogs(struct bpf_verifier_env *env)
1122 {
1123 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
1124 struct bpf_subprog_info *subprog = env->subprog_info;
1125 struct bpf_insn *insn = env->prog->insnsi;
1126 int insn_cnt = env->prog->len;
1127
1128 /* Add entry function. */
1129 ret = add_subprog(env, 0);
1130 if (ret < 0)
1131 return ret;
1132
1133 /* determine subprog starts. The end is one before the next starts */
1134 for (i = 0; i < insn_cnt; i++) {
1135 if (insn[i].code != (BPF_JMP | BPF_CALL))
1136 continue;
1137 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1138 continue;
1139 if (!env->allow_ptr_leaks) {
1140 verbose(env, "function calls to other bpf functions are allowed for root only\n");
1141 return -EPERM;
1142 }
1143 ret = add_subprog(env, i + insn[i].imm + 1);
1144 if (ret < 0)
1145 return ret;
1146 }
1147
1148 /* Add a fake 'exit' subprog which could simplify subprog iteration
1149 * logic. 'subprog_cnt' should not be increased.
1150 */
1151 subprog[env->subprog_cnt].start = insn_cnt;
1152
1153 if (env->log.level & BPF_LOG_LEVEL2)
1154 for (i = 0; i < env->subprog_cnt; i++)
1155 verbose(env, "func#%d @%d\n", i, subprog[i].start);
1156
1157 /* now check that all jumps are within the same subprog */
1158 subprog_start = subprog[cur_subprog].start;
1159 subprog_end = subprog[cur_subprog + 1].start;
1160 for (i = 0; i < insn_cnt; i++) {
1161 u8 code = insn[i].code;
1162
1163 if (code == (BPF_JMP | BPF_CALL) &&
1164 insn[i].imm == BPF_FUNC_tail_call &&
1165 insn[i].src_reg != BPF_PSEUDO_CALL)
1166 subprog[cur_subprog].has_tail_call = true;
1167 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
1168 goto next;
1169 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1170 goto next;
1171 off = i + insn[i].off + 1;
1172 if (off < subprog_start || off >= subprog_end) {
1173 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1174 return -EINVAL;
1175 }
1176 next:
1177 if (i == subprog_end - 1) {
1178 /* to avoid fall-through from one subprog into another
1179 * the last insn of the subprog should be either exit
1180 * or unconditional jump back
1181 */
1182 if (code != (BPF_JMP | BPF_EXIT) &&
1183 code != (BPF_JMP | BPF_JA)) {
1184 verbose(env, "last insn is not an exit or jmp\n");
1185 return -EINVAL;
1186 }
1187 subprog_start = subprog_end;
1188 cur_subprog++;
1189 if (cur_subprog < env->subprog_cnt)
1190 subprog_end = subprog[cur_subprog + 1].start;
1191 }
1192 }
1193 return 0;
1194 }
1195
1196 /* Parentage chain of this register (or stack slot) should take care of all
1197 * issues like callee-saved registers, stack slot allocation time, etc.
1198 */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent,u8 flag)1199 static int mark_reg_read(struct bpf_verifier_env *env,
1200 const struct bpf_reg_state *state,
1201 struct bpf_reg_state *parent, u8 flag)
1202 {
1203 bool writes = parent == state->parent; /* Observe write marks */
1204 int cnt = 0;
1205
1206 while (parent) {
1207 /* if read wasn't screened by an earlier write ... */
1208 if (writes && state->live & REG_LIVE_WRITTEN)
1209 break;
1210 if (parent->live & REG_LIVE_DONE) {
1211 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1212 reg_type_str[parent->type],
1213 parent->var_off.value, parent->off);
1214 return -EFAULT;
1215 }
1216 /* The first condition is more likely to be true than the
1217 * second, checked it first.
1218 */
1219 if ((parent->live & REG_LIVE_READ) == flag ||
1220 parent->live & REG_LIVE_READ64)
1221 /* The parentage chain never changes and
1222 * this parent was already marked as LIVE_READ.
1223 * There is no need to keep walking the chain again and
1224 * keep re-marking all parents as LIVE_READ.
1225 * This case happens when the same register is read
1226 * multiple times without writes into it in-between.
1227 * Also, if parent has the stronger REG_LIVE_READ64 set,
1228 * then no need to set the weak REG_LIVE_READ32.
1229 */
1230 break;
1231 /* ... then we depend on parent's value */
1232 parent->live |= flag;
1233 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1234 if (flag == REG_LIVE_READ64)
1235 parent->live &= ~REG_LIVE_READ32;
1236 state = parent;
1237 parent = state->parent;
1238 writes = true;
1239 cnt++;
1240 }
1241
1242 if (env->longest_mark_read_walk < cnt)
1243 env->longest_mark_read_walk = cnt;
1244 return 0;
1245 }
1246
1247 /* This function is supposed to be used by the following 32-bit optimization
1248 * code only. It returns TRUE if the source or destination register operates
1249 * on 64-bit, otherwise return FALSE.
1250 */
is_reg64(struct bpf_verifier_env * env,struct bpf_insn * insn,u32 regno,struct bpf_reg_state * reg,enum reg_arg_type t)1251 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1252 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1253 {
1254 u8 code, class, op;
1255
1256 code = insn->code;
1257 class = BPF_CLASS(code);
1258 op = BPF_OP(code);
1259 if (class == BPF_JMP) {
1260 /* BPF_EXIT for "main" will reach here. Return TRUE
1261 * conservatively.
1262 */
1263 if (op == BPF_EXIT)
1264 return true;
1265 if (op == BPF_CALL) {
1266 /* BPF to BPF call will reach here because of marking
1267 * caller saved clobber with DST_OP_NO_MARK for which we
1268 * don't care the register def because they are anyway
1269 * marked as NOT_INIT already.
1270 */
1271 if (insn->src_reg == BPF_PSEUDO_CALL)
1272 return false;
1273 /* Helper call will reach here because of arg type
1274 * check, conservatively return TRUE.
1275 */
1276 if (t == SRC_OP)
1277 return true;
1278
1279 return false;
1280 }
1281 }
1282
1283 if (class == BPF_ALU64 || class == BPF_JMP ||
1284 /* BPF_END always use BPF_ALU class. */
1285 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1286 return true;
1287
1288 if (class == BPF_ALU || class == BPF_JMP32)
1289 return false;
1290
1291 if (class == BPF_LDX) {
1292 if (t != SRC_OP)
1293 return BPF_SIZE(code) == BPF_DW;
1294 /* LDX source must be ptr. */
1295 return true;
1296 }
1297
1298 if (class == BPF_STX) {
1299 if (reg->type != SCALAR_VALUE)
1300 return true;
1301 return BPF_SIZE(code) == BPF_DW;
1302 }
1303
1304 if (class == BPF_LD) {
1305 u8 mode = BPF_MODE(code);
1306
1307 /* LD_IMM64 */
1308 if (mode == BPF_IMM)
1309 return true;
1310
1311 /* Both LD_IND and LD_ABS return 32-bit data. */
1312 if (t != SRC_OP)
1313 return false;
1314
1315 /* Implicit ctx ptr. */
1316 if (regno == BPF_REG_6)
1317 return true;
1318
1319 /* Explicit source could be any width. */
1320 return true;
1321 }
1322
1323 if (class == BPF_ST)
1324 /* The only source register for BPF_ST is a ptr. */
1325 return true;
1326
1327 /* Conservatively return true at default. */
1328 return true;
1329 }
1330
1331 /* Return TRUE if INSN doesn't have explicit value define. */
insn_no_def(struct bpf_insn * insn)1332 static bool insn_no_def(struct bpf_insn *insn)
1333 {
1334 u8 class = BPF_CLASS(insn->code);
1335
1336 return (class == BPF_JMP || class == BPF_JMP32 ||
1337 class == BPF_STX || class == BPF_ST);
1338 }
1339
1340 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
insn_has_def32(struct bpf_verifier_env * env,struct bpf_insn * insn)1341 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1342 {
1343 if (insn_no_def(insn))
1344 return false;
1345
1346 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1347 }
1348
mark_insn_zext(struct bpf_verifier_env * env,struct bpf_reg_state * reg)1349 static void mark_insn_zext(struct bpf_verifier_env *env,
1350 struct bpf_reg_state *reg)
1351 {
1352 s32 def_idx = reg->subreg_def;
1353
1354 if (def_idx == DEF_NOT_SUBREG)
1355 return;
1356
1357 env->insn_aux_data[def_idx - 1].zext_dst = true;
1358 /* The dst will be zero extended, so won't be sub-register anymore. */
1359 reg->subreg_def = DEF_NOT_SUBREG;
1360 }
1361
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)1362 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
1363 enum reg_arg_type t)
1364 {
1365 struct bpf_verifier_state *vstate = env->cur_state;
1366 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1367 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
1368 struct bpf_reg_state *reg, *regs = state->regs;
1369 bool rw64;
1370
1371 if (regno >= MAX_BPF_REG) {
1372 verbose(env, "R%d is invalid\n", regno);
1373 return -EINVAL;
1374 }
1375
1376 reg = ®s[regno];
1377 rw64 = is_reg64(env, insn, regno, reg, t);
1378 if (t == SRC_OP) {
1379 /* check whether register used as source operand can be read */
1380 if (reg->type == NOT_INIT) {
1381 verbose(env, "R%d !read_ok\n", regno);
1382 return -EACCES;
1383 }
1384 /* We don't need to worry about FP liveness because it's read-only */
1385 if (regno == BPF_REG_FP)
1386 return 0;
1387
1388 if (rw64)
1389 mark_insn_zext(env, reg);
1390
1391 return mark_reg_read(env, reg, reg->parent,
1392 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
1393 } else {
1394 /* check whether register used as dest operand can be written to */
1395 if (regno == BPF_REG_FP) {
1396 verbose(env, "frame pointer is read only\n");
1397 return -EACCES;
1398 }
1399 reg->live |= REG_LIVE_WRITTEN;
1400 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
1401 if (t == DST_OP)
1402 mark_reg_unknown(env, regs, regno);
1403 }
1404 return 0;
1405 }
1406
1407 /* 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)1408 static int push_jmp_history(struct bpf_verifier_env *env,
1409 struct bpf_verifier_state *cur)
1410 {
1411 u32 cnt = cur->jmp_history_cnt;
1412 struct bpf_idx_pair *p;
1413
1414 cnt++;
1415 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1416 if (!p)
1417 return -ENOMEM;
1418 p[cnt - 1].idx = env->insn_idx;
1419 p[cnt - 1].prev_idx = env->prev_insn_idx;
1420 cur->jmp_history = p;
1421 cur->jmp_history_cnt = cnt;
1422 return 0;
1423 }
1424
1425 /* Backtrack one insn at a time. If idx is not at the top of recorded
1426 * history then previous instruction came from straight line execution.
1427 */
get_prev_insn_idx(struct bpf_verifier_state * st,int i,u32 * history)1428 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1429 u32 *history)
1430 {
1431 u32 cnt = *history;
1432
1433 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1434 i = st->jmp_history[cnt - 1].prev_idx;
1435 (*history)--;
1436 } else {
1437 i--;
1438 }
1439 return i;
1440 }
1441
1442 /* For given verifier state backtrack_insn() is called from the last insn to
1443 * the first insn. Its purpose is to compute a bitmask of registers and
1444 * stack slots that needs precision in the parent verifier state.
1445 */
backtrack_insn(struct bpf_verifier_env * env,int idx,u32 * reg_mask,u64 * stack_mask)1446 static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1447 u32 *reg_mask, u64 *stack_mask)
1448 {
1449 const struct bpf_insn_cbs cbs = {
1450 .cb_print = verbose,
1451 .private_data = env,
1452 };
1453 struct bpf_insn *insn = env->prog->insnsi + idx;
1454 u8 class = BPF_CLASS(insn->code);
1455 u8 opcode = BPF_OP(insn->code);
1456 u8 mode = BPF_MODE(insn->code);
1457 u32 dreg = 1u << insn->dst_reg;
1458 u32 sreg = 1u << insn->src_reg;
1459 u32 spi;
1460
1461 if (insn->code == 0)
1462 return 0;
1463 if (env->log.level & BPF_LOG_LEVEL) {
1464 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1465 verbose(env, "%d: ", idx);
1466 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1467 }
1468
1469 if (class == BPF_ALU || class == BPF_ALU64) {
1470 if (!(*reg_mask & dreg))
1471 return 0;
1472 if (opcode == BPF_END || opcode == BPF_NEG) {
1473 /* sreg is reserved and unused
1474 * dreg still need precision before this insn
1475 */
1476 return 0;
1477 } else if (opcode == BPF_MOV) {
1478 if (BPF_SRC(insn->code) == BPF_X) {
1479 /* dreg = sreg
1480 * dreg needs precision after this insn
1481 * sreg needs precision before this insn
1482 */
1483 *reg_mask &= ~dreg;
1484 *reg_mask |= sreg;
1485 } else {
1486 /* dreg = K
1487 * dreg needs precision after this insn.
1488 * Corresponding register is already marked
1489 * as precise=true in this verifier state.
1490 * No further markings in parent are necessary
1491 */
1492 *reg_mask &= ~dreg;
1493 }
1494 } else {
1495 if (BPF_SRC(insn->code) == BPF_X) {
1496 /* dreg += sreg
1497 * both dreg and sreg need precision
1498 * before this insn
1499 */
1500 *reg_mask |= sreg;
1501 } /* else dreg += K
1502 * dreg still needs precision before this insn
1503 */
1504 }
1505 } else if (class == BPF_LDX) {
1506 if (!(*reg_mask & dreg))
1507 return 0;
1508 *reg_mask &= ~dreg;
1509
1510 /* scalars can only be spilled into stack w/o losing precision.
1511 * Load from any other memory can be zero extended.
1512 * The desire to keep that precision is already indicated
1513 * by 'precise' mark in corresponding register of this state.
1514 * No further tracking necessary.
1515 */
1516 if (insn->src_reg != BPF_REG_FP)
1517 return 0;
1518 if (BPF_SIZE(insn->code) != BPF_DW)
1519 return 0;
1520
1521 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1522 * that [fp - off] slot contains scalar that needs to be
1523 * tracked with precision
1524 */
1525 spi = (-insn->off - 1) / BPF_REG_SIZE;
1526 if (spi >= 64) {
1527 verbose(env, "BUG spi %d\n", spi);
1528 WARN_ONCE(1, "verifier backtracking bug");
1529 return -EFAULT;
1530 }
1531 *stack_mask |= 1ull << spi;
1532 } else if (class == BPF_STX || class == BPF_ST) {
1533 if (*reg_mask & dreg)
1534 /* stx & st shouldn't be using _scalar_ dst_reg
1535 * to access memory. It means backtracking
1536 * encountered a case of pointer subtraction.
1537 */
1538 return -ENOTSUPP;
1539 /* scalars can only be spilled into stack */
1540 if (insn->dst_reg != BPF_REG_FP)
1541 return 0;
1542 if (BPF_SIZE(insn->code) != BPF_DW)
1543 return 0;
1544 spi = (-insn->off - 1) / BPF_REG_SIZE;
1545 if (spi >= 64) {
1546 verbose(env, "BUG spi %d\n", spi);
1547 WARN_ONCE(1, "verifier backtracking bug");
1548 return -EFAULT;
1549 }
1550 if (!(*stack_mask & (1ull << spi)))
1551 return 0;
1552 *stack_mask &= ~(1ull << spi);
1553 if (class == BPF_STX)
1554 *reg_mask |= sreg;
1555 } else if (class == BPF_JMP || class == BPF_JMP32) {
1556 if (opcode == BPF_CALL) {
1557 if (insn->src_reg == BPF_PSEUDO_CALL)
1558 return -ENOTSUPP;
1559 /* regular helper call sets R0 */
1560 *reg_mask &= ~1;
1561 if (*reg_mask & 0x3f) {
1562 /* if backtracing was looking for registers R1-R5
1563 * they should have been found already.
1564 */
1565 verbose(env, "BUG regs %x\n", *reg_mask);
1566 WARN_ONCE(1, "verifier backtracking bug");
1567 return -EFAULT;
1568 }
1569 } else if (opcode == BPF_EXIT) {
1570 return -ENOTSUPP;
1571 } else if (BPF_SRC(insn->code) == BPF_X) {
1572 if (!(*reg_mask & (dreg | sreg)))
1573 return 0;
1574 /* dreg <cond> sreg
1575 * Both dreg and sreg need precision before
1576 * this insn. If only sreg was marked precise
1577 * before it would be equally necessary to
1578 * propagate it to dreg.
1579 */
1580 *reg_mask |= (sreg | dreg);
1581 /* else dreg <cond> K
1582 * Only dreg still needs precision before
1583 * this insn, so for the K-based conditional
1584 * there is nothing new to be marked.
1585 */
1586 }
1587 } else if (class == BPF_LD) {
1588 if (!(*reg_mask & dreg))
1589 return 0;
1590 *reg_mask &= ~dreg;
1591 /* It's ld_imm64 or ld_abs or ld_ind.
1592 * For ld_imm64 no further tracking of precision
1593 * into parent is necessary
1594 */
1595 if (mode == BPF_IND || mode == BPF_ABS)
1596 /* to be analyzed */
1597 return -ENOTSUPP;
1598 }
1599 return 0;
1600 }
1601
1602 /* the scalar precision tracking algorithm:
1603 * . at the start all registers have precise=false.
1604 * . scalar ranges are tracked as normal through alu and jmp insns.
1605 * . once precise value of the scalar register is used in:
1606 * . ptr + scalar alu
1607 * . if (scalar cond K|scalar)
1608 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1609 * backtrack through the verifier states and mark all registers and
1610 * stack slots with spilled constants that these scalar regisers
1611 * should be precise.
1612 * . during state pruning two registers (or spilled stack slots)
1613 * are equivalent if both are not precise.
1614 *
1615 * Note the verifier cannot simply walk register parentage chain,
1616 * since many different registers and stack slots could have been
1617 * used to compute single precise scalar.
1618 *
1619 * The approach of starting with precise=true for all registers and then
1620 * backtrack to mark a register as not precise when the verifier detects
1621 * that program doesn't care about specific value (e.g., when helper
1622 * takes register as ARG_ANYTHING parameter) is not safe.
1623 *
1624 * It's ok to walk single parentage chain of the verifier states.
1625 * It's possible that this backtracking will go all the way till 1st insn.
1626 * All other branches will be explored for needing precision later.
1627 *
1628 * The backtracking needs to deal with cases like:
1629 * 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)
1630 * r9 -= r8
1631 * r5 = r9
1632 * if r5 > 0x79f goto pc+7
1633 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
1634 * r5 += 1
1635 * ...
1636 * call bpf_perf_event_output#25
1637 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
1638 *
1639 * and this case:
1640 * r6 = 1
1641 * call foo // uses callee's r6 inside to compute r0
1642 * r0 += r6
1643 * if r0 == 0 goto
1644 *
1645 * to track above reg_mask/stack_mask needs to be independent for each frame.
1646 *
1647 * Also if parent's curframe > frame where backtracking started,
1648 * the verifier need to mark registers in both frames, otherwise callees
1649 * may incorrectly prune callers. This is similar to
1650 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
1651 *
1652 * For now backtracking falls back into conservative marking.
1653 */
mark_all_scalars_precise(struct bpf_verifier_env * env,struct bpf_verifier_state * st)1654 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
1655 struct bpf_verifier_state *st)
1656 {
1657 struct bpf_func_state *func;
1658 struct bpf_reg_state *reg;
1659 int i, j;
1660
1661 /* big hammer: mark all scalars precise in this path.
1662 * pop_stack may still get !precise scalars.
1663 */
1664 for (; st; st = st->parent)
1665 for (i = 0; i <= st->curframe; i++) {
1666 func = st->frame[i];
1667 for (j = 0; j < BPF_REG_FP; j++) {
1668 reg = &func->regs[j];
1669 if (reg->type != SCALAR_VALUE)
1670 continue;
1671 reg->precise = true;
1672 }
1673 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
1674 if (func->stack[j].slot_type[0] != STACK_SPILL)
1675 continue;
1676 reg = &func->stack[j].spilled_ptr;
1677 if (reg->type != SCALAR_VALUE)
1678 continue;
1679 reg->precise = true;
1680 }
1681 }
1682 }
1683
__mark_chain_precision(struct bpf_verifier_env * env,int regno,int spi)1684 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
1685 int spi)
1686 {
1687 struct bpf_verifier_state *st = env->cur_state;
1688 int first_idx = st->first_insn_idx;
1689 int last_idx = env->insn_idx;
1690 struct bpf_func_state *func;
1691 struct bpf_reg_state *reg;
1692 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
1693 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
1694 bool skip_first = true;
1695 bool new_marks = false;
1696 int i, err;
1697
1698 if (!env->allow_ptr_leaks)
1699 /* backtracking is root only for now */
1700 return 0;
1701
1702 func = st->frame[st->curframe];
1703 if (regno >= 0) {
1704 reg = &func->regs[regno];
1705 if (reg->type != SCALAR_VALUE) {
1706 WARN_ONCE(1, "backtracing misuse");
1707 return -EFAULT;
1708 }
1709 if (!reg->precise)
1710 new_marks = true;
1711 else
1712 reg_mask = 0;
1713 reg->precise = true;
1714 }
1715
1716 while (spi >= 0) {
1717 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
1718 stack_mask = 0;
1719 break;
1720 }
1721 reg = &func->stack[spi].spilled_ptr;
1722 if (reg->type != SCALAR_VALUE) {
1723 stack_mask = 0;
1724 break;
1725 }
1726 if (!reg->precise)
1727 new_marks = true;
1728 else
1729 stack_mask = 0;
1730 reg->precise = true;
1731 break;
1732 }
1733
1734 if (!new_marks)
1735 return 0;
1736 if (!reg_mask && !stack_mask)
1737 return 0;
1738 for (;;) {
1739 DECLARE_BITMAP(mask, 64);
1740 u32 history = st->jmp_history_cnt;
1741
1742 if (env->log.level & BPF_LOG_LEVEL)
1743 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
1744 for (i = last_idx;;) {
1745 if (skip_first) {
1746 err = 0;
1747 skip_first = false;
1748 } else {
1749 err = backtrack_insn(env, i, ®_mask, &stack_mask);
1750 }
1751 if (err == -ENOTSUPP) {
1752 mark_all_scalars_precise(env, st);
1753 return 0;
1754 } else if (err) {
1755 return err;
1756 }
1757 if (!reg_mask && !stack_mask)
1758 /* Found assignment(s) into tracked register in this state.
1759 * Since this state is already marked, just return.
1760 * Nothing to be tracked further in the parent state.
1761 */
1762 return 0;
1763 if (i == first_idx)
1764 break;
1765 i = get_prev_insn_idx(st, i, &history);
1766 if (i >= env->prog->len) {
1767 /* This can happen if backtracking reached insn 0
1768 * and there are still reg_mask or stack_mask
1769 * to backtrack.
1770 * It means the backtracking missed the spot where
1771 * particular register was initialized with a constant.
1772 */
1773 verbose(env, "BUG backtracking idx %d\n", i);
1774 WARN_ONCE(1, "verifier backtracking bug");
1775 return -EFAULT;
1776 }
1777 }
1778 st = st->parent;
1779 if (!st)
1780 break;
1781
1782 new_marks = false;
1783 func = st->frame[st->curframe];
1784 bitmap_from_u64(mask, reg_mask);
1785 for_each_set_bit(i, mask, 32) {
1786 reg = &func->regs[i];
1787 if (reg->type != SCALAR_VALUE) {
1788 reg_mask &= ~(1u << i);
1789 continue;
1790 }
1791 if (!reg->precise)
1792 new_marks = true;
1793 reg->precise = true;
1794 }
1795
1796 bitmap_from_u64(mask, stack_mask);
1797 for_each_set_bit(i, mask, 64) {
1798 if (i >= func->allocated_stack / BPF_REG_SIZE) {
1799 /* the sequence of instructions:
1800 * 2: (bf) r3 = r10
1801 * 3: (7b) *(u64 *)(r3 -8) = r0
1802 * 4: (79) r4 = *(u64 *)(r10 -8)
1803 * doesn't contain jmps. It's backtracked
1804 * as a single block.
1805 * During backtracking insn 3 is not recognized as
1806 * stack access, so at the end of backtracking
1807 * stack slot fp-8 is still marked in stack_mask.
1808 * However the parent state may not have accessed
1809 * fp-8 and it's "unallocated" stack space.
1810 * In such case fallback to conservative.
1811 */
1812 mark_all_scalars_precise(env, st);
1813 return 0;
1814 }
1815
1816 if (func->stack[i].slot_type[0] != STACK_SPILL) {
1817 stack_mask &= ~(1ull << i);
1818 continue;
1819 }
1820 reg = &func->stack[i].spilled_ptr;
1821 if (reg->type != SCALAR_VALUE) {
1822 stack_mask &= ~(1ull << i);
1823 continue;
1824 }
1825 if (!reg->precise)
1826 new_marks = true;
1827 reg->precise = true;
1828 }
1829 if (env->log.level & BPF_LOG_LEVEL) {
1830 print_verifier_state(env, func);
1831 verbose(env, "parent %s regs=%x stack=%llx marks\n",
1832 new_marks ? "didn't have" : "already had",
1833 reg_mask, stack_mask);
1834 }
1835
1836 if (!reg_mask && !stack_mask)
1837 break;
1838 if (!new_marks)
1839 break;
1840
1841 last_idx = st->last_insn_idx;
1842 first_idx = st->first_insn_idx;
1843 }
1844 return 0;
1845 }
1846
mark_chain_precision(struct bpf_verifier_env * env,int regno)1847 static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
1848 {
1849 return __mark_chain_precision(env, regno, -1);
1850 }
1851
mark_chain_precision_stack(struct bpf_verifier_env * env,int spi)1852 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
1853 {
1854 return __mark_chain_precision(env, -1, spi);
1855 }
1856
is_spillable_regtype(enum bpf_reg_type type)1857 static bool is_spillable_regtype(enum bpf_reg_type type)
1858 {
1859 switch (type) {
1860 case PTR_TO_MAP_VALUE:
1861 case PTR_TO_MAP_VALUE_OR_NULL:
1862 case PTR_TO_STACK:
1863 case PTR_TO_CTX:
1864 case PTR_TO_PACKET:
1865 case PTR_TO_PACKET_META:
1866 case PTR_TO_PACKET_END:
1867 case PTR_TO_FLOW_KEYS:
1868 case CONST_PTR_TO_MAP:
1869 case PTR_TO_SOCKET:
1870 case PTR_TO_SOCKET_OR_NULL:
1871 case PTR_TO_SOCK_COMMON:
1872 case PTR_TO_SOCK_COMMON_OR_NULL:
1873 case PTR_TO_TCP_SOCK:
1874 case PTR_TO_TCP_SOCK_OR_NULL:
1875 case PTR_TO_XDP_SOCK:
1876 return true;
1877 default:
1878 return false;
1879 }
1880 }
1881
1882 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)1883 static bool register_is_null(struct bpf_reg_state *reg)
1884 {
1885 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
1886 }
1887
register_is_const(struct bpf_reg_state * reg)1888 static bool register_is_const(struct bpf_reg_state *reg)
1889 {
1890 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
1891 }
1892
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)1893 static bool __is_pointer_value(bool allow_ptr_leaks,
1894 const struct bpf_reg_state *reg)
1895 {
1896 if (allow_ptr_leaks)
1897 return false;
1898
1899 return reg->type != SCALAR_VALUE;
1900 }
1901
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg)1902 static void save_register_state(struct bpf_func_state *state,
1903 int spi, struct bpf_reg_state *reg)
1904 {
1905 int i;
1906
1907 state->stack[spi].spilled_ptr = *reg;
1908 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1909
1910 for (i = 0; i < BPF_REG_SIZE; i++)
1911 state->stack[spi].slot_type[i] = STACK_SPILL;
1912 }
1913
1914 /* check_stack_read/write functions track spill/fill of registers,
1915 * stack boundary and alignment are checked in check_mem_access()
1916 */
check_stack_write(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)1917 static int check_stack_write(struct bpf_verifier_env *env,
1918 struct bpf_func_state *state, /* func where register points to */
1919 int off, int size, int value_regno, int insn_idx)
1920 {
1921 struct bpf_func_state *cur; /* state of the current function */
1922 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
1923 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
1924 struct bpf_reg_state *reg = NULL;
1925
1926 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
1927 state->acquired_refs, true);
1928 if (err)
1929 return err;
1930 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
1931 * so it's aligned access and [off, off + size) are within stack limits
1932 */
1933 if (!env->allow_ptr_leaks &&
1934 state->stack[spi].slot_type[0] == STACK_SPILL &&
1935 size != BPF_REG_SIZE) {
1936 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1937 return -EACCES;
1938 }
1939
1940 cur = env->cur_state->frame[env->cur_state->curframe];
1941 if (value_regno >= 0)
1942 reg = &cur->regs[value_regno];
1943 if (!env->allow_ptr_leaks) {
1944 bool sanitize = reg && is_spillable_regtype(reg->type);
1945
1946 for (i = 0; i < size; i++) {
1947 u8 type = state->stack[spi].slot_type[i];
1948
1949 if (type != STACK_MISC && type != STACK_ZERO) {
1950 sanitize = true;
1951 break;
1952 }
1953 }
1954
1955 if (sanitize)
1956 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
1957 }
1958
1959 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1960 !register_is_null(reg) && env->allow_ptr_leaks) {
1961 if (dst_reg != BPF_REG_FP) {
1962 /* The backtracking logic can only recognize explicit
1963 * stack slot address like [fp - 8]. Other spill of
1964 * scalar via different register has to be conervative.
1965 * Backtrack from here and mark all registers as precise
1966 * that contributed into 'reg' being a constant.
1967 */
1968 err = mark_chain_precision(env, value_regno);
1969 if (err)
1970 return err;
1971 }
1972 save_register_state(state, spi, reg);
1973 } else if (reg && is_spillable_regtype(reg->type)) {
1974 /* register containing pointer is being spilled into stack */
1975 if (size != BPF_REG_SIZE) {
1976 verbose_linfo(env, insn_idx, "; ");
1977 verbose(env, "invalid size of register spill\n");
1978 return -EACCES;
1979 }
1980 if (state != cur && reg->type == PTR_TO_STACK) {
1981 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1982 return -EINVAL;
1983 }
1984 save_register_state(state, spi, reg);
1985 } else {
1986 u8 type = STACK_MISC;
1987
1988 /* regular write of data into stack destroys any spilled ptr */
1989 state->stack[spi].spilled_ptr.type = NOT_INIT;
1990 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
1991 if (state->stack[spi].slot_type[0] == STACK_SPILL)
1992 for (i = 0; i < BPF_REG_SIZE; i++)
1993 state->stack[spi].slot_type[i] = STACK_MISC;
1994
1995 /* only mark the slot as written if all 8 bytes were written
1996 * otherwise read propagation may incorrectly stop too soon
1997 * when stack slots are partially written.
1998 * This heuristic means that read propagation will be
1999 * conservative, since it will add reg_live_read marks
2000 * to stack slots all the way to first state when programs
2001 * writes+reads less than 8 bytes
2002 */
2003 if (size == BPF_REG_SIZE)
2004 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2005
2006 /* when we zero initialize stack slots mark them as such */
2007 if (reg && register_is_null(reg)) {
2008 /* backtracking doesn't work for STACK_ZERO yet. */
2009 err = mark_chain_precision(env, value_regno);
2010 if (err)
2011 return err;
2012 type = STACK_ZERO;
2013 }
2014
2015 /* Mark slots affected by this stack write. */
2016 for (i = 0; i < size; i++)
2017 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
2018 type;
2019 }
2020 return 0;
2021 }
2022
check_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int value_regno)2023 static int check_stack_read(struct bpf_verifier_env *env,
2024 struct bpf_func_state *reg_state /* func where register points to */,
2025 int off, int size, int value_regno)
2026 {
2027 struct bpf_verifier_state *vstate = env->cur_state;
2028 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2029 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
2030 struct bpf_reg_state *reg;
2031 u8 *stype;
2032
2033 if (reg_state->allocated_stack <= slot) {
2034 verbose(env, "invalid read from stack off %d+0 size %d\n",
2035 off, size);
2036 return -EACCES;
2037 }
2038 stype = reg_state->stack[spi].slot_type;
2039 reg = ®_state->stack[spi].spilled_ptr;
2040
2041 if (stype[0] == STACK_SPILL) {
2042 if (size != BPF_REG_SIZE) {
2043 if (reg->type != SCALAR_VALUE) {
2044 verbose_linfo(env, env->insn_idx, "; ");
2045 verbose(env, "invalid size of register fill\n");
2046 return -EACCES;
2047 }
2048 if (value_regno >= 0) {
2049 mark_reg_unknown(env, state->regs, value_regno);
2050 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2051 }
2052 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2053 return 0;
2054 }
2055 for (i = 1; i < BPF_REG_SIZE; i++) {
2056 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
2057 verbose(env, "corrupted spill memory\n");
2058 return -EACCES;
2059 }
2060 }
2061
2062 if (value_regno >= 0) {
2063 /* restore register state from stack */
2064 state->regs[value_regno] = *reg;
2065 /* mark reg as written since spilled pointer state likely
2066 * has its liveness marks cleared by is_state_visited()
2067 * which resets stack/reg liveness for state transitions
2068 */
2069 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2070 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
2071 /* If value_regno==-1, the caller is asking us whether
2072 * it is acceptable to use this value as a SCALAR_VALUE
2073 * (e.g. for XADD).
2074 * We must not allow unprivileged callers to do that
2075 * with spilled pointers.
2076 */
2077 verbose(env, "leaking pointer from stack off %d\n",
2078 off);
2079 return -EACCES;
2080 }
2081 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2082 } else {
2083 int zeros = 0;
2084
2085 for (i = 0; i < size; i++) {
2086 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
2087 continue;
2088 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
2089 zeros++;
2090 continue;
2091 }
2092 verbose(env, "invalid read from stack off %d+%d size %d\n",
2093 off, i, size);
2094 return -EACCES;
2095 }
2096 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2097 if (value_regno >= 0) {
2098 if (zeros == size) {
2099 /* any size read into register is zero extended,
2100 * so the whole register == const_zero
2101 */
2102 __mark_reg_const_zero(&state->regs[value_regno]);
2103 /* backtracking doesn't support STACK_ZERO yet,
2104 * so mark it precise here, so that later
2105 * backtracking can stop here.
2106 * Backtracking may not need this if this register
2107 * doesn't participate in pointer adjustment.
2108 * Forward propagation of precise flag is not
2109 * necessary either. This mark is only to stop
2110 * backtracking. Any register that contributed
2111 * to const 0 was marked precise before spill.
2112 */
2113 state->regs[value_regno].precise = true;
2114 } else {
2115 /* have read misc data from the stack */
2116 mark_reg_unknown(env, state->regs, value_regno);
2117 }
2118 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
2119 }
2120 }
2121 return 0;
2122 }
2123
check_stack_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size)2124 static int check_stack_access(struct bpf_verifier_env *env,
2125 const struct bpf_reg_state *reg,
2126 int off, int size)
2127 {
2128 /* Stack accesses must be at a fixed offset, so that we
2129 * can determine what type of data were returned. See
2130 * check_stack_read().
2131 */
2132 if (!tnum_is_const(reg->var_off)) {
2133 char tn_buf[48];
2134
2135 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2136 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
2137 tn_buf, off, size);
2138 return -EACCES;
2139 }
2140
2141 if (off >= 0 || off < -MAX_BPF_STACK) {
2142 verbose(env, "invalid stack off=%d size=%d\n", off, size);
2143 return -EACCES;
2144 }
2145
2146 return 0;
2147 }
2148
check_map_access_type(struct bpf_verifier_env * env,u32 regno,int off,int size,enum bpf_access_type type)2149 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2150 int off, int size, enum bpf_access_type type)
2151 {
2152 struct bpf_reg_state *regs = cur_regs(env);
2153 struct bpf_map *map = regs[regno].map_ptr;
2154 u32 cap = bpf_map_flags_to_cap(map);
2155
2156 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2157 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2158 map->value_size, off, size);
2159 return -EACCES;
2160 }
2161
2162 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2163 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2164 map->value_size, off, size);
2165 return -EACCES;
2166 }
2167
2168 return 0;
2169 }
2170
2171 /* check read/write into map element returned by bpf_map_lookup_elem() */
__check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)2172 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
2173 int size, bool zero_size_allowed)
2174 {
2175 struct bpf_reg_state *regs = cur_regs(env);
2176 struct bpf_map *map = regs[regno].map_ptr;
2177
2178 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2179 off + size > map->value_size) {
2180 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
2181 map->value_size, off, size);
2182 return -EACCES;
2183 }
2184 return 0;
2185 }
2186
2187 /* 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)2188 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2189 int off, int size, bool zero_size_allowed)
2190 {
2191 struct bpf_verifier_state *vstate = env->cur_state;
2192 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2193 struct bpf_reg_state *reg = &state->regs[regno];
2194 int err;
2195
2196 /* We may have adjusted the register to this map value, so we
2197 * need to try adding each of min_value and max_value to off
2198 * to make sure our theoretical access will be safe.
2199 */
2200 if (env->log.level & BPF_LOG_LEVEL)
2201 print_verifier_state(env, state);
2202
2203 /* The minimum value is only important with signed
2204 * comparisons where we can't assume the floor of a
2205 * value is 0. If we are using signed variables for our
2206 * index'es we need to make sure that whatever we use
2207 * will have a set floor within our range.
2208 */
2209 if (reg->smin_value < 0 &&
2210 (reg->smin_value == S64_MIN ||
2211 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2212 reg->smin_value + off < 0)) {
2213 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2214 regno);
2215 return -EACCES;
2216 }
2217 err = __check_map_access(env, regno, reg->smin_value + off, size,
2218 zero_size_allowed);
2219 if (err) {
2220 verbose(env, "R%d min value is outside of the array range\n",
2221 regno);
2222 return err;
2223 }
2224
2225 /* If we haven't set a max value then we need to bail since we can't be
2226 * sure we won't do bad things.
2227 * If reg->umax_value + off could overflow, treat that as unbounded too.
2228 */
2229 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
2230 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
2231 regno);
2232 return -EACCES;
2233 }
2234 err = __check_map_access(env, regno, reg->umax_value + off, size,
2235 zero_size_allowed);
2236 if (err)
2237 verbose(env, "R%d max value is outside of the array range\n",
2238 regno);
2239
2240 if (map_value_has_spin_lock(reg->map_ptr)) {
2241 u32 lock = reg->map_ptr->spin_lock_off;
2242
2243 /* if any part of struct bpf_spin_lock can be touched by
2244 * load/store reject this program.
2245 * To check that [x1, x2) overlaps with [y1, y2)
2246 * it is sufficient to check x1 < y2 && y1 < x2.
2247 */
2248 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2249 lock < reg->umax_value + off + size) {
2250 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2251 return -EACCES;
2252 }
2253 }
2254 return err;
2255 }
2256
2257 #define MAX_PACKET_OFF 0xffff
2258
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)2259 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
2260 const struct bpf_call_arg_meta *meta,
2261 enum bpf_access_type t)
2262 {
2263 switch (env->prog->type) {
2264 /* Program types only with direct read access go here! */
2265 case BPF_PROG_TYPE_LWT_IN:
2266 case BPF_PROG_TYPE_LWT_OUT:
2267 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2268 case BPF_PROG_TYPE_SK_REUSEPORT:
2269 case BPF_PROG_TYPE_FLOW_DISSECTOR:
2270 case BPF_PROG_TYPE_CGROUP_SKB:
2271 if (t == BPF_WRITE)
2272 return false;
2273 /* fallthrough */
2274
2275 /* Program types with direct read + write access go here! */
2276 case BPF_PROG_TYPE_SCHED_CLS:
2277 case BPF_PROG_TYPE_SCHED_ACT:
2278 case BPF_PROG_TYPE_XDP:
2279 case BPF_PROG_TYPE_LWT_XMIT:
2280 case BPF_PROG_TYPE_SK_SKB:
2281 case BPF_PROG_TYPE_SK_MSG:
2282 if (meta)
2283 return meta->pkt_access;
2284
2285 env->seen_direct_write = true;
2286 return true;
2287
2288 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2289 if (t == BPF_WRITE)
2290 env->seen_direct_write = true;
2291
2292 return true;
2293
2294 default:
2295 return false;
2296 }
2297 }
2298
__check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)2299 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
2300 int off, int size, bool zero_size_allowed)
2301 {
2302 struct bpf_reg_state *regs = cur_regs(env);
2303 struct bpf_reg_state *reg = ®s[regno];
2304
2305 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
2306 (u64)off + size > reg->range) {
2307 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2308 off, size, regno, reg->id, reg->off, reg->range);
2309 return -EACCES;
2310 }
2311 return 0;
2312 }
2313
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)2314 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
2315 int size, bool zero_size_allowed)
2316 {
2317 struct bpf_reg_state *regs = cur_regs(env);
2318 struct bpf_reg_state *reg = ®s[regno];
2319 int err;
2320
2321 /* We may have added a variable offset to the packet pointer; but any
2322 * reg->range we have comes after that. We are only checking the fixed
2323 * offset.
2324 */
2325
2326 /* We don't allow negative numbers, because we aren't tracking enough
2327 * detail to prove they're safe.
2328 */
2329 if (reg->smin_value < 0) {
2330 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2331 regno);
2332 return -EACCES;
2333 }
2334 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
2335 if (err) {
2336 verbose(env, "R%d offset is outside of the packet\n", regno);
2337 return err;
2338 }
2339
2340 /* __check_packet_access has made sure "off + size - 1" is within u16.
2341 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
2342 * otherwise find_good_pkt_pointers would have refused to set range info
2343 * that __check_packet_access would have rejected this pkt access.
2344 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
2345 */
2346 env->prog->aux->max_pkt_offset =
2347 max_t(u32, env->prog->aux->max_pkt_offset,
2348 off + reg->umax_value + size - 1);
2349
2350 return err;
2351 }
2352
2353 /* 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)2354 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
2355 enum bpf_access_type t, enum bpf_reg_type *reg_type)
2356 {
2357 struct bpf_insn_access_aux info = {
2358 .reg_type = *reg_type,
2359 };
2360
2361 if (env->ops->is_valid_access &&
2362 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
2363 /* A non zero info.ctx_field_size indicates that this field is a
2364 * candidate for later verifier transformation to load the whole
2365 * field and then apply a mask when accessed with a narrower
2366 * access than actual ctx access size. A zero info.ctx_field_size
2367 * will only allow for whole field access and rejects any other
2368 * type of narrower access.
2369 */
2370 *reg_type = info.reg_type;
2371
2372 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
2373 /* remember the offset of last byte accessed in ctx */
2374 if (env->prog->aux->max_ctx_offset < off + size)
2375 env->prog->aux->max_ctx_offset = off + size;
2376 return 0;
2377 }
2378
2379 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
2380 return -EACCES;
2381 }
2382
check_flow_keys_access(struct bpf_verifier_env * env,int off,int size)2383 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
2384 int size)
2385 {
2386 if (size < 0 || off < 0 ||
2387 (u64)off + size > sizeof(struct bpf_flow_keys)) {
2388 verbose(env, "invalid access to flow keys off=%d size=%d\n",
2389 off, size);
2390 return -EACCES;
2391 }
2392 return 0;
2393 }
2394
check_sock_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int size,enum bpf_access_type t)2395 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
2396 u32 regno, int off, int size,
2397 enum bpf_access_type t)
2398 {
2399 struct bpf_reg_state *regs = cur_regs(env);
2400 struct bpf_reg_state *reg = ®s[regno];
2401 struct bpf_insn_access_aux info = {};
2402 bool valid;
2403
2404 if (reg->smin_value < 0) {
2405 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
2406 regno);
2407 return -EACCES;
2408 }
2409
2410 switch (reg->type) {
2411 case PTR_TO_SOCK_COMMON:
2412 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
2413 break;
2414 case PTR_TO_SOCKET:
2415 valid = bpf_sock_is_valid_access(off, size, t, &info);
2416 break;
2417 case PTR_TO_TCP_SOCK:
2418 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
2419 break;
2420 case PTR_TO_XDP_SOCK:
2421 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
2422 break;
2423 default:
2424 valid = false;
2425 }
2426
2427
2428 if (valid) {
2429 env->insn_aux_data[insn_idx].ctx_field_size =
2430 info.ctx_field_size;
2431 return 0;
2432 }
2433
2434 verbose(env, "R%d invalid %s access off=%d size=%d\n",
2435 regno, reg_type_str[reg->type], off, size);
2436
2437 return -EACCES;
2438 }
2439
reg_state(struct bpf_verifier_env * env,int regno)2440 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2441 {
2442 return cur_regs(env) + regno;
2443 }
2444
is_pointer_value(struct bpf_verifier_env * env,int regno)2445 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
2446 {
2447 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
2448 }
2449
is_ctx_reg(struct bpf_verifier_env * env,int regno)2450 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
2451 {
2452 const struct bpf_reg_state *reg = reg_state(env, regno);
2453
2454 return reg->type == PTR_TO_CTX;
2455 }
2456
is_sk_reg(struct bpf_verifier_env * env,int regno)2457 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
2458 {
2459 const struct bpf_reg_state *reg = reg_state(env, regno);
2460
2461 return type_is_sk_pointer(reg->type);
2462 }
2463
is_pkt_reg(struct bpf_verifier_env * env,int regno)2464 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
2465 {
2466 const struct bpf_reg_state *reg = reg_state(env, regno);
2467
2468 return type_is_pkt_pointer(reg->type);
2469 }
2470
is_flow_key_reg(struct bpf_verifier_env * env,int regno)2471 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
2472 {
2473 const struct bpf_reg_state *reg = reg_state(env, regno);
2474
2475 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
2476 return reg->type == PTR_TO_FLOW_KEYS;
2477 }
2478
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)2479 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
2480 const struct bpf_reg_state *reg,
2481 int off, int size, bool strict)
2482 {
2483 struct tnum reg_off;
2484 int ip_align;
2485
2486 /* Byte size accesses are always allowed. */
2487 if (!strict || size == 1)
2488 return 0;
2489
2490 /* For platforms that do not have a Kconfig enabling
2491 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
2492 * NET_IP_ALIGN is universally set to '2'. And on platforms
2493 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
2494 * to this code only in strict mode where we want to emulate
2495 * the NET_IP_ALIGN==2 checking. Therefore use an
2496 * unconditional IP align value of '2'.
2497 */
2498 ip_align = 2;
2499
2500 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
2501 if (!tnum_is_aligned(reg_off, size)) {
2502 char tn_buf[48];
2503
2504 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2505 verbose(env,
2506 "misaligned packet access off %d+%s+%d+%d size %d\n",
2507 ip_align, tn_buf, reg->off, off, size);
2508 return -EACCES;
2509 }
2510
2511 return 0;
2512 }
2513
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)2514 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
2515 const struct bpf_reg_state *reg,
2516 const char *pointer_desc,
2517 int off, int size, bool strict)
2518 {
2519 struct tnum reg_off;
2520
2521 /* Byte size accesses are always allowed. */
2522 if (!strict || size == 1)
2523 return 0;
2524
2525 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
2526 if (!tnum_is_aligned(reg_off, size)) {
2527 char tn_buf[48];
2528
2529 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2530 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
2531 pointer_desc, tn_buf, reg->off, off, size);
2532 return -EACCES;
2533 }
2534
2535 return 0;
2536 }
2537
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)2538 static int check_ptr_alignment(struct bpf_verifier_env *env,
2539 const struct bpf_reg_state *reg, int off,
2540 int size, bool strict_alignment_once)
2541 {
2542 bool strict = env->strict_alignment || strict_alignment_once;
2543 const char *pointer_desc = "";
2544
2545 switch (reg->type) {
2546 case PTR_TO_PACKET:
2547 case PTR_TO_PACKET_META:
2548 /* Special case, because of NET_IP_ALIGN. Given metadata sits
2549 * right in front, treat it the very same way.
2550 */
2551 return check_pkt_ptr_alignment(env, reg, off, size, strict);
2552 case PTR_TO_FLOW_KEYS:
2553 pointer_desc = "flow keys ";
2554 break;
2555 case PTR_TO_MAP_VALUE:
2556 pointer_desc = "value ";
2557 break;
2558 case PTR_TO_CTX:
2559 pointer_desc = "context ";
2560 break;
2561 case PTR_TO_STACK:
2562 pointer_desc = "stack ";
2563 /* The stack spill tracking logic in check_stack_write()
2564 * and check_stack_read() relies on stack accesses being
2565 * aligned.
2566 */
2567 strict = true;
2568 break;
2569 case PTR_TO_SOCKET:
2570 pointer_desc = "sock ";
2571 break;
2572 case PTR_TO_SOCK_COMMON:
2573 pointer_desc = "sock_common ";
2574 break;
2575 case PTR_TO_TCP_SOCK:
2576 pointer_desc = "tcp_sock ";
2577 break;
2578 case PTR_TO_XDP_SOCK:
2579 pointer_desc = "xdp_sock ";
2580 break;
2581 default:
2582 break;
2583 }
2584 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
2585 strict);
2586 }
2587
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)2588 static int update_stack_depth(struct bpf_verifier_env *env,
2589 const struct bpf_func_state *func,
2590 int off)
2591 {
2592 u16 stack = env->subprog_info[func->subprogno].stack_depth;
2593
2594 if (stack >= -off)
2595 return 0;
2596
2597 /* update known max for given subprogram */
2598 env->subprog_info[func->subprogno].stack_depth = -off;
2599 return 0;
2600 }
2601
2602 /* starting from main bpf function walk all instructions of the function
2603 * and recursively walk all callees that given function can call.
2604 * Ignore jump and exit insns.
2605 * Since recursion is prevented by check_cfg() this algorithm
2606 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
2607 */
check_max_stack_depth(struct bpf_verifier_env * env)2608 static int check_max_stack_depth(struct bpf_verifier_env *env)
2609 {
2610 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
2611 struct bpf_subprog_info *subprog = env->subprog_info;
2612 struct bpf_insn *insn = env->prog->insnsi;
2613 int ret_insn[MAX_CALL_FRAMES];
2614 int ret_prog[MAX_CALL_FRAMES];
2615
2616 process_func:
2617 /* protect against potential stack overflow that might happen when
2618 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
2619 * depth for such case down to 256 so that the worst case scenario
2620 * would result in 8k stack size (32 which is tailcall limit * 256 =
2621 * 8k).
2622 *
2623 * To get the idea what might happen, see an example:
2624 * func1 -> sub rsp, 128
2625 * subfunc1 -> sub rsp, 256
2626 * tailcall1 -> add rsp, 256
2627 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
2628 * subfunc2 -> sub rsp, 64
2629 * subfunc22 -> sub rsp, 128
2630 * tailcall2 -> add rsp, 128
2631 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
2632 *
2633 * tailcall will unwind the current stack frame but it will not get rid
2634 * of caller's stack as shown on the example above.
2635 */
2636 if (idx && subprog[idx].has_tail_call && depth >= 256) {
2637 verbose(env,
2638 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
2639 depth);
2640 return -EACCES;
2641 }
2642 /* round up to 32-bytes, since this is granularity
2643 * of interpreter stack size
2644 */
2645 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2646 if (depth > MAX_BPF_STACK) {
2647 verbose(env, "combined stack size of %d calls is %d. Too large\n",
2648 frame + 1, depth);
2649 return -EACCES;
2650 }
2651 continue_func:
2652 subprog_end = subprog[idx + 1].start;
2653 for (; i < subprog_end; i++) {
2654 if (insn[i].code != (BPF_JMP | BPF_CALL))
2655 continue;
2656 if (insn[i].src_reg != BPF_PSEUDO_CALL)
2657 continue;
2658 /* remember insn and function to return to */
2659 ret_insn[frame] = i + 1;
2660 ret_prog[frame] = idx;
2661
2662 /* find the callee */
2663 i = i + insn[i].imm + 1;
2664 idx = find_subprog(env, i);
2665 if (idx < 0) {
2666 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2667 i);
2668 return -EFAULT;
2669 }
2670 frame++;
2671 if (frame >= MAX_CALL_FRAMES) {
2672 verbose(env, "the call stack of %d frames is too deep !\n",
2673 frame);
2674 return -E2BIG;
2675 }
2676 goto process_func;
2677 }
2678 /* end of for() loop means the last insn of the 'subprog'
2679 * was reached. Doesn't matter whether it was JA or EXIT
2680 */
2681 if (frame == 0)
2682 return 0;
2683 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
2684 frame--;
2685 i = ret_insn[frame];
2686 idx = ret_prog[frame];
2687 goto continue_func;
2688 }
2689
2690 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)2691 static int get_callee_stack_depth(struct bpf_verifier_env *env,
2692 const struct bpf_insn *insn, int idx)
2693 {
2694 int start = idx + insn->imm + 1, subprog;
2695
2696 subprog = find_subprog(env, start);
2697 if (subprog < 0) {
2698 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
2699 start);
2700 return -EFAULT;
2701 }
2702 return env->subprog_info[subprog].stack_depth;
2703 }
2704 #endif
2705
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)2706 static int check_ctx_reg(struct bpf_verifier_env *env,
2707 const struct bpf_reg_state *reg, int regno)
2708 {
2709 /* Access to ctx or passing it to a helper is only allowed in
2710 * its original, unmodified form.
2711 */
2712
2713 if (reg->off) {
2714 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
2715 regno, reg->off);
2716 return -EACCES;
2717 }
2718
2719 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2720 char tn_buf[48];
2721
2722 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2723 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
2724 return -EACCES;
2725 }
2726
2727 return 0;
2728 }
2729
check_tp_buffer_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno,int off,int size)2730 static int check_tp_buffer_access(struct bpf_verifier_env *env,
2731 const struct bpf_reg_state *reg,
2732 int regno, int off, int size)
2733 {
2734 if (off < 0) {
2735 verbose(env,
2736 "R%d invalid tracepoint buffer access: off=%d, size=%d",
2737 regno, off, size);
2738 return -EACCES;
2739 }
2740 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
2741 char tn_buf[48];
2742
2743 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2744 verbose(env,
2745 "R%d invalid variable buffer offset: off=%d, var_off=%s",
2746 regno, off, tn_buf);
2747 return -EACCES;
2748 }
2749 if (off + size > env->prog->aux->max_tp_access)
2750 env->prog->aux->max_tp_access = off + size;
2751
2752 return 0;
2753 }
2754
2755
2756 /* truncate register to smaller size (in bytes)
2757 * must be called with size < BPF_REG_SIZE
2758 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)2759 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
2760 {
2761 u64 mask;
2762
2763 /* clear high bits in bit representation */
2764 reg->var_off = tnum_cast(reg->var_off, size);
2765
2766 /* fix arithmetic bounds */
2767 mask = ((u64)1 << (size * 8)) - 1;
2768 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
2769 reg->umin_value &= mask;
2770 reg->umax_value &= mask;
2771 } else {
2772 reg->umin_value = 0;
2773 reg->umax_value = mask;
2774 }
2775 reg->smin_value = reg->umin_value;
2776 reg->smax_value = reg->umax_value;
2777 }
2778
bpf_map_is_rdonly(const struct bpf_map * map)2779 static bool bpf_map_is_rdonly(const struct bpf_map *map)
2780 {
2781 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
2782 }
2783
bpf_map_direct_read(struct bpf_map * map,int off,int size,u64 * val)2784 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
2785 {
2786 void *ptr;
2787 u64 addr;
2788 int err;
2789
2790 err = map->ops->map_direct_value_addr(map, &addr, off);
2791 if (err)
2792 return err;
2793 ptr = (void *)(long)addr + off;
2794
2795 switch (size) {
2796 case sizeof(u8):
2797 *val = (u64)*(u8 *)ptr;
2798 break;
2799 case sizeof(u16):
2800 *val = (u64)*(u16 *)ptr;
2801 break;
2802 case sizeof(u32):
2803 *val = (u64)*(u32 *)ptr;
2804 break;
2805 case sizeof(u64):
2806 *val = *(u64 *)ptr;
2807 break;
2808 default:
2809 return -EINVAL;
2810 }
2811 return 0;
2812 }
2813
2814 /* check whether memory at (regno + off) is accessible for t = (read | write)
2815 * if t==write, value_regno is a register which value is stored into memory
2816 * if t==read, value_regno is a register which will receive the value from memory
2817 * if t==write && value_regno==-1, some unknown value is stored into memory
2818 * if t==read && value_regno==-1, don't care what we read from memory
2819 */
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)2820 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
2821 int off, int bpf_size, enum bpf_access_type t,
2822 int value_regno, bool strict_alignment_once)
2823 {
2824 struct bpf_reg_state *regs = cur_regs(env);
2825 struct bpf_reg_state *reg = regs + regno;
2826 struct bpf_func_state *state;
2827 int size, err = 0;
2828
2829 size = bpf_size_to_bytes(bpf_size);
2830 if (size < 0)
2831 return size;
2832
2833 /* alignment checks will add in reg->off themselves */
2834 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
2835 if (err)
2836 return err;
2837
2838 /* for access checks, reg->off is just part of off */
2839 off += reg->off;
2840
2841 if (reg->type == PTR_TO_MAP_VALUE) {
2842 if (t == BPF_WRITE && value_regno >= 0 &&
2843 is_pointer_value(env, value_regno)) {
2844 verbose(env, "R%d leaks addr into map\n", value_regno);
2845 return -EACCES;
2846 }
2847 err = check_map_access_type(env, regno, off, size, t);
2848 if (err)
2849 return err;
2850 err = check_map_access(env, regno, off, size, false);
2851 if (!err && t == BPF_READ && value_regno >= 0) {
2852 struct bpf_map *map = reg->map_ptr;
2853
2854 /* if map is read-only, track its contents as scalars */
2855 if (tnum_is_const(reg->var_off) &&
2856 bpf_map_is_rdonly(map) &&
2857 map->ops->map_direct_value_addr) {
2858 int map_off = off + reg->var_off.value;
2859 u64 val = 0;
2860
2861 err = bpf_map_direct_read(map, map_off, size,
2862 &val);
2863 if (err)
2864 return err;
2865
2866 regs[value_regno].type = SCALAR_VALUE;
2867 __mark_reg_known(®s[value_regno], val);
2868 } else {
2869 mark_reg_unknown(env, regs, value_regno);
2870 }
2871 }
2872 } else if (reg->type == PTR_TO_CTX) {
2873 enum bpf_reg_type reg_type = SCALAR_VALUE;
2874
2875 if (t == BPF_WRITE && value_regno >= 0 &&
2876 is_pointer_value(env, value_regno)) {
2877 verbose(env, "R%d leaks addr into ctx\n", value_regno);
2878 return -EACCES;
2879 }
2880
2881 err = check_ctx_reg(env, reg, regno);
2882 if (err < 0)
2883 return err;
2884
2885 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
2886 if (!err && t == BPF_READ && value_regno >= 0) {
2887 /* ctx access returns either a scalar, or a
2888 * PTR_TO_PACKET[_META,_END]. In the latter
2889 * case, we know the offset is zero.
2890 */
2891 if (reg_type == SCALAR_VALUE) {
2892 mark_reg_unknown(env, regs, value_regno);
2893 } else {
2894 mark_reg_known_zero(env, regs,
2895 value_regno);
2896 if (reg_type_may_be_null(reg_type))
2897 regs[value_regno].id = ++env->id_gen;
2898 /* A load of ctx field could have different
2899 * actual load size with the one encoded in the
2900 * insn. When the dst is PTR, it is for sure not
2901 * a sub-register.
2902 */
2903 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
2904 }
2905 regs[value_regno].type = reg_type;
2906 }
2907
2908 } else if (reg->type == PTR_TO_STACK) {
2909 off += reg->var_off.value;
2910 err = check_stack_access(env, reg, off, size);
2911 if (err)
2912 return err;
2913
2914 state = func(env, reg);
2915 err = update_stack_depth(env, state, off);
2916 if (err)
2917 return err;
2918
2919 if (t == BPF_WRITE)
2920 err = check_stack_write(env, state, off, size,
2921 value_regno, insn_idx);
2922 else
2923 err = check_stack_read(env, state, off, size,
2924 value_regno);
2925 } else if (reg_is_pkt_pointer(reg)) {
2926 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
2927 verbose(env, "cannot write into packet\n");
2928 return -EACCES;
2929 }
2930 if (t == BPF_WRITE && value_regno >= 0 &&
2931 is_pointer_value(env, value_regno)) {
2932 verbose(env, "R%d leaks addr into packet\n",
2933 value_regno);
2934 return -EACCES;
2935 }
2936 err = check_packet_access(env, regno, off, size, false);
2937 if (!err && t == BPF_READ && value_regno >= 0)
2938 mark_reg_unknown(env, regs, value_regno);
2939 } else if (reg->type == PTR_TO_FLOW_KEYS) {
2940 if (t == BPF_WRITE && value_regno >= 0 &&
2941 is_pointer_value(env, value_regno)) {
2942 verbose(env, "R%d leaks addr into flow keys\n",
2943 value_regno);
2944 return -EACCES;
2945 }
2946
2947 err = check_flow_keys_access(env, off, size);
2948 if (!err && t == BPF_READ && value_regno >= 0)
2949 mark_reg_unknown(env, regs, value_regno);
2950 } else if (type_is_sk_pointer(reg->type)) {
2951 if (t == BPF_WRITE) {
2952 verbose(env, "R%d cannot write into %s\n",
2953 regno, reg_type_str[reg->type]);
2954 return -EACCES;
2955 }
2956 err = check_sock_access(env, insn_idx, regno, off, size, t);
2957 if (!err && value_regno >= 0)
2958 mark_reg_unknown(env, regs, value_regno);
2959 } else if (reg->type == PTR_TO_TP_BUFFER) {
2960 err = check_tp_buffer_access(env, reg, regno, off, size);
2961 if (!err && t == BPF_READ && value_regno >= 0)
2962 mark_reg_unknown(env, regs, value_regno);
2963 } else {
2964 verbose(env, "R%d invalid mem access '%s'\n", regno,
2965 reg_type_str[reg->type]);
2966 return -EACCES;
2967 }
2968
2969 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
2970 regs[value_regno].type == SCALAR_VALUE) {
2971 /* b/h/w load zero-extends, mark upper bits as known 0 */
2972 coerce_reg_to_size(®s[value_regno], size);
2973 }
2974 return err;
2975 }
2976
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)2977 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
2978 {
2979 int err;
2980
2981 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
2982 insn->imm != 0) {
2983 verbose(env, "BPF_XADD uses reserved fields\n");
2984 return -EINVAL;
2985 }
2986
2987 /* check src1 operand */
2988 err = check_reg_arg(env, insn->src_reg, SRC_OP);
2989 if (err)
2990 return err;
2991
2992 /* check src2 operand */
2993 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2994 if (err)
2995 return err;
2996
2997 if (is_pointer_value(env, insn->src_reg)) {
2998 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
2999 return -EACCES;
3000 }
3001
3002 if (is_ctx_reg(env, insn->dst_reg) ||
3003 is_pkt_reg(env, insn->dst_reg) ||
3004 is_flow_key_reg(env, insn->dst_reg) ||
3005 is_sk_reg(env, insn->dst_reg)) {
3006 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
3007 insn->dst_reg,
3008 reg_type_str[reg_state(env, insn->dst_reg)->type]);
3009 return -EACCES;
3010 }
3011
3012 /* check whether atomic_add can read the memory */
3013 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3014 BPF_SIZE(insn->code), BPF_READ, -1, true);
3015 if (err)
3016 return err;
3017
3018 /* check whether atomic_add can write into the same memory */
3019 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3020 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
3021 }
3022
__check_stack_boundary(struct bpf_verifier_env * env,u32 regno,int off,int access_size,bool zero_size_allowed)3023 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno,
3024 int off, int access_size,
3025 bool zero_size_allowed)
3026 {
3027 struct bpf_reg_state *reg = reg_state(env, regno);
3028
3029 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
3030 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
3031 if (tnum_is_const(reg->var_off)) {
3032 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
3033 regno, off, access_size);
3034 } else {
3035 char tn_buf[48];
3036
3037 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3038 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n",
3039 regno, tn_buf, access_size);
3040 }
3041 return -EACCES;
3042 }
3043 return 0;
3044 }
3045
3046 /* when register 'regno' is passed into function that will read 'access_size'
3047 * bytes from that pointer, make sure that it's within stack boundary
3048 * and all elements of stack are initialized.
3049 * Unlike most pointer bounds-checking functions, this one doesn't take an
3050 * 'off' argument, so it has to add in reg->off itself.
3051 */
check_stack_boundary(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)3052 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
3053 int access_size, bool zero_size_allowed,
3054 struct bpf_call_arg_meta *meta)
3055 {
3056 struct bpf_reg_state *reg = reg_state(env, regno);
3057 struct bpf_func_state *state = func(env, reg);
3058 int err, min_off, max_off, i, j, slot, spi;
3059
3060 if (reg->type != PTR_TO_STACK) {
3061 /* Allow zero-byte read from NULL, regardless of pointer type */
3062 if (zero_size_allowed && access_size == 0 &&
3063 register_is_null(reg))
3064 return 0;
3065
3066 verbose(env, "R%d type=%s expected=%s\n", regno,
3067 reg_type_str[reg->type],
3068 reg_type_str[PTR_TO_STACK]);
3069 return -EACCES;
3070 }
3071
3072 if (tnum_is_const(reg->var_off)) {
3073 min_off = max_off = reg->var_off.value + reg->off;
3074 err = __check_stack_boundary(env, regno, min_off, access_size,
3075 zero_size_allowed);
3076 if (err)
3077 return err;
3078 } else {
3079 /* Variable offset is prohibited for unprivileged mode for
3080 * simplicity since it requires corresponding support in
3081 * Spectre masking for stack ALU.
3082 * See also retrieve_ptr_limit().
3083 */
3084 if (!env->allow_ptr_leaks) {
3085 char tn_buf[48];
3086
3087 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3088 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n",
3089 regno, tn_buf);
3090 return -EACCES;
3091 }
3092 /* Only initialized buffer on stack is allowed to be accessed
3093 * with variable offset. With uninitialized buffer it's hard to
3094 * guarantee that whole memory is marked as initialized on
3095 * helper return since specific bounds are unknown what may
3096 * cause uninitialized stack leaking.
3097 */
3098 if (meta && meta->raw_mode)
3099 meta = NULL;
3100
3101 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3102 reg->smax_value <= -BPF_MAX_VAR_OFF) {
3103 verbose(env, "R%d unbounded indirect variable offset stack access\n",
3104 regno);
3105 return -EACCES;
3106 }
3107 min_off = reg->smin_value + reg->off;
3108 max_off = reg->smax_value + reg->off;
3109 err = __check_stack_boundary(env, regno, min_off, access_size,
3110 zero_size_allowed);
3111 if (err) {
3112 verbose(env, "R%d min value is outside of stack bound\n",
3113 regno);
3114 return err;
3115 }
3116 err = __check_stack_boundary(env, regno, max_off, access_size,
3117 zero_size_allowed);
3118 if (err) {
3119 verbose(env, "R%d max value is outside of stack bound\n",
3120 regno);
3121 return err;
3122 }
3123 }
3124
3125 if (meta && meta->raw_mode) {
3126 meta->access_size = access_size;
3127 meta->regno = regno;
3128 return 0;
3129 }
3130
3131 for (i = min_off; i < max_off + access_size; i++) {
3132 u8 *stype;
3133
3134 slot = -i - 1;
3135 spi = slot / BPF_REG_SIZE;
3136 if (state->allocated_stack <= slot)
3137 goto err;
3138 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
3139 if (*stype == STACK_MISC)
3140 goto mark;
3141 if (*stype == STACK_ZERO) {
3142 /* helper can write anything into the stack */
3143 *stype = STACK_MISC;
3144 goto mark;
3145 }
3146 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
3147 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
3148 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
3149 for (j = 0; j < BPF_REG_SIZE; j++)
3150 state->stack[spi].slot_type[j] = STACK_MISC;
3151 goto mark;
3152 }
3153
3154 err:
3155 if (tnum_is_const(reg->var_off)) {
3156 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
3157 min_off, i - min_off, access_size);
3158 } else {
3159 char tn_buf[48];
3160
3161 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3162 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n",
3163 tn_buf, i - min_off, access_size);
3164 }
3165 return -EACCES;
3166 mark:
3167 /* reading any byte out of 8-byte 'spill_slot' will cause
3168 * the whole slot to be marked as 'read'
3169 */
3170 mark_reg_read(env, &state->stack[spi].spilled_ptr,
3171 state->stack[spi].spilled_ptr.parent,
3172 REG_LIVE_READ64);
3173 }
3174 return update_stack_depth(env, state, min_off);
3175 }
3176
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)3177 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
3178 int access_size, bool zero_size_allowed,
3179 struct bpf_call_arg_meta *meta)
3180 {
3181 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3182
3183 switch (reg->type) {
3184 case PTR_TO_PACKET:
3185 case PTR_TO_PACKET_META:
3186 return check_packet_access(env, regno, reg->off, access_size,
3187 zero_size_allowed);
3188 case PTR_TO_MAP_VALUE:
3189 if (check_map_access_type(env, regno, reg->off, access_size,
3190 meta && meta->raw_mode ? BPF_WRITE :
3191 BPF_READ))
3192 return -EACCES;
3193 return check_map_access(env, regno, reg->off, access_size,
3194 zero_size_allowed);
3195 default: /* scalar_value|ptr_to_stack or invalid ptr */
3196 return check_stack_boundary(env, regno, access_size,
3197 zero_size_allowed, meta);
3198 }
3199 }
3200
3201 /* Implementation details:
3202 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
3203 * Two bpf_map_lookups (even with the same key) will have different reg->id.
3204 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
3205 * value_or_null->value transition, since the verifier only cares about
3206 * the range of access to valid map value pointer and doesn't care about actual
3207 * address of the map element.
3208 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
3209 * reg->id > 0 after value_or_null->value transition. By doing so
3210 * two bpf_map_lookups will be considered two different pointers that
3211 * point to different bpf_spin_locks.
3212 * The verifier allows taking only one bpf_spin_lock at a time to avoid
3213 * dead-locks.
3214 * Since only one bpf_spin_lock is allowed the checks are simpler than
3215 * reg_is_refcounted() logic. The verifier needs to remember only
3216 * one spin_lock instead of array of acquired_refs.
3217 * cur_state->active_spin_lock remembers which map value element got locked
3218 * and clears it after bpf_spin_unlock.
3219 */
process_spin_lock(struct bpf_verifier_env * env,int regno,bool is_lock)3220 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
3221 bool is_lock)
3222 {
3223 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3224 struct bpf_verifier_state *cur = env->cur_state;
3225 bool is_const = tnum_is_const(reg->var_off);
3226 struct bpf_map *map = reg->map_ptr;
3227 u64 val = reg->var_off.value;
3228
3229 if (reg->type != PTR_TO_MAP_VALUE) {
3230 verbose(env, "R%d is not a pointer to map_value\n", regno);
3231 return -EINVAL;
3232 }
3233 if (!is_const) {
3234 verbose(env,
3235 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
3236 regno);
3237 return -EINVAL;
3238 }
3239 if (!map->btf) {
3240 verbose(env,
3241 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
3242 map->name);
3243 return -EINVAL;
3244 }
3245 if (!map_value_has_spin_lock(map)) {
3246 if (map->spin_lock_off == -E2BIG)
3247 verbose(env,
3248 "map '%s' has more than one 'struct bpf_spin_lock'\n",
3249 map->name);
3250 else if (map->spin_lock_off == -ENOENT)
3251 verbose(env,
3252 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
3253 map->name);
3254 else
3255 verbose(env,
3256 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
3257 map->name);
3258 return -EINVAL;
3259 }
3260 if (map->spin_lock_off != val + reg->off) {
3261 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
3262 val + reg->off);
3263 return -EINVAL;
3264 }
3265 if (is_lock) {
3266 if (cur->active_spin_lock) {
3267 verbose(env,
3268 "Locking two bpf_spin_locks are not allowed\n");
3269 return -EINVAL;
3270 }
3271 cur->active_spin_lock = reg->id;
3272 } else {
3273 if (!cur->active_spin_lock) {
3274 verbose(env, "bpf_spin_unlock without taking a lock\n");
3275 return -EINVAL;
3276 }
3277 if (cur->active_spin_lock != reg->id) {
3278 verbose(env, "bpf_spin_unlock of different lock\n");
3279 return -EINVAL;
3280 }
3281 cur->active_spin_lock = 0;
3282 }
3283 return 0;
3284 }
3285
arg_type_is_mem_ptr(enum bpf_arg_type type)3286 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
3287 {
3288 return type == ARG_PTR_TO_MEM ||
3289 type == ARG_PTR_TO_MEM_OR_NULL ||
3290 type == ARG_PTR_TO_UNINIT_MEM;
3291 }
3292
arg_type_is_mem_size(enum bpf_arg_type type)3293 static bool arg_type_is_mem_size(enum bpf_arg_type type)
3294 {
3295 return type == ARG_CONST_SIZE ||
3296 type == ARG_CONST_SIZE_OR_ZERO;
3297 }
3298
arg_type_is_int_ptr(enum bpf_arg_type type)3299 static bool arg_type_is_int_ptr(enum bpf_arg_type type)
3300 {
3301 return type == ARG_PTR_TO_INT ||
3302 type == ARG_PTR_TO_LONG;
3303 }
3304
int_ptr_type_to_size(enum bpf_arg_type type)3305 static int int_ptr_type_to_size(enum bpf_arg_type type)
3306 {
3307 if (type == ARG_PTR_TO_INT)
3308 return sizeof(u32);
3309 else if (type == ARG_PTR_TO_LONG)
3310 return sizeof(u64);
3311
3312 return -EINVAL;
3313 }
3314
check_func_arg(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,struct bpf_call_arg_meta * meta)3315 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
3316 enum bpf_arg_type arg_type,
3317 struct bpf_call_arg_meta *meta)
3318 {
3319 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
3320 enum bpf_reg_type expected_type, type = reg->type;
3321 int err = 0;
3322
3323 if (arg_type == ARG_DONTCARE)
3324 return 0;
3325
3326 err = check_reg_arg(env, regno, SRC_OP);
3327 if (err)
3328 return err;
3329
3330 if (arg_type == ARG_ANYTHING) {
3331 if (is_pointer_value(env, regno)) {
3332 verbose(env, "R%d leaks addr into helper function\n",
3333 regno);
3334 return -EACCES;
3335 }
3336 return 0;
3337 }
3338
3339 if (type_is_pkt_pointer(type) &&
3340 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
3341 verbose(env, "helper access to the packet is not allowed\n");
3342 return -EACCES;
3343 }
3344
3345 if (arg_type == ARG_PTR_TO_MAP_KEY ||
3346 arg_type == ARG_PTR_TO_MAP_VALUE ||
3347 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
3348 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
3349 expected_type = PTR_TO_STACK;
3350 if (register_is_null(reg) &&
3351 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL)
3352 /* final test in check_stack_boundary() */;
3353 else if (!type_is_pkt_pointer(type) &&
3354 type != PTR_TO_MAP_VALUE &&
3355 type != expected_type)
3356 goto err_type;
3357 } else if (arg_type == ARG_CONST_SIZE ||
3358 arg_type == ARG_CONST_SIZE_OR_ZERO) {
3359 expected_type = SCALAR_VALUE;
3360 if (type != expected_type)
3361 goto err_type;
3362 } else if (arg_type == ARG_CONST_MAP_PTR) {
3363 expected_type = CONST_PTR_TO_MAP;
3364 if (type != expected_type)
3365 goto err_type;
3366 } else if (arg_type == ARG_PTR_TO_CTX) {
3367 expected_type = PTR_TO_CTX;
3368 if (type != expected_type)
3369 goto err_type;
3370 err = check_ctx_reg(env, reg, regno);
3371 if (err < 0)
3372 return err;
3373 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) {
3374 expected_type = PTR_TO_SOCK_COMMON;
3375 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */
3376 if (!type_is_sk_pointer(type))
3377 goto err_type;
3378 if (reg->ref_obj_id) {
3379 if (meta->ref_obj_id) {
3380 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
3381 regno, reg->ref_obj_id,
3382 meta->ref_obj_id);
3383 return -EFAULT;
3384 }
3385 meta->ref_obj_id = reg->ref_obj_id;
3386 }
3387 } else if (arg_type == ARG_PTR_TO_SOCKET) {
3388 expected_type = PTR_TO_SOCKET;
3389 if (type != expected_type)
3390 goto err_type;
3391 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
3392 if (meta->func_id == BPF_FUNC_spin_lock) {
3393 if (process_spin_lock(env, regno, true))
3394 return -EACCES;
3395 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
3396 if (process_spin_lock(env, regno, false))
3397 return -EACCES;
3398 } else {
3399 verbose(env, "verifier internal error\n");
3400 return -EFAULT;
3401 }
3402 } else if (arg_type_is_mem_ptr(arg_type)) {
3403 expected_type = PTR_TO_STACK;
3404 /* One exception here. In case function allows for NULL to be
3405 * passed in as argument, it's a SCALAR_VALUE type. Final test
3406 * happens during stack boundary checking.
3407 */
3408 if (register_is_null(reg) &&
3409 arg_type == ARG_PTR_TO_MEM_OR_NULL)
3410 /* final test in check_stack_boundary() */;
3411 else if (!type_is_pkt_pointer(type) &&
3412 type != PTR_TO_MAP_VALUE &&
3413 type != expected_type)
3414 goto err_type;
3415 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
3416 } else if (arg_type_is_int_ptr(arg_type)) {
3417 expected_type = PTR_TO_STACK;
3418 if (!type_is_pkt_pointer(type) &&
3419 type != PTR_TO_MAP_VALUE &&
3420 type != expected_type)
3421 goto err_type;
3422 } else {
3423 verbose(env, "unsupported arg_type %d\n", arg_type);
3424 return -EFAULT;
3425 }
3426
3427 if (arg_type == ARG_CONST_MAP_PTR) {
3428 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
3429 meta->map_ptr = reg->map_ptr;
3430 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
3431 /* bpf_map_xxx(..., map_ptr, ..., key) call:
3432 * check that [key, key + map->key_size) are within
3433 * stack limits and initialized
3434 */
3435 if (!meta->map_ptr) {
3436 /* in function declaration map_ptr must come before
3437 * map_key, so that it's verified and known before
3438 * we have to check map_key here. Otherwise it means
3439 * that kernel subsystem misconfigured verifier
3440 */
3441 verbose(env, "invalid map_ptr to access map->key\n");
3442 return -EACCES;
3443 }
3444 err = check_helper_mem_access(env, regno,
3445 meta->map_ptr->key_size, false,
3446 NULL);
3447 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
3448 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
3449 !register_is_null(reg)) ||
3450 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
3451 /* bpf_map_xxx(..., map_ptr, ..., value) call:
3452 * check [value, value + map->value_size) validity
3453 */
3454 if (!meta->map_ptr) {
3455 /* kernel subsystem misconfigured verifier */
3456 verbose(env, "invalid map_ptr to access map->value\n");
3457 return -EACCES;
3458 }
3459 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
3460 err = check_helper_mem_access(env, regno,
3461 meta->map_ptr->value_size, false,
3462 meta);
3463 } else if (arg_type_is_mem_size(arg_type)) {
3464 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
3465
3466 /* remember the mem_size which may be used later
3467 * to refine return values.
3468 */
3469 meta->msize_max_value = reg->umax_value;
3470
3471 /* The register is SCALAR_VALUE; the access check
3472 * happens using its boundaries.
3473 */
3474 if (!tnum_is_const(reg->var_off))
3475 /* For unprivileged variable accesses, disable raw
3476 * mode so that the program is required to
3477 * initialize all the memory that the helper could
3478 * just partially fill up.
3479 */
3480 meta = NULL;
3481
3482 if (reg->smin_value < 0) {
3483 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
3484 regno);
3485 return -EACCES;
3486 }
3487
3488 if (reg->umin_value == 0) {
3489 err = check_helper_mem_access(env, regno - 1, 0,
3490 zero_size_allowed,
3491 meta);
3492 if (err)
3493 return err;
3494 }
3495
3496 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
3497 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
3498 regno);
3499 return -EACCES;
3500 }
3501 err = check_helper_mem_access(env, regno - 1,
3502 reg->umax_value,
3503 zero_size_allowed, meta);
3504 if (!err)
3505 err = mark_chain_precision(env, regno);
3506 } else if (arg_type_is_int_ptr(arg_type)) {
3507 int size = int_ptr_type_to_size(arg_type);
3508
3509 err = check_helper_mem_access(env, regno, size, false, meta);
3510 if (err)
3511 return err;
3512 err = check_ptr_alignment(env, reg, 0, size, true);
3513 }
3514
3515 return err;
3516 err_type:
3517 verbose(env, "R%d type=%s expected=%s\n", regno,
3518 reg_type_str[type], reg_type_str[expected_type]);
3519 return -EACCES;
3520 }
3521
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)3522 static int check_map_func_compatibility(struct bpf_verifier_env *env,
3523 struct bpf_map *map, int func_id)
3524 {
3525 if (!map)
3526 return 0;
3527
3528 /* We need a two way check, first is from map perspective ... */
3529 switch (map->map_type) {
3530 case BPF_MAP_TYPE_PROG_ARRAY:
3531 if (func_id != BPF_FUNC_tail_call)
3532 goto error;
3533 break;
3534 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
3535 if (func_id != BPF_FUNC_perf_event_read &&
3536 func_id != BPF_FUNC_perf_event_output &&
3537 func_id != BPF_FUNC_perf_event_read_value)
3538 goto error;
3539 break;
3540 case BPF_MAP_TYPE_STACK_TRACE:
3541 if (func_id != BPF_FUNC_get_stackid)
3542 goto error;
3543 break;
3544 case BPF_MAP_TYPE_CGROUP_ARRAY:
3545 if (func_id != BPF_FUNC_skb_under_cgroup &&
3546 func_id != BPF_FUNC_current_task_under_cgroup)
3547 goto error;
3548 break;
3549 case BPF_MAP_TYPE_CGROUP_STORAGE:
3550 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
3551 if (func_id != BPF_FUNC_get_local_storage)
3552 goto error;
3553 break;
3554 case BPF_MAP_TYPE_DEVMAP:
3555 case BPF_MAP_TYPE_DEVMAP_HASH:
3556 if (func_id != BPF_FUNC_redirect_map &&
3557 func_id != BPF_FUNC_map_lookup_elem)
3558 goto error;
3559 break;
3560 /* Restrict bpf side of cpumap and xskmap, open when use-cases
3561 * appear.
3562 */
3563 case BPF_MAP_TYPE_CPUMAP:
3564 if (func_id != BPF_FUNC_redirect_map)
3565 goto error;
3566 break;
3567 case BPF_MAP_TYPE_XSKMAP:
3568 if (func_id != BPF_FUNC_redirect_map &&
3569 func_id != BPF_FUNC_map_lookup_elem)
3570 goto error;
3571 break;
3572 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
3573 case BPF_MAP_TYPE_HASH_OF_MAPS:
3574 if (func_id != BPF_FUNC_map_lookup_elem)
3575 goto error;
3576 break;
3577 case BPF_MAP_TYPE_SOCKMAP:
3578 if (func_id != BPF_FUNC_sk_redirect_map &&
3579 func_id != BPF_FUNC_sock_map_update &&
3580 func_id != BPF_FUNC_map_delete_elem &&
3581 func_id != BPF_FUNC_msg_redirect_map)
3582 goto error;
3583 break;
3584 case BPF_MAP_TYPE_SOCKHASH:
3585 if (func_id != BPF_FUNC_sk_redirect_hash &&
3586 func_id != BPF_FUNC_sock_hash_update &&
3587 func_id != BPF_FUNC_map_delete_elem &&
3588 func_id != BPF_FUNC_msg_redirect_hash)
3589 goto error;
3590 break;
3591 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
3592 if (func_id != BPF_FUNC_sk_select_reuseport)
3593 goto error;
3594 break;
3595 case BPF_MAP_TYPE_QUEUE:
3596 case BPF_MAP_TYPE_STACK:
3597 if (func_id != BPF_FUNC_map_peek_elem &&
3598 func_id != BPF_FUNC_map_pop_elem &&
3599 func_id != BPF_FUNC_map_push_elem)
3600 goto error;
3601 break;
3602 case BPF_MAP_TYPE_SK_STORAGE:
3603 if (func_id != BPF_FUNC_sk_storage_get &&
3604 func_id != BPF_FUNC_sk_storage_delete)
3605 goto error;
3606 break;
3607 default:
3608 break;
3609 }
3610
3611 /* ... and second from the function itself. */
3612 switch (func_id) {
3613 case BPF_FUNC_tail_call:
3614 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
3615 goto error;
3616 if (env->subprog_cnt > 1) {
3617 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
3618 return -EINVAL;
3619 }
3620 break;
3621 case BPF_FUNC_perf_event_read:
3622 case BPF_FUNC_perf_event_output:
3623 case BPF_FUNC_perf_event_read_value:
3624 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
3625 goto error;
3626 break;
3627 case BPF_FUNC_get_stackid:
3628 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
3629 goto error;
3630 break;
3631 case BPF_FUNC_current_task_under_cgroup:
3632 case BPF_FUNC_skb_under_cgroup:
3633 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
3634 goto error;
3635 break;
3636 case BPF_FUNC_redirect_map:
3637 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
3638 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
3639 map->map_type != BPF_MAP_TYPE_CPUMAP &&
3640 map->map_type != BPF_MAP_TYPE_XSKMAP)
3641 goto error;
3642 break;
3643 case BPF_FUNC_sk_redirect_map:
3644 case BPF_FUNC_msg_redirect_map:
3645 case BPF_FUNC_sock_map_update:
3646 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
3647 goto error;
3648 break;
3649 case BPF_FUNC_sk_redirect_hash:
3650 case BPF_FUNC_msg_redirect_hash:
3651 case BPF_FUNC_sock_hash_update:
3652 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
3653 goto error;
3654 break;
3655 case BPF_FUNC_get_local_storage:
3656 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
3657 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
3658 goto error;
3659 break;
3660 case BPF_FUNC_sk_select_reuseport:
3661 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
3662 goto error;
3663 break;
3664 case BPF_FUNC_map_peek_elem:
3665 case BPF_FUNC_map_pop_elem:
3666 case BPF_FUNC_map_push_elem:
3667 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
3668 map->map_type != BPF_MAP_TYPE_STACK)
3669 goto error;
3670 break;
3671 case BPF_FUNC_sk_storage_get:
3672 case BPF_FUNC_sk_storage_delete:
3673 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
3674 goto error;
3675 break;
3676 default:
3677 break;
3678 }
3679
3680 return 0;
3681 error:
3682 verbose(env, "cannot pass map_type %d into func %s#%d\n",
3683 map->map_type, func_id_name(func_id), func_id);
3684 return -EINVAL;
3685 }
3686
check_raw_mode_ok(const struct bpf_func_proto * fn)3687 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
3688 {
3689 int count = 0;
3690
3691 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
3692 count++;
3693 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
3694 count++;
3695 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
3696 count++;
3697 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
3698 count++;
3699 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
3700 count++;
3701
3702 /* We only support one arg being in raw mode at the moment,
3703 * which is sufficient for the helper functions we have
3704 * right now.
3705 */
3706 return count <= 1;
3707 }
3708
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)3709 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
3710 enum bpf_arg_type arg_next)
3711 {
3712 return (arg_type_is_mem_ptr(arg_curr) &&
3713 !arg_type_is_mem_size(arg_next)) ||
3714 (!arg_type_is_mem_ptr(arg_curr) &&
3715 arg_type_is_mem_size(arg_next));
3716 }
3717
check_arg_pair_ok(const struct bpf_func_proto * fn)3718 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
3719 {
3720 /* bpf_xxx(..., buf, len) call will access 'len'
3721 * bytes from memory 'buf'. Both arg types need
3722 * to be paired, so make sure there's no buggy
3723 * helper function specification.
3724 */
3725 if (arg_type_is_mem_size(fn->arg1_type) ||
3726 arg_type_is_mem_ptr(fn->arg5_type) ||
3727 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
3728 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
3729 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
3730 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
3731 return false;
3732
3733 return true;
3734 }
3735
check_refcount_ok(const struct bpf_func_proto * fn,int func_id)3736 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
3737 {
3738 int count = 0;
3739
3740 if (arg_type_may_be_refcounted(fn->arg1_type))
3741 count++;
3742 if (arg_type_may_be_refcounted(fn->arg2_type))
3743 count++;
3744 if (arg_type_may_be_refcounted(fn->arg3_type))
3745 count++;
3746 if (arg_type_may_be_refcounted(fn->arg4_type))
3747 count++;
3748 if (arg_type_may_be_refcounted(fn->arg5_type))
3749 count++;
3750
3751 /* A reference acquiring function cannot acquire
3752 * another refcounted ptr.
3753 */
3754 if (is_acquire_function(func_id) && count)
3755 return false;
3756
3757 /* We only support one arg being unreferenced at the moment,
3758 * which is sufficient for the helper functions we have right now.
3759 */
3760 return count <= 1;
3761 }
3762
check_func_proto(const struct bpf_func_proto * fn,int func_id)3763 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
3764 {
3765 return check_raw_mode_ok(fn) &&
3766 check_arg_pair_ok(fn) &&
3767 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
3768 }
3769
3770 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
3771 * are now invalid, so turn them into unknown SCALAR_VALUE.
3772 */
__clear_all_pkt_pointers(struct bpf_verifier_env * env,struct bpf_func_state * state)3773 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
3774 struct bpf_func_state *state)
3775 {
3776 struct bpf_reg_state *regs = state->regs, *reg;
3777 int i;
3778
3779 for (i = 0; i < MAX_BPF_REG; i++)
3780 if (reg_is_pkt_pointer_any(®s[i]))
3781 mark_reg_unknown(env, regs, i);
3782
3783 bpf_for_each_spilled_reg(i, state, reg) {
3784 if (!reg)
3785 continue;
3786 if (reg_is_pkt_pointer_any(reg))
3787 __mark_reg_unknown(env, reg);
3788 }
3789 }
3790
clear_all_pkt_pointers(struct bpf_verifier_env * env)3791 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
3792 {
3793 struct bpf_verifier_state *vstate = env->cur_state;
3794 int i;
3795
3796 for (i = 0; i <= vstate->curframe; i++)
3797 __clear_all_pkt_pointers(env, vstate->frame[i]);
3798 }
3799
release_reg_references(struct bpf_verifier_env * env,struct bpf_func_state * state,int ref_obj_id)3800 static void release_reg_references(struct bpf_verifier_env *env,
3801 struct bpf_func_state *state,
3802 int ref_obj_id)
3803 {
3804 struct bpf_reg_state *regs = state->regs, *reg;
3805 int i;
3806
3807 for (i = 0; i < MAX_BPF_REG; i++)
3808 if (regs[i].ref_obj_id == ref_obj_id)
3809 mark_reg_unknown(env, regs, i);
3810
3811 bpf_for_each_spilled_reg(i, state, reg) {
3812 if (!reg)
3813 continue;
3814 if (reg->ref_obj_id == ref_obj_id)
3815 __mark_reg_unknown(env, reg);
3816 }
3817 }
3818
3819 /* The pointer with the specified id has released its reference to kernel
3820 * resources. Identify all copies of the same pointer and clear the reference.
3821 */
release_reference(struct bpf_verifier_env * env,int ref_obj_id)3822 static int release_reference(struct bpf_verifier_env *env,
3823 int ref_obj_id)
3824 {
3825 struct bpf_verifier_state *vstate = env->cur_state;
3826 int err;
3827 int i;
3828
3829 err = release_reference_state(cur_func(env), ref_obj_id);
3830 if (err)
3831 return err;
3832
3833 for (i = 0; i <= vstate->curframe; i++)
3834 release_reg_references(env, vstate->frame[i], ref_obj_id);
3835
3836 return 0;
3837 }
3838
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)3839 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
3840 int *insn_idx)
3841 {
3842 struct bpf_verifier_state *state = env->cur_state;
3843 struct bpf_func_state *caller, *callee;
3844 int i, err, subprog, target_insn;
3845
3846 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
3847 verbose(env, "the call stack of %d frames is too deep\n",
3848 state->curframe + 2);
3849 return -E2BIG;
3850 }
3851
3852 target_insn = *insn_idx + insn->imm;
3853 subprog = find_subprog(env, target_insn + 1);
3854 if (subprog < 0) {
3855 verbose(env, "verifier bug. No program starts at insn %d\n",
3856 target_insn + 1);
3857 return -EFAULT;
3858 }
3859
3860 caller = state->frame[state->curframe];
3861 if (state->frame[state->curframe + 1]) {
3862 verbose(env, "verifier bug. Frame %d already allocated\n",
3863 state->curframe + 1);
3864 return -EFAULT;
3865 }
3866
3867 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
3868 if (!callee)
3869 return -ENOMEM;
3870 state->frame[state->curframe + 1] = callee;
3871
3872 /* callee cannot access r0, r6 - r9 for reading and has to write
3873 * into its own stack before reading from it.
3874 * callee can read/write into caller's stack
3875 */
3876 init_func_state(env, callee,
3877 /* remember the callsite, it will be used by bpf_exit */
3878 *insn_idx /* callsite */,
3879 state->curframe + 1 /* frameno within this callchain */,
3880 subprog /* subprog number within this prog */);
3881
3882 /* Transfer references to the callee */
3883 err = transfer_reference_state(callee, caller);
3884 if (err)
3885 return err;
3886
3887 /* copy r1 - r5 args that callee can access. The copy includes parent
3888 * pointers, which connects us up to the liveness chain
3889 */
3890 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3891 callee->regs[i] = caller->regs[i];
3892
3893 /* after the call registers r0 - r5 were scratched */
3894 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3895 mark_reg_not_init(env, caller->regs, caller_saved[i]);
3896 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3897 }
3898
3899 /* only increment it after check_reg_arg() finished */
3900 state->curframe++;
3901
3902 /* and go analyze first insn of the callee */
3903 *insn_idx = target_insn;
3904
3905 if (env->log.level & BPF_LOG_LEVEL) {
3906 verbose(env, "caller:\n");
3907 print_verifier_state(env, caller);
3908 verbose(env, "callee:\n");
3909 print_verifier_state(env, callee);
3910 }
3911 return 0;
3912 }
3913
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)3914 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
3915 {
3916 struct bpf_verifier_state *state = env->cur_state;
3917 struct bpf_func_state *caller, *callee;
3918 struct bpf_reg_state *r0;
3919 int err;
3920
3921 callee = state->frame[state->curframe];
3922 r0 = &callee->regs[BPF_REG_0];
3923 if (r0->type == PTR_TO_STACK) {
3924 /* technically it's ok to return caller's stack pointer
3925 * (or caller's caller's pointer) back to the caller,
3926 * since these pointers are valid. Only current stack
3927 * pointer will be invalid as soon as function exits,
3928 * but let's be conservative
3929 */
3930 verbose(env, "cannot return stack pointer to the caller\n");
3931 return -EINVAL;
3932 }
3933
3934 state->curframe--;
3935 caller = state->frame[state->curframe];
3936 /* return to the caller whatever r0 had in the callee */
3937 caller->regs[BPF_REG_0] = *r0;
3938
3939 /* Transfer references to the caller */
3940 err = transfer_reference_state(caller, callee);
3941 if (err)
3942 return err;
3943
3944 *insn_idx = callee->callsite + 1;
3945 if (env->log.level & BPF_LOG_LEVEL) {
3946 verbose(env, "returning from callee:\n");
3947 print_verifier_state(env, callee);
3948 verbose(env, "to caller at %d:\n", *insn_idx);
3949 print_verifier_state(env, caller);
3950 }
3951 /* clear everything in the callee */
3952 free_func_state(callee);
3953 state->frame[state->curframe + 1] = NULL;
3954 return 0;
3955 }
3956
do_refine_retval_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)3957 static int do_refine_retval_range(struct bpf_verifier_env *env,
3958 struct bpf_reg_state *regs, int ret_type,
3959 int func_id, struct bpf_call_arg_meta *meta)
3960 {
3961 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
3962 struct bpf_reg_state tmp_reg = *ret_reg;
3963 bool ret;
3964
3965 if (ret_type != RET_INTEGER ||
3966 (func_id != BPF_FUNC_get_stack &&
3967 func_id != BPF_FUNC_probe_read_str))
3968 return 0;
3969
3970 /* Error case where ret is in interval [S32MIN, -1]. */
3971 ret_reg->smin_value = S32_MIN;
3972 ret_reg->smax_value = -1;
3973
3974 __reg_deduce_bounds(ret_reg);
3975 __reg_bound_offset(ret_reg);
3976 __update_reg_bounds(ret_reg);
3977
3978 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
3979 if (!ret)
3980 return -EFAULT;
3981
3982 *ret_reg = tmp_reg;
3983
3984 /* Success case where ret is in range [0, msize_max_value]. */
3985 ret_reg->smin_value = 0;
3986 ret_reg->smax_value = meta->msize_max_value;
3987 ret_reg->umin_value = ret_reg->smin_value;
3988 ret_reg->umax_value = ret_reg->smax_value;
3989
3990 __reg_deduce_bounds(ret_reg);
3991 __reg_bound_offset(ret_reg);
3992 __update_reg_bounds(ret_reg);
3993
3994 return 0;
3995 }
3996
3997 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)3998 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
3999 int func_id, int insn_idx)
4000 {
4001 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
4002 struct bpf_map *map = meta->map_ptr;
4003
4004 if (func_id != BPF_FUNC_tail_call &&
4005 func_id != BPF_FUNC_map_lookup_elem &&
4006 func_id != BPF_FUNC_map_update_elem &&
4007 func_id != BPF_FUNC_map_delete_elem &&
4008 func_id != BPF_FUNC_map_push_elem &&
4009 func_id != BPF_FUNC_map_pop_elem &&
4010 func_id != BPF_FUNC_map_peek_elem)
4011 return 0;
4012
4013 if (map == NULL) {
4014 verbose(env, "kernel subsystem misconfigured verifier\n");
4015 return -EINVAL;
4016 }
4017
4018 /* In case of read-only, some additional restrictions
4019 * need to be applied in order to prevent altering the
4020 * state of the map from program side.
4021 */
4022 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
4023 (func_id == BPF_FUNC_map_delete_elem ||
4024 func_id == BPF_FUNC_map_update_elem ||
4025 func_id == BPF_FUNC_map_push_elem ||
4026 func_id == BPF_FUNC_map_pop_elem)) {
4027 verbose(env, "write into map forbidden\n");
4028 return -EACCES;
4029 }
4030
4031 if (!BPF_MAP_PTR(aux->map_state))
4032 bpf_map_ptr_store(aux, meta->map_ptr,
4033 meta->map_ptr->unpriv_array);
4034 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
4035 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
4036 meta->map_ptr->unpriv_array);
4037 return 0;
4038 }
4039
check_reference_leak(struct bpf_verifier_env * env)4040 static int check_reference_leak(struct bpf_verifier_env *env)
4041 {
4042 struct bpf_func_state *state = cur_func(env);
4043 int i;
4044
4045 for (i = 0; i < state->acquired_refs; i++) {
4046 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
4047 state->refs[i].id, state->refs[i].insn_idx);
4048 }
4049 return state->acquired_refs ? -EINVAL : 0;
4050 }
4051
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)4052 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
4053 {
4054 const struct bpf_func_proto *fn = NULL;
4055 struct bpf_reg_state *regs;
4056 struct bpf_call_arg_meta meta;
4057 bool changes_data;
4058 int i, err;
4059
4060 /* find function prototype */
4061 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
4062 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
4063 func_id);
4064 return -EINVAL;
4065 }
4066
4067 if (env->ops->get_func_proto)
4068 fn = env->ops->get_func_proto(func_id, env->prog);
4069 if (!fn) {
4070 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
4071 func_id);
4072 return -EINVAL;
4073 }
4074
4075 /* eBPF programs must be GPL compatible to use GPL-ed functions */
4076 if (!env->prog->gpl_compatible && fn->gpl_only) {
4077 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
4078 return -EINVAL;
4079 }
4080
4081 /* With LD_ABS/IND some JITs save/restore skb from r1. */
4082 changes_data = bpf_helper_changes_pkt_data(fn->func);
4083 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
4084 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
4085 func_id_name(func_id), func_id);
4086 return -EINVAL;
4087 }
4088
4089 memset(&meta, 0, sizeof(meta));
4090 meta.pkt_access = fn->pkt_access;
4091
4092 err = check_func_proto(fn, func_id);
4093 if (err) {
4094 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
4095 func_id_name(func_id), func_id);
4096 return err;
4097 }
4098
4099 meta.func_id = func_id;
4100 /* check args */
4101 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
4102 if (err)
4103 return err;
4104 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
4105 if (err)
4106 return err;
4107 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
4108 if (err)
4109 return err;
4110 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
4111 if (err)
4112 return err;
4113 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
4114 if (err)
4115 return err;
4116
4117 err = record_func_map(env, &meta, func_id, insn_idx);
4118 if (err)
4119 return err;
4120
4121 /* Mark slots with STACK_MISC in case of raw mode, stack offset
4122 * is inferred from register state.
4123 */
4124 for (i = 0; i < meta.access_size; i++) {
4125 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
4126 BPF_WRITE, -1, false);
4127 if (err)
4128 return err;
4129 }
4130
4131 if (func_id == BPF_FUNC_tail_call) {
4132 err = check_reference_leak(env);
4133 if (err) {
4134 verbose(env, "tail_call would lead to reference leak\n");
4135 return err;
4136 }
4137 } else if (is_release_function(func_id)) {
4138 err = release_reference(env, meta.ref_obj_id);
4139 if (err) {
4140 verbose(env, "func %s#%d reference has not been acquired before\n",
4141 func_id_name(func_id), func_id);
4142 return err;
4143 }
4144 }
4145
4146 regs = cur_regs(env);
4147
4148 /* check that flags argument in get_local_storage(map, flags) is 0,
4149 * this is required because get_local_storage() can't return an error.
4150 */
4151 if (func_id == BPF_FUNC_get_local_storage &&
4152 !register_is_null(®s[BPF_REG_2])) {
4153 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
4154 return -EINVAL;
4155 }
4156
4157 /* reset caller saved regs */
4158 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4159 mark_reg_not_init(env, regs, caller_saved[i]);
4160 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4161 }
4162
4163 /* helper call returns 64-bit value. */
4164 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
4165
4166 /* update return register (already marked as written above) */
4167 if (fn->ret_type == RET_INTEGER) {
4168 /* sets type to SCALAR_VALUE */
4169 mark_reg_unknown(env, regs, BPF_REG_0);
4170 } else if (fn->ret_type == RET_VOID) {
4171 regs[BPF_REG_0].type = NOT_INIT;
4172 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
4173 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4174 /* There is no offset yet applied, variable or fixed */
4175 mark_reg_known_zero(env, regs, BPF_REG_0);
4176 /* remember map_ptr, so that check_map_access()
4177 * can check 'value_size' boundary of memory access
4178 * to map element returned from bpf_map_lookup_elem()
4179 */
4180 if (meta.map_ptr == NULL) {
4181 verbose(env,
4182 "kernel subsystem misconfigured verifier\n");
4183 return -EINVAL;
4184 }
4185 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4186 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
4187 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
4188 if (map_value_has_spin_lock(meta.map_ptr))
4189 regs[BPF_REG_0].id = ++env->id_gen;
4190 } else {
4191 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4192 regs[BPF_REG_0].id = ++env->id_gen;
4193 }
4194 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
4195 mark_reg_known_zero(env, regs, BPF_REG_0);
4196 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
4197 regs[BPF_REG_0].id = ++env->id_gen;
4198 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
4199 mark_reg_known_zero(env, regs, BPF_REG_0);
4200 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
4201 regs[BPF_REG_0].id = ++env->id_gen;
4202 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
4203 mark_reg_known_zero(env, regs, BPF_REG_0);
4204 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
4205 regs[BPF_REG_0].id = ++env->id_gen;
4206 } else {
4207 verbose(env, "unknown return type %d of func %s#%d\n",
4208 fn->ret_type, func_id_name(func_id), func_id);
4209 return -EINVAL;
4210 }
4211
4212 if (is_ptr_cast_function(func_id)) {
4213 /* For release_reference() */
4214 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
4215 } else if (is_acquire_function(func_id)) {
4216 int id = acquire_reference_state(env, insn_idx);
4217
4218 if (id < 0)
4219 return id;
4220 /* For mark_ptr_or_null_reg() */
4221 regs[BPF_REG_0].id = id;
4222 /* For release_reference() */
4223 regs[BPF_REG_0].ref_obj_id = id;
4224 }
4225
4226 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
4227 if (err)
4228 return err;
4229
4230 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
4231 if (err)
4232 return err;
4233
4234 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
4235 const char *err_str;
4236
4237 #ifdef CONFIG_PERF_EVENTS
4238 err = get_callchain_buffers(sysctl_perf_event_max_stack);
4239 err_str = "cannot get callchain buffer for func %s#%d\n";
4240 #else
4241 err = -ENOTSUPP;
4242 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
4243 #endif
4244 if (err) {
4245 verbose(env, err_str, func_id_name(func_id), func_id);
4246 return err;
4247 }
4248
4249 env->prog->has_callchain_buf = true;
4250 }
4251
4252 if (changes_data)
4253 clear_all_pkt_pointers(env);
4254 return 0;
4255 }
4256
signed_add_overflows(s64 a,s64 b)4257 static bool signed_add_overflows(s64 a, s64 b)
4258 {
4259 /* Do the add in u64, where overflow is well-defined */
4260 s64 res = (s64)((u64)a + (u64)b);
4261
4262 if (b < 0)
4263 return res > a;
4264 return res < a;
4265 }
4266
signed_sub_overflows(s64 a,s64 b)4267 static bool signed_sub_overflows(s64 a, s64 b)
4268 {
4269 /* Do the sub in u64, where overflow is well-defined */
4270 s64 res = (s64)((u64)a - (u64)b);
4271
4272 if (b < 0)
4273 return res < a;
4274 return res > a;
4275 }
4276
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)4277 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
4278 const struct bpf_reg_state *reg,
4279 enum bpf_reg_type type)
4280 {
4281 bool known = tnum_is_const(reg->var_off);
4282 s64 val = reg->var_off.value;
4283 s64 smin = reg->smin_value;
4284
4285 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
4286 verbose(env, "math between %s pointer and %lld is not allowed\n",
4287 reg_type_str[type], val);
4288 return false;
4289 }
4290
4291 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
4292 verbose(env, "%s pointer offset %d is not allowed\n",
4293 reg_type_str[type], reg->off);
4294 return false;
4295 }
4296
4297 if (smin == S64_MIN) {
4298 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
4299 reg_type_str[type]);
4300 return false;
4301 }
4302
4303 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
4304 verbose(env, "value %lld makes %s pointer be out of bounds\n",
4305 smin, reg_type_str[type]);
4306 return false;
4307 }
4308
4309 return true;
4310 }
4311
cur_aux(struct bpf_verifier_env * env)4312 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
4313 {
4314 return &env->insn_aux_data[env->insn_idx];
4315 }
4316
4317 enum {
4318 REASON_BOUNDS = -1,
4319 REASON_TYPE = -2,
4320 REASON_PATHS = -3,
4321 REASON_LIMIT = -4,
4322 REASON_STACK = -5,
4323 };
4324
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)4325 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
4326 u32 *alu_limit, bool mask_to_left)
4327 {
4328 u32 max = 0, ptr_limit = 0;
4329
4330 switch (ptr_reg->type) {
4331 case PTR_TO_STACK:
4332 /* Offset 0 is out-of-bounds, but acceptable start for the
4333 * left direction, see BPF_REG_FP. Also, unknown scalar
4334 * offset where we would need to deal with min/max bounds is
4335 * currently prohibited for unprivileged.
4336 */
4337 max = MAX_BPF_STACK + mask_to_left;
4338 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
4339 break;
4340 case PTR_TO_MAP_VALUE:
4341 max = ptr_reg->map_ptr->value_size;
4342 ptr_limit = (mask_to_left ?
4343 ptr_reg->smin_value :
4344 ptr_reg->umax_value) + ptr_reg->off;
4345 break;
4346 default:
4347 return REASON_TYPE;
4348 }
4349
4350 if (ptr_limit >= max)
4351 return REASON_LIMIT;
4352 *alu_limit = ptr_limit;
4353 return 0;
4354 }
4355
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)4356 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
4357 const struct bpf_insn *insn)
4358 {
4359 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
4360 }
4361
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)4362 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
4363 u32 alu_state, u32 alu_limit)
4364 {
4365 /* If we arrived here from different branches with different
4366 * state or limits to sanitize, then this won't work.
4367 */
4368 if (aux->alu_state &&
4369 (aux->alu_state != alu_state ||
4370 aux->alu_limit != alu_limit))
4371 return REASON_PATHS;
4372
4373 /* Corresponding fixup done in fixup_bpf_calls(). */
4374 aux->alu_state = alu_state;
4375 aux->alu_limit = alu_limit;
4376 return 0;
4377 }
4378
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)4379 static int sanitize_val_alu(struct bpf_verifier_env *env,
4380 struct bpf_insn *insn)
4381 {
4382 struct bpf_insn_aux_data *aux = cur_aux(env);
4383
4384 if (can_skip_alu_sanitation(env, insn))
4385 return 0;
4386
4387 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
4388 }
4389
sanitize_needed(u8 opcode)4390 static bool sanitize_needed(u8 opcode)
4391 {
4392 return opcode == BPF_ADD || opcode == BPF_SUB;
4393 }
4394
4395 struct bpf_sanitize_info {
4396 struct bpf_insn_aux_data aux;
4397 bool mask_to_left;
4398 };
4399
4400 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)4401 sanitize_speculative_path(struct bpf_verifier_env *env,
4402 const struct bpf_insn *insn,
4403 u32 next_idx, u32 curr_idx)
4404 {
4405 struct bpf_verifier_state *branch;
4406 struct bpf_reg_state *regs;
4407
4408 branch = push_stack(env, next_idx, curr_idx, true);
4409 if (branch && insn) {
4410 regs = branch->frame[branch->curframe]->regs;
4411 if (BPF_SRC(insn->code) == BPF_K) {
4412 mark_reg_unknown(env, regs, insn->dst_reg);
4413 } else if (BPF_SRC(insn->code) == BPF_X) {
4414 mark_reg_unknown(env, regs, insn->dst_reg);
4415 mark_reg_unknown(env, regs, insn->src_reg);
4416 }
4417 }
4418 return branch;
4419 }
4420
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)4421 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
4422 struct bpf_insn *insn,
4423 const struct bpf_reg_state *ptr_reg,
4424 const struct bpf_reg_state *off_reg,
4425 struct bpf_reg_state *dst_reg,
4426 struct bpf_sanitize_info *info,
4427 const bool commit_window)
4428 {
4429 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
4430 struct bpf_verifier_state *vstate = env->cur_state;
4431 bool off_is_imm = tnum_is_const(off_reg->var_off);
4432 bool off_is_neg = off_reg->smin_value < 0;
4433 bool ptr_is_dst_reg = ptr_reg == dst_reg;
4434 u8 opcode = BPF_OP(insn->code);
4435 u32 alu_state, alu_limit;
4436 struct bpf_reg_state tmp;
4437 bool ret;
4438 int err;
4439
4440 if (can_skip_alu_sanitation(env, insn))
4441 return 0;
4442
4443 /* We already marked aux for masking from non-speculative
4444 * paths, thus we got here in the first place. We only care
4445 * to explore bad access from here.
4446 */
4447 if (vstate->speculative)
4448 goto do_sim;
4449
4450 if (!commit_window) {
4451 if (!tnum_is_const(off_reg->var_off) &&
4452 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
4453 return REASON_BOUNDS;
4454
4455 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
4456 (opcode == BPF_SUB && !off_is_neg);
4457 }
4458
4459 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
4460 if (err < 0)
4461 return err;
4462
4463 if (commit_window) {
4464 /* In commit phase we narrow the masking window based on
4465 * the observed pointer move after the simulated operation.
4466 */
4467 alu_state = info->aux.alu_state;
4468 alu_limit = abs(info->aux.alu_limit - alu_limit);
4469 } else {
4470 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
4471 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
4472 alu_state |= ptr_is_dst_reg ?
4473 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
4474
4475 /* Limit pruning on unknown scalars to enable deep search for
4476 * potential masking differences from other program paths.
4477 */
4478 if (!off_is_imm)
4479 env->explore_alu_limits = true;
4480 }
4481
4482 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
4483 if (err < 0)
4484 return err;
4485 do_sim:
4486 /* If we're in commit phase, we're done here given we already
4487 * pushed the truncated dst_reg into the speculative verification
4488 * stack.
4489 *
4490 * Also, when register is a known constant, we rewrite register-based
4491 * operation to immediate-based, and thus do not need masking (and as
4492 * a consequence, do not need to simulate the zero-truncation either).
4493 */
4494 if (commit_window || off_is_imm)
4495 return 0;
4496
4497 /* Simulate and find potential out-of-bounds access under
4498 * speculative execution from truncation as a result of
4499 * masking when off was not within expected range. If off
4500 * sits in dst, then we temporarily need to move ptr there
4501 * to simulate dst (== 0) +/-= ptr. Needed, for example,
4502 * for cases where we use K-based arithmetic in one direction
4503 * and truncated reg-based in the other in order to explore
4504 * bad access.
4505 */
4506 if (!ptr_is_dst_reg) {
4507 tmp = *dst_reg;
4508 *dst_reg = *ptr_reg;
4509 }
4510 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
4511 env->insn_idx);
4512 if (!ptr_is_dst_reg && ret)
4513 *dst_reg = tmp;
4514 return !ret ? REASON_STACK : 0;
4515 }
4516
sanitize_mark_insn_seen(struct bpf_verifier_env * env)4517 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
4518 {
4519 struct bpf_verifier_state *vstate = env->cur_state;
4520
4521 /* If we simulate paths under speculation, we don't update the
4522 * insn as 'seen' such that when we verify unreachable paths in
4523 * the non-speculative domain, sanitize_dead_code() can still
4524 * rewrite/sanitize them.
4525 */
4526 if (!vstate->speculative)
4527 env->insn_aux_data[env->insn_idx].seen = true;
4528 }
4529
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)4530 static int sanitize_err(struct bpf_verifier_env *env,
4531 const struct bpf_insn *insn, int reason,
4532 const struct bpf_reg_state *off_reg,
4533 const struct bpf_reg_state *dst_reg)
4534 {
4535 static const char *err = "pointer arithmetic with it prohibited for !root";
4536 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
4537 u32 dst = insn->dst_reg, src = insn->src_reg;
4538
4539 switch (reason) {
4540 case REASON_BOUNDS:
4541 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
4542 off_reg == dst_reg ? dst : src, err);
4543 break;
4544 case REASON_TYPE:
4545 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
4546 off_reg == dst_reg ? src : dst, err);
4547 break;
4548 case REASON_PATHS:
4549 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
4550 dst, op, err);
4551 break;
4552 case REASON_LIMIT:
4553 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
4554 dst, op, err);
4555 break;
4556 case REASON_STACK:
4557 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
4558 dst, err);
4559 break;
4560 default:
4561 verbose(env, "verifier internal error: unknown reason (%d)\n",
4562 reason);
4563 break;
4564 }
4565
4566 return -EACCES;
4567 }
4568
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)4569 static int sanitize_check_bounds(struct bpf_verifier_env *env,
4570 const struct bpf_insn *insn,
4571 const struct bpf_reg_state *dst_reg)
4572 {
4573 u32 dst = insn->dst_reg;
4574
4575 /* For unprivileged we require that resulting offset must be in bounds
4576 * in order to be able to sanitize access later on.
4577 */
4578 if (env->allow_ptr_leaks)
4579 return 0;
4580
4581 switch (dst_reg->type) {
4582 case PTR_TO_STACK:
4583 if (check_stack_access(env, dst_reg, dst_reg->off +
4584 dst_reg->var_off.value, 1)) {
4585 verbose(env, "R%d stack pointer arithmetic goes out of range, "
4586 "prohibited for !root\n", dst);
4587 return -EACCES;
4588 }
4589 break;
4590 case PTR_TO_MAP_VALUE:
4591 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
4592 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
4593 "prohibited for !root\n", dst);
4594 return -EACCES;
4595 }
4596 break;
4597 default:
4598 break;
4599 }
4600
4601 return 0;
4602 }
4603
4604 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
4605 * Caller should also handle BPF_MOV case separately.
4606 * If we return -EACCES, caller may want to try again treating pointer as a
4607 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
4608 */
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)4609 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
4610 struct bpf_insn *insn,
4611 const struct bpf_reg_state *ptr_reg,
4612 const struct bpf_reg_state *off_reg)
4613 {
4614 struct bpf_verifier_state *vstate = env->cur_state;
4615 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4616 struct bpf_reg_state *regs = state->regs, *dst_reg;
4617 bool known = tnum_is_const(off_reg->var_off);
4618 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
4619 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
4620 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
4621 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
4622 struct bpf_sanitize_info info = {};
4623 u8 opcode = BPF_OP(insn->code);
4624 u32 dst = insn->dst_reg;
4625 int ret;
4626
4627 dst_reg = ®s[dst];
4628
4629 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
4630 smin_val > smax_val || umin_val > umax_val) {
4631 /* Taint dst register if offset had invalid bounds derived from
4632 * e.g. dead branches.
4633 */
4634 __mark_reg_unknown(env, dst_reg);
4635 return 0;
4636 }
4637
4638 if (BPF_CLASS(insn->code) != BPF_ALU64) {
4639 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
4640 verbose(env,
4641 "R%d 32-bit pointer arithmetic prohibited\n",
4642 dst);
4643 return -EACCES;
4644 }
4645
4646 switch (ptr_reg->type) {
4647 case PTR_TO_MAP_VALUE_OR_NULL:
4648 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
4649 dst, reg_type_str[ptr_reg->type]);
4650 return -EACCES;
4651 case CONST_PTR_TO_MAP:
4652 /* smin_val represents the known value */
4653 if (known && smin_val == 0 && opcode == BPF_ADD)
4654 break;
4655 /* fall-through */
4656 case PTR_TO_PACKET_END:
4657 case PTR_TO_SOCKET:
4658 case PTR_TO_SOCKET_OR_NULL:
4659 case PTR_TO_SOCK_COMMON:
4660 case PTR_TO_SOCK_COMMON_OR_NULL:
4661 case PTR_TO_TCP_SOCK:
4662 case PTR_TO_TCP_SOCK_OR_NULL:
4663 case PTR_TO_XDP_SOCK:
4664 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
4665 dst, reg_type_str[ptr_reg->type]);
4666 return -EACCES;
4667 default:
4668 break;
4669 }
4670
4671 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
4672 * The id may be overwritten later if we create a new variable offset.
4673 */
4674 dst_reg->type = ptr_reg->type;
4675 dst_reg->id = ptr_reg->id;
4676
4677 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
4678 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
4679 return -EINVAL;
4680
4681 if (sanitize_needed(opcode)) {
4682 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
4683 &info, false);
4684 if (ret < 0)
4685 return sanitize_err(env, insn, ret, off_reg, dst_reg);
4686 }
4687
4688 switch (opcode) {
4689 case BPF_ADD:
4690 /* We can take a fixed offset as long as it doesn't overflow
4691 * the s32 'off' field
4692 */
4693 if (known && (ptr_reg->off + smin_val ==
4694 (s64)(s32)(ptr_reg->off + smin_val))) {
4695 /* pointer += K. Accumulate it into fixed offset */
4696 dst_reg->smin_value = smin_ptr;
4697 dst_reg->smax_value = smax_ptr;
4698 dst_reg->umin_value = umin_ptr;
4699 dst_reg->umax_value = umax_ptr;
4700 dst_reg->var_off = ptr_reg->var_off;
4701 dst_reg->off = ptr_reg->off + smin_val;
4702 dst_reg->raw = ptr_reg->raw;
4703 break;
4704 }
4705 /* A new variable offset is created. Note that off_reg->off
4706 * == 0, since it's a scalar.
4707 * dst_reg gets the pointer type and since some positive
4708 * integer value was added to the pointer, give it a new 'id'
4709 * if it's a PTR_TO_PACKET.
4710 * this creates a new 'base' pointer, off_reg (variable) gets
4711 * added into the variable offset, and we copy the fixed offset
4712 * from ptr_reg.
4713 */
4714 if (signed_add_overflows(smin_ptr, smin_val) ||
4715 signed_add_overflows(smax_ptr, smax_val)) {
4716 dst_reg->smin_value = S64_MIN;
4717 dst_reg->smax_value = S64_MAX;
4718 } else {
4719 dst_reg->smin_value = smin_ptr + smin_val;
4720 dst_reg->smax_value = smax_ptr + smax_val;
4721 }
4722 if (umin_ptr + umin_val < umin_ptr ||
4723 umax_ptr + umax_val < umax_ptr) {
4724 dst_reg->umin_value = 0;
4725 dst_reg->umax_value = U64_MAX;
4726 } else {
4727 dst_reg->umin_value = umin_ptr + umin_val;
4728 dst_reg->umax_value = umax_ptr + umax_val;
4729 }
4730 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
4731 dst_reg->off = ptr_reg->off;
4732 dst_reg->raw = ptr_reg->raw;
4733 if (reg_is_pkt_pointer(ptr_reg)) {
4734 dst_reg->id = ++env->id_gen;
4735 /* something was added to pkt_ptr, set range to zero */
4736 dst_reg->raw = 0;
4737 }
4738 break;
4739 case BPF_SUB:
4740 if (dst_reg == off_reg) {
4741 /* scalar -= pointer. Creates an unknown scalar */
4742 verbose(env, "R%d tried to subtract pointer from scalar\n",
4743 dst);
4744 return -EACCES;
4745 }
4746 /* We don't allow subtraction from FP, because (according to
4747 * test_verifier.c test "invalid fp arithmetic", JITs might not
4748 * be able to deal with it.
4749 */
4750 if (ptr_reg->type == PTR_TO_STACK) {
4751 verbose(env, "R%d subtraction from stack pointer prohibited\n",
4752 dst);
4753 return -EACCES;
4754 }
4755 if (known && (ptr_reg->off - smin_val ==
4756 (s64)(s32)(ptr_reg->off - smin_val))) {
4757 /* pointer -= K. Subtract it from fixed offset */
4758 dst_reg->smin_value = smin_ptr;
4759 dst_reg->smax_value = smax_ptr;
4760 dst_reg->umin_value = umin_ptr;
4761 dst_reg->umax_value = umax_ptr;
4762 dst_reg->var_off = ptr_reg->var_off;
4763 dst_reg->id = ptr_reg->id;
4764 dst_reg->off = ptr_reg->off - smin_val;
4765 dst_reg->raw = ptr_reg->raw;
4766 break;
4767 }
4768 /* A new variable offset is created. If the subtrahend is known
4769 * nonnegative, then any reg->range we had before is still good.
4770 */
4771 if (signed_sub_overflows(smin_ptr, smax_val) ||
4772 signed_sub_overflows(smax_ptr, smin_val)) {
4773 /* Overflow possible, we know nothing */
4774 dst_reg->smin_value = S64_MIN;
4775 dst_reg->smax_value = S64_MAX;
4776 } else {
4777 dst_reg->smin_value = smin_ptr - smax_val;
4778 dst_reg->smax_value = smax_ptr - smin_val;
4779 }
4780 if (umin_ptr < umax_val) {
4781 /* Overflow possible, we know nothing */
4782 dst_reg->umin_value = 0;
4783 dst_reg->umax_value = U64_MAX;
4784 } else {
4785 /* Cannot overflow (as long as bounds are consistent) */
4786 dst_reg->umin_value = umin_ptr - umax_val;
4787 dst_reg->umax_value = umax_ptr - umin_val;
4788 }
4789 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
4790 dst_reg->off = ptr_reg->off;
4791 dst_reg->raw = ptr_reg->raw;
4792 if (reg_is_pkt_pointer(ptr_reg)) {
4793 dst_reg->id = ++env->id_gen;
4794 /* something was added to pkt_ptr, set range to zero */
4795 if (smin_val < 0)
4796 dst_reg->raw = 0;
4797 }
4798 break;
4799 case BPF_AND:
4800 case BPF_OR:
4801 case BPF_XOR:
4802 /* bitwise ops on pointers are troublesome, prohibit. */
4803 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
4804 dst, bpf_alu_string[opcode >> 4]);
4805 return -EACCES;
4806 default:
4807 /* other operators (e.g. MUL,LSH) produce non-pointer results */
4808 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
4809 dst, bpf_alu_string[opcode >> 4]);
4810 return -EACCES;
4811 }
4812
4813 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
4814 return -EINVAL;
4815
4816 __update_reg_bounds(dst_reg);
4817 __reg_deduce_bounds(dst_reg);
4818 __reg_bound_offset(dst_reg);
4819
4820 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
4821 return -EACCES;
4822 if (sanitize_needed(opcode)) {
4823 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
4824 &info, true);
4825 if (ret < 0)
4826 return sanitize_err(env, insn, ret, off_reg, dst_reg);
4827 }
4828
4829 return 0;
4830 }
4831
4832 /* WARNING: This function does calculations on 64-bit values, but the actual
4833 * execution may occur on 32-bit values. Therefore, things like bitshifts
4834 * need extra checks in the 32-bit case.
4835 */
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)4836 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
4837 struct bpf_insn *insn,
4838 struct bpf_reg_state *dst_reg,
4839 struct bpf_reg_state src_reg)
4840 {
4841 struct bpf_reg_state *regs = cur_regs(env);
4842 u8 opcode = BPF_OP(insn->code);
4843 bool src_known, dst_known;
4844 s64 smin_val, smax_val;
4845 u64 umin_val, umax_val;
4846 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
4847 int ret;
4848
4849 if (insn_bitness == 32) {
4850 /* Relevant for 32-bit RSH: Information can propagate towards
4851 * LSB, so it isn't sufficient to only truncate the output to
4852 * 32 bits.
4853 */
4854 coerce_reg_to_size(dst_reg, 4);
4855 coerce_reg_to_size(&src_reg, 4);
4856 }
4857
4858 smin_val = src_reg.smin_value;
4859 smax_val = src_reg.smax_value;
4860 umin_val = src_reg.umin_value;
4861 umax_val = src_reg.umax_value;
4862 src_known = tnum_is_const(src_reg.var_off);
4863 dst_known = tnum_is_const(dst_reg->var_off);
4864
4865 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
4866 smin_val > smax_val || umin_val > umax_val) {
4867 /* Taint dst register if offset had invalid bounds derived from
4868 * e.g. dead branches.
4869 */
4870 __mark_reg_unknown(env, dst_reg);
4871 return 0;
4872 }
4873
4874 if (!src_known &&
4875 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
4876 __mark_reg_unknown(env, dst_reg);
4877 return 0;
4878 }
4879
4880 if (sanitize_needed(opcode)) {
4881 ret = sanitize_val_alu(env, insn);
4882 if (ret < 0)
4883 return sanitize_err(env, insn, ret, NULL, NULL);
4884 }
4885
4886 switch (opcode) {
4887 case BPF_ADD:
4888 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
4889 signed_add_overflows(dst_reg->smax_value, smax_val)) {
4890 dst_reg->smin_value = S64_MIN;
4891 dst_reg->smax_value = S64_MAX;
4892 } else {
4893 dst_reg->smin_value += smin_val;
4894 dst_reg->smax_value += smax_val;
4895 }
4896 if (dst_reg->umin_value + umin_val < umin_val ||
4897 dst_reg->umax_value + umax_val < umax_val) {
4898 dst_reg->umin_value = 0;
4899 dst_reg->umax_value = U64_MAX;
4900 } else {
4901 dst_reg->umin_value += umin_val;
4902 dst_reg->umax_value += umax_val;
4903 }
4904 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
4905 break;
4906 case BPF_SUB:
4907 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
4908 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
4909 /* Overflow possible, we know nothing */
4910 dst_reg->smin_value = S64_MIN;
4911 dst_reg->smax_value = S64_MAX;
4912 } else {
4913 dst_reg->smin_value -= smax_val;
4914 dst_reg->smax_value -= smin_val;
4915 }
4916 if (dst_reg->umin_value < umax_val) {
4917 /* Overflow possible, we know nothing */
4918 dst_reg->umin_value = 0;
4919 dst_reg->umax_value = U64_MAX;
4920 } else {
4921 /* Cannot overflow (as long as bounds are consistent) */
4922 dst_reg->umin_value -= umax_val;
4923 dst_reg->umax_value -= umin_val;
4924 }
4925 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
4926 break;
4927 case BPF_MUL:
4928 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
4929 if (smin_val < 0 || dst_reg->smin_value < 0) {
4930 /* Ain't nobody got time to multiply that sign */
4931 __mark_reg_unbounded(dst_reg);
4932 __update_reg_bounds(dst_reg);
4933 break;
4934 }
4935 /* Both values are positive, so we can work with unsigned and
4936 * copy the result to signed (unless it exceeds S64_MAX).
4937 */
4938 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
4939 /* Potential overflow, we know nothing */
4940 __mark_reg_unbounded(dst_reg);
4941 /* (except what we can learn from the var_off) */
4942 __update_reg_bounds(dst_reg);
4943 break;
4944 }
4945 dst_reg->umin_value *= umin_val;
4946 dst_reg->umax_value *= umax_val;
4947 if (dst_reg->umax_value > S64_MAX) {
4948 /* Overflow possible, we know nothing */
4949 dst_reg->smin_value = S64_MIN;
4950 dst_reg->smax_value = S64_MAX;
4951 } else {
4952 dst_reg->smin_value = dst_reg->umin_value;
4953 dst_reg->smax_value = dst_reg->umax_value;
4954 }
4955 break;
4956 case BPF_AND:
4957 if (src_known && dst_known) {
4958 __mark_reg_known(dst_reg, dst_reg->var_off.value &
4959 src_reg.var_off.value);
4960 break;
4961 }
4962 /* We get our minimum from the var_off, since that's inherently
4963 * bitwise. Our maximum is the minimum of the operands' maxima.
4964 */
4965 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
4966 dst_reg->umin_value = dst_reg->var_off.value;
4967 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
4968 if (dst_reg->smin_value < 0 || smin_val < 0) {
4969 /* Lose signed bounds when ANDing negative numbers,
4970 * ain't nobody got time for that.
4971 */
4972 dst_reg->smin_value = S64_MIN;
4973 dst_reg->smax_value = S64_MAX;
4974 } else {
4975 /* ANDing two positives gives a positive, so safe to
4976 * cast result into s64.
4977 */
4978 dst_reg->smin_value = dst_reg->umin_value;
4979 dst_reg->smax_value = dst_reg->umax_value;
4980 }
4981 /* We may learn something more from the var_off */
4982 __update_reg_bounds(dst_reg);
4983 break;
4984 case BPF_OR:
4985 if (src_known && dst_known) {
4986 __mark_reg_known(dst_reg, dst_reg->var_off.value |
4987 src_reg.var_off.value);
4988 break;
4989 }
4990 /* We get our maximum from the var_off, and our minimum is the
4991 * maximum of the operands' minima
4992 */
4993 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
4994 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
4995 dst_reg->umax_value = dst_reg->var_off.value |
4996 dst_reg->var_off.mask;
4997 if (dst_reg->smin_value < 0 || smin_val < 0) {
4998 /* Lose signed bounds when ORing negative numbers,
4999 * ain't nobody got time for that.
5000 */
5001 dst_reg->smin_value = S64_MIN;
5002 dst_reg->smax_value = S64_MAX;
5003 } else {
5004 /* ORing two positives gives a positive, so safe to
5005 * cast result into s64.
5006 */
5007 dst_reg->smin_value = dst_reg->umin_value;
5008 dst_reg->smax_value = dst_reg->umax_value;
5009 }
5010 /* We may learn something more from the var_off */
5011 __update_reg_bounds(dst_reg);
5012 break;
5013 case BPF_LSH:
5014 if (umax_val >= insn_bitness) {
5015 /* Shifts greater than 31 or 63 are undefined.
5016 * This includes shifts by a negative number.
5017 */
5018 mark_reg_unknown(env, regs, insn->dst_reg);
5019 break;
5020 }
5021 /* We lose all sign bit information (except what we can pick
5022 * up from var_off)
5023 */
5024 dst_reg->smin_value = S64_MIN;
5025 dst_reg->smax_value = S64_MAX;
5026 /* If we might shift our top bit out, then we know nothing */
5027 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
5028 dst_reg->umin_value = 0;
5029 dst_reg->umax_value = U64_MAX;
5030 } else {
5031 dst_reg->umin_value <<= umin_val;
5032 dst_reg->umax_value <<= umax_val;
5033 }
5034 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
5035 /* We may learn something more from the var_off */
5036 __update_reg_bounds(dst_reg);
5037 break;
5038 case BPF_RSH:
5039 if (umax_val >= insn_bitness) {
5040 /* Shifts greater than 31 or 63 are undefined.
5041 * This includes shifts by a negative number.
5042 */
5043 mark_reg_unknown(env, regs, insn->dst_reg);
5044 break;
5045 }
5046 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
5047 * be negative, then either:
5048 * 1) src_reg might be zero, so the sign bit of the result is
5049 * unknown, so we lose our signed bounds
5050 * 2) it's known negative, thus the unsigned bounds capture the
5051 * signed bounds
5052 * 3) the signed bounds cross zero, so they tell us nothing
5053 * about the result
5054 * If the value in dst_reg is known nonnegative, then again the
5055 * unsigned bounts capture the signed bounds.
5056 * Thus, in all cases it suffices to blow away our signed bounds
5057 * and rely on inferring new ones from the unsigned bounds and
5058 * var_off of the result.
5059 */
5060 dst_reg->smin_value = S64_MIN;
5061 dst_reg->smax_value = S64_MAX;
5062 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
5063 dst_reg->umin_value >>= umax_val;
5064 dst_reg->umax_value >>= umin_val;
5065 /* We may learn something more from the var_off */
5066 __update_reg_bounds(dst_reg);
5067 break;
5068 case BPF_ARSH:
5069 if (umax_val >= insn_bitness) {
5070 /* Shifts greater than 31 or 63 are undefined.
5071 * This includes shifts by a negative number.
5072 */
5073 mark_reg_unknown(env, regs, insn->dst_reg);
5074 break;
5075 }
5076
5077 /* Upon reaching here, src_known is true and
5078 * umax_val is equal to umin_val.
5079 */
5080 if (insn_bitness == 32) {
5081 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
5082 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
5083 } else {
5084 dst_reg->smin_value >>= umin_val;
5085 dst_reg->smax_value >>= umin_val;
5086 }
5087
5088 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
5089 insn_bitness);
5090
5091 /* blow away the dst_reg umin_value/umax_value and rely on
5092 * dst_reg var_off to refine the result.
5093 */
5094 dst_reg->umin_value = 0;
5095 dst_reg->umax_value = U64_MAX;
5096 __update_reg_bounds(dst_reg);
5097 break;
5098 default:
5099 mark_reg_unknown(env, regs, insn->dst_reg);
5100 break;
5101 }
5102
5103 if (BPF_CLASS(insn->code) != BPF_ALU64) {
5104 /* 32-bit ALU ops are (32,32)->32 */
5105 coerce_reg_to_size(dst_reg, 4);
5106 }
5107
5108 __update_reg_bounds(dst_reg);
5109 __reg_deduce_bounds(dst_reg);
5110 __reg_bound_offset(dst_reg);
5111 return 0;
5112 }
5113
5114 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
5115 * and var_off.
5116 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)5117 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
5118 struct bpf_insn *insn)
5119 {
5120 struct bpf_verifier_state *vstate = env->cur_state;
5121 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5122 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
5123 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
5124 u8 opcode = BPF_OP(insn->code);
5125 int err;
5126
5127 dst_reg = ®s[insn->dst_reg];
5128 src_reg = NULL;
5129 if (dst_reg->type != SCALAR_VALUE)
5130 ptr_reg = dst_reg;
5131 if (BPF_SRC(insn->code) == BPF_X) {
5132 src_reg = ®s[insn->src_reg];
5133 if (src_reg->type != SCALAR_VALUE) {
5134 if (dst_reg->type != SCALAR_VALUE) {
5135 /* Combining two pointers by any ALU op yields
5136 * an arbitrary scalar. Disallow all math except
5137 * pointer subtraction
5138 */
5139 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
5140 mark_reg_unknown(env, regs, insn->dst_reg);
5141 return 0;
5142 }
5143 verbose(env, "R%d pointer %s pointer prohibited\n",
5144 insn->dst_reg,
5145 bpf_alu_string[opcode >> 4]);
5146 return -EACCES;
5147 } else {
5148 /* scalar += pointer
5149 * This is legal, but we have to reverse our
5150 * src/dest handling in computing the range
5151 */
5152 err = mark_chain_precision(env, insn->dst_reg);
5153 if (err)
5154 return err;
5155 return adjust_ptr_min_max_vals(env, insn,
5156 src_reg, dst_reg);
5157 }
5158 } else if (ptr_reg) {
5159 /* pointer += scalar */
5160 err = mark_chain_precision(env, insn->src_reg);
5161 if (err)
5162 return err;
5163 return adjust_ptr_min_max_vals(env, insn,
5164 dst_reg, src_reg);
5165 } else if (dst_reg->precise) {
5166 /* if dst_reg is precise, src_reg should be precise as well */
5167 err = mark_chain_precision(env, insn->src_reg);
5168 if (err)
5169 return err;
5170 }
5171 } else {
5172 /* Pretend the src is a reg with a known value, since we only
5173 * need to be able to read from this state.
5174 */
5175 off_reg.type = SCALAR_VALUE;
5176 __mark_reg_known(&off_reg, insn->imm);
5177 src_reg = &off_reg;
5178 if (ptr_reg) /* pointer += K */
5179 return adjust_ptr_min_max_vals(env, insn,
5180 ptr_reg, src_reg);
5181 }
5182
5183 /* Got here implies adding two SCALAR_VALUEs */
5184 if (WARN_ON_ONCE(ptr_reg)) {
5185 print_verifier_state(env, state);
5186 verbose(env, "verifier internal error: unexpected ptr_reg\n");
5187 return -EINVAL;
5188 }
5189 if (WARN_ON(!src_reg)) {
5190 print_verifier_state(env, state);
5191 verbose(env, "verifier internal error: no src_reg\n");
5192 return -EINVAL;
5193 }
5194 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
5195 }
5196
5197 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)5198 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
5199 {
5200 struct bpf_reg_state *regs = cur_regs(env);
5201 u8 opcode = BPF_OP(insn->code);
5202 int err;
5203
5204 if (opcode == BPF_END || opcode == BPF_NEG) {
5205 if (opcode == BPF_NEG) {
5206 if (BPF_SRC(insn->code) != 0 ||
5207 insn->src_reg != BPF_REG_0 ||
5208 insn->off != 0 || insn->imm != 0) {
5209 verbose(env, "BPF_NEG uses reserved fields\n");
5210 return -EINVAL;
5211 }
5212 } else {
5213 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
5214 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
5215 BPF_CLASS(insn->code) == BPF_ALU64) {
5216 verbose(env, "BPF_END uses reserved fields\n");
5217 return -EINVAL;
5218 }
5219 }
5220
5221 /* check src operand */
5222 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5223 if (err)
5224 return err;
5225
5226 if (is_pointer_value(env, insn->dst_reg)) {
5227 verbose(env, "R%d pointer arithmetic prohibited\n",
5228 insn->dst_reg);
5229 return -EACCES;
5230 }
5231
5232 /* check dest operand */
5233 err = check_reg_arg(env, insn->dst_reg, DST_OP);
5234 if (err)
5235 return err;
5236
5237 } else if (opcode == BPF_MOV) {
5238
5239 if (BPF_SRC(insn->code) == BPF_X) {
5240 if (insn->imm != 0 || insn->off != 0) {
5241 verbose(env, "BPF_MOV uses reserved fields\n");
5242 return -EINVAL;
5243 }
5244
5245 /* check src operand */
5246 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5247 if (err)
5248 return err;
5249 } else {
5250 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5251 verbose(env, "BPF_MOV uses reserved fields\n");
5252 return -EINVAL;
5253 }
5254 }
5255
5256 /* check dest operand, mark as required later */
5257 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5258 if (err)
5259 return err;
5260
5261 if (BPF_SRC(insn->code) == BPF_X) {
5262 struct bpf_reg_state *src_reg = regs + insn->src_reg;
5263 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
5264
5265 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5266 /* case: R1 = R2
5267 * copy register state to dest reg
5268 */
5269 *dst_reg = *src_reg;
5270 dst_reg->live |= REG_LIVE_WRITTEN;
5271 dst_reg->subreg_def = DEF_NOT_SUBREG;
5272 } else {
5273 /* R1 = (u32) R2 */
5274 if (is_pointer_value(env, insn->src_reg)) {
5275 verbose(env,
5276 "R%d partial copy of pointer\n",
5277 insn->src_reg);
5278 return -EACCES;
5279 } else if (src_reg->type == SCALAR_VALUE) {
5280 *dst_reg = *src_reg;
5281 dst_reg->live |= REG_LIVE_WRITTEN;
5282 dst_reg->subreg_def = env->insn_idx + 1;
5283 } else {
5284 mark_reg_unknown(env, regs,
5285 insn->dst_reg);
5286 }
5287 coerce_reg_to_size(dst_reg, 4);
5288 }
5289 } else {
5290 /* case: R = imm
5291 * remember the value we stored into this reg
5292 */
5293 /* clear any state __mark_reg_known doesn't set */
5294 mark_reg_unknown(env, regs, insn->dst_reg);
5295 regs[insn->dst_reg].type = SCALAR_VALUE;
5296 if (BPF_CLASS(insn->code) == BPF_ALU64) {
5297 __mark_reg_known(regs + insn->dst_reg,
5298 insn->imm);
5299 } else {
5300 __mark_reg_known(regs + insn->dst_reg,
5301 (u32)insn->imm);
5302 }
5303 }
5304
5305 } else if (opcode > BPF_END) {
5306 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
5307 return -EINVAL;
5308
5309 } else { /* all other ALU ops: and, sub, xor, add, ... */
5310
5311 if (BPF_SRC(insn->code) == BPF_X) {
5312 if (insn->imm != 0 || insn->off != 0) {
5313 verbose(env, "BPF_ALU uses reserved fields\n");
5314 return -EINVAL;
5315 }
5316 /* check src1 operand */
5317 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5318 if (err)
5319 return err;
5320 } else {
5321 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
5322 verbose(env, "BPF_ALU uses reserved fields\n");
5323 return -EINVAL;
5324 }
5325 }
5326
5327 /* check src2 operand */
5328 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5329 if (err)
5330 return err;
5331
5332 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
5333 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
5334 verbose(env, "div by zero\n");
5335 return -EINVAL;
5336 }
5337
5338 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
5339 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
5340 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
5341
5342 if (insn->imm < 0 || insn->imm >= size) {
5343 verbose(env, "invalid shift %d\n", insn->imm);
5344 return -EINVAL;
5345 }
5346 }
5347
5348 /* check dest operand */
5349 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5350 if (err)
5351 return err;
5352
5353 return adjust_reg_min_max_vals(env, insn);
5354 }
5355
5356 return 0;
5357 }
5358
__find_good_pkt_pointers(struct bpf_func_state * state,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,u16 new_range)5359 static void __find_good_pkt_pointers(struct bpf_func_state *state,
5360 struct bpf_reg_state *dst_reg,
5361 enum bpf_reg_type type, u16 new_range)
5362 {
5363 struct bpf_reg_state *reg;
5364 int i;
5365
5366 for (i = 0; i < MAX_BPF_REG; i++) {
5367 reg = &state->regs[i];
5368 if (reg->type == type && reg->id == dst_reg->id)
5369 /* keep the maximum range already checked */
5370 reg->range = max(reg->range, new_range);
5371 }
5372
5373 bpf_for_each_spilled_reg(i, state, reg) {
5374 if (!reg)
5375 continue;
5376 if (reg->type == type && reg->id == dst_reg->id)
5377 reg->range = max(reg->range, new_range);
5378 }
5379 }
5380
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)5381 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
5382 struct bpf_reg_state *dst_reg,
5383 enum bpf_reg_type type,
5384 bool range_right_open)
5385 {
5386 u16 new_range;
5387 int i;
5388
5389 if (dst_reg->off < 0 ||
5390 (dst_reg->off == 0 && range_right_open))
5391 /* This doesn't give us any range */
5392 return;
5393
5394 if (dst_reg->umax_value > MAX_PACKET_OFF ||
5395 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
5396 /* Risk of overflow. For instance, ptr + (1<<63) may be less
5397 * than pkt_end, but that's because it's also less than pkt.
5398 */
5399 return;
5400
5401 new_range = dst_reg->off;
5402 if (range_right_open)
5403 new_range++;
5404
5405 /* Examples for register markings:
5406 *
5407 * pkt_data in dst register:
5408 *
5409 * r2 = r3;
5410 * r2 += 8;
5411 * if (r2 > pkt_end) goto <handle exception>
5412 * <access okay>
5413 *
5414 * r2 = r3;
5415 * r2 += 8;
5416 * if (r2 < pkt_end) goto <access okay>
5417 * <handle exception>
5418 *
5419 * Where:
5420 * r2 == dst_reg, pkt_end == src_reg
5421 * r2=pkt(id=n,off=8,r=0)
5422 * r3=pkt(id=n,off=0,r=0)
5423 *
5424 * pkt_data in src register:
5425 *
5426 * r2 = r3;
5427 * r2 += 8;
5428 * if (pkt_end >= r2) goto <access okay>
5429 * <handle exception>
5430 *
5431 * r2 = r3;
5432 * r2 += 8;
5433 * if (pkt_end <= r2) goto <handle exception>
5434 * <access okay>
5435 *
5436 * Where:
5437 * pkt_end == dst_reg, r2 == src_reg
5438 * r2=pkt(id=n,off=8,r=0)
5439 * r3=pkt(id=n,off=0,r=0)
5440 *
5441 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
5442 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
5443 * and [r3, r3 + 8-1) respectively is safe to access depending on
5444 * the check.
5445 */
5446
5447 /* If our ids match, then we must have the same max_value. And we
5448 * don't care about the other reg's fixed offset, since if it's too big
5449 * the range won't allow anything.
5450 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
5451 */
5452 for (i = 0; i <= vstate->curframe; i++)
5453 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
5454 new_range);
5455 }
5456
5457 /* compute branch direction of the expression "if (reg opcode val) goto target;"
5458 * and return:
5459 * 1 - branch will be taken and "goto target" will be executed
5460 * 0 - branch will not be taken and fall-through to next insn
5461 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
5462 */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)5463 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
5464 bool is_jmp32)
5465 {
5466 struct bpf_reg_state reg_lo;
5467 s64 sval;
5468
5469 if (__is_pointer_value(false, reg))
5470 return -1;
5471
5472 if (is_jmp32) {
5473 reg_lo = *reg;
5474 reg = ®_lo;
5475 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
5476 * could truncate high bits and update umin/umax according to
5477 * information of low bits.
5478 */
5479 coerce_reg_to_size(reg, 4);
5480 /* smin/smax need special handling. For example, after coerce,
5481 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
5482 * used as operand to JMP32. It is a negative number from s32's
5483 * point of view, while it is a positive number when seen as
5484 * s64. The smin/smax are kept as s64, therefore, when used with
5485 * JMP32, they need to be transformed into s32, then sign
5486 * extended back to s64.
5487 *
5488 * Also, smin/smax were copied from umin/umax. If umin/umax has
5489 * different sign bit, then min/max relationship doesn't
5490 * maintain after casting into s32, for this case, set smin/smax
5491 * to safest range.
5492 */
5493 if ((reg->umax_value ^ reg->umin_value) &
5494 (1ULL << 31)) {
5495 reg->smin_value = S32_MIN;
5496 reg->smax_value = S32_MAX;
5497 }
5498 reg->smin_value = (s64)(s32)reg->smin_value;
5499 reg->smax_value = (s64)(s32)reg->smax_value;
5500
5501 val = (u32)val;
5502 sval = (s64)(s32)val;
5503 } else {
5504 sval = (s64)val;
5505 }
5506
5507 switch (opcode) {
5508 case BPF_JEQ:
5509 if (tnum_is_const(reg->var_off))
5510 return !!tnum_equals_const(reg->var_off, val);
5511 break;
5512 case BPF_JNE:
5513 if (tnum_is_const(reg->var_off))
5514 return !tnum_equals_const(reg->var_off, val);
5515 break;
5516 case BPF_JSET:
5517 if ((~reg->var_off.mask & reg->var_off.value) & val)
5518 return 1;
5519 if (!((reg->var_off.mask | reg->var_off.value) & val))
5520 return 0;
5521 break;
5522 case BPF_JGT:
5523 if (reg->umin_value > val)
5524 return 1;
5525 else if (reg->umax_value <= val)
5526 return 0;
5527 break;
5528 case BPF_JSGT:
5529 if (reg->smin_value > sval)
5530 return 1;
5531 else if (reg->smax_value < sval)
5532 return 0;
5533 break;
5534 case BPF_JLT:
5535 if (reg->umax_value < val)
5536 return 1;
5537 else if (reg->umin_value >= val)
5538 return 0;
5539 break;
5540 case BPF_JSLT:
5541 if (reg->smax_value < sval)
5542 return 1;
5543 else if (reg->smin_value >= sval)
5544 return 0;
5545 break;
5546 case BPF_JGE:
5547 if (reg->umin_value >= val)
5548 return 1;
5549 else if (reg->umax_value < val)
5550 return 0;
5551 break;
5552 case BPF_JSGE:
5553 if (reg->smin_value >= sval)
5554 return 1;
5555 else if (reg->smax_value < sval)
5556 return 0;
5557 break;
5558 case BPF_JLE:
5559 if (reg->umax_value <= val)
5560 return 1;
5561 else if (reg->umin_value > val)
5562 return 0;
5563 break;
5564 case BPF_JSLE:
5565 if (reg->smax_value <= sval)
5566 return 1;
5567 else if (reg->smin_value > sval)
5568 return 0;
5569 break;
5570 }
5571
5572 return -1;
5573 }
5574
5575 /* Generate min value of the high 32-bit from TNUM info. */
gen_hi_min(struct tnum var)5576 static u64 gen_hi_min(struct tnum var)
5577 {
5578 return var.value & ~0xffffffffULL;
5579 }
5580
5581 /* Generate max value of the high 32-bit from TNUM info. */
gen_hi_max(struct tnum var)5582 static u64 gen_hi_max(struct tnum var)
5583 {
5584 return (var.value | var.mask) & ~0xffffffffULL;
5585 }
5586
5587 /* Return true if VAL is compared with a s64 sign extended from s32, and they
5588 * are with the same signedness.
5589 */
cmp_val_with_extended_s64(s64 sval,struct bpf_reg_state * reg)5590 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
5591 {
5592 return ((s32)sval >= 0 &&
5593 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
5594 ((s32)sval < 0 &&
5595 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
5596 }
5597
5598 /* Constrain the possible values of @reg with unsigned upper bound @bound.
5599 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5600 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5601 * of @reg.
5602 */
set_upper_bound(struct bpf_reg_state * reg,u64 bound,bool is_jmp32,bool is_exclusive)5603 static void set_upper_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5604 bool is_exclusive)
5605 {
5606 if (is_exclusive) {
5607 /* There are no values for `reg` that make `reg<0` true. */
5608 if (bound == 0)
5609 return;
5610 bound--;
5611 }
5612 if (is_jmp32) {
5613 /* Constrain the register's value in the tnum representation.
5614 * For 64-bit comparisons this happens later in
5615 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5616 * more precise than what can be derived from the updated
5617 * numeric bounds.
5618 */
5619 struct tnum t = tnum_range(0, bound);
5620
5621 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5622 reg->var_off = tnum_intersect(reg->var_off, t);
5623
5624 /* Compute the 64-bit bound from the 32-bit bound. */
5625 bound += gen_hi_max(reg->var_off);
5626 }
5627 reg->umax_value = min(reg->umax_value, bound);
5628 }
5629
5630 /* Constrain the possible values of @reg with unsigned lower bound @bound.
5631 * If @is_exclusive, @bound is an exclusive limit, otherwise it is inclusive.
5632 * If @is_jmp32, @bound is a 32-bit value that only constrains the low 32 bits
5633 * of @reg.
5634 */
set_lower_bound(struct bpf_reg_state * reg,u64 bound,bool is_jmp32,bool is_exclusive)5635 static void set_lower_bound(struct bpf_reg_state *reg, u64 bound, bool is_jmp32,
5636 bool is_exclusive)
5637 {
5638 if (is_exclusive) {
5639 /* There are no values for `reg` that make `reg>MAX` true. */
5640 if (bound == (is_jmp32 ? U32_MAX : U64_MAX))
5641 return;
5642 bound++;
5643 }
5644 if (is_jmp32) {
5645 /* Constrain the register's value in the tnum representation.
5646 * For 64-bit comparisons this happens later in
5647 * __reg_bound_offset(), but for 32-bit comparisons, we can be
5648 * more precise than what can be derived from the updated
5649 * numeric bounds.
5650 */
5651 struct tnum t = tnum_range(bound, U32_MAX);
5652
5653 t.mask |= ~0xffffffffULL; /* upper half is unknown */
5654 reg->var_off = tnum_intersect(reg->var_off, t);
5655
5656 /* Compute the 64-bit bound from the 32-bit bound. */
5657 bound += gen_hi_min(reg->var_off);
5658 }
5659 reg->umin_value = max(reg->umin_value, bound);
5660 }
5661
5662 /* Adjusts the register min/max values in the case that the dst_reg is the
5663 * variable register that we are working on, and src_reg is a constant or we're
5664 * simply doing a BPF_K check.
5665 * In JEQ/JNE cases we also adjust the var_off values.
5666 */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode,bool is_jmp32)5667 static void reg_set_min_max(struct bpf_reg_state *true_reg,
5668 struct bpf_reg_state *false_reg, u64 val,
5669 u8 opcode, bool is_jmp32)
5670 {
5671 s64 sval;
5672
5673 /* If the dst_reg is a pointer, we can't learn anything about its
5674 * variable offset from the compare (unless src_reg were a pointer into
5675 * the same object, but we don't bother with that.
5676 * Since false_reg and true_reg have the same type by construction, we
5677 * only need to check one of them for pointerness.
5678 */
5679 if (__is_pointer_value(false, false_reg))
5680 return;
5681
5682 val = is_jmp32 ? (u32)val : val;
5683 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
5684
5685 switch (opcode) {
5686 case BPF_JEQ:
5687 case BPF_JNE:
5688 {
5689 struct bpf_reg_state *reg =
5690 opcode == BPF_JEQ ? true_reg : false_reg;
5691
5692 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
5693 * if it is true we know the value for sure. Likewise for
5694 * BPF_JNE.
5695 */
5696 if (is_jmp32) {
5697 u64 old_v = reg->var_off.value;
5698 u64 hi_mask = ~0xffffffffULL;
5699
5700 reg->var_off.value = (old_v & hi_mask) | val;
5701 reg->var_off.mask &= hi_mask;
5702 } else {
5703 __mark_reg_known(reg, val);
5704 }
5705 break;
5706 }
5707 case BPF_JSET:
5708 false_reg->var_off = tnum_and(false_reg->var_off,
5709 tnum_const(~val));
5710 if (is_power_of_2(val))
5711 true_reg->var_off = tnum_or(true_reg->var_off,
5712 tnum_const(val));
5713 break;
5714 case BPF_JGE:
5715 case BPF_JGT:
5716 {
5717 set_upper_bound(false_reg, val, is_jmp32, opcode == BPF_JGE);
5718 set_lower_bound(true_reg, val, is_jmp32, opcode == BPF_JGT);
5719 break;
5720 }
5721 case BPF_JSGE:
5722 case BPF_JSGT:
5723 {
5724 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
5725 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
5726
5727 /* If the full s64 was not sign-extended from s32 then don't
5728 * deduct further info.
5729 */
5730 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5731 break;
5732 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5733 true_reg->smin_value = max(true_reg->smin_value, true_smin);
5734 break;
5735 }
5736 case BPF_JLE:
5737 case BPF_JLT:
5738 {
5739 set_lower_bound(false_reg, val, is_jmp32, opcode == BPF_JLE);
5740 set_upper_bound(true_reg, val, is_jmp32, opcode == BPF_JLT);
5741 break;
5742 }
5743 case BPF_JSLE:
5744 case BPF_JSLT:
5745 {
5746 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
5747 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
5748
5749 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5750 break;
5751 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5752 true_reg->smax_value = min(true_reg->smax_value, true_smax);
5753 break;
5754 }
5755 default:
5756 break;
5757 }
5758
5759 __reg_deduce_bounds(false_reg);
5760 __reg_deduce_bounds(true_reg);
5761 /* We might have learned some bits from the bounds. */
5762 __reg_bound_offset(false_reg);
5763 __reg_bound_offset(true_reg);
5764 /* Intersecting with the old var_off might have improved our bounds
5765 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5766 * then new var_off is (0; 0x7f...fc) which improves our umax.
5767 */
5768 __update_reg_bounds(false_reg);
5769 __update_reg_bounds(true_reg);
5770 }
5771
5772 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
5773 * the variable reg.
5774 */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode,bool is_jmp32)5775 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
5776 struct bpf_reg_state *false_reg, u64 val,
5777 u8 opcode, bool is_jmp32)
5778 {
5779 s64 sval;
5780
5781 if (__is_pointer_value(false, false_reg))
5782 return;
5783
5784 val = is_jmp32 ? (u32)val : val;
5785 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
5786
5787 switch (opcode) {
5788 case BPF_JEQ:
5789 case BPF_JNE:
5790 {
5791 struct bpf_reg_state *reg =
5792 opcode == BPF_JEQ ? true_reg : false_reg;
5793
5794 if (is_jmp32) {
5795 u64 old_v = reg->var_off.value;
5796 u64 hi_mask = ~0xffffffffULL;
5797
5798 reg->var_off.value = (old_v & hi_mask) | val;
5799 reg->var_off.mask &= hi_mask;
5800 } else {
5801 __mark_reg_known(reg, val);
5802 }
5803 break;
5804 }
5805 case BPF_JSET:
5806 false_reg->var_off = tnum_and(false_reg->var_off,
5807 tnum_const(~val));
5808 if (is_power_of_2(val))
5809 true_reg->var_off = tnum_or(true_reg->var_off,
5810 tnum_const(val));
5811 break;
5812 case BPF_JGE:
5813 case BPF_JGT:
5814 {
5815 set_lower_bound(false_reg, val, is_jmp32, opcode == BPF_JGE);
5816 set_upper_bound(true_reg, val, is_jmp32, opcode == BPF_JGT);
5817 break;
5818 }
5819 case BPF_JSGE:
5820 case BPF_JSGT:
5821 {
5822 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
5823 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
5824
5825 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5826 break;
5827 false_reg->smin_value = max(false_reg->smin_value, false_smin);
5828 true_reg->smax_value = min(true_reg->smax_value, true_smax);
5829 break;
5830 }
5831 case BPF_JLE:
5832 case BPF_JLT:
5833 {
5834 set_upper_bound(false_reg, val, is_jmp32, opcode == BPF_JLE);
5835 set_lower_bound(true_reg, val, is_jmp32, opcode == BPF_JLT);
5836 break;
5837 }
5838 case BPF_JSLE:
5839 case BPF_JSLT:
5840 {
5841 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
5842 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
5843
5844 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
5845 break;
5846 false_reg->smax_value = min(false_reg->smax_value, false_smax);
5847 true_reg->smin_value = max(true_reg->smin_value, true_smin);
5848 break;
5849 }
5850 default:
5851 break;
5852 }
5853
5854 __reg_deduce_bounds(false_reg);
5855 __reg_deduce_bounds(true_reg);
5856 /* We might have learned some bits from the bounds. */
5857 __reg_bound_offset(false_reg);
5858 __reg_bound_offset(true_reg);
5859 /* Intersecting with the old var_off might have improved our bounds
5860 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5861 * then new var_off is (0; 0x7f...fc) which improves our umax.
5862 */
5863 __update_reg_bounds(false_reg);
5864 __update_reg_bounds(true_reg);
5865 }
5866
5867 /* 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)5868 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
5869 struct bpf_reg_state *dst_reg)
5870 {
5871 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
5872 dst_reg->umin_value);
5873 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
5874 dst_reg->umax_value);
5875 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
5876 dst_reg->smin_value);
5877 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
5878 dst_reg->smax_value);
5879 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
5880 dst_reg->var_off);
5881 /* We might have learned new bounds from the var_off. */
5882 __update_reg_bounds(src_reg);
5883 __update_reg_bounds(dst_reg);
5884 /* We might have learned something about the sign bit. */
5885 __reg_deduce_bounds(src_reg);
5886 __reg_deduce_bounds(dst_reg);
5887 /* We might have learned some bits from the bounds. */
5888 __reg_bound_offset(src_reg);
5889 __reg_bound_offset(dst_reg);
5890 /* Intersecting with the old var_off might have improved our bounds
5891 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
5892 * then new var_off is (0; 0x7f...fc) which improves our umax.
5893 */
5894 __update_reg_bounds(src_reg);
5895 __update_reg_bounds(dst_reg);
5896 }
5897
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)5898 static void reg_combine_min_max(struct bpf_reg_state *true_src,
5899 struct bpf_reg_state *true_dst,
5900 struct bpf_reg_state *false_src,
5901 struct bpf_reg_state *false_dst,
5902 u8 opcode)
5903 {
5904 switch (opcode) {
5905 case BPF_JEQ:
5906 __reg_combine_min_max(true_src, true_dst);
5907 break;
5908 case BPF_JNE:
5909 __reg_combine_min_max(false_src, false_dst);
5910 break;
5911 }
5912 }
5913
mark_ptr_or_null_reg(struct bpf_func_state * state,struct bpf_reg_state * reg,u32 id,bool is_null)5914 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
5915 struct bpf_reg_state *reg, u32 id,
5916 bool is_null)
5917 {
5918 if (reg_type_may_be_null(reg->type) && reg->id == id) {
5919 /* Old offset (both fixed and variable parts) should
5920 * have been known-zero, because we don't allow pointer
5921 * arithmetic on pointers that might be NULL.
5922 */
5923 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
5924 !tnum_equals_const(reg->var_off, 0) ||
5925 reg->off)) {
5926 __mark_reg_known_zero(reg);
5927 reg->off = 0;
5928 }
5929 if (is_null) {
5930 reg->type = SCALAR_VALUE;
5931 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
5932 if (reg->map_ptr->inner_map_meta) {
5933 reg->type = CONST_PTR_TO_MAP;
5934 reg->map_ptr = reg->map_ptr->inner_map_meta;
5935 } else if (reg->map_ptr->map_type ==
5936 BPF_MAP_TYPE_XSKMAP) {
5937 reg->type = PTR_TO_XDP_SOCK;
5938 } else {
5939 reg->type = PTR_TO_MAP_VALUE;
5940 }
5941 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) {
5942 reg->type = PTR_TO_SOCKET;
5943 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) {
5944 reg->type = PTR_TO_SOCK_COMMON;
5945 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) {
5946 reg->type = PTR_TO_TCP_SOCK;
5947 }
5948 if (is_null) {
5949 /* We don't need id and ref_obj_id from this point
5950 * onwards anymore, thus we should better reset it,
5951 * so that state pruning has chances to take effect.
5952 */
5953 reg->id = 0;
5954 reg->ref_obj_id = 0;
5955 } else if (!reg_may_point_to_spin_lock(reg)) {
5956 /* For not-NULL ptr, reg->ref_obj_id will be reset
5957 * in release_reg_references().
5958 *
5959 * reg->id is still used by spin_lock ptr. Other
5960 * than spin_lock ptr type, reg->id can be reset.
5961 */
5962 reg->id = 0;
5963 }
5964 }
5965 }
5966
__mark_ptr_or_null_regs(struct bpf_func_state * state,u32 id,bool is_null)5967 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
5968 bool is_null)
5969 {
5970 struct bpf_reg_state *reg;
5971 int i;
5972
5973 for (i = 0; i < MAX_BPF_REG; i++)
5974 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
5975
5976 bpf_for_each_spilled_reg(i, state, reg) {
5977 if (!reg)
5978 continue;
5979 mark_ptr_or_null_reg(state, reg, id, is_null);
5980 }
5981 }
5982
5983 /* The logic is similar to find_good_pkt_pointers(), both could eventually
5984 * be folded together at some point.
5985 */
mark_ptr_or_null_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)5986 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
5987 bool is_null)
5988 {
5989 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5990 struct bpf_reg_state *regs = state->regs;
5991 u32 ref_obj_id = regs[regno].ref_obj_id;
5992 u32 id = regs[regno].id;
5993 int i;
5994
5995 if (ref_obj_id && ref_obj_id == id && is_null)
5996 /* regs[regno] is in the " == NULL" branch.
5997 * No one could have freed the reference state before
5998 * doing the NULL check.
5999 */
6000 WARN_ON_ONCE(release_reference_state(state, id));
6001
6002 for (i = 0; i <= vstate->curframe; i++)
6003 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
6004 }
6005
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)6006 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
6007 struct bpf_reg_state *dst_reg,
6008 struct bpf_reg_state *src_reg,
6009 struct bpf_verifier_state *this_branch,
6010 struct bpf_verifier_state *other_branch)
6011 {
6012 if (BPF_SRC(insn->code) != BPF_X)
6013 return false;
6014
6015 /* Pointers are always 64-bit. */
6016 if (BPF_CLASS(insn->code) == BPF_JMP32)
6017 return false;
6018
6019 switch (BPF_OP(insn->code)) {
6020 case BPF_JGT:
6021 if ((dst_reg->type == PTR_TO_PACKET &&
6022 src_reg->type == PTR_TO_PACKET_END) ||
6023 (dst_reg->type == PTR_TO_PACKET_META &&
6024 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6025 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
6026 find_good_pkt_pointers(this_branch, dst_reg,
6027 dst_reg->type, false);
6028 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6029 src_reg->type == PTR_TO_PACKET) ||
6030 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6031 src_reg->type == PTR_TO_PACKET_META)) {
6032 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
6033 find_good_pkt_pointers(other_branch, src_reg,
6034 src_reg->type, true);
6035 } else {
6036 return false;
6037 }
6038 break;
6039 case BPF_JLT:
6040 if ((dst_reg->type == PTR_TO_PACKET &&
6041 src_reg->type == PTR_TO_PACKET_END) ||
6042 (dst_reg->type == PTR_TO_PACKET_META &&
6043 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6044 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
6045 find_good_pkt_pointers(other_branch, dst_reg,
6046 dst_reg->type, true);
6047 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6048 src_reg->type == PTR_TO_PACKET) ||
6049 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6050 src_reg->type == PTR_TO_PACKET_META)) {
6051 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
6052 find_good_pkt_pointers(this_branch, src_reg,
6053 src_reg->type, false);
6054 } else {
6055 return false;
6056 }
6057 break;
6058 case BPF_JGE:
6059 if ((dst_reg->type == PTR_TO_PACKET &&
6060 src_reg->type == PTR_TO_PACKET_END) ||
6061 (dst_reg->type == PTR_TO_PACKET_META &&
6062 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6063 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
6064 find_good_pkt_pointers(this_branch, dst_reg,
6065 dst_reg->type, true);
6066 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6067 src_reg->type == PTR_TO_PACKET) ||
6068 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6069 src_reg->type == PTR_TO_PACKET_META)) {
6070 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
6071 find_good_pkt_pointers(other_branch, src_reg,
6072 src_reg->type, false);
6073 } else {
6074 return false;
6075 }
6076 break;
6077 case BPF_JLE:
6078 if ((dst_reg->type == PTR_TO_PACKET &&
6079 src_reg->type == PTR_TO_PACKET_END) ||
6080 (dst_reg->type == PTR_TO_PACKET_META &&
6081 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
6082 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
6083 find_good_pkt_pointers(other_branch, dst_reg,
6084 dst_reg->type, false);
6085 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
6086 src_reg->type == PTR_TO_PACKET) ||
6087 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
6088 src_reg->type == PTR_TO_PACKET_META)) {
6089 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
6090 find_good_pkt_pointers(this_branch, src_reg,
6091 src_reg->type, true);
6092 } else {
6093 return false;
6094 }
6095 break;
6096 default:
6097 return false;
6098 }
6099
6100 return true;
6101 }
6102
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)6103 static int check_cond_jmp_op(struct bpf_verifier_env *env,
6104 struct bpf_insn *insn, int *insn_idx)
6105 {
6106 struct bpf_verifier_state *this_branch = env->cur_state;
6107 struct bpf_verifier_state *other_branch;
6108 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
6109 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
6110 u8 opcode = BPF_OP(insn->code);
6111 bool is_jmp32;
6112 int pred = -1;
6113 int err;
6114
6115 /* Only conditional jumps are expected to reach here. */
6116 if (opcode == BPF_JA || opcode > BPF_JSLE) {
6117 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
6118 return -EINVAL;
6119 }
6120
6121 if (BPF_SRC(insn->code) == BPF_X) {
6122 if (insn->imm != 0) {
6123 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6124 return -EINVAL;
6125 }
6126
6127 /* check src1 operand */
6128 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6129 if (err)
6130 return err;
6131
6132 if (is_pointer_value(env, insn->src_reg)) {
6133 verbose(env, "R%d pointer comparison prohibited\n",
6134 insn->src_reg);
6135 return -EACCES;
6136 }
6137 src_reg = ®s[insn->src_reg];
6138 } else {
6139 if (insn->src_reg != BPF_REG_0) {
6140 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
6141 return -EINVAL;
6142 }
6143 }
6144
6145 /* check src2 operand */
6146 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6147 if (err)
6148 return err;
6149
6150 dst_reg = ®s[insn->dst_reg];
6151 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
6152
6153 if (BPF_SRC(insn->code) == BPF_K)
6154 pred = is_branch_taken(dst_reg, insn->imm,
6155 opcode, is_jmp32);
6156 else if (src_reg->type == SCALAR_VALUE &&
6157 tnum_is_const(src_reg->var_off))
6158 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
6159 opcode, is_jmp32);
6160 if (pred >= 0) {
6161 err = mark_chain_precision(env, insn->dst_reg);
6162 if (BPF_SRC(insn->code) == BPF_X && !err)
6163 err = mark_chain_precision(env, insn->src_reg);
6164 if (err)
6165 return err;
6166 }
6167
6168 if (pred == 1) {
6169 /* Only follow the goto, ignore fall-through. If needed, push
6170 * the fall-through branch for simulation under speculative
6171 * execution.
6172 */
6173 if (!env->allow_ptr_leaks &&
6174 !sanitize_speculative_path(env, insn, *insn_idx + 1,
6175 *insn_idx))
6176 return -EFAULT;
6177 *insn_idx += insn->off;
6178 return 0;
6179 } else if (pred == 0) {
6180 /* Only follow the fall-through branch, since that's where the
6181 * program will go. If needed, push the goto branch for
6182 * simulation under speculative execution.
6183 */
6184 if (!env->allow_ptr_leaks &&
6185 !sanitize_speculative_path(env, insn,
6186 *insn_idx + insn->off + 1,
6187 *insn_idx))
6188 return -EFAULT;
6189 return 0;
6190 }
6191
6192 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
6193 false);
6194 if (!other_branch)
6195 return -EFAULT;
6196 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
6197
6198 /* detect if we are comparing against a constant value so we can adjust
6199 * our min/max values for our dst register.
6200 * this is only legit if both are scalars (or pointers to the same
6201 * object, I suppose, but we don't support that right now), because
6202 * otherwise the different base pointers mean the offsets aren't
6203 * comparable.
6204 */
6205 if (BPF_SRC(insn->code) == BPF_X) {
6206 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
6207 struct bpf_reg_state lo_reg0 = *dst_reg;
6208 struct bpf_reg_state lo_reg1 = *src_reg;
6209 struct bpf_reg_state *src_lo, *dst_lo;
6210
6211 dst_lo = &lo_reg0;
6212 src_lo = &lo_reg1;
6213 coerce_reg_to_size(dst_lo, 4);
6214 coerce_reg_to_size(src_lo, 4);
6215
6216 if (dst_reg->type == SCALAR_VALUE &&
6217 src_reg->type == SCALAR_VALUE) {
6218 if (tnum_is_const(src_reg->var_off) ||
6219 (is_jmp32 && tnum_is_const(src_lo->var_off)))
6220 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6221 dst_reg,
6222 is_jmp32
6223 ? src_lo->var_off.value
6224 : src_reg->var_off.value,
6225 opcode, is_jmp32);
6226 else if (tnum_is_const(dst_reg->var_off) ||
6227 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
6228 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
6229 src_reg,
6230 is_jmp32
6231 ? dst_lo->var_off.value
6232 : dst_reg->var_off.value,
6233 opcode, is_jmp32);
6234 else if (!is_jmp32 &&
6235 (opcode == BPF_JEQ || opcode == BPF_JNE))
6236 /* Comparing for equality, we can combine knowledge */
6237 reg_combine_min_max(&other_branch_regs[insn->src_reg],
6238 &other_branch_regs[insn->dst_reg],
6239 src_reg, dst_reg, opcode);
6240 }
6241 } else if (dst_reg->type == SCALAR_VALUE) {
6242 reg_set_min_max(&other_branch_regs[insn->dst_reg],
6243 dst_reg, insn->imm, opcode, is_jmp32);
6244 }
6245
6246 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
6247 * NOTE: these optimizations below are related with pointer comparison
6248 * which will never be JMP32.
6249 */
6250 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
6251 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
6252 reg_type_may_be_null(dst_reg->type)) {
6253 /* Mark all identical registers in each branch as either
6254 * safe or unknown depending R == 0 or R != 0 conditional.
6255 */
6256 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
6257 opcode == BPF_JNE);
6258 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
6259 opcode == BPF_JEQ);
6260 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
6261 this_branch, other_branch) &&
6262 is_pointer_value(env, insn->dst_reg)) {
6263 verbose(env, "R%d pointer comparison prohibited\n",
6264 insn->dst_reg);
6265 return -EACCES;
6266 }
6267 if (env->log.level & BPF_LOG_LEVEL)
6268 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
6269 return 0;
6270 }
6271
6272 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)6273 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
6274 {
6275 struct bpf_insn_aux_data *aux = cur_aux(env);
6276 struct bpf_reg_state *regs = cur_regs(env);
6277 struct bpf_map *map;
6278 int err;
6279
6280 if (BPF_SIZE(insn->code) != BPF_DW) {
6281 verbose(env, "invalid BPF_LD_IMM insn\n");
6282 return -EINVAL;
6283 }
6284 if (insn->off != 0) {
6285 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
6286 return -EINVAL;
6287 }
6288
6289 err = check_reg_arg(env, insn->dst_reg, DST_OP);
6290 if (err)
6291 return err;
6292
6293 if (insn->src_reg == 0) {
6294 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
6295
6296 regs[insn->dst_reg].type = SCALAR_VALUE;
6297 __mark_reg_known(®s[insn->dst_reg], imm);
6298 return 0;
6299 }
6300
6301 map = env->used_maps[aux->map_index];
6302 mark_reg_known_zero(env, regs, insn->dst_reg);
6303 regs[insn->dst_reg].map_ptr = map;
6304
6305 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
6306 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
6307 regs[insn->dst_reg].off = aux->map_off;
6308 if (map_value_has_spin_lock(map))
6309 regs[insn->dst_reg].id = ++env->id_gen;
6310 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
6311 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
6312 } else {
6313 verbose(env, "bpf verifier is misconfigured\n");
6314 return -EINVAL;
6315 }
6316
6317 return 0;
6318 }
6319
may_access_skb(enum bpf_prog_type type)6320 static bool may_access_skb(enum bpf_prog_type type)
6321 {
6322 switch (type) {
6323 case BPF_PROG_TYPE_SOCKET_FILTER:
6324 case BPF_PROG_TYPE_SCHED_CLS:
6325 case BPF_PROG_TYPE_SCHED_ACT:
6326 return true;
6327 default:
6328 return false;
6329 }
6330 }
6331
6332 /* verify safety of LD_ABS|LD_IND instructions:
6333 * - they can only appear in the programs where ctx == skb
6334 * - since they are wrappers of function calls, they scratch R1-R5 registers,
6335 * preserve R6-R9, and store return value into R0
6336 *
6337 * Implicit input:
6338 * ctx == skb == R6 == CTX
6339 *
6340 * Explicit input:
6341 * SRC == any register
6342 * IMM == 32-bit immediate
6343 *
6344 * Output:
6345 * R0 - 8/16/32-bit skb data converted to cpu endianness
6346 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)6347 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
6348 {
6349 struct bpf_reg_state *regs = cur_regs(env);
6350 static const int ctx_reg = BPF_REG_6;
6351 u8 mode = BPF_MODE(insn->code);
6352 int i, err;
6353
6354 if (!may_access_skb(env->prog->type)) {
6355 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
6356 return -EINVAL;
6357 }
6358
6359 if (!env->ops->gen_ld_abs) {
6360 verbose(env, "bpf verifier is misconfigured\n");
6361 return -EINVAL;
6362 }
6363
6364 if (env->subprog_cnt > 1) {
6365 /* when program has LD_ABS insn JITs and interpreter assume
6366 * that r1 == ctx == skb which is not the case for callees
6367 * that can have arbitrary arguments. It's problematic
6368 * for main prog as well since JITs would need to analyze
6369 * all functions in order to make proper register save/restore
6370 * decisions in the main prog. Hence disallow LD_ABS with calls
6371 */
6372 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
6373 return -EINVAL;
6374 }
6375
6376 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
6377 BPF_SIZE(insn->code) == BPF_DW ||
6378 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
6379 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
6380 return -EINVAL;
6381 }
6382
6383 /* check whether implicit source operand (register R6) is readable */
6384 err = check_reg_arg(env, ctx_reg, SRC_OP);
6385 if (err)
6386 return err;
6387
6388 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
6389 * gen_ld_abs() may terminate the program at runtime, leading to
6390 * reference leak.
6391 */
6392 err = check_reference_leak(env);
6393 if (err) {
6394 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
6395 return err;
6396 }
6397
6398 if (env->cur_state->active_spin_lock) {
6399 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
6400 return -EINVAL;
6401 }
6402
6403 if (regs[ctx_reg].type != PTR_TO_CTX) {
6404 verbose(env,
6405 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
6406 return -EINVAL;
6407 }
6408
6409 if (mode == BPF_IND) {
6410 /* check explicit source operand */
6411 err = check_reg_arg(env, insn->src_reg, SRC_OP);
6412 if (err)
6413 return err;
6414 }
6415
6416 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
6417 if (err < 0)
6418 return err;
6419
6420 /* reset caller saved regs to unreadable */
6421 for (i = 0; i < CALLER_SAVED_REGS; i++) {
6422 mark_reg_not_init(env, regs, caller_saved[i]);
6423 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6424 }
6425
6426 /* mark destination R0 register as readable, since it contains
6427 * the value fetched from the packet.
6428 * Already marked as written above.
6429 */
6430 mark_reg_unknown(env, regs, BPF_REG_0);
6431 /* ld_abs load up to 32-bit skb data. */
6432 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
6433 return 0;
6434 }
6435
check_return_code(struct bpf_verifier_env * env)6436 static int check_return_code(struct bpf_verifier_env *env)
6437 {
6438 struct tnum enforce_attach_type_range = tnum_unknown;
6439 struct bpf_reg_state *reg;
6440 struct tnum range = tnum_range(0, 1);
6441
6442 switch (env->prog->type) {
6443 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
6444 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
6445 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
6446 range = tnum_range(1, 1);
6447 break;
6448 case BPF_PROG_TYPE_CGROUP_SKB:
6449 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
6450 range = tnum_range(0, 3);
6451 enforce_attach_type_range = tnum_range(2, 3);
6452 }
6453 break;
6454 case BPF_PROG_TYPE_CGROUP_SOCK:
6455 case BPF_PROG_TYPE_SOCK_OPS:
6456 case BPF_PROG_TYPE_CGROUP_DEVICE:
6457 case BPF_PROG_TYPE_CGROUP_SYSCTL:
6458 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
6459 break;
6460 default:
6461 return 0;
6462 }
6463
6464 reg = cur_regs(env) + BPF_REG_0;
6465 if (reg->type != SCALAR_VALUE) {
6466 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
6467 reg_type_str[reg->type]);
6468 return -EINVAL;
6469 }
6470
6471 if (!tnum_in(range, reg->var_off)) {
6472 char tn_buf[48];
6473
6474 verbose(env, "At program exit the register R0 ");
6475 if (!tnum_is_unknown(reg->var_off)) {
6476 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6477 verbose(env, "has value %s", tn_buf);
6478 } else {
6479 verbose(env, "has unknown scalar value");
6480 }
6481 tnum_strn(tn_buf, sizeof(tn_buf), range);
6482 verbose(env, " should have been in %s\n", tn_buf);
6483 return -EINVAL;
6484 }
6485
6486 if (!tnum_is_unknown(enforce_attach_type_range) &&
6487 tnum_in(enforce_attach_type_range, reg->var_off))
6488 env->prog->enforce_expected_attach_type = 1;
6489 return 0;
6490 }
6491
6492 /* non-recursive DFS pseudo code
6493 * 1 procedure DFS-iterative(G,v):
6494 * 2 label v as discovered
6495 * 3 let S be a stack
6496 * 4 S.push(v)
6497 * 5 while S is not empty
6498 * 6 t <- S.pop()
6499 * 7 if t is what we're looking for:
6500 * 8 return t
6501 * 9 for all edges e in G.adjacentEdges(t) do
6502 * 10 if edge e is already labelled
6503 * 11 continue with the next edge
6504 * 12 w <- G.adjacentVertex(t,e)
6505 * 13 if vertex w is not discovered and not explored
6506 * 14 label e as tree-edge
6507 * 15 label w as discovered
6508 * 16 S.push(w)
6509 * 17 continue at 5
6510 * 18 else if vertex w is discovered
6511 * 19 label e as back-edge
6512 * 20 else
6513 * 21 // vertex w is explored
6514 * 22 label e as forward- or cross-edge
6515 * 23 label t as explored
6516 * 24 S.pop()
6517 *
6518 * convention:
6519 * 0x10 - discovered
6520 * 0x11 - discovered and fall-through edge labelled
6521 * 0x12 - discovered and fall-through and branch edges labelled
6522 * 0x20 - explored
6523 */
6524
6525 enum {
6526 DISCOVERED = 0x10,
6527 EXPLORED = 0x20,
6528 FALLTHROUGH = 1,
6529 BRANCH = 2,
6530 };
6531
state_htab_size(struct bpf_verifier_env * env)6532 static u32 state_htab_size(struct bpf_verifier_env *env)
6533 {
6534 return env->prog->len;
6535 }
6536
explored_state(struct bpf_verifier_env * env,int idx)6537 static struct bpf_verifier_state_list **explored_state(
6538 struct bpf_verifier_env *env,
6539 int idx)
6540 {
6541 struct bpf_verifier_state *cur = env->cur_state;
6542 struct bpf_func_state *state = cur->frame[cur->curframe];
6543
6544 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
6545 }
6546
init_explored_state(struct bpf_verifier_env * env,int idx)6547 static void init_explored_state(struct bpf_verifier_env *env, int idx)
6548 {
6549 env->insn_aux_data[idx].prune_point = true;
6550 }
6551
6552 /* t, w, e - match pseudo-code above:
6553 * t - index of current instruction
6554 * w - next instruction
6555 * e - edge
6556 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env,bool loop_ok)6557 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
6558 bool loop_ok)
6559 {
6560 int *insn_stack = env->cfg.insn_stack;
6561 int *insn_state = env->cfg.insn_state;
6562
6563 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
6564 return 0;
6565
6566 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
6567 return 0;
6568
6569 if (w < 0 || w >= env->prog->len) {
6570 verbose_linfo(env, t, "%d: ", t);
6571 verbose(env, "jump out of range from insn %d to %d\n", t, w);
6572 return -EINVAL;
6573 }
6574
6575 if (e == BRANCH)
6576 /* mark branch target for state pruning */
6577 init_explored_state(env, w);
6578
6579 if (insn_state[w] == 0) {
6580 /* tree-edge */
6581 insn_state[t] = DISCOVERED | e;
6582 insn_state[w] = DISCOVERED;
6583 if (env->cfg.cur_stack >= env->prog->len)
6584 return -E2BIG;
6585 insn_stack[env->cfg.cur_stack++] = w;
6586 return 1;
6587 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
6588 if (loop_ok && env->allow_ptr_leaks)
6589 return 0;
6590 verbose_linfo(env, t, "%d: ", t);
6591 verbose_linfo(env, w, "%d: ", w);
6592 verbose(env, "back-edge from insn %d to %d\n", t, w);
6593 return -EINVAL;
6594 } else if (insn_state[w] == EXPLORED) {
6595 /* forward- or cross-edge */
6596 insn_state[t] = DISCOVERED | e;
6597 } else {
6598 verbose(env, "insn state internal bug\n");
6599 return -EFAULT;
6600 }
6601 return 0;
6602 }
6603
6604 /* non-recursive depth-first-search to detect loops in BPF program
6605 * loop == back-edge in directed graph
6606 */
check_cfg(struct bpf_verifier_env * env)6607 static int check_cfg(struct bpf_verifier_env *env)
6608 {
6609 struct bpf_insn *insns = env->prog->insnsi;
6610 int insn_cnt = env->prog->len;
6611 int *insn_stack, *insn_state;
6612 int ret = 0;
6613 int i, t;
6614
6615 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
6616 if (!insn_state)
6617 return -ENOMEM;
6618
6619 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
6620 if (!insn_stack) {
6621 kvfree(insn_state);
6622 return -ENOMEM;
6623 }
6624
6625 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
6626 insn_stack[0] = 0; /* 0 is the first instruction */
6627 env->cfg.cur_stack = 1;
6628
6629 peek_stack:
6630 if (env->cfg.cur_stack == 0)
6631 goto check_state;
6632 t = insn_stack[env->cfg.cur_stack - 1];
6633
6634 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
6635 BPF_CLASS(insns[t].code) == BPF_JMP32) {
6636 u8 opcode = BPF_OP(insns[t].code);
6637
6638 if (opcode == BPF_EXIT) {
6639 goto mark_explored;
6640 } else if (opcode == BPF_CALL) {
6641 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
6642 if (ret == 1)
6643 goto peek_stack;
6644 else if (ret < 0)
6645 goto err_free;
6646 if (t + 1 < insn_cnt)
6647 init_explored_state(env, t + 1);
6648 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
6649 init_explored_state(env, t);
6650 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
6651 env, false);
6652 if (ret == 1)
6653 goto peek_stack;
6654 else if (ret < 0)
6655 goto err_free;
6656 }
6657 } else if (opcode == BPF_JA) {
6658 if (BPF_SRC(insns[t].code) != BPF_K) {
6659 ret = -EINVAL;
6660 goto err_free;
6661 }
6662 /* unconditional jump with single edge */
6663 ret = push_insn(t, t + insns[t].off + 1,
6664 FALLTHROUGH, env, true);
6665 if (ret == 1)
6666 goto peek_stack;
6667 else if (ret < 0)
6668 goto err_free;
6669 /* unconditional jmp is not a good pruning point,
6670 * but it's marked, since backtracking needs
6671 * to record jmp history in is_state_visited().
6672 */
6673 init_explored_state(env, t + insns[t].off + 1);
6674 /* tell verifier to check for equivalent states
6675 * after every call and jump
6676 */
6677 if (t + 1 < insn_cnt)
6678 init_explored_state(env, t + 1);
6679 } else {
6680 /* conditional jump with two edges */
6681 init_explored_state(env, t);
6682 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
6683 if (ret == 1)
6684 goto peek_stack;
6685 else if (ret < 0)
6686 goto err_free;
6687
6688 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
6689 if (ret == 1)
6690 goto peek_stack;
6691 else if (ret < 0)
6692 goto err_free;
6693 }
6694 } else {
6695 /* all other non-branch instructions with single
6696 * fall-through edge
6697 */
6698 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
6699 if (ret == 1)
6700 goto peek_stack;
6701 else if (ret < 0)
6702 goto err_free;
6703 }
6704
6705 mark_explored:
6706 insn_state[t] = EXPLORED;
6707 if (env->cfg.cur_stack-- <= 0) {
6708 verbose(env, "pop stack internal bug\n");
6709 ret = -EFAULT;
6710 goto err_free;
6711 }
6712 goto peek_stack;
6713
6714 check_state:
6715 for (i = 0; i < insn_cnt; i++) {
6716 if (insn_state[i] != EXPLORED) {
6717 verbose(env, "unreachable insn %d\n", i);
6718 ret = -EINVAL;
6719 goto err_free;
6720 }
6721 }
6722 ret = 0; /* cfg looks good */
6723
6724 err_free:
6725 kvfree(insn_state);
6726 kvfree(insn_stack);
6727 env->cfg.insn_state = env->cfg.insn_stack = NULL;
6728 return ret;
6729 }
6730
6731 /* The minimum supported BTF func info size */
6732 #define MIN_BPF_FUNCINFO_SIZE 8
6733 #define MAX_FUNCINFO_REC_SIZE 252
6734
check_btf_func(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)6735 static int check_btf_func(struct bpf_verifier_env *env,
6736 const union bpf_attr *attr,
6737 union bpf_attr __user *uattr)
6738 {
6739 u32 i, nfuncs, urec_size, min_size;
6740 u32 krec_size = sizeof(struct bpf_func_info);
6741 struct bpf_func_info *krecord;
6742 const struct btf_type *type;
6743 struct bpf_prog *prog;
6744 const struct btf *btf;
6745 void __user *urecord;
6746 u32 prev_offset = 0;
6747 int ret = 0;
6748
6749 nfuncs = attr->func_info_cnt;
6750 if (!nfuncs)
6751 return 0;
6752
6753 if (nfuncs != env->subprog_cnt) {
6754 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
6755 return -EINVAL;
6756 }
6757
6758 urec_size = attr->func_info_rec_size;
6759 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
6760 urec_size > MAX_FUNCINFO_REC_SIZE ||
6761 urec_size % sizeof(u32)) {
6762 verbose(env, "invalid func info rec size %u\n", urec_size);
6763 return -EINVAL;
6764 }
6765
6766 prog = env->prog;
6767 btf = prog->aux->btf;
6768
6769 urecord = u64_to_user_ptr(attr->func_info);
6770 min_size = min_t(u32, krec_size, urec_size);
6771
6772 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
6773 if (!krecord)
6774 return -ENOMEM;
6775
6776 for (i = 0; i < nfuncs; i++) {
6777 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
6778 if (ret) {
6779 if (ret == -E2BIG) {
6780 verbose(env, "nonzero tailing record in func info");
6781 /* set the size kernel expects so loader can zero
6782 * out the rest of the record.
6783 */
6784 if (put_user(min_size, &uattr->func_info_rec_size))
6785 ret = -EFAULT;
6786 }
6787 goto err_free;
6788 }
6789
6790 if (copy_from_user(&krecord[i], urecord, min_size)) {
6791 ret = -EFAULT;
6792 goto err_free;
6793 }
6794
6795 /* check insn_off */
6796 if (i == 0) {
6797 if (krecord[i].insn_off) {
6798 verbose(env,
6799 "nonzero insn_off %u for the first func info record",
6800 krecord[i].insn_off);
6801 ret = -EINVAL;
6802 goto err_free;
6803 }
6804 } else if (krecord[i].insn_off <= prev_offset) {
6805 verbose(env,
6806 "same or smaller insn offset (%u) than previous func info record (%u)",
6807 krecord[i].insn_off, prev_offset);
6808 ret = -EINVAL;
6809 goto err_free;
6810 }
6811
6812 if (env->subprog_info[i].start != krecord[i].insn_off) {
6813 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
6814 ret = -EINVAL;
6815 goto err_free;
6816 }
6817
6818 /* check type_id */
6819 type = btf_type_by_id(btf, krecord[i].type_id);
6820 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) {
6821 verbose(env, "invalid type id %d in func info",
6822 krecord[i].type_id);
6823 ret = -EINVAL;
6824 goto err_free;
6825 }
6826
6827 prev_offset = krecord[i].insn_off;
6828 urecord += urec_size;
6829 }
6830
6831 prog->aux->func_info = krecord;
6832 prog->aux->func_info_cnt = nfuncs;
6833 return 0;
6834
6835 err_free:
6836 kvfree(krecord);
6837 return ret;
6838 }
6839
adjust_btf_func(struct bpf_verifier_env * env)6840 static void adjust_btf_func(struct bpf_verifier_env *env)
6841 {
6842 int i;
6843
6844 if (!env->prog->aux->func_info)
6845 return;
6846
6847 for (i = 0; i < env->subprog_cnt; i++)
6848 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start;
6849 }
6850
6851 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
6852 sizeof(((struct bpf_line_info *)(0))->line_col))
6853 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
6854
check_btf_line(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)6855 static int check_btf_line(struct bpf_verifier_env *env,
6856 const union bpf_attr *attr,
6857 union bpf_attr __user *uattr)
6858 {
6859 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
6860 struct bpf_subprog_info *sub;
6861 struct bpf_line_info *linfo;
6862 struct bpf_prog *prog;
6863 const struct btf *btf;
6864 void __user *ulinfo;
6865 int err;
6866
6867 nr_linfo = attr->line_info_cnt;
6868 if (!nr_linfo)
6869 return 0;
6870 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
6871 return -EINVAL;
6872
6873 rec_size = attr->line_info_rec_size;
6874 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
6875 rec_size > MAX_LINEINFO_REC_SIZE ||
6876 rec_size & (sizeof(u32) - 1))
6877 return -EINVAL;
6878
6879 /* Need to zero it in case the userspace may
6880 * pass in a smaller bpf_line_info object.
6881 */
6882 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
6883 GFP_KERNEL | __GFP_NOWARN);
6884 if (!linfo)
6885 return -ENOMEM;
6886
6887 prog = env->prog;
6888 btf = prog->aux->btf;
6889
6890 s = 0;
6891 sub = env->subprog_info;
6892 ulinfo = u64_to_user_ptr(attr->line_info);
6893 expected_size = sizeof(struct bpf_line_info);
6894 ncopy = min_t(u32, expected_size, rec_size);
6895 for (i = 0; i < nr_linfo; i++) {
6896 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
6897 if (err) {
6898 if (err == -E2BIG) {
6899 verbose(env, "nonzero tailing record in line_info");
6900 if (put_user(expected_size,
6901 &uattr->line_info_rec_size))
6902 err = -EFAULT;
6903 }
6904 goto err_free;
6905 }
6906
6907 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
6908 err = -EFAULT;
6909 goto err_free;
6910 }
6911
6912 /*
6913 * Check insn_off to ensure
6914 * 1) strictly increasing AND
6915 * 2) bounded by prog->len
6916 *
6917 * The linfo[0].insn_off == 0 check logically falls into
6918 * the later "missing bpf_line_info for func..." case
6919 * because the first linfo[0].insn_off must be the
6920 * first sub also and the first sub must have
6921 * subprog_info[0].start == 0.
6922 */
6923 if ((i && linfo[i].insn_off <= prev_offset) ||
6924 linfo[i].insn_off >= prog->len) {
6925 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
6926 i, linfo[i].insn_off, prev_offset,
6927 prog->len);
6928 err = -EINVAL;
6929 goto err_free;
6930 }
6931
6932 if (!prog->insnsi[linfo[i].insn_off].code) {
6933 verbose(env,
6934 "Invalid insn code at line_info[%u].insn_off\n",
6935 i);
6936 err = -EINVAL;
6937 goto err_free;
6938 }
6939
6940 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
6941 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
6942 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
6943 err = -EINVAL;
6944 goto err_free;
6945 }
6946
6947 if (s != env->subprog_cnt) {
6948 if (linfo[i].insn_off == sub[s].start) {
6949 sub[s].linfo_idx = i;
6950 s++;
6951 } else if (sub[s].start < linfo[i].insn_off) {
6952 verbose(env, "missing bpf_line_info for func#%u\n", s);
6953 err = -EINVAL;
6954 goto err_free;
6955 }
6956 }
6957
6958 prev_offset = linfo[i].insn_off;
6959 ulinfo += rec_size;
6960 }
6961
6962 if (s != env->subprog_cnt) {
6963 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
6964 env->subprog_cnt - s, s);
6965 err = -EINVAL;
6966 goto err_free;
6967 }
6968
6969 prog->aux->linfo = linfo;
6970 prog->aux->nr_linfo = nr_linfo;
6971
6972 return 0;
6973
6974 err_free:
6975 kvfree(linfo);
6976 return err;
6977 }
6978
check_btf_info(struct bpf_verifier_env * env,const union bpf_attr * attr,union bpf_attr __user * uattr)6979 static int check_btf_info(struct bpf_verifier_env *env,
6980 const union bpf_attr *attr,
6981 union bpf_attr __user *uattr)
6982 {
6983 struct btf *btf;
6984 int err;
6985
6986 if (!attr->func_info_cnt && !attr->line_info_cnt)
6987 return 0;
6988
6989 btf = btf_get_by_fd(attr->prog_btf_fd);
6990 if (IS_ERR(btf))
6991 return PTR_ERR(btf);
6992 env->prog->aux->btf = btf;
6993
6994 err = check_btf_func(env, attr, uattr);
6995 if (err)
6996 return err;
6997
6998 err = check_btf_line(env, attr, uattr);
6999 if (err)
7000 return err;
7001
7002 return 0;
7003 }
7004
7005 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)7006 static bool range_within(struct bpf_reg_state *old,
7007 struct bpf_reg_state *cur)
7008 {
7009 return old->umin_value <= cur->umin_value &&
7010 old->umax_value >= cur->umax_value &&
7011 old->smin_value <= cur->smin_value &&
7012 old->smax_value >= cur->smax_value;
7013 }
7014
7015 /* If in the old state two registers had the same id, then they need to have
7016 * the same id in the new state as well. But that id could be different from
7017 * the old state, so we need to track the mapping from old to new ids.
7018 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
7019 * regs with old id 5 must also have new id 9 for the new state to be safe. But
7020 * regs with a different old id could still have new id 9, we don't care about
7021 * that.
7022 * So we look through our idmap to see if this old id has been seen before. If
7023 * so, we require the new id to match; otherwise, we add the id pair to the map.
7024 */
check_ids(u32 old_id,u32 cur_id,struct bpf_id_pair * idmap)7025 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
7026 {
7027 unsigned int i;
7028
7029 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
7030 if (!idmap[i].old) {
7031 /* Reached an empty slot; haven't seen this id before */
7032 idmap[i].old = old_id;
7033 idmap[i].cur = cur_id;
7034 return true;
7035 }
7036 if (idmap[i].old == old_id)
7037 return idmap[i].cur == cur_id;
7038 }
7039 /* We ran out of idmap slots, which should be impossible */
7040 WARN_ON_ONCE(1);
7041 return false;
7042 }
7043
clean_func_state(struct bpf_verifier_env * env,struct bpf_func_state * st)7044 static void clean_func_state(struct bpf_verifier_env *env,
7045 struct bpf_func_state *st)
7046 {
7047 enum bpf_reg_liveness live;
7048 int i, j;
7049
7050 for (i = 0; i < BPF_REG_FP; i++) {
7051 live = st->regs[i].live;
7052 /* liveness must not touch this register anymore */
7053 st->regs[i].live |= REG_LIVE_DONE;
7054 if (!(live & REG_LIVE_READ))
7055 /* since the register is unused, clear its state
7056 * to make further comparison simpler
7057 */
7058 __mark_reg_not_init(env, &st->regs[i]);
7059 }
7060
7061 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
7062 live = st->stack[i].spilled_ptr.live;
7063 /* liveness must not touch this stack slot anymore */
7064 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
7065 if (!(live & REG_LIVE_READ)) {
7066 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
7067 for (j = 0; j < BPF_REG_SIZE; j++)
7068 st->stack[i].slot_type[j] = STACK_INVALID;
7069 }
7070 }
7071 }
7072
clean_verifier_state(struct bpf_verifier_env * env,struct bpf_verifier_state * st)7073 static void clean_verifier_state(struct bpf_verifier_env *env,
7074 struct bpf_verifier_state *st)
7075 {
7076 int i;
7077
7078 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
7079 /* all regs in this state in all frames were already marked */
7080 return;
7081
7082 for (i = 0; i <= st->curframe; i++)
7083 clean_func_state(env, st->frame[i]);
7084 }
7085
7086 /* the parentage chains form a tree.
7087 * the verifier states are added to state lists at given insn and
7088 * pushed into state stack for future exploration.
7089 * when the verifier reaches bpf_exit insn some of the verifer states
7090 * stored in the state lists have their final liveness state already,
7091 * but a lot of states will get revised from liveness point of view when
7092 * the verifier explores other branches.
7093 * Example:
7094 * 1: r0 = 1
7095 * 2: if r1 == 100 goto pc+1
7096 * 3: r0 = 2
7097 * 4: exit
7098 * when the verifier reaches exit insn the register r0 in the state list of
7099 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
7100 * of insn 2 and goes exploring further. At the insn 4 it will walk the
7101 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
7102 *
7103 * Since the verifier pushes the branch states as it sees them while exploring
7104 * the program the condition of walking the branch instruction for the second
7105 * time means that all states below this branch were already explored and
7106 * their final liveness markes are already propagated.
7107 * Hence when the verifier completes the search of state list in is_state_visited()
7108 * we can call this clean_live_states() function to mark all liveness states
7109 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
7110 * will not be used.
7111 * This function also clears the registers and stack for states that !READ
7112 * to simplify state merging.
7113 *
7114 * Important note here that walking the same branch instruction in the callee
7115 * doesn't meant that the states are DONE. The verifier has to compare
7116 * the callsites
7117 */
clean_live_states(struct bpf_verifier_env * env,int insn,struct bpf_verifier_state * cur)7118 static void clean_live_states(struct bpf_verifier_env *env, int insn,
7119 struct bpf_verifier_state *cur)
7120 {
7121 struct bpf_verifier_state_list *sl;
7122 int i;
7123
7124 sl = *explored_state(env, insn);
7125 while (sl) {
7126 if (sl->state.branches)
7127 goto next;
7128 if (sl->state.insn_idx != insn ||
7129 sl->state.curframe != cur->curframe)
7130 goto next;
7131 for (i = 0; i <= cur->curframe; i++)
7132 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
7133 goto next;
7134 clean_verifier_state(env, &sl->state);
7135 next:
7136 sl = sl->next;
7137 }
7138 }
7139
7140 /* 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)7141 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
7142 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
7143 {
7144 bool equal;
7145
7146 if (!(rold->live & REG_LIVE_READ))
7147 /* explored state didn't use this */
7148 return true;
7149
7150 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
7151
7152 if (rold->type == PTR_TO_STACK)
7153 /* two stack pointers are equal only if they're pointing to
7154 * the same stack frame, since fp-8 in foo != fp-8 in bar
7155 */
7156 return equal && rold->frameno == rcur->frameno;
7157
7158 if (equal)
7159 return true;
7160
7161 if (rold->type == NOT_INIT)
7162 /* explored state can't have used this */
7163 return true;
7164 if (rcur->type == NOT_INIT)
7165 return false;
7166 switch (rold->type) {
7167 case SCALAR_VALUE:
7168 if (env->explore_alu_limits)
7169 return false;
7170 if (rcur->type == SCALAR_VALUE) {
7171 if (!rold->precise && !rcur->precise)
7172 return true;
7173 /* new val must satisfy old val knowledge */
7174 return range_within(rold, rcur) &&
7175 tnum_in(rold->var_off, rcur->var_off);
7176 } else {
7177 /* We're trying to use a pointer in place of a scalar.
7178 * Even if the scalar was unbounded, this could lead to
7179 * pointer leaks because scalars are allowed to leak
7180 * while pointers are not. We could make this safe in
7181 * special cases if root is calling us, but it's
7182 * probably not worth the hassle.
7183 */
7184 return false;
7185 }
7186 case PTR_TO_MAP_VALUE:
7187 /* If the new min/max/var_off satisfy the old ones and
7188 * everything else matches, we are OK.
7189 * 'id' is not compared, since it's only used for maps with
7190 * bpf_spin_lock inside map element and in such cases if
7191 * the rest of the prog is valid for one map element then
7192 * it's valid for all map elements regardless of the key
7193 * used in bpf_map_lookup()
7194 */
7195 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
7196 range_within(rold, rcur) &&
7197 tnum_in(rold->var_off, rcur->var_off);
7198 case PTR_TO_MAP_VALUE_OR_NULL:
7199 /* a PTR_TO_MAP_VALUE could be safe to use as a
7200 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
7201 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
7202 * checked, doing so could have affected others with the same
7203 * id, and we can't check for that because we lost the id when
7204 * we converted to a PTR_TO_MAP_VALUE.
7205 */
7206 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
7207 return false;
7208 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
7209 return false;
7210 /* Check our ids match any regs they're supposed to */
7211 return check_ids(rold->id, rcur->id, idmap);
7212 case PTR_TO_PACKET_META:
7213 case PTR_TO_PACKET:
7214 if (rcur->type != rold->type)
7215 return false;
7216 /* We must have at least as much range as the old ptr
7217 * did, so that any accesses which were safe before are
7218 * still safe. This is true even if old range < old off,
7219 * since someone could have accessed through (ptr - k), or
7220 * even done ptr -= k in a register, to get a safe access.
7221 */
7222 if (rold->range > rcur->range)
7223 return false;
7224 /* If the offsets don't match, we can't trust our alignment;
7225 * nor can we be sure that we won't fall out of range.
7226 */
7227 if (rold->off != rcur->off)
7228 return false;
7229 /* id relations must be preserved */
7230 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
7231 return false;
7232 /* new val must satisfy old val knowledge */
7233 return range_within(rold, rcur) &&
7234 tnum_in(rold->var_off, rcur->var_off);
7235 case PTR_TO_CTX:
7236 case CONST_PTR_TO_MAP:
7237 case PTR_TO_PACKET_END:
7238 case PTR_TO_FLOW_KEYS:
7239 case PTR_TO_SOCKET:
7240 case PTR_TO_SOCKET_OR_NULL:
7241 case PTR_TO_SOCK_COMMON:
7242 case PTR_TO_SOCK_COMMON_OR_NULL:
7243 case PTR_TO_TCP_SOCK:
7244 case PTR_TO_TCP_SOCK_OR_NULL:
7245 case PTR_TO_XDP_SOCK:
7246 /* Only valid matches are exact, which memcmp() above
7247 * would have accepted
7248 */
7249 default:
7250 /* Don't know what's going on, just say it's not safe */
7251 return false;
7252 }
7253
7254 /* Shouldn't get here; if we do, say it's not safe */
7255 WARN_ON_ONCE(1);
7256 return false;
7257 }
7258
stacksafe(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur,struct bpf_id_pair * idmap)7259 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
7260 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
7261 {
7262 int i, spi;
7263
7264 /* walk slots of the explored stack and ignore any additional
7265 * slots in the current stack, since explored(safe) state
7266 * didn't use them
7267 */
7268 for (i = 0; i < old->allocated_stack; i++) {
7269 spi = i / BPF_REG_SIZE;
7270
7271 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
7272 i += BPF_REG_SIZE - 1;
7273 /* explored state didn't use this */
7274 continue;
7275 }
7276
7277 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
7278 continue;
7279
7280 /* explored stack has more populated slots than current stack
7281 * and these slots were used
7282 */
7283 if (i >= cur->allocated_stack)
7284 return false;
7285
7286 /* if old state was safe with misc data in the stack
7287 * it will be safe with zero-initialized stack.
7288 * The opposite is not true
7289 */
7290 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
7291 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
7292 continue;
7293 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
7294 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
7295 /* Ex: old explored (safe) state has STACK_SPILL in
7296 * this stack slot, but current has has STACK_MISC ->
7297 * this verifier states are not equivalent,
7298 * return false to continue verification of this path
7299 */
7300 return false;
7301 if (i % BPF_REG_SIZE)
7302 continue;
7303 if (old->stack[spi].slot_type[0] != STACK_SPILL)
7304 continue;
7305 if (!regsafe(env, &old->stack[spi].spilled_ptr,
7306 &cur->stack[spi].spilled_ptr, idmap))
7307 /* when explored and current stack slot are both storing
7308 * spilled registers, check that stored pointers types
7309 * are the same as well.
7310 * Ex: explored safe path could have stored
7311 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
7312 * but current path has stored:
7313 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
7314 * such verifier states are not equivalent.
7315 * return false to continue verification of this path
7316 */
7317 return false;
7318 }
7319 return true;
7320 }
7321
refsafe(struct bpf_func_state * old,struct bpf_func_state * cur)7322 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
7323 {
7324 if (old->acquired_refs != cur->acquired_refs)
7325 return false;
7326 return !memcmp(old->refs, cur->refs,
7327 sizeof(*old->refs) * old->acquired_refs);
7328 }
7329
7330 /* compare two verifier states
7331 *
7332 * all states stored in state_list are known to be valid, since
7333 * verifier reached 'bpf_exit' instruction through them
7334 *
7335 * this function is called when verifier exploring different branches of
7336 * execution popped from the state stack. If it sees an old state that has
7337 * more strict register state and more strict stack state then this execution
7338 * branch doesn't need to be explored further, since verifier already
7339 * concluded that more strict state leads to valid finish.
7340 *
7341 * Therefore two states are equivalent if register state is more conservative
7342 * and explored stack state is more conservative than the current one.
7343 * Example:
7344 * explored current
7345 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
7346 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
7347 *
7348 * In other words if current stack state (one being explored) has more
7349 * valid slots than old one that already passed validation, it means
7350 * the verifier can stop exploring and conclude that current state is valid too
7351 *
7352 * Similarly with registers. If explored state has register type as invalid
7353 * whereas register type in current state is meaningful, it means that
7354 * the current state will reach 'bpf_exit' instruction safely
7355 */
func_states_equal(struct bpf_verifier_env * env,struct bpf_func_state * old,struct bpf_func_state * cur)7356 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
7357 struct bpf_func_state *cur)
7358 {
7359 int i;
7360
7361 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
7362 for (i = 0; i < MAX_BPF_REG; i++)
7363 if (!regsafe(env, &old->regs[i], &cur->regs[i],
7364 env->idmap_scratch))
7365 return false;
7366
7367 if (!stacksafe(env, old, cur, env->idmap_scratch))
7368 return false;
7369
7370 if (!refsafe(old, cur))
7371 return false;
7372
7373 return true;
7374 }
7375
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7376 static bool states_equal(struct bpf_verifier_env *env,
7377 struct bpf_verifier_state *old,
7378 struct bpf_verifier_state *cur)
7379 {
7380 int i;
7381
7382 if (old->curframe != cur->curframe)
7383 return false;
7384
7385 /* Verification state from speculative execution simulation
7386 * must never prune a non-speculative execution one.
7387 */
7388 if (old->speculative && !cur->speculative)
7389 return false;
7390
7391 if (old->active_spin_lock != cur->active_spin_lock)
7392 return false;
7393
7394 /* for states to be equal callsites have to be the same
7395 * and all frame states need to be equivalent
7396 */
7397 for (i = 0; i <= old->curframe; i++) {
7398 if (old->frame[i]->callsite != cur->frame[i]->callsite)
7399 return false;
7400 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
7401 return false;
7402 }
7403 return true;
7404 }
7405
7406 /* Return 0 if no propagation happened. Return negative error code if error
7407 * happened. Otherwise, return the propagated bit.
7408 */
propagate_liveness_reg(struct bpf_verifier_env * env,struct bpf_reg_state * reg,struct bpf_reg_state * parent_reg)7409 static int propagate_liveness_reg(struct bpf_verifier_env *env,
7410 struct bpf_reg_state *reg,
7411 struct bpf_reg_state *parent_reg)
7412 {
7413 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
7414 u8 flag = reg->live & REG_LIVE_READ;
7415 int err;
7416
7417 /* When comes here, read flags of PARENT_REG or REG could be any of
7418 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
7419 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
7420 */
7421 if (parent_flag == REG_LIVE_READ64 ||
7422 /* Or if there is no read flag from REG. */
7423 !flag ||
7424 /* Or if the read flag from REG is the same as PARENT_REG. */
7425 parent_flag == flag)
7426 return 0;
7427
7428 err = mark_reg_read(env, reg, parent_reg, flag);
7429 if (err)
7430 return err;
7431
7432 return flag;
7433 }
7434
7435 /* A write screens off any subsequent reads; but write marks come from the
7436 * straight-line code between a state and its parent. When we arrive at an
7437 * equivalent state (jump target or such) we didn't arrive by the straight-line
7438 * code, so read marks in the state must propagate to the parent regardless
7439 * of the state's write marks. That's what 'parent == state->parent' comparison
7440 * in mark_reg_read() is for.
7441 */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)7442 static int propagate_liveness(struct bpf_verifier_env *env,
7443 const struct bpf_verifier_state *vstate,
7444 struct bpf_verifier_state *vparent)
7445 {
7446 struct bpf_reg_state *state_reg, *parent_reg;
7447 struct bpf_func_state *state, *parent;
7448 int i, frame, err = 0;
7449
7450 if (vparent->curframe != vstate->curframe) {
7451 WARN(1, "propagate_live: parent frame %d current frame %d\n",
7452 vparent->curframe, vstate->curframe);
7453 return -EFAULT;
7454 }
7455 /* Propagate read liveness of registers... */
7456 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
7457 for (frame = 0; frame <= vstate->curframe; frame++) {
7458 parent = vparent->frame[frame];
7459 state = vstate->frame[frame];
7460 parent_reg = parent->regs;
7461 state_reg = state->regs;
7462 /* We don't need to worry about FP liveness, it's read-only */
7463 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
7464 err = propagate_liveness_reg(env, &state_reg[i],
7465 &parent_reg[i]);
7466 if (err < 0)
7467 return err;
7468 if (err == REG_LIVE_READ64)
7469 mark_insn_zext(env, &parent_reg[i]);
7470 }
7471
7472 /* Propagate stack slots. */
7473 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
7474 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
7475 parent_reg = &parent->stack[i].spilled_ptr;
7476 state_reg = &state->stack[i].spilled_ptr;
7477 err = propagate_liveness_reg(env, state_reg,
7478 parent_reg);
7479 if (err < 0)
7480 return err;
7481 }
7482 }
7483 return 0;
7484 }
7485
7486 /* find precise scalars in the previous equivalent state and
7487 * propagate them into the current state
7488 */
propagate_precision(struct bpf_verifier_env * env,const struct bpf_verifier_state * old)7489 static int propagate_precision(struct bpf_verifier_env *env,
7490 const struct bpf_verifier_state *old)
7491 {
7492 struct bpf_reg_state *state_reg;
7493 struct bpf_func_state *state;
7494 int i, err = 0;
7495
7496 state = old->frame[old->curframe];
7497 state_reg = state->regs;
7498 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
7499 if (state_reg->type != SCALAR_VALUE ||
7500 !state_reg->precise)
7501 continue;
7502 if (env->log.level & BPF_LOG_LEVEL2)
7503 verbose(env, "propagating r%d\n", i);
7504 err = mark_chain_precision(env, i);
7505 if (err < 0)
7506 return err;
7507 }
7508
7509 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
7510 if (state->stack[i].slot_type[0] != STACK_SPILL)
7511 continue;
7512 state_reg = &state->stack[i].spilled_ptr;
7513 if (state_reg->type != SCALAR_VALUE ||
7514 !state_reg->precise)
7515 continue;
7516 if (env->log.level & BPF_LOG_LEVEL2)
7517 verbose(env, "propagating fp%d\n",
7518 (-i - 1) * BPF_REG_SIZE);
7519 err = mark_chain_precision_stack(env, i);
7520 if (err < 0)
7521 return err;
7522 }
7523 return 0;
7524 }
7525
states_maybe_looping(struct bpf_verifier_state * old,struct bpf_verifier_state * cur)7526 static bool states_maybe_looping(struct bpf_verifier_state *old,
7527 struct bpf_verifier_state *cur)
7528 {
7529 struct bpf_func_state *fold, *fcur;
7530 int i, fr = cur->curframe;
7531
7532 if (old->curframe != fr)
7533 return false;
7534
7535 fold = old->frame[fr];
7536 fcur = cur->frame[fr];
7537 for (i = 0; i < MAX_BPF_REG; i++)
7538 if (memcmp(&fold->regs[i], &fcur->regs[i],
7539 offsetof(struct bpf_reg_state, parent)))
7540 return false;
7541 return true;
7542 }
7543
7544
is_state_visited(struct bpf_verifier_env * env,int insn_idx)7545 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
7546 {
7547 struct bpf_verifier_state_list *new_sl;
7548 struct bpf_verifier_state_list *sl, **pprev;
7549 struct bpf_verifier_state *cur = env->cur_state, *new;
7550 int i, j, err, states_cnt = 0;
7551 bool add_new_state = env->test_state_freq ? true : false;
7552
7553 cur->last_insn_idx = env->prev_insn_idx;
7554 if (!env->insn_aux_data[insn_idx].prune_point)
7555 /* this 'insn_idx' instruction wasn't marked, so we will not
7556 * be doing state search here
7557 */
7558 return 0;
7559
7560 /* bpf progs typically have pruning point every 4 instructions
7561 * http://vger.kernel.org/bpfconf2019.html#session-1
7562 * Do not add new state for future pruning if the verifier hasn't seen
7563 * at least 2 jumps and at least 8 instructions.
7564 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
7565 * In tests that amounts to up to 50% reduction into total verifier
7566 * memory consumption and 20% verifier time speedup.
7567 */
7568 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
7569 env->insn_processed - env->prev_insn_processed >= 8)
7570 add_new_state = true;
7571
7572 pprev = explored_state(env, insn_idx);
7573 sl = *pprev;
7574
7575 clean_live_states(env, insn_idx, cur);
7576
7577 while (sl) {
7578 states_cnt++;
7579 if (sl->state.insn_idx != insn_idx)
7580 goto next;
7581 if (sl->state.branches) {
7582 if (states_maybe_looping(&sl->state, cur) &&
7583 states_equal(env, &sl->state, cur)) {
7584 verbose_linfo(env, insn_idx, "; ");
7585 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
7586 return -EINVAL;
7587 }
7588 /* if the verifier is processing a loop, avoid adding new state
7589 * too often, since different loop iterations have distinct
7590 * states and may not help future pruning.
7591 * This threshold shouldn't be too low to make sure that
7592 * a loop with large bound will be rejected quickly.
7593 * The most abusive loop will be:
7594 * r1 += 1
7595 * if r1 < 1000000 goto pc-2
7596 * 1M insn_procssed limit / 100 == 10k peak states.
7597 * This threshold shouldn't be too high either, since states
7598 * at the end of the loop are likely to be useful in pruning.
7599 */
7600 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
7601 env->insn_processed - env->prev_insn_processed < 100)
7602 add_new_state = false;
7603 goto miss;
7604 }
7605 if (states_equal(env, &sl->state, cur)) {
7606 sl->hit_cnt++;
7607 /* reached equivalent register/stack state,
7608 * prune the search.
7609 * Registers read by the continuation are read by us.
7610 * If we have any write marks in env->cur_state, they
7611 * will prevent corresponding reads in the continuation
7612 * from reaching our parent (an explored_state). Our
7613 * own state will get the read marks recorded, but
7614 * they'll be immediately forgotten as we're pruning
7615 * this state and will pop a new one.
7616 */
7617 err = propagate_liveness(env, &sl->state, cur);
7618
7619 /* if previous state reached the exit with precision and
7620 * current state is equivalent to it (except precsion marks)
7621 * the precision needs to be propagated back in
7622 * the current state.
7623 */
7624 err = err ? : push_jmp_history(env, cur);
7625 err = err ? : propagate_precision(env, &sl->state);
7626 if (err)
7627 return err;
7628 return 1;
7629 }
7630 miss:
7631 /* when new state is not going to be added do not increase miss count.
7632 * Otherwise several loop iterations will remove the state
7633 * recorded earlier. The goal of these heuristics is to have
7634 * states from some iterations of the loop (some in the beginning
7635 * and some at the end) to help pruning.
7636 */
7637 if (add_new_state)
7638 sl->miss_cnt++;
7639 /* heuristic to determine whether this state is beneficial
7640 * to keep checking from state equivalence point of view.
7641 * Higher numbers increase max_states_per_insn and verification time,
7642 * but do not meaningfully decrease insn_processed.
7643 */
7644 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
7645 /* the state is unlikely to be useful. Remove it to
7646 * speed up verification
7647 */
7648 *pprev = sl->next;
7649 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
7650 u32 br = sl->state.branches;
7651
7652 WARN_ONCE(br,
7653 "BUG live_done but branches_to_explore %d\n",
7654 br);
7655 free_verifier_state(&sl->state, false);
7656 kfree(sl);
7657 env->peak_states--;
7658 } else {
7659 /* cannot free this state, since parentage chain may
7660 * walk it later. Add it for free_list instead to
7661 * be freed at the end of verification
7662 */
7663 sl->next = env->free_list;
7664 env->free_list = sl;
7665 }
7666 sl = *pprev;
7667 continue;
7668 }
7669 next:
7670 pprev = &sl->next;
7671 sl = *pprev;
7672 }
7673
7674 if (env->max_states_per_insn < states_cnt)
7675 env->max_states_per_insn = states_cnt;
7676
7677 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
7678 return push_jmp_history(env, cur);
7679
7680 if (!add_new_state)
7681 return push_jmp_history(env, cur);
7682
7683 /* There were no equivalent states, remember the current one.
7684 * Technically the current state is not proven to be safe yet,
7685 * but it will either reach outer most bpf_exit (which means it's safe)
7686 * or it will be rejected. When there are no loops the verifier won't be
7687 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
7688 * again on the way to bpf_exit.
7689 * When looping the sl->state.branches will be > 0 and this state
7690 * will not be considered for equivalence until branches == 0.
7691 */
7692 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
7693 if (!new_sl)
7694 return -ENOMEM;
7695 env->total_states++;
7696 env->peak_states++;
7697 env->prev_jmps_processed = env->jmps_processed;
7698 env->prev_insn_processed = env->insn_processed;
7699
7700 /* add new state to the head of linked list */
7701 new = &new_sl->state;
7702 err = copy_verifier_state(new, cur);
7703 if (err) {
7704 free_verifier_state(new, false);
7705 kfree(new_sl);
7706 return err;
7707 }
7708 new->insn_idx = insn_idx;
7709 WARN_ONCE(new->branches != 1,
7710 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
7711
7712 cur->parent = new;
7713 cur->first_insn_idx = insn_idx;
7714 clear_jmp_history(cur);
7715 new_sl->next = *explored_state(env, insn_idx);
7716 *explored_state(env, insn_idx) = new_sl;
7717 /* connect new state to parentage chain. Current frame needs all
7718 * registers connected. Only r6 - r9 of the callers are alive (pushed
7719 * to the stack implicitly by JITs) so in callers' frames connect just
7720 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
7721 * the state of the call instruction (with WRITTEN set), and r0 comes
7722 * from callee with its full parentage chain, anyway.
7723 */
7724 /* clear write marks in current state: the writes we did are not writes
7725 * our child did, so they don't screen off its reads from us.
7726 * (There are no read marks in current state, because reads always mark
7727 * their parent and current state never has children yet. Only
7728 * explored_states can get read marks.)
7729 */
7730 for (j = 0; j <= cur->curframe; j++) {
7731 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
7732 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
7733 for (i = 0; i < BPF_REG_FP; i++)
7734 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
7735 }
7736
7737 /* all stack frames are accessible from callee, clear them all */
7738 for (j = 0; j <= cur->curframe; j++) {
7739 struct bpf_func_state *frame = cur->frame[j];
7740 struct bpf_func_state *newframe = new->frame[j];
7741
7742 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
7743 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
7744 frame->stack[i].spilled_ptr.parent =
7745 &newframe->stack[i].spilled_ptr;
7746 }
7747 }
7748 return 0;
7749 }
7750
7751 /* Return true if it's OK to have the same insn return a different type. */
reg_type_mismatch_ok(enum bpf_reg_type type)7752 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
7753 {
7754 switch (type) {
7755 case PTR_TO_CTX:
7756 case PTR_TO_SOCKET:
7757 case PTR_TO_SOCKET_OR_NULL:
7758 case PTR_TO_SOCK_COMMON:
7759 case PTR_TO_SOCK_COMMON_OR_NULL:
7760 case PTR_TO_TCP_SOCK:
7761 case PTR_TO_TCP_SOCK_OR_NULL:
7762 case PTR_TO_XDP_SOCK:
7763 return false;
7764 default:
7765 return true;
7766 }
7767 }
7768
7769 /* If an instruction was previously used with particular pointer types, then we
7770 * need to be careful to avoid cases such as the below, where it may be ok
7771 * for one branch accessing the pointer, but not ok for the other branch:
7772 *
7773 * R1 = sock_ptr
7774 * goto X;
7775 * ...
7776 * R1 = some_other_valid_ptr;
7777 * goto X;
7778 * ...
7779 * R2 = *(u32 *)(R1 + 0);
7780 */
reg_type_mismatch(enum bpf_reg_type src,enum bpf_reg_type prev)7781 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
7782 {
7783 return src != prev && (!reg_type_mismatch_ok(src) ||
7784 !reg_type_mismatch_ok(prev));
7785 }
7786
do_check(struct bpf_verifier_env * env)7787 static int do_check(struct bpf_verifier_env *env)
7788 {
7789 struct bpf_verifier_state *state;
7790 struct bpf_insn *insns = env->prog->insnsi;
7791 struct bpf_reg_state *regs;
7792 int insn_cnt = env->prog->len;
7793 bool do_print_state = false;
7794 int prev_insn_idx = -1;
7795
7796 env->prev_linfo = NULL;
7797
7798 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
7799 if (!state)
7800 return -ENOMEM;
7801 state->curframe = 0;
7802 state->speculative = false;
7803 state->branches = 1;
7804 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
7805 if (!state->frame[0]) {
7806 kfree(state);
7807 return -ENOMEM;
7808 }
7809 env->cur_state = state;
7810 init_func_state(env, state->frame[0],
7811 BPF_MAIN_FUNC /* callsite */,
7812 0 /* frameno */,
7813 0 /* subprogno, zero == main subprog */);
7814
7815 for (;;) {
7816 struct bpf_insn *insn;
7817 u8 class;
7818 int err;
7819
7820 env->prev_insn_idx = prev_insn_idx;
7821 if (env->insn_idx >= insn_cnt) {
7822 verbose(env, "invalid insn idx %d insn_cnt %d\n",
7823 env->insn_idx, insn_cnt);
7824 return -EFAULT;
7825 }
7826
7827 insn = &insns[env->insn_idx];
7828 class = BPF_CLASS(insn->code);
7829
7830 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
7831 verbose(env,
7832 "BPF program is too large. Processed %d insn\n",
7833 env->insn_processed);
7834 return -E2BIG;
7835 }
7836
7837 err = is_state_visited(env, env->insn_idx);
7838 if (err < 0)
7839 return err;
7840 if (err == 1) {
7841 /* found equivalent state, can prune the search */
7842 if (env->log.level & BPF_LOG_LEVEL) {
7843 if (do_print_state)
7844 verbose(env, "\nfrom %d to %d%s: safe\n",
7845 env->prev_insn_idx, env->insn_idx,
7846 env->cur_state->speculative ?
7847 " (speculative execution)" : "");
7848 else
7849 verbose(env, "%d: safe\n", env->insn_idx);
7850 }
7851 goto process_bpf_exit;
7852 }
7853
7854 if (signal_pending(current))
7855 return -EAGAIN;
7856
7857 if (need_resched())
7858 cond_resched();
7859
7860 if (env->log.level & BPF_LOG_LEVEL2 ||
7861 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
7862 if (env->log.level & BPF_LOG_LEVEL2)
7863 verbose(env, "%d:", env->insn_idx);
7864 else
7865 verbose(env, "\nfrom %d to %d%s:",
7866 env->prev_insn_idx, env->insn_idx,
7867 env->cur_state->speculative ?
7868 " (speculative execution)" : "");
7869 print_verifier_state(env, state->frame[state->curframe]);
7870 do_print_state = false;
7871 }
7872
7873 if (env->log.level & BPF_LOG_LEVEL) {
7874 const struct bpf_insn_cbs cbs = {
7875 .cb_print = verbose,
7876 .private_data = env,
7877 };
7878
7879 verbose_linfo(env, env->insn_idx, "; ");
7880 verbose(env, "%d: ", env->insn_idx);
7881 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
7882 }
7883
7884 if (bpf_prog_is_dev_bound(env->prog->aux)) {
7885 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
7886 env->prev_insn_idx);
7887 if (err)
7888 return err;
7889 }
7890
7891 regs = cur_regs(env);
7892 sanitize_mark_insn_seen(env);
7893 prev_insn_idx = env->insn_idx;
7894
7895 if (class == BPF_ALU || class == BPF_ALU64) {
7896 err = check_alu_op(env, insn);
7897 if (err)
7898 return err;
7899
7900 } else if (class == BPF_LDX) {
7901 enum bpf_reg_type *prev_src_type, src_reg_type;
7902
7903 /* check for reserved fields is already done */
7904
7905 /* check src operand */
7906 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7907 if (err)
7908 return err;
7909
7910 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
7911 if (err)
7912 return err;
7913
7914 src_reg_type = regs[insn->src_reg].type;
7915
7916 /* check that memory (src_reg + off) is readable,
7917 * the state of dst_reg will be updated by this func
7918 */
7919 err = check_mem_access(env, env->insn_idx, insn->src_reg,
7920 insn->off, BPF_SIZE(insn->code),
7921 BPF_READ, insn->dst_reg, false);
7922 if (err)
7923 return err;
7924
7925 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
7926
7927 if (*prev_src_type == NOT_INIT) {
7928 /* saw a valid insn
7929 * dst_reg = *(u32 *)(src_reg + off)
7930 * save type to validate intersecting paths
7931 */
7932 *prev_src_type = src_reg_type;
7933
7934 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
7935 /* ABuser program is trying to use the same insn
7936 * dst_reg = *(u32*) (src_reg + off)
7937 * with different pointer types:
7938 * src_reg == ctx in one branch and
7939 * src_reg == stack|map in some other branch.
7940 * Reject it.
7941 */
7942 verbose(env, "same insn cannot be used with different pointers\n");
7943 return -EINVAL;
7944 }
7945
7946 } else if (class == BPF_STX) {
7947 enum bpf_reg_type *prev_dst_type, dst_reg_type;
7948
7949 if (BPF_MODE(insn->code) == BPF_XADD) {
7950 err = check_xadd(env, env->insn_idx, insn);
7951 if (err)
7952 return err;
7953 env->insn_idx++;
7954 continue;
7955 }
7956
7957 /* check src1 operand */
7958 err = check_reg_arg(env, insn->src_reg, SRC_OP);
7959 if (err)
7960 return err;
7961 /* check src2 operand */
7962 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7963 if (err)
7964 return err;
7965
7966 dst_reg_type = regs[insn->dst_reg].type;
7967
7968 /* check that memory (dst_reg + off) is writeable */
7969 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
7970 insn->off, BPF_SIZE(insn->code),
7971 BPF_WRITE, insn->src_reg, false);
7972 if (err)
7973 return err;
7974
7975 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
7976
7977 if (*prev_dst_type == NOT_INIT) {
7978 *prev_dst_type = dst_reg_type;
7979 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
7980 verbose(env, "same insn cannot be used with different pointers\n");
7981 return -EINVAL;
7982 }
7983
7984 } else if (class == BPF_ST) {
7985 if (BPF_MODE(insn->code) != BPF_MEM ||
7986 insn->src_reg != BPF_REG_0) {
7987 verbose(env, "BPF_ST uses reserved fields\n");
7988 return -EINVAL;
7989 }
7990 /* check src operand */
7991 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7992 if (err)
7993 return err;
7994
7995 if (is_ctx_reg(env, insn->dst_reg)) {
7996 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
7997 insn->dst_reg,
7998 reg_type_str[reg_state(env, insn->dst_reg)->type]);
7999 return -EACCES;
8000 }
8001
8002 /* check that memory (dst_reg + off) is writeable */
8003 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
8004 insn->off, BPF_SIZE(insn->code),
8005 BPF_WRITE, -1, false);
8006 if (err)
8007 return err;
8008
8009 } else if (class == BPF_JMP || class == BPF_JMP32) {
8010 u8 opcode = BPF_OP(insn->code);
8011
8012 env->jmps_processed++;
8013 if (opcode == BPF_CALL) {
8014 if (BPF_SRC(insn->code) != BPF_K ||
8015 insn->off != 0 ||
8016 (insn->src_reg != BPF_REG_0 &&
8017 insn->src_reg != BPF_PSEUDO_CALL) ||
8018 insn->dst_reg != BPF_REG_0 ||
8019 class == BPF_JMP32) {
8020 verbose(env, "BPF_CALL uses reserved fields\n");
8021 return -EINVAL;
8022 }
8023
8024 if (env->cur_state->active_spin_lock &&
8025 (insn->src_reg == BPF_PSEUDO_CALL ||
8026 insn->imm != BPF_FUNC_spin_unlock)) {
8027 verbose(env, "function calls are not allowed while holding a lock\n");
8028 return -EINVAL;
8029 }
8030 if (insn->src_reg == BPF_PSEUDO_CALL)
8031 err = check_func_call(env, insn, &env->insn_idx);
8032 else
8033 err = check_helper_call(env, insn->imm, env->insn_idx);
8034 if (err)
8035 return err;
8036
8037 } else if (opcode == BPF_JA) {
8038 if (BPF_SRC(insn->code) != BPF_K ||
8039 insn->imm != 0 ||
8040 insn->src_reg != BPF_REG_0 ||
8041 insn->dst_reg != BPF_REG_0 ||
8042 class == BPF_JMP32) {
8043 verbose(env, "BPF_JA uses reserved fields\n");
8044 return -EINVAL;
8045 }
8046
8047 env->insn_idx += insn->off + 1;
8048 continue;
8049
8050 } else if (opcode == BPF_EXIT) {
8051 if (BPF_SRC(insn->code) != BPF_K ||
8052 insn->imm != 0 ||
8053 insn->src_reg != BPF_REG_0 ||
8054 insn->dst_reg != BPF_REG_0 ||
8055 class == BPF_JMP32) {
8056 verbose(env, "BPF_EXIT uses reserved fields\n");
8057 return -EINVAL;
8058 }
8059
8060 if (env->cur_state->active_spin_lock) {
8061 verbose(env, "bpf_spin_unlock is missing\n");
8062 return -EINVAL;
8063 }
8064
8065 if (state->curframe) {
8066 /* exit from nested function */
8067 err = prepare_func_exit(env, &env->insn_idx);
8068 if (err)
8069 return err;
8070 do_print_state = true;
8071 continue;
8072 }
8073
8074 err = check_reference_leak(env);
8075 if (err)
8076 return err;
8077
8078 /* eBPF calling convetion is such that R0 is used
8079 * to return the value from eBPF program.
8080 * Make sure that it's readable at this time
8081 * of bpf_exit, which means that program wrote
8082 * something into it earlier
8083 */
8084 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8085 if (err)
8086 return err;
8087
8088 if (is_pointer_value(env, BPF_REG_0)) {
8089 verbose(env, "R0 leaks addr as return value\n");
8090 return -EACCES;
8091 }
8092
8093 err = check_return_code(env);
8094 if (err)
8095 return err;
8096 process_bpf_exit:
8097 update_branch_counts(env, env->cur_state);
8098 err = pop_stack(env, &prev_insn_idx,
8099 &env->insn_idx);
8100 if (err < 0) {
8101 if (err != -ENOENT)
8102 return err;
8103 break;
8104 } else {
8105 do_print_state = true;
8106 continue;
8107 }
8108 } else {
8109 err = check_cond_jmp_op(env, insn, &env->insn_idx);
8110 if (err)
8111 return err;
8112 }
8113 } else if (class == BPF_LD) {
8114 u8 mode = BPF_MODE(insn->code);
8115
8116 if (mode == BPF_ABS || mode == BPF_IND) {
8117 err = check_ld_abs(env, insn);
8118 if (err)
8119 return err;
8120
8121 } else if (mode == BPF_IMM) {
8122 err = check_ld_imm(env, insn);
8123 if (err)
8124 return err;
8125
8126 env->insn_idx++;
8127 sanitize_mark_insn_seen(env);
8128 } else {
8129 verbose(env, "invalid BPF_LD mode\n");
8130 return -EINVAL;
8131 }
8132 } else {
8133 verbose(env, "unknown insn class %d\n", class);
8134 return -EINVAL;
8135 }
8136
8137 env->insn_idx++;
8138 }
8139
8140 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
8141 return 0;
8142 }
8143
check_map_prealloc(struct bpf_map * map)8144 static int check_map_prealloc(struct bpf_map *map)
8145 {
8146 return (map->map_type != BPF_MAP_TYPE_HASH &&
8147 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8148 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
8149 !(map->map_flags & BPF_F_NO_PREALLOC);
8150 }
8151
is_tracing_prog_type(enum bpf_prog_type type)8152 static bool is_tracing_prog_type(enum bpf_prog_type type)
8153 {
8154 switch (type) {
8155 case BPF_PROG_TYPE_KPROBE:
8156 case BPF_PROG_TYPE_TRACEPOINT:
8157 case BPF_PROG_TYPE_PERF_EVENT:
8158 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8159 return true;
8160 default:
8161 return false;
8162 }
8163 }
8164
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)8165 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
8166 struct bpf_map *map,
8167 struct bpf_prog *prog)
8168
8169 {
8170 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
8171 * preallocated hash maps, since doing memory allocation
8172 * in overflow_handler can crash depending on where nmi got
8173 * triggered.
8174 */
8175 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
8176 if (!check_map_prealloc(map)) {
8177 verbose(env, "perf_event programs can only use preallocated hash map\n");
8178 return -EINVAL;
8179 }
8180 if (map->inner_map_meta &&
8181 !check_map_prealloc(map->inner_map_meta)) {
8182 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
8183 return -EINVAL;
8184 }
8185 }
8186
8187 if ((is_tracing_prog_type(prog->type) ||
8188 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) &&
8189 map_value_has_spin_lock(map)) {
8190 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
8191 return -EINVAL;
8192 }
8193
8194 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
8195 !bpf_offload_prog_map_match(prog, map)) {
8196 verbose(env, "offload device mismatch between prog and map\n");
8197 return -EINVAL;
8198 }
8199
8200 return 0;
8201 }
8202
bpf_map_is_cgroup_storage(struct bpf_map * map)8203 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
8204 {
8205 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
8206 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
8207 }
8208
8209 /* look for pseudo eBPF instructions that access map FDs and
8210 * replace them with actual map pointers
8211 */
replace_map_fd_with_map_ptr(struct bpf_verifier_env * env)8212 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
8213 {
8214 struct bpf_insn *insn = env->prog->insnsi;
8215 int insn_cnt = env->prog->len;
8216 int i, j, err;
8217
8218 err = bpf_prog_calc_tag(env->prog);
8219 if (err)
8220 return err;
8221
8222 for (i = 0; i < insn_cnt; i++, insn++) {
8223 if (BPF_CLASS(insn->code) == BPF_LDX &&
8224 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
8225 verbose(env, "BPF_LDX uses reserved fields\n");
8226 return -EINVAL;
8227 }
8228
8229 if (BPF_CLASS(insn->code) == BPF_STX &&
8230 ((BPF_MODE(insn->code) != BPF_MEM &&
8231 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
8232 verbose(env, "BPF_STX uses reserved fields\n");
8233 return -EINVAL;
8234 }
8235
8236 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
8237 struct bpf_insn_aux_data *aux;
8238 struct bpf_map *map;
8239 struct fd f;
8240 u64 addr;
8241
8242 if (i == insn_cnt - 1 || insn[1].code != 0 ||
8243 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
8244 insn[1].off != 0) {
8245 verbose(env, "invalid bpf_ld_imm64 insn\n");
8246 return -EINVAL;
8247 }
8248
8249 if (insn[0].src_reg == 0)
8250 /* valid generic load 64-bit imm */
8251 goto next_insn;
8252
8253 /* In final convert_pseudo_ld_imm64() step, this is
8254 * converted into regular 64-bit imm load insn.
8255 */
8256 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
8257 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
8258 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
8259 insn[1].imm != 0)) {
8260 verbose(env,
8261 "unrecognized bpf_ld_imm64 insn\n");
8262 return -EINVAL;
8263 }
8264
8265 f = fdget(insn[0].imm);
8266 map = __bpf_map_get(f);
8267 if (IS_ERR(map)) {
8268 verbose(env, "fd %d is not pointing to valid bpf_map\n",
8269 insn[0].imm);
8270 return PTR_ERR(map);
8271 }
8272
8273 err = check_map_prog_compatibility(env, map, env->prog);
8274 if (err) {
8275 fdput(f);
8276 return err;
8277 }
8278
8279 aux = &env->insn_aux_data[i];
8280 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
8281 addr = (unsigned long)map;
8282 } else {
8283 u32 off = insn[1].imm;
8284
8285 if (off >= BPF_MAX_VAR_OFF) {
8286 verbose(env, "direct value offset of %u is not allowed\n", off);
8287 fdput(f);
8288 return -EINVAL;
8289 }
8290
8291 if (!map->ops->map_direct_value_addr) {
8292 verbose(env, "no direct value access support for this map type\n");
8293 fdput(f);
8294 return -EINVAL;
8295 }
8296
8297 err = map->ops->map_direct_value_addr(map, &addr, off);
8298 if (err) {
8299 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
8300 map->value_size, off);
8301 fdput(f);
8302 return err;
8303 }
8304
8305 aux->map_off = off;
8306 addr += off;
8307 }
8308
8309 insn[0].imm = (u32)addr;
8310 insn[1].imm = addr >> 32;
8311
8312 /* check whether we recorded this map already */
8313 for (j = 0; j < env->used_map_cnt; j++) {
8314 if (env->used_maps[j] == map) {
8315 aux->map_index = j;
8316 fdput(f);
8317 goto next_insn;
8318 }
8319 }
8320
8321 if (env->used_map_cnt >= MAX_USED_MAPS) {
8322 fdput(f);
8323 return -E2BIG;
8324 }
8325
8326 /* hold the map. If the program is rejected by verifier,
8327 * the map will be released by release_maps() or it
8328 * will be used by the valid program until it's unloaded
8329 * and all maps are released in free_used_maps()
8330 */
8331 map = bpf_map_inc(map, false);
8332 if (IS_ERR(map)) {
8333 fdput(f);
8334 return PTR_ERR(map);
8335 }
8336
8337 aux->map_index = env->used_map_cnt;
8338 env->used_maps[env->used_map_cnt++] = map;
8339
8340 if (bpf_map_is_cgroup_storage(map) &&
8341 bpf_cgroup_storage_assign(env->prog, map)) {
8342 verbose(env, "only one cgroup storage of each type is allowed\n");
8343 fdput(f);
8344 return -EBUSY;
8345 }
8346
8347 fdput(f);
8348 next_insn:
8349 insn++;
8350 i++;
8351 continue;
8352 }
8353
8354 /* Basic sanity check before we invest more work here. */
8355 if (!bpf_opcode_in_insntable(insn->code)) {
8356 verbose(env, "unknown opcode %02x\n", insn->code);
8357 return -EINVAL;
8358 }
8359 }
8360
8361 /* now all pseudo BPF_LD_IMM64 instructions load valid
8362 * 'struct bpf_map *' into a register instead of user map_fd.
8363 * These pointers will be used later by verifier to validate map access.
8364 */
8365 return 0;
8366 }
8367
8368 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)8369 static void release_maps(struct bpf_verifier_env *env)
8370 {
8371 enum bpf_cgroup_storage_type stype;
8372 int i;
8373
8374 for_each_cgroup_storage_type(stype) {
8375 if (!env->prog->aux->cgroup_storage[stype])
8376 continue;
8377 bpf_cgroup_storage_release(env->prog,
8378 env->prog->aux->cgroup_storage[stype]);
8379 }
8380
8381 for (i = 0; i < env->used_map_cnt; i++)
8382 bpf_map_put(env->used_maps[i]);
8383 }
8384
8385 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)8386 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
8387 {
8388 struct bpf_insn *insn = env->prog->insnsi;
8389 int insn_cnt = env->prog->len;
8390 int i;
8391
8392 for (i = 0; i < insn_cnt; i++, insn++)
8393 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
8394 insn->src_reg = 0;
8395 }
8396
8397 /* single env->prog->insni[off] instruction was replaced with the range
8398 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
8399 * [0, off) and [off, end) to new locations, so the patched range stays zero
8400 */
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)8401 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
8402 struct bpf_insn_aux_data *new_data,
8403 struct bpf_prog *new_prog, u32 off, u32 cnt)
8404 {
8405 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
8406 struct bpf_insn *insn = new_prog->insnsi;
8407 bool old_seen = old_data[off].seen;
8408 u32 prog_len;
8409 int i;
8410
8411 /* aux info at OFF always needs adjustment, no matter fast path
8412 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
8413 * original insn at old prog.
8414 */
8415 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
8416
8417 if (cnt == 1)
8418 return;
8419 prog_len = new_prog->len;
8420
8421 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
8422 memcpy(new_data + off + cnt - 1, old_data + off,
8423 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
8424 for (i = off; i < off + cnt - 1; i++) {
8425 /* Expand insni[off]'s seen count to the patched range. */
8426 new_data[i].seen = old_seen;
8427 new_data[i].zext_dst = insn_has_def32(env, insn + i);
8428 }
8429 env->insn_aux_data = new_data;
8430 vfree(old_data);
8431 }
8432
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)8433 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
8434 {
8435 int i;
8436
8437 if (len == 1)
8438 return;
8439 /* NOTE: fake 'exit' subprog should be updated as well. */
8440 for (i = 0; i <= env->subprog_cnt; i++) {
8441 if (env->subprog_info[i].start <= off)
8442 continue;
8443 env->subprog_info[i].start += len - 1;
8444 }
8445 }
8446
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)8447 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
8448 const struct bpf_insn *patch, u32 len)
8449 {
8450 struct bpf_prog *new_prog;
8451 struct bpf_insn_aux_data *new_data = NULL;
8452
8453 if (len > 1) {
8454 new_data = vzalloc(array_size(env->prog->len + len - 1,
8455 sizeof(struct bpf_insn_aux_data)));
8456 if (!new_data)
8457 return NULL;
8458 }
8459
8460 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
8461 if (IS_ERR(new_prog)) {
8462 if (PTR_ERR(new_prog) == -ERANGE)
8463 verbose(env,
8464 "insn %d cannot be patched due to 16-bit range\n",
8465 env->insn_aux_data[off].orig_idx);
8466 vfree(new_data);
8467 return NULL;
8468 }
8469 adjust_insn_aux_data(env, new_data, new_prog, off, len);
8470 adjust_subprog_starts(env, off, len);
8471 return new_prog;
8472 }
8473
adjust_subprog_starts_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)8474 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
8475 u32 off, u32 cnt)
8476 {
8477 int i, j;
8478
8479 /* find first prog starting at or after off (first to remove) */
8480 for (i = 0; i < env->subprog_cnt; i++)
8481 if (env->subprog_info[i].start >= off)
8482 break;
8483 /* find first prog starting at or after off + cnt (first to stay) */
8484 for (j = i; j < env->subprog_cnt; j++)
8485 if (env->subprog_info[j].start >= off + cnt)
8486 break;
8487 /* if j doesn't start exactly at off + cnt, we are just removing
8488 * the front of previous prog
8489 */
8490 if (env->subprog_info[j].start != off + cnt)
8491 j--;
8492
8493 if (j > i) {
8494 struct bpf_prog_aux *aux = env->prog->aux;
8495 int move;
8496
8497 /* move fake 'exit' subprog as well */
8498 move = env->subprog_cnt + 1 - j;
8499
8500 memmove(env->subprog_info + i,
8501 env->subprog_info + j,
8502 sizeof(*env->subprog_info) * move);
8503 env->subprog_cnt -= j - i;
8504
8505 /* remove func_info */
8506 if (aux->func_info) {
8507 move = aux->func_info_cnt - j;
8508
8509 memmove(aux->func_info + i,
8510 aux->func_info + j,
8511 sizeof(*aux->func_info) * move);
8512 aux->func_info_cnt -= j - i;
8513 /* func_info->insn_off is set after all code rewrites,
8514 * in adjust_btf_func() - no need to adjust
8515 */
8516 }
8517 } else {
8518 /* convert i from "first prog to remove" to "first to adjust" */
8519 if (env->subprog_info[i].start == off)
8520 i++;
8521 }
8522
8523 /* update fake 'exit' subprog as well */
8524 for (; i <= env->subprog_cnt; i++)
8525 env->subprog_info[i].start -= cnt;
8526
8527 return 0;
8528 }
8529
bpf_adj_linfo_after_remove(struct bpf_verifier_env * env,u32 off,u32 cnt)8530 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
8531 u32 cnt)
8532 {
8533 struct bpf_prog *prog = env->prog;
8534 u32 i, l_off, l_cnt, nr_linfo;
8535 struct bpf_line_info *linfo;
8536
8537 nr_linfo = prog->aux->nr_linfo;
8538 if (!nr_linfo)
8539 return 0;
8540
8541 linfo = prog->aux->linfo;
8542
8543 /* find first line info to remove, count lines to be removed */
8544 for (i = 0; i < nr_linfo; i++)
8545 if (linfo[i].insn_off >= off)
8546 break;
8547
8548 l_off = i;
8549 l_cnt = 0;
8550 for (; i < nr_linfo; i++)
8551 if (linfo[i].insn_off < off + cnt)
8552 l_cnt++;
8553 else
8554 break;
8555
8556 /* First live insn doesn't match first live linfo, it needs to "inherit"
8557 * last removed linfo. prog is already modified, so prog->len == off
8558 * means no live instructions after (tail of the program was removed).
8559 */
8560 if (prog->len != off && l_cnt &&
8561 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
8562 l_cnt--;
8563 linfo[--i].insn_off = off + cnt;
8564 }
8565
8566 /* remove the line info which refer to the removed instructions */
8567 if (l_cnt) {
8568 memmove(linfo + l_off, linfo + i,
8569 sizeof(*linfo) * (nr_linfo - i));
8570
8571 prog->aux->nr_linfo -= l_cnt;
8572 nr_linfo = prog->aux->nr_linfo;
8573 }
8574
8575 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
8576 for (i = l_off; i < nr_linfo; i++)
8577 linfo[i].insn_off -= cnt;
8578
8579 /* fix up all subprogs (incl. 'exit') which start >= off */
8580 for (i = 0; i <= env->subprog_cnt; i++)
8581 if (env->subprog_info[i].linfo_idx > l_off) {
8582 /* program may have started in the removed region but
8583 * may not be fully removed
8584 */
8585 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
8586 env->subprog_info[i].linfo_idx -= l_cnt;
8587 else
8588 env->subprog_info[i].linfo_idx = l_off;
8589 }
8590
8591 return 0;
8592 }
8593
verifier_remove_insns(struct bpf_verifier_env * env,u32 off,u32 cnt)8594 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
8595 {
8596 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8597 unsigned int orig_prog_len = env->prog->len;
8598 int err;
8599
8600 if (bpf_prog_is_dev_bound(env->prog->aux))
8601 bpf_prog_offload_remove_insns(env, off, cnt);
8602
8603 err = bpf_remove_insns(env->prog, off, cnt);
8604 if (err)
8605 return err;
8606
8607 err = adjust_subprog_starts_after_remove(env, off, cnt);
8608 if (err)
8609 return err;
8610
8611 err = bpf_adj_linfo_after_remove(env, off, cnt);
8612 if (err)
8613 return err;
8614
8615 memmove(aux_data + off, aux_data + off + cnt,
8616 sizeof(*aux_data) * (orig_prog_len - off - cnt));
8617
8618 return 0;
8619 }
8620
8621 /* The verifier does more data flow analysis than llvm and will not
8622 * explore branches that are dead at run time. Malicious programs can
8623 * have dead code too. Therefore replace all dead at-run-time code
8624 * with 'ja -1'.
8625 *
8626 * Just nops are not optimal, e.g. if they would sit at the end of the
8627 * program and through another bug we would manage to jump there, then
8628 * we'd execute beyond program memory otherwise. Returning exception
8629 * code also wouldn't work since we can have subprogs where the dead
8630 * code could be located.
8631 */
sanitize_dead_code(struct bpf_verifier_env * env)8632 static void sanitize_dead_code(struct bpf_verifier_env *env)
8633 {
8634 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8635 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
8636 struct bpf_insn *insn = env->prog->insnsi;
8637 const int insn_cnt = env->prog->len;
8638 int i;
8639
8640 for (i = 0; i < insn_cnt; i++) {
8641 if (aux_data[i].seen)
8642 continue;
8643 memcpy(insn + i, &trap, sizeof(trap));
8644 aux_data[i].zext_dst = false;
8645 }
8646 }
8647
insn_is_cond_jump(u8 code)8648 static bool insn_is_cond_jump(u8 code)
8649 {
8650 u8 op;
8651
8652 if (BPF_CLASS(code) == BPF_JMP32)
8653 return true;
8654
8655 if (BPF_CLASS(code) != BPF_JMP)
8656 return false;
8657
8658 op = BPF_OP(code);
8659 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
8660 }
8661
opt_hard_wire_dead_code_branches(struct bpf_verifier_env * env)8662 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
8663 {
8664 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8665 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8666 struct bpf_insn *insn = env->prog->insnsi;
8667 const int insn_cnt = env->prog->len;
8668 int i;
8669
8670 for (i = 0; i < insn_cnt; i++, insn++) {
8671 if (!insn_is_cond_jump(insn->code))
8672 continue;
8673
8674 if (!aux_data[i + 1].seen)
8675 ja.off = insn->off;
8676 else if (!aux_data[i + 1 + insn->off].seen)
8677 ja.off = 0;
8678 else
8679 continue;
8680
8681 if (bpf_prog_is_dev_bound(env->prog->aux))
8682 bpf_prog_offload_replace_insn(env, i, &ja);
8683
8684 memcpy(insn, &ja, sizeof(ja));
8685 }
8686 }
8687
opt_remove_dead_code(struct bpf_verifier_env * env)8688 static int opt_remove_dead_code(struct bpf_verifier_env *env)
8689 {
8690 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
8691 int insn_cnt = env->prog->len;
8692 int i, err;
8693
8694 for (i = 0; i < insn_cnt; i++) {
8695 int j;
8696
8697 j = 0;
8698 while (i + j < insn_cnt && !aux_data[i + j].seen)
8699 j++;
8700 if (!j)
8701 continue;
8702
8703 err = verifier_remove_insns(env, i, j);
8704 if (err)
8705 return err;
8706 insn_cnt = env->prog->len;
8707 }
8708
8709 return 0;
8710 }
8711
opt_remove_nops(struct bpf_verifier_env * env)8712 static int opt_remove_nops(struct bpf_verifier_env *env)
8713 {
8714 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
8715 struct bpf_insn *insn = env->prog->insnsi;
8716 int insn_cnt = env->prog->len;
8717 int i, err;
8718
8719 for (i = 0; i < insn_cnt; i++) {
8720 if (memcmp(&insn[i], &ja, sizeof(ja)))
8721 continue;
8722
8723 err = verifier_remove_insns(env, i, 1);
8724 if (err)
8725 return err;
8726 insn_cnt--;
8727 i--;
8728 }
8729
8730 return 0;
8731 }
8732
opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env * env,const union bpf_attr * attr)8733 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
8734 const union bpf_attr *attr)
8735 {
8736 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
8737 struct bpf_insn_aux_data *aux = env->insn_aux_data;
8738 int i, patch_len, delta = 0, len = env->prog->len;
8739 struct bpf_insn *insns = env->prog->insnsi;
8740 struct bpf_prog *new_prog;
8741 bool rnd_hi32;
8742
8743 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
8744 zext_patch[1] = BPF_ZEXT_REG(0);
8745 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
8746 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
8747 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
8748 for (i = 0; i < len; i++) {
8749 int adj_idx = i + delta;
8750 struct bpf_insn insn;
8751
8752 insn = insns[adj_idx];
8753 if (!aux[adj_idx].zext_dst) {
8754 u8 code, class;
8755 u32 imm_rnd;
8756
8757 if (!rnd_hi32)
8758 continue;
8759
8760 code = insn.code;
8761 class = BPF_CLASS(code);
8762 if (insn_no_def(&insn))
8763 continue;
8764
8765 /* NOTE: arg "reg" (the fourth one) is only used for
8766 * BPF_STX which has been ruled out in above
8767 * check, it is safe to pass NULL here.
8768 */
8769 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
8770 if (class == BPF_LD &&
8771 BPF_MODE(code) == BPF_IMM)
8772 i++;
8773 continue;
8774 }
8775
8776 /* ctx load could be transformed into wider load. */
8777 if (class == BPF_LDX &&
8778 aux[adj_idx].ptr_type == PTR_TO_CTX)
8779 continue;
8780
8781 imm_rnd = get_random_int();
8782 rnd_hi32_patch[0] = insn;
8783 rnd_hi32_patch[1].imm = imm_rnd;
8784 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
8785 patch = rnd_hi32_patch;
8786 patch_len = 4;
8787 goto apply_patch_buffer;
8788 }
8789
8790 if (!bpf_jit_needs_zext())
8791 continue;
8792
8793 zext_patch[0] = insn;
8794 zext_patch[1].dst_reg = insn.dst_reg;
8795 zext_patch[1].src_reg = insn.dst_reg;
8796 patch = zext_patch;
8797 patch_len = 2;
8798 apply_patch_buffer:
8799 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
8800 if (!new_prog)
8801 return -ENOMEM;
8802 env->prog = new_prog;
8803 insns = new_prog->insnsi;
8804 aux = env->insn_aux_data;
8805 delta += patch_len - 1;
8806 }
8807
8808 return 0;
8809 }
8810
8811 /* convert load instructions that access fields of a context type into a
8812 * sequence of instructions that access fields of the underlying structure:
8813 * struct __sk_buff -> struct sk_buff
8814 * struct bpf_sock_ops -> struct sock
8815 */
convert_ctx_accesses(struct bpf_verifier_env * env)8816 static int convert_ctx_accesses(struct bpf_verifier_env *env)
8817 {
8818 const struct bpf_verifier_ops *ops = env->ops;
8819 int i, cnt, size, ctx_field_size, delta = 0;
8820 const int insn_cnt = env->prog->len;
8821 struct bpf_insn insn_buf[16], *insn;
8822 u32 target_size, size_default, off;
8823 struct bpf_prog *new_prog;
8824 enum bpf_access_type type;
8825 bool is_narrower_load;
8826
8827 if (ops->gen_prologue || env->seen_direct_write) {
8828 if (!ops->gen_prologue) {
8829 verbose(env, "bpf verifier is misconfigured\n");
8830 return -EINVAL;
8831 }
8832 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
8833 env->prog);
8834 if (cnt >= ARRAY_SIZE(insn_buf)) {
8835 verbose(env, "bpf verifier is misconfigured\n");
8836 return -EINVAL;
8837 } else if (cnt) {
8838 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
8839 if (!new_prog)
8840 return -ENOMEM;
8841
8842 env->prog = new_prog;
8843 delta += cnt - 1;
8844 }
8845 }
8846
8847 if (bpf_prog_is_dev_bound(env->prog->aux))
8848 return 0;
8849
8850 insn = env->prog->insnsi + delta;
8851
8852 for (i = 0; i < insn_cnt; i++, insn++) {
8853 bpf_convert_ctx_access_t convert_ctx_access;
8854 bool ctx_access;
8855
8856 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
8857 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
8858 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
8859 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
8860 type = BPF_READ;
8861 ctx_access = true;
8862 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
8863 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
8864 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
8865 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
8866 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
8867 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
8868 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
8869 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
8870 type = BPF_WRITE;
8871 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
8872 } else {
8873 continue;
8874 }
8875
8876 if (type == BPF_WRITE &&
8877 env->insn_aux_data[i + delta].sanitize_stack_spill) {
8878 struct bpf_insn patch[] = {
8879 *insn,
8880 BPF_ST_NOSPEC(),
8881 };
8882
8883 cnt = ARRAY_SIZE(patch);
8884 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
8885 if (!new_prog)
8886 return -ENOMEM;
8887
8888 delta += cnt - 1;
8889 env->prog = new_prog;
8890 insn = new_prog->insnsi + i + delta;
8891 continue;
8892 }
8893
8894 if (!ctx_access)
8895 continue;
8896
8897 switch (env->insn_aux_data[i + delta].ptr_type) {
8898 case PTR_TO_CTX:
8899 if (!ops->convert_ctx_access)
8900 continue;
8901 convert_ctx_access = ops->convert_ctx_access;
8902 break;
8903 case PTR_TO_SOCKET:
8904 case PTR_TO_SOCK_COMMON:
8905 convert_ctx_access = bpf_sock_convert_ctx_access;
8906 break;
8907 case PTR_TO_TCP_SOCK:
8908 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
8909 break;
8910 case PTR_TO_XDP_SOCK:
8911 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
8912 break;
8913 default:
8914 continue;
8915 }
8916
8917 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
8918 size = BPF_LDST_BYTES(insn);
8919
8920 /* If the read access is a narrower load of the field,
8921 * convert to a 4/8-byte load, to minimum program type specific
8922 * convert_ctx_access changes. If conversion is successful,
8923 * we will apply proper mask to the result.
8924 */
8925 is_narrower_load = size < ctx_field_size;
8926 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
8927 off = insn->off;
8928 if (is_narrower_load) {
8929 u8 size_code;
8930
8931 if (type == BPF_WRITE) {
8932 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
8933 return -EINVAL;
8934 }
8935
8936 size_code = BPF_H;
8937 if (ctx_field_size == 4)
8938 size_code = BPF_W;
8939 else if (ctx_field_size == 8)
8940 size_code = BPF_DW;
8941
8942 insn->off = off & ~(size_default - 1);
8943 insn->code = BPF_LDX | BPF_MEM | size_code;
8944 }
8945
8946 target_size = 0;
8947 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
8948 &target_size);
8949 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
8950 (ctx_field_size && !target_size)) {
8951 verbose(env, "bpf verifier is misconfigured\n");
8952 return -EINVAL;
8953 }
8954
8955 if (is_narrower_load && size < target_size) {
8956 u8 shift = bpf_ctx_narrow_access_offset(
8957 off, size, size_default) * 8;
8958 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
8959 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
8960 return -EINVAL;
8961 }
8962 if (ctx_field_size <= 4) {
8963 if (shift)
8964 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
8965 insn->dst_reg,
8966 shift);
8967 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
8968 (1 << size * 8) - 1);
8969 } else {
8970 if (shift)
8971 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
8972 insn->dst_reg,
8973 shift);
8974 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
8975 (1ULL << size * 8) - 1);
8976 }
8977 }
8978
8979 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
8980 if (!new_prog)
8981 return -ENOMEM;
8982
8983 delta += cnt - 1;
8984
8985 /* keep walking new program and skip insns we just inserted */
8986 env->prog = new_prog;
8987 insn = new_prog->insnsi + i + delta;
8988 }
8989
8990 return 0;
8991 }
8992
jit_subprogs(struct bpf_verifier_env * env)8993 static int jit_subprogs(struct bpf_verifier_env *env)
8994 {
8995 struct bpf_prog *prog = env->prog, **func, *tmp;
8996 int i, j, subprog_start, subprog_end = 0, len, subprog;
8997 struct bpf_insn *insn;
8998 void *old_bpf_func;
8999 int err;
9000
9001 if (env->subprog_cnt <= 1)
9002 return 0;
9003
9004 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9005 if (insn->code != (BPF_JMP | BPF_CALL) ||
9006 insn->src_reg != BPF_PSEUDO_CALL)
9007 continue;
9008 /* Upon error here we cannot fall back to interpreter but
9009 * need a hard reject of the program. Thus -EFAULT is
9010 * propagated in any case.
9011 */
9012 subprog = find_subprog(env, i + insn->imm + 1);
9013 if (subprog < 0) {
9014 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
9015 i + insn->imm + 1);
9016 return -EFAULT;
9017 }
9018 /* temporarily remember subprog id inside insn instead of
9019 * aux_data, since next loop will split up all insns into funcs
9020 */
9021 insn->off = subprog;
9022 /* remember original imm in case JIT fails and fallback
9023 * to interpreter will be needed
9024 */
9025 env->insn_aux_data[i].call_imm = insn->imm;
9026 /* point imm to __bpf_call_base+1 from JITs point of view */
9027 insn->imm = 1;
9028 }
9029
9030 err = bpf_prog_alloc_jited_linfo(prog);
9031 if (err)
9032 goto out_undo_insn;
9033
9034 err = -ENOMEM;
9035 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
9036 if (!func)
9037 goto out_undo_insn;
9038
9039 for (i = 0; i < env->subprog_cnt; i++) {
9040 subprog_start = subprog_end;
9041 subprog_end = env->subprog_info[i + 1].start;
9042
9043 len = subprog_end - subprog_start;
9044 /* BPF_PROG_RUN doesn't call subprogs directly,
9045 * hence main prog stats include the runtime of subprogs.
9046 * subprogs don't have IDs and not reachable via prog_get_next_id
9047 * func[i]->aux->stats will never be accessed and stays NULL
9048 */
9049 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
9050 if (!func[i])
9051 goto out_free;
9052 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
9053 len * sizeof(struct bpf_insn));
9054 func[i]->type = prog->type;
9055 func[i]->len = len;
9056 if (bpf_prog_calc_tag(func[i]))
9057 goto out_free;
9058 func[i]->is_func = 1;
9059 func[i]->aux->func_idx = i;
9060 /* the btf and func_info will be freed only at prog->aux */
9061 func[i]->aux->btf = prog->aux->btf;
9062 func[i]->aux->func_info = prog->aux->func_info;
9063
9064 /* Use bpf_prog_F_tag to indicate functions in stack traces.
9065 * Long term would need debug info to populate names
9066 */
9067 func[i]->aux->name[0] = 'F';
9068 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
9069 func[i]->jit_requested = 1;
9070 func[i]->aux->linfo = prog->aux->linfo;
9071 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
9072 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
9073 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
9074 func[i] = bpf_int_jit_compile(func[i]);
9075 if (!func[i]->jited) {
9076 err = -ENOTSUPP;
9077 goto out_free;
9078 }
9079 cond_resched();
9080 }
9081 /* at this point all bpf functions were successfully JITed
9082 * now populate all bpf_calls with correct addresses and
9083 * run last pass of JIT
9084 */
9085 for (i = 0; i < env->subprog_cnt; i++) {
9086 insn = func[i]->insnsi;
9087 for (j = 0; j < func[i]->len; j++, insn++) {
9088 if (insn->code != (BPF_JMP | BPF_CALL) ||
9089 insn->src_reg != BPF_PSEUDO_CALL)
9090 continue;
9091 subprog = insn->off;
9092 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
9093 __bpf_call_base;
9094 }
9095
9096 /* we use the aux data to keep a list of the start addresses
9097 * of the JITed images for each function in the program
9098 *
9099 * for some architectures, such as powerpc64, the imm field
9100 * might not be large enough to hold the offset of the start
9101 * address of the callee's JITed image from __bpf_call_base
9102 *
9103 * in such cases, we can lookup the start address of a callee
9104 * by using its subprog id, available from the off field of
9105 * the call instruction, as an index for this list
9106 */
9107 func[i]->aux->func = func;
9108 func[i]->aux->func_cnt = env->subprog_cnt;
9109 }
9110 for (i = 0; i < env->subprog_cnt; i++) {
9111 old_bpf_func = func[i]->bpf_func;
9112 tmp = bpf_int_jit_compile(func[i]);
9113 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
9114 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
9115 err = -ENOTSUPP;
9116 goto out_free;
9117 }
9118 cond_resched();
9119 }
9120
9121 /* finally lock prog and jit images for all functions and
9122 * populate kallsysm
9123 */
9124 for (i = 0; i < env->subprog_cnt; i++) {
9125 bpf_prog_lock_ro(func[i]);
9126 bpf_prog_kallsyms_add(func[i]);
9127 }
9128
9129 /* Last step: make now unused interpreter insns from main
9130 * prog consistent for later dump requests, so they can
9131 * later look the same as if they were interpreted only.
9132 */
9133 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9134 if (insn->code != (BPF_JMP | BPF_CALL) ||
9135 insn->src_reg != BPF_PSEUDO_CALL)
9136 continue;
9137 insn->off = env->insn_aux_data[i].call_imm;
9138 subprog = find_subprog(env, i + insn->off + 1);
9139 insn->imm = subprog;
9140 }
9141
9142 prog->jited = 1;
9143 prog->bpf_func = func[0]->bpf_func;
9144 prog->aux->func = func;
9145 prog->aux->func_cnt = env->subprog_cnt;
9146 bpf_prog_free_unused_jited_linfo(prog);
9147 return 0;
9148 out_free:
9149 for (i = 0; i < env->subprog_cnt; i++)
9150 if (func[i])
9151 bpf_jit_free(func[i]);
9152 kfree(func);
9153 out_undo_insn:
9154 /* cleanup main prog to be interpreted */
9155 prog->jit_requested = 0;
9156 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
9157 if (insn->code != (BPF_JMP | BPF_CALL) ||
9158 insn->src_reg != BPF_PSEUDO_CALL)
9159 continue;
9160 insn->off = 0;
9161 insn->imm = env->insn_aux_data[i].call_imm;
9162 }
9163 bpf_prog_free_jited_linfo(prog);
9164 return err;
9165 }
9166
fixup_call_args(struct bpf_verifier_env * env)9167 static int fixup_call_args(struct bpf_verifier_env *env)
9168 {
9169 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9170 struct bpf_prog *prog = env->prog;
9171 struct bpf_insn *insn = prog->insnsi;
9172 int i, depth;
9173 #endif
9174 int err = 0;
9175
9176 if (env->prog->jit_requested &&
9177 !bpf_prog_is_dev_bound(env->prog->aux)) {
9178 err = jit_subprogs(env);
9179 if (err == 0)
9180 return 0;
9181 if (err == -EFAULT)
9182 return err;
9183 }
9184 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
9185 for (i = 0; i < prog->len; i++, insn++) {
9186 if (insn->code != (BPF_JMP | BPF_CALL) ||
9187 insn->src_reg != BPF_PSEUDO_CALL)
9188 continue;
9189 depth = get_callee_stack_depth(env, insn, i);
9190 if (depth < 0)
9191 return depth;
9192 bpf_patch_call_args(insn, depth);
9193 }
9194 err = 0;
9195 #endif
9196 return err;
9197 }
9198
9199 /* fixup insn->imm field of bpf_call instructions
9200 * and inline eligible helpers as explicit sequence of BPF instructions
9201 *
9202 * this function is called after eBPF program passed verification
9203 */
fixup_bpf_calls(struct bpf_verifier_env * env)9204 static int fixup_bpf_calls(struct bpf_verifier_env *env)
9205 {
9206 struct bpf_prog *prog = env->prog;
9207 struct bpf_insn *insn = prog->insnsi;
9208 const struct bpf_func_proto *fn;
9209 const int insn_cnt = prog->len;
9210 const struct bpf_map_ops *ops;
9211 struct bpf_insn_aux_data *aux;
9212 struct bpf_insn insn_buf[16];
9213 struct bpf_prog *new_prog;
9214 struct bpf_map *map_ptr;
9215 int i, cnt, delta = 0;
9216
9217 for (i = 0; i < insn_cnt; i++, insn++) {
9218 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
9219 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
9220 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
9221 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
9222 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
9223 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
9224 struct bpf_insn *patchlet;
9225 struct bpf_insn chk_and_div[] = {
9226 /* [R,W]x div 0 -> 0 */
9227 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
9228 BPF_JNE | BPF_K, insn->src_reg,
9229 0, 2, 0),
9230 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
9231 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9232 *insn,
9233 };
9234 struct bpf_insn chk_and_mod[] = {
9235 /* [R,W]x mod 0 -> [R,W]x */
9236 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
9237 BPF_JEQ | BPF_K, insn->src_reg,
9238 0, 1 + (is64 ? 0 : 1), 0),
9239 *insn,
9240 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
9241 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
9242 };
9243
9244 patchlet = isdiv ? chk_and_div : chk_and_mod;
9245 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9246 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
9247
9248 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
9249 if (!new_prog)
9250 return -ENOMEM;
9251
9252 delta += cnt - 1;
9253 env->prog = prog = new_prog;
9254 insn = new_prog->insnsi + i + delta;
9255 continue;
9256 }
9257
9258 if (BPF_CLASS(insn->code) == BPF_LD &&
9259 (BPF_MODE(insn->code) == BPF_ABS ||
9260 BPF_MODE(insn->code) == BPF_IND)) {
9261 cnt = env->ops->gen_ld_abs(insn, insn_buf);
9262 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9263 verbose(env, "bpf verifier is misconfigured\n");
9264 return -EINVAL;
9265 }
9266
9267 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9268 if (!new_prog)
9269 return -ENOMEM;
9270
9271 delta += cnt - 1;
9272 env->prog = prog = new_prog;
9273 insn = new_prog->insnsi + i + delta;
9274 continue;
9275 }
9276
9277 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
9278 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
9279 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
9280 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
9281 struct bpf_insn insn_buf[16];
9282 struct bpf_insn *patch = &insn_buf[0];
9283 bool issrc, isneg, isimm;
9284 u32 off_reg;
9285
9286 aux = &env->insn_aux_data[i + delta];
9287 if (!aux->alu_state ||
9288 aux->alu_state == BPF_ALU_NON_POINTER)
9289 continue;
9290
9291 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
9292 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
9293 BPF_ALU_SANITIZE_SRC;
9294 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
9295
9296 off_reg = issrc ? insn->src_reg : insn->dst_reg;
9297 if (isimm) {
9298 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
9299 } else {
9300 if (isneg)
9301 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9302 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
9303 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
9304 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
9305 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
9306 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
9307 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
9308 }
9309 if (!issrc)
9310 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
9311 insn->src_reg = BPF_REG_AX;
9312 if (isneg)
9313 insn->code = insn->code == code_add ?
9314 code_sub : code_add;
9315 *patch++ = *insn;
9316 if (issrc && isneg && !isimm)
9317 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
9318 cnt = patch - insn_buf;
9319
9320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9321 if (!new_prog)
9322 return -ENOMEM;
9323
9324 delta += cnt - 1;
9325 env->prog = prog = new_prog;
9326 insn = new_prog->insnsi + i + delta;
9327 continue;
9328 }
9329
9330 if (insn->code != (BPF_JMP | BPF_CALL))
9331 continue;
9332 if (insn->src_reg == BPF_PSEUDO_CALL)
9333 continue;
9334
9335 if (insn->imm == BPF_FUNC_get_route_realm)
9336 prog->dst_needed = 1;
9337 if (insn->imm == BPF_FUNC_get_prandom_u32)
9338 bpf_user_rnd_init_once();
9339 if (insn->imm == BPF_FUNC_override_return)
9340 prog->kprobe_override = 1;
9341 if (insn->imm == BPF_FUNC_tail_call) {
9342 /* If we tail call into other programs, we
9343 * cannot make any assumptions since they can
9344 * be replaced dynamically during runtime in
9345 * the program array.
9346 */
9347 prog->cb_access = 1;
9348 env->prog->aux->stack_depth = MAX_BPF_STACK;
9349 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF;
9350
9351 /* mark bpf_tail_call as different opcode to avoid
9352 * conditional branch in the interpeter for every normal
9353 * call and to prevent accidental JITing by JIT compiler
9354 * that doesn't support bpf_tail_call yet
9355 */
9356 insn->imm = 0;
9357 insn->code = BPF_JMP | BPF_TAIL_CALL;
9358
9359 aux = &env->insn_aux_data[i + delta];
9360 if (!bpf_map_ptr_unpriv(aux))
9361 continue;
9362
9363 /* instead of changing every JIT dealing with tail_call
9364 * emit two extra insns:
9365 * if (index >= max_entries) goto out;
9366 * index &= array->index_mask;
9367 * to avoid out-of-bounds cpu speculation
9368 */
9369 if (bpf_map_ptr_poisoned(aux)) {
9370 verbose(env, "tail_call abusing map_ptr\n");
9371 return -EINVAL;
9372 }
9373
9374 map_ptr = BPF_MAP_PTR(aux->map_state);
9375 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
9376 map_ptr->max_entries, 2);
9377 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
9378 container_of(map_ptr,
9379 struct bpf_array,
9380 map)->index_mask);
9381 insn_buf[2] = *insn;
9382 cnt = 3;
9383 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9384 if (!new_prog)
9385 return -ENOMEM;
9386
9387 delta += cnt - 1;
9388 env->prog = prog = new_prog;
9389 insn = new_prog->insnsi + i + delta;
9390 continue;
9391 }
9392
9393 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
9394 * and other inlining handlers are currently limited to 64 bit
9395 * only.
9396 */
9397 if (prog->jit_requested && BITS_PER_LONG == 64 &&
9398 (insn->imm == BPF_FUNC_map_lookup_elem ||
9399 insn->imm == BPF_FUNC_map_update_elem ||
9400 insn->imm == BPF_FUNC_map_delete_elem ||
9401 insn->imm == BPF_FUNC_map_push_elem ||
9402 insn->imm == BPF_FUNC_map_pop_elem ||
9403 insn->imm == BPF_FUNC_map_peek_elem)) {
9404 aux = &env->insn_aux_data[i + delta];
9405 if (bpf_map_ptr_poisoned(aux))
9406 goto patch_call_imm;
9407
9408 map_ptr = BPF_MAP_PTR(aux->map_state);
9409 ops = map_ptr->ops;
9410 if (insn->imm == BPF_FUNC_map_lookup_elem &&
9411 ops->map_gen_lookup) {
9412 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
9413 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
9414 verbose(env, "bpf verifier is misconfigured\n");
9415 return -EINVAL;
9416 }
9417
9418 new_prog = bpf_patch_insn_data(env, i + delta,
9419 insn_buf, cnt);
9420 if (!new_prog)
9421 return -ENOMEM;
9422
9423 delta += cnt - 1;
9424 env->prog = prog = new_prog;
9425 insn = new_prog->insnsi + i + delta;
9426 continue;
9427 }
9428
9429 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
9430 (void *(*)(struct bpf_map *map, void *key))NULL));
9431 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
9432 (int (*)(struct bpf_map *map, void *key))NULL));
9433 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
9434 (int (*)(struct bpf_map *map, void *key, void *value,
9435 u64 flags))NULL));
9436 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
9437 (int (*)(struct bpf_map *map, void *value,
9438 u64 flags))NULL));
9439 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
9440 (int (*)(struct bpf_map *map, void *value))NULL));
9441 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
9442 (int (*)(struct bpf_map *map, void *value))NULL));
9443
9444 switch (insn->imm) {
9445 case BPF_FUNC_map_lookup_elem:
9446 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
9447 __bpf_call_base;
9448 continue;
9449 case BPF_FUNC_map_update_elem:
9450 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
9451 __bpf_call_base;
9452 continue;
9453 case BPF_FUNC_map_delete_elem:
9454 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
9455 __bpf_call_base;
9456 continue;
9457 case BPF_FUNC_map_push_elem:
9458 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
9459 __bpf_call_base;
9460 continue;
9461 case BPF_FUNC_map_pop_elem:
9462 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
9463 __bpf_call_base;
9464 continue;
9465 case BPF_FUNC_map_peek_elem:
9466 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
9467 __bpf_call_base;
9468 continue;
9469 }
9470
9471 goto patch_call_imm;
9472 }
9473
9474 patch_call_imm:
9475 fn = env->ops->get_func_proto(insn->imm, env->prog);
9476 /* all functions that have prototype and verifier allowed
9477 * programs to call them, must be real in-kernel functions
9478 */
9479 if (!fn->func) {
9480 verbose(env,
9481 "kernel subsystem misconfigured func %s#%d\n",
9482 func_id_name(insn->imm), insn->imm);
9483 return -EFAULT;
9484 }
9485 insn->imm = fn->func - __bpf_call_base;
9486 }
9487
9488 return 0;
9489 }
9490
free_states(struct bpf_verifier_env * env)9491 static void free_states(struct bpf_verifier_env *env)
9492 {
9493 struct bpf_verifier_state_list *sl, *sln;
9494 int i;
9495
9496 sl = env->free_list;
9497 while (sl) {
9498 sln = sl->next;
9499 free_verifier_state(&sl->state, false);
9500 kfree(sl);
9501 sl = sln;
9502 }
9503
9504 if (!env->explored_states)
9505 return;
9506
9507 for (i = 0; i < state_htab_size(env); i++) {
9508 sl = env->explored_states[i];
9509
9510 while (sl) {
9511 sln = sl->next;
9512 free_verifier_state(&sl->state, false);
9513 kfree(sl);
9514 sl = sln;
9515 }
9516 }
9517
9518 kvfree(env->explored_states);
9519 }
9520
print_verification_stats(struct bpf_verifier_env * env)9521 static void print_verification_stats(struct bpf_verifier_env *env)
9522 {
9523 int i;
9524
9525 if (env->log.level & BPF_LOG_STATS) {
9526 verbose(env, "verification time %lld usec\n",
9527 div_u64(env->verification_time, 1000));
9528 verbose(env, "stack depth ");
9529 for (i = 0; i < env->subprog_cnt; i++) {
9530 u32 depth = env->subprog_info[i].stack_depth;
9531
9532 verbose(env, "%d", depth);
9533 if (i + 1 < env->subprog_cnt)
9534 verbose(env, "+");
9535 }
9536 verbose(env, "\n");
9537 }
9538 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
9539 "total_states %d peak_states %d mark_read %d\n",
9540 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
9541 env->max_states_per_insn, env->total_states,
9542 env->peak_states, env->longest_mark_read_walk);
9543 }
9544
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr,union bpf_attr __user * uattr)9545 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
9546 union bpf_attr __user *uattr)
9547 {
9548 u64 start_time = ktime_get_ns();
9549 struct bpf_verifier_env *env;
9550 struct bpf_verifier_log *log;
9551 int i, len, ret = -EINVAL;
9552 bool is_priv;
9553
9554 /* no program is valid */
9555 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
9556 return -EINVAL;
9557
9558 /* 'struct bpf_verifier_env' can be global, but since it's not small,
9559 * allocate/free it every time bpf_check() is called
9560 */
9561 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
9562 if (!env)
9563 return -ENOMEM;
9564 log = &env->log;
9565
9566 len = (*prog)->len;
9567 env->insn_aux_data =
9568 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
9569 ret = -ENOMEM;
9570 if (!env->insn_aux_data)
9571 goto err_free_env;
9572 for (i = 0; i < len; i++)
9573 env->insn_aux_data[i].orig_idx = i;
9574 env->prog = *prog;
9575 env->ops = bpf_verifier_ops[env->prog->type];
9576 is_priv = capable(CAP_SYS_ADMIN);
9577
9578 /* grab the mutex to protect few globals used by verifier */
9579 if (!is_priv)
9580 mutex_lock(&bpf_verifier_lock);
9581
9582 if (attr->log_level || attr->log_buf || attr->log_size) {
9583 /* user requested verbose verifier output
9584 * and supplied buffer to store the verification trace
9585 */
9586 log->level = attr->log_level;
9587 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
9588 log->len_total = attr->log_size;
9589
9590 ret = -EINVAL;
9591 /* log attributes have to be sane */
9592 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
9593 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
9594 goto err_unlock;
9595 }
9596
9597 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
9598 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
9599 env->strict_alignment = true;
9600 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
9601 env->strict_alignment = false;
9602
9603 env->allow_ptr_leaks = is_priv;
9604
9605 if (is_priv)
9606 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
9607
9608 ret = replace_map_fd_with_map_ptr(env);
9609 if (ret < 0)
9610 goto skip_full_check;
9611
9612 if (bpf_prog_is_dev_bound(env->prog->aux)) {
9613 ret = bpf_prog_offload_verifier_prep(env->prog);
9614 if (ret)
9615 goto skip_full_check;
9616 }
9617
9618 env->explored_states = kvcalloc(state_htab_size(env),
9619 sizeof(struct bpf_verifier_state_list *),
9620 GFP_USER);
9621 ret = -ENOMEM;
9622 if (!env->explored_states)
9623 goto skip_full_check;
9624
9625 ret = check_subprogs(env);
9626 if (ret < 0)
9627 goto skip_full_check;
9628
9629 ret = check_btf_info(env, attr, uattr);
9630 if (ret < 0)
9631 goto skip_full_check;
9632
9633 ret = check_cfg(env);
9634 if (ret < 0)
9635 goto skip_full_check;
9636
9637 ret = do_check(env);
9638 if (env->cur_state) {
9639 free_verifier_state(env->cur_state, true);
9640 env->cur_state = NULL;
9641 }
9642
9643 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
9644 ret = bpf_prog_offload_finalize(env);
9645
9646 skip_full_check:
9647 while (!pop_stack(env, NULL, NULL));
9648 free_states(env);
9649
9650 if (ret == 0)
9651 ret = check_max_stack_depth(env);
9652
9653 /* instruction rewrites happen after this point */
9654 if (is_priv) {
9655 if (ret == 0)
9656 opt_hard_wire_dead_code_branches(env);
9657 if (ret == 0)
9658 ret = opt_remove_dead_code(env);
9659 if (ret == 0)
9660 ret = opt_remove_nops(env);
9661 } else {
9662 if (ret == 0)
9663 sanitize_dead_code(env);
9664 }
9665
9666 if (ret == 0)
9667 /* program is valid, convert *(u32*)(ctx + off) accesses */
9668 ret = convert_ctx_accesses(env);
9669
9670 if (ret == 0)
9671 ret = fixup_bpf_calls(env);
9672
9673 /* do 32-bit optimization after insn patching has done so those patched
9674 * insns could be handled correctly.
9675 */
9676 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
9677 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
9678 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
9679 : false;
9680 }
9681
9682 if (ret == 0)
9683 ret = fixup_call_args(env);
9684
9685 env->verification_time = ktime_get_ns() - start_time;
9686 print_verification_stats(env);
9687
9688 if (log->level && bpf_verifier_log_full(log))
9689 ret = -ENOSPC;
9690 if (log->level && !log->ubuf) {
9691 ret = -EFAULT;
9692 goto err_release_maps;
9693 }
9694
9695 if (ret == 0 && env->used_map_cnt) {
9696 /* if program passed verifier, update used_maps in bpf_prog_info */
9697 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
9698 sizeof(env->used_maps[0]),
9699 GFP_KERNEL);
9700
9701 if (!env->prog->aux->used_maps) {
9702 ret = -ENOMEM;
9703 goto err_release_maps;
9704 }
9705
9706 memcpy(env->prog->aux->used_maps, env->used_maps,
9707 sizeof(env->used_maps[0]) * env->used_map_cnt);
9708 env->prog->aux->used_map_cnt = env->used_map_cnt;
9709
9710 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
9711 * bpf_ld_imm64 instructions
9712 */
9713 convert_pseudo_ld_imm64(env);
9714 }
9715
9716 if (ret == 0)
9717 adjust_btf_func(env);
9718
9719 err_release_maps:
9720 if (!env->prog->aux->used_maps)
9721 /* if we didn't copy map pointers into bpf_prog_info, release
9722 * them now. Otherwise free_used_maps() will release them.
9723 */
9724 release_maps(env);
9725 *prog = env->prog;
9726 err_unlock:
9727 if (!is_priv)
9728 mutex_unlock(&bpf_verifier_lock);
9729 vfree(env->insn_aux_data);
9730 err_free_env:
9731 kfree(env);
9732 return ret;
9733 }
9734