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