]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blob - kernel/bpf/verifier.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[mirror_ubuntu-jammy-kernel.git] / kernel / bpf / verifier.c
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22 #include <linux/stringify.h>
23 #include <linux/bsearch.h>
24 #include <linux/sort.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name) \
30 [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #include <linux/bpf_types.h>
33 #undef BPF_PROG_TYPE
34 #undef BPF_MAP_TYPE
35 };
36
37 /* bpf_check() is a static code analyzer that walks eBPF program
38 * instruction by instruction and updates register/stack state.
39 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
40 *
41 * The first pass is depth-first-search to check that the program is a DAG.
42 * It rejects the following programs:
43 * - larger than BPF_MAXINSNS insns
44 * - if loop is present (detected via back-edge)
45 * - unreachable insns exist (shouldn't be a forest. program = one function)
46 * - out of bounds or malformed jumps
47 * The second pass is all possible path descent from the 1st insn.
48 * Since it's analyzing all pathes through the program, the length of the
49 * analysis is limited to 64k insn, which may be hit even if total number of
50 * insn is less then 4K, but there are too many branches that change stack/regs.
51 * Number of 'branches to be analyzed' is limited to 1k
52 *
53 * On entry to each instruction, each register has a type, and the instruction
54 * changes the types of the registers depending on instruction semantics.
55 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
56 * copied to R1.
57 *
58 * All registers are 64-bit.
59 * R0 - return register
60 * R1-R5 argument passing registers
61 * R6-R9 callee saved registers
62 * R10 - frame pointer read-only
63 *
64 * At the start of BPF program the register R1 contains a pointer to bpf_context
65 * and has type PTR_TO_CTX.
66 *
67 * Verifier tracks arithmetic operations on pointers in case:
68 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
69 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
70 * 1st insn copies R10 (which has FRAME_PTR) type into R1
71 * and 2nd arithmetic instruction is pattern matched to recognize
72 * that it wants to construct a pointer to some element within stack.
73 * So after 2nd insn, the register R1 has type PTR_TO_STACK
74 * (and -20 constant is saved for further stack bounds checking).
75 * Meaning that this reg is a pointer to stack plus known immediate constant.
76 *
77 * Most of the time the registers have SCALAR_VALUE type, which
78 * means the register has some value, but it's not a valid pointer.
79 * (like pointer plus pointer becomes SCALAR_VALUE type)
80 *
81 * When verifier sees load or store instructions the type of base register
82 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
83 * types recognized by check_mem_access() function.
84 *
85 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
86 * and the range of [ptr, ptr + map's value_size) is accessible.
87 *
88 * registers used to pass values to function calls are checked against
89 * function argument constraints.
90 *
91 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
92 * It means that the register type passed to this function must be
93 * PTR_TO_STACK and it will be used inside the function as
94 * 'pointer to map element key'
95 *
96 * For example the argument constraints for bpf_map_lookup_elem():
97 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
98 * .arg1_type = ARG_CONST_MAP_PTR,
99 * .arg2_type = ARG_PTR_TO_MAP_KEY,
100 *
101 * ret_type says that this function returns 'pointer to map elem value or null'
102 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
103 * 2nd argument should be a pointer to stack, which will be used inside
104 * the helper function as a pointer to map element key.
105 *
106 * On the kernel side the helper function looks like:
107 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
108 * {
109 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
110 * void *key = (void *) (unsigned long) r2;
111 * void *value;
112 *
113 * here kernel can access 'key' and 'map' pointers safely, knowing that
114 * [key, key + map->key_size) bytes are valid and were initialized on
115 * the stack of eBPF program.
116 * }
117 *
118 * Corresponding eBPF program may look like:
119 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
120 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
121 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
122 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
123 * here verifier looks at prototype of map_lookup_elem() and sees:
124 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
125 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
126 *
127 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
128 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
129 * and were initialized prior to this call.
130 * If it's ok, then verifier allows this BPF_CALL insn and looks at
131 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
132 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
133 * returns ether pointer to map value or NULL.
134 *
135 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
136 * insn, the register holding that pointer in the true branch changes state to
137 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
138 * branch. See check_cond_jmp_op().
139 *
140 * After the call R0 is set to return type of the function and registers R1-R5
141 * are set to NOT_INIT to indicate that they are no longer readable.
142 */
143
144 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
145 struct bpf_verifier_stack_elem {
146 /* verifer state is 'st'
147 * before processing instruction 'insn_idx'
148 * and after processing instruction 'prev_insn_idx'
149 */
150 struct bpf_verifier_state st;
151 int insn_idx;
152 int prev_insn_idx;
153 struct bpf_verifier_stack_elem *next;
154 };
155
156 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
157 #define BPF_COMPLEXITY_LIMIT_STACK 1024
158
159 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
160
161 struct bpf_call_arg_meta {
162 struct bpf_map *map_ptr;
163 bool raw_mode;
164 bool pkt_access;
165 int regno;
166 int access_size;
167 };
168
169 static DEFINE_MUTEX(bpf_verifier_lock);
170
171 /* log_level controls verbosity level of eBPF verifier.
172 * bpf_verifier_log_write() is used to dump the verification trace to the log,
173 * so the user can figure out what's wrong with the program
174 */
175 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
176 const char *fmt, ...)
177 {
178 struct bpf_verifer_log *log = &env->log;
179 unsigned int n;
180 va_list args;
181
182 if (!log->level || !log->ubuf || bpf_verifier_log_full(log))
183 return;
184
185 va_start(args, fmt);
186 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
187 va_end(args);
188
189 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
190 "verifier log line truncated - local buffer too short\n");
191
192 n = min(log->len_total - log->len_used - 1, n);
193 log->kbuf[n] = '\0';
194
195 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
196 log->len_used += n;
197 else
198 log->ubuf = NULL;
199 }
200 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
201 /* Historically bpf_verifier_log_write was called verbose, but the name was too
202 * generic for symbol export. The function was renamed, but not the calls in
203 * the verifier to avoid complicating backports. Hence the alias below.
204 */
205 static __printf(2, 3) void verbose(struct bpf_verifier_env *env,
206 const char *fmt, ...)
207 __attribute__((alias("bpf_verifier_log_write")));
208
209 static bool type_is_pkt_pointer(enum bpf_reg_type type)
210 {
211 return type == PTR_TO_PACKET ||
212 type == PTR_TO_PACKET_META;
213 }
214
215 /* string representation of 'enum bpf_reg_type' */
216 static const char * const reg_type_str[] = {
217 [NOT_INIT] = "?",
218 [SCALAR_VALUE] = "inv",
219 [PTR_TO_CTX] = "ctx",
220 [CONST_PTR_TO_MAP] = "map_ptr",
221 [PTR_TO_MAP_VALUE] = "map_value",
222 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
223 [PTR_TO_STACK] = "fp",
224 [PTR_TO_PACKET] = "pkt",
225 [PTR_TO_PACKET_META] = "pkt_meta",
226 [PTR_TO_PACKET_END] = "pkt_end",
227 };
228
229 static void print_liveness(struct bpf_verifier_env *env,
230 enum bpf_reg_liveness live)
231 {
232 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
233 verbose(env, "_");
234 if (live & REG_LIVE_READ)
235 verbose(env, "r");
236 if (live & REG_LIVE_WRITTEN)
237 verbose(env, "w");
238 }
239
240 static struct bpf_func_state *func(struct bpf_verifier_env *env,
241 const struct bpf_reg_state *reg)
242 {
243 struct bpf_verifier_state *cur = env->cur_state;
244
245 return cur->frame[reg->frameno];
246 }
247
248 static void print_verifier_state(struct bpf_verifier_env *env,
249 const struct bpf_func_state *state)
250 {
251 const struct bpf_reg_state *reg;
252 enum bpf_reg_type t;
253 int i;
254
255 if (state->frameno)
256 verbose(env, " frame%d:", state->frameno);
257 for (i = 0; i < MAX_BPF_REG; i++) {
258 reg = &state->regs[i];
259 t = reg->type;
260 if (t == NOT_INIT)
261 continue;
262 verbose(env, " R%d", i);
263 print_liveness(env, reg->live);
264 verbose(env, "=%s", reg_type_str[t]);
265 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
266 tnum_is_const(reg->var_off)) {
267 /* reg->off should be 0 for SCALAR_VALUE */
268 verbose(env, "%lld", reg->var_off.value + reg->off);
269 if (t == PTR_TO_STACK)
270 verbose(env, ",call_%d", func(env, reg)->callsite);
271 } else {
272 verbose(env, "(id=%d", reg->id);
273 if (t != SCALAR_VALUE)
274 verbose(env, ",off=%d", reg->off);
275 if (type_is_pkt_pointer(t))
276 verbose(env, ",r=%d", reg->range);
277 else if (t == CONST_PTR_TO_MAP ||
278 t == PTR_TO_MAP_VALUE ||
279 t == PTR_TO_MAP_VALUE_OR_NULL)
280 verbose(env, ",ks=%d,vs=%d",
281 reg->map_ptr->key_size,
282 reg->map_ptr->value_size);
283 if (tnum_is_const(reg->var_off)) {
284 /* Typically an immediate SCALAR_VALUE, but
285 * could be a pointer whose offset is too big
286 * for reg->off
287 */
288 verbose(env, ",imm=%llx", reg->var_off.value);
289 } else {
290 if (reg->smin_value != reg->umin_value &&
291 reg->smin_value != S64_MIN)
292 verbose(env, ",smin_value=%lld",
293 (long long)reg->smin_value);
294 if (reg->smax_value != reg->umax_value &&
295 reg->smax_value != S64_MAX)
296 verbose(env, ",smax_value=%lld",
297 (long long)reg->smax_value);
298 if (reg->umin_value != 0)
299 verbose(env, ",umin_value=%llu",
300 (unsigned long long)reg->umin_value);
301 if (reg->umax_value != U64_MAX)
302 verbose(env, ",umax_value=%llu",
303 (unsigned long long)reg->umax_value);
304 if (!tnum_is_unknown(reg->var_off)) {
305 char tn_buf[48];
306
307 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
308 verbose(env, ",var_off=%s", tn_buf);
309 }
310 }
311 verbose(env, ")");
312 }
313 }
314 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
315 if (state->stack[i].slot_type[0] == STACK_SPILL) {
316 verbose(env, " fp%d",
317 (-i - 1) * BPF_REG_SIZE);
318 print_liveness(env, state->stack[i].spilled_ptr.live);
319 verbose(env, "=%s",
320 reg_type_str[state->stack[i].spilled_ptr.type]);
321 }
322 if (state->stack[i].slot_type[0] == STACK_ZERO)
323 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
324 }
325 verbose(env, "\n");
326 }
327
328 static int copy_stack_state(struct bpf_func_state *dst,
329 const struct bpf_func_state *src)
330 {
331 if (!src->stack)
332 return 0;
333 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
334 /* internal bug, make state invalid to reject the program */
335 memset(dst, 0, sizeof(*dst));
336 return -EFAULT;
337 }
338 memcpy(dst->stack, src->stack,
339 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
340 return 0;
341 }
342
343 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
344 * make it consume minimal amount of memory. check_stack_write() access from
345 * the program calls into realloc_func_state() to grow the stack size.
346 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
347 * which this function copies over. It points to previous bpf_verifier_state
348 * which is never reallocated
349 */
350 static int realloc_func_state(struct bpf_func_state *state, int size,
351 bool copy_old)
352 {
353 u32 old_size = state->allocated_stack;
354 struct bpf_stack_state *new_stack;
355 int slot = size / BPF_REG_SIZE;
356
357 if (size <= old_size || !size) {
358 if (copy_old)
359 return 0;
360 state->allocated_stack = slot * BPF_REG_SIZE;
361 if (!size && old_size) {
362 kfree(state->stack);
363 state->stack = NULL;
364 }
365 return 0;
366 }
367 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
368 GFP_KERNEL);
369 if (!new_stack)
370 return -ENOMEM;
371 if (copy_old) {
372 if (state->stack)
373 memcpy(new_stack, state->stack,
374 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
375 memset(new_stack + old_size / BPF_REG_SIZE, 0,
376 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
377 }
378 state->allocated_stack = slot * BPF_REG_SIZE;
379 kfree(state->stack);
380 state->stack = new_stack;
381 return 0;
382 }
383
384 static void free_func_state(struct bpf_func_state *state)
385 {
386 if (!state)
387 return;
388 kfree(state->stack);
389 kfree(state);
390 }
391
392 static void free_verifier_state(struct bpf_verifier_state *state,
393 bool free_self)
394 {
395 int i;
396
397 for (i = 0; i <= state->curframe; i++) {
398 free_func_state(state->frame[i]);
399 state->frame[i] = NULL;
400 }
401 if (free_self)
402 kfree(state);
403 }
404
405 /* copy verifier state from src to dst growing dst stack space
406 * when necessary to accommodate larger src stack
407 */
408 static int copy_func_state(struct bpf_func_state *dst,
409 const struct bpf_func_state *src)
410 {
411 int err;
412
413 err = realloc_func_state(dst, src->allocated_stack, false);
414 if (err)
415 return err;
416 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
417 return copy_stack_state(dst, src);
418 }
419
420 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
421 const struct bpf_verifier_state *src)
422 {
423 struct bpf_func_state *dst;
424 int i, err;
425
426 /* if dst has more stack frames then src frame, free them */
427 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
428 free_func_state(dst_state->frame[i]);
429 dst_state->frame[i] = NULL;
430 }
431 dst_state->curframe = src->curframe;
432 dst_state->parent = src->parent;
433 for (i = 0; i <= src->curframe; i++) {
434 dst = dst_state->frame[i];
435 if (!dst) {
436 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
437 if (!dst)
438 return -ENOMEM;
439 dst_state->frame[i] = dst;
440 }
441 err = copy_func_state(dst, src->frame[i]);
442 if (err)
443 return err;
444 }
445 return 0;
446 }
447
448 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
449 int *insn_idx)
450 {
451 struct bpf_verifier_state *cur = env->cur_state;
452 struct bpf_verifier_stack_elem *elem, *head = env->head;
453 int err;
454
455 if (env->head == NULL)
456 return -ENOENT;
457
458 if (cur) {
459 err = copy_verifier_state(cur, &head->st);
460 if (err)
461 return err;
462 }
463 if (insn_idx)
464 *insn_idx = head->insn_idx;
465 if (prev_insn_idx)
466 *prev_insn_idx = head->prev_insn_idx;
467 elem = head->next;
468 free_verifier_state(&head->st, false);
469 kfree(head);
470 env->head = elem;
471 env->stack_size--;
472 return 0;
473 }
474
475 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
476 int insn_idx, int prev_insn_idx)
477 {
478 struct bpf_verifier_state *cur = env->cur_state;
479 struct bpf_verifier_stack_elem *elem;
480 int err;
481
482 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
483 if (!elem)
484 goto err;
485
486 elem->insn_idx = insn_idx;
487 elem->prev_insn_idx = prev_insn_idx;
488 elem->next = env->head;
489 env->head = elem;
490 env->stack_size++;
491 err = copy_verifier_state(&elem->st, cur);
492 if (err)
493 goto err;
494 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
495 verbose(env, "BPF program is too complex\n");
496 goto err;
497 }
498 return &elem->st;
499 err:
500 free_verifier_state(env->cur_state, true);
501 env->cur_state = NULL;
502 /* pop all elements and return */
503 while (!pop_stack(env, NULL, NULL));
504 return NULL;
505 }
506
507 #define CALLER_SAVED_REGS 6
508 static const int caller_saved[CALLER_SAVED_REGS] = {
509 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
510 };
511 #define CALLEE_SAVED_REGS 5
512 static const int callee_saved[CALLEE_SAVED_REGS] = {
513 BPF_REG_6, BPF_REG_7, BPF_REG_8, BPF_REG_9
514 };
515
516 static void __mark_reg_not_init(struct bpf_reg_state *reg);
517
518 /* Mark the unknown part of a register (variable offset or scalar value) as
519 * known to have the value @imm.
520 */
521 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
522 {
523 reg->id = 0;
524 reg->var_off = tnum_const(imm);
525 reg->smin_value = (s64)imm;
526 reg->smax_value = (s64)imm;
527 reg->umin_value = imm;
528 reg->umax_value = imm;
529 }
530
531 /* Mark the 'variable offset' part of a register as zero. This should be
532 * used only on registers holding a pointer type.
533 */
534 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
535 {
536 __mark_reg_known(reg, 0);
537 }
538
539 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
540 {
541 __mark_reg_known(reg, 0);
542 reg->off = 0;
543 reg->type = SCALAR_VALUE;
544 }
545
546 static void mark_reg_known_zero(struct bpf_verifier_env *env,
547 struct bpf_reg_state *regs, u32 regno)
548 {
549 if (WARN_ON(regno >= MAX_BPF_REG)) {
550 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
551 /* Something bad happened, let's kill all regs */
552 for (regno = 0; regno < MAX_BPF_REG; regno++)
553 __mark_reg_not_init(regs + regno);
554 return;
555 }
556 __mark_reg_known_zero(regs + regno);
557 }
558
559 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
560 {
561 return type_is_pkt_pointer(reg->type);
562 }
563
564 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
565 {
566 return reg_is_pkt_pointer(reg) ||
567 reg->type == PTR_TO_PACKET_END;
568 }
569
570 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
571 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
572 enum bpf_reg_type which)
573 {
574 /* The register can already have a range from prior markings.
575 * This is fine as long as it hasn't been advanced from its
576 * origin.
577 */
578 return reg->type == which &&
579 reg->id == 0 &&
580 reg->off == 0 &&
581 tnum_equals_const(reg->var_off, 0);
582 }
583
584 /* Attempts to improve min/max values based on var_off information */
585 static void __update_reg_bounds(struct bpf_reg_state *reg)
586 {
587 /* min signed is max(sign bit) | min(other bits) */
588 reg->smin_value = max_t(s64, reg->smin_value,
589 reg->var_off.value | (reg->var_off.mask & S64_MIN));
590 /* max signed is min(sign bit) | max(other bits) */
591 reg->smax_value = min_t(s64, reg->smax_value,
592 reg->var_off.value | (reg->var_off.mask & S64_MAX));
593 reg->umin_value = max(reg->umin_value, reg->var_off.value);
594 reg->umax_value = min(reg->umax_value,
595 reg->var_off.value | reg->var_off.mask);
596 }
597
598 /* Uses signed min/max values to inform unsigned, and vice-versa */
599 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
600 {
601 /* Learn sign from signed bounds.
602 * If we cannot cross the sign boundary, then signed and unsigned bounds
603 * are the same, so combine. This works even in the negative case, e.g.
604 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
605 */
606 if (reg->smin_value >= 0 || reg->smax_value < 0) {
607 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
608 reg->umin_value);
609 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
610 reg->umax_value);
611 return;
612 }
613 /* Learn sign from unsigned bounds. Signed bounds cross the sign
614 * boundary, so we must be careful.
615 */
616 if ((s64)reg->umax_value >= 0) {
617 /* Positive. We can't learn anything from the smin, but smax
618 * is positive, hence safe.
619 */
620 reg->smin_value = reg->umin_value;
621 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
622 reg->umax_value);
623 } else if ((s64)reg->umin_value < 0) {
624 /* Negative. We can't learn anything from the smax, but smin
625 * is negative, hence safe.
626 */
627 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
628 reg->umin_value);
629 reg->smax_value = reg->umax_value;
630 }
631 }
632
633 /* Attempts to improve var_off based on unsigned min/max information */
634 static void __reg_bound_offset(struct bpf_reg_state *reg)
635 {
636 reg->var_off = tnum_intersect(reg->var_off,
637 tnum_range(reg->umin_value,
638 reg->umax_value));
639 }
640
641 /* Reset the min/max bounds of a register */
642 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
643 {
644 reg->smin_value = S64_MIN;
645 reg->smax_value = S64_MAX;
646 reg->umin_value = 0;
647 reg->umax_value = U64_MAX;
648 }
649
650 /* Mark a register as having a completely unknown (scalar) value. */
651 static void __mark_reg_unknown(struct bpf_reg_state *reg)
652 {
653 reg->type = SCALAR_VALUE;
654 reg->id = 0;
655 reg->off = 0;
656 reg->var_off = tnum_unknown;
657 reg->frameno = 0;
658 __mark_reg_unbounded(reg);
659 }
660
661 static void mark_reg_unknown(struct bpf_verifier_env *env,
662 struct bpf_reg_state *regs, u32 regno)
663 {
664 if (WARN_ON(regno >= MAX_BPF_REG)) {
665 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
666 /* Something bad happened, let's kill all regs except FP */
667 for (regno = 0; regno < BPF_REG_FP; regno++)
668 __mark_reg_not_init(regs + regno);
669 return;
670 }
671 __mark_reg_unknown(regs + regno);
672 }
673
674 static void __mark_reg_not_init(struct bpf_reg_state *reg)
675 {
676 __mark_reg_unknown(reg);
677 reg->type = NOT_INIT;
678 }
679
680 static void mark_reg_not_init(struct bpf_verifier_env *env,
681 struct bpf_reg_state *regs, u32 regno)
682 {
683 if (WARN_ON(regno >= MAX_BPF_REG)) {
684 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
685 /* Something bad happened, let's kill all regs except FP */
686 for (regno = 0; regno < BPF_REG_FP; regno++)
687 __mark_reg_not_init(regs + regno);
688 return;
689 }
690 __mark_reg_not_init(regs + regno);
691 }
692
693 static void init_reg_state(struct bpf_verifier_env *env,
694 struct bpf_func_state *state)
695 {
696 struct bpf_reg_state *regs = state->regs;
697 int i;
698
699 for (i = 0; i < MAX_BPF_REG; i++) {
700 mark_reg_not_init(env, regs, i);
701 regs[i].live = REG_LIVE_NONE;
702 }
703
704 /* frame pointer */
705 regs[BPF_REG_FP].type = PTR_TO_STACK;
706 mark_reg_known_zero(env, regs, BPF_REG_FP);
707 regs[BPF_REG_FP].frameno = state->frameno;
708
709 /* 1st arg to a function */
710 regs[BPF_REG_1].type = PTR_TO_CTX;
711 mark_reg_known_zero(env, regs, BPF_REG_1);
712 }
713
714 #define BPF_MAIN_FUNC (-1)
715 static void init_func_state(struct bpf_verifier_env *env,
716 struct bpf_func_state *state,
717 int callsite, int frameno, int subprogno)
718 {
719 state->callsite = callsite;
720 state->frameno = frameno;
721 state->subprogno = subprogno;
722 init_reg_state(env, state);
723 }
724
725 enum reg_arg_type {
726 SRC_OP, /* register is used as source operand */
727 DST_OP, /* register is used as destination operand */
728 DST_OP_NO_MARK /* same as above, check only, don't mark */
729 };
730
731 static int cmp_subprogs(const void *a, const void *b)
732 {
733 return *(int *)a - *(int *)b;
734 }
735
736 static int find_subprog(struct bpf_verifier_env *env, int off)
737 {
738 u32 *p;
739
740 p = bsearch(&off, env->subprog_starts, env->subprog_cnt,
741 sizeof(env->subprog_starts[0]), cmp_subprogs);
742 if (!p)
743 return -ENOENT;
744 return p - env->subprog_starts;
745
746 }
747
748 static int add_subprog(struct bpf_verifier_env *env, int off)
749 {
750 int insn_cnt = env->prog->len;
751 int ret;
752
753 if (off >= insn_cnt || off < 0) {
754 verbose(env, "call to invalid destination\n");
755 return -EINVAL;
756 }
757 ret = find_subprog(env, off);
758 if (ret >= 0)
759 return 0;
760 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
761 verbose(env, "too many subprograms\n");
762 return -E2BIG;
763 }
764 env->subprog_starts[env->subprog_cnt++] = off;
765 sort(env->subprog_starts, env->subprog_cnt,
766 sizeof(env->subprog_starts[0]), cmp_subprogs, NULL);
767 return 0;
768 }
769
770 static int check_subprogs(struct bpf_verifier_env *env)
771 {
772 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
773 struct bpf_insn *insn = env->prog->insnsi;
774 int insn_cnt = env->prog->len;
775
776 /* determine subprog starts. The end is one before the next starts */
777 for (i = 0; i < insn_cnt; i++) {
778 if (insn[i].code != (BPF_JMP | BPF_CALL))
779 continue;
780 if (insn[i].src_reg != BPF_PSEUDO_CALL)
781 continue;
782 if (!env->allow_ptr_leaks) {
783 verbose(env, "function calls to other bpf functions are allowed for root only\n");
784 return -EPERM;
785 }
786 if (bpf_prog_is_dev_bound(env->prog->aux)) {
787 verbose(env, "function calls in offloaded programs are not supported yet\n");
788 return -EINVAL;
789 }
790 ret = add_subprog(env, i + insn[i].imm + 1);
791 if (ret < 0)
792 return ret;
793 }
794
795 if (env->log.level > 1)
796 for (i = 0; i < env->subprog_cnt; i++)
797 verbose(env, "func#%d @%d\n", i, env->subprog_starts[i]);
798
799 /* now check that all jumps are within the same subprog */
800 subprog_start = 0;
801 if (env->subprog_cnt == cur_subprog)
802 subprog_end = insn_cnt;
803 else
804 subprog_end = env->subprog_starts[cur_subprog++];
805 for (i = 0; i < insn_cnt; i++) {
806 u8 code = insn[i].code;
807
808 if (BPF_CLASS(code) != BPF_JMP)
809 goto next;
810 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
811 goto next;
812 off = i + insn[i].off + 1;
813 if (off < subprog_start || off >= subprog_end) {
814 verbose(env, "jump out of range from insn %d to %d\n", i, off);
815 return -EINVAL;
816 }
817 next:
818 if (i == subprog_end - 1) {
819 /* to avoid fall-through from one subprog into another
820 * the last insn of the subprog should be either exit
821 * or unconditional jump back
822 */
823 if (code != (BPF_JMP | BPF_EXIT) &&
824 code != (BPF_JMP | BPF_JA)) {
825 verbose(env, "last insn is not an exit or jmp\n");
826 return -EINVAL;
827 }
828 subprog_start = subprog_end;
829 if (env->subprog_cnt == cur_subprog)
830 subprog_end = insn_cnt;
831 else
832 subprog_end = env->subprog_starts[cur_subprog++];
833 }
834 }
835 return 0;
836 }
837
838 static
839 struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
840 const struct bpf_verifier_state *state,
841 struct bpf_verifier_state *parent,
842 u32 regno)
843 {
844 struct bpf_verifier_state *tmp = NULL;
845
846 /* 'parent' could be a state of caller and
847 * 'state' could be a state of callee. In such case
848 * parent->curframe < state->curframe
849 * and it's ok for r1 - r5 registers
850 *
851 * 'parent' could be a callee's state after it bpf_exit-ed.
852 * In such case parent->curframe > state->curframe
853 * and it's ok for r0 only
854 */
855 if (parent->curframe == state->curframe ||
856 (parent->curframe < state->curframe &&
857 regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
858 (parent->curframe > state->curframe &&
859 regno == BPF_REG_0))
860 return parent;
861
862 if (parent->curframe > state->curframe &&
863 regno >= BPF_REG_6) {
864 /* for callee saved regs we have to skip the whole chain
865 * of states that belong to callee and mark as LIVE_READ
866 * the registers before the call
867 */
868 tmp = parent;
869 while (tmp && tmp->curframe != state->curframe) {
870 tmp = tmp->parent;
871 }
872 if (!tmp)
873 goto bug;
874 parent = tmp;
875 } else {
876 goto bug;
877 }
878 return parent;
879 bug:
880 verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
881 verbose(env, "regno %d parent frame %d current frame %d\n",
882 regno, parent->curframe, state->curframe);
883 return NULL;
884 }
885
886 static int mark_reg_read(struct bpf_verifier_env *env,
887 const struct bpf_verifier_state *state,
888 struct bpf_verifier_state *parent,
889 u32 regno)
890 {
891 bool writes = parent == state->parent; /* Observe write marks */
892
893 if (regno == BPF_REG_FP)
894 /* We don't need to worry about FP liveness because it's read-only */
895 return 0;
896
897 while (parent) {
898 /* if read wasn't screened by an earlier write ... */
899 if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
900 break;
901 parent = skip_callee(env, state, parent, regno);
902 if (!parent)
903 return -EFAULT;
904 /* ... then we depend on parent's value */
905 parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
906 state = parent;
907 parent = state->parent;
908 writes = true;
909 }
910 return 0;
911 }
912
913 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
914 enum reg_arg_type t)
915 {
916 struct bpf_verifier_state *vstate = env->cur_state;
917 struct bpf_func_state *state = vstate->frame[vstate->curframe];
918 struct bpf_reg_state *regs = state->regs;
919
920 if (regno >= MAX_BPF_REG) {
921 verbose(env, "R%d is invalid\n", regno);
922 return -EINVAL;
923 }
924
925 if (t == SRC_OP) {
926 /* check whether register used as source operand can be read */
927 if (regs[regno].type == NOT_INIT) {
928 verbose(env, "R%d !read_ok\n", regno);
929 return -EACCES;
930 }
931 return mark_reg_read(env, vstate, vstate->parent, regno);
932 } else {
933 /* check whether register used as dest operand can be written to */
934 if (regno == BPF_REG_FP) {
935 verbose(env, "frame pointer is read only\n");
936 return -EACCES;
937 }
938 regs[regno].live |= REG_LIVE_WRITTEN;
939 if (t == DST_OP)
940 mark_reg_unknown(env, regs, regno);
941 }
942 return 0;
943 }
944
945 static bool is_spillable_regtype(enum bpf_reg_type type)
946 {
947 switch (type) {
948 case PTR_TO_MAP_VALUE:
949 case PTR_TO_MAP_VALUE_OR_NULL:
950 case PTR_TO_STACK:
951 case PTR_TO_CTX:
952 case PTR_TO_PACKET:
953 case PTR_TO_PACKET_META:
954 case PTR_TO_PACKET_END:
955 case CONST_PTR_TO_MAP:
956 return true;
957 default:
958 return false;
959 }
960 }
961
962 /* Does this register contain a constant zero? */
963 static bool register_is_null(struct bpf_reg_state *reg)
964 {
965 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
966 }
967
968 /* check_stack_read/write functions track spill/fill of registers,
969 * stack boundary and alignment are checked in check_mem_access()
970 */
971 static int check_stack_write(struct bpf_verifier_env *env,
972 struct bpf_func_state *state, /* func where register points to */
973 int off, int size, int value_regno)
974 {
975 struct bpf_func_state *cur; /* state of the current function */
976 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
977 enum bpf_reg_type type;
978
979 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
980 true);
981 if (err)
982 return err;
983 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
984 * so it's aligned access and [off, off + size) are within stack limits
985 */
986 if (!env->allow_ptr_leaks &&
987 state->stack[spi].slot_type[0] == STACK_SPILL &&
988 size != BPF_REG_SIZE) {
989 verbose(env, "attempt to corrupt spilled pointer on stack\n");
990 return -EACCES;
991 }
992
993 cur = env->cur_state->frame[env->cur_state->curframe];
994 if (value_regno >= 0 &&
995 is_spillable_regtype((type = cur->regs[value_regno].type))) {
996
997 /* register containing pointer is being spilled into stack */
998 if (size != BPF_REG_SIZE) {
999 verbose(env, "invalid size of register spill\n");
1000 return -EACCES;
1001 }
1002
1003 if (state != cur && type == PTR_TO_STACK) {
1004 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1005 return -EINVAL;
1006 }
1007
1008 /* save register state */
1009 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1010 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1011
1012 for (i = 0; i < BPF_REG_SIZE; i++)
1013 state->stack[spi].slot_type[i] = STACK_SPILL;
1014 } else {
1015 u8 type = STACK_MISC;
1016
1017 /* regular write of data into stack */
1018 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
1019
1020 /* only mark the slot as written if all 8 bytes were written
1021 * otherwise read propagation may incorrectly stop too soon
1022 * when stack slots are partially written.
1023 * This heuristic means that read propagation will be
1024 * conservative, since it will add reg_live_read marks
1025 * to stack slots all the way to first state when programs
1026 * writes+reads less than 8 bytes
1027 */
1028 if (size == BPF_REG_SIZE)
1029 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1030
1031 /* when we zero initialize stack slots mark them as such */
1032 if (value_regno >= 0 &&
1033 register_is_null(&cur->regs[value_regno]))
1034 type = STACK_ZERO;
1035
1036 for (i = 0; i < size; i++)
1037 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1038 type;
1039 }
1040 return 0;
1041 }
1042
1043 /* registers of every function are unique and mark_reg_read() propagates
1044 * the liveness in the following cases:
1045 * - from callee into caller for R1 - R5 that were used as arguments
1046 * - from caller into callee for R0 that used as result of the call
1047 * - from caller to the same caller skipping states of the callee for R6 - R9,
1048 * since R6 - R9 are callee saved by implicit function prologue and
1049 * caller's R6 != callee's R6, so when we propagate liveness up to
1050 * parent states we need to skip callee states for R6 - R9.
1051 *
1052 * stack slot marking is different, since stacks of caller and callee are
1053 * accessible in both (since caller can pass a pointer to caller's stack to
1054 * callee which can pass it to another function), hence mark_stack_slot_read()
1055 * has to propagate the stack liveness to all parent states at given frame number.
1056 * Consider code:
1057 * f1() {
1058 * ptr = fp - 8;
1059 * *ptr = ctx;
1060 * call f2 {
1061 * .. = *ptr;
1062 * }
1063 * .. = *ptr;
1064 * }
1065 * First *ptr is reading from f1's stack and mark_stack_slot_read() has
1066 * to mark liveness at the f1's frame and not f2's frame.
1067 * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
1068 * to propagate liveness to f2 states at f1's frame level and further into
1069 * f1 states at f1's frame level until write into that stack slot
1070 */
1071 static void mark_stack_slot_read(struct bpf_verifier_env *env,
1072 const struct bpf_verifier_state *state,
1073 struct bpf_verifier_state *parent,
1074 int slot, int frameno)
1075 {
1076 bool writes = parent == state->parent; /* Observe write marks */
1077
1078 while (parent) {
1079 if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
1080 /* since LIVE_WRITTEN mark is only done for full 8-byte
1081 * write the read marks are conservative and parent
1082 * state may not even have the stack allocated. In such case
1083 * end the propagation, since the loop reached beginning
1084 * of the function
1085 */
1086 break;
1087 /* if read wasn't screened by an earlier write ... */
1088 if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
1089 break;
1090 /* ... then we depend on parent's value */
1091 parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
1092 state = parent;
1093 parent = state->parent;
1094 writes = true;
1095 }
1096 }
1097
1098 static int check_stack_read(struct bpf_verifier_env *env,
1099 struct bpf_func_state *reg_state /* func where register points to */,
1100 int off, int size, int value_regno)
1101 {
1102 struct bpf_verifier_state *vstate = env->cur_state;
1103 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1104 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1105 u8 *stype;
1106
1107 if (reg_state->allocated_stack <= slot) {
1108 verbose(env, "invalid read from stack off %d+0 size %d\n",
1109 off, size);
1110 return -EACCES;
1111 }
1112 stype = reg_state->stack[spi].slot_type;
1113
1114 if (stype[0] == STACK_SPILL) {
1115 if (size != BPF_REG_SIZE) {
1116 verbose(env, "invalid size of register spill\n");
1117 return -EACCES;
1118 }
1119 for (i = 1; i < BPF_REG_SIZE; i++) {
1120 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1121 verbose(env, "corrupted spill memory\n");
1122 return -EACCES;
1123 }
1124 }
1125
1126 if (value_regno >= 0) {
1127 /* restore register state from stack */
1128 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1129 /* mark reg as written since spilled pointer state likely
1130 * has its liveness marks cleared by is_state_visited()
1131 * which resets stack/reg liveness for state transitions
1132 */
1133 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1134 }
1135 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1136 reg_state->frameno);
1137 return 0;
1138 } else {
1139 int zeros = 0;
1140
1141 for (i = 0; i < size; i++) {
1142 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1143 continue;
1144 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1145 zeros++;
1146 continue;
1147 }
1148 verbose(env, "invalid read from stack off %d+%d size %d\n",
1149 off, i, size);
1150 return -EACCES;
1151 }
1152 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1153 reg_state->frameno);
1154 if (value_regno >= 0) {
1155 if (zeros == size) {
1156 /* any size read into register is zero extended,
1157 * so the whole register == const_zero
1158 */
1159 __mark_reg_const_zero(&state->regs[value_regno]);
1160 } else {
1161 /* have read misc data from the stack */
1162 mark_reg_unknown(env, state->regs, value_regno);
1163 }
1164 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1165 }
1166 return 0;
1167 }
1168 }
1169
1170 /* check read/write into map element returned by bpf_map_lookup_elem() */
1171 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1172 int size, bool zero_size_allowed)
1173 {
1174 struct bpf_reg_state *regs = cur_regs(env);
1175 struct bpf_map *map = regs[regno].map_ptr;
1176
1177 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1178 off + size > map->value_size) {
1179 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1180 map->value_size, off, size);
1181 return -EACCES;
1182 }
1183 return 0;
1184 }
1185
1186 /* check read/write into a map element with possible variable offset */
1187 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1188 int off, int size, bool zero_size_allowed)
1189 {
1190 struct bpf_verifier_state *vstate = env->cur_state;
1191 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1192 struct bpf_reg_state *reg = &state->regs[regno];
1193 int err;
1194
1195 /* We may have adjusted the register to this map value, so we
1196 * need to try adding each of min_value and max_value to off
1197 * to make sure our theoretical access will be safe.
1198 */
1199 if (env->log.level)
1200 print_verifier_state(env, state);
1201 /* The minimum value is only important with signed
1202 * comparisons where we can't assume the floor of a
1203 * value is 0. If we are using signed variables for our
1204 * index'es we need to make sure that whatever we use
1205 * will have a set floor within our range.
1206 */
1207 if (reg->smin_value < 0) {
1208 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1209 regno);
1210 return -EACCES;
1211 }
1212 err = __check_map_access(env, regno, reg->smin_value + off, size,
1213 zero_size_allowed);
1214 if (err) {
1215 verbose(env, "R%d min value is outside of the array range\n",
1216 regno);
1217 return err;
1218 }
1219
1220 /* If we haven't set a max value then we need to bail since we can't be
1221 * sure we won't do bad things.
1222 * If reg->umax_value + off could overflow, treat that as unbounded too.
1223 */
1224 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1225 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1226 regno);
1227 return -EACCES;
1228 }
1229 err = __check_map_access(env, regno, reg->umax_value + off, size,
1230 zero_size_allowed);
1231 if (err)
1232 verbose(env, "R%d max value is outside of the array range\n",
1233 regno);
1234 return err;
1235 }
1236
1237 #define MAX_PACKET_OFF 0xffff
1238
1239 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1240 const struct bpf_call_arg_meta *meta,
1241 enum bpf_access_type t)
1242 {
1243 switch (env->prog->type) {
1244 case BPF_PROG_TYPE_LWT_IN:
1245 case BPF_PROG_TYPE_LWT_OUT:
1246 /* dst_input() and dst_output() can't write for now */
1247 if (t == BPF_WRITE)
1248 return false;
1249 /* fallthrough */
1250 case BPF_PROG_TYPE_SCHED_CLS:
1251 case BPF_PROG_TYPE_SCHED_ACT:
1252 case BPF_PROG_TYPE_XDP:
1253 case BPF_PROG_TYPE_LWT_XMIT:
1254 case BPF_PROG_TYPE_SK_SKB:
1255 if (meta)
1256 return meta->pkt_access;
1257
1258 env->seen_direct_write = true;
1259 return true;
1260 default:
1261 return false;
1262 }
1263 }
1264
1265 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1266 int off, int size, bool zero_size_allowed)
1267 {
1268 struct bpf_reg_state *regs = cur_regs(env);
1269 struct bpf_reg_state *reg = &regs[regno];
1270
1271 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1272 (u64)off + size > reg->range) {
1273 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1274 off, size, regno, reg->id, reg->off, reg->range);
1275 return -EACCES;
1276 }
1277 return 0;
1278 }
1279
1280 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1281 int size, bool zero_size_allowed)
1282 {
1283 struct bpf_reg_state *regs = cur_regs(env);
1284 struct bpf_reg_state *reg = &regs[regno];
1285 int err;
1286
1287 /* We may have added a variable offset to the packet pointer; but any
1288 * reg->range we have comes after that. We are only checking the fixed
1289 * offset.
1290 */
1291
1292 /* We don't allow negative numbers, because we aren't tracking enough
1293 * detail to prove they're safe.
1294 */
1295 if (reg->smin_value < 0) {
1296 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1297 regno);
1298 return -EACCES;
1299 }
1300 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1301 if (err) {
1302 verbose(env, "R%d offset is outside of the packet\n", regno);
1303 return err;
1304 }
1305 return err;
1306 }
1307
1308 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
1309 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1310 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1311 {
1312 struct bpf_insn_access_aux info = {
1313 .reg_type = *reg_type,
1314 };
1315
1316 if (env->ops->is_valid_access &&
1317 env->ops->is_valid_access(off, size, t, &info)) {
1318 /* A non zero info.ctx_field_size indicates that this field is a
1319 * candidate for later verifier transformation to load the whole
1320 * field and then apply a mask when accessed with a narrower
1321 * access than actual ctx access size. A zero info.ctx_field_size
1322 * will only allow for whole field access and rejects any other
1323 * type of narrower access.
1324 */
1325 *reg_type = info.reg_type;
1326
1327 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1328 /* remember the offset of last byte accessed in ctx */
1329 if (env->prog->aux->max_ctx_offset < off + size)
1330 env->prog->aux->max_ctx_offset = off + size;
1331 return 0;
1332 }
1333
1334 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1335 return -EACCES;
1336 }
1337
1338 static bool __is_pointer_value(bool allow_ptr_leaks,
1339 const struct bpf_reg_state *reg)
1340 {
1341 if (allow_ptr_leaks)
1342 return false;
1343
1344 return reg->type != SCALAR_VALUE;
1345 }
1346
1347 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1348 {
1349 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1350 }
1351
1352 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1353 {
1354 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1355
1356 return reg->type == PTR_TO_CTX;
1357 }
1358
1359 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1360 const struct bpf_reg_state *reg,
1361 int off, int size, bool strict)
1362 {
1363 struct tnum reg_off;
1364 int ip_align;
1365
1366 /* Byte size accesses are always allowed. */
1367 if (!strict || size == 1)
1368 return 0;
1369
1370 /* For platforms that do not have a Kconfig enabling
1371 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1372 * NET_IP_ALIGN is universally set to '2'. And on platforms
1373 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1374 * to this code only in strict mode where we want to emulate
1375 * the NET_IP_ALIGN==2 checking. Therefore use an
1376 * unconditional IP align value of '2'.
1377 */
1378 ip_align = 2;
1379
1380 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1381 if (!tnum_is_aligned(reg_off, size)) {
1382 char tn_buf[48];
1383
1384 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1385 verbose(env,
1386 "misaligned packet access off %d+%s+%d+%d size %d\n",
1387 ip_align, tn_buf, reg->off, off, size);
1388 return -EACCES;
1389 }
1390
1391 return 0;
1392 }
1393
1394 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1395 const struct bpf_reg_state *reg,
1396 const char *pointer_desc,
1397 int off, int size, bool strict)
1398 {
1399 struct tnum reg_off;
1400
1401 /* Byte size accesses are always allowed. */
1402 if (!strict || size == 1)
1403 return 0;
1404
1405 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1406 if (!tnum_is_aligned(reg_off, size)) {
1407 char tn_buf[48];
1408
1409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1410 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1411 pointer_desc, tn_buf, reg->off, off, size);
1412 return -EACCES;
1413 }
1414
1415 return 0;
1416 }
1417
1418 static int check_ptr_alignment(struct bpf_verifier_env *env,
1419 const struct bpf_reg_state *reg,
1420 int off, int size)
1421 {
1422 bool strict = env->strict_alignment;
1423 const char *pointer_desc = "";
1424
1425 switch (reg->type) {
1426 case PTR_TO_PACKET:
1427 case PTR_TO_PACKET_META:
1428 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1429 * right in front, treat it the very same way.
1430 */
1431 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1432 case PTR_TO_MAP_VALUE:
1433 pointer_desc = "value ";
1434 break;
1435 case PTR_TO_CTX:
1436 pointer_desc = "context ";
1437 break;
1438 case PTR_TO_STACK:
1439 pointer_desc = "stack ";
1440 /* The stack spill tracking logic in check_stack_write()
1441 * and check_stack_read() relies on stack accesses being
1442 * aligned.
1443 */
1444 strict = true;
1445 break;
1446 default:
1447 break;
1448 }
1449 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1450 strict);
1451 }
1452
1453 static int update_stack_depth(struct bpf_verifier_env *env,
1454 const struct bpf_func_state *func,
1455 int off)
1456 {
1457 u16 stack = env->subprog_stack_depth[func->subprogno];
1458
1459 if (stack >= -off)
1460 return 0;
1461
1462 /* update known max for given subprogram */
1463 env->subprog_stack_depth[func->subprogno] = -off;
1464 return 0;
1465 }
1466
1467 /* starting from main bpf function walk all instructions of the function
1468 * and recursively walk all callees that given function can call.
1469 * Ignore jump and exit insns.
1470 * Since recursion is prevented by check_cfg() this algorithm
1471 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1472 */
1473 static int check_max_stack_depth(struct bpf_verifier_env *env)
1474 {
1475 int depth = 0, frame = 0, subprog = 0, i = 0, subprog_end;
1476 struct bpf_insn *insn = env->prog->insnsi;
1477 int insn_cnt = env->prog->len;
1478 int ret_insn[MAX_CALL_FRAMES];
1479 int ret_prog[MAX_CALL_FRAMES];
1480
1481 process_func:
1482 /* round up to 32-bytes, since this is granularity
1483 * of interpreter stack size
1484 */
1485 depth += round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1486 if (depth > MAX_BPF_STACK) {
1487 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1488 frame + 1, depth);
1489 return -EACCES;
1490 }
1491 continue_func:
1492 if (env->subprog_cnt == subprog)
1493 subprog_end = insn_cnt;
1494 else
1495 subprog_end = env->subprog_starts[subprog];
1496 for (; i < subprog_end; i++) {
1497 if (insn[i].code != (BPF_JMP | BPF_CALL))
1498 continue;
1499 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1500 continue;
1501 /* remember insn and function to return to */
1502 ret_insn[frame] = i + 1;
1503 ret_prog[frame] = subprog;
1504
1505 /* find the callee */
1506 i = i + insn[i].imm + 1;
1507 subprog = find_subprog(env, i);
1508 if (subprog < 0) {
1509 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1510 i);
1511 return -EFAULT;
1512 }
1513 subprog++;
1514 frame++;
1515 if (frame >= MAX_CALL_FRAMES) {
1516 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1517 return -EFAULT;
1518 }
1519 goto process_func;
1520 }
1521 /* end of for() loop means the last insn of the 'subprog'
1522 * was reached. Doesn't matter whether it was JA or EXIT
1523 */
1524 if (frame == 0)
1525 return 0;
1526 depth -= round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1527 frame--;
1528 i = ret_insn[frame];
1529 subprog = ret_prog[frame];
1530 goto continue_func;
1531 }
1532
1533 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1534 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1535 const struct bpf_insn *insn, int idx)
1536 {
1537 int start = idx + insn->imm + 1, subprog;
1538
1539 subprog = find_subprog(env, start);
1540 if (subprog < 0) {
1541 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1542 start);
1543 return -EFAULT;
1544 }
1545 subprog++;
1546 return env->subprog_stack_depth[subprog];
1547 }
1548 #endif
1549
1550 /* truncate register to smaller size (in bytes)
1551 * must be called with size < BPF_REG_SIZE
1552 */
1553 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1554 {
1555 u64 mask;
1556
1557 /* clear high bits in bit representation */
1558 reg->var_off = tnum_cast(reg->var_off, size);
1559
1560 /* fix arithmetic bounds */
1561 mask = ((u64)1 << (size * 8)) - 1;
1562 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1563 reg->umin_value &= mask;
1564 reg->umax_value &= mask;
1565 } else {
1566 reg->umin_value = 0;
1567 reg->umax_value = mask;
1568 }
1569 reg->smin_value = reg->umin_value;
1570 reg->smax_value = reg->umax_value;
1571 }
1572
1573 /* check whether memory at (regno + off) is accessible for t = (read | write)
1574 * if t==write, value_regno is a register which value is stored into memory
1575 * if t==read, value_regno is a register which will receive the value from memory
1576 * if t==write && value_regno==-1, some unknown value is stored into memory
1577 * if t==read && value_regno==-1, don't care what we read from memory
1578 */
1579 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
1580 int bpf_size, enum bpf_access_type t,
1581 int value_regno)
1582 {
1583 struct bpf_reg_state *regs = cur_regs(env);
1584 struct bpf_reg_state *reg = regs + regno;
1585 struct bpf_func_state *state;
1586 int size, err = 0;
1587
1588 size = bpf_size_to_bytes(bpf_size);
1589 if (size < 0)
1590 return size;
1591
1592 /* alignment checks will add in reg->off themselves */
1593 err = check_ptr_alignment(env, reg, off, size);
1594 if (err)
1595 return err;
1596
1597 /* for access checks, reg->off is just part of off */
1598 off += reg->off;
1599
1600 if (reg->type == PTR_TO_MAP_VALUE) {
1601 if (t == BPF_WRITE && value_regno >= 0 &&
1602 is_pointer_value(env, value_regno)) {
1603 verbose(env, "R%d leaks addr into map\n", value_regno);
1604 return -EACCES;
1605 }
1606
1607 err = check_map_access(env, regno, off, size, false);
1608 if (!err && t == BPF_READ && value_regno >= 0)
1609 mark_reg_unknown(env, regs, value_regno);
1610
1611 } else if (reg->type == PTR_TO_CTX) {
1612 enum bpf_reg_type reg_type = SCALAR_VALUE;
1613
1614 if (t == BPF_WRITE && value_regno >= 0 &&
1615 is_pointer_value(env, value_regno)) {
1616 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1617 return -EACCES;
1618 }
1619 /* ctx accesses must be at a fixed offset, so that we can
1620 * determine what type of data were returned.
1621 */
1622 if (reg->off) {
1623 verbose(env,
1624 "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
1625 regno, reg->off, off - reg->off);
1626 return -EACCES;
1627 }
1628 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1629 char tn_buf[48];
1630
1631 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1632 verbose(env,
1633 "variable ctx access var_off=%s off=%d size=%d",
1634 tn_buf, off, size);
1635 return -EACCES;
1636 }
1637 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1638 if (!err && t == BPF_READ && value_regno >= 0) {
1639 /* ctx access returns either a scalar, or a
1640 * PTR_TO_PACKET[_META,_END]. In the latter
1641 * case, we know the offset is zero.
1642 */
1643 if (reg_type == SCALAR_VALUE)
1644 mark_reg_unknown(env, regs, value_regno);
1645 else
1646 mark_reg_known_zero(env, regs,
1647 value_regno);
1648 regs[value_regno].id = 0;
1649 regs[value_regno].off = 0;
1650 regs[value_regno].range = 0;
1651 regs[value_regno].type = reg_type;
1652 }
1653
1654 } else if (reg->type == PTR_TO_STACK) {
1655 /* stack accesses must be at a fixed offset, so that we can
1656 * determine what type of data were returned.
1657 * See check_stack_read().
1658 */
1659 if (!tnum_is_const(reg->var_off)) {
1660 char tn_buf[48];
1661
1662 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1663 verbose(env, "variable stack access var_off=%s off=%d size=%d",
1664 tn_buf, off, size);
1665 return -EACCES;
1666 }
1667 off += reg->var_off.value;
1668 if (off >= 0 || off < -MAX_BPF_STACK) {
1669 verbose(env, "invalid stack off=%d size=%d\n", off,
1670 size);
1671 return -EACCES;
1672 }
1673
1674 state = func(env, reg);
1675 err = update_stack_depth(env, state, off);
1676 if (err)
1677 return err;
1678
1679 if (t == BPF_WRITE)
1680 err = check_stack_write(env, state, off, size,
1681 value_regno);
1682 else
1683 err = check_stack_read(env, state, off, size,
1684 value_regno);
1685 } else if (reg_is_pkt_pointer(reg)) {
1686 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1687 verbose(env, "cannot write into packet\n");
1688 return -EACCES;
1689 }
1690 if (t == BPF_WRITE && value_regno >= 0 &&
1691 is_pointer_value(env, value_regno)) {
1692 verbose(env, "R%d leaks addr into packet\n",
1693 value_regno);
1694 return -EACCES;
1695 }
1696 err = check_packet_access(env, regno, off, size, false);
1697 if (!err && t == BPF_READ && value_regno >= 0)
1698 mark_reg_unknown(env, regs, value_regno);
1699 } else {
1700 verbose(env, "R%d invalid mem access '%s'\n", regno,
1701 reg_type_str[reg->type]);
1702 return -EACCES;
1703 }
1704
1705 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1706 regs[value_regno].type == SCALAR_VALUE) {
1707 /* b/h/w load zero-extends, mark upper bits as known 0 */
1708 coerce_reg_to_size(&regs[value_regno], size);
1709 }
1710 return err;
1711 }
1712
1713 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1714 {
1715 int err;
1716
1717 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1718 insn->imm != 0) {
1719 verbose(env, "BPF_XADD uses reserved fields\n");
1720 return -EINVAL;
1721 }
1722
1723 /* check src1 operand */
1724 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1725 if (err)
1726 return err;
1727
1728 /* check src2 operand */
1729 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1730 if (err)
1731 return err;
1732
1733 if (is_pointer_value(env, insn->src_reg)) {
1734 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1735 return -EACCES;
1736 }
1737
1738 if (is_ctx_reg(env, insn->dst_reg)) {
1739 verbose(env, "BPF_XADD stores into R%d context is not allowed\n",
1740 insn->dst_reg);
1741 return -EACCES;
1742 }
1743
1744 /* check whether atomic_add can read the memory */
1745 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1746 BPF_SIZE(insn->code), BPF_READ, -1);
1747 if (err)
1748 return err;
1749
1750 /* check whether atomic_add can write into the same memory */
1751 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1752 BPF_SIZE(insn->code), BPF_WRITE, -1);
1753 }
1754
1755 /* when register 'regno' is passed into function that will read 'access_size'
1756 * bytes from that pointer, make sure that it's within stack boundary
1757 * and all elements of stack are initialized.
1758 * Unlike most pointer bounds-checking functions, this one doesn't take an
1759 * 'off' argument, so it has to add in reg->off itself.
1760 */
1761 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1762 int access_size, bool zero_size_allowed,
1763 struct bpf_call_arg_meta *meta)
1764 {
1765 struct bpf_reg_state *reg = cur_regs(env) + regno;
1766 struct bpf_func_state *state = func(env, reg);
1767 int off, i, slot, spi;
1768
1769 if (reg->type != PTR_TO_STACK) {
1770 /* Allow zero-byte read from NULL, regardless of pointer type */
1771 if (zero_size_allowed && access_size == 0 &&
1772 register_is_null(reg))
1773 return 0;
1774
1775 verbose(env, "R%d type=%s expected=%s\n", regno,
1776 reg_type_str[reg->type],
1777 reg_type_str[PTR_TO_STACK]);
1778 return -EACCES;
1779 }
1780
1781 /* Only allow fixed-offset stack reads */
1782 if (!tnum_is_const(reg->var_off)) {
1783 char tn_buf[48];
1784
1785 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1786 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1787 regno, tn_buf);
1788 return -EACCES;
1789 }
1790 off = reg->off + reg->var_off.value;
1791 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1792 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1793 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1794 regno, off, access_size);
1795 return -EACCES;
1796 }
1797
1798 if (meta && meta->raw_mode) {
1799 meta->access_size = access_size;
1800 meta->regno = regno;
1801 return 0;
1802 }
1803
1804 for (i = 0; i < access_size; i++) {
1805 u8 *stype;
1806
1807 slot = -(off + i) - 1;
1808 spi = slot / BPF_REG_SIZE;
1809 if (state->allocated_stack <= slot)
1810 goto err;
1811 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1812 if (*stype == STACK_MISC)
1813 goto mark;
1814 if (*stype == STACK_ZERO) {
1815 /* helper can write anything into the stack */
1816 *stype = STACK_MISC;
1817 goto mark;
1818 }
1819 err:
1820 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1821 off, i, access_size);
1822 return -EACCES;
1823 mark:
1824 /* reading any byte out of 8-byte 'spill_slot' will cause
1825 * the whole slot to be marked as 'read'
1826 */
1827 mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
1828 spi, state->frameno);
1829 }
1830 return update_stack_depth(env, state, off);
1831 }
1832
1833 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1834 int access_size, bool zero_size_allowed,
1835 struct bpf_call_arg_meta *meta)
1836 {
1837 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1838
1839 switch (reg->type) {
1840 case PTR_TO_PACKET:
1841 case PTR_TO_PACKET_META:
1842 return check_packet_access(env, regno, reg->off, access_size,
1843 zero_size_allowed);
1844 case PTR_TO_MAP_VALUE:
1845 return check_map_access(env, regno, reg->off, access_size,
1846 zero_size_allowed);
1847 default: /* scalar_value|ptr_to_stack or invalid ptr */
1848 return check_stack_boundary(env, regno, access_size,
1849 zero_size_allowed, meta);
1850 }
1851 }
1852
1853 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1854 enum bpf_arg_type arg_type,
1855 struct bpf_call_arg_meta *meta)
1856 {
1857 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1858 enum bpf_reg_type expected_type, type = reg->type;
1859 int err = 0;
1860
1861 if (arg_type == ARG_DONTCARE)
1862 return 0;
1863
1864 err = check_reg_arg(env, regno, SRC_OP);
1865 if (err)
1866 return err;
1867
1868 if (arg_type == ARG_ANYTHING) {
1869 if (is_pointer_value(env, regno)) {
1870 verbose(env, "R%d leaks addr into helper function\n",
1871 regno);
1872 return -EACCES;
1873 }
1874 return 0;
1875 }
1876
1877 if (type_is_pkt_pointer(type) &&
1878 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1879 verbose(env, "helper access to the packet is not allowed\n");
1880 return -EACCES;
1881 }
1882
1883 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1884 arg_type == ARG_PTR_TO_MAP_VALUE) {
1885 expected_type = PTR_TO_STACK;
1886 if (!type_is_pkt_pointer(type) &&
1887 type != expected_type)
1888 goto err_type;
1889 } else if (arg_type == ARG_CONST_SIZE ||
1890 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1891 expected_type = SCALAR_VALUE;
1892 if (type != expected_type)
1893 goto err_type;
1894 } else if (arg_type == ARG_CONST_MAP_PTR) {
1895 expected_type = CONST_PTR_TO_MAP;
1896 if (type != expected_type)
1897 goto err_type;
1898 } else if (arg_type == ARG_PTR_TO_CTX) {
1899 expected_type = PTR_TO_CTX;
1900 if (type != expected_type)
1901 goto err_type;
1902 } else if (arg_type == ARG_PTR_TO_MEM ||
1903 arg_type == ARG_PTR_TO_MEM_OR_NULL ||
1904 arg_type == ARG_PTR_TO_UNINIT_MEM) {
1905 expected_type = PTR_TO_STACK;
1906 /* One exception here. In case function allows for NULL to be
1907 * passed in as argument, it's a SCALAR_VALUE type. Final test
1908 * happens during stack boundary checking.
1909 */
1910 if (register_is_null(reg) &&
1911 arg_type == ARG_PTR_TO_MEM_OR_NULL)
1912 /* final test in check_stack_boundary() */;
1913 else if (!type_is_pkt_pointer(type) &&
1914 type != PTR_TO_MAP_VALUE &&
1915 type != expected_type)
1916 goto err_type;
1917 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1918 } else {
1919 verbose(env, "unsupported arg_type %d\n", arg_type);
1920 return -EFAULT;
1921 }
1922
1923 if (arg_type == ARG_CONST_MAP_PTR) {
1924 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1925 meta->map_ptr = reg->map_ptr;
1926 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1927 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1928 * check that [key, key + map->key_size) are within
1929 * stack limits and initialized
1930 */
1931 if (!meta->map_ptr) {
1932 /* in function declaration map_ptr must come before
1933 * map_key, so that it's verified and known before
1934 * we have to check map_key here. Otherwise it means
1935 * that kernel subsystem misconfigured verifier
1936 */
1937 verbose(env, "invalid map_ptr to access map->key\n");
1938 return -EACCES;
1939 }
1940 if (type_is_pkt_pointer(type))
1941 err = check_packet_access(env, regno, reg->off,
1942 meta->map_ptr->key_size,
1943 false);
1944 else
1945 err = check_stack_boundary(env, regno,
1946 meta->map_ptr->key_size,
1947 false, NULL);
1948 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1949 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1950 * check [value, value + map->value_size) validity
1951 */
1952 if (!meta->map_ptr) {
1953 /* kernel subsystem misconfigured verifier */
1954 verbose(env, "invalid map_ptr to access map->value\n");
1955 return -EACCES;
1956 }
1957 if (type_is_pkt_pointer(type))
1958 err = check_packet_access(env, regno, reg->off,
1959 meta->map_ptr->value_size,
1960 false);
1961 else
1962 err = check_stack_boundary(env, regno,
1963 meta->map_ptr->value_size,
1964 false, NULL);
1965 } else if (arg_type == ARG_CONST_SIZE ||
1966 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1967 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1968
1969 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1970 * from stack pointer 'buf'. Check it
1971 * note: regno == len, regno - 1 == buf
1972 */
1973 if (regno == 0) {
1974 /* kernel subsystem misconfigured verifier */
1975 verbose(env,
1976 "ARG_CONST_SIZE cannot be first argument\n");
1977 return -EACCES;
1978 }
1979
1980 /* The register is SCALAR_VALUE; the access check
1981 * happens using its boundaries.
1982 */
1983
1984 if (!tnum_is_const(reg->var_off))
1985 /* For unprivileged variable accesses, disable raw
1986 * mode so that the program is required to
1987 * initialize all the memory that the helper could
1988 * just partially fill up.
1989 */
1990 meta = NULL;
1991
1992 if (reg->smin_value < 0) {
1993 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
1994 regno);
1995 return -EACCES;
1996 }
1997
1998 if (reg->umin_value == 0) {
1999 err = check_helper_mem_access(env, regno - 1, 0,
2000 zero_size_allowed,
2001 meta);
2002 if (err)
2003 return err;
2004 }
2005
2006 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2007 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2008 regno);
2009 return -EACCES;
2010 }
2011 err = check_helper_mem_access(env, regno - 1,
2012 reg->umax_value,
2013 zero_size_allowed, meta);
2014 }
2015
2016 return err;
2017 err_type:
2018 verbose(env, "R%d type=%s expected=%s\n", regno,
2019 reg_type_str[type], reg_type_str[expected_type]);
2020 return -EACCES;
2021 }
2022
2023 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2024 struct bpf_map *map, int func_id)
2025 {
2026 if (!map)
2027 return 0;
2028
2029 /* We need a two way check, first is from map perspective ... */
2030 switch (map->map_type) {
2031 case BPF_MAP_TYPE_PROG_ARRAY:
2032 if (func_id != BPF_FUNC_tail_call)
2033 goto error;
2034 break;
2035 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2036 if (func_id != BPF_FUNC_perf_event_read &&
2037 func_id != BPF_FUNC_perf_event_output &&
2038 func_id != BPF_FUNC_perf_event_read_value)
2039 goto error;
2040 break;
2041 case BPF_MAP_TYPE_STACK_TRACE:
2042 if (func_id != BPF_FUNC_get_stackid)
2043 goto error;
2044 break;
2045 case BPF_MAP_TYPE_CGROUP_ARRAY:
2046 if (func_id != BPF_FUNC_skb_under_cgroup &&
2047 func_id != BPF_FUNC_current_task_under_cgroup)
2048 goto error;
2049 break;
2050 /* devmap returns a pointer to a live net_device ifindex that we cannot
2051 * allow to be modified from bpf side. So do not allow lookup elements
2052 * for now.
2053 */
2054 case BPF_MAP_TYPE_DEVMAP:
2055 if (func_id != BPF_FUNC_redirect_map)
2056 goto error;
2057 break;
2058 /* Restrict bpf side of cpumap, open when use-cases appear */
2059 case BPF_MAP_TYPE_CPUMAP:
2060 if (func_id != BPF_FUNC_redirect_map)
2061 goto error;
2062 break;
2063 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2064 case BPF_MAP_TYPE_HASH_OF_MAPS:
2065 if (func_id != BPF_FUNC_map_lookup_elem)
2066 goto error;
2067 break;
2068 case BPF_MAP_TYPE_SOCKMAP:
2069 if (func_id != BPF_FUNC_sk_redirect_map &&
2070 func_id != BPF_FUNC_sock_map_update &&
2071 func_id != BPF_FUNC_map_delete_elem)
2072 goto error;
2073 break;
2074 default:
2075 break;
2076 }
2077
2078 /* ... and second from the function itself. */
2079 switch (func_id) {
2080 case BPF_FUNC_tail_call:
2081 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2082 goto error;
2083 if (env->subprog_cnt) {
2084 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2085 return -EINVAL;
2086 }
2087 break;
2088 case BPF_FUNC_perf_event_read:
2089 case BPF_FUNC_perf_event_output:
2090 case BPF_FUNC_perf_event_read_value:
2091 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2092 goto error;
2093 break;
2094 case BPF_FUNC_get_stackid:
2095 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2096 goto error;
2097 break;
2098 case BPF_FUNC_current_task_under_cgroup:
2099 case BPF_FUNC_skb_under_cgroup:
2100 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2101 goto error;
2102 break;
2103 case BPF_FUNC_redirect_map:
2104 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2105 map->map_type != BPF_MAP_TYPE_CPUMAP)
2106 goto error;
2107 break;
2108 case BPF_FUNC_sk_redirect_map:
2109 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2110 goto error;
2111 break;
2112 case BPF_FUNC_sock_map_update:
2113 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2114 goto error;
2115 break;
2116 default:
2117 break;
2118 }
2119
2120 return 0;
2121 error:
2122 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2123 map->map_type, func_id_name(func_id), func_id);
2124 return -EINVAL;
2125 }
2126
2127 static int check_raw_mode(const struct bpf_func_proto *fn)
2128 {
2129 int count = 0;
2130
2131 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2132 count++;
2133 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2134 count++;
2135 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2136 count++;
2137 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2138 count++;
2139 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2140 count++;
2141
2142 return count > 1 ? -EINVAL : 0;
2143 }
2144
2145 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2146 * are now invalid, so turn them into unknown SCALAR_VALUE.
2147 */
2148 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2149 struct bpf_func_state *state)
2150 {
2151 struct bpf_reg_state *regs = state->regs, *reg;
2152 int i;
2153
2154 for (i = 0; i < MAX_BPF_REG; i++)
2155 if (reg_is_pkt_pointer_any(&regs[i]))
2156 mark_reg_unknown(env, regs, i);
2157
2158 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2159 if (state->stack[i].slot_type[0] != STACK_SPILL)
2160 continue;
2161 reg = &state->stack[i].spilled_ptr;
2162 if (reg_is_pkt_pointer_any(reg))
2163 __mark_reg_unknown(reg);
2164 }
2165 }
2166
2167 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2168 {
2169 struct bpf_verifier_state *vstate = env->cur_state;
2170 int i;
2171
2172 for (i = 0; i <= vstate->curframe; i++)
2173 __clear_all_pkt_pointers(env, vstate->frame[i]);
2174 }
2175
2176 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2177 int *insn_idx)
2178 {
2179 struct bpf_verifier_state *state = env->cur_state;
2180 struct bpf_func_state *caller, *callee;
2181 int i, subprog, target_insn;
2182
2183 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2184 verbose(env, "the call stack of %d frames is too deep\n",
2185 state->curframe + 2);
2186 return -E2BIG;
2187 }
2188
2189 target_insn = *insn_idx + insn->imm;
2190 subprog = find_subprog(env, target_insn + 1);
2191 if (subprog < 0) {
2192 verbose(env, "verifier bug. No program starts at insn %d\n",
2193 target_insn + 1);
2194 return -EFAULT;
2195 }
2196
2197 caller = state->frame[state->curframe];
2198 if (state->frame[state->curframe + 1]) {
2199 verbose(env, "verifier bug. Frame %d already allocated\n",
2200 state->curframe + 1);
2201 return -EFAULT;
2202 }
2203
2204 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2205 if (!callee)
2206 return -ENOMEM;
2207 state->frame[state->curframe + 1] = callee;
2208
2209 /* callee cannot access r0, r6 - r9 for reading and has to write
2210 * into its own stack before reading from it.
2211 * callee can read/write into caller's stack
2212 */
2213 init_func_state(env, callee,
2214 /* remember the callsite, it will be used by bpf_exit */
2215 *insn_idx /* callsite */,
2216 state->curframe + 1 /* frameno within this callchain */,
2217 subprog + 1 /* subprog number within this prog */);
2218
2219 /* copy r1 - r5 args that callee can access */
2220 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2221 callee->regs[i] = caller->regs[i];
2222
2223 /* after the call regsiters r0 - r5 were scratched */
2224 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2225 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2226 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2227 }
2228
2229 /* only increment it after check_reg_arg() finished */
2230 state->curframe++;
2231
2232 /* and go analyze first insn of the callee */
2233 *insn_idx = target_insn;
2234
2235 if (env->log.level) {
2236 verbose(env, "caller:\n");
2237 print_verifier_state(env, caller);
2238 verbose(env, "callee:\n");
2239 print_verifier_state(env, callee);
2240 }
2241 return 0;
2242 }
2243
2244 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2245 {
2246 struct bpf_verifier_state *state = env->cur_state;
2247 struct bpf_func_state *caller, *callee;
2248 struct bpf_reg_state *r0;
2249
2250 callee = state->frame[state->curframe];
2251 r0 = &callee->regs[BPF_REG_0];
2252 if (r0->type == PTR_TO_STACK) {
2253 /* technically it's ok to return caller's stack pointer
2254 * (or caller's caller's pointer) back to the caller,
2255 * since these pointers are valid. Only current stack
2256 * pointer will be invalid as soon as function exits,
2257 * but let's be conservative
2258 */
2259 verbose(env, "cannot return stack pointer to the caller\n");
2260 return -EINVAL;
2261 }
2262
2263 state->curframe--;
2264 caller = state->frame[state->curframe];
2265 /* return to the caller whatever r0 had in the callee */
2266 caller->regs[BPF_REG_0] = *r0;
2267
2268 *insn_idx = callee->callsite + 1;
2269 if (env->log.level) {
2270 verbose(env, "returning from callee:\n");
2271 print_verifier_state(env, callee);
2272 verbose(env, "to caller at %d:\n", *insn_idx);
2273 print_verifier_state(env, caller);
2274 }
2275 /* clear everything in the callee */
2276 free_func_state(callee);
2277 state->frame[state->curframe + 1] = NULL;
2278 return 0;
2279 }
2280
2281 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2282 {
2283 const struct bpf_func_proto *fn = NULL;
2284 struct bpf_reg_state *regs;
2285 struct bpf_call_arg_meta meta;
2286 bool changes_data;
2287 int i, err;
2288
2289 /* find function prototype */
2290 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2291 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2292 func_id);
2293 return -EINVAL;
2294 }
2295
2296 if (env->ops->get_func_proto)
2297 fn = env->ops->get_func_proto(func_id);
2298
2299 if (!fn) {
2300 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2301 func_id);
2302 return -EINVAL;
2303 }
2304
2305 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2306 if (!env->prog->gpl_compatible && fn->gpl_only) {
2307 verbose(env, "cannot call GPL only function from proprietary program\n");
2308 return -EINVAL;
2309 }
2310
2311 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2312 changes_data = bpf_helper_changes_pkt_data(fn->func);
2313 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2314 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2315 func_id_name(func_id), func_id);
2316 return -EINVAL;
2317 }
2318
2319 memset(&meta, 0, sizeof(meta));
2320 meta.pkt_access = fn->pkt_access;
2321
2322 /* We only support one arg being in raw mode at the moment, which
2323 * is sufficient for the helper functions we have right now.
2324 */
2325 err = check_raw_mode(fn);
2326 if (err) {
2327 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2328 func_id_name(func_id), func_id);
2329 return err;
2330 }
2331
2332 /* check args */
2333 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2334 if (err)
2335 return err;
2336 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2337 if (err)
2338 return err;
2339 if (func_id == BPF_FUNC_tail_call) {
2340 if (meta.map_ptr == NULL) {
2341 verbose(env, "verifier bug\n");
2342 return -EINVAL;
2343 }
2344 env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
2345 }
2346 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2347 if (err)
2348 return err;
2349 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2350 if (err)
2351 return err;
2352 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2353 if (err)
2354 return err;
2355
2356 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2357 * is inferred from register state.
2358 */
2359 for (i = 0; i < meta.access_size; i++) {
2360 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
2361 if (err)
2362 return err;
2363 }
2364
2365 regs = cur_regs(env);
2366 /* reset caller saved regs */
2367 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2368 mark_reg_not_init(env, regs, caller_saved[i]);
2369 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2370 }
2371
2372 /* update return register (already marked as written above) */
2373 if (fn->ret_type == RET_INTEGER) {
2374 /* sets type to SCALAR_VALUE */
2375 mark_reg_unknown(env, regs, BPF_REG_0);
2376 } else if (fn->ret_type == RET_VOID) {
2377 regs[BPF_REG_0].type = NOT_INIT;
2378 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
2379 struct bpf_insn_aux_data *insn_aux;
2380
2381 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2382 /* There is no offset yet applied, variable or fixed */
2383 mark_reg_known_zero(env, regs, BPF_REG_0);
2384 regs[BPF_REG_0].off = 0;
2385 /* remember map_ptr, so that check_map_access()
2386 * can check 'value_size' boundary of memory access
2387 * to map element returned from bpf_map_lookup_elem()
2388 */
2389 if (meta.map_ptr == NULL) {
2390 verbose(env,
2391 "kernel subsystem misconfigured verifier\n");
2392 return -EINVAL;
2393 }
2394 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2395 regs[BPF_REG_0].id = ++env->id_gen;
2396 insn_aux = &env->insn_aux_data[insn_idx];
2397 if (!insn_aux->map_ptr)
2398 insn_aux->map_ptr = meta.map_ptr;
2399 else if (insn_aux->map_ptr != meta.map_ptr)
2400 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
2401 } else {
2402 verbose(env, "unknown return type %d of func %s#%d\n",
2403 fn->ret_type, func_id_name(func_id), func_id);
2404 return -EINVAL;
2405 }
2406
2407 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2408 if (err)
2409 return err;
2410
2411 if (changes_data)
2412 clear_all_pkt_pointers(env);
2413 return 0;
2414 }
2415
2416 static bool signed_add_overflows(s64 a, s64 b)
2417 {
2418 /* Do the add in u64, where overflow is well-defined */
2419 s64 res = (s64)((u64)a + (u64)b);
2420
2421 if (b < 0)
2422 return res > a;
2423 return res < a;
2424 }
2425
2426 static bool signed_sub_overflows(s64 a, s64 b)
2427 {
2428 /* Do the sub in u64, where overflow is well-defined */
2429 s64 res = (s64)((u64)a - (u64)b);
2430
2431 if (b < 0)
2432 return res < a;
2433 return res > a;
2434 }
2435
2436 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2437 const struct bpf_reg_state *reg,
2438 enum bpf_reg_type type)
2439 {
2440 bool known = tnum_is_const(reg->var_off);
2441 s64 val = reg->var_off.value;
2442 s64 smin = reg->smin_value;
2443
2444 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2445 verbose(env, "math between %s pointer and %lld is not allowed\n",
2446 reg_type_str[type], val);
2447 return false;
2448 }
2449
2450 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2451 verbose(env, "%s pointer offset %d is not allowed\n",
2452 reg_type_str[type], reg->off);
2453 return false;
2454 }
2455
2456 if (smin == S64_MIN) {
2457 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2458 reg_type_str[type]);
2459 return false;
2460 }
2461
2462 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2463 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2464 smin, reg_type_str[type]);
2465 return false;
2466 }
2467
2468 return true;
2469 }
2470
2471 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2472 * Caller should also handle BPF_MOV case separately.
2473 * If we return -EACCES, caller may want to try again treating pointer as a
2474 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2475 */
2476 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2477 struct bpf_insn *insn,
2478 const struct bpf_reg_state *ptr_reg,
2479 const struct bpf_reg_state *off_reg)
2480 {
2481 struct bpf_verifier_state *vstate = env->cur_state;
2482 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2483 struct bpf_reg_state *regs = state->regs, *dst_reg;
2484 bool known = tnum_is_const(off_reg->var_off);
2485 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2486 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2487 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2488 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2489 u8 opcode = BPF_OP(insn->code);
2490 u32 dst = insn->dst_reg;
2491
2492 dst_reg = &regs[dst];
2493
2494 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2495 smin_val > smax_val || umin_val > umax_val) {
2496 /* Taint dst register if offset had invalid bounds derived from
2497 * e.g. dead branches.
2498 */
2499 __mark_reg_unknown(dst_reg);
2500 return 0;
2501 }
2502
2503 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2504 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2505 verbose(env,
2506 "R%d 32-bit pointer arithmetic prohibited\n",
2507 dst);
2508 return -EACCES;
2509 }
2510
2511 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2512 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2513 dst);
2514 return -EACCES;
2515 }
2516 if (ptr_reg->type == CONST_PTR_TO_MAP) {
2517 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2518 dst);
2519 return -EACCES;
2520 }
2521 if (ptr_reg->type == PTR_TO_PACKET_END) {
2522 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2523 dst);
2524 return -EACCES;
2525 }
2526
2527 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2528 * The id may be overwritten later if we create a new variable offset.
2529 */
2530 dst_reg->type = ptr_reg->type;
2531 dst_reg->id = ptr_reg->id;
2532
2533 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2534 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2535 return -EINVAL;
2536
2537 switch (opcode) {
2538 case BPF_ADD:
2539 /* We can take a fixed offset as long as it doesn't overflow
2540 * the s32 'off' field
2541 */
2542 if (known && (ptr_reg->off + smin_val ==
2543 (s64)(s32)(ptr_reg->off + smin_val))) {
2544 /* pointer += K. Accumulate it into fixed offset */
2545 dst_reg->smin_value = smin_ptr;
2546 dst_reg->smax_value = smax_ptr;
2547 dst_reg->umin_value = umin_ptr;
2548 dst_reg->umax_value = umax_ptr;
2549 dst_reg->var_off = ptr_reg->var_off;
2550 dst_reg->off = ptr_reg->off + smin_val;
2551 dst_reg->range = ptr_reg->range;
2552 break;
2553 }
2554 /* A new variable offset is created. Note that off_reg->off
2555 * == 0, since it's a scalar.
2556 * dst_reg gets the pointer type and since some positive
2557 * integer value was added to the pointer, give it a new 'id'
2558 * if it's a PTR_TO_PACKET.
2559 * this creates a new 'base' pointer, off_reg (variable) gets
2560 * added into the variable offset, and we copy the fixed offset
2561 * from ptr_reg.
2562 */
2563 if (signed_add_overflows(smin_ptr, smin_val) ||
2564 signed_add_overflows(smax_ptr, smax_val)) {
2565 dst_reg->smin_value = S64_MIN;
2566 dst_reg->smax_value = S64_MAX;
2567 } else {
2568 dst_reg->smin_value = smin_ptr + smin_val;
2569 dst_reg->smax_value = smax_ptr + smax_val;
2570 }
2571 if (umin_ptr + umin_val < umin_ptr ||
2572 umax_ptr + umax_val < umax_ptr) {
2573 dst_reg->umin_value = 0;
2574 dst_reg->umax_value = U64_MAX;
2575 } else {
2576 dst_reg->umin_value = umin_ptr + umin_val;
2577 dst_reg->umax_value = umax_ptr + umax_val;
2578 }
2579 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2580 dst_reg->off = ptr_reg->off;
2581 if (reg_is_pkt_pointer(ptr_reg)) {
2582 dst_reg->id = ++env->id_gen;
2583 /* something was added to pkt_ptr, set range to zero */
2584 dst_reg->range = 0;
2585 }
2586 break;
2587 case BPF_SUB:
2588 if (dst_reg == off_reg) {
2589 /* scalar -= pointer. Creates an unknown scalar */
2590 verbose(env, "R%d tried to subtract pointer from scalar\n",
2591 dst);
2592 return -EACCES;
2593 }
2594 /* We don't allow subtraction from FP, because (according to
2595 * test_verifier.c test "invalid fp arithmetic", JITs might not
2596 * be able to deal with it.
2597 */
2598 if (ptr_reg->type == PTR_TO_STACK) {
2599 verbose(env, "R%d subtraction from stack pointer prohibited\n",
2600 dst);
2601 return -EACCES;
2602 }
2603 if (known && (ptr_reg->off - smin_val ==
2604 (s64)(s32)(ptr_reg->off - smin_val))) {
2605 /* pointer -= K. Subtract it from fixed offset */
2606 dst_reg->smin_value = smin_ptr;
2607 dst_reg->smax_value = smax_ptr;
2608 dst_reg->umin_value = umin_ptr;
2609 dst_reg->umax_value = umax_ptr;
2610 dst_reg->var_off = ptr_reg->var_off;
2611 dst_reg->id = ptr_reg->id;
2612 dst_reg->off = ptr_reg->off - smin_val;
2613 dst_reg->range = ptr_reg->range;
2614 break;
2615 }
2616 /* A new variable offset is created. If the subtrahend is known
2617 * nonnegative, then any reg->range we had before is still good.
2618 */
2619 if (signed_sub_overflows(smin_ptr, smax_val) ||
2620 signed_sub_overflows(smax_ptr, smin_val)) {
2621 /* Overflow possible, we know nothing */
2622 dst_reg->smin_value = S64_MIN;
2623 dst_reg->smax_value = S64_MAX;
2624 } else {
2625 dst_reg->smin_value = smin_ptr - smax_val;
2626 dst_reg->smax_value = smax_ptr - smin_val;
2627 }
2628 if (umin_ptr < umax_val) {
2629 /* Overflow possible, we know nothing */
2630 dst_reg->umin_value = 0;
2631 dst_reg->umax_value = U64_MAX;
2632 } else {
2633 /* Cannot overflow (as long as bounds are consistent) */
2634 dst_reg->umin_value = umin_ptr - umax_val;
2635 dst_reg->umax_value = umax_ptr - umin_val;
2636 }
2637 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2638 dst_reg->off = ptr_reg->off;
2639 if (reg_is_pkt_pointer(ptr_reg)) {
2640 dst_reg->id = ++env->id_gen;
2641 /* something was added to pkt_ptr, set range to zero */
2642 if (smin_val < 0)
2643 dst_reg->range = 0;
2644 }
2645 break;
2646 case BPF_AND:
2647 case BPF_OR:
2648 case BPF_XOR:
2649 /* bitwise ops on pointers are troublesome, prohibit. */
2650 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
2651 dst, bpf_alu_string[opcode >> 4]);
2652 return -EACCES;
2653 default:
2654 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2655 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
2656 dst, bpf_alu_string[opcode >> 4]);
2657 return -EACCES;
2658 }
2659
2660 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2661 return -EINVAL;
2662
2663 __update_reg_bounds(dst_reg);
2664 __reg_deduce_bounds(dst_reg);
2665 __reg_bound_offset(dst_reg);
2666 return 0;
2667 }
2668
2669 /* WARNING: This function does calculations on 64-bit values, but the actual
2670 * execution may occur on 32-bit values. Therefore, things like bitshifts
2671 * need extra checks in the 32-bit case.
2672 */
2673 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2674 struct bpf_insn *insn,
2675 struct bpf_reg_state *dst_reg,
2676 struct bpf_reg_state src_reg)
2677 {
2678 struct bpf_reg_state *regs = cur_regs(env);
2679 u8 opcode = BPF_OP(insn->code);
2680 bool src_known, dst_known;
2681 s64 smin_val, smax_val;
2682 u64 umin_val, umax_val;
2683 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2684
2685 smin_val = src_reg.smin_value;
2686 smax_val = src_reg.smax_value;
2687 umin_val = src_reg.umin_value;
2688 umax_val = src_reg.umax_value;
2689 src_known = tnum_is_const(src_reg.var_off);
2690 dst_known = tnum_is_const(dst_reg->var_off);
2691
2692 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2693 smin_val > smax_val || umin_val > umax_val) {
2694 /* Taint dst register if offset had invalid bounds derived from
2695 * e.g. dead branches.
2696 */
2697 __mark_reg_unknown(dst_reg);
2698 return 0;
2699 }
2700
2701 if (!src_known &&
2702 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2703 __mark_reg_unknown(dst_reg);
2704 return 0;
2705 }
2706
2707 switch (opcode) {
2708 case BPF_ADD:
2709 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2710 signed_add_overflows(dst_reg->smax_value, smax_val)) {
2711 dst_reg->smin_value = S64_MIN;
2712 dst_reg->smax_value = S64_MAX;
2713 } else {
2714 dst_reg->smin_value += smin_val;
2715 dst_reg->smax_value += smax_val;
2716 }
2717 if (dst_reg->umin_value + umin_val < umin_val ||
2718 dst_reg->umax_value + umax_val < umax_val) {
2719 dst_reg->umin_value = 0;
2720 dst_reg->umax_value = U64_MAX;
2721 } else {
2722 dst_reg->umin_value += umin_val;
2723 dst_reg->umax_value += umax_val;
2724 }
2725 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2726 break;
2727 case BPF_SUB:
2728 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2729 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2730 /* Overflow possible, we know nothing */
2731 dst_reg->smin_value = S64_MIN;
2732 dst_reg->smax_value = S64_MAX;
2733 } else {
2734 dst_reg->smin_value -= smax_val;
2735 dst_reg->smax_value -= smin_val;
2736 }
2737 if (dst_reg->umin_value < umax_val) {
2738 /* Overflow possible, we know nothing */
2739 dst_reg->umin_value = 0;
2740 dst_reg->umax_value = U64_MAX;
2741 } else {
2742 /* Cannot overflow (as long as bounds are consistent) */
2743 dst_reg->umin_value -= umax_val;
2744 dst_reg->umax_value -= umin_val;
2745 }
2746 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2747 break;
2748 case BPF_MUL:
2749 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2750 if (smin_val < 0 || dst_reg->smin_value < 0) {
2751 /* Ain't nobody got time to multiply that sign */
2752 __mark_reg_unbounded(dst_reg);
2753 __update_reg_bounds(dst_reg);
2754 break;
2755 }
2756 /* Both values are positive, so we can work with unsigned and
2757 * copy the result to signed (unless it exceeds S64_MAX).
2758 */
2759 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2760 /* Potential overflow, we know nothing */
2761 __mark_reg_unbounded(dst_reg);
2762 /* (except what we can learn from the var_off) */
2763 __update_reg_bounds(dst_reg);
2764 break;
2765 }
2766 dst_reg->umin_value *= umin_val;
2767 dst_reg->umax_value *= umax_val;
2768 if (dst_reg->umax_value > S64_MAX) {
2769 /* Overflow possible, we know nothing */
2770 dst_reg->smin_value = S64_MIN;
2771 dst_reg->smax_value = S64_MAX;
2772 } else {
2773 dst_reg->smin_value = dst_reg->umin_value;
2774 dst_reg->smax_value = dst_reg->umax_value;
2775 }
2776 break;
2777 case BPF_AND:
2778 if (src_known && dst_known) {
2779 __mark_reg_known(dst_reg, dst_reg->var_off.value &
2780 src_reg.var_off.value);
2781 break;
2782 }
2783 /* We get our minimum from the var_off, since that's inherently
2784 * bitwise. Our maximum is the minimum of the operands' maxima.
2785 */
2786 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2787 dst_reg->umin_value = dst_reg->var_off.value;
2788 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2789 if (dst_reg->smin_value < 0 || smin_val < 0) {
2790 /* Lose signed bounds when ANDing negative numbers,
2791 * ain't nobody got time for that.
2792 */
2793 dst_reg->smin_value = S64_MIN;
2794 dst_reg->smax_value = S64_MAX;
2795 } else {
2796 /* ANDing two positives gives a positive, so safe to
2797 * cast result into s64.
2798 */
2799 dst_reg->smin_value = dst_reg->umin_value;
2800 dst_reg->smax_value = dst_reg->umax_value;
2801 }
2802 /* We may learn something more from the var_off */
2803 __update_reg_bounds(dst_reg);
2804 break;
2805 case BPF_OR:
2806 if (src_known && dst_known) {
2807 __mark_reg_known(dst_reg, dst_reg->var_off.value |
2808 src_reg.var_off.value);
2809 break;
2810 }
2811 /* We get our maximum from the var_off, and our minimum is the
2812 * maximum of the operands' minima
2813 */
2814 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2815 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2816 dst_reg->umax_value = dst_reg->var_off.value |
2817 dst_reg->var_off.mask;
2818 if (dst_reg->smin_value < 0 || smin_val < 0) {
2819 /* Lose signed bounds when ORing negative numbers,
2820 * ain't nobody got time for that.
2821 */
2822 dst_reg->smin_value = S64_MIN;
2823 dst_reg->smax_value = S64_MAX;
2824 } else {
2825 /* ORing two positives gives a positive, so safe to
2826 * cast result into s64.
2827 */
2828 dst_reg->smin_value = dst_reg->umin_value;
2829 dst_reg->smax_value = dst_reg->umax_value;
2830 }
2831 /* We may learn something more from the var_off */
2832 __update_reg_bounds(dst_reg);
2833 break;
2834 case BPF_LSH:
2835 if (umax_val >= insn_bitness) {
2836 /* Shifts greater than 31 or 63 are undefined.
2837 * This includes shifts by a negative number.
2838 */
2839 mark_reg_unknown(env, regs, insn->dst_reg);
2840 break;
2841 }
2842 /* We lose all sign bit information (except what we can pick
2843 * up from var_off)
2844 */
2845 dst_reg->smin_value = S64_MIN;
2846 dst_reg->smax_value = S64_MAX;
2847 /* If we might shift our top bit out, then we know nothing */
2848 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2849 dst_reg->umin_value = 0;
2850 dst_reg->umax_value = U64_MAX;
2851 } else {
2852 dst_reg->umin_value <<= umin_val;
2853 dst_reg->umax_value <<= umax_val;
2854 }
2855 if (src_known)
2856 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2857 else
2858 dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2859 /* We may learn something more from the var_off */
2860 __update_reg_bounds(dst_reg);
2861 break;
2862 case BPF_RSH:
2863 if (umax_val >= insn_bitness) {
2864 /* Shifts greater than 31 or 63 are undefined.
2865 * This includes shifts by a negative number.
2866 */
2867 mark_reg_unknown(env, regs, insn->dst_reg);
2868 break;
2869 }
2870 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
2871 * be negative, then either:
2872 * 1) src_reg might be zero, so the sign bit of the result is
2873 * unknown, so we lose our signed bounds
2874 * 2) it's known negative, thus the unsigned bounds capture the
2875 * signed bounds
2876 * 3) the signed bounds cross zero, so they tell us nothing
2877 * about the result
2878 * If the value in dst_reg is known nonnegative, then again the
2879 * unsigned bounts capture the signed bounds.
2880 * Thus, in all cases it suffices to blow away our signed bounds
2881 * and rely on inferring new ones from the unsigned bounds and
2882 * var_off of the result.
2883 */
2884 dst_reg->smin_value = S64_MIN;
2885 dst_reg->smax_value = S64_MAX;
2886 if (src_known)
2887 dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2888 umin_val);
2889 else
2890 dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2891 dst_reg->umin_value >>= umax_val;
2892 dst_reg->umax_value >>= umin_val;
2893 /* We may learn something more from the var_off */
2894 __update_reg_bounds(dst_reg);
2895 break;
2896 default:
2897 mark_reg_unknown(env, regs, insn->dst_reg);
2898 break;
2899 }
2900
2901 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2902 /* 32-bit ALU ops are (32,32)->32 */
2903 coerce_reg_to_size(dst_reg, 4);
2904 coerce_reg_to_size(&src_reg, 4);
2905 }
2906
2907 __reg_deduce_bounds(dst_reg);
2908 __reg_bound_offset(dst_reg);
2909 return 0;
2910 }
2911
2912 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2913 * and var_off.
2914 */
2915 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2916 struct bpf_insn *insn)
2917 {
2918 struct bpf_verifier_state *vstate = env->cur_state;
2919 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2920 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
2921 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2922 u8 opcode = BPF_OP(insn->code);
2923
2924 dst_reg = &regs[insn->dst_reg];
2925 src_reg = NULL;
2926 if (dst_reg->type != SCALAR_VALUE)
2927 ptr_reg = dst_reg;
2928 if (BPF_SRC(insn->code) == BPF_X) {
2929 src_reg = &regs[insn->src_reg];
2930 if (src_reg->type != SCALAR_VALUE) {
2931 if (dst_reg->type != SCALAR_VALUE) {
2932 /* Combining two pointers by any ALU op yields
2933 * an arbitrary scalar. Disallow all math except
2934 * pointer subtraction
2935 */
2936 if (opcode == BPF_SUB){
2937 mark_reg_unknown(env, regs, insn->dst_reg);
2938 return 0;
2939 }
2940 verbose(env, "R%d pointer %s pointer prohibited\n",
2941 insn->dst_reg,
2942 bpf_alu_string[opcode >> 4]);
2943 return -EACCES;
2944 } else {
2945 /* scalar += pointer
2946 * This is legal, but we have to reverse our
2947 * src/dest handling in computing the range
2948 */
2949 return adjust_ptr_min_max_vals(env, insn,
2950 src_reg, dst_reg);
2951 }
2952 } else if (ptr_reg) {
2953 /* pointer += scalar */
2954 return adjust_ptr_min_max_vals(env, insn,
2955 dst_reg, src_reg);
2956 }
2957 } else {
2958 /* Pretend the src is a reg with a known value, since we only
2959 * need to be able to read from this state.
2960 */
2961 off_reg.type = SCALAR_VALUE;
2962 __mark_reg_known(&off_reg, insn->imm);
2963 src_reg = &off_reg;
2964 if (ptr_reg) /* pointer += K */
2965 return adjust_ptr_min_max_vals(env, insn,
2966 ptr_reg, src_reg);
2967 }
2968
2969 /* Got here implies adding two SCALAR_VALUEs */
2970 if (WARN_ON_ONCE(ptr_reg)) {
2971 print_verifier_state(env, state);
2972 verbose(env, "verifier internal error: unexpected ptr_reg\n");
2973 return -EINVAL;
2974 }
2975 if (WARN_ON(!src_reg)) {
2976 print_verifier_state(env, state);
2977 verbose(env, "verifier internal error: no src_reg\n");
2978 return -EINVAL;
2979 }
2980 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
2981 }
2982
2983 /* check validity of 32-bit and 64-bit arithmetic operations */
2984 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
2985 {
2986 struct bpf_reg_state *regs = cur_regs(env);
2987 u8 opcode = BPF_OP(insn->code);
2988 int err;
2989
2990 if (opcode == BPF_END || opcode == BPF_NEG) {
2991 if (opcode == BPF_NEG) {
2992 if (BPF_SRC(insn->code) != 0 ||
2993 insn->src_reg != BPF_REG_0 ||
2994 insn->off != 0 || insn->imm != 0) {
2995 verbose(env, "BPF_NEG uses reserved fields\n");
2996 return -EINVAL;
2997 }
2998 } else {
2999 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3000 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3001 BPF_CLASS(insn->code) == BPF_ALU64) {
3002 verbose(env, "BPF_END uses reserved fields\n");
3003 return -EINVAL;
3004 }
3005 }
3006
3007 /* check src operand */
3008 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3009 if (err)
3010 return err;
3011
3012 if (is_pointer_value(env, insn->dst_reg)) {
3013 verbose(env, "R%d pointer arithmetic prohibited\n",
3014 insn->dst_reg);
3015 return -EACCES;
3016 }
3017
3018 /* check dest operand */
3019 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3020 if (err)
3021 return err;
3022
3023 } else if (opcode == BPF_MOV) {
3024
3025 if (BPF_SRC(insn->code) == BPF_X) {
3026 if (insn->imm != 0 || insn->off != 0) {
3027 verbose(env, "BPF_MOV uses reserved fields\n");
3028 return -EINVAL;
3029 }
3030
3031 /* check src operand */
3032 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3033 if (err)
3034 return err;
3035 } else {
3036 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3037 verbose(env, "BPF_MOV uses reserved fields\n");
3038 return -EINVAL;
3039 }
3040 }
3041
3042 /* check dest operand */
3043 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3044 if (err)
3045 return err;
3046
3047 if (BPF_SRC(insn->code) == BPF_X) {
3048 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3049 /* case: R1 = R2
3050 * copy register state to dest reg
3051 */
3052 regs[insn->dst_reg] = regs[insn->src_reg];
3053 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3054 } else {
3055 /* R1 = (u32) R2 */
3056 if (is_pointer_value(env, insn->src_reg)) {
3057 verbose(env,
3058 "R%d partial copy of pointer\n",
3059 insn->src_reg);
3060 return -EACCES;
3061 }
3062 mark_reg_unknown(env, regs, insn->dst_reg);
3063 coerce_reg_to_size(&regs[insn->dst_reg], 4);
3064 }
3065 } else {
3066 /* case: R = imm
3067 * remember the value we stored into this reg
3068 */
3069 regs[insn->dst_reg].type = SCALAR_VALUE;
3070 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3071 __mark_reg_known(regs + insn->dst_reg,
3072 insn->imm);
3073 } else {
3074 __mark_reg_known(regs + insn->dst_reg,
3075 (u32)insn->imm);
3076 }
3077 }
3078
3079 } else if (opcode > BPF_END) {
3080 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3081 return -EINVAL;
3082
3083 } else { /* all other ALU ops: and, sub, xor, add, ... */
3084
3085 if (BPF_SRC(insn->code) == BPF_X) {
3086 if (insn->imm != 0 || insn->off != 0) {
3087 verbose(env, "BPF_ALU uses reserved fields\n");
3088 return -EINVAL;
3089 }
3090 /* check src1 operand */
3091 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3092 if (err)
3093 return err;
3094 } else {
3095 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3096 verbose(env, "BPF_ALU uses reserved fields\n");
3097 return -EINVAL;
3098 }
3099 }
3100
3101 /* check src2 operand */
3102 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3103 if (err)
3104 return err;
3105
3106 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3107 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3108 verbose(env, "div by zero\n");
3109 return -EINVAL;
3110 }
3111
3112 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3113 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3114 return -EINVAL;
3115 }
3116
3117 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3118 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3119 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3120
3121 if (insn->imm < 0 || insn->imm >= size) {
3122 verbose(env, "invalid shift %d\n", insn->imm);
3123 return -EINVAL;
3124 }
3125 }
3126
3127 /* check dest operand */
3128 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3129 if (err)
3130 return err;
3131
3132 return adjust_reg_min_max_vals(env, insn);
3133 }
3134
3135 return 0;
3136 }
3137
3138 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3139 struct bpf_reg_state *dst_reg,
3140 enum bpf_reg_type type,
3141 bool range_right_open)
3142 {
3143 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3144 struct bpf_reg_state *regs = state->regs, *reg;
3145 u16 new_range;
3146 int i, j;
3147
3148 if (dst_reg->off < 0 ||
3149 (dst_reg->off == 0 && range_right_open))
3150 /* This doesn't give us any range */
3151 return;
3152
3153 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3154 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3155 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3156 * than pkt_end, but that's because it's also less than pkt.
3157 */
3158 return;
3159
3160 new_range = dst_reg->off;
3161 if (range_right_open)
3162 new_range--;
3163
3164 /* Examples for register markings:
3165 *
3166 * pkt_data in dst register:
3167 *
3168 * r2 = r3;
3169 * r2 += 8;
3170 * if (r2 > pkt_end) goto <handle exception>
3171 * <access okay>
3172 *
3173 * r2 = r3;
3174 * r2 += 8;
3175 * if (r2 < pkt_end) goto <access okay>
3176 * <handle exception>
3177 *
3178 * Where:
3179 * r2 == dst_reg, pkt_end == src_reg
3180 * r2=pkt(id=n,off=8,r=0)
3181 * r3=pkt(id=n,off=0,r=0)
3182 *
3183 * pkt_data in src register:
3184 *
3185 * r2 = r3;
3186 * r2 += 8;
3187 * if (pkt_end >= r2) goto <access okay>
3188 * <handle exception>
3189 *
3190 * r2 = r3;
3191 * r2 += 8;
3192 * if (pkt_end <= r2) goto <handle exception>
3193 * <access okay>
3194 *
3195 * Where:
3196 * pkt_end == dst_reg, r2 == src_reg
3197 * r2=pkt(id=n,off=8,r=0)
3198 * r3=pkt(id=n,off=0,r=0)
3199 *
3200 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3201 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3202 * and [r3, r3 + 8-1) respectively is safe to access depending on
3203 * the check.
3204 */
3205
3206 /* If our ids match, then we must have the same max_value. And we
3207 * don't care about the other reg's fixed offset, since if it's too big
3208 * the range won't allow anything.
3209 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3210 */
3211 for (i = 0; i < MAX_BPF_REG; i++)
3212 if (regs[i].type == type && regs[i].id == dst_reg->id)
3213 /* keep the maximum range already checked */
3214 regs[i].range = max(regs[i].range, new_range);
3215
3216 for (j = 0; j <= vstate->curframe; j++) {
3217 state = vstate->frame[j];
3218 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3219 if (state->stack[i].slot_type[0] != STACK_SPILL)
3220 continue;
3221 reg = &state->stack[i].spilled_ptr;
3222 if (reg->type == type && reg->id == dst_reg->id)
3223 reg->range = max(reg->range, new_range);
3224 }
3225 }
3226 }
3227
3228 /* Adjusts the register min/max values in the case that the dst_reg is the
3229 * variable register that we are working on, and src_reg is a constant or we're
3230 * simply doing a BPF_K check.
3231 * In JEQ/JNE cases we also adjust the var_off values.
3232 */
3233 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3234 struct bpf_reg_state *false_reg, u64 val,
3235 u8 opcode)
3236 {
3237 /* If the dst_reg is a pointer, we can't learn anything about its
3238 * variable offset from the compare (unless src_reg were a pointer into
3239 * the same object, but we don't bother with that.
3240 * Since false_reg and true_reg have the same type by construction, we
3241 * only need to check one of them for pointerness.
3242 */
3243 if (__is_pointer_value(false, false_reg))
3244 return;
3245
3246 switch (opcode) {
3247 case BPF_JEQ:
3248 /* If this is false then we know nothing Jon Snow, but if it is
3249 * true then we know for sure.
3250 */
3251 __mark_reg_known(true_reg, val);
3252 break;
3253 case BPF_JNE:
3254 /* If this is true we know nothing Jon Snow, but if it is false
3255 * we know the value for sure;
3256 */
3257 __mark_reg_known(false_reg, val);
3258 break;
3259 case BPF_JGT:
3260 false_reg->umax_value = min(false_reg->umax_value, val);
3261 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3262 break;
3263 case BPF_JSGT:
3264 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3265 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3266 break;
3267 case BPF_JLT:
3268 false_reg->umin_value = max(false_reg->umin_value, val);
3269 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3270 break;
3271 case BPF_JSLT:
3272 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3273 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3274 break;
3275 case BPF_JGE:
3276 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3277 true_reg->umin_value = max(true_reg->umin_value, val);
3278 break;
3279 case BPF_JSGE:
3280 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3281 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3282 break;
3283 case BPF_JLE:
3284 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3285 true_reg->umax_value = min(true_reg->umax_value, val);
3286 break;
3287 case BPF_JSLE:
3288 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3289 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3290 break;
3291 default:
3292 break;
3293 }
3294
3295 __reg_deduce_bounds(false_reg);
3296 __reg_deduce_bounds(true_reg);
3297 /* We might have learned some bits from the bounds. */
3298 __reg_bound_offset(false_reg);
3299 __reg_bound_offset(true_reg);
3300 /* Intersecting with the old var_off might have improved our bounds
3301 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3302 * then new var_off is (0; 0x7f...fc) which improves our umax.
3303 */
3304 __update_reg_bounds(false_reg);
3305 __update_reg_bounds(true_reg);
3306 }
3307
3308 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3309 * the variable reg.
3310 */
3311 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3312 struct bpf_reg_state *false_reg, u64 val,
3313 u8 opcode)
3314 {
3315 if (__is_pointer_value(false, false_reg))
3316 return;
3317
3318 switch (opcode) {
3319 case BPF_JEQ:
3320 /* If this is false then we know nothing Jon Snow, but if it is
3321 * true then we know for sure.
3322 */
3323 __mark_reg_known(true_reg, val);
3324 break;
3325 case BPF_JNE:
3326 /* If this is true we know nothing Jon Snow, but if it is false
3327 * we know the value for sure;
3328 */
3329 __mark_reg_known(false_reg, val);
3330 break;
3331 case BPF_JGT:
3332 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3333 false_reg->umin_value = max(false_reg->umin_value, val);
3334 break;
3335 case BPF_JSGT:
3336 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3337 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3338 break;
3339 case BPF_JLT:
3340 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3341 false_reg->umax_value = min(false_reg->umax_value, val);
3342 break;
3343 case BPF_JSLT:
3344 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3345 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3346 break;
3347 case BPF_JGE:
3348 true_reg->umax_value = min(true_reg->umax_value, val);
3349 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3350 break;
3351 case BPF_JSGE:
3352 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3353 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3354 break;
3355 case BPF_JLE:
3356 true_reg->umin_value = max(true_reg->umin_value, val);
3357 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3358 break;
3359 case BPF_JSLE:
3360 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3361 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3362 break;
3363 default:
3364 break;
3365 }
3366
3367 __reg_deduce_bounds(false_reg);
3368 __reg_deduce_bounds(true_reg);
3369 /* We might have learned some bits from the bounds. */
3370 __reg_bound_offset(false_reg);
3371 __reg_bound_offset(true_reg);
3372 /* Intersecting with the old var_off might have improved our bounds
3373 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3374 * then new var_off is (0; 0x7f...fc) which improves our umax.
3375 */
3376 __update_reg_bounds(false_reg);
3377 __update_reg_bounds(true_reg);
3378 }
3379
3380 /* Regs are known to be equal, so intersect their min/max/var_off */
3381 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3382 struct bpf_reg_state *dst_reg)
3383 {
3384 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3385 dst_reg->umin_value);
3386 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3387 dst_reg->umax_value);
3388 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3389 dst_reg->smin_value);
3390 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3391 dst_reg->smax_value);
3392 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3393 dst_reg->var_off);
3394 /* We might have learned new bounds from the var_off. */
3395 __update_reg_bounds(src_reg);
3396 __update_reg_bounds(dst_reg);
3397 /* We might have learned something about the sign bit. */
3398 __reg_deduce_bounds(src_reg);
3399 __reg_deduce_bounds(dst_reg);
3400 /* We might have learned some bits from the bounds. */
3401 __reg_bound_offset(src_reg);
3402 __reg_bound_offset(dst_reg);
3403 /* Intersecting with the old var_off might have improved our bounds
3404 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3405 * then new var_off is (0; 0x7f...fc) which improves our umax.
3406 */
3407 __update_reg_bounds(src_reg);
3408 __update_reg_bounds(dst_reg);
3409 }
3410
3411 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3412 struct bpf_reg_state *true_dst,
3413 struct bpf_reg_state *false_src,
3414 struct bpf_reg_state *false_dst,
3415 u8 opcode)
3416 {
3417 switch (opcode) {
3418 case BPF_JEQ:
3419 __reg_combine_min_max(true_src, true_dst);
3420 break;
3421 case BPF_JNE:
3422 __reg_combine_min_max(false_src, false_dst);
3423 break;
3424 }
3425 }
3426
3427 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3428 bool is_null)
3429 {
3430 struct bpf_reg_state *reg = &regs[regno];
3431
3432 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3433 /* Old offset (both fixed and variable parts) should
3434 * have been known-zero, because we don't allow pointer
3435 * arithmetic on pointers that might be NULL.
3436 */
3437 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3438 !tnum_equals_const(reg->var_off, 0) ||
3439 reg->off)) {
3440 __mark_reg_known_zero(reg);
3441 reg->off = 0;
3442 }
3443 if (is_null) {
3444 reg->type = SCALAR_VALUE;
3445 } else if (reg->map_ptr->inner_map_meta) {
3446 reg->type = CONST_PTR_TO_MAP;
3447 reg->map_ptr = reg->map_ptr->inner_map_meta;
3448 } else {
3449 reg->type = PTR_TO_MAP_VALUE;
3450 }
3451 /* We don't need id from this point onwards anymore, thus we
3452 * should better reset it, so that state pruning has chances
3453 * to take effect.
3454 */
3455 reg->id = 0;
3456 }
3457 }
3458
3459 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3460 * be folded together at some point.
3461 */
3462 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3463 bool is_null)
3464 {
3465 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3466 struct bpf_reg_state *regs = state->regs;
3467 u32 id = regs[regno].id;
3468 int i, j;
3469
3470 for (i = 0; i < MAX_BPF_REG; i++)
3471 mark_map_reg(regs, i, id, is_null);
3472
3473 for (j = 0; j <= vstate->curframe; j++) {
3474 state = vstate->frame[j];
3475 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3476 if (state->stack[i].slot_type[0] != STACK_SPILL)
3477 continue;
3478 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3479 }
3480 }
3481 }
3482
3483 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3484 struct bpf_reg_state *dst_reg,
3485 struct bpf_reg_state *src_reg,
3486 struct bpf_verifier_state *this_branch,
3487 struct bpf_verifier_state *other_branch)
3488 {
3489 if (BPF_SRC(insn->code) != BPF_X)
3490 return false;
3491
3492 switch (BPF_OP(insn->code)) {
3493 case BPF_JGT:
3494 if ((dst_reg->type == PTR_TO_PACKET &&
3495 src_reg->type == PTR_TO_PACKET_END) ||
3496 (dst_reg->type == PTR_TO_PACKET_META &&
3497 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3498 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
3499 find_good_pkt_pointers(this_branch, dst_reg,
3500 dst_reg->type, false);
3501 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3502 src_reg->type == PTR_TO_PACKET) ||
3503 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3504 src_reg->type == PTR_TO_PACKET_META)) {
3505 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
3506 find_good_pkt_pointers(other_branch, src_reg,
3507 src_reg->type, true);
3508 } else {
3509 return false;
3510 }
3511 break;
3512 case BPF_JLT:
3513 if ((dst_reg->type == PTR_TO_PACKET &&
3514 src_reg->type == PTR_TO_PACKET_END) ||
3515 (dst_reg->type == PTR_TO_PACKET_META &&
3516 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3517 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
3518 find_good_pkt_pointers(other_branch, dst_reg,
3519 dst_reg->type, true);
3520 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3521 src_reg->type == PTR_TO_PACKET) ||
3522 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3523 src_reg->type == PTR_TO_PACKET_META)) {
3524 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
3525 find_good_pkt_pointers(this_branch, src_reg,
3526 src_reg->type, false);
3527 } else {
3528 return false;
3529 }
3530 break;
3531 case BPF_JGE:
3532 if ((dst_reg->type == PTR_TO_PACKET &&
3533 src_reg->type == PTR_TO_PACKET_END) ||
3534 (dst_reg->type == PTR_TO_PACKET_META &&
3535 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3536 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
3537 find_good_pkt_pointers(this_branch, dst_reg,
3538 dst_reg->type, true);
3539 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3540 src_reg->type == PTR_TO_PACKET) ||
3541 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3542 src_reg->type == PTR_TO_PACKET_META)) {
3543 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
3544 find_good_pkt_pointers(other_branch, src_reg,
3545 src_reg->type, false);
3546 } else {
3547 return false;
3548 }
3549 break;
3550 case BPF_JLE:
3551 if ((dst_reg->type == PTR_TO_PACKET &&
3552 src_reg->type == PTR_TO_PACKET_END) ||
3553 (dst_reg->type == PTR_TO_PACKET_META &&
3554 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3555 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
3556 find_good_pkt_pointers(other_branch, dst_reg,
3557 dst_reg->type, false);
3558 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3559 src_reg->type == PTR_TO_PACKET) ||
3560 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3561 src_reg->type == PTR_TO_PACKET_META)) {
3562 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
3563 find_good_pkt_pointers(this_branch, src_reg,
3564 src_reg->type, true);
3565 } else {
3566 return false;
3567 }
3568 break;
3569 default:
3570 return false;
3571 }
3572
3573 return true;
3574 }
3575
3576 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3577 struct bpf_insn *insn, int *insn_idx)
3578 {
3579 struct bpf_verifier_state *this_branch = env->cur_state;
3580 struct bpf_verifier_state *other_branch;
3581 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
3582 struct bpf_reg_state *dst_reg, *other_branch_regs;
3583 u8 opcode = BPF_OP(insn->code);
3584 int err;
3585
3586 if (opcode > BPF_JSLE) {
3587 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
3588 return -EINVAL;
3589 }
3590
3591 if (BPF_SRC(insn->code) == BPF_X) {
3592 if (insn->imm != 0) {
3593 verbose(env, "BPF_JMP uses reserved fields\n");
3594 return -EINVAL;
3595 }
3596
3597 /* check src1 operand */
3598 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3599 if (err)
3600 return err;
3601
3602 if (is_pointer_value(env, insn->src_reg)) {
3603 verbose(env, "R%d pointer comparison prohibited\n",
3604 insn->src_reg);
3605 return -EACCES;
3606 }
3607 } else {
3608 if (insn->src_reg != BPF_REG_0) {
3609 verbose(env, "BPF_JMP uses reserved fields\n");
3610 return -EINVAL;
3611 }
3612 }
3613
3614 /* check src2 operand */
3615 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3616 if (err)
3617 return err;
3618
3619 dst_reg = &regs[insn->dst_reg];
3620
3621 /* detect if R == 0 where R was initialized to zero earlier */
3622 if (BPF_SRC(insn->code) == BPF_K &&
3623 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3624 dst_reg->type == SCALAR_VALUE &&
3625 tnum_is_const(dst_reg->var_off)) {
3626 if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
3627 (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
3628 /* if (imm == imm) goto pc+off;
3629 * only follow the goto, ignore fall-through
3630 */
3631 *insn_idx += insn->off;
3632 return 0;
3633 } else {
3634 /* if (imm != imm) goto pc+off;
3635 * only follow fall-through branch, since
3636 * that's where the program will go
3637 */
3638 return 0;
3639 }
3640 }
3641
3642 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
3643 if (!other_branch)
3644 return -EFAULT;
3645 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
3646
3647 /* detect if we are comparing against a constant value so we can adjust
3648 * our min/max values for our dst register.
3649 * this is only legit if both are scalars (or pointers to the same
3650 * object, I suppose, but we don't support that right now), because
3651 * otherwise the different base pointers mean the offsets aren't
3652 * comparable.
3653 */
3654 if (BPF_SRC(insn->code) == BPF_X) {
3655 if (dst_reg->type == SCALAR_VALUE &&
3656 regs[insn->src_reg].type == SCALAR_VALUE) {
3657 if (tnum_is_const(regs[insn->src_reg].var_off))
3658 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3659 dst_reg, regs[insn->src_reg].var_off.value,
3660 opcode);
3661 else if (tnum_is_const(dst_reg->var_off))
3662 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
3663 &regs[insn->src_reg],
3664 dst_reg->var_off.value, opcode);
3665 else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3666 /* Comparing for equality, we can combine knowledge */
3667 reg_combine_min_max(&other_branch_regs[insn->src_reg],
3668 &other_branch_regs[insn->dst_reg],
3669 &regs[insn->src_reg],
3670 &regs[insn->dst_reg], opcode);
3671 }
3672 } else if (dst_reg->type == SCALAR_VALUE) {
3673 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3674 dst_reg, insn->imm, opcode);
3675 }
3676
3677 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3678 if (BPF_SRC(insn->code) == BPF_K &&
3679 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3680 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3681 /* Mark all identical map registers in each branch as either
3682 * safe or unknown depending R == 0 or R != 0 conditional.
3683 */
3684 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3685 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3686 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
3687 this_branch, other_branch) &&
3688 is_pointer_value(env, insn->dst_reg)) {
3689 verbose(env, "R%d pointer comparison prohibited\n",
3690 insn->dst_reg);
3691 return -EACCES;
3692 }
3693 if (env->log.level)
3694 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
3695 return 0;
3696 }
3697
3698 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3699 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3700 {
3701 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3702
3703 return (struct bpf_map *) (unsigned long) imm64;
3704 }
3705
3706 /* verify BPF_LD_IMM64 instruction */
3707 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3708 {
3709 struct bpf_reg_state *regs = cur_regs(env);
3710 int err;
3711
3712 if (BPF_SIZE(insn->code) != BPF_DW) {
3713 verbose(env, "invalid BPF_LD_IMM insn\n");
3714 return -EINVAL;
3715 }
3716 if (insn->off != 0) {
3717 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
3718 return -EINVAL;
3719 }
3720
3721 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3722 if (err)
3723 return err;
3724
3725 if (insn->src_reg == 0) {
3726 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3727
3728 regs[insn->dst_reg].type = SCALAR_VALUE;
3729 __mark_reg_known(&regs[insn->dst_reg], imm);
3730 return 0;
3731 }
3732
3733 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3734 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3735
3736 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3737 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3738 return 0;
3739 }
3740
3741 static bool may_access_skb(enum bpf_prog_type type)
3742 {
3743 switch (type) {
3744 case BPF_PROG_TYPE_SOCKET_FILTER:
3745 case BPF_PROG_TYPE_SCHED_CLS:
3746 case BPF_PROG_TYPE_SCHED_ACT:
3747 return true;
3748 default:
3749 return false;
3750 }
3751 }
3752
3753 /* verify safety of LD_ABS|LD_IND instructions:
3754 * - they can only appear in the programs where ctx == skb
3755 * - since they are wrappers of function calls, they scratch R1-R5 registers,
3756 * preserve R6-R9, and store return value into R0
3757 *
3758 * Implicit input:
3759 * ctx == skb == R6 == CTX
3760 *
3761 * Explicit input:
3762 * SRC == any register
3763 * IMM == 32-bit immediate
3764 *
3765 * Output:
3766 * R0 - 8/16/32-bit skb data converted to cpu endianness
3767 */
3768 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3769 {
3770 struct bpf_reg_state *regs = cur_regs(env);
3771 u8 mode = BPF_MODE(insn->code);
3772 int i, err;
3773
3774 if (!may_access_skb(env->prog->type)) {
3775 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3776 return -EINVAL;
3777 }
3778
3779 if (env->subprog_cnt) {
3780 /* when program has LD_ABS insn JITs and interpreter assume
3781 * that r1 == ctx == skb which is not the case for callees
3782 * that can have arbitrary arguments. It's problematic
3783 * for main prog as well since JITs would need to analyze
3784 * all functions in order to make proper register save/restore
3785 * decisions in the main prog. Hence disallow LD_ABS with calls
3786 */
3787 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
3788 return -EINVAL;
3789 }
3790
3791 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3792 BPF_SIZE(insn->code) == BPF_DW ||
3793 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3794 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
3795 return -EINVAL;
3796 }
3797
3798 /* check whether implicit source operand (register R6) is readable */
3799 err = check_reg_arg(env, BPF_REG_6, SRC_OP);
3800 if (err)
3801 return err;
3802
3803 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
3804 verbose(env,
3805 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3806 return -EINVAL;
3807 }
3808
3809 if (mode == BPF_IND) {
3810 /* check explicit source operand */
3811 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3812 if (err)
3813 return err;
3814 }
3815
3816 /* reset caller saved regs to unreadable */
3817 for (i = 0; i < CALLER_SAVED_REGS; i++) {
3818 mark_reg_not_init(env, regs, caller_saved[i]);
3819 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3820 }
3821
3822 /* mark destination R0 register as readable, since it contains
3823 * the value fetched from the packet.
3824 * Already marked as written above.
3825 */
3826 mark_reg_unknown(env, regs, BPF_REG_0);
3827 return 0;
3828 }
3829
3830 static int check_return_code(struct bpf_verifier_env *env)
3831 {
3832 struct bpf_reg_state *reg;
3833 struct tnum range = tnum_range(0, 1);
3834
3835 switch (env->prog->type) {
3836 case BPF_PROG_TYPE_CGROUP_SKB:
3837 case BPF_PROG_TYPE_CGROUP_SOCK:
3838 case BPF_PROG_TYPE_SOCK_OPS:
3839 case BPF_PROG_TYPE_CGROUP_DEVICE:
3840 break;
3841 default:
3842 return 0;
3843 }
3844
3845 reg = cur_regs(env) + BPF_REG_0;
3846 if (reg->type != SCALAR_VALUE) {
3847 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
3848 reg_type_str[reg->type]);
3849 return -EINVAL;
3850 }
3851
3852 if (!tnum_in(range, reg->var_off)) {
3853 verbose(env, "At program exit the register R0 ");
3854 if (!tnum_is_unknown(reg->var_off)) {
3855 char tn_buf[48];
3856
3857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3858 verbose(env, "has value %s", tn_buf);
3859 } else {
3860 verbose(env, "has unknown scalar value");
3861 }
3862 verbose(env, " should have been 0 or 1\n");
3863 return -EINVAL;
3864 }
3865 return 0;
3866 }
3867
3868 /* non-recursive DFS pseudo code
3869 * 1 procedure DFS-iterative(G,v):
3870 * 2 label v as discovered
3871 * 3 let S be a stack
3872 * 4 S.push(v)
3873 * 5 while S is not empty
3874 * 6 t <- S.pop()
3875 * 7 if t is what we're looking for:
3876 * 8 return t
3877 * 9 for all edges e in G.adjacentEdges(t) do
3878 * 10 if edge e is already labelled
3879 * 11 continue with the next edge
3880 * 12 w <- G.adjacentVertex(t,e)
3881 * 13 if vertex w is not discovered and not explored
3882 * 14 label e as tree-edge
3883 * 15 label w as discovered
3884 * 16 S.push(w)
3885 * 17 continue at 5
3886 * 18 else if vertex w is discovered
3887 * 19 label e as back-edge
3888 * 20 else
3889 * 21 // vertex w is explored
3890 * 22 label e as forward- or cross-edge
3891 * 23 label t as explored
3892 * 24 S.pop()
3893 *
3894 * convention:
3895 * 0x10 - discovered
3896 * 0x11 - discovered and fall-through edge labelled
3897 * 0x12 - discovered and fall-through and branch edges labelled
3898 * 0x20 - explored
3899 */
3900
3901 enum {
3902 DISCOVERED = 0x10,
3903 EXPLORED = 0x20,
3904 FALLTHROUGH = 1,
3905 BRANCH = 2,
3906 };
3907
3908 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3909
3910 static int *insn_stack; /* stack of insns to process */
3911 static int cur_stack; /* current stack index */
3912 static int *insn_state;
3913
3914 /* t, w, e - match pseudo-code above:
3915 * t - index of current instruction
3916 * w - next instruction
3917 * e - edge
3918 */
3919 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3920 {
3921 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3922 return 0;
3923
3924 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3925 return 0;
3926
3927 if (w < 0 || w >= env->prog->len) {
3928 verbose(env, "jump out of range from insn %d to %d\n", t, w);
3929 return -EINVAL;
3930 }
3931
3932 if (e == BRANCH)
3933 /* mark branch target for state pruning */
3934 env->explored_states[w] = STATE_LIST_MARK;
3935
3936 if (insn_state[w] == 0) {
3937 /* tree-edge */
3938 insn_state[t] = DISCOVERED | e;
3939 insn_state[w] = DISCOVERED;
3940 if (cur_stack >= env->prog->len)
3941 return -E2BIG;
3942 insn_stack[cur_stack++] = w;
3943 return 1;
3944 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3945 verbose(env, "back-edge from insn %d to %d\n", t, w);
3946 return -EINVAL;
3947 } else if (insn_state[w] == EXPLORED) {
3948 /* forward- or cross-edge */
3949 insn_state[t] = DISCOVERED | e;
3950 } else {
3951 verbose(env, "insn state internal bug\n");
3952 return -EFAULT;
3953 }
3954 return 0;
3955 }
3956
3957 /* non-recursive depth-first-search to detect loops in BPF program
3958 * loop == back-edge in directed graph
3959 */
3960 static int check_cfg(struct bpf_verifier_env *env)
3961 {
3962 struct bpf_insn *insns = env->prog->insnsi;
3963 int insn_cnt = env->prog->len;
3964 int ret = 0;
3965 int i, t;
3966
3967 ret = check_subprogs(env);
3968 if (ret < 0)
3969 return ret;
3970
3971 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3972 if (!insn_state)
3973 return -ENOMEM;
3974
3975 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3976 if (!insn_stack) {
3977 kfree(insn_state);
3978 return -ENOMEM;
3979 }
3980
3981 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3982 insn_stack[0] = 0; /* 0 is the first instruction */
3983 cur_stack = 1;
3984
3985 peek_stack:
3986 if (cur_stack == 0)
3987 goto check_state;
3988 t = insn_stack[cur_stack - 1];
3989
3990 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3991 u8 opcode = BPF_OP(insns[t].code);
3992
3993 if (opcode == BPF_EXIT) {
3994 goto mark_explored;
3995 } else if (opcode == BPF_CALL) {
3996 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3997 if (ret == 1)
3998 goto peek_stack;
3999 else if (ret < 0)
4000 goto err_free;
4001 if (t + 1 < insn_cnt)
4002 env->explored_states[t + 1] = STATE_LIST_MARK;
4003 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4004 env->explored_states[t] = STATE_LIST_MARK;
4005 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4006 if (ret == 1)
4007 goto peek_stack;
4008 else if (ret < 0)
4009 goto err_free;
4010 }
4011 } else if (opcode == BPF_JA) {
4012 if (BPF_SRC(insns[t].code) != BPF_K) {
4013 ret = -EINVAL;
4014 goto err_free;
4015 }
4016 /* unconditional jump with single edge */
4017 ret = push_insn(t, t + insns[t].off + 1,
4018 FALLTHROUGH, env);
4019 if (ret == 1)
4020 goto peek_stack;
4021 else if (ret < 0)
4022 goto err_free;
4023 /* tell verifier to check for equivalent states
4024 * after every call and jump
4025 */
4026 if (t + 1 < insn_cnt)
4027 env->explored_states[t + 1] = STATE_LIST_MARK;
4028 } else {
4029 /* conditional jump with two edges */
4030 env->explored_states[t] = STATE_LIST_MARK;
4031 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4032 if (ret == 1)
4033 goto peek_stack;
4034 else if (ret < 0)
4035 goto err_free;
4036
4037 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4038 if (ret == 1)
4039 goto peek_stack;
4040 else if (ret < 0)
4041 goto err_free;
4042 }
4043 } else {
4044 /* all other non-branch instructions with single
4045 * fall-through edge
4046 */
4047 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4048 if (ret == 1)
4049 goto peek_stack;
4050 else if (ret < 0)
4051 goto err_free;
4052 }
4053
4054 mark_explored:
4055 insn_state[t] = EXPLORED;
4056 if (cur_stack-- <= 0) {
4057 verbose(env, "pop stack internal bug\n");
4058 ret = -EFAULT;
4059 goto err_free;
4060 }
4061 goto peek_stack;
4062
4063 check_state:
4064 for (i = 0; i < insn_cnt; i++) {
4065 if (insn_state[i] != EXPLORED) {
4066 verbose(env, "unreachable insn %d\n", i);
4067 ret = -EINVAL;
4068 goto err_free;
4069 }
4070 }
4071 ret = 0; /* cfg looks good */
4072
4073 err_free:
4074 kfree(insn_state);
4075 kfree(insn_stack);
4076 return ret;
4077 }
4078
4079 /* check %cur's range satisfies %old's */
4080 static bool range_within(struct bpf_reg_state *old,
4081 struct bpf_reg_state *cur)
4082 {
4083 return old->umin_value <= cur->umin_value &&
4084 old->umax_value >= cur->umax_value &&
4085 old->smin_value <= cur->smin_value &&
4086 old->smax_value >= cur->smax_value;
4087 }
4088
4089 /* Maximum number of register states that can exist at once */
4090 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4091 struct idpair {
4092 u32 old;
4093 u32 cur;
4094 };
4095
4096 /* If in the old state two registers had the same id, then they need to have
4097 * the same id in the new state as well. But that id could be different from
4098 * the old state, so we need to track the mapping from old to new ids.
4099 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4100 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4101 * regs with a different old id could still have new id 9, we don't care about
4102 * that.
4103 * So we look through our idmap to see if this old id has been seen before. If
4104 * so, we require the new id to match; otherwise, we add the id pair to the map.
4105 */
4106 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4107 {
4108 unsigned int i;
4109
4110 for (i = 0; i < ID_MAP_SIZE; i++) {
4111 if (!idmap[i].old) {
4112 /* Reached an empty slot; haven't seen this id before */
4113 idmap[i].old = old_id;
4114 idmap[i].cur = cur_id;
4115 return true;
4116 }
4117 if (idmap[i].old == old_id)
4118 return idmap[i].cur == cur_id;
4119 }
4120 /* We ran out of idmap slots, which should be impossible */
4121 WARN_ON_ONCE(1);
4122 return false;
4123 }
4124
4125 /* Returns true if (rold safe implies rcur safe) */
4126 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4127 struct idpair *idmap)
4128 {
4129 bool equal;
4130
4131 if (!(rold->live & REG_LIVE_READ))
4132 /* explored state didn't use this */
4133 return true;
4134
4135 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
4136
4137 if (rold->type == PTR_TO_STACK)
4138 /* two stack pointers are equal only if they're pointing to
4139 * the same stack frame, since fp-8 in foo != fp-8 in bar
4140 */
4141 return equal && rold->frameno == rcur->frameno;
4142
4143 if (equal)
4144 return true;
4145
4146 if (rold->type == NOT_INIT)
4147 /* explored state can't have used this */
4148 return true;
4149 if (rcur->type == NOT_INIT)
4150 return false;
4151 switch (rold->type) {
4152 case SCALAR_VALUE:
4153 if (rcur->type == SCALAR_VALUE) {
4154 /* new val must satisfy old val knowledge */
4155 return range_within(rold, rcur) &&
4156 tnum_in(rold->var_off, rcur->var_off);
4157 } else {
4158 /* We're trying to use a pointer in place of a scalar.
4159 * Even if the scalar was unbounded, this could lead to
4160 * pointer leaks because scalars are allowed to leak
4161 * while pointers are not. We could make this safe in
4162 * special cases if root is calling us, but it's
4163 * probably not worth the hassle.
4164 */
4165 return false;
4166 }
4167 case PTR_TO_MAP_VALUE:
4168 /* If the new min/max/var_off satisfy the old ones and
4169 * everything else matches, we are OK.
4170 * We don't care about the 'id' value, because nothing
4171 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4172 */
4173 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4174 range_within(rold, rcur) &&
4175 tnum_in(rold->var_off, rcur->var_off);
4176 case PTR_TO_MAP_VALUE_OR_NULL:
4177 /* a PTR_TO_MAP_VALUE could be safe to use as a
4178 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4179 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4180 * checked, doing so could have affected others with the same
4181 * id, and we can't check for that because we lost the id when
4182 * we converted to a PTR_TO_MAP_VALUE.
4183 */
4184 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4185 return false;
4186 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4187 return false;
4188 /* Check our ids match any regs they're supposed to */
4189 return check_ids(rold->id, rcur->id, idmap);
4190 case PTR_TO_PACKET_META:
4191 case PTR_TO_PACKET:
4192 if (rcur->type != rold->type)
4193 return false;
4194 /* We must have at least as much range as the old ptr
4195 * did, so that any accesses which were safe before are
4196 * still safe. This is true even if old range < old off,
4197 * since someone could have accessed through (ptr - k), or
4198 * even done ptr -= k in a register, to get a safe access.
4199 */
4200 if (rold->range > rcur->range)
4201 return false;
4202 /* If the offsets don't match, we can't trust our alignment;
4203 * nor can we be sure that we won't fall out of range.
4204 */
4205 if (rold->off != rcur->off)
4206 return false;
4207 /* id relations must be preserved */
4208 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4209 return false;
4210 /* new val must satisfy old val knowledge */
4211 return range_within(rold, rcur) &&
4212 tnum_in(rold->var_off, rcur->var_off);
4213 case PTR_TO_CTX:
4214 case CONST_PTR_TO_MAP:
4215 case PTR_TO_PACKET_END:
4216 /* Only valid matches are exact, which memcmp() above
4217 * would have accepted
4218 */
4219 default:
4220 /* Don't know what's going on, just say it's not safe */
4221 return false;
4222 }
4223
4224 /* Shouldn't get here; if we do, say it's not safe */
4225 WARN_ON_ONCE(1);
4226 return false;
4227 }
4228
4229 static bool stacksafe(struct bpf_func_state *old,
4230 struct bpf_func_state *cur,
4231 struct idpair *idmap)
4232 {
4233 int i, spi;
4234
4235 /* if explored stack has more populated slots than current stack
4236 * such stacks are not equivalent
4237 */
4238 if (old->allocated_stack > cur->allocated_stack)
4239 return false;
4240
4241 /* walk slots of the explored stack and ignore any additional
4242 * slots in the current stack, since explored(safe) state
4243 * didn't use them
4244 */
4245 for (i = 0; i < old->allocated_stack; i++) {
4246 spi = i / BPF_REG_SIZE;
4247
4248 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4249 /* explored state didn't use this */
4250 continue;
4251
4252 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4253 continue;
4254 /* if old state was safe with misc data in the stack
4255 * it will be safe with zero-initialized stack.
4256 * The opposite is not true
4257 */
4258 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4259 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4260 continue;
4261 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4262 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4263 /* Ex: old explored (safe) state has STACK_SPILL in
4264 * this stack slot, but current has has STACK_MISC ->
4265 * this verifier states are not equivalent,
4266 * return false to continue verification of this path
4267 */
4268 return false;
4269 if (i % BPF_REG_SIZE)
4270 continue;
4271 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4272 continue;
4273 if (!regsafe(&old->stack[spi].spilled_ptr,
4274 &cur->stack[spi].spilled_ptr,
4275 idmap))
4276 /* when explored and current stack slot are both storing
4277 * spilled registers, check that stored pointers types
4278 * are the same as well.
4279 * Ex: explored safe path could have stored
4280 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4281 * but current path has stored:
4282 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4283 * such verifier states are not equivalent.
4284 * return false to continue verification of this path
4285 */
4286 return false;
4287 }
4288 return true;
4289 }
4290
4291 /* compare two verifier states
4292 *
4293 * all states stored in state_list are known to be valid, since
4294 * verifier reached 'bpf_exit' instruction through them
4295 *
4296 * this function is called when verifier exploring different branches of
4297 * execution popped from the state stack. If it sees an old state that has
4298 * more strict register state and more strict stack state then this execution
4299 * branch doesn't need to be explored further, since verifier already
4300 * concluded that more strict state leads to valid finish.
4301 *
4302 * Therefore two states are equivalent if register state is more conservative
4303 * and explored stack state is more conservative than the current one.
4304 * Example:
4305 * explored current
4306 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4307 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4308 *
4309 * In other words if current stack state (one being explored) has more
4310 * valid slots than old one that already passed validation, it means
4311 * the verifier can stop exploring and conclude that current state is valid too
4312 *
4313 * Similarly with registers. If explored state has register type as invalid
4314 * whereas register type in current state is meaningful, it means that
4315 * the current state will reach 'bpf_exit' instruction safely
4316 */
4317 static bool func_states_equal(struct bpf_func_state *old,
4318 struct bpf_func_state *cur)
4319 {
4320 struct idpair *idmap;
4321 bool ret = false;
4322 int i;
4323
4324 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4325 /* If we failed to allocate the idmap, just say it's not safe */
4326 if (!idmap)
4327 return false;
4328
4329 for (i = 0; i < MAX_BPF_REG; i++) {
4330 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4331 goto out_free;
4332 }
4333
4334 if (!stacksafe(old, cur, idmap))
4335 goto out_free;
4336 ret = true;
4337 out_free:
4338 kfree(idmap);
4339 return ret;
4340 }
4341
4342 static bool states_equal(struct bpf_verifier_env *env,
4343 struct bpf_verifier_state *old,
4344 struct bpf_verifier_state *cur)
4345 {
4346 int i;
4347
4348 if (old->curframe != cur->curframe)
4349 return false;
4350
4351 /* for states to be equal callsites have to be the same
4352 * and all frame states need to be equivalent
4353 */
4354 for (i = 0; i <= old->curframe; i++) {
4355 if (old->frame[i]->callsite != cur->frame[i]->callsite)
4356 return false;
4357 if (!func_states_equal(old->frame[i], cur->frame[i]))
4358 return false;
4359 }
4360 return true;
4361 }
4362
4363 /* A write screens off any subsequent reads; but write marks come from the
4364 * straight-line code between a state and its parent. When we arrive at an
4365 * equivalent state (jump target or such) we didn't arrive by the straight-line
4366 * code, so read marks in the state must propagate to the parent regardless
4367 * of the state's write marks. That's what 'parent == state->parent' comparison
4368 * in mark_reg_read() and mark_stack_slot_read() is for.
4369 */
4370 static int propagate_liveness(struct bpf_verifier_env *env,
4371 const struct bpf_verifier_state *vstate,
4372 struct bpf_verifier_state *vparent)
4373 {
4374 int i, frame, err = 0;
4375 struct bpf_func_state *state, *parent;
4376
4377 if (vparent->curframe != vstate->curframe) {
4378 WARN(1, "propagate_live: parent frame %d current frame %d\n",
4379 vparent->curframe, vstate->curframe);
4380 return -EFAULT;
4381 }
4382 /* Propagate read liveness of registers... */
4383 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4384 /* We don't need to worry about FP liveness because it's read-only */
4385 for (i = 0; i < BPF_REG_FP; i++) {
4386 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4387 continue;
4388 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4389 err = mark_reg_read(env, vstate, vparent, i);
4390 if (err)
4391 return err;
4392 }
4393 }
4394
4395 /* ... and stack slots */
4396 for (frame = 0; frame <= vstate->curframe; frame++) {
4397 state = vstate->frame[frame];
4398 parent = vparent->frame[frame];
4399 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4400 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4401 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4402 continue;
4403 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4404 mark_stack_slot_read(env, vstate, vparent, i, frame);
4405 }
4406 }
4407 return err;
4408 }
4409
4410 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4411 {
4412 struct bpf_verifier_state_list *new_sl;
4413 struct bpf_verifier_state_list *sl;
4414 struct bpf_verifier_state *cur = env->cur_state;
4415 int i, j, err;
4416
4417 sl = env->explored_states[insn_idx];
4418 if (!sl)
4419 /* this 'insn_idx' instruction wasn't marked, so we will not
4420 * be doing state search here
4421 */
4422 return 0;
4423
4424 while (sl != STATE_LIST_MARK) {
4425 if (states_equal(env, &sl->state, cur)) {
4426 /* reached equivalent register/stack state,
4427 * prune the search.
4428 * Registers read by the continuation are read by us.
4429 * If we have any write marks in env->cur_state, they
4430 * will prevent corresponding reads in the continuation
4431 * from reaching our parent (an explored_state). Our
4432 * own state will get the read marks recorded, but
4433 * they'll be immediately forgotten as we're pruning
4434 * this state and will pop a new one.
4435 */
4436 err = propagate_liveness(env, &sl->state, cur);
4437 if (err)
4438 return err;
4439 return 1;
4440 }
4441 sl = sl->next;
4442 }
4443
4444 /* there were no equivalent states, remember current one.
4445 * technically the current state is not proven to be safe yet,
4446 * but it will either reach outer most bpf_exit (which means it's safe)
4447 * or it will be rejected. Since there are no loops, we won't be
4448 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4449 * again on the way to bpf_exit
4450 */
4451 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4452 if (!new_sl)
4453 return -ENOMEM;
4454
4455 /* add new state to the head of linked list */
4456 err = copy_verifier_state(&new_sl->state, cur);
4457 if (err) {
4458 free_verifier_state(&new_sl->state, false);
4459 kfree(new_sl);
4460 return err;
4461 }
4462 new_sl->next = env->explored_states[insn_idx];
4463 env->explored_states[insn_idx] = new_sl;
4464 /* connect new state to parentage chain */
4465 cur->parent = &new_sl->state;
4466 /* clear write marks in current state: the writes we did are not writes
4467 * our child did, so they don't screen off its reads from us.
4468 * (There are no read marks in current state, because reads always mark
4469 * their parent and current state never has children yet. Only
4470 * explored_states can get read marks.)
4471 */
4472 for (i = 0; i < BPF_REG_FP; i++)
4473 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4474
4475 /* all stack frames are accessible from callee, clear them all */
4476 for (j = 0; j <= cur->curframe; j++) {
4477 struct bpf_func_state *frame = cur->frame[j];
4478
4479 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
4480 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4481 }
4482 return 0;
4483 }
4484
4485 static int do_check(struct bpf_verifier_env *env)
4486 {
4487 struct bpf_verifier_state *state;
4488 struct bpf_insn *insns = env->prog->insnsi;
4489 struct bpf_reg_state *regs;
4490 int insn_cnt = env->prog->len, i;
4491 int insn_idx, prev_insn_idx = 0;
4492 int insn_processed = 0;
4493 bool do_print_state = false;
4494
4495 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4496 if (!state)
4497 return -ENOMEM;
4498 state->curframe = 0;
4499 state->parent = NULL;
4500 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
4501 if (!state->frame[0]) {
4502 kfree(state);
4503 return -ENOMEM;
4504 }
4505 env->cur_state = state;
4506 init_func_state(env, state->frame[0],
4507 BPF_MAIN_FUNC /* callsite */,
4508 0 /* frameno */,
4509 0 /* subprogno, zero == main subprog */);
4510 insn_idx = 0;
4511 for (;;) {
4512 struct bpf_insn *insn;
4513 u8 class;
4514 int err;
4515
4516 if (insn_idx >= insn_cnt) {
4517 verbose(env, "invalid insn idx %d insn_cnt %d\n",
4518 insn_idx, insn_cnt);
4519 return -EFAULT;
4520 }
4521
4522 insn = &insns[insn_idx];
4523 class = BPF_CLASS(insn->code);
4524
4525 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4526 verbose(env,
4527 "BPF program is too large. Processed %d insn\n",
4528 insn_processed);
4529 return -E2BIG;
4530 }
4531
4532 err = is_state_visited(env, insn_idx);
4533 if (err < 0)
4534 return err;
4535 if (err == 1) {
4536 /* found equivalent state, can prune the search */
4537 if (env->log.level) {
4538 if (do_print_state)
4539 verbose(env, "\nfrom %d to %d: safe\n",
4540 prev_insn_idx, insn_idx);
4541 else
4542 verbose(env, "%d: safe\n", insn_idx);
4543 }
4544 goto process_bpf_exit;
4545 }
4546
4547 if (need_resched())
4548 cond_resched();
4549
4550 if (env->log.level > 1 || (env->log.level && do_print_state)) {
4551 if (env->log.level > 1)
4552 verbose(env, "%d:", insn_idx);
4553 else
4554 verbose(env, "\nfrom %d to %d:",
4555 prev_insn_idx, insn_idx);
4556 print_verifier_state(env, state->frame[state->curframe]);
4557 do_print_state = false;
4558 }
4559
4560 if (env->log.level) {
4561 const struct bpf_insn_cbs cbs = {
4562 .cb_print = verbose,
4563 };
4564
4565 verbose(env, "%d: ", insn_idx);
4566 print_bpf_insn(&cbs, env, insn, env->allow_ptr_leaks);
4567 }
4568
4569 if (bpf_prog_is_dev_bound(env->prog->aux)) {
4570 err = bpf_prog_offload_verify_insn(env, insn_idx,
4571 prev_insn_idx);
4572 if (err)
4573 return err;
4574 }
4575
4576 regs = cur_regs(env);
4577 env->insn_aux_data[insn_idx].seen = true;
4578 if (class == BPF_ALU || class == BPF_ALU64) {
4579 err = check_alu_op(env, insn);
4580 if (err)
4581 return err;
4582
4583 } else if (class == BPF_LDX) {
4584 enum bpf_reg_type *prev_src_type, src_reg_type;
4585
4586 /* check for reserved fields is already done */
4587
4588 /* check src operand */
4589 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4590 if (err)
4591 return err;
4592
4593 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4594 if (err)
4595 return err;
4596
4597 src_reg_type = regs[insn->src_reg].type;
4598
4599 /* check that memory (src_reg + off) is readable,
4600 * the state of dst_reg will be updated by this func
4601 */
4602 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
4603 BPF_SIZE(insn->code), BPF_READ,
4604 insn->dst_reg);
4605 if (err)
4606 return err;
4607
4608 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
4609
4610 if (*prev_src_type == NOT_INIT) {
4611 /* saw a valid insn
4612 * dst_reg = *(u32 *)(src_reg + off)
4613 * save type to validate intersecting paths
4614 */
4615 *prev_src_type = src_reg_type;
4616
4617 } else if (src_reg_type != *prev_src_type &&
4618 (src_reg_type == PTR_TO_CTX ||
4619 *prev_src_type == PTR_TO_CTX)) {
4620 /* ABuser program is trying to use the same insn
4621 * dst_reg = *(u32*) (src_reg + off)
4622 * with different pointer types:
4623 * src_reg == ctx in one branch and
4624 * src_reg == stack|map in some other branch.
4625 * Reject it.
4626 */
4627 verbose(env, "same insn cannot be used with different pointers\n");
4628 return -EINVAL;
4629 }
4630
4631 } else if (class == BPF_STX) {
4632 enum bpf_reg_type *prev_dst_type, dst_reg_type;
4633
4634 if (BPF_MODE(insn->code) == BPF_XADD) {
4635 err = check_xadd(env, insn_idx, insn);
4636 if (err)
4637 return err;
4638 insn_idx++;
4639 continue;
4640 }
4641
4642 /* check src1 operand */
4643 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4644 if (err)
4645 return err;
4646 /* check src2 operand */
4647 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4648 if (err)
4649 return err;
4650
4651 dst_reg_type = regs[insn->dst_reg].type;
4652
4653 /* check that memory (dst_reg + off) is writeable */
4654 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4655 BPF_SIZE(insn->code), BPF_WRITE,
4656 insn->src_reg);
4657 if (err)
4658 return err;
4659
4660 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
4661
4662 if (*prev_dst_type == NOT_INIT) {
4663 *prev_dst_type = dst_reg_type;
4664 } else if (dst_reg_type != *prev_dst_type &&
4665 (dst_reg_type == PTR_TO_CTX ||
4666 *prev_dst_type == PTR_TO_CTX)) {
4667 verbose(env, "same insn cannot be used with different pointers\n");
4668 return -EINVAL;
4669 }
4670
4671 } else if (class == BPF_ST) {
4672 if (BPF_MODE(insn->code) != BPF_MEM ||
4673 insn->src_reg != BPF_REG_0) {
4674 verbose(env, "BPF_ST uses reserved fields\n");
4675 return -EINVAL;
4676 }
4677 /* check src operand */
4678 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4679 if (err)
4680 return err;
4681
4682 if (is_ctx_reg(env, insn->dst_reg)) {
4683 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
4684 insn->dst_reg);
4685 return -EACCES;
4686 }
4687
4688 /* check that memory (dst_reg + off) is writeable */
4689 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4690 BPF_SIZE(insn->code), BPF_WRITE,
4691 -1);
4692 if (err)
4693 return err;
4694
4695 } else if (class == BPF_JMP) {
4696 u8 opcode = BPF_OP(insn->code);
4697
4698 if (opcode == BPF_CALL) {
4699 if (BPF_SRC(insn->code) != BPF_K ||
4700 insn->off != 0 ||
4701 (insn->src_reg != BPF_REG_0 &&
4702 insn->src_reg != BPF_PSEUDO_CALL) ||
4703 insn->dst_reg != BPF_REG_0) {
4704 verbose(env, "BPF_CALL uses reserved fields\n");
4705 return -EINVAL;
4706 }
4707
4708 if (insn->src_reg == BPF_PSEUDO_CALL)
4709 err = check_func_call(env, insn, &insn_idx);
4710 else
4711 err = check_helper_call(env, insn->imm, insn_idx);
4712 if (err)
4713 return err;
4714
4715 } else if (opcode == BPF_JA) {
4716 if (BPF_SRC(insn->code) != BPF_K ||
4717 insn->imm != 0 ||
4718 insn->src_reg != BPF_REG_0 ||
4719 insn->dst_reg != BPF_REG_0) {
4720 verbose(env, "BPF_JA uses reserved fields\n");
4721 return -EINVAL;
4722 }
4723
4724 insn_idx += insn->off + 1;
4725 continue;
4726
4727 } else if (opcode == BPF_EXIT) {
4728 if (BPF_SRC(insn->code) != BPF_K ||
4729 insn->imm != 0 ||
4730 insn->src_reg != BPF_REG_0 ||
4731 insn->dst_reg != BPF_REG_0) {
4732 verbose(env, "BPF_EXIT uses reserved fields\n");
4733 return -EINVAL;
4734 }
4735
4736 if (state->curframe) {
4737 /* exit from nested function */
4738 prev_insn_idx = insn_idx;
4739 err = prepare_func_exit(env, &insn_idx);
4740 if (err)
4741 return err;
4742 do_print_state = true;
4743 continue;
4744 }
4745
4746 /* eBPF calling convetion is such that R0 is used
4747 * to return the value from eBPF program.
4748 * Make sure that it's readable at this time
4749 * of bpf_exit, which means that program wrote
4750 * something into it earlier
4751 */
4752 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4753 if (err)
4754 return err;
4755
4756 if (is_pointer_value(env, BPF_REG_0)) {
4757 verbose(env, "R0 leaks addr as return value\n");
4758 return -EACCES;
4759 }
4760
4761 err = check_return_code(env);
4762 if (err)
4763 return err;
4764 process_bpf_exit:
4765 err = pop_stack(env, &prev_insn_idx, &insn_idx);
4766 if (err < 0) {
4767 if (err != -ENOENT)
4768 return err;
4769 break;
4770 } else {
4771 do_print_state = true;
4772 continue;
4773 }
4774 } else {
4775 err = check_cond_jmp_op(env, insn, &insn_idx);
4776 if (err)
4777 return err;
4778 }
4779 } else if (class == BPF_LD) {
4780 u8 mode = BPF_MODE(insn->code);
4781
4782 if (mode == BPF_ABS || mode == BPF_IND) {
4783 err = check_ld_abs(env, insn);
4784 if (err)
4785 return err;
4786
4787 } else if (mode == BPF_IMM) {
4788 err = check_ld_imm(env, insn);
4789 if (err)
4790 return err;
4791
4792 insn_idx++;
4793 env->insn_aux_data[insn_idx].seen = true;
4794 } else {
4795 verbose(env, "invalid BPF_LD mode\n");
4796 return -EINVAL;
4797 }
4798 } else {
4799 verbose(env, "unknown insn class %d\n", class);
4800 return -EINVAL;
4801 }
4802
4803 insn_idx++;
4804 }
4805
4806 verbose(env, "processed %d insns, stack depth ", insn_processed);
4807 for (i = 0; i < env->subprog_cnt + 1; i++) {
4808 u32 depth = env->subprog_stack_depth[i];
4809
4810 verbose(env, "%d", depth);
4811 if (i + 1 < env->subprog_cnt + 1)
4812 verbose(env, "+");
4813 }
4814 verbose(env, "\n");
4815 env->prog->aux->stack_depth = env->subprog_stack_depth[0];
4816 return 0;
4817 }
4818
4819 static int check_map_prealloc(struct bpf_map *map)
4820 {
4821 return (map->map_type != BPF_MAP_TYPE_HASH &&
4822 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4823 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4824 !(map->map_flags & BPF_F_NO_PREALLOC);
4825 }
4826
4827 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
4828 struct bpf_map *map,
4829 struct bpf_prog *prog)
4830
4831 {
4832 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4833 * preallocated hash maps, since doing memory allocation
4834 * in overflow_handler can crash depending on where nmi got
4835 * triggered.
4836 */
4837 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4838 if (!check_map_prealloc(map)) {
4839 verbose(env, "perf_event programs can only use preallocated hash map\n");
4840 return -EINVAL;
4841 }
4842 if (map->inner_map_meta &&
4843 !check_map_prealloc(map->inner_map_meta)) {
4844 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
4845 return -EINVAL;
4846 }
4847 }
4848
4849 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
4850 !bpf_offload_dev_match(prog, map)) {
4851 verbose(env, "offload device mismatch between prog and map\n");
4852 return -EINVAL;
4853 }
4854
4855 return 0;
4856 }
4857
4858 /* look for pseudo eBPF instructions that access map FDs and
4859 * replace them with actual map pointers
4860 */
4861 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4862 {
4863 struct bpf_insn *insn = env->prog->insnsi;
4864 int insn_cnt = env->prog->len;
4865 int i, j, err;
4866
4867 err = bpf_prog_calc_tag(env->prog);
4868 if (err)
4869 return err;
4870
4871 for (i = 0; i < insn_cnt; i++, insn++) {
4872 if (BPF_CLASS(insn->code) == BPF_LDX &&
4873 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4874 verbose(env, "BPF_LDX uses reserved fields\n");
4875 return -EINVAL;
4876 }
4877
4878 if (BPF_CLASS(insn->code) == BPF_STX &&
4879 ((BPF_MODE(insn->code) != BPF_MEM &&
4880 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4881 verbose(env, "BPF_STX uses reserved fields\n");
4882 return -EINVAL;
4883 }
4884
4885 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4886 struct bpf_map *map;
4887 struct fd f;
4888
4889 if (i == insn_cnt - 1 || insn[1].code != 0 ||
4890 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4891 insn[1].off != 0) {
4892 verbose(env, "invalid bpf_ld_imm64 insn\n");
4893 return -EINVAL;
4894 }
4895
4896 if (insn->src_reg == 0)
4897 /* valid generic load 64-bit imm */
4898 goto next_insn;
4899
4900 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4901 verbose(env,
4902 "unrecognized bpf_ld_imm64 insn\n");
4903 return -EINVAL;
4904 }
4905
4906 f = fdget(insn->imm);
4907 map = __bpf_map_get(f);
4908 if (IS_ERR(map)) {
4909 verbose(env, "fd %d is not pointing to valid bpf_map\n",
4910 insn->imm);
4911 return PTR_ERR(map);
4912 }
4913
4914 err = check_map_prog_compatibility(env, map, env->prog);
4915 if (err) {
4916 fdput(f);
4917 return err;
4918 }
4919
4920 /* store map pointer inside BPF_LD_IMM64 instruction */
4921 insn[0].imm = (u32) (unsigned long) map;
4922 insn[1].imm = ((u64) (unsigned long) map) >> 32;
4923
4924 /* check whether we recorded this map already */
4925 for (j = 0; j < env->used_map_cnt; j++)
4926 if (env->used_maps[j] == map) {
4927 fdput(f);
4928 goto next_insn;
4929 }
4930
4931 if (env->used_map_cnt >= MAX_USED_MAPS) {
4932 fdput(f);
4933 return -E2BIG;
4934 }
4935
4936 /* hold the map. If the program is rejected by verifier,
4937 * the map will be released by release_maps() or it
4938 * will be used by the valid program until it's unloaded
4939 * and all maps are released in free_bpf_prog_info()
4940 */
4941 map = bpf_map_inc(map, false);
4942 if (IS_ERR(map)) {
4943 fdput(f);
4944 return PTR_ERR(map);
4945 }
4946 env->used_maps[env->used_map_cnt++] = map;
4947
4948 fdput(f);
4949 next_insn:
4950 insn++;
4951 i++;
4952 }
4953 }
4954
4955 /* now all pseudo BPF_LD_IMM64 instructions load valid
4956 * 'struct bpf_map *' into a register instead of user map_fd.
4957 * These pointers will be used later by verifier to validate map access.
4958 */
4959 return 0;
4960 }
4961
4962 /* drop refcnt of maps used by the rejected program */
4963 static void release_maps(struct bpf_verifier_env *env)
4964 {
4965 int i;
4966
4967 for (i = 0; i < env->used_map_cnt; i++)
4968 bpf_map_put(env->used_maps[i]);
4969 }
4970
4971 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
4972 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
4973 {
4974 struct bpf_insn *insn = env->prog->insnsi;
4975 int insn_cnt = env->prog->len;
4976 int i;
4977
4978 for (i = 0; i < insn_cnt; i++, insn++)
4979 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
4980 insn->src_reg = 0;
4981 }
4982
4983 /* single env->prog->insni[off] instruction was replaced with the range
4984 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
4985 * [0, off) and [off, end) to new locations, so the patched range stays zero
4986 */
4987 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
4988 u32 off, u32 cnt)
4989 {
4990 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
4991 int i;
4992
4993 if (cnt == 1)
4994 return 0;
4995 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
4996 if (!new_data)
4997 return -ENOMEM;
4998 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
4999 memcpy(new_data + off + cnt - 1, old_data + off,
5000 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5001 for (i = off; i < off + cnt - 1; i++)
5002 new_data[i].seen = true;
5003 env->insn_aux_data = new_data;
5004 vfree(old_data);
5005 return 0;
5006 }
5007
5008 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5009 {
5010 int i;
5011
5012 if (len == 1)
5013 return;
5014 for (i = 0; i < env->subprog_cnt; i++) {
5015 if (env->subprog_starts[i] < off)
5016 continue;
5017 env->subprog_starts[i] += len - 1;
5018 }
5019 }
5020
5021 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5022 const struct bpf_insn *patch, u32 len)
5023 {
5024 struct bpf_prog *new_prog;
5025
5026 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5027 if (!new_prog)
5028 return NULL;
5029 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5030 return NULL;
5031 adjust_subprog_starts(env, off, len);
5032 return new_prog;
5033 }
5034
5035 /* The verifier does more data flow analysis than llvm and will not explore
5036 * branches that are dead at run time. Malicious programs can have dead code
5037 * too. Therefore replace all dead at-run-time code with nops.
5038 */
5039 static void sanitize_dead_code(struct bpf_verifier_env *env)
5040 {
5041 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5042 struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
5043 struct bpf_insn *insn = env->prog->insnsi;
5044 const int insn_cnt = env->prog->len;
5045 int i;
5046
5047 for (i = 0; i < insn_cnt; i++) {
5048 if (aux_data[i].seen)
5049 continue;
5050 memcpy(insn + i, &nop, sizeof(nop));
5051 }
5052 }
5053
5054 /* convert load instructions that access fields of 'struct __sk_buff'
5055 * into sequence of instructions that access fields of 'struct sk_buff'
5056 */
5057 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5058 {
5059 const struct bpf_verifier_ops *ops = env->ops;
5060 int i, cnt, size, ctx_field_size, delta = 0;
5061 const int insn_cnt = env->prog->len;
5062 struct bpf_insn insn_buf[16], *insn;
5063 struct bpf_prog *new_prog;
5064 enum bpf_access_type type;
5065 bool is_narrower_load;
5066 u32 target_size;
5067
5068 if (ops->gen_prologue) {
5069 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5070 env->prog);
5071 if (cnt >= ARRAY_SIZE(insn_buf)) {
5072 verbose(env, "bpf verifier is misconfigured\n");
5073 return -EINVAL;
5074 } else if (cnt) {
5075 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5076 if (!new_prog)
5077 return -ENOMEM;
5078
5079 env->prog = new_prog;
5080 delta += cnt - 1;
5081 }
5082 }
5083
5084 if (!ops->convert_ctx_access)
5085 return 0;
5086
5087 insn = env->prog->insnsi + delta;
5088
5089 for (i = 0; i < insn_cnt; i++, insn++) {
5090 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5091 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5092 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5093 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5094 type = BPF_READ;
5095 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5096 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5097 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5098 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5099 type = BPF_WRITE;
5100 else
5101 continue;
5102
5103 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5104 continue;
5105
5106 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5107 size = BPF_LDST_BYTES(insn);
5108
5109 /* If the read access is a narrower load of the field,
5110 * convert to a 4/8-byte load, to minimum program type specific
5111 * convert_ctx_access changes. If conversion is successful,
5112 * we will apply proper mask to the result.
5113 */
5114 is_narrower_load = size < ctx_field_size;
5115 if (is_narrower_load) {
5116 u32 off = insn->off;
5117 u8 size_code;
5118
5119 if (type == BPF_WRITE) {
5120 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5121 return -EINVAL;
5122 }
5123
5124 size_code = BPF_H;
5125 if (ctx_field_size == 4)
5126 size_code = BPF_W;
5127 else if (ctx_field_size == 8)
5128 size_code = BPF_DW;
5129
5130 insn->off = off & ~(ctx_field_size - 1);
5131 insn->code = BPF_LDX | BPF_MEM | size_code;
5132 }
5133
5134 target_size = 0;
5135 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5136 &target_size);
5137 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5138 (ctx_field_size && !target_size)) {
5139 verbose(env, "bpf verifier is misconfigured\n");
5140 return -EINVAL;
5141 }
5142
5143 if (is_narrower_load && size < target_size) {
5144 if (ctx_field_size <= 4)
5145 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5146 (1 << size * 8) - 1);
5147 else
5148 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5149 (1 << size * 8) - 1);
5150 }
5151
5152 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5153 if (!new_prog)
5154 return -ENOMEM;
5155
5156 delta += cnt - 1;
5157
5158 /* keep walking new program and skip insns we just inserted */
5159 env->prog = new_prog;
5160 insn = new_prog->insnsi + i + delta;
5161 }
5162
5163 return 0;
5164 }
5165
5166 static int jit_subprogs(struct bpf_verifier_env *env)
5167 {
5168 struct bpf_prog *prog = env->prog, **func, *tmp;
5169 int i, j, subprog_start, subprog_end = 0, len, subprog;
5170 struct bpf_insn *insn;
5171 void *old_bpf_func;
5172 int err = -ENOMEM;
5173
5174 if (env->subprog_cnt == 0)
5175 return 0;
5176
5177 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5178 if (insn->code != (BPF_JMP | BPF_CALL) ||
5179 insn->src_reg != BPF_PSEUDO_CALL)
5180 continue;
5181 subprog = find_subprog(env, i + insn->imm + 1);
5182 if (subprog < 0) {
5183 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5184 i + insn->imm + 1);
5185 return -EFAULT;
5186 }
5187 /* temporarily remember subprog id inside insn instead of
5188 * aux_data, since next loop will split up all insns into funcs
5189 */
5190 insn->off = subprog + 1;
5191 /* remember original imm in case JIT fails and fallback
5192 * to interpreter will be needed
5193 */
5194 env->insn_aux_data[i].call_imm = insn->imm;
5195 /* point imm to __bpf_call_base+1 from JITs point of view */
5196 insn->imm = 1;
5197 }
5198
5199 func = kzalloc(sizeof(prog) * (env->subprog_cnt + 1), GFP_KERNEL);
5200 if (!func)
5201 return -ENOMEM;
5202
5203 for (i = 0; i <= env->subprog_cnt; i++) {
5204 subprog_start = subprog_end;
5205 if (env->subprog_cnt == i)
5206 subprog_end = prog->len;
5207 else
5208 subprog_end = env->subprog_starts[i];
5209
5210 len = subprog_end - subprog_start;
5211 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5212 if (!func[i])
5213 goto out_free;
5214 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5215 len * sizeof(struct bpf_insn));
5216 func[i]->type = prog->type;
5217 func[i]->len = len;
5218 if (bpf_prog_calc_tag(func[i]))
5219 goto out_free;
5220 func[i]->is_func = 1;
5221 /* Use bpf_prog_F_tag to indicate functions in stack traces.
5222 * Long term would need debug info to populate names
5223 */
5224 func[i]->aux->name[0] = 'F';
5225 func[i]->aux->stack_depth = env->subprog_stack_depth[i];
5226 func[i]->jit_requested = 1;
5227 func[i] = bpf_int_jit_compile(func[i]);
5228 if (!func[i]->jited) {
5229 err = -ENOTSUPP;
5230 goto out_free;
5231 }
5232 cond_resched();
5233 }
5234 /* at this point all bpf functions were successfully JITed
5235 * now populate all bpf_calls with correct addresses and
5236 * run last pass of JIT
5237 */
5238 for (i = 0; i <= env->subprog_cnt; i++) {
5239 insn = func[i]->insnsi;
5240 for (j = 0; j < func[i]->len; j++, insn++) {
5241 if (insn->code != (BPF_JMP | BPF_CALL) ||
5242 insn->src_reg != BPF_PSEUDO_CALL)
5243 continue;
5244 subprog = insn->off;
5245 insn->off = 0;
5246 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5247 func[subprog]->bpf_func -
5248 __bpf_call_base;
5249 }
5250 }
5251 for (i = 0; i <= env->subprog_cnt; i++) {
5252 old_bpf_func = func[i]->bpf_func;
5253 tmp = bpf_int_jit_compile(func[i]);
5254 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5255 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5256 err = -EFAULT;
5257 goto out_free;
5258 }
5259 cond_resched();
5260 }
5261
5262 /* finally lock prog and jit images for all functions and
5263 * populate kallsysm
5264 */
5265 for (i = 0; i <= env->subprog_cnt; i++) {
5266 bpf_prog_lock_ro(func[i]);
5267 bpf_prog_kallsyms_add(func[i]);
5268 }
5269
5270 /* Last step: make now unused interpreter insns from main
5271 * prog consistent for later dump requests, so they can
5272 * later look the same as if they were interpreted only.
5273 */
5274 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5275 unsigned long addr;
5276
5277 if (insn->code != (BPF_JMP | BPF_CALL) ||
5278 insn->src_reg != BPF_PSEUDO_CALL)
5279 continue;
5280 insn->off = env->insn_aux_data[i].call_imm;
5281 subprog = find_subprog(env, i + insn->off + 1);
5282 addr = (unsigned long)func[subprog + 1]->bpf_func;
5283 addr &= PAGE_MASK;
5284 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5285 addr - __bpf_call_base;
5286 }
5287
5288 prog->jited = 1;
5289 prog->bpf_func = func[0]->bpf_func;
5290 prog->aux->func = func;
5291 prog->aux->func_cnt = env->subprog_cnt + 1;
5292 return 0;
5293 out_free:
5294 for (i = 0; i <= env->subprog_cnt; i++)
5295 if (func[i])
5296 bpf_jit_free(func[i]);
5297 kfree(func);
5298 /* cleanup main prog to be interpreted */
5299 prog->jit_requested = 0;
5300 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5301 if (insn->code != (BPF_JMP | BPF_CALL) ||
5302 insn->src_reg != BPF_PSEUDO_CALL)
5303 continue;
5304 insn->off = 0;
5305 insn->imm = env->insn_aux_data[i].call_imm;
5306 }
5307 return err;
5308 }
5309
5310 static int fixup_call_args(struct bpf_verifier_env *env)
5311 {
5312 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5313 struct bpf_prog *prog = env->prog;
5314 struct bpf_insn *insn = prog->insnsi;
5315 int i, depth;
5316 #endif
5317 int err;
5318
5319 err = 0;
5320 if (env->prog->jit_requested) {
5321 err = jit_subprogs(env);
5322 if (err == 0)
5323 return 0;
5324 }
5325 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5326 for (i = 0; i < prog->len; i++, insn++) {
5327 if (insn->code != (BPF_JMP | BPF_CALL) ||
5328 insn->src_reg != BPF_PSEUDO_CALL)
5329 continue;
5330 depth = get_callee_stack_depth(env, insn, i);
5331 if (depth < 0)
5332 return depth;
5333 bpf_patch_call_args(insn, depth);
5334 }
5335 err = 0;
5336 #endif
5337 return err;
5338 }
5339
5340 /* fixup insn->imm field of bpf_call instructions
5341 * and inline eligible helpers as explicit sequence of BPF instructions
5342 *
5343 * this function is called after eBPF program passed verification
5344 */
5345 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5346 {
5347 struct bpf_prog *prog = env->prog;
5348 struct bpf_insn *insn = prog->insnsi;
5349 const struct bpf_func_proto *fn;
5350 const int insn_cnt = prog->len;
5351 struct bpf_insn insn_buf[16];
5352 struct bpf_prog *new_prog;
5353 struct bpf_map *map_ptr;
5354 int i, cnt, delta = 0;
5355
5356 for (i = 0; i < insn_cnt; i++, insn++) {
5357 if (insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5358 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5359 /* due to JIT bugs clear upper 32-bits of src register
5360 * before div/mod operation
5361 */
5362 insn_buf[0] = BPF_MOV32_REG(insn->src_reg, insn->src_reg);
5363 insn_buf[1] = *insn;
5364 cnt = 2;
5365 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5366 if (!new_prog)
5367 return -ENOMEM;
5368
5369 delta += cnt - 1;
5370 env->prog = prog = new_prog;
5371 insn = new_prog->insnsi + i + delta;
5372 continue;
5373 }
5374
5375 if (insn->code != (BPF_JMP | BPF_CALL))
5376 continue;
5377 if (insn->src_reg == BPF_PSEUDO_CALL)
5378 continue;
5379
5380 if (insn->imm == BPF_FUNC_get_route_realm)
5381 prog->dst_needed = 1;
5382 if (insn->imm == BPF_FUNC_get_prandom_u32)
5383 bpf_user_rnd_init_once();
5384 if (insn->imm == BPF_FUNC_override_return)
5385 prog->kprobe_override = 1;
5386 if (insn->imm == BPF_FUNC_tail_call) {
5387 /* If we tail call into other programs, we
5388 * cannot make any assumptions since they can
5389 * be replaced dynamically during runtime in
5390 * the program array.
5391 */
5392 prog->cb_access = 1;
5393 env->prog->aux->stack_depth = MAX_BPF_STACK;
5394
5395 /* mark bpf_tail_call as different opcode to avoid
5396 * conditional branch in the interpeter for every normal
5397 * call and to prevent accidental JITing by JIT compiler
5398 * that doesn't support bpf_tail_call yet
5399 */
5400 insn->imm = 0;
5401 insn->code = BPF_JMP | BPF_TAIL_CALL;
5402
5403 /* instead of changing every JIT dealing with tail_call
5404 * emit two extra insns:
5405 * if (index >= max_entries) goto out;
5406 * index &= array->index_mask;
5407 * to avoid out-of-bounds cpu speculation
5408 */
5409 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5410 if (map_ptr == BPF_MAP_PTR_POISON) {
5411 verbose(env, "tail_call abusing map_ptr\n");
5412 return -EINVAL;
5413 }
5414 if (!map_ptr->unpriv_array)
5415 continue;
5416 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
5417 map_ptr->max_entries, 2);
5418 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
5419 container_of(map_ptr,
5420 struct bpf_array,
5421 map)->index_mask);
5422 insn_buf[2] = *insn;
5423 cnt = 3;
5424 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5425 if (!new_prog)
5426 return -ENOMEM;
5427
5428 delta += cnt - 1;
5429 env->prog = prog = new_prog;
5430 insn = new_prog->insnsi + i + delta;
5431 continue;
5432 }
5433
5434 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
5435 * handlers are currently limited to 64 bit only.
5436 */
5437 if (prog->jit_requested && BITS_PER_LONG == 64 &&
5438 insn->imm == BPF_FUNC_map_lookup_elem) {
5439 map_ptr = env->insn_aux_data[i + delta].map_ptr;
5440 if (map_ptr == BPF_MAP_PTR_POISON ||
5441 !map_ptr->ops->map_gen_lookup)
5442 goto patch_call_imm;
5443
5444 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5445 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5446 verbose(env, "bpf verifier is misconfigured\n");
5447 return -EINVAL;
5448 }
5449
5450 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5451 cnt);
5452 if (!new_prog)
5453 return -ENOMEM;
5454
5455 delta += cnt - 1;
5456
5457 /* keep walking new program and skip insns we just inserted */
5458 env->prog = prog = new_prog;
5459 insn = new_prog->insnsi + i + delta;
5460 continue;
5461 }
5462
5463 if (insn->imm == BPF_FUNC_redirect_map) {
5464 /* Note, we cannot use prog directly as imm as subsequent
5465 * rewrites would still change the prog pointer. The only
5466 * stable address we can use is aux, which also works with
5467 * prog clones during blinding.
5468 */
5469 u64 addr = (unsigned long)prog->aux;
5470 struct bpf_insn r4_ld[] = {
5471 BPF_LD_IMM64(BPF_REG_4, addr),
5472 *insn,
5473 };
5474 cnt = ARRAY_SIZE(r4_ld);
5475
5476 new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5477 if (!new_prog)
5478 return -ENOMEM;
5479
5480 delta += cnt - 1;
5481 env->prog = prog = new_prog;
5482 insn = new_prog->insnsi + i + delta;
5483 }
5484 patch_call_imm:
5485 fn = env->ops->get_func_proto(insn->imm);
5486 /* all functions that have prototype and verifier allowed
5487 * programs to call them, must be real in-kernel functions
5488 */
5489 if (!fn->func) {
5490 verbose(env,
5491 "kernel subsystem misconfigured func %s#%d\n",
5492 func_id_name(insn->imm), insn->imm);
5493 return -EFAULT;
5494 }
5495 insn->imm = fn->func - __bpf_call_base;
5496 }
5497
5498 return 0;
5499 }
5500
5501 static void free_states(struct bpf_verifier_env *env)
5502 {
5503 struct bpf_verifier_state_list *sl, *sln;
5504 int i;
5505
5506 if (!env->explored_states)
5507 return;
5508
5509 for (i = 0; i < env->prog->len; i++) {
5510 sl = env->explored_states[i];
5511
5512 if (sl)
5513 while (sl != STATE_LIST_MARK) {
5514 sln = sl->next;
5515 free_verifier_state(&sl->state, false);
5516 kfree(sl);
5517 sl = sln;
5518 }
5519 }
5520
5521 kfree(env->explored_states);
5522 }
5523
5524 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5525 {
5526 struct bpf_verifier_env *env;
5527 struct bpf_verifer_log *log;
5528 int ret = -EINVAL;
5529
5530 /* no program is valid */
5531 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
5532 return -EINVAL;
5533
5534 /* 'struct bpf_verifier_env' can be global, but since it's not small,
5535 * allocate/free it every time bpf_check() is called
5536 */
5537 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5538 if (!env)
5539 return -ENOMEM;
5540 log = &env->log;
5541
5542 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5543 (*prog)->len);
5544 ret = -ENOMEM;
5545 if (!env->insn_aux_data)
5546 goto err_free_env;
5547 env->prog = *prog;
5548 env->ops = bpf_verifier_ops[env->prog->type];
5549
5550 /* grab the mutex to protect few globals used by verifier */
5551 mutex_lock(&bpf_verifier_lock);
5552
5553 if (attr->log_level || attr->log_buf || attr->log_size) {
5554 /* user requested verbose verifier output
5555 * and supplied buffer to store the verification trace
5556 */
5557 log->level = attr->log_level;
5558 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
5559 log->len_total = attr->log_size;
5560
5561 ret = -EINVAL;
5562 /* log attributes have to be sane */
5563 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
5564 !log->level || !log->ubuf)
5565 goto err_unlock;
5566 }
5567
5568 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5569 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5570 env->strict_alignment = true;
5571
5572 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5573 ret = bpf_prog_offload_verifier_prep(env);
5574 if (ret)
5575 goto err_unlock;
5576 }
5577
5578 ret = replace_map_fd_with_map_ptr(env);
5579 if (ret < 0)
5580 goto skip_full_check;
5581
5582 env->explored_states = kcalloc(env->prog->len,
5583 sizeof(struct bpf_verifier_state_list *),
5584 GFP_USER);
5585 ret = -ENOMEM;
5586 if (!env->explored_states)
5587 goto skip_full_check;
5588
5589 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5590
5591 ret = check_cfg(env);
5592 if (ret < 0)
5593 goto skip_full_check;
5594
5595 ret = do_check(env);
5596 if (env->cur_state) {
5597 free_verifier_state(env->cur_state, true);
5598 env->cur_state = NULL;
5599 }
5600
5601 skip_full_check:
5602 while (!pop_stack(env, NULL, NULL));
5603 free_states(env);
5604
5605 if (ret == 0)
5606 sanitize_dead_code(env);
5607
5608 if (ret == 0)
5609 ret = check_max_stack_depth(env);
5610
5611 if (ret == 0)
5612 /* program is valid, convert *(u32*)(ctx + off) accesses */
5613 ret = convert_ctx_accesses(env);
5614
5615 if (ret == 0)
5616 ret = fixup_bpf_calls(env);
5617
5618 if (ret == 0)
5619 ret = fixup_call_args(env);
5620
5621 if (log->level && bpf_verifier_log_full(log))
5622 ret = -ENOSPC;
5623 if (log->level && !log->ubuf) {
5624 ret = -EFAULT;
5625 goto err_release_maps;
5626 }
5627
5628 if (ret == 0 && env->used_map_cnt) {
5629 /* if program passed verifier, update used_maps in bpf_prog_info */
5630 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5631 sizeof(env->used_maps[0]),
5632 GFP_KERNEL);
5633
5634 if (!env->prog->aux->used_maps) {
5635 ret = -ENOMEM;
5636 goto err_release_maps;
5637 }
5638
5639 memcpy(env->prog->aux->used_maps, env->used_maps,
5640 sizeof(env->used_maps[0]) * env->used_map_cnt);
5641 env->prog->aux->used_map_cnt = env->used_map_cnt;
5642
5643 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5644 * bpf_ld_imm64 instructions
5645 */
5646 convert_pseudo_ld_imm64(env);
5647 }
5648
5649 err_release_maps:
5650 if (!env->prog->aux->used_maps)
5651 /* if we didn't copy map pointers into bpf_prog_info, release
5652 * them now. Otherwise free_bpf_prog_info() will release them.
5653 */
5654 release_maps(env);
5655 *prog = env->prog;
5656 err_unlock:
5657 mutex_unlock(&bpf_verifier_lock);
5658 vfree(env->insn_aux_data);
5659 err_free_env:
5660 kfree(env);
5661 return ret;
5662 }