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