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