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