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