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