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