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