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