]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blame - kernel/bpf/verifier.c
macvlan: propagate the mac address change status for lowerdev
[mirror_ubuntu-artful-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 *
64 * Most of the time the registers have UNKNOWN_VALUE type, which
65 * means the register has some value, but it's not a valid pointer.
66 * (like pointer plus pointer becomes UNKNOWN_VALUE type)
67 *
68 * When verifier sees load or store instructions the type of base register
69 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
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
3c2ce60b 143#define BPF_COMPLEXITY_LIMIT_INSNS 98304
07016151
DB
144#define BPF_COMPLEXITY_LIMIT_STACK 1024
145
fad73a1a
MKL
146#define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
147
33ff9823
DB
148struct bpf_call_arg_meta {
149 struct bpf_map *map_ptr;
435faee1 150 bool raw_mode;
36bbef52 151 bool pkt_access;
435faee1
DB
152 int regno;
153 int access_size;
33ff9823
DB
154};
155
cbd35700
AS
156/* verbose verifier prints what it's seeing
157 * bpf_check() is called under lock, so no race to access these global vars
158 */
159static u32 log_level, log_size, log_len;
160static char *log_buf;
161
162static DEFINE_MUTEX(bpf_verifier_lock);
163
164/* log_level controls verbosity level of eBPF verifier.
165 * verbose() is used to dump the verification trace to the log, so the user
166 * can figure out what's wrong with the program
167 */
1d056d9c 168static __printf(1, 2) void verbose(const char *fmt, ...)
cbd35700
AS
169{
170 va_list args;
171
172 if (log_level == 0 || log_len >= log_size - 1)
173 return;
174
175 va_start(args, fmt);
176 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
177 va_end(args);
178}
179
17a52670
AS
180/* string representation of 'enum bpf_reg_type' */
181static const char * const reg_type_str[] = {
182 [NOT_INIT] = "?",
183 [UNKNOWN_VALUE] = "inv",
184 [PTR_TO_CTX] = "ctx",
185 [CONST_PTR_TO_MAP] = "map_ptr",
186 [PTR_TO_MAP_VALUE] = "map_value",
187 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
48461135 188 [PTR_TO_MAP_VALUE_ADJ] = "map_value_adj",
17a52670
AS
189 [FRAME_PTR] = "fp",
190 [PTR_TO_STACK] = "fp",
191 [CONST_IMM] = "imm",
969bf05e
AS
192 [PTR_TO_PACKET] = "pkt",
193 [PTR_TO_PACKET_END] = "pkt_end",
17a52670
AS
194};
195
ebb676da
TG
196#define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
197static const char * const func_id_str[] = {
198 __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
199};
200#undef __BPF_FUNC_STR_FN
201
202static const char *func_id_name(int id)
203{
204 BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
205
206 if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
207 return func_id_str[id];
208 else
209 return "unknown";
210}
211
58e2af8b 212static void print_verifier_state(struct bpf_verifier_state *state)
17a52670 213{
58e2af8b 214 struct bpf_reg_state *reg;
17a52670
AS
215 enum bpf_reg_type t;
216 int i;
217
218 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
219 reg = &state->regs[i];
220 t = reg->type;
17a52670
AS
221 if (t == NOT_INIT)
222 continue;
223 verbose(" R%d=%s", i, reg_type_str[t]);
224 if (t == CONST_IMM || t == PTR_TO_STACK)
969bf05e
AS
225 verbose("%lld", reg->imm);
226 else if (t == PTR_TO_PACKET)
227 verbose("(id=%d,off=%d,r=%d)",
228 reg->id, reg->off, reg->range);
229 else if (t == UNKNOWN_VALUE && reg->imm)
230 verbose("%lld", reg->imm);
17a52670 231 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
48461135
JB
232 t == PTR_TO_MAP_VALUE_OR_NULL ||
233 t == PTR_TO_MAP_VALUE_ADJ)
57a09bf0 234 verbose("(ks=%d,vs=%d,id=%u)",
1a0dc1ac 235 reg->map_ptr->key_size,
57a09bf0
TG
236 reg->map_ptr->value_size,
237 reg->id);
48461135 238 if (reg->min_value != BPF_REGISTER_MIN_RANGE)
f23cc643
JB
239 verbose(",min_value=%lld",
240 (long long)reg->min_value);
48461135
JB
241 if (reg->max_value != BPF_REGISTER_MAX_RANGE)
242 verbose(",max_value=%llu",
243 (unsigned long long)reg->max_value);
d1174416
DM
244 if (reg->min_align)
245 verbose(",min_align=%u", reg->min_align);
246 if (reg->aux_off)
247 verbose(",aux_off=%u", reg->aux_off);
248 if (reg->aux_off_align)
249 verbose(",aux_off_align=%u", reg->aux_off_align);
17a52670 250 }
9c399760 251 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1a0dc1ac 252 if (state->stack_slot_type[i] == STACK_SPILL)
17a52670 253 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
1a0dc1ac 254 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
17a52670
AS
255 }
256 verbose("\n");
257}
258
cbd35700
AS
259static const char *const bpf_class_string[] = {
260 [BPF_LD] = "ld",
261 [BPF_LDX] = "ldx",
262 [BPF_ST] = "st",
263 [BPF_STX] = "stx",
264 [BPF_ALU] = "alu",
265 [BPF_JMP] = "jmp",
266 [BPF_RET] = "BUG",
267 [BPF_ALU64] = "alu64",
268};
269
687f0715 270static const char *const bpf_alu_string[16] = {
cbd35700
AS
271 [BPF_ADD >> 4] = "+=",
272 [BPF_SUB >> 4] = "-=",
273 [BPF_MUL >> 4] = "*=",
274 [BPF_DIV >> 4] = "/=",
275 [BPF_OR >> 4] = "|=",
276 [BPF_AND >> 4] = "&=",
277 [BPF_LSH >> 4] = "<<=",
278 [BPF_RSH >> 4] = ">>=",
279 [BPF_NEG >> 4] = "neg",
280 [BPF_MOD >> 4] = "%=",
281 [BPF_XOR >> 4] = "^=",
282 [BPF_MOV >> 4] = "=",
283 [BPF_ARSH >> 4] = "s>>=",
284 [BPF_END >> 4] = "endian",
285};
286
287static const char *const bpf_ldst_string[] = {
288 [BPF_W >> 3] = "u32",
289 [BPF_H >> 3] = "u16",
290 [BPF_B >> 3] = "u8",
291 [BPF_DW >> 3] = "u64",
292};
293
687f0715 294static const char *const bpf_jmp_string[16] = {
cbd35700
AS
295 [BPF_JA >> 4] = "jmp",
296 [BPF_JEQ >> 4] = "==",
297 [BPF_JGT >> 4] = ">",
298 [BPF_JGE >> 4] = ">=",
299 [BPF_JSET >> 4] = "&",
300 [BPF_JNE >> 4] = "!=",
301 [BPF_JSGT >> 4] = "s>",
302 [BPF_JSGE >> 4] = "s>=",
303 [BPF_CALL >> 4] = "call",
304 [BPF_EXIT >> 4] = "exit",
305};
306
0d0e5769
DB
307static void print_bpf_insn(const struct bpf_verifier_env *env,
308 const struct bpf_insn *insn)
cbd35700
AS
309{
310 u8 class = BPF_CLASS(insn->code);
311
312 if (class == BPF_ALU || class == BPF_ALU64) {
313 if (BPF_SRC(insn->code) == BPF_X)
314 verbose("(%02x) %sr%d %s %sr%d\n",
315 insn->code, class == BPF_ALU ? "(u32) " : "",
316 insn->dst_reg,
317 bpf_alu_string[BPF_OP(insn->code) >> 4],
318 class == BPF_ALU ? "(u32) " : "",
319 insn->src_reg);
320 else
321 verbose("(%02x) %sr%d %s %s%d\n",
322 insn->code, class == BPF_ALU ? "(u32) " : "",
323 insn->dst_reg,
324 bpf_alu_string[BPF_OP(insn->code) >> 4],
325 class == BPF_ALU ? "(u32) " : "",
326 insn->imm);
327 } else if (class == BPF_STX) {
328 if (BPF_MODE(insn->code) == BPF_MEM)
329 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
330 insn->code,
331 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
332 insn->dst_reg,
333 insn->off, insn->src_reg);
334 else if (BPF_MODE(insn->code) == BPF_XADD)
335 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
336 insn->code,
337 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
338 insn->dst_reg, insn->off,
339 insn->src_reg);
340 else
341 verbose("BUG_%02x\n", insn->code);
342 } else if (class == BPF_ST) {
343 if (BPF_MODE(insn->code) != BPF_MEM) {
344 verbose("BUG_st_%02x\n", insn->code);
345 return;
346 }
347 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
348 insn->code,
349 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
350 insn->dst_reg,
351 insn->off, insn->imm);
352 } else if (class == BPF_LDX) {
353 if (BPF_MODE(insn->code) != BPF_MEM) {
354 verbose("BUG_ldx_%02x\n", insn->code);
355 return;
356 }
357 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
358 insn->code, insn->dst_reg,
359 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
360 insn->src_reg, insn->off);
361 } else if (class == BPF_LD) {
362 if (BPF_MODE(insn->code) == BPF_ABS) {
363 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
364 insn->code,
365 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
366 insn->imm);
367 } else if (BPF_MODE(insn->code) == BPF_IND) {
368 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
369 insn->code,
370 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
371 insn->src_reg, insn->imm);
0d0e5769
DB
372 } else if (BPF_MODE(insn->code) == BPF_IMM &&
373 BPF_SIZE(insn->code) == BPF_DW) {
374 /* At this point, we already made sure that the second
375 * part of the ldimm64 insn is accessible.
376 */
377 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
378 bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
379
380 if (map_ptr && !env->allow_ptr_leaks)
381 imm = 0;
382
383 verbose("(%02x) r%d = 0x%llx\n", insn->code,
384 insn->dst_reg, (unsigned long long)imm);
cbd35700
AS
385 } else {
386 verbose("BUG_ld_%02x\n", insn->code);
387 return;
388 }
389 } else if (class == BPF_JMP) {
390 u8 opcode = BPF_OP(insn->code);
391
392 if (opcode == BPF_CALL) {
ebb676da
TG
393 verbose("(%02x) call %s#%d\n", insn->code,
394 func_id_name(insn->imm), insn->imm);
cbd35700
AS
395 } else if (insn->code == (BPF_JMP | BPF_JA)) {
396 verbose("(%02x) goto pc%+d\n",
397 insn->code, insn->off);
398 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
399 verbose("(%02x) exit\n", insn->code);
400 } else if (BPF_SRC(insn->code) == BPF_X) {
401 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
402 insn->code, insn->dst_reg,
403 bpf_jmp_string[BPF_OP(insn->code) >> 4],
404 insn->src_reg, insn->off);
405 } else {
406 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
407 insn->code, insn->dst_reg,
408 bpf_jmp_string[BPF_OP(insn->code) >> 4],
409 insn->imm, insn->off);
410 }
411 } else {
412 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
413 }
414}
415
58e2af8b 416static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
17a52670 417{
58e2af8b 418 struct bpf_verifier_stack_elem *elem;
17a52670
AS
419 int insn_idx;
420
421 if (env->head == NULL)
422 return -1;
423
424 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
425 insn_idx = env->head->insn_idx;
426 if (prev_insn_idx)
427 *prev_insn_idx = env->head->prev_insn_idx;
428 elem = env->head->next;
429 kfree(env->head);
430 env->head = elem;
431 env->stack_size--;
432 return insn_idx;
433}
434
58e2af8b
JK
435static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
436 int insn_idx, int prev_insn_idx)
17a52670 437{
58e2af8b 438 struct bpf_verifier_stack_elem *elem;
17a52670 439
58e2af8b 440 elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
441 if (!elem)
442 goto err;
443
444 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
445 elem->insn_idx = insn_idx;
446 elem->prev_insn_idx = prev_insn_idx;
447 elem->next = env->head;
448 env->head = elem;
449 env->stack_size++;
07016151 450 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
17a52670
AS
451 verbose("BPF program is too complex\n");
452 goto err;
453 }
454 return &elem->st;
455err:
456 /* pop all elements and return */
457 while (pop_stack(env, NULL) >= 0);
458 return NULL;
459}
460
461#define CALLER_SAVED_REGS 6
462static const int caller_saved[CALLER_SAVED_REGS] = {
463 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
464};
465
a9789ef9
DB
466static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
467{
468 BUG_ON(regno >= MAX_BPF_REG);
469
470 memset(&regs[regno], 0, sizeof(regs[regno]));
471 regs[regno].type = NOT_INIT;
472 regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
473 regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
474}
475
58e2af8b 476static void init_reg_state(struct bpf_reg_state *regs)
17a52670
AS
477{
478 int i;
479
a9789ef9
DB
480 for (i = 0; i < MAX_BPF_REG; i++)
481 mark_reg_not_init(regs, i);
17a52670
AS
482
483 /* frame pointer */
484 regs[BPF_REG_FP].type = FRAME_PTR;
485
486 /* 1st arg to a function */
487 regs[BPF_REG_1].type = PTR_TO_CTX;
488}
489
6760bf2d 490static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
17a52670 491{
17a52670 492 regs[regno].type = UNKNOWN_VALUE;
57a09bf0 493 regs[regno].id = 0;
17a52670 494 regs[regno].imm = 0;
17a52670
AS
495}
496
6760bf2d
DB
497static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
498{
499 BUG_ON(regno >= MAX_BPF_REG);
500 __mark_reg_unknown_value(regs, regno);
501}
502
48461135
JB
503static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
504{
505 regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
506 regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
d1174416 507 regs[regno].min_align = 0;
48461135
JB
508}
509
f0318d01
GB
510static void mark_reg_unknown_value_and_range(struct bpf_reg_state *regs,
511 u32 regno)
512{
513 mark_reg_unknown_value(regs, regno);
514 reset_reg_range_values(regs, regno);
515}
516
17a52670
AS
517enum reg_arg_type {
518 SRC_OP, /* register is used as source operand */
519 DST_OP, /* register is used as destination operand */
520 DST_OP_NO_MARK /* same as above, check only, don't mark */
521};
522
58e2af8b 523static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
17a52670
AS
524 enum reg_arg_type t)
525{
526 if (regno >= MAX_BPF_REG) {
527 verbose("R%d is invalid\n", regno);
528 return -EINVAL;
529 }
530
531 if (t == SRC_OP) {
532 /* check whether register used as source operand can be read */
533 if (regs[regno].type == NOT_INIT) {
534 verbose("R%d !read_ok\n", regno);
535 return -EACCES;
536 }
537 } else {
538 /* check whether register used as dest operand can be written to */
539 if (regno == BPF_REG_FP) {
540 verbose("frame pointer is read only\n");
541 return -EACCES;
542 }
543 if (t == DST_OP)
544 mark_reg_unknown_value(regs, regno);
545 }
546 return 0;
547}
548
549static int bpf_size_to_bytes(int bpf_size)
550{
551 if (bpf_size == BPF_W)
552 return 4;
553 else if (bpf_size == BPF_H)
554 return 2;
555 else if (bpf_size == BPF_B)
556 return 1;
557 else if (bpf_size == BPF_DW)
558 return 8;
559 else
560 return -EINVAL;
561}
562
1be7f75d
AS
563static bool is_spillable_regtype(enum bpf_reg_type type)
564{
565 switch (type) {
566 case PTR_TO_MAP_VALUE:
567 case PTR_TO_MAP_VALUE_OR_NULL:
f0318d01 568 case PTR_TO_MAP_VALUE_ADJ:
1be7f75d
AS
569 case PTR_TO_STACK:
570 case PTR_TO_CTX:
969bf05e
AS
571 case PTR_TO_PACKET:
572 case PTR_TO_PACKET_END:
1be7f75d
AS
573 case FRAME_PTR:
574 case CONST_PTR_TO_MAP:
575 return true;
576 default:
577 return false;
578 }
579}
580
17a52670
AS
581/* check_stack_read/write functions track spill/fill of registers,
582 * stack boundary and alignment are checked in check_mem_access()
583 */
58e2af8b
JK
584static int check_stack_write(struct bpf_verifier_state *state, int off,
585 int size, int value_regno)
17a52670 586{
17a52670 587 int i;
9c399760
AS
588 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
589 * so it's aligned access and [off, off + size) are within stack limits
590 */
17a52670
AS
591
592 if (value_regno >= 0 &&
1be7f75d 593 is_spillable_regtype(state->regs[value_regno].type)) {
17a52670
AS
594
595 /* register containing pointer is being spilled into stack */
9c399760 596 if (size != BPF_REG_SIZE) {
17a52670
AS
597 verbose("invalid size of register spill\n");
598 return -EACCES;
599 }
600
17a52670 601 /* save register state */
9c399760
AS
602 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
603 state->regs[value_regno];
17a52670 604
9c399760
AS
605 for (i = 0; i < BPF_REG_SIZE; i++)
606 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
607 } else {
17a52670 608 /* regular write of data into stack */
9c399760 609 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
58e2af8b 610 (struct bpf_reg_state) {};
9c399760
AS
611
612 for (i = 0; i < size; i++)
613 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
17a52670
AS
614 }
615 return 0;
616}
617
58e2af8b 618static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
17a52670
AS
619 int value_regno)
620{
9c399760 621 u8 *slot_type;
17a52670 622 int i;
17a52670 623
9c399760 624 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
17a52670 625
9c399760
AS
626 if (slot_type[0] == STACK_SPILL) {
627 if (size != BPF_REG_SIZE) {
17a52670
AS
628 verbose("invalid size of register spill\n");
629 return -EACCES;
630 }
9c399760
AS
631 for (i = 1; i < BPF_REG_SIZE; i++) {
632 if (slot_type[i] != STACK_SPILL) {
17a52670
AS
633 verbose("corrupted spill memory\n");
634 return -EACCES;
635 }
636 }
637
638 if (value_regno >= 0)
639 /* restore register state from stack */
9c399760
AS
640 state->regs[value_regno] =
641 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
17a52670
AS
642 return 0;
643 } else {
644 for (i = 0; i < size; i++) {
9c399760 645 if (slot_type[i] != STACK_MISC) {
17a52670
AS
646 verbose("invalid read from stack off %d+%d size %d\n",
647 off, i, size);
648 return -EACCES;
649 }
650 }
651 if (value_regno >= 0)
652 /* have read misc data from the stack */
f0318d01
GB
653 mark_reg_unknown_value_and_range(state->regs,
654 value_regno);
17a52670
AS
655 return 0;
656 }
657}
658
659/* check read/write into map element returned by bpf_map_lookup_elem() */
58e2af8b 660static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
661 int size)
662{
663 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
664
5722569b 665 if (off < 0 || size <= 0 || off + size > map->value_size) {
17a52670
AS
666 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
667 map->value_size, off, size);
668 return -EACCES;
669 }
670 return 0;
671}
672
dbcfe5f7
GB
673/* check read/write into an adjusted map element */
674static int check_map_access_adj(struct bpf_verifier_env *env, u32 regno,
675 int off, int size)
676{
677 struct bpf_verifier_state *state = &env->cur_state;
678 struct bpf_reg_state *reg = &state->regs[regno];
679 int err;
680
681 /* We adjusted the register to this map value, so we
682 * need to change off and size to min_value and max_value
683 * respectively to make sure our theoretical access will be
684 * safe.
685 */
686 if (log_level)
687 print_verifier_state(state);
688 env->varlen_map_value_access = true;
689 /* The minimum value is only important with signed
690 * comparisons where we can't assume the floor of a
691 * value is 0. If we are using signed variables for our
692 * index'es we need to make sure that whatever we use
693 * will have a set floor within our range.
694 */
695 if (reg->min_value < 0) {
696 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
697 regno);
698 return -EACCES;
699 }
700 err = check_map_access(env, regno, reg->min_value + off, size);
701 if (err) {
702 verbose("R%d min value is outside of the array range\n",
703 regno);
704 return err;
705 }
706
707 /* If we haven't set a max value then we need to bail
708 * since we can't be sure we won't do bad things.
709 */
710 if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
711 verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
712 regno);
713 return -EACCES;
714 }
715 return check_map_access(env, regno, reg->max_value + off, size);
716}
717
969bf05e
AS
718#define MAX_PACKET_OFF 0xffff
719
58e2af8b 720static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
721 const struct bpf_call_arg_meta *meta,
722 enum bpf_access_type t)
4acf6c0b 723{
36bbef52 724 switch (env->prog->type) {
3a0af8fd
TG
725 case BPF_PROG_TYPE_LWT_IN:
726 case BPF_PROG_TYPE_LWT_OUT:
727 /* dst_input() and dst_output() can't write for now */
728 if (t == BPF_WRITE)
729 return false;
7e57fbb2 730 /* fallthrough */
36bbef52
DB
731 case BPF_PROG_TYPE_SCHED_CLS:
732 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 733 case BPF_PROG_TYPE_XDP:
3a0af8fd 734 case BPF_PROG_TYPE_LWT_XMIT:
36bbef52
DB
735 if (meta)
736 return meta->pkt_access;
737
738 env->seen_direct_write = true;
4acf6c0b
BB
739 return true;
740 default:
741 return false;
742 }
743}
744
58e2af8b 745static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
969bf05e
AS
746 int size)
747{
58e2af8b
JK
748 struct bpf_reg_state *regs = env->cur_state.regs;
749 struct bpf_reg_state *reg = &regs[regno];
969bf05e 750
d91b28ed 751 off += reg->off;
b399cf64 752 if (off < 0 || size <= 0 || off + size > reg->range) {
d91b28ed
AS
753 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
754 off, size, regno, reg->id, reg->off, reg->range);
969bf05e
AS
755 return -EACCES;
756 }
757 return 0;
758}
759
17a52670 760/* check access to 'struct bpf_context' fields */
58e2af8b 761static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
19de99f7 762 enum bpf_access_type t, enum bpf_reg_type *reg_type)
17a52670 763{
13a27dfc
JK
764 /* for analyzer ctx accesses are already validated and converted */
765 if (env->analyzer_ops)
766 return 0;
767
17a52670 768 if (env->prog->aux->ops->is_valid_access &&
19de99f7 769 env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
32bbe007
AS
770 /* remember the offset of last byte accessed in ctx */
771 if (env->prog->aux->max_ctx_offset < off + size)
772 env->prog->aux->max_ctx_offset = off + size;
17a52670 773 return 0;
32bbe007 774 }
17a52670
AS
775
776 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
777 return -EACCES;
778}
779
58e2af8b 780static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1be7f75d
AS
781{
782 if (env->allow_ptr_leaks)
783 return false;
784
785 switch (env->cur_state.regs[regno].type) {
786 case UNKNOWN_VALUE:
787 case CONST_IMM:
788 return false;
789 default:
790 return true;
791 }
792}
793
79adffcd 794static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
d1174416 795 int off, int size, bool strict)
969bf05e 796{
e07b98d9 797 int ip_align;
d1174416
DM
798 int reg_off;
799
800 /* Byte size accesses are always allowed. */
801 if (!strict || size == 1)
802 return 0;
803
804 reg_off = reg->off;
805 if (reg->id) {
806 if (reg->aux_off_align % size) {
807 verbose("Packet access is only %u byte aligned, %d byte access not allowed\n",
808 reg->aux_off_align, size);
809 return -EACCES;
810 }
811 reg_off += reg->aux_off;
969bf05e
AS
812 }
813
e4eda884
DM
814 /* For platforms that do not have a Kconfig enabling
815 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
816 * NET_IP_ALIGN is universally set to '2'. And on platforms
817 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
818 * to this code only in strict mode where we want to emulate
819 * the NET_IP_ALIGN==2 checking. Therefore use an
820 * unconditional IP align value of '2'.
e07b98d9 821 */
e4eda884 822 ip_align = 2;
e07b98d9 823 if ((ip_align + reg_off + off) % size != 0) {
969bf05e 824 verbose("misaligned packet access off %d+%d+%d size %d\n",
e07b98d9 825 ip_align, reg_off, off, size);
969bf05e
AS
826 return -EACCES;
827 }
79adffcd 828
969bf05e
AS
829 return 0;
830}
831
79adffcd 832static int check_val_ptr_alignment(const struct bpf_reg_state *reg,
d1174416 833 int size, bool strict)
79adffcd 834{
d1174416 835 if (strict && size != 1) {
79adffcd
DB
836 verbose("Unknown alignment. Only byte-sized access allowed in value access.\n");
837 return -EACCES;
838 }
839
969bf05e
AS
840 return 0;
841}
842
e07b98d9
DM
843static int check_ptr_alignment(struct bpf_verifier_env *env,
844 const struct bpf_reg_state *reg,
79adffcd
DB
845 int off, int size)
846{
e07b98d9 847 bool strict = env->strict_alignment;
d1174416 848
79adffcd
DB
849 switch (reg->type) {
850 case PTR_TO_PACKET:
d1174416 851 return check_pkt_ptr_alignment(reg, off, size, strict);
79adffcd 852 case PTR_TO_MAP_VALUE_ADJ:
d1174416 853 return check_val_ptr_alignment(reg, size, strict);
79adffcd
DB
854 default:
855 if (off % size != 0) {
856 verbose("misaligned access off %d size %d\n",
857 off, size);
858 return -EACCES;
859 }
860
861 return 0;
862 }
863}
864
17a52670
AS
865/* check whether memory at (regno + off) is accessible for t = (read | write)
866 * if t==write, value_regno is a register which value is stored into memory
867 * if t==read, value_regno is a register which will receive the value from memory
868 * if t==write && value_regno==-1, some unknown value is stored into memory
869 * if t==read && value_regno==-1, don't care what we read from memory
870 */
58e2af8b 871static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
17a52670
AS
872 int bpf_size, enum bpf_access_type t,
873 int value_regno)
874{
58e2af8b
JK
875 struct bpf_verifier_state *state = &env->cur_state;
876 struct bpf_reg_state *reg = &state->regs[regno];
17a52670
AS
877 int size, err = 0;
878
1a0dc1ac
AS
879 if (reg->type == PTR_TO_STACK)
880 off += reg->imm;
24b4d2ab 881
17a52670
AS
882 size = bpf_size_to_bytes(bpf_size);
883 if (size < 0)
884 return size;
885
e07b98d9 886 err = check_ptr_alignment(env, reg, off, size);
969bf05e
AS
887 if (err)
888 return err;
17a52670 889
48461135
JB
890 if (reg->type == PTR_TO_MAP_VALUE ||
891 reg->type == PTR_TO_MAP_VALUE_ADJ) {
1be7f75d
AS
892 if (t == BPF_WRITE && value_regno >= 0 &&
893 is_pointer_value(env, value_regno)) {
894 verbose("R%d leaks addr into map\n", value_regno);
895 return -EACCES;
896 }
48461135 897
dbcfe5f7
GB
898 if (reg->type == PTR_TO_MAP_VALUE_ADJ)
899 err = check_map_access_adj(env, regno, off, size);
900 else
901 err = check_map_access(env, regno, off, size);
17a52670 902 if (!err && t == BPF_READ && value_regno >= 0)
f0318d01
GB
903 mark_reg_unknown_value_and_range(state->regs,
904 value_regno);
17a52670 905
1a0dc1ac 906 } else if (reg->type == PTR_TO_CTX) {
19de99f7
AS
907 enum bpf_reg_type reg_type = UNKNOWN_VALUE;
908
1be7f75d
AS
909 if (t == BPF_WRITE && value_regno >= 0 &&
910 is_pointer_value(env, value_regno)) {
911 verbose("R%d leaks addr into ctx\n", value_regno);
912 return -EACCES;
913 }
19de99f7 914 err = check_ctx_access(env, off, size, t, &reg_type);
969bf05e 915 if (!err && t == BPF_READ && value_regno >= 0) {
f0318d01
GB
916 mark_reg_unknown_value_and_range(state->regs,
917 value_regno);
1955351d
MS
918 /* note that reg.[id|off|range] == 0 */
919 state->regs[value_regno].type = reg_type;
d1174416
DM
920 state->regs[value_regno].aux_off = 0;
921 state->regs[value_regno].aux_off_align = 0;
969bf05e 922 }
17a52670 923
1a0dc1ac 924 } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
17a52670
AS
925 if (off >= 0 || off < -MAX_BPF_STACK) {
926 verbose("invalid stack off=%d size=%d\n", off, size);
927 return -EACCES;
928 }
8726679a
AS
929
930 if (env->prog->aux->stack_depth < -off)
931 env->prog->aux->stack_depth = -off;
932
1be7f75d
AS
933 if (t == BPF_WRITE) {
934 if (!env->allow_ptr_leaks &&
935 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
936 size != BPF_REG_SIZE) {
937 verbose("attempt to corrupt spilled pointer on stack\n");
938 return -EACCES;
939 }
17a52670 940 err = check_stack_write(state, off, size, value_regno);
1be7f75d 941 } else {
17a52670 942 err = check_stack_read(state, off, size, value_regno);
1be7f75d 943 }
969bf05e 944 } else if (state->regs[regno].type == PTR_TO_PACKET) {
3a0af8fd 945 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
969bf05e
AS
946 verbose("cannot write into packet\n");
947 return -EACCES;
948 }
4acf6c0b
BB
949 if (t == BPF_WRITE && value_regno >= 0 &&
950 is_pointer_value(env, value_regno)) {
951 verbose("R%d leaks addr into packet\n", value_regno);
952 return -EACCES;
953 }
969bf05e
AS
954 err = check_packet_access(env, regno, off, size);
955 if (!err && t == BPF_READ && value_regno >= 0)
f0318d01
GB
956 mark_reg_unknown_value_and_range(state->regs,
957 value_regno);
17a52670
AS
958 } else {
959 verbose("R%d invalid mem access '%s'\n",
1a0dc1ac 960 regno, reg_type_str[reg->type]);
17a52670
AS
961 return -EACCES;
962 }
969bf05e
AS
963
964 if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
965 state->regs[value_regno].type == UNKNOWN_VALUE) {
966 /* 1 or 2 byte load zero-extends, determine the number of
967 * zero upper bits. Not doing it fo 4 byte load, since
968 * such values cannot be added to ptr_to_packet anyway.
969 */
970 state->regs[value_regno].imm = 64 - size * 8;
971 }
17a52670
AS
972 return err;
973}
974
58e2af8b 975static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 976{
58e2af8b 977 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
978 int err;
979
980 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
981 insn->imm != 0) {
982 verbose("BPF_XADD uses reserved fields\n");
983 return -EINVAL;
984 }
985
986 /* check src1 operand */
987 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
988 if (err)
989 return err;
990
991 /* check src2 operand */
992 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
993 if (err)
994 return err;
995
996 /* check whether atomic_add can read the memory */
997 err = check_mem_access(env, insn->dst_reg, insn->off,
998 BPF_SIZE(insn->code), BPF_READ, -1);
999 if (err)
1000 return err;
1001
1002 /* check whether atomic_add can write into the same memory */
1003 return check_mem_access(env, insn->dst_reg, insn->off,
1004 BPF_SIZE(insn->code), BPF_WRITE, -1);
1005}
1006
1007/* when register 'regno' is passed into function that will read 'access_size'
1008 * bytes from that pointer, make sure that it's within stack boundary
1009 * and all elements of stack are initialized
1010 */
58e2af8b 1011static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
435faee1
DB
1012 int access_size, bool zero_size_allowed,
1013 struct bpf_call_arg_meta *meta)
17a52670 1014{
58e2af8b
JK
1015 struct bpf_verifier_state *state = &env->cur_state;
1016 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1017 int off, i;
1018
8e2fe1d9
DB
1019 if (regs[regno].type != PTR_TO_STACK) {
1020 if (zero_size_allowed && access_size == 0 &&
1021 regs[regno].type == CONST_IMM &&
1022 regs[regno].imm == 0)
1023 return 0;
1024
1025 verbose("R%d type=%s expected=%s\n", regno,
1026 reg_type_str[regs[regno].type],
1027 reg_type_str[PTR_TO_STACK]);
17a52670 1028 return -EACCES;
8e2fe1d9 1029 }
17a52670
AS
1030
1031 off = regs[regno].imm;
1032 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1033 access_size <= 0) {
1034 verbose("invalid stack type R%d off=%d access_size=%d\n",
1035 regno, off, access_size);
1036 return -EACCES;
1037 }
1038
8726679a
AS
1039 if (env->prog->aux->stack_depth < -off)
1040 env->prog->aux->stack_depth = -off;
1041
435faee1
DB
1042 if (meta && meta->raw_mode) {
1043 meta->access_size = access_size;
1044 meta->regno = regno;
1045 return 0;
1046 }
1047
17a52670 1048 for (i = 0; i < access_size; i++) {
9c399760 1049 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
17a52670
AS
1050 verbose("invalid indirect read from stack off %d+%d size %d\n",
1051 off, i, access_size);
1052 return -EACCES;
1053 }
1054 }
1055 return 0;
1056}
1057
06c1c049
GB
1058static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1059 int access_size, bool zero_size_allowed,
1060 struct bpf_call_arg_meta *meta)
1061{
1062 struct bpf_reg_state *regs = env->cur_state.regs;
1063
1064 switch (regs[regno].type) {
1065 case PTR_TO_PACKET:
1066 return check_packet_access(env, regno, 0, access_size);
1067 case PTR_TO_MAP_VALUE:
1068 return check_map_access(env, regno, 0, access_size);
1069 case PTR_TO_MAP_VALUE_ADJ:
1070 return check_map_access_adj(env, regno, 0, access_size);
1071 default: /* const_imm|ptr_to_stack or invalid ptr */
1072 return check_stack_boundary(env, regno, access_size,
1073 zero_size_allowed, meta);
1074 }
1075}
1076
58e2af8b 1077static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
33ff9823
DB
1078 enum bpf_arg_type arg_type,
1079 struct bpf_call_arg_meta *meta)
17a52670 1080{
58e2af8b 1081 struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
6841de8b 1082 enum bpf_reg_type expected_type, type = reg->type;
17a52670
AS
1083 int err = 0;
1084
80f1d68c 1085 if (arg_type == ARG_DONTCARE)
17a52670
AS
1086 return 0;
1087
6841de8b 1088 if (type == NOT_INIT) {
17a52670
AS
1089 verbose("R%d !read_ok\n", regno);
1090 return -EACCES;
1091 }
1092
1be7f75d
AS
1093 if (arg_type == ARG_ANYTHING) {
1094 if (is_pointer_value(env, regno)) {
1095 verbose("R%d leaks addr into helper function\n", regno);
1096 return -EACCES;
1097 }
80f1d68c 1098 return 0;
1be7f75d 1099 }
80f1d68c 1100
3a0af8fd
TG
1101 if (type == PTR_TO_PACKET &&
1102 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
36bbef52 1103 verbose("helper access to the packet is not allowed\n");
6841de8b
AS
1104 return -EACCES;
1105 }
1106
8e2fe1d9 1107 if (arg_type == ARG_PTR_TO_MAP_KEY ||
17a52670
AS
1108 arg_type == ARG_PTR_TO_MAP_VALUE) {
1109 expected_type = PTR_TO_STACK;
6841de8b
AS
1110 if (type != PTR_TO_PACKET && type != expected_type)
1111 goto err_type;
39f19ebb
AS
1112 } else if (arg_type == ARG_CONST_SIZE ||
1113 arg_type == ARG_CONST_SIZE_OR_ZERO) {
17a52670 1114 expected_type = CONST_IMM;
06c1c049
GB
1115 /* One exception. Allow UNKNOWN_VALUE registers when the
1116 * boundaries are known and don't cause unsafe memory accesses
1117 */
1118 if (type != UNKNOWN_VALUE && type != expected_type)
6841de8b 1119 goto err_type;
17a52670
AS
1120 } else if (arg_type == ARG_CONST_MAP_PTR) {
1121 expected_type = CONST_PTR_TO_MAP;
6841de8b
AS
1122 if (type != expected_type)
1123 goto err_type;
608cd71a
AS
1124 } else if (arg_type == ARG_PTR_TO_CTX) {
1125 expected_type = PTR_TO_CTX;
6841de8b
AS
1126 if (type != expected_type)
1127 goto err_type;
39f19ebb
AS
1128 } else if (arg_type == ARG_PTR_TO_MEM ||
1129 arg_type == ARG_PTR_TO_UNINIT_MEM) {
8e2fe1d9
DB
1130 expected_type = PTR_TO_STACK;
1131 /* One exception here. In case function allows for NULL to be
1132 * passed in as argument, it's a CONST_IMM type. Final test
1133 * happens during stack boundary checking.
1134 */
6841de8b
AS
1135 if (type == CONST_IMM && reg->imm == 0)
1136 /* final test in check_stack_boundary() */;
5722569b
GB
1137 else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
1138 type != PTR_TO_MAP_VALUE_ADJ && type != expected_type)
6841de8b 1139 goto err_type;
39f19ebb 1140 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
17a52670
AS
1141 } else {
1142 verbose("unsupported arg_type %d\n", arg_type);
1143 return -EFAULT;
1144 }
1145
17a52670
AS
1146 if (arg_type == ARG_CONST_MAP_PTR) {
1147 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 1148 meta->map_ptr = reg->map_ptr;
17a52670
AS
1149 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1150 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1151 * check that [key, key + map->key_size) are within
1152 * stack limits and initialized
1153 */
33ff9823 1154 if (!meta->map_ptr) {
17a52670
AS
1155 /* in function declaration map_ptr must come before
1156 * map_key, so that it's verified and known before
1157 * we have to check map_key here. Otherwise it means
1158 * that kernel subsystem misconfigured verifier
1159 */
1160 verbose("invalid map_ptr to access map->key\n");
1161 return -EACCES;
1162 }
6841de8b
AS
1163 if (type == PTR_TO_PACKET)
1164 err = check_packet_access(env, regno, 0,
1165 meta->map_ptr->key_size);
1166 else
1167 err = check_stack_boundary(env, regno,
1168 meta->map_ptr->key_size,
1169 false, NULL);
17a52670
AS
1170 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1171 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1172 * check [value, value + map->value_size) validity
1173 */
33ff9823 1174 if (!meta->map_ptr) {
17a52670
AS
1175 /* kernel subsystem misconfigured verifier */
1176 verbose("invalid map_ptr to access map->value\n");
1177 return -EACCES;
1178 }
6841de8b
AS
1179 if (type == PTR_TO_PACKET)
1180 err = check_packet_access(env, regno, 0,
1181 meta->map_ptr->value_size);
1182 else
1183 err = check_stack_boundary(env, regno,
1184 meta->map_ptr->value_size,
1185 false, NULL);
39f19ebb
AS
1186 } else if (arg_type == ARG_CONST_SIZE ||
1187 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1188 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 1189
17a52670
AS
1190 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1191 * from stack pointer 'buf'. Check it
1192 * note: regno == len, regno - 1 == buf
1193 */
1194 if (regno == 0) {
1195 /* kernel subsystem misconfigured verifier */
39f19ebb 1196 verbose("ARG_CONST_SIZE cannot be first argument\n");
17a52670
AS
1197 return -EACCES;
1198 }
06c1c049
GB
1199
1200 /* If the register is UNKNOWN_VALUE, the access check happens
1201 * using its boundaries. Otherwise, just use its imm
1202 */
1203 if (type == UNKNOWN_VALUE) {
1204 /* For unprivileged variable accesses, disable raw
1205 * mode so that the program is required to
1206 * initialize all the memory that the helper could
1207 * just partially fill up.
1208 */
1209 meta = NULL;
1210
1211 if (reg->min_value < 0) {
1212 verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
1213 regno);
1214 return -EACCES;
1215 }
1216
1217 if (reg->min_value == 0) {
1218 err = check_helper_mem_access(env, regno - 1, 0,
1219 zero_size_allowed,
1220 meta);
1221 if (err)
1222 return err;
1223 }
1224
1225 if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
1226 verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
1227 regno);
1228 return -EACCES;
1229 }
1230 err = check_helper_mem_access(env, regno - 1,
1231 reg->max_value,
1232 zero_size_allowed, meta);
1233 if (err)
1234 return err;
1235 } else {
1236 /* register is CONST_IMM */
1237 err = check_helper_mem_access(env, regno - 1, reg->imm,
1238 zero_size_allowed, meta);
1239 }
17a52670
AS
1240 }
1241
1242 return err;
6841de8b
AS
1243err_type:
1244 verbose("R%d type=%s expected=%s\n", regno,
1245 reg_type_str[type], reg_type_str[expected_type]);
1246 return -EACCES;
17a52670
AS
1247}
1248
35578d79
KX
1249static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1250{
35578d79
KX
1251 if (!map)
1252 return 0;
1253
6aff67c8
AS
1254 /* We need a two way check, first is from map perspective ... */
1255 switch (map->map_type) {
1256 case BPF_MAP_TYPE_PROG_ARRAY:
1257 if (func_id != BPF_FUNC_tail_call)
1258 goto error;
1259 break;
1260 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1261 if (func_id != BPF_FUNC_perf_event_read &&
1262 func_id != BPF_FUNC_perf_event_output)
1263 goto error;
1264 break;
1265 case BPF_MAP_TYPE_STACK_TRACE:
1266 if (func_id != BPF_FUNC_get_stackid)
1267 goto error;
1268 break;
4ed8ec52 1269 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 1270 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 1271 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
1272 goto error;
1273 break;
56f668df 1274 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 1275 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
1276 if (func_id != BPF_FUNC_map_lookup_elem)
1277 goto error;
6aff67c8
AS
1278 default:
1279 break;
1280 }
1281
1282 /* ... and second from the function itself. */
1283 switch (func_id) {
1284 case BPF_FUNC_tail_call:
1285 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1286 goto error;
1287 break;
1288 case BPF_FUNC_perf_event_read:
1289 case BPF_FUNC_perf_event_output:
1290 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1291 goto error;
1292 break;
1293 case BPF_FUNC_get_stackid:
1294 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1295 goto error;
1296 break;
60d20f91 1297 case BPF_FUNC_current_task_under_cgroup:
747ea55e 1298 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
1299 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1300 goto error;
1301 break;
6aff67c8
AS
1302 default:
1303 break;
35578d79
KX
1304 }
1305
1306 return 0;
6aff67c8 1307error:
ebb676da
TG
1308 verbose("cannot pass map_type %d into func %s#%d\n",
1309 map->map_type, func_id_name(func_id), func_id);
6aff67c8 1310 return -EINVAL;
35578d79
KX
1311}
1312
435faee1
DB
1313static int check_raw_mode(const struct bpf_func_proto *fn)
1314{
1315 int count = 0;
1316
39f19ebb 1317 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1318 count++;
39f19ebb 1319 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1320 count++;
39f19ebb 1321 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1322 count++;
39f19ebb 1323 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 1324 count++;
39f19ebb 1325 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
1326 count++;
1327
1328 return count > 1 ? -EINVAL : 0;
1329}
1330
58e2af8b 1331static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
969bf05e 1332{
58e2af8b
JK
1333 struct bpf_verifier_state *state = &env->cur_state;
1334 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
1335 int i;
1336
1337 for (i = 0; i < MAX_BPF_REG; i++)
1338 if (regs[i].type == PTR_TO_PACKET ||
1339 regs[i].type == PTR_TO_PACKET_END)
1340 mark_reg_unknown_value(regs, i);
1341
1342 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1343 if (state->stack_slot_type[i] != STACK_SPILL)
1344 continue;
1345 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1346 if (reg->type != PTR_TO_PACKET &&
1347 reg->type != PTR_TO_PACKET_END)
1348 continue;
36e24c00
DB
1349 __mark_reg_unknown_value(state->spilled_regs,
1350 i / BPF_REG_SIZE);
969bf05e
AS
1351 }
1352}
1353
81ed18ab 1354static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
17a52670 1355{
58e2af8b 1356 struct bpf_verifier_state *state = &env->cur_state;
17a52670 1357 const struct bpf_func_proto *fn = NULL;
58e2af8b 1358 struct bpf_reg_state *regs = state->regs;
33ff9823 1359 struct bpf_call_arg_meta meta;
969bf05e 1360 bool changes_data;
17a52670
AS
1361 int i, err;
1362
1363 /* find function prototype */
1364 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
ebb676da 1365 verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
17a52670
AS
1366 return -EINVAL;
1367 }
1368
1369 if (env->prog->aux->ops->get_func_proto)
1370 fn = env->prog->aux->ops->get_func_proto(func_id);
1371
1372 if (!fn) {
ebb676da 1373 verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
17a52670
AS
1374 return -EINVAL;
1375 }
1376
1377 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 1378 if (!env->prog->gpl_compatible && fn->gpl_only) {
17a52670
AS
1379 verbose("cannot call GPL only function from proprietary program\n");
1380 return -EINVAL;
1381 }
1382
17bedab2 1383 changes_data = bpf_helper_changes_pkt_data(fn->func);
969bf05e 1384
33ff9823 1385 memset(&meta, 0, sizeof(meta));
36bbef52 1386 meta.pkt_access = fn->pkt_access;
33ff9823 1387
435faee1
DB
1388 /* We only support one arg being in raw mode at the moment, which
1389 * is sufficient for the helper functions we have right now.
1390 */
1391 err = check_raw_mode(fn);
1392 if (err) {
ebb676da
TG
1393 verbose("kernel subsystem misconfigured func %s#%d\n",
1394 func_id_name(func_id), func_id);
435faee1
DB
1395 return err;
1396 }
1397
17a52670 1398 /* check args */
33ff9823 1399 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
1400 if (err)
1401 return err;
33ff9823 1402 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
1403 if (err)
1404 return err;
33ff9823 1405 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
1406 if (err)
1407 return err;
33ff9823 1408 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
1409 if (err)
1410 return err;
33ff9823 1411 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
1412 if (err)
1413 return err;
1414
435faee1
DB
1415 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1416 * is inferred from register state.
1417 */
1418 for (i = 0; i < meta.access_size; i++) {
1419 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1420 if (err)
1421 return err;
1422 }
1423
17a52670 1424 /* reset caller saved regs */
a9789ef9
DB
1425 for (i = 0; i < CALLER_SAVED_REGS; i++)
1426 mark_reg_not_init(regs, caller_saved[i]);
17a52670
AS
1427
1428 /* update return register */
1429 if (fn->ret_type == RET_INTEGER) {
1430 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1431 } else if (fn->ret_type == RET_VOID) {
1432 regs[BPF_REG_0].type = NOT_INIT;
1433 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
fad73a1a
MKL
1434 struct bpf_insn_aux_data *insn_aux;
1435
17a52670 1436 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
48461135 1437 regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
17a52670
AS
1438 /* remember map_ptr, so that check_map_access()
1439 * can check 'value_size' boundary of memory access
1440 * to map element returned from bpf_map_lookup_elem()
1441 */
33ff9823 1442 if (meta.map_ptr == NULL) {
17a52670
AS
1443 verbose("kernel subsystem misconfigured verifier\n");
1444 return -EINVAL;
1445 }
33ff9823 1446 regs[BPF_REG_0].map_ptr = meta.map_ptr;
57a09bf0 1447 regs[BPF_REG_0].id = ++env->id_gen;
fad73a1a
MKL
1448 insn_aux = &env->insn_aux_data[insn_idx];
1449 if (!insn_aux->map_ptr)
1450 insn_aux->map_ptr = meta.map_ptr;
1451 else if (insn_aux->map_ptr != meta.map_ptr)
1452 insn_aux->map_ptr = BPF_MAP_PTR_POISON;
17a52670 1453 } else {
ebb676da
TG
1454 verbose("unknown return type %d of func %s#%d\n",
1455 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
1456 return -EINVAL;
1457 }
04fd61ab 1458
33ff9823 1459 err = check_map_func_compatibility(meta.map_ptr, func_id);
35578d79
KX
1460 if (err)
1461 return err;
04fd61ab 1462
969bf05e
AS
1463 if (changes_data)
1464 clear_all_pkt_pointers(env);
1465 return 0;
1466}
1467
58e2af8b
JK
1468static int check_packet_ptr_add(struct bpf_verifier_env *env,
1469 struct bpf_insn *insn)
969bf05e 1470{
58e2af8b
JK
1471 struct bpf_reg_state *regs = env->cur_state.regs;
1472 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1473 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1474 struct bpf_reg_state tmp_reg;
969bf05e
AS
1475 s32 imm;
1476
1477 if (BPF_SRC(insn->code) == BPF_K) {
1478 /* pkt_ptr += imm */
1479 imm = insn->imm;
1480
1481add_imm:
63dfef75 1482 if (imm < 0) {
969bf05e
AS
1483 verbose("addition of negative constant to packet pointer is not allowed\n");
1484 return -EACCES;
1485 }
1486 if (imm >= MAX_PACKET_OFF ||
1487 imm + dst_reg->off >= MAX_PACKET_OFF) {
1488 verbose("constant %d is too large to add to packet pointer\n",
1489 imm);
1490 return -EACCES;
1491 }
1492 /* a constant was added to pkt_ptr.
1493 * Remember it while keeping the same 'id'
1494 */
1495 dst_reg->off += imm;
1496 } else {
d1174416
DM
1497 bool had_id;
1498
1b9b69ec
AS
1499 if (src_reg->type == PTR_TO_PACKET) {
1500 /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1501 tmp_reg = *dst_reg; /* save r7 state */
1502 *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1503 src_reg = &tmp_reg; /* pretend it's src_reg state */
1504 /* if the checks below reject it, the copy won't matter,
1505 * since we're rejecting the whole program. If all ok,
1506 * then imm22 state will be added to r7
1507 * and r7 will be pkt(id=0,off=22,r=62) while
1508 * r6 will stay as pkt(id=0,off=0,r=62)
1509 */
1510 }
1511
969bf05e
AS
1512 if (src_reg->type == CONST_IMM) {
1513 /* pkt_ptr += reg where reg is known constant */
1514 imm = src_reg->imm;
1515 goto add_imm;
1516 }
1517 /* disallow pkt_ptr += reg
1518 * if reg is not uknown_value with guaranteed zero upper bits
1519 * otherwise pkt_ptr may overflow and addition will become
1520 * subtraction which is not allowed
1521 */
1522 if (src_reg->type != UNKNOWN_VALUE) {
1523 verbose("cannot add '%s' to ptr_to_packet\n",
1524 reg_type_str[src_reg->type]);
1525 return -EACCES;
1526 }
1527 if (src_reg->imm < 48) {
1528 verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1529 src_reg->imm);
1530 return -EACCES;
1531 }
d1174416
DM
1532
1533 had_id = (dst_reg->id != 0);
1534
969bf05e
AS
1535 /* dst_reg stays as pkt_ptr type and since some positive
1536 * integer value was added to the pointer, increment its 'id'
1537 */
1f415a74 1538 dst_reg->id = ++env->id_gen;
969bf05e 1539
d1174416 1540 /* something was added to pkt_ptr, set range to zero */
6832a333 1541 dst_reg->aux_off += dst_reg->off;
969bf05e
AS
1542 dst_reg->off = 0;
1543 dst_reg->range = 0;
d1174416
DM
1544 if (had_id)
1545 dst_reg->aux_off_align = min(dst_reg->aux_off_align,
1546 src_reg->min_align);
1547 else
1548 dst_reg->aux_off_align = src_reg->min_align;
969bf05e
AS
1549 }
1550 return 0;
1551}
1552
58e2af8b 1553static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
969bf05e 1554{
58e2af8b
JK
1555 struct bpf_reg_state *regs = env->cur_state.regs;
1556 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
969bf05e
AS
1557 u8 opcode = BPF_OP(insn->code);
1558 s64 imm_log2;
1559
1560 /* for type == UNKNOWN_VALUE:
1561 * imm > 0 -> number of zero upper bits
1562 * imm == 0 -> don't track which is the same as all bits can be non-zero
1563 */
1564
1565 if (BPF_SRC(insn->code) == BPF_X) {
58e2af8b 1566 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
969bf05e
AS
1567
1568 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1569 dst_reg->imm && opcode == BPF_ADD) {
1570 /* dreg += sreg
1571 * where both have zero upper bits. Adding them
1572 * can only result making one more bit non-zero
1573 * in the larger value.
1574 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1575 * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1576 */
1577 dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1578 dst_reg->imm--;
1579 return 0;
1580 }
1581 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1582 dst_reg->imm && opcode == BPF_ADD) {
1583 /* dreg += sreg
1584 * where dreg has zero upper bits and sreg is const.
1585 * Adding them can only result making one more bit
1586 * non-zero in the larger value.
1587 */
1588 imm_log2 = __ilog2_u64((long long)src_reg->imm);
1589 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1590 dst_reg->imm--;
1591 return 0;
1592 }
1593 /* all other cases non supported yet, just mark dst_reg */
1594 dst_reg->imm = 0;
1595 return 0;
1596 }
1597
1598 /* sign extend 32-bit imm into 64-bit to make sure that
1599 * negative values occupy bit 63. Note ilog2() would have
1600 * been incorrect, since sizeof(insn->imm) == 4
1601 */
1602 imm_log2 = __ilog2_u64((long long)insn->imm);
1603
1604 if (dst_reg->imm && opcode == BPF_LSH) {
1605 /* reg <<= imm
1606 * if reg was a result of 2 byte load, then its imm == 48
1607 * which means that upper 48 bits are zero and shifting this reg
1608 * left by 4 would mean that upper 44 bits are still zero
1609 */
1610 dst_reg->imm -= insn->imm;
1611 } else if (dst_reg->imm && opcode == BPF_MUL) {
1612 /* reg *= imm
1613 * if multiplying by 14 subtract 4
1614 * This is conservative calculation of upper zero bits.
1615 * It's not trying to special case insn->imm == 1 or 0 cases
1616 */
1617 dst_reg->imm -= imm_log2 + 1;
1618 } else if (opcode == BPF_AND) {
1619 /* reg &= imm */
1620 dst_reg->imm = 63 - imm_log2;
1621 } else if (dst_reg->imm && opcode == BPF_ADD) {
1622 /* reg += imm */
1623 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1624 dst_reg->imm--;
1625 } else if (opcode == BPF_RSH) {
1626 /* reg >>= imm
1627 * which means that after right shift, upper bits will be zero
1628 * note that verifier already checked that
1629 * 0 <= imm < 64 for shift insn
1630 */
1631 dst_reg->imm += insn->imm;
1632 if (unlikely(dst_reg->imm > 64))
1633 /* some dumb code did:
1634 * r2 = *(u32 *)mem;
1635 * r2 >>= 32;
1636 * and all bits are zero now */
1637 dst_reg->imm = 64;
1638 } else {
1639 /* all other alu ops, means that we don't know what will
1640 * happen to the value, mark it with unknown number of zero bits
1641 */
1642 dst_reg->imm = 0;
1643 }
1644
1645 if (dst_reg->imm < 0) {
1646 /* all 64 bits of the register can contain non-zero bits
1647 * and such value cannot be added to ptr_to_packet, since it
1648 * may overflow, mark it as unknown to avoid further eval
1649 */
1650 dst_reg->imm = 0;
1651 }
1652 return 0;
1653}
1654
58e2af8b
JK
1655static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1656 struct bpf_insn *insn)
969bf05e 1657{
58e2af8b
JK
1658 struct bpf_reg_state *regs = env->cur_state.regs;
1659 struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1660 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
969bf05e 1661 u8 opcode = BPF_OP(insn->code);
3fadc801 1662 u64 dst_imm = dst_reg->imm;
969bf05e 1663
3fadc801
DB
1664 /* dst_reg->type == CONST_IMM here. Simulate execution of insns
1665 * containing ALU ops. Don't care about overflow or negative
1666 * values, just add/sub/... them; registers are in u64.
969bf05e 1667 */
3fadc801
DB
1668 if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K) {
1669 dst_imm += insn->imm;
1670 } else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1671 src_reg->type == CONST_IMM) {
1672 dst_imm += src_reg->imm;
1673 } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_K) {
1674 dst_imm -= insn->imm;
1675 } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_X &&
1676 src_reg->type == CONST_IMM) {
1677 dst_imm -= src_reg->imm;
1678 } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_K) {
1679 dst_imm *= insn->imm;
1680 } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_X &&
1681 src_reg->type == CONST_IMM) {
1682 dst_imm *= src_reg->imm;
1683 } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_K) {
1684 dst_imm |= insn->imm;
1685 } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_X &&
1686 src_reg->type == CONST_IMM) {
1687 dst_imm |= src_reg->imm;
1688 } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_K) {
1689 dst_imm &= insn->imm;
1690 } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_X &&
1691 src_reg->type == CONST_IMM) {
1692 dst_imm &= src_reg->imm;
1693 } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_K) {
1694 dst_imm >>= insn->imm;
1695 } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_X &&
1696 src_reg->type == CONST_IMM) {
1697 dst_imm >>= src_reg->imm;
1698 } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_K) {
1699 dst_imm <<= insn->imm;
1700 } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_X &&
1701 src_reg->type == CONST_IMM) {
1702 dst_imm <<= src_reg->imm;
1703 } else {
969bf05e 1704 mark_reg_unknown_value(regs, insn->dst_reg);
3fadc801
DB
1705 goto out;
1706 }
1707
1708 dst_reg->imm = dst_imm;
1709out:
17a52670
AS
1710 return 0;
1711}
1712
48461135
JB
1713static void check_reg_overflow(struct bpf_reg_state *reg)
1714{
1715 if (reg->max_value > BPF_REGISTER_MAX_RANGE)
1716 reg->max_value = BPF_REGISTER_MAX_RANGE;
f23cc643
JB
1717 if (reg->min_value < BPF_REGISTER_MIN_RANGE ||
1718 reg->min_value > BPF_REGISTER_MAX_RANGE)
48461135
JB
1719 reg->min_value = BPF_REGISTER_MIN_RANGE;
1720}
1721
d1174416
DM
1722static u32 calc_align(u32 imm)
1723{
1724 if (!imm)
1725 return 1U << 31;
1726 return imm - ((imm - 1) & imm);
1727}
1728
48461135
JB
1729static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
1730 struct bpf_insn *insn)
1731{
1732 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
f23cc643
JB
1733 s64 min_val = BPF_REGISTER_MIN_RANGE;
1734 u64 max_val = BPF_REGISTER_MAX_RANGE;
48461135 1735 u8 opcode = BPF_OP(insn->code);
d1174416 1736 u32 dst_align, src_align;
48461135
JB
1737
1738 dst_reg = &regs[insn->dst_reg];
d1174416 1739 src_align = 0;
48461135
JB
1740 if (BPF_SRC(insn->code) == BPF_X) {
1741 check_reg_overflow(&regs[insn->src_reg]);
1742 min_val = regs[insn->src_reg].min_value;
1743 max_val = regs[insn->src_reg].max_value;
1744
1745 /* If the source register is a random pointer then the
1746 * min_value/max_value values represent the range of the known
1747 * accesses into that value, not the actual min/max value of the
1748 * register itself. In this case we have to reset the reg range
1749 * values so we know it is not safe to look at.
1750 */
1751 if (regs[insn->src_reg].type != CONST_IMM &&
1752 regs[insn->src_reg].type != UNKNOWN_VALUE) {
1753 min_val = BPF_REGISTER_MIN_RANGE;
1754 max_val = BPF_REGISTER_MAX_RANGE;
d1174416
DM
1755 src_align = 0;
1756 } else {
1757 src_align = regs[insn->src_reg].min_align;
48461135
JB
1758 }
1759 } else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
1760 (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
1761 min_val = max_val = insn->imm;
d1174416 1762 src_align = calc_align(insn->imm);
48461135
JB
1763 }
1764
d1174416
DM
1765 dst_align = dst_reg->min_align;
1766
48461135
JB
1767 /* We don't know anything about what was done to this register, mark it
1768 * as unknown.
1769 */
1770 if (min_val == BPF_REGISTER_MIN_RANGE &&
1771 max_val == BPF_REGISTER_MAX_RANGE) {
1772 reset_reg_range_values(regs, insn->dst_reg);
1773 return;
1774 }
1775
f23cc643
JB
1776 /* If one of our values was at the end of our ranges then we can't just
1777 * do our normal operations to the register, we need to set the values
1778 * to the min/max since they are undefined.
1779 */
1780 if (min_val == BPF_REGISTER_MIN_RANGE)
1781 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1782 if (max_val == BPF_REGISTER_MAX_RANGE)
1783 dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1784
48461135
JB
1785 switch (opcode) {
1786 case BPF_ADD:
f23cc643
JB
1787 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1788 dst_reg->min_value += min_val;
1789 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1790 dst_reg->max_value += max_val;
d1174416 1791 dst_reg->min_align = min(src_align, dst_align);
48461135
JB
1792 break;
1793 case BPF_SUB:
f23cc643
JB
1794 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1795 dst_reg->min_value -= min_val;
1796 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1797 dst_reg->max_value -= max_val;
d1174416 1798 dst_reg->min_align = min(src_align, dst_align);
48461135
JB
1799 break;
1800 case BPF_MUL:
f23cc643
JB
1801 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1802 dst_reg->min_value *= min_val;
1803 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1804 dst_reg->max_value *= max_val;
d1174416 1805 dst_reg->min_align = max(src_align, dst_align);
48461135
JB
1806 break;
1807 case BPF_AND:
f23cc643
JB
1808 /* Disallow AND'ing of negative numbers, ain't nobody got time
1809 * for that. Otherwise the minimum is 0 and the max is the max
1810 * value we could AND against.
1811 */
1812 if (min_val < 0)
1813 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1814 else
1815 dst_reg->min_value = 0;
48461135 1816 dst_reg->max_value = max_val;
d1174416 1817 dst_reg->min_align = max(src_align, dst_align);
48461135
JB
1818 break;
1819 case BPF_LSH:
1820 /* Gotta have special overflow logic here, if we're shifting
1821 * more than MAX_RANGE then just assume we have an invalid
1822 * range.
1823 */
d1174416 1824 if (min_val > ilog2(BPF_REGISTER_MAX_RANGE)) {
48461135 1825 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
d1174416
DM
1826 dst_reg->min_align = 1;
1827 } else {
1828 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1829 dst_reg->min_value <<= min_val;
1830 if (!dst_reg->min_align)
1831 dst_reg->min_align = 1;
1832 dst_reg->min_align <<= min_val;
1833 }
48461135
JB
1834 if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
1835 dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
f23cc643 1836 else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
48461135
JB
1837 dst_reg->max_value <<= max_val;
1838 break;
1839 case BPF_RSH:
f23cc643
JB
1840 /* RSH by a negative number is undefined, and the BPF_RSH is an
1841 * unsigned shift, so make the appropriate casts.
48461135 1842 */
d1174416 1843 if (min_val < 0 || dst_reg->min_value < 0) {
f23cc643 1844 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
d1174416 1845 } else {
f23cc643
JB
1846 dst_reg->min_value =
1847 (u64)(dst_reg->min_value) >> min_val;
d1174416
DM
1848 }
1849 if (min_val < 0) {
1850 dst_reg->min_align = 1;
1851 } else {
1852 dst_reg->min_align >>= (u64) min_val;
1853 if (!dst_reg->min_align)
1854 dst_reg->min_align = 1;
1855 }
f23cc643
JB
1856 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1857 dst_reg->max_value >>= max_val;
48461135
JB
1858 break;
1859 default:
1860 reset_reg_range_values(regs, insn->dst_reg);
1861 break;
1862 }
1863
1864 check_reg_overflow(dst_reg);
1865}
1866
17a52670 1867/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 1868static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 1869{
58e2af8b 1870 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
17a52670
AS
1871 u8 opcode = BPF_OP(insn->code);
1872 int err;
1873
1874 if (opcode == BPF_END || opcode == BPF_NEG) {
1875 if (opcode == BPF_NEG) {
1876 if (BPF_SRC(insn->code) != 0 ||
1877 insn->src_reg != BPF_REG_0 ||
1878 insn->off != 0 || insn->imm != 0) {
1879 verbose("BPF_NEG uses reserved fields\n");
1880 return -EINVAL;
1881 }
1882 } else {
1883 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1884 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1885 verbose("BPF_END uses reserved fields\n");
1886 return -EINVAL;
1887 }
1888 }
1889
1890 /* check src operand */
1891 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1892 if (err)
1893 return err;
1894
1be7f75d
AS
1895 if (is_pointer_value(env, insn->dst_reg)) {
1896 verbose("R%d pointer arithmetic prohibited\n",
1897 insn->dst_reg);
1898 return -EACCES;
1899 }
1900
17a52670
AS
1901 /* check dest operand */
1902 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1903 if (err)
1904 return err;
1905
1906 } else if (opcode == BPF_MOV) {
1907
1908 if (BPF_SRC(insn->code) == BPF_X) {
1909 if (insn->imm != 0 || insn->off != 0) {
1910 verbose("BPF_MOV uses reserved fields\n");
1911 return -EINVAL;
1912 }
1913
1914 /* check src operand */
1915 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1916 if (err)
1917 return err;
1918 } else {
1919 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1920 verbose("BPF_MOV uses reserved fields\n");
1921 return -EINVAL;
1922 }
1923 }
1924
1925 /* check dest operand */
1926 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1927 if (err)
1928 return err;
1929
48461135
JB
1930 /* we are setting our register to something new, we need to
1931 * reset its range values.
1932 */
1933 reset_reg_range_values(regs, insn->dst_reg);
1934
17a52670
AS
1935 if (BPF_SRC(insn->code) == BPF_X) {
1936 if (BPF_CLASS(insn->code) == BPF_ALU64) {
1937 /* case: R1 = R2
1938 * copy register state to dest reg
1939 */
1940 regs[insn->dst_reg] = regs[insn->src_reg];
1941 } else {
1be7f75d
AS
1942 if (is_pointer_value(env, insn->src_reg)) {
1943 verbose("R%d partial copy of pointer\n",
1944 insn->src_reg);
1945 return -EACCES;
1946 }
57a09bf0 1947 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
1948 }
1949 } else {
1950 /* case: R = imm
1951 * remember the value we stored into this reg
1952 */
1953 regs[insn->dst_reg].type = CONST_IMM;
1954 regs[insn->dst_reg].imm = insn->imm;
4a2ff55a 1955 regs[insn->dst_reg].id = 0;
48461135
JB
1956 regs[insn->dst_reg].max_value = insn->imm;
1957 regs[insn->dst_reg].min_value = insn->imm;
d1174416 1958 regs[insn->dst_reg].min_align = calc_align(insn->imm);
17a52670
AS
1959 }
1960
1961 } else if (opcode > BPF_END) {
1962 verbose("invalid BPF_ALU opcode %x\n", opcode);
1963 return -EINVAL;
1964
1965 } else { /* all other ALU ops: and, sub, xor, add, ... */
1966
17a52670
AS
1967 if (BPF_SRC(insn->code) == BPF_X) {
1968 if (insn->imm != 0 || insn->off != 0) {
1969 verbose("BPF_ALU uses reserved fields\n");
1970 return -EINVAL;
1971 }
1972 /* check src1 operand */
1973 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1974 if (err)
1975 return err;
1976 } else {
1977 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1978 verbose("BPF_ALU uses reserved fields\n");
1979 return -EINVAL;
1980 }
1981 }
1982
1983 /* check src2 operand */
1984 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1985 if (err)
1986 return err;
1987
1988 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1989 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1990 verbose("div by zero\n");
1991 return -EINVAL;
1992 }
1993
229394e8
RV
1994 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1995 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1996 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1997
1998 if (insn->imm < 0 || insn->imm >= size) {
1999 verbose("invalid shift %d\n", insn->imm);
2000 return -EINVAL;
2001 }
2002 }
2003
1a0dc1ac
AS
2004 /* check dest operand */
2005 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2006 if (err)
2007 return err;
2008
2009 dst_reg = &regs[insn->dst_reg];
2010
48461135
JB
2011 /* first we want to adjust our ranges. */
2012 adjust_reg_min_max_vals(env, insn);
2013
17a52670
AS
2014 /* pattern match 'bpf_add Rx, imm' instruction */
2015 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1a0dc1ac
AS
2016 dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
2017 dst_reg->type = PTR_TO_STACK;
2018 dst_reg->imm = insn->imm;
2019 return 0;
332270fd
YS
2020 } else if (opcode == BPF_ADD &&
2021 BPF_CLASS(insn->code) == BPF_ALU64 &&
2022 dst_reg->type == PTR_TO_STACK &&
2023 ((BPF_SRC(insn->code) == BPF_X &&
2024 regs[insn->src_reg].type == CONST_IMM) ||
2025 BPF_SRC(insn->code) == BPF_K)) {
2026 if (BPF_SRC(insn->code) == BPF_X)
2027 dst_reg->imm += regs[insn->src_reg].imm;
2028 else
2029 dst_reg->imm += insn->imm;
2030 return 0;
969bf05e
AS
2031 } else if (opcode == BPF_ADD &&
2032 BPF_CLASS(insn->code) == BPF_ALU64 &&
1b9b69ec
AS
2033 (dst_reg->type == PTR_TO_PACKET ||
2034 (BPF_SRC(insn->code) == BPF_X &&
2035 regs[insn->src_reg].type == PTR_TO_PACKET))) {
969bf05e
AS
2036 /* ptr_to_packet += K|X */
2037 return check_packet_ptr_add(env, insn);
2038 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
2039 dst_reg->type == UNKNOWN_VALUE &&
2040 env->allow_ptr_leaks) {
2041 /* unknown += K|X */
2042 return evaluate_reg_alu(env, insn);
2043 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
2044 dst_reg->type == CONST_IMM &&
2045 env->allow_ptr_leaks) {
2046 /* reg_imm += K|X */
2047 return evaluate_reg_imm_alu(env, insn);
1be7f75d
AS
2048 } else if (is_pointer_value(env, insn->dst_reg)) {
2049 verbose("R%d pointer arithmetic prohibited\n",
2050 insn->dst_reg);
2051 return -EACCES;
2052 } else if (BPF_SRC(insn->code) == BPF_X &&
2053 is_pointer_value(env, insn->src_reg)) {
2054 verbose("R%d pointer arithmetic prohibited\n",
2055 insn->src_reg);
2056 return -EACCES;
2057 }
17a52670 2058
48461135
JB
2059 /* If we did pointer math on a map value then just set it to our
2060 * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
2061 * loads to this register appropriately, otherwise just mark the
2062 * register as unknown.
2063 */
2064 if (env->allow_ptr_leaks &&
fce366a9 2065 BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD &&
48461135
JB
2066 (dst_reg->type == PTR_TO_MAP_VALUE ||
2067 dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
2068 dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
2069 else
2070 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
2071 }
2072
2073 return 0;
2074}
2075
58e2af8b
JK
2076static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2077 struct bpf_reg_state *dst_reg)
969bf05e 2078{
58e2af8b 2079 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e 2080 int i;
2d2be8ca
DB
2081
2082 /* LLVM can generate two kind of checks:
2083 *
2084 * Type 1:
2085 *
2086 * r2 = r3;
2087 * r2 += 8;
2088 * if (r2 > pkt_end) goto <handle exception>
2089 * <access okay>
2090 *
2091 * Where:
2092 * r2 == dst_reg, pkt_end == src_reg
2093 * r2=pkt(id=n,off=8,r=0)
2094 * r3=pkt(id=n,off=0,r=0)
2095 *
2096 * Type 2:
2097 *
2098 * r2 = r3;
2099 * r2 += 8;
2100 * if (pkt_end >= r2) goto <access okay>
2101 * <handle exception>
2102 *
2103 * Where:
2104 * pkt_end == dst_reg, r2 == src_reg
2105 * r2=pkt(id=n,off=8,r=0)
2106 * r3=pkt(id=n,off=0,r=0)
2107 *
2108 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
2109 * so that range of bytes [r3, r3 + 8) is safe to access.
969bf05e 2110 */
2d2be8ca 2111
969bf05e
AS
2112 for (i = 0; i < MAX_BPF_REG; i++)
2113 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
b1977682
AS
2114 /* keep the maximum range already checked */
2115 regs[i].range = max(regs[i].range, dst_reg->off);
969bf05e
AS
2116
2117 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2118 if (state->stack_slot_type[i] != STACK_SPILL)
2119 continue;
2120 reg = &state->spilled_regs[i / BPF_REG_SIZE];
2121 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
b1977682 2122 reg->range = max(reg->range, dst_reg->off);
969bf05e
AS
2123 }
2124}
2125
48461135
JB
2126/* Adjusts the register min/max values in the case that the dst_reg is the
2127 * variable register that we are working on, and src_reg is a constant or we're
2128 * simply doing a BPF_K check.
2129 */
2130static void reg_set_min_max(struct bpf_reg_state *true_reg,
2131 struct bpf_reg_state *false_reg, u64 val,
2132 u8 opcode)
2133{
2134 switch (opcode) {
2135 case BPF_JEQ:
2136 /* If this is false then we know nothing Jon Snow, but if it is
2137 * true then we know for sure.
2138 */
2139 true_reg->max_value = true_reg->min_value = val;
2140 break;
2141 case BPF_JNE:
2142 /* If this is true we know nothing Jon Snow, but if it is false
2143 * we know the value for sure;
2144 */
2145 false_reg->max_value = false_reg->min_value = val;
2146 break;
2147 case BPF_JGT:
2148 /* Unsigned comparison, the minimum value is 0. */
2149 false_reg->min_value = 0;
7e57fbb2 2150 /* fallthrough */
48461135
JB
2151 case BPF_JSGT:
2152 /* If this is false then we know the maximum val is val,
2153 * otherwise we know the min val is val+1.
2154 */
2155 false_reg->max_value = val;
2156 true_reg->min_value = val + 1;
2157 break;
2158 case BPF_JGE:
2159 /* Unsigned comparison, the minimum value is 0. */
2160 false_reg->min_value = 0;
7e57fbb2 2161 /* fallthrough */
48461135
JB
2162 case BPF_JSGE:
2163 /* If this is false then we know the maximum value is val - 1,
2164 * otherwise we know the mimimum value is val.
2165 */
2166 false_reg->max_value = val - 1;
2167 true_reg->min_value = val;
2168 break;
2169 default:
2170 break;
2171 }
2172
2173 check_reg_overflow(false_reg);
2174 check_reg_overflow(true_reg);
2175}
2176
2177/* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
2178 * is the variable reg.
2179 */
2180static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
2181 struct bpf_reg_state *false_reg, u64 val,
2182 u8 opcode)
2183{
2184 switch (opcode) {
2185 case BPF_JEQ:
2186 /* If this is false then we know nothing Jon Snow, but if it is
2187 * true then we know for sure.
2188 */
2189 true_reg->max_value = true_reg->min_value = val;
2190 break;
2191 case BPF_JNE:
2192 /* If this is true we know nothing Jon Snow, but if it is false
2193 * we know the value for sure;
2194 */
2195 false_reg->max_value = false_reg->min_value = val;
2196 break;
2197 case BPF_JGT:
2198 /* Unsigned comparison, the minimum value is 0. */
2199 true_reg->min_value = 0;
7e57fbb2 2200 /* fallthrough */
48461135
JB
2201 case BPF_JSGT:
2202 /*
2203 * If this is false, then the val is <= the register, if it is
2204 * true the register <= to the val.
2205 */
2206 false_reg->min_value = val;
2207 true_reg->max_value = val - 1;
2208 break;
2209 case BPF_JGE:
2210 /* Unsigned comparison, the minimum value is 0. */
2211 true_reg->min_value = 0;
7e57fbb2 2212 /* fallthrough */
48461135
JB
2213 case BPF_JSGE:
2214 /* If this is false then constant < register, if it is true then
2215 * the register < constant.
2216 */
2217 false_reg->min_value = val + 1;
2218 true_reg->max_value = val;
2219 break;
2220 default:
2221 break;
2222 }
2223
2224 check_reg_overflow(false_reg);
2225 check_reg_overflow(true_reg);
2226}
2227
57a09bf0
TG
2228static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
2229 enum bpf_reg_type type)
2230{
2231 struct bpf_reg_state *reg = &regs[regno];
2232
2233 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
56f668df
MKL
2234 if (type == UNKNOWN_VALUE) {
2235 __mark_reg_unknown_value(regs, regno);
2236 } else if (reg->map_ptr->inner_map_meta) {
2237 reg->type = CONST_PTR_TO_MAP;
2238 reg->map_ptr = reg->map_ptr->inner_map_meta;
2239 } else {
2240 reg->type = type;
2241 }
a08dd0da
DB
2242 /* We don't need id from this point onwards anymore, thus we
2243 * should better reset it, so that state pruning has chances
2244 * to take effect.
2245 */
2246 reg->id = 0;
57a09bf0
TG
2247 }
2248}
2249
2250/* The logic is similar to find_good_pkt_pointers(), both could eventually
2251 * be folded together at some point.
2252 */
2253static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
2254 enum bpf_reg_type type)
2255{
2256 struct bpf_reg_state *regs = state->regs;
a08dd0da 2257 u32 id = regs[regno].id;
57a09bf0
TG
2258 int i;
2259
2260 for (i = 0; i < MAX_BPF_REG; i++)
a08dd0da 2261 mark_map_reg(regs, i, id, type);
57a09bf0
TG
2262
2263 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2264 if (state->stack_slot_type[i] != STACK_SPILL)
2265 continue;
a08dd0da 2266 mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type);
57a09bf0
TG
2267 }
2268}
2269
58e2af8b 2270static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
2271 struct bpf_insn *insn, int *insn_idx)
2272{
58e2af8b
JK
2273 struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
2274 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
17a52670
AS
2275 u8 opcode = BPF_OP(insn->code);
2276 int err;
2277
2278 if (opcode > BPF_EXIT) {
2279 verbose("invalid BPF_JMP opcode %x\n", opcode);
2280 return -EINVAL;
2281 }
2282
2283 if (BPF_SRC(insn->code) == BPF_X) {
2284 if (insn->imm != 0) {
2285 verbose("BPF_JMP uses reserved fields\n");
2286 return -EINVAL;
2287 }
2288
2289 /* check src1 operand */
2290 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2291 if (err)
2292 return err;
1be7f75d
AS
2293
2294 if (is_pointer_value(env, insn->src_reg)) {
2295 verbose("R%d pointer comparison prohibited\n",
2296 insn->src_reg);
2297 return -EACCES;
2298 }
17a52670
AS
2299 } else {
2300 if (insn->src_reg != BPF_REG_0) {
2301 verbose("BPF_JMP uses reserved fields\n");
2302 return -EINVAL;
2303 }
2304 }
2305
2306 /* check src2 operand */
2307 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2308 if (err)
2309 return err;
2310
1a0dc1ac
AS
2311 dst_reg = &regs[insn->dst_reg];
2312
17a52670
AS
2313 /* detect if R == 0 where R was initialized to zero earlier */
2314 if (BPF_SRC(insn->code) == BPF_K &&
2315 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1a0dc1ac 2316 dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
17a52670
AS
2317 if (opcode == BPF_JEQ) {
2318 /* if (imm == imm) goto pc+off;
2319 * only follow the goto, ignore fall-through
2320 */
2321 *insn_idx += insn->off;
2322 return 0;
2323 } else {
2324 /* if (imm != imm) goto pc+off;
2325 * only follow fall-through branch, since
2326 * that's where the program will go
2327 */
2328 return 0;
2329 }
2330 }
2331
2332 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2333 if (!other_branch)
2334 return -EFAULT;
2335
48461135
JB
2336 /* detect if we are comparing against a constant value so we can adjust
2337 * our min/max values for our dst register.
2338 */
2339 if (BPF_SRC(insn->code) == BPF_X) {
2340 if (regs[insn->src_reg].type == CONST_IMM)
2341 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2342 dst_reg, regs[insn->src_reg].imm,
2343 opcode);
2344 else if (dst_reg->type == CONST_IMM)
2345 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2346 &regs[insn->src_reg], dst_reg->imm,
2347 opcode);
2348 } else {
2349 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2350 dst_reg, insn->imm, opcode);
2351 }
2352
58e2af8b 2353 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
17a52670 2354 if (BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac
AS
2355 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2356 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
57a09bf0
TG
2357 /* Mark all identical map registers in each branch as either
2358 * safe or unknown depending R == 0 or R != 0 conditional.
2359 */
2360 mark_map_regs(this_branch, insn->dst_reg,
2361 opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
2362 mark_map_regs(other_branch, insn->dst_reg,
2363 opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
969bf05e
AS
2364 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2365 dst_reg->type == PTR_TO_PACKET &&
2366 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2d2be8ca
DB
2367 find_good_pkt_pointers(this_branch, dst_reg);
2368 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2369 dst_reg->type == PTR_TO_PACKET_END &&
2370 regs[insn->src_reg].type == PTR_TO_PACKET) {
2371 find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
1be7f75d
AS
2372 } else if (is_pointer_value(env, insn->dst_reg)) {
2373 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2374 return -EACCES;
17a52670
AS
2375 }
2376 if (log_level)
2d2be8ca 2377 print_verifier_state(this_branch);
17a52670
AS
2378 return 0;
2379}
2380
0246e64d
AS
2381/* return the map pointer stored inside BPF_LD_IMM64 instruction */
2382static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2383{
2384 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2385
2386 return (struct bpf_map *) (unsigned long) imm64;
2387}
2388
17a52670 2389/* verify BPF_LD_IMM64 instruction */
58e2af8b 2390static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 2391{
58e2af8b 2392 struct bpf_reg_state *regs = env->cur_state.regs;
17a52670
AS
2393 int err;
2394
2395 if (BPF_SIZE(insn->code) != BPF_DW) {
2396 verbose("invalid BPF_LD_IMM insn\n");
2397 return -EINVAL;
2398 }
2399 if (insn->off != 0) {
2400 verbose("BPF_LD_IMM64 uses reserved fields\n");
2401 return -EINVAL;
2402 }
2403
2404 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2405 if (err)
2406 return err;
2407
6b173873 2408 if (insn->src_reg == 0) {
6b173873
JK
2409 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2410
6b173873
JK
2411 regs[insn->dst_reg].type = CONST_IMM;
2412 regs[insn->dst_reg].imm = imm;
4a2ff55a 2413 regs[insn->dst_reg].id = 0;
17a52670 2414 return 0;
6b173873 2415 }
17a52670
AS
2416
2417 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2418 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2419
2420 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2421 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2422 return 0;
2423}
2424
96be4325
DB
2425static bool may_access_skb(enum bpf_prog_type type)
2426{
2427 switch (type) {
2428 case BPF_PROG_TYPE_SOCKET_FILTER:
2429 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 2430 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
2431 return true;
2432 default:
2433 return false;
2434 }
2435}
2436
ddd872bc
AS
2437/* verify safety of LD_ABS|LD_IND instructions:
2438 * - they can only appear in the programs where ctx == skb
2439 * - since they are wrappers of function calls, they scratch R1-R5 registers,
2440 * preserve R6-R9, and store return value into R0
2441 *
2442 * Implicit input:
2443 * ctx == skb == R6 == CTX
2444 *
2445 * Explicit input:
2446 * SRC == any register
2447 * IMM == 32-bit immediate
2448 *
2449 * Output:
2450 * R0 - 8/16/32-bit skb data converted to cpu endianness
2451 */
58e2af8b 2452static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 2453{
58e2af8b 2454 struct bpf_reg_state *regs = env->cur_state.regs;
ddd872bc 2455 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
2456 int i, err;
2457
24701ece 2458 if (!may_access_skb(env->prog->type)) {
1a0dc1ac 2459 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
2460 return -EINVAL;
2461 }
2462
2463 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 2464 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 2465 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1a0dc1ac 2466 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
2467 return -EINVAL;
2468 }
2469
2470 /* check whether implicit source operand (register R6) is readable */
2471 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2472 if (err)
2473 return err;
2474
2475 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2476 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2477 return -EINVAL;
2478 }
2479
2480 if (mode == BPF_IND) {
2481 /* check explicit source operand */
2482 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2483 if (err)
2484 return err;
2485 }
2486
2487 /* reset caller saved regs to unreadable */
a9789ef9
DB
2488 for (i = 0; i < CALLER_SAVED_REGS; i++)
2489 mark_reg_not_init(regs, caller_saved[i]);
ddd872bc
AS
2490
2491 /* mark destination R0 register as readable, since it contains
2492 * the value fetched from the packet
2493 */
2494 regs[BPF_REG_0].type = UNKNOWN_VALUE;
2495 return 0;
2496}
2497
475fb78f
AS
2498/* non-recursive DFS pseudo code
2499 * 1 procedure DFS-iterative(G,v):
2500 * 2 label v as discovered
2501 * 3 let S be a stack
2502 * 4 S.push(v)
2503 * 5 while S is not empty
2504 * 6 t <- S.pop()
2505 * 7 if t is what we're looking for:
2506 * 8 return t
2507 * 9 for all edges e in G.adjacentEdges(t) do
2508 * 10 if edge e is already labelled
2509 * 11 continue with the next edge
2510 * 12 w <- G.adjacentVertex(t,e)
2511 * 13 if vertex w is not discovered and not explored
2512 * 14 label e as tree-edge
2513 * 15 label w as discovered
2514 * 16 S.push(w)
2515 * 17 continue at 5
2516 * 18 else if vertex w is discovered
2517 * 19 label e as back-edge
2518 * 20 else
2519 * 21 // vertex w is explored
2520 * 22 label e as forward- or cross-edge
2521 * 23 label t as explored
2522 * 24 S.pop()
2523 *
2524 * convention:
2525 * 0x10 - discovered
2526 * 0x11 - discovered and fall-through edge labelled
2527 * 0x12 - discovered and fall-through and branch edges labelled
2528 * 0x20 - explored
2529 */
2530
2531enum {
2532 DISCOVERED = 0x10,
2533 EXPLORED = 0x20,
2534 FALLTHROUGH = 1,
2535 BRANCH = 2,
2536};
2537
58e2af8b 2538#define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
f1bca824 2539
475fb78f
AS
2540static int *insn_stack; /* stack of insns to process */
2541static int cur_stack; /* current stack index */
2542static int *insn_state;
2543
2544/* t, w, e - match pseudo-code above:
2545 * t - index of current instruction
2546 * w - next instruction
2547 * e - edge
2548 */
58e2af8b 2549static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
475fb78f
AS
2550{
2551 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2552 return 0;
2553
2554 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2555 return 0;
2556
2557 if (w < 0 || w >= env->prog->len) {
2558 verbose("jump out of range from insn %d to %d\n", t, w);
2559 return -EINVAL;
2560 }
2561
f1bca824
AS
2562 if (e == BRANCH)
2563 /* mark branch target for state pruning */
2564 env->explored_states[w] = STATE_LIST_MARK;
2565
475fb78f
AS
2566 if (insn_state[w] == 0) {
2567 /* tree-edge */
2568 insn_state[t] = DISCOVERED | e;
2569 insn_state[w] = DISCOVERED;
2570 if (cur_stack >= env->prog->len)
2571 return -E2BIG;
2572 insn_stack[cur_stack++] = w;
2573 return 1;
2574 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2575 verbose("back-edge from insn %d to %d\n", t, w);
2576 return -EINVAL;
2577 } else if (insn_state[w] == EXPLORED) {
2578 /* forward- or cross-edge */
2579 insn_state[t] = DISCOVERED | e;
2580 } else {
2581 verbose("insn state internal bug\n");
2582 return -EFAULT;
2583 }
2584 return 0;
2585}
2586
2587/* non-recursive depth-first-search to detect loops in BPF program
2588 * loop == back-edge in directed graph
2589 */
58e2af8b 2590static int check_cfg(struct bpf_verifier_env *env)
475fb78f
AS
2591{
2592 struct bpf_insn *insns = env->prog->insnsi;
2593 int insn_cnt = env->prog->len;
2594 int ret = 0;
2595 int i, t;
2596
2597 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2598 if (!insn_state)
2599 return -ENOMEM;
2600
2601 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2602 if (!insn_stack) {
2603 kfree(insn_state);
2604 return -ENOMEM;
2605 }
2606
2607 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
2608 insn_stack[0] = 0; /* 0 is the first instruction */
2609 cur_stack = 1;
2610
2611peek_stack:
2612 if (cur_stack == 0)
2613 goto check_state;
2614 t = insn_stack[cur_stack - 1];
2615
2616 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
2617 u8 opcode = BPF_OP(insns[t].code);
2618
2619 if (opcode == BPF_EXIT) {
2620 goto mark_explored;
2621 } else if (opcode == BPF_CALL) {
2622 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2623 if (ret == 1)
2624 goto peek_stack;
2625 else if (ret < 0)
2626 goto err_free;
07016151
DB
2627 if (t + 1 < insn_cnt)
2628 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
2629 } else if (opcode == BPF_JA) {
2630 if (BPF_SRC(insns[t].code) != BPF_K) {
2631 ret = -EINVAL;
2632 goto err_free;
2633 }
2634 /* unconditional jump with single edge */
2635 ret = push_insn(t, t + insns[t].off + 1,
2636 FALLTHROUGH, env);
2637 if (ret == 1)
2638 goto peek_stack;
2639 else if (ret < 0)
2640 goto err_free;
f1bca824
AS
2641 /* tell verifier to check for equivalent states
2642 * after every call and jump
2643 */
c3de6317
AS
2644 if (t + 1 < insn_cnt)
2645 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
2646 } else {
2647 /* conditional jump with two edges */
3c2ce60b 2648 env->explored_states[t] = STATE_LIST_MARK;
475fb78f
AS
2649 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2650 if (ret == 1)
2651 goto peek_stack;
2652 else if (ret < 0)
2653 goto err_free;
2654
2655 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2656 if (ret == 1)
2657 goto peek_stack;
2658 else if (ret < 0)
2659 goto err_free;
2660 }
2661 } else {
2662 /* all other non-branch instructions with single
2663 * fall-through edge
2664 */
2665 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2666 if (ret == 1)
2667 goto peek_stack;
2668 else if (ret < 0)
2669 goto err_free;
2670 }
2671
2672mark_explored:
2673 insn_state[t] = EXPLORED;
2674 if (cur_stack-- <= 0) {
2675 verbose("pop stack internal bug\n");
2676 ret = -EFAULT;
2677 goto err_free;
2678 }
2679 goto peek_stack;
2680
2681check_state:
2682 for (i = 0; i < insn_cnt; i++) {
2683 if (insn_state[i] != EXPLORED) {
2684 verbose("unreachable insn %d\n", i);
2685 ret = -EINVAL;
2686 goto err_free;
2687 }
2688 }
2689 ret = 0; /* cfg looks good */
2690
2691err_free:
2692 kfree(insn_state);
2693 kfree(insn_stack);
2694 return ret;
2695}
2696
969bf05e
AS
2697/* the following conditions reduce the number of explored insns
2698 * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2699 */
1ad2f583
DB
2700static bool compare_ptrs_to_packet(struct bpf_verifier_env *env,
2701 struct bpf_reg_state *old,
58e2af8b 2702 struct bpf_reg_state *cur)
969bf05e
AS
2703{
2704 if (old->id != cur->id)
2705 return false;
2706
2707 /* old ptr_to_packet is more conservative, since it allows smaller
2708 * range. Ex:
2709 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2710 * old(off=0,r=10) means that with range=10 the verifier proceeded
2711 * further and found no issues with the program. Now we're in the same
2712 * spot with cur(off=0,r=20), so we're safe too, since anything further
2713 * will only be looking at most 10 bytes after this pointer.
2714 */
2715 if (old->off == cur->off && old->range < cur->range)
2716 return true;
2717
2718 /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2719 * since both cannot be used for packet access and safe(old)
2720 * pointer has smaller off that could be used for further
2721 * 'if (ptr > data_end)' check
2722 * Ex:
2723 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2724 * that we cannot access the packet.
2725 * The safe range is:
2726 * [ptr, ptr + range - off)
2727 * so whenever off >=range, it means no safe bytes from this pointer.
2728 * When comparing old->off <= cur->off, it means that older code
2729 * went with smaller offset and that offset was later
2730 * used to figure out the safe range after 'if (ptr > data_end)' check
2731 * Say, 'old' state was explored like:
2732 * ... R3(off=0, r=0)
2733 * R4 = R3 + 20
2734 * ... now R4(off=20,r=0) <-- here
2735 * if (R4 > data_end)
2736 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2737 * ... the code further went all the way to bpf_exit.
2738 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2739 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2740 * goes further, such cur_R4 will give larger safe packet range after
2741 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2742 * so they will be good with r=30 and we can prune the search.
2743 */
1ad2f583 2744 if (!env->strict_alignment && old->off <= cur->off &&
969bf05e
AS
2745 old->off >= old->range && cur->off >= cur->range)
2746 return true;
2747
2748 return false;
2749}
2750
f1bca824
AS
2751/* compare two verifier states
2752 *
2753 * all states stored in state_list are known to be valid, since
2754 * verifier reached 'bpf_exit' instruction through them
2755 *
2756 * this function is called when verifier exploring different branches of
2757 * execution popped from the state stack. If it sees an old state that has
2758 * more strict register state and more strict stack state then this execution
2759 * branch doesn't need to be explored further, since verifier already
2760 * concluded that more strict state leads to valid finish.
2761 *
2762 * Therefore two states are equivalent if register state is more conservative
2763 * and explored stack state is more conservative than the current one.
2764 * Example:
2765 * explored current
2766 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2767 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2768 *
2769 * In other words if current stack state (one being explored) has more
2770 * valid slots than old one that already passed validation, it means
2771 * the verifier can stop exploring and conclude that current state is valid too
2772 *
2773 * Similarly with registers. If explored state has register type as invalid
2774 * whereas register type in current state is meaningful, it means that
2775 * the current state will reach 'bpf_exit' instruction safely
2776 */
48461135
JB
2777static bool states_equal(struct bpf_verifier_env *env,
2778 struct bpf_verifier_state *old,
58e2af8b 2779 struct bpf_verifier_state *cur)
f1bca824 2780{
e2d2afe1 2781 bool varlen_map_access = env->varlen_map_value_access;
58e2af8b 2782 struct bpf_reg_state *rold, *rcur;
f1bca824
AS
2783 int i;
2784
2785 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
2786 rold = &old->regs[i];
2787 rcur = &cur->regs[i];
2788
2789 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2790 continue;
2791
48461135
JB
2792 /* If the ranges were not the same, but everything else was and
2793 * we didn't do a variable access into a map then we are a-ok.
2794 */
e2d2afe1 2795 if (!varlen_map_access &&
d2a4dd37 2796 memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0)
48461135
JB
2797 continue;
2798
e2d2afe1
JB
2799 /* If we didn't map access then again we don't care about the
2800 * mismatched range values and it's ok if our old type was
2801 * UNKNOWN and we didn't go to a NOT_INIT'ed reg.
2802 */
1a0dc1ac 2803 if (rold->type == NOT_INIT ||
e2d2afe1
JB
2804 (!varlen_map_access && rold->type == UNKNOWN_VALUE &&
2805 rcur->type != NOT_INIT))
1a0dc1ac
AS
2806 continue;
2807
3c2ce60b
DB
2808 /* Don't care about the reg->id in this case. */
2809 if (rold->type == PTR_TO_MAP_VALUE_OR_NULL &&
2810 rcur->type == PTR_TO_MAP_VALUE_OR_NULL &&
2811 rold->map_ptr == rcur->map_ptr)
2812 continue;
2813
969bf05e 2814 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
1ad2f583 2815 compare_ptrs_to_packet(env, rold, rcur))
969bf05e
AS
2816 continue;
2817
1a0dc1ac 2818 return false;
f1bca824
AS
2819 }
2820
2821 for (i = 0; i < MAX_BPF_STACK; i++) {
9c399760
AS
2822 if (old->stack_slot_type[i] == STACK_INVALID)
2823 continue;
2824 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2825 /* Ex: old explored (safe) state has STACK_SPILL in
2826 * this stack slot, but current has has STACK_MISC ->
2827 * this verifier states are not equivalent,
2828 * return false to continue verification of this path
2829 */
f1bca824 2830 return false;
9c399760
AS
2831 if (i % BPF_REG_SIZE)
2832 continue;
d25da6ca
DB
2833 if (old->stack_slot_type[i] != STACK_SPILL)
2834 continue;
9c399760
AS
2835 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2836 &cur->spilled_regs[i / BPF_REG_SIZE],
2837 sizeof(old->spilled_regs[0])))
2838 /* when explored and current stack slot types are
2839 * the same, check that stored pointers types
2840 * are the same as well.
2841 * Ex: explored safe path could have stored
58e2af8b 2842 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
9c399760 2843 * but current path has stored:
58e2af8b 2844 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
9c399760
AS
2845 * such verifier states are not equivalent.
2846 * return false to continue verification of this path
2847 */
2848 return false;
2849 else
2850 continue;
f1bca824
AS
2851 }
2852 return true;
2853}
2854
58e2af8b 2855static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 2856{
58e2af8b
JK
2857 struct bpf_verifier_state_list *new_sl;
2858 struct bpf_verifier_state_list *sl;
f1bca824
AS
2859
2860 sl = env->explored_states[insn_idx];
2861 if (!sl)
2862 /* this 'insn_idx' instruction wasn't marked, so we will not
2863 * be doing state search here
2864 */
2865 return 0;
2866
2867 while (sl != STATE_LIST_MARK) {
48461135 2868 if (states_equal(env, &sl->state, &env->cur_state))
f1bca824
AS
2869 /* reached equivalent register/stack state,
2870 * prune the search
2871 */
2872 return 1;
2873 sl = sl->next;
2874 }
2875
2876 /* there were no equivalent states, remember current one.
2877 * technically the current state is not proven to be safe yet,
2878 * but it will either reach bpf_exit (which means it's safe) or
2879 * it will be rejected. Since there are no loops, we won't be
2880 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2881 */
58e2af8b 2882 new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
f1bca824
AS
2883 if (!new_sl)
2884 return -ENOMEM;
2885
2886 /* add new state to the head of linked list */
2887 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2888 new_sl->next = env->explored_states[insn_idx];
2889 env->explored_states[insn_idx] = new_sl;
2890 return 0;
2891}
2892
13a27dfc
JK
2893static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2894 int insn_idx, int prev_insn_idx)
2895{
2896 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2897 return 0;
2898
2899 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2900}
2901
58e2af8b 2902static int do_check(struct bpf_verifier_env *env)
17a52670 2903{
58e2af8b 2904 struct bpf_verifier_state *state = &env->cur_state;
17a52670 2905 struct bpf_insn *insns = env->prog->insnsi;
58e2af8b 2906 struct bpf_reg_state *regs = state->regs;
17a52670
AS
2907 int insn_cnt = env->prog->len;
2908 int insn_idx, prev_insn_idx = 0;
2909 int insn_processed = 0;
2910 bool do_print_state = false;
2911
2912 init_reg_state(regs);
2913 insn_idx = 0;
48461135 2914 env->varlen_map_value_access = false;
17a52670
AS
2915 for (;;) {
2916 struct bpf_insn *insn;
2917 u8 class;
2918 int err;
2919
2920 if (insn_idx >= insn_cnt) {
2921 verbose("invalid insn idx %d insn_cnt %d\n",
2922 insn_idx, insn_cnt);
2923 return -EFAULT;
2924 }
2925
2926 insn = &insns[insn_idx];
2927 class = BPF_CLASS(insn->code);
2928
07016151 2929 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
bc1750f3 2930 verbose("BPF program is too large. Processed %d insn\n",
17a52670
AS
2931 insn_processed);
2932 return -E2BIG;
2933 }
2934
f1bca824
AS
2935 err = is_state_visited(env, insn_idx);
2936 if (err < 0)
2937 return err;
2938 if (err == 1) {
2939 /* found equivalent state, can prune the search */
2940 if (log_level) {
2941 if (do_print_state)
2942 verbose("\nfrom %d to %d: safe\n",
2943 prev_insn_idx, insn_idx);
2944 else
2945 verbose("%d: safe\n", insn_idx);
2946 }
2947 goto process_bpf_exit;
2948 }
2949
3c2ce60b
DB
2950 if (need_resched())
2951 cond_resched();
2952
c5fc9692
DM
2953 if (log_level > 1 || (log_level && do_print_state)) {
2954 if (log_level > 1)
2955 verbose("%d:", insn_idx);
2956 else
2957 verbose("\nfrom %d to %d:",
2958 prev_insn_idx, insn_idx);
1a0dc1ac 2959 print_verifier_state(&env->cur_state);
17a52670
AS
2960 do_print_state = false;
2961 }
2962
2963 if (log_level) {
2964 verbose("%d: ", insn_idx);
0d0e5769 2965 print_bpf_insn(env, insn);
17a52670
AS
2966 }
2967
13a27dfc
JK
2968 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2969 if (err)
2970 return err;
2971
17a52670 2972 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 2973 err = check_alu_op(env, insn);
17a52670
AS
2974 if (err)
2975 return err;
2976
2977 } else if (class == BPF_LDX) {
3df126f3 2978 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
2979
2980 /* check for reserved fields is already done */
2981
17a52670
AS
2982 /* check src operand */
2983 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2984 if (err)
2985 return err;
2986
2987 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2988 if (err)
2989 return err;
2990
725f9dcd
AS
2991 src_reg_type = regs[insn->src_reg].type;
2992
17a52670
AS
2993 /* check that memory (src_reg + off) is readable,
2994 * the state of dst_reg will be updated by this func
2995 */
2996 err = check_mem_access(env, insn->src_reg, insn->off,
2997 BPF_SIZE(insn->code), BPF_READ,
2998 insn->dst_reg);
2999 if (err)
3000 return err;
3001
ea2e7ce5
AS
3002 if (BPF_SIZE(insn->code) != BPF_W &&
3003 BPF_SIZE(insn->code) != BPF_DW) {
725f9dcd
AS
3004 insn_idx++;
3005 continue;
3006 }
9bac3d6d 3007
3df126f3
JK
3008 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
3009
3010 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
3011 /* saw a valid insn
3012 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 3013 * save type to validate intersecting paths
9bac3d6d 3014 */
3df126f3 3015 *prev_src_type = src_reg_type;
9bac3d6d 3016
3df126f3 3017 } else if (src_reg_type != *prev_src_type &&
9bac3d6d 3018 (src_reg_type == PTR_TO_CTX ||
3df126f3 3019 *prev_src_type == PTR_TO_CTX)) {
9bac3d6d
AS
3020 /* ABuser program is trying to use the same insn
3021 * dst_reg = *(u32*) (src_reg + off)
3022 * with different pointer types:
3023 * src_reg == ctx in one branch and
3024 * src_reg == stack|map in some other branch.
3025 * Reject it.
3026 */
3027 verbose("same insn cannot be used with different pointers\n");
3028 return -EINVAL;
3029 }
3030
17a52670 3031 } else if (class == BPF_STX) {
3df126f3 3032 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 3033
17a52670
AS
3034 if (BPF_MODE(insn->code) == BPF_XADD) {
3035 err = check_xadd(env, insn);
3036 if (err)
3037 return err;
3038 insn_idx++;
3039 continue;
3040 }
3041
17a52670
AS
3042 /* check src1 operand */
3043 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
3044 if (err)
3045 return err;
3046 /* check src2 operand */
3047 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3048 if (err)
3049 return err;
3050
d691f9e8
AS
3051 dst_reg_type = regs[insn->dst_reg].type;
3052
17a52670
AS
3053 /* check that memory (dst_reg + off) is writeable */
3054 err = check_mem_access(env, insn->dst_reg, insn->off,
3055 BPF_SIZE(insn->code), BPF_WRITE,
3056 insn->src_reg);
3057 if (err)
3058 return err;
3059
3df126f3
JK
3060 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
3061
3062 if (*prev_dst_type == NOT_INIT) {
3063 *prev_dst_type = dst_reg_type;
3064 } else if (dst_reg_type != *prev_dst_type &&
d691f9e8 3065 (dst_reg_type == PTR_TO_CTX ||
3df126f3 3066 *prev_dst_type == PTR_TO_CTX)) {
d691f9e8
AS
3067 verbose("same insn cannot be used with different pointers\n");
3068 return -EINVAL;
3069 }
3070
17a52670
AS
3071 } else if (class == BPF_ST) {
3072 if (BPF_MODE(insn->code) != BPF_MEM ||
3073 insn->src_reg != BPF_REG_0) {
3074 verbose("BPF_ST uses reserved fields\n");
3075 return -EINVAL;
3076 }
3077 /* check src operand */
3078 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3079 if (err)
3080 return err;
3081
3082 /* check that memory (dst_reg + off) is writeable */
3083 err = check_mem_access(env, insn->dst_reg, insn->off,
3084 BPF_SIZE(insn->code), BPF_WRITE,
3085 -1);
3086 if (err)
3087 return err;
3088
3089 } else if (class == BPF_JMP) {
3090 u8 opcode = BPF_OP(insn->code);
3091
3092 if (opcode == BPF_CALL) {
3093 if (BPF_SRC(insn->code) != BPF_K ||
3094 insn->off != 0 ||
3095 insn->src_reg != BPF_REG_0 ||
3096 insn->dst_reg != BPF_REG_0) {
3097 verbose("BPF_CALL uses reserved fields\n");
3098 return -EINVAL;
3099 }
3100
81ed18ab 3101 err = check_call(env, insn->imm, insn_idx);
17a52670
AS
3102 if (err)
3103 return err;
3104
3105 } else if (opcode == BPF_JA) {
3106 if (BPF_SRC(insn->code) != BPF_K ||
3107 insn->imm != 0 ||
3108 insn->src_reg != BPF_REG_0 ||
3109 insn->dst_reg != BPF_REG_0) {
3110 verbose("BPF_JA uses reserved fields\n");
3111 return -EINVAL;
3112 }
3113
3114 insn_idx += insn->off + 1;
3115 continue;
3116
3117 } else if (opcode == BPF_EXIT) {
3118 if (BPF_SRC(insn->code) != BPF_K ||
3119 insn->imm != 0 ||
3120 insn->src_reg != BPF_REG_0 ||
3121 insn->dst_reg != BPF_REG_0) {
3122 verbose("BPF_EXIT uses reserved fields\n");
3123 return -EINVAL;
3124 }
3125
3126 /* eBPF calling convetion is such that R0 is used
3127 * to return the value from eBPF program.
3128 * Make sure that it's readable at this time
3129 * of bpf_exit, which means that program wrote
3130 * something into it earlier
3131 */
3132 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
3133 if (err)
3134 return err;
3135
1be7f75d
AS
3136 if (is_pointer_value(env, BPF_REG_0)) {
3137 verbose("R0 leaks addr as return value\n");
3138 return -EACCES;
3139 }
3140
f1bca824 3141process_bpf_exit:
17a52670
AS
3142 insn_idx = pop_stack(env, &prev_insn_idx);
3143 if (insn_idx < 0) {
3144 break;
3145 } else {
3146 do_print_state = true;
3147 continue;
3148 }
3149 } else {
3150 err = check_cond_jmp_op(env, insn, &insn_idx);
3151 if (err)
3152 return err;
3153 }
3154 } else if (class == BPF_LD) {
3155 u8 mode = BPF_MODE(insn->code);
3156
3157 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
3158 err = check_ld_abs(env, insn);
3159 if (err)
3160 return err;
3161
17a52670
AS
3162 } else if (mode == BPF_IMM) {
3163 err = check_ld_imm(env, insn);
3164 if (err)
3165 return err;
3166
3167 insn_idx++;
3168 } else {
3169 verbose("invalid BPF_LD mode\n");
3170 return -EINVAL;
3171 }
48461135 3172 reset_reg_range_values(regs, insn->dst_reg);
17a52670
AS
3173 } else {
3174 verbose("unknown insn class %d\n", class);
3175 return -EINVAL;
3176 }
3177
3178 insn_idx++;
3179 }
3180
8726679a
AS
3181 verbose("processed %d insns, stack depth %d\n",
3182 insn_processed, env->prog->aux->stack_depth);
17a52670
AS
3183 return 0;
3184}
3185
56f668df
MKL
3186static int check_map_prealloc(struct bpf_map *map)
3187{
3188 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
3189 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
3190 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
3191 !(map->map_flags & BPF_F_NO_PREALLOC);
3192}
3193
fdc15d38
AS
3194static int check_map_prog_compatibility(struct bpf_map *map,
3195 struct bpf_prog *prog)
3196
3197{
56f668df
MKL
3198 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
3199 * preallocated hash maps, since doing memory allocation
3200 * in overflow_handler can crash depending on where nmi got
3201 * triggered.
3202 */
3203 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
3204 if (!check_map_prealloc(map)) {
3205 verbose("perf_event programs can only use preallocated hash map\n");
3206 return -EINVAL;
3207 }
3208 if (map->inner_map_meta &&
3209 !check_map_prealloc(map->inner_map_meta)) {
3210 verbose("perf_event programs can only use preallocated inner hash map\n");
3211 return -EINVAL;
3212 }
fdc15d38
AS
3213 }
3214 return 0;
3215}
3216
0246e64d
AS
3217/* look for pseudo eBPF instructions that access map FDs and
3218 * replace them with actual map pointers
3219 */
58e2af8b 3220static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
0246e64d
AS
3221{
3222 struct bpf_insn *insn = env->prog->insnsi;
3223 int insn_cnt = env->prog->len;
fdc15d38 3224 int i, j, err;
0246e64d 3225
f1f7714e 3226 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
3227 if (err)
3228 return err;
3229
0246e64d 3230 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 3231 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 3232 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9bac3d6d
AS
3233 verbose("BPF_LDX uses reserved fields\n");
3234 return -EINVAL;
3235 }
3236
d691f9e8
AS
3237 if (BPF_CLASS(insn->code) == BPF_STX &&
3238 ((BPF_MODE(insn->code) != BPF_MEM &&
3239 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
3240 verbose("BPF_STX uses reserved fields\n");
3241 return -EINVAL;
3242 }
3243
0246e64d
AS
3244 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
3245 struct bpf_map *map;
3246 struct fd f;
3247
3248 if (i == insn_cnt - 1 || insn[1].code != 0 ||
3249 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
3250 insn[1].off != 0) {
3251 verbose("invalid bpf_ld_imm64 insn\n");
3252 return -EINVAL;
3253 }
3254
3255 if (insn->src_reg == 0)
3256 /* valid generic load 64-bit imm */
3257 goto next_insn;
3258
3259 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
3260 verbose("unrecognized bpf_ld_imm64 insn\n");
3261 return -EINVAL;
3262 }
3263
3264 f = fdget(insn->imm);
c2101297 3265 map = __bpf_map_get(f);
0246e64d
AS
3266 if (IS_ERR(map)) {
3267 verbose("fd %d is not pointing to valid bpf_map\n",
3268 insn->imm);
0246e64d
AS
3269 return PTR_ERR(map);
3270 }
3271
fdc15d38
AS
3272 err = check_map_prog_compatibility(map, env->prog);
3273 if (err) {
3274 fdput(f);
3275 return err;
3276 }
3277
0246e64d
AS
3278 /* store map pointer inside BPF_LD_IMM64 instruction */
3279 insn[0].imm = (u32) (unsigned long) map;
3280 insn[1].imm = ((u64) (unsigned long) map) >> 32;
3281
3282 /* check whether we recorded this map already */
3283 for (j = 0; j < env->used_map_cnt; j++)
3284 if (env->used_maps[j] == map) {
3285 fdput(f);
3286 goto next_insn;
3287 }
3288
3289 if (env->used_map_cnt >= MAX_USED_MAPS) {
3290 fdput(f);
3291 return -E2BIG;
3292 }
3293
0246e64d
AS
3294 /* hold the map. If the program is rejected by verifier,
3295 * the map will be released by release_maps() or it
3296 * will be used by the valid program until it's unloaded
3297 * and all maps are released in free_bpf_prog_info()
3298 */
92117d84
AS
3299 map = bpf_map_inc(map, false);
3300 if (IS_ERR(map)) {
3301 fdput(f);
3302 return PTR_ERR(map);
3303 }
3304 env->used_maps[env->used_map_cnt++] = map;
3305
0246e64d
AS
3306 fdput(f);
3307next_insn:
3308 insn++;
3309 i++;
3310 }
3311 }
3312
3313 /* now all pseudo BPF_LD_IMM64 instructions load valid
3314 * 'struct bpf_map *' into a register instead of user map_fd.
3315 * These pointers will be used later by verifier to validate map access.
3316 */
3317 return 0;
3318}
3319
3320/* drop refcnt of maps used by the rejected program */
58e2af8b 3321static void release_maps(struct bpf_verifier_env *env)
0246e64d
AS
3322{
3323 int i;
3324
3325 for (i = 0; i < env->used_map_cnt; i++)
3326 bpf_map_put(env->used_maps[i]);
3327}
3328
3329/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 3330static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
3331{
3332 struct bpf_insn *insn = env->prog->insnsi;
3333 int insn_cnt = env->prog->len;
3334 int i;
3335
3336 for (i = 0; i < insn_cnt; i++, insn++)
3337 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
3338 insn->src_reg = 0;
3339}
3340
8041902d
AS
3341/* single env->prog->insni[off] instruction was replaced with the range
3342 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
3343 * [0, off) and [off, end) to new locations, so the patched range stays zero
3344 */
3345static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
3346 u32 off, u32 cnt)
3347{
3348 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
3349
3350 if (cnt == 1)
3351 return 0;
3352 new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
3353 if (!new_data)
3354 return -ENOMEM;
3355 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
3356 memcpy(new_data + off + cnt - 1, old_data + off,
3357 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
3358 env->insn_aux_data = new_data;
3359 vfree(old_data);
3360 return 0;
3361}
3362
3363static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
3364 const struct bpf_insn *patch, u32 len)
3365{
3366 struct bpf_prog *new_prog;
3367
3368 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
3369 if (!new_prog)
3370 return NULL;
3371 if (adjust_insn_aux_data(env, new_prog->len, off, len))
3372 return NULL;
3373 return new_prog;
3374}
3375
9bac3d6d
AS
3376/* convert load instructions that access fields of 'struct __sk_buff'
3377 * into sequence of instructions that access fields of 'struct sk_buff'
3378 */
58e2af8b 3379static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 3380{
36bbef52 3381 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
3df126f3 3382 const int insn_cnt = env->prog->len;
36bbef52 3383 struct bpf_insn insn_buf[16], *insn;
9bac3d6d 3384 struct bpf_prog *new_prog;
d691f9e8 3385 enum bpf_access_type type;
3df126f3 3386 int i, cnt, delta = 0;
9bac3d6d 3387
36bbef52
DB
3388 if (ops->gen_prologue) {
3389 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
3390 env->prog);
3391 if (cnt >= ARRAY_SIZE(insn_buf)) {
3392 verbose("bpf verifier is misconfigured\n");
3393 return -EINVAL;
3394 } else if (cnt) {
8041902d 3395 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
3396 if (!new_prog)
3397 return -ENOMEM;
8041902d 3398
36bbef52 3399 env->prog = new_prog;
3df126f3 3400 delta += cnt - 1;
36bbef52
DB
3401 }
3402 }
3403
3404 if (!ops->convert_ctx_access)
9bac3d6d
AS
3405 return 0;
3406
3df126f3 3407 insn = env->prog->insnsi + delta;
36bbef52 3408
9bac3d6d 3409 for (i = 0; i < insn_cnt; i++, insn++) {
62c7989b
DB
3410 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
3411 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
3412 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 3413 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 3414 type = BPF_READ;
62c7989b
DB
3415 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
3416 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
3417 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 3418 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
3419 type = BPF_WRITE;
3420 else
9bac3d6d
AS
3421 continue;
3422
8041902d 3423 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
9bac3d6d 3424 continue;
9bac3d6d 3425
6b8cc1d1 3426 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog);
9bac3d6d
AS
3427 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3428 verbose("bpf verifier is misconfigured\n");
3429 return -EINVAL;
3430 }
3431
8041902d 3432 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
3433 if (!new_prog)
3434 return -ENOMEM;
3435
3df126f3 3436 delta += cnt - 1;
9bac3d6d
AS
3437
3438 /* keep walking new program and skip insns we just inserted */
3439 env->prog = new_prog;
3df126f3 3440 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
3441 }
3442
3443 return 0;
3444}
3445
79741b3b 3446/* fixup insn->imm field of bpf_call instructions
81ed18ab 3447 * and inline eligible helpers as explicit sequence of BPF instructions
e245c5c6
AS
3448 *
3449 * this function is called after eBPF program passed verification
3450 */
79741b3b 3451static int fixup_bpf_calls(struct bpf_verifier_env *env)
e245c5c6 3452{
79741b3b
AS
3453 struct bpf_prog *prog = env->prog;
3454 struct bpf_insn *insn = prog->insnsi;
e245c5c6 3455 const struct bpf_func_proto *fn;
79741b3b 3456 const int insn_cnt = prog->len;
81ed18ab
AS
3457 struct bpf_insn insn_buf[16];
3458 struct bpf_prog *new_prog;
3459 struct bpf_map *map_ptr;
3460 int i, cnt, delta = 0;
e245c5c6 3461
79741b3b
AS
3462 for (i = 0; i < insn_cnt; i++, insn++) {
3463 if (insn->code != (BPF_JMP | BPF_CALL))
3464 continue;
e245c5c6 3465
79741b3b
AS
3466 if (insn->imm == BPF_FUNC_get_route_realm)
3467 prog->dst_needed = 1;
3468 if (insn->imm == BPF_FUNC_get_prandom_u32)
3469 bpf_user_rnd_init_once();
79741b3b 3470 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
3471 /* If we tail call into other programs, we
3472 * cannot make any assumptions since they can
3473 * be replaced dynamically during runtime in
3474 * the program array.
3475 */
3476 prog->cb_access = 1;
80a58d02 3477 env->prog->aux->stack_depth = MAX_BPF_STACK;
7b9f6da1 3478
79741b3b
AS
3479 /* mark bpf_tail_call as different opcode to avoid
3480 * conditional branch in the interpeter for every normal
3481 * call and to prevent accidental JITing by JIT compiler
3482 * that doesn't support bpf_tail_call yet
e245c5c6 3483 */
79741b3b 3484 insn->imm = 0;
71189fa9 3485 insn->code = BPF_JMP | BPF_TAIL_CALL;
79741b3b
AS
3486 continue;
3487 }
e245c5c6 3488
81ed18ab
AS
3489 if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) {
3490 map_ptr = env->insn_aux_data[i + delta].map_ptr;
fad73a1a
MKL
3491 if (map_ptr == BPF_MAP_PTR_POISON ||
3492 !map_ptr->ops->map_gen_lookup)
81ed18ab
AS
3493 goto patch_call_imm;
3494
3495 cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
3496 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3497 verbose("bpf verifier is misconfigured\n");
3498 return -EINVAL;
3499 }
3500
3501 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
3502 cnt);
3503 if (!new_prog)
3504 return -ENOMEM;
3505
3506 delta += cnt - 1;
3507
3508 /* keep walking new program and skip insns we just inserted */
3509 env->prog = prog = new_prog;
3510 insn = new_prog->insnsi + i + delta;
3511 continue;
3512 }
3513
3514patch_call_imm:
79741b3b
AS
3515 fn = prog->aux->ops->get_func_proto(insn->imm);
3516 /* all functions that have prototype and verifier allowed
3517 * programs to call them, must be real in-kernel functions
3518 */
3519 if (!fn->func) {
3520 verbose("kernel subsystem misconfigured func %s#%d\n",
3521 func_id_name(insn->imm), insn->imm);
3522 return -EFAULT;
e245c5c6 3523 }
79741b3b 3524 insn->imm = fn->func - __bpf_call_base;
e245c5c6 3525 }
e245c5c6 3526
79741b3b
AS
3527 return 0;
3528}
e245c5c6 3529
58e2af8b 3530static void free_states(struct bpf_verifier_env *env)
f1bca824 3531{
58e2af8b 3532 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
3533 int i;
3534
3535 if (!env->explored_states)
3536 return;
3537
3538 for (i = 0; i < env->prog->len; i++) {
3539 sl = env->explored_states[i];
3540
3541 if (sl)
3542 while (sl != STATE_LIST_MARK) {
3543 sln = sl->next;
3544 kfree(sl);
3545 sl = sln;
3546 }
3547 }
3548
3549 kfree(env->explored_states);
3550}
3551
9bac3d6d 3552int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
51580e79 3553{
cbd35700 3554 char __user *log_ubuf = NULL;
58e2af8b 3555 struct bpf_verifier_env *env;
51580e79
AS
3556 int ret = -EINVAL;
3557
58e2af8b 3558 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
3559 * allocate/free it every time bpf_check() is called
3560 */
58e2af8b 3561 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
3562 if (!env)
3563 return -ENOMEM;
3564
3df126f3
JK
3565 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3566 (*prog)->len);
3567 ret = -ENOMEM;
3568 if (!env->insn_aux_data)
3569 goto err_free_env;
9bac3d6d 3570 env->prog = *prog;
0246e64d 3571
cbd35700
AS
3572 /* grab the mutex to protect few globals used by verifier */
3573 mutex_lock(&bpf_verifier_lock);
3574
3575 if (attr->log_level || attr->log_buf || attr->log_size) {
3576 /* user requested verbose verifier output
3577 * and supplied buffer to store the verification trace
3578 */
3579 log_level = attr->log_level;
3580 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
3581 log_size = attr->log_size;
3582 log_len = 0;
3583
3584 ret = -EINVAL;
3585 /* log_* values have to be sane */
3586 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
3587 log_level == 0 || log_ubuf == NULL)
3df126f3 3588 goto err_unlock;
cbd35700
AS
3589
3590 ret = -ENOMEM;
3591 log_buf = vmalloc(log_size);
3592 if (!log_buf)
3df126f3 3593 goto err_unlock;
cbd35700
AS
3594 } else {
3595 log_level = 0;
3596 }
1ad2f583
DB
3597
3598 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
3599 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 3600 env->strict_alignment = true;
cbd35700 3601
0246e64d
AS
3602 ret = replace_map_fd_with_map_ptr(env);
3603 if (ret < 0)
3604 goto skip_full_check;
3605
9bac3d6d 3606 env->explored_states = kcalloc(env->prog->len,
58e2af8b 3607 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
3608 GFP_USER);
3609 ret = -ENOMEM;
3610 if (!env->explored_states)
3611 goto skip_full_check;
3612
475fb78f
AS
3613 ret = check_cfg(env);
3614 if (ret < 0)
3615 goto skip_full_check;
3616
1be7f75d
AS
3617 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3618
17a52670 3619 ret = do_check(env);
cbd35700 3620
0246e64d 3621skip_full_check:
17a52670 3622 while (pop_stack(env, NULL) >= 0);
f1bca824 3623 free_states(env);
0246e64d 3624
9bac3d6d
AS
3625 if (ret == 0)
3626 /* program is valid, convert *(u32*)(ctx + off) accesses */
3627 ret = convert_ctx_accesses(env);
3628
e245c5c6 3629 if (ret == 0)
79741b3b 3630 ret = fixup_bpf_calls(env);
e245c5c6 3631
cbd35700
AS
3632 if (log_level && log_len >= log_size - 1) {
3633 BUG_ON(log_len >= log_size);
3634 /* verifier log exceeded user supplied buffer */
3635 ret = -ENOSPC;
3636 /* fall through to return what was recorded */
3637 }
3638
3639 /* copy verifier log back to user space including trailing zero */
3640 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
3641 ret = -EFAULT;
3642 goto free_log_buf;
3643 }
3644
0246e64d
AS
3645 if (ret == 0 && env->used_map_cnt) {
3646 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
3647 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
3648 sizeof(env->used_maps[0]),
3649 GFP_KERNEL);
0246e64d 3650
9bac3d6d 3651 if (!env->prog->aux->used_maps) {
0246e64d
AS
3652 ret = -ENOMEM;
3653 goto free_log_buf;
3654 }
3655
9bac3d6d 3656 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 3657 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 3658 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
3659
3660 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
3661 * bpf_ld_imm64 instructions
3662 */
3663 convert_pseudo_ld_imm64(env);
3664 }
cbd35700
AS
3665
3666free_log_buf:
3667 if (log_level)
3668 vfree(log_buf);
9bac3d6d 3669 if (!env->prog->aux->used_maps)
0246e64d
AS
3670 /* if we didn't copy map pointers into bpf_prog_info, release
3671 * them now. Otherwise free_bpf_prog_info() will release them.
3672 */
3673 release_maps(env);
9bac3d6d 3674 *prog = env->prog;
3df126f3 3675err_unlock:
cbd35700 3676 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
3677 vfree(env->insn_aux_data);
3678err_free_env:
3679 kfree(env);
51580e79
AS
3680 return ret;
3681}
13a27dfc
JK
3682
3683int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
3684 void *priv)
3685{
3686 struct bpf_verifier_env *env;
3687 int ret;
3688
3689 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3690 if (!env)
3691 return -ENOMEM;
3692
3693 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3694 prog->len);
3695 ret = -ENOMEM;
3696 if (!env->insn_aux_data)
3697 goto err_free_env;
3698 env->prog = prog;
3699 env->analyzer_ops = ops;
3700 env->analyzer_priv = priv;
3701
3702 /* grab the mutex to protect few globals used by verifier */
3703 mutex_lock(&bpf_verifier_lock);
3704
3705 log_level = 0;
1ad2f583 3706
e07b98d9 3707 env->strict_alignment = false;
1ad2f583
DB
3708 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
3709 env->strict_alignment = true;
13a27dfc
JK
3710
3711 env->explored_states = kcalloc(env->prog->len,
3712 sizeof(struct bpf_verifier_state_list *),
3713 GFP_KERNEL);
3714 ret = -ENOMEM;
3715 if (!env->explored_states)
3716 goto skip_full_check;
3717
3718 ret = check_cfg(env);
3719 if (ret < 0)
3720 goto skip_full_check;
3721
3722 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3723
3724 ret = do_check(env);
3725
3726skip_full_check:
3727 while (pop_stack(env, NULL) >= 0);
3728 free_states(env);
3729
3730 mutex_unlock(&bpf_verifier_lock);
3731 vfree(env->insn_aux_data);
3732err_free_env:
3733 kfree(env);
3734 return ret;
3735}
3736EXPORT_SYMBOL_GPL(bpf_analyzer);