]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - kernel/bpf/verifier.c
bpf: cleanup verifier code
[mirror_ubuntu-hirsute-kernel.git] / kernel / bpf / verifier.c
CommitLineData
51580e79
AS
1/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
6 *
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
11 */
12#include <linux/kernel.h>
13#include <linux/types.h>
14#include <linux/slab.h>
15#include <linux/bpf.h>
16#include <linux/filter.h>
17#include <net/netlink.h>
18#include <linux/file.h>
19#include <linux/vmalloc.h>
20
21/* bpf_check() is a static code analyzer that walks eBPF program
22 * instruction by instruction and updates register/stack state.
23 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
24 *
25 * The first pass is depth-first-search to check that the program is a DAG.
26 * It rejects the following programs:
27 * - larger than BPF_MAXINSNS insns
28 * - if loop is present (detected via back-edge)
29 * - unreachable insns exist (shouldn't be a forest. program = one function)
30 * - out of bounds or malformed jumps
31 * The second pass is all possible path descent from the 1st insn.
32 * Since it's analyzing all pathes through the program, the length of the
33 * analysis is limited to 32k insn, which may be hit even if total number of
34 * insn is less then 4K, but there are too many branches that change stack/regs.
35 * Number of 'branches to be analyzed' is limited to 1k
36 *
37 * On entry to each instruction, each register has a type, and the instruction
38 * changes the types of the registers depending on instruction semantics.
39 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
40 * copied to R1.
41 *
42 * All registers are 64-bit.
43 * R0 - return register
44 * R1-R5 argument passing registers
45 * R6-R9 callee saved registers
46 * R10 - frame pointer read-only
47 *
48 * At the start of BPF program the register R1 contains a pointer to bpf_context
49 * and has type PTR_TO_CTX.
50 *
51 * Verifier tracks arithmetic operations on pointers in case:
52 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
53 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
54 * 1st insn copies R10 (which has FRAME_PTR) type into R1
55 * and 2nd arithmetic instruction is pattern matched to recognize
56 * that it wants to construct a pointer to some element within stack.
57 * So after 2nd insn, the register R1 has type PTR_TO_STACK
58 * (and -20 constant is saved for further stack bounds checking).
59 * Meaning that this reg is a pointer to stack plus known immediate constant.
60 *
61 * Most of the time the registers have UNKNOWN_VALUE type, which
62 * means the register has some value, but it's not a valid pointer.
63 * (like pointer plus pointer becomes UNKNOWN_VALUE type)
64 *
65 * When verifier sees load or store instructions the type of base register
66 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
67 * types recognized by check_mem_access() function.
68 *
69 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
70 * and the range of [ptr, ptr + map's value_size) is accessible.
71 *
72 * registers used to pass values to function calls are checked against
73 * function argument constraints.
74 *
75 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
76 * It means that the register type passed to this function must be
77 * PTR_TO_STACK and it will be used inside the function as
78 * 'pointer to map element key'
79 *
80 * For example the argument constraints for bpf_map_lookup_elem():
81 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
82 * .arg1_type = ARG_CONST_MAP_PTR,
83 * .arg2_type = ARG_PTR_TO_MAP_KEY,
84 *
85 * ret_type says that this function returns 'pointer to map elem value or null'
86 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
87 * 2nd argument should be a pointer to stack, which will be used inside
88 * the helper function as a pointer to map element key.
89 *
90 * On the kernel side the helper function looks like:
91 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
92 * {
93 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
94 * void *key = (void *) (unsigned long) r2;
95 * void *value;
96 *
97 * here kernel can access 'key' and 'map' pointers safely, knowing that
98 * [key, key + map->key_size) bytes are valid and were initialized on
99 * the stack of eBPF program.
100 * }
101 *
102 * Corresponding eBPF program may look like:
103 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
104 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
105 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
106 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
107 * here verifier looks at prototype of map_lookup_elem() and sees:
108 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
109 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
110 *
111 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
112 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
113 * and were initialized prior to this call.
114 * If it's ok, then verifier allows this BPF_CALL insn and looks at
115 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
116 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
117 * returns ether pointer to map value or NULL.
118 *
119 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
120 * insn, the register holding that pointer in the true branch changes state to
121 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
122 * branch. See check_cond_jmp_op().
123 *
124 * After the call R0 is set to return type of the function and registers R1-R5
125 * are set to NOT_INIT to indicate that they are no longer readable.
126 */
127
17a52670
AS
128/* types of values stored in eBPF registers */
129enum bpf_reg_type {
130 NOT_INIT = 0, /* nothing was written into register */
131 UNKNOWN_VALUE, /* reg doesn't contain a valid pointer */
132 PTR_TO_CTX, /* reg points to bpf_context */
133 CONST_PTR_TO_MAP, /* reg points to struct bpf_map */
134 PTR_TO_MAP_VALUE, /* reg points to map element value */
135 PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */
136 FRAME_PTR, /* reg == frame_pointer */
137 PTR_TO_STACK, /* reg == frame_pointer + imm */
138 CONST_IMM, /* constant integer value */
139};
140
141struct reg_state {
142 enum bpf_reg_type type;
143 union {
144 /* valid when type == CONST_IMM | PTR_TO_STACK */
4923ec0b 145 long imm;
17a52670
AS
146
147 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
148 * PTR_TO_MAP_VALUE_OR_NULL
149 */
150 struct bpf_map *map_ptr;
151 };
152};
153
154enum bpf_stack_slot_type {
155 STACK_INVALID, /* nothing was stored in this stack slot */
9c399760 156 STACK_SPILL, /* register spilled into stack */
17a52670
AS
157 STACK_MISC /* BPF program wrote some data into this slot */
158};
159
9c399760 160#define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
17a52670
AS
161
162/* state of the program:
163 * type of all registers and stack info
164 */
165struct verifier_state {
166 struct reg_state regs[MAX_BPF_REG];
9c399760
AS
167 u8 stack_slot_type[MAX_BPF_STACK];
168 struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE];
17a52670
AS
169};
170
171/* linked list of verifier states used to prune search */
172struct verifier_state_list {
173 struct verifier_state state;
174 struct verifier_state_list *next;
175};
176
177/* verifier_state + insn_idx are pushed to stack when branch is encountered */
178struct verifier_stack_elem {
179 /* verifer state is 'st'
180 * before processing instruction 'insn_idx'
181 * and after processing instruction 'prev_insn_idx'
182 */
183 struct verifier_state st;
184 int insn_idx;
185 int prev_insn_idx;
186 struct verifier_stack_elem *next;
187};
188
0246e64d
AS
189#define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
190
cbd35700
AS
191/* single container for all structs
192 * one verifier_env per bpf_check() call
193 */
194struct verifier_env {
0246e64d 195 struct bpf_prog *prog; /* eBPF program being verified */
17a52670
AS
196 struct verifier_stack_elem *head; /* stack of verifier states to be processed */
197 int stack_size; /* number of states to be processed */
198 struct verifier_state cur_state; /* current verifier state */
f1bca824 199 struct verifier_state_list **explored_states; /* search pruning optimization */
0246e64d
AS
200 struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
201 u32 used_map_cnt; /* number of used maps */
1be7f75d 202 bool allow_ptr_leaks;
cbd35700
AS
203};
204
07016151
DB
205#define BPF_COMPLEXITY_LIMIT_INSNS 65536
206#define BPF_COMPLEXITY_LIMIT_STACK 1024
207
33ff9823
DB
208struct bpf_call_arg_meta {
209 struct bpf_map *map_ptr;
435faee1
DB
210 bool raw_mode;
211 int regno;
212 int access_size;
33ff9823
DB
213};
214
cbd35700
AS
215/* verbose verifier prints what it's seeing
216 * bpf_check() is called under lock, so no race to access these global vars
217 */
218static u32 log_level, log_size, log_len;
219static char *log_buf;
220
221static DEFINE_MUTEX(bpf_verifier_lock);
222
223/* log_level controls verbosity level of eBPF verifier.
224 * verbose() is used to dump the verification trace to the log, so the user
225 * can figure out what's wrong with the program
226 */
1d056d9c 227static __printf(1, 2) void verbose(const char *fmt, ...)
cbd35700
AS
228{
229 va_list args;
230
231 if (log_level == 0 || log_len >= log_size - 1)
232 return;
233
234 va_start(args, fmt);
235 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
236 va_end(args);
237}
238
17a52670
AS
239/* string representation of 'enum bpf_reg_type' */
240static const char * const reg_type_str[] = {
241 [NOT_INIT] = "?",
242 [UNKNOWN_VALUE] = "inv",
243 [PTR_TO_CTX] = "ctx",
244 [CONST_PTR_TO_MAP] = "map_ptr",
245 [PTR_TO_MAP_VALUE] = "map_value",
246 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
247 [FRAME_PTR] = "fp",
248 [PTR_TO_STACK] = "fp",
249 [CONST_IMM] = "imm",
250};
251
1a0dc1ac 252static void print_verifier_state(struct verifier_state *state)
17a52670 253{
1a0dc1ac 254 struct reg_state *reg;
17a52670
AS
255 enum bpf_reg_type t;
256 int i;
257
258 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
259 reg = &state->regs[i];
260 t = reg->type;
17a52670
AS
261 if (t == NOT_INIT)
262 continue;
263 verbose(" R%d=%s", i, reg_type_str[t]);
264 if (t == CONST_IMM || t == PTR_TO_STACK)
1a0dc1ac 265 verbose("%ld", reg->imm);
17a52670
AS
266 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
267 t == PTR_TO_MAP_VALUE_OR_NULL)
268 verbose("(ks=%d,vs=%d)",
1a0dc1ac
AS
269 reg->map_ptr->key_size,
270 reg->map_ptr->value_size);
17a52670 271 }
9c399760 272 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1a0dc1ac 273 if (state->stack_slot_type[i] == STACK_SPILL)
17a52670 274 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
1a0dc1ac 275 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
17a52670
AS
276 }
277 verbose("\n");
278}
279
cbd35700
AS
280static const char *const bpf_class_string[] = {
281 [BPF_LD] = "ld",
282 [BPF_LDX] = "ldx",
283 [BPF_ST] = "st",
284 [BPF_STX] = "stx",
285 [BPF_ALU] = "alu",
286 [BPF_JMP] = "jmp",
287 [BPF_RET] = "BUG",
288 [BPF_ALU64] = "alu64",
289};
290
687f0715 291static const char *const bpf_alu_string[16] = {
cbd35700
AS
292 [BPF_ADD >> 4] = "+=",
293 [BPF_SUB >> 4] = "-=",
294 [BPF_MUL >> 4] = "*=",
295 [BPF_DIV >> 4] = "/=",
296 [BPF_OR >> 4] = "|=",
297 [BPF_AND >> 4] = "&=",
298 [BPF_LSH >> 4] = "<<=",
299 [BPF_RSH >> 4] = ">>=",
300 [BPF_NEG >> 4] = "neg",
301 [BPF_MOD >> 4] = "%=",
302 [BPF_XOR >> 4] = "^=",
303 [BPF_MOV >> 4] = "=",
304 [BPF_ARSH >> 4] = "s>>=",
305 [BPF_END >> 4] = "endian",
306};
307
308static const char *const bpf_ldst_string[] = {
309 [BPF_W >> 3] = "u32",
310 [BPF_H >> 3] = "u16",
311 [BPF_B >> 3] = "u8",
312 [BPF_DW >> 3] = "u64",
313};
314
687f0715 315static const char *const bpf_jmp_string[16] = {
cbd35700
AS
316 [BPF_JA >> 4] = "jmp",
317 [BPF_JEQ >> 4] = "==",
318 [BPF_JGT >> 4] = ">",
319 [BPF_JGE >> 4] = ">=",
320 [BPF_JSET >> 4] = "&",
321 [BPF_JNE >> 4] = "!=",
322 [BPF_JSGT >> 4] = "s>",
323 [BPF_JSGE >> 4] = "s>=",
324 [BPF_CALL >> 4] = "call",
325 [BPF_EXIT >> 4] = "exit",
326};
327
328static void print_bpf_insn(struct bpf_insn *insn)
329{
330 u8 class = BPF_CLASS(insn->code);
331
332 if (class == BPF_ALU || class == BPF_ALU64) {
333 if (BPF_SRC(insn->code) == BPF_X)
334 verbose("(%02x) %sr%d %s %sr%d\n",
335 insn->code, class == BPF_ALU ? "(u32) " : "",
336 insn->dst_reg,
337 bpf_alu_string[BPF_OP(insn->code) >> 4],
338 class == BPF_ALU ? "(u32) " : "",
339 insn->src_reg);
340 else
341 verbose("(%02x) %sr%d %s %s%d\n",
342 insn->code, class == BPF_ALU ? "(u32) " : "",
343 insn->dst_reg,
344 bpf_alu_string[BPF_OP(insn->code) >> 4],
345 class == BPF_ALU ? "(u32) " : "",
346 insn->imm);
347 } else if (class == BPF_STX) {
348 if (BPF_MODE(insn->code) == BPF_MEM)
349 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
350 insn->code,
351 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
352 insn->dst_reg,
353 insn->off, insn->src_reg);
354 else if (BPF_MODE(insn->code) == BPF_XADD)
355 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
356 insn->code,
357 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
358 insn->dst_reg, insn->off,
359 insn->src_reg);
360 else
361 verbose("BUG_%02x\n", insn->code);
362 } else if (class == BPF_ST) {
363 if (BPF_MODE(insn->code) != BPF_MEM) {
364 verbose("BUG_st_%02x\n", insn->code);
365 return;
366 }
367 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
368 insn->code,
369 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
370 insn->dst_reg,
371 insn->off, insn->imm);
372 } else if (class == BPF_LDX) {
373 if (BPF_MODE(insn->code) != BPF_MEM) {
374 verbose("BUG_ldx_%02x\n", insn->code);
375 return;
376 }
377 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
378 insn->code, insn->dst_reg,
379 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
380 insn->src_reg, insn->off);
381 } else if (class == BPF_LD) {
382 if (BPF_MODE(insn->code) == BPF_ABS) {
383 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
384 insn->code,
385 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
386 insn->imm);
387 } else if (BPF_MODE(insn->code) == BPF_IND) {
388 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
389 insn->code,
390 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
391 insn->src_reg, insn->imm);
392 } else if (BPF_MODE(insn->code) == BPF_IMM) {
393 verbose("(%02x) r%d = 0x%x\n",
394 insn->code, insn->dst_reg, insn->imm);
395 } else {
396 verbose("BUG_ld_%02x\n", insn->code);
397 return;
398 }
399 } else if (class == BPF_JMP) {
400 u8 opcode = BPF_OP(insn->code);
401
402 if (opcode == BPF_CALL) {
403 verbose("(%02x) call %d\n", insn->code, insn->imm);
404 } else if (insn->code == (BPF_JMP | BPF_JA)) {
405 verbose("(%02x) goto pc%+d\n",
406 insn->code, insn->off);
407 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
408 verbose("(%02x) exit\n", insn->code);
409 } else if (BPF_SRC(insn->code) == BPF_X) {
410 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
411 insn->code, insn->dst_reg,
412 bpf_jmp_string[BPF_OP(insn->code) >> 4],
413 insn->src_reg, insn->off);
414 } else {
415 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
416 insn->code, insn->dst_reg,
417 bpf_jmp_string[BPF_OP(insn->code) >> 4],
418 insn->imm, insn->off);
419 }
420 } else {
421 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
422 }
423}
424
17a52670
AS
425static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
426{
427 struct verifier_stack_elem *elem;
428 int insn_idx;
429
430 if (env->head == NULL)
431 return -1;
432
433 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
434 insn_idx = env->head->insn_idx;
435 if (prev_insn_idx)
436 *prev_insn_idx = env->head->prev_insn_idx;
437 elem = env->head->next;
438 kfree(env->head);
439 env->head = elem;
440 env->stack_size--;
441 return insn_idx;
442}
443
444static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
445 int prev_insn_idx)
446{
447 struct verifier_stack_elem *elem;
448
449 elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
450 if (!elem)
451 goto err;
452
453 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
454 elem->insn_idx = insn_idx;
455 elem->prev_insn_idx = prev_insn_idx;
456 elem->next = env->head;
457 env->head = elem;
458 env->stack_size++;
07016151 459 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
17a52670
AS
460 verbose("BPF program is too complex\n");
461 goto err;
462 }
463 return &elem->st;
464err:
465 /* pop all elements and return */
466 while (pop_stack(env, NULL) >= 0);
467 return NULL;
468}
469
470#define CALLER_SAVED_REGS 6
471static const int caller_saved[CALLER_SAVED_REGS] = {
472 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
473};
474
475static void init_reg_state(struct reg_state *regs)
476{
477 int i;
478
479 for (i = 0; i < MAX_BPF_REG; i++) {
480 regs[i].type = NOT_INIT;
481 regs[i].imm = 0;
17a52670
AS
482 }
483
484 /* frame pointer */
485 regs[BPF_REG_FP].type = FRAME_PTR;
486
487 /* 1st arg to a function */
488 regs[BPF_REG_1].type = PTR_TO_CTX;
489}
490
491static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
492{
493 BUG_ON(regno >= MAX_BPF_REG);
494 regs[regno].type = UNKNOWN_VALUE;
495 regs[regno].imm = 0;
17a52670
AS
496}
497
498enum reg_arg_type {
499 SRC_OP, /* register is used as source operand */
500 DST_OP, /* register is used as destination operand */
501 DST_OP_NO_MARK /* same as above, check only, don't mark */
502};
503
504static int check_reg_arg(struct reg_state *regs, u32 regno,
505 enum reg_arg_type t)
506{
507 if (regno >= MAX_BPF_REG) {
508 verbose("R%d is invalid\n", regno);
509 return -EINVAL;
510 }
511
512 if (t == SRC_OP) {
513 /* check whether register used as source operand can be read */
514 if (regs[regno].type == NOT_INIT) {
515 verbose("R%d !read_ok\n", regno);
516 return -EACCES;
517 }
518 } else {
519 /* check whether register used as dest operand can be written to */
520 if (regno == BPF_REG_FP) {
521 verbose("frame pointer is read only\n");
522 return -EACCES;
523 }
524 if (t == DST_OP)
525 mark_reg_unknown_value(regs, regno);
526 }
527 return 0;
528}
529
530static int bpf_size_to_bytes(int bpf_size)
531{
532 if (bpf_size == BPF_W)
533 return 4;
534 else if (bpf_size == BPF_H)
535 return 2;
536 else if (bpf_size == BPF_B)
537 return 1;
538 else if (bpf_size == BPF_DW)
539 return 8;
540 else
541 return -EINVAL;
542}
543
1be7f75d
AS
544static bool is_spillable_regtype(enum bpf_reg_type type)
545{
546 switch (type) {
547 case PTR_TO_MAP_VALUE:
548 case PTR_TO_MAP_VALUE_OR_NULL:
549 case PTR_TO_STACK:
550 case PTR_TO_CTX:
551 case FRAME_PTR:
552 case CONST_PTR_TO_MAP:
553 return true;
554 default:
555 return false;
556 }
557}
558
17a52670
AS
559/* check_stack_read/write functions track spill/fill of registers,
560 * stack boundary and alignment are checked in check_mem_access()
561 */
562static int check_stack_write(struct verifier_state *state, int off, int size,
563 int value_regno)
564{
17a52670 565 int i;
9c399760
AS
566 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
567 * so it's aligned access and [off, off + size) are within stack limits
568 */
17a52670
AS
569
570 if (value_regno >= 0 &&
1be7f75d 571 is_spillable_regtype(state->regs[value_regno].type)) {
17a52670
AS
572
573 /* register containing pointer is being spilled into stack */
9c399760 574 if (size != BPF_REG_SIZE) {
17a52670
AS
575 verbose("invalid size of register spill\n");
576 return -EACCES;
577 }
578
17a52670 579 /* save register state */
9c399760
AS
580 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
581 state->regs[value_regno];
17a52670 582
9c399760
AS
583 for (i = 0; i < BPF_REG_SIZE; i++)
584 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
585 } else {
17a52670 586 /* regular write of data into stack */
9c399760
AS
587 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
588 (struct reg_state) {};
589
590 for (i = 0; i < size; i++)
591 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
17a52670
AS
592 }
593 return 0;
594}
595
596static int check_stack_read(struct verifier_state *state, int off, int size,
597 int value_regno)
598{
9c399760 599 u8 *slot_type;
17a52670 600 int i;
17a52670 601
9c399760 602 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
17a52670 603
9c399760
AS
604 if (slot_type[0] == STACK_SPILL) {
605 if (size != BPF_REG_SIZE) {
17a52670
AS
606 verbose("invalid size of register spill\n");
607 return -EACCES;
608 }
9c399760
AS
609 for (i = 1; i < BPF_REG_SIZE; i++) {
610 if (slot_type[i] != STACK_SPILL) {
17a52670
AS
611 verbose("corrupted spill memory\n");
612 return -EACCES;
613 }
614 }
615
616 if (value_regno >= 0)
617 /* restore register state from stack */
9c399760
AS
618 state->regs[value_regno] =
619 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
17a52670
AS
620 return 0;
621 } else {
622 for (i = 0; i < size; i++) {
9c399760 623 if (slot_type[i] != STACK_MISC) {
17a52670
AS
624 verbose("invalid read from stack off %d+%d size %d\n",
625 off, i, size);
626 return -EACCES;
627 }
628 }
629 if (value_regno >= 0)
630 /* have read misc data from the stack */
631 mark_reg_unknown_value(state->regs, value_regno);
632 return 0;
633 }
634}
635
636/* check read/write into map element returned by bpf_map_lookup_elem() */
637static int check_map_access(struct verifier_env *env, u32 regno, int off,
638 int size)
639{
640 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
641
642 if (off < 0 || off + size > map->value_size) {
643 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
644 map->value_size, off, size);
645 return -EACCES;
646 }
647 return 0;
648}
649
650/* check access to 'struct bpf_context' fields */
651static int check_ctx_access(struct verifier_env *env, int off, int size,
652 enum bpf_access_type t)
653{
654 if (env->prog->aux->ops->is_valid_access &&
32bbe007
AS
655 env->prog->aux->ops->is_valid_access(off, size, t)) {
656 /* remember the offset of last byte accessed in ctx */
657 if (env->prog->aux->max_ctx_offset < off + size)
658 env->prog->aux->max_ctx_offset = off + size;
17a52670 659 return 0;
32bbe007 660 }
17a52670
AS
661
662 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
663 return -EACCES;
664}
665
1be7f75d
AS
666static bool is_pointer_value(struct verifier_env *env, int regno)
667{
668 if (env->allow_ptr_leaks)
669 return false;
670
671 switch (env->cur_state.regs[regno].type) {
672 case UNKNOWN_VALUE:
673 case CONST_IMM:
674 return false;
675 default:
676 return true;
677 }
678}
679
17a52670
AS
680/* check whether memory at (regno + off) is accessible for t = (read | write)
681 * if t==write, value_regno is a register which value is stored into memory
682 * if t==read, value_regno is a register which will receive the value from memory
683 * if t==write && value_regno==-1, some unknown value is stored into memory
684 * if t==read && value_regno==-1, don't care what we read from memory
685 */
686static int check_mem_access(struct verifier_env *env, u32 regno, int off,
687 int bpf_size, enum bpf_access_type t,
688 int value_regno)
689{
690 struct verifier_state *state = &env->cur_state;
1a0dc1ac 691 struct reg_state *reg = &state->regs[regno];
17a52670
AS
692 int size, err = 0;
693
1a0dc1ac
AS
694 if (reg->type == PTR_TO_STACK)
695 off += reg->imm;
24b4d2ab 696
17a52670
AS
697 size = bpf_size_to_bytes(bpf_size);
698 if (size < 0)
699 return size;
700
701 if (off % size != 0) {
702 verbose("misaligned access off %d size %d\n", off, size);
703 return -EACCES;
704 }
705
1a0dc1ac 706 if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
707 if (t == BPF_WRITE && value_regno >= 0 &&
708 is_pointer_value(env, value_regno)) {
709 verbose("R%d leaks addr into map\n", value_regno);
710 return -EACCES;
711 }
17a52670
AS
712 err = check_map_access(env, regno, off, size);
713 if (!err && t == BPF_READ && value_regno >= 0)
714 mark_reg_unknown_value(state->regs, value_regno);
715
1a0dc1ac 716 } else if (reg->type == PTR_TO_CTX) {
1be7f75d
AS
717 if (t == BPF_WRITE && value_regno >= 0 &&
718 is_pointer_value(env, value_regno)) {
719 verbose("R%d leaks addr into ctx\n", value_regno);
720 return -EACCES;
721 }
17a52670
AS
722 err = check_ctx_access(env, off, size, t);
723 if (!err && t == BPF_READ && value_regno >= 0)
724 mark_reg_unknown_value(state->regs, value_regno);
725
1a0dc1ac 726 } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
17a52670
AS
727 if (off >= 0 || off < -MAX_BPF_STACK) {
728 verbose("invalid stack off=%d size=%d\n", off, size);
729 return -EACCES;
730 }
1be7f75d
AS
731 if (t == BPF_WRITE) {
732 if (!env->allow_ptr_leaks &&
733 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
734 size != BPF_REG_SIZE) {
735 verbose("attempt to corrupt spilled pointer on stack\n");
736 return -EACCES;
737 }
17a52670 738 err = check_stack_write(state, off, size, value_regno);
1be7f75d 739 } else {
17a52670 740 err = check_stack_read(state, off, size, value_regno);
1be7f75d 741 }
17a52670
AS
742 } else {
743 verbose("R%d invalid mem access '%s'\n",
1a0dc1ac 744 regno, reg_type_str[reg->type]);
17a52670
AS
745 return -EACCES;
746 }
747 return err;
748}
749
750static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
751{
752 struct reg_state *regs = env->cur_state.regs;
753 int err;
754
755 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
756 insn->imm != 0) {
757 verbose("BPF_XADD uses reserved fields\n");
758 return -EINVAL;
759 }
760
761 /* check src1 operand */
762 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
763 if (err)
764 return err;
765
766 /* check src2 operand */
767 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
768 if (err)
769 return err;
770
771 /* check whether atomic_add can read the memory */
772 err = check_mem_access(env, insn->dst_reg, insn->off,
773 BPF_SIZE(insn->code), BPF_READ, -1);
774 if (err)
775 return err;
776
777 /* check whether atomic_add can write into the same memory */
778 return check_mem_access(env, insn->dst_reg, insn->off,
779 BPF_SIZE(insn->code), BPF_WRITE, -1);
780}
781
782/* when register 'regno' is passed into function that will read 'access_size'
783 * bytes from that pointer, make sure that it's within stack boundary
784 * and all elements of stack are initialized
785 */
8e2fe1d9 786static int check_stack_boundary(struct verifier_env *env, int regno,
435faee1
DB
787 int access_size, bool zero_size_allowed,
788 struct bpf_call_arg_meta *meta)
17a52670
AS
789{
790 struct verifier_state *state = &env->cur_state;
791 struct reg_state *regs = state->regs;
792 int off, i;
793
8e2fe1d9
DB
794 if (regs[regno].type != PTR_TO_STACK) {
795 if (zero_size_allowed && access_size == 0 &&
796 regs[regno].type == CONST_IMM &&
797 regs[regno].imm == 0)
798 return 0;
799
800 verbose("R%d type=%s expected=%s\n", regno,
801 reg_type_str[regs[regno].type],
802 reg_type_str[PTR_TO_STACK]);
17a52670 803 return -EACCES;
8e2fe1d9 804 }
17a52670
AS
805
806 off = regs[regno].imm;
807 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
808 access_size <= 0) {
809 verbose("invalid stack type R%d off=%d access_size=%d\n",
810 regno, off, access_size);
811 return -EACCES;
812 }
813
435faee1
DB
814 if (meta && meta->raw_mode) {
815 meta->access_size = access_size;
816 meta->regno = regno;
817 return 0;
818 }
819
17a52670 820 for (i = 0; i < access_size; i++) {
9c399760 821 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
17a52670
AS
822 verbose("invalid indirect read from stack off %d+%d size %d\n",
823 off, i, access_size);
824 return -EACCES;
825 }
826 }
827 return 0;
828}
829
830static int check_func_arg(struct verifier_env *env, u32 regno,
33ff9823
DB
831 enum bpf_arg_type arg_type,
832 struct bpf_call_arg_meta *meta)
17a52670
AS
833{
834 struct reg_state *reg = env->cur_state.regs + regno;
835 enum bpf_reg_type expected_type;
836 int err = 0;
837
80f1d68c 838 if (arg_type == ARG_DONTCARE)
17a52670
AS
839 return 0;
840
841 if (reg->type == NOT_INIT) {
842 verbose("R%d !read_ok\n", regno);
843 return -EACCES;
844 }
845
1be7f75d
AS
846 if (arg_type == ARG_ANYTHING) {
847 if (is_pointer_value(env, regno)) {
848 verbose("R%d leaks addr into helper function\n", regno);
849 return -EACCES;
850 }
80f1d68c 851 return 0;
1be7f75d 852 }
80f1d68c 853
8e2fe1d9 854 if (arg_type == ARG_PTR_TO_MAP_KEY ||
17a52670
AS
855 arg_type == ARG_PTR_TO_MAP_VALUE) {
856 expected_type = PTR_TO_STACK;
8e2fe1d9
DB
857 } else if (arg_type == ARG_CONST_STACK_SIZE ||
858 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
17a52670
AS
859 expected_type = CONST_IMM;
860 } else if (arg_type == ARG_CONST_MAP_PTR) {
861 expected_type = CONST_PTR_TO_MAP;
608cd71a
AS
862 } else if (arg_type == ARG_PTR_TO_CTX) {
863 expected_type = PTR_TO_CTX;
435faee1
DB
864 } else if (arg_type == ARG_PTR_TO_STACK ||
865 arg_type == ARG_PTR_TO_RAW_STACK) {
8e2fe1d9
DB
866 expected_type = PTR_TO_STACK;
867 /* One exception here. In case function allows for NULL to be
868 * passed in as argument, it's a CONST_IMM type. Final test
869 * happens during stack boundary checking.
870 */
871 if (reg->type == CONST_IMM && reg->imm == 0)
872 expected_type = CONST_IMM;
435faee1 873 meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
17a52670
AS
874 } else {
875 verbose("unsupported arg_type %d\n", arg_type);
876 return -EFAULT;
877 }
878
879 if (reg->type != expected_type) {
880 verbose("R%d type=%s expected=%s\n", regno,
881 reg_type_str[reg->type], reg_type_str[expected_type]);
882 return -EACCES;
883 }
884
885 if (arg_type == ARG_CONST_MAP_PTR) {
886 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 887 meta->map_ptr = reg->map_ptr;
17a52670
AS
888 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
889 /* bpf_map_xxx(..., map_ptr, ..., key) call:
890 * check that [key, key + map->key_size) are within
891 * stack limits and initialized
892 */
33ff9823 893 if (!meta->map_ptr) {
17a52670
AS
894 /* in function declaration map_ptr must come before
895 * map_key, so that it's verified and known before
896 * we have to check map_key here. Otherwise it means
897 * that kernel subsystem misconfigured verifier
898 */
899 verbose("invalid map_ptr to access map->key\n");
900 return -EACCES;
901 }
33ff9823 902 err = check_stack_boundary(env, regno, meta->map_ptr->key_size,
435faee1 903 false, NULL);
17a52670
AS
904 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
905 /* bpf_map_xxx(..., map_ptr, ..., value) call:
906 * check [value, value + map->value_size) validity
907 */
33ff9823 908 if (!meta->map_ptr) {
17a52670
AS
909 /* kernel subsystem misconfigured verifier */
910 verbose("invalid map_ptr to access map->value\n");
911 return -EACCES;
912 }
33ff9823 913 err = check_stack_boundary(env, regno,
435faee1
DB
914 meta->map_ptr->value_size,
915 false, NULL);
8e2fe1d9
DB
916 } else if (arg_type == ARG_CONST_STACK_SIZE ||
917 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
918 bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
17a52670 919
17a52670
AS
920 /* bpf_xxx(..., buf, len) call will access 'len' bytes
921 * from stack pointer 'buf'. Check it
922 * note: regno == len, regno - 1 == buf
923 */
924 if (regno == 0) {
925 /* kernel subsystem misconfigured verifier */
926 verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
927 return -EACCES;
928 }
8e2fe1d9 929 err = check_stack_boundary(env, regno - 1, reg->imm,
435faee1 930 zero_size_allowed, meta);
17a52670
AS
931 }
932
933 return err;
934}
935
35578d79
KX
936static int check_map_func_compatibility(struct bpf_map *map, int func_id)
937{
35578d79
KX
938 if (!map)
939 return 0;
940
6aff67c8
AS
941 /* We need a two way check, first is from map perspective ... */
942 switch (map->map_type) {
943 case BPF_MAP_TYPE_PROG_ARRAY:
944 if (func_id != BPF_FUNC_tail_call)
945 goto error;
946 break;
947 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
948 if (func_id != BPF_FUNC_perf_event_read &&
949 func_id != BPF_FUNC_perf_event_output)
950 goto error;
951 break;
952 case BPF_MAP_TYPE_STACK_TRACE:
953 if (func_id != BPF_FUNC_get_stackid)
954 goto error;
955 break;
956 default:
957 break;
958 }
959
960 /* ... and second from the function itself. */
961 switch (func_id) {
962 case BPF_FUNC_tail_call:
963 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
964 goto error;
965 break;
966 case BPF_FUNC_perf_event_read:
967 case BPF_FUNC_perf_event_output:
968 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
969 goto error;
970 break;
971 case BPF_FUNC_get_stackid:
972 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
973 goto error;
974 break;
975 default:
976 break;
35578d79
KX
977 }
978
979 return 0;
6aff67c8
AS
980error:
981 verbose("cannot pass map_type %d into func %d\n",
982 map->map_type, func_id);
983 return -EINVAL;
35578d79
KX
984}
985
435faee1
DB
986static int check_raw_mode(const struct bpf_func_proto *fn)
987{
988 int count = 0;
989
990 if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
991 count++;
992 if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
993 count++;
994 if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
995 count++;
996 if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
997 count++;
998 if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
999 count++;
1000
1001 return count > 1 ? -EINVAL : 0;
1002}
1003
17a52670
AS
1004static int check_call(struct verifier_env *env, int func_id)
1005{
1006 struct verifier_state *state = &env->cur_state;
1007 const struct bpf_func_proto *fn = NULL;
1008 struct reg_state *regs = state->regs;
17a52670 1009 struct reg_state *reg;
33ff9823 1010 struct bpf_call_arg_meta meta;
17a52670
AS
1011 int i, err;
1012
1013 /* find function prototype */
1014 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1015 verbose("invalid func %d\n", func_id);
1016 return -EINVAL;
1017 }
1018
1019 if (env->prog->aux->ops->get_func_proto)
1020 fn = env->prog->aux->ops->get_func_proto(func_id);
1021
1022 if (!fn) {
1023 verbose("unknown func %d\n", func_id);
1024 return -EINVAL;
1025 }
1026
1027 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 1028 if (!env->prog->gpl_compatible && fn->gpl_only) {
17a52670
AS
1029 verbose("cannot call GPL only function from proprietary program\n");
1030 return -EINVAL;
1031 }
1032
33ff9823
DB
1033 memset(&meta, 0, sizeof(meta));
1034
435faee1
DB
1035 /* We only support one arg being in raw mode at the moment, which
1036 * is sufficient for the helper functions we have right now.
1037 */
1038 err = check_raw_mode(fn);
1039 if (err) {
1040 verbose("kernel subsystem misconfigured func %d\n", func_id);
1041 return err;
1042 }
1043
17a52670 1044 /* check args */
33ff9823 1045 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
17a52670
AS
1046 if (err)
1047 return err;
33ff9823 1048 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
17a52670
AS
1049 if (err)
1050 return err;
33ff9823 1051 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
17a52670
AS
1052 if (err)
1053 return err;
33ff9823 1054 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
17a52670
AS
1055 if (err)
1056 return err;
33ff9823 1057 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
17a52670
AS
1058 if (err)
1059 return err;
1060
435faee1
DB
1061 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1062 * is inferred from register state.
1063 */
1064 for (i = 0; i < meta.access_size; i++) {
1065 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1066 if (err)
1067 return err;
1068 }
1069
17a52670
AS
1070 /* reset caller saved regs */
1071 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1072 reg = regs + caller_saved[i];
1073 reg->type = NOT_INIT;
1074 reg->imm = 0;
1075 }
1076
1077 /* update return register */
1078 if (fn->ret_type == RET_INTEGER) {
1079 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1080 } else if (fn->ret_type == RET_VOID) {
1081 regs[BPF_REG_0].type = NOT_INIT;
1082 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1083 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1084 /* remember map_ptr, so that check_map_access()
1085 * can check 'value_size' boundary of memory access
1086 * to map element returned from bpf_map_lookup_elem()
1087 */
33ff9823 1088 if (meta.map_ptr == NULL) {
17a52670
AS
1089 verbose("kernel subsystem misconfigured verifier\n");
1090 return -EINVAL;
1091 }
33ff9823 1092 regs[BPF_REG_0].map_ptr = meta.map_ptr;
17a52670
AS
1093 } else {
1094 verbose("unknown return type %d of func %d\n",
1095 fn->ret_type, func_id);
1096 return -EINVAL;
1097 }
04fd61ab 1098
33ff9823 1099 err = check_map_func_compatibility(meta.map_ptr, func_id);
35578d79
KX
1100 if (err)
1101 return err;
04fd61ab 1102
17a52670
AS
1103 return 0;
1104}
1105
1106/* check validity of 32-bit and 64-bit arithmetic operations */
1be7f75d 1107static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn)
17a52670 1108{
1a0dc1ac 1109 struct reg_state *regs = env->cur_state.regs, *dst_reg;
17a52670
AS
1110 u8 opcode = BPF_OP(insn->code);
1111 int err;
1112
1113 if (opcode == BPF_END || opcode == BPF_NEG) {
1114 if (opcode == BPF_NEG) {
1115 if (BPF_SRC(insn->code) != 0 ||
1116 insn->src_reg != BPF_REG_0 ||
1117 insn->off != 0 || insn->imm != 0) {
1118 verbose("BPF_NEG uses reserved fields\n");
1119 return -EINVAL;
1120 }
1121 } else {
1122 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1123 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1124 verbose("BPF_END uses reserved fields\n");
1125 return -EINVAL;
1126 }
1127 }
1128
1129 /* check src operand */
1130 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1131 if (err)
1132 return err;
1133
1be7f75d
AS
1134 if (is_pointer_value(env, insn->dst_reg)) {
1135 verbose("R%d pointer arithmetic prohibited\n",
1136 insn->dst_reg);
1137 return -EACCES;
1138 }
1139
17a52670
AS
1140 /* check dest operand */
1141 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1142 if (err)
1143 return err;
1144
1145 } else if (opcode == BPF_MOV) {
1146
1147 if (BPF_SRC(insn->code) == BPF_X) {
1148 if (insn->imm != 0 || insn->off != 0) {
1149 verbose("BPF_MOV uses reserved fields\n");
1150 return -EINVAL;
1151 }
1152
1153 /* check src operand */
1154 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1155 if (err)
1156 return err;
1157 } else {
1158 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1159 verbose("BPF_MOV uses reserved fields\n");
1160 return -EINVAL;
1161 }
1162 }
1163
1164 /* check dest operand */
1165 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1166 if (err)
1167 return err;
1168
1169 if (BPF_SRC(insn->code) == BPF_X) {
1170 if (BPF_CLASS(insn->code) == BPF_ALU64) {
1171 /* case: R1 = R2
1172 * copy register state to dest reg
1173 */
1174 regs[insn->dst_reg] = regs[insn->src_reg];
1175 } else {
1be7f75d
AS
1176 if (is_pointer_value(env, insn->src_reg)) {
1177 verbose("R%d partial copy of pointer\n",
1178 insn->src_reg);
1179 return -EACCES;
1180 }
17a52670
AS
1181 regs[insn->dst_reg].type = UNKNOWN_VALUE;
1182 regs[insn->dst_reg].map_ptr = NULL;
1183 }
1184 } else {
1185 /* case: R = imm
1186 * remember the value we stored into this reg
1187 */
1188 regs[insn->dst_reg].type = CONST_IMM;
1189 regs[insn->dst_reg].imm = insn->imm;
1190 }
1191
1192 } else if (opcode > BPF_END) {
1193 verbose("invalid BPF_ALU opcode %x\n", opcode);
1194 return -EINVAL;
1195
1196 } else { /* all other ALU ops: and, sub, xor, add, ... */
1197
17a52670
AS
1198 if (BPF_SRC(insn->code) == BPF_X) {
1199 if (insn->imm != 0 || insn->off != 0) {
1200 verbose("BPF_ALU uses reserved fields\n");
1201 return -EINVAL;
1202 }
1203 /* check src1 operand */
1204 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1205 if (err)
1206 return err;
1207 } else {
1208 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1209 verbose("BPF_ALU uses reserved fields\n");
1210 return -EINVAL;
1211 }
1212 }
1213
1214 /* check src2 operand */
1215 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1216 if (err)
1217 return err;
1218
1219 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1220 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1221 verbose("div by zero\n");
1222 return -EINVAL;
1223 }
1224
229394e8
RV
1225 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1226 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1227 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1228
1229 if (insn->imm < 0 || insn->imm >= size) {
1230 verbose("invalid shift %d\n", insn->imm);
1231 return -EINVAL;
1232 }
1233 }
1234
1a0dc1ac
AS
1235 /* check dest operand */
1236 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1237 if (err)
1238 return err;
1239
1240 dst_reg = &regs[insn->dst_reg];
1241
17a52670
AS
1242 /* pattern match 'bpf_add Rx, imm' instruction */
1243 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1a0dc1ac
AS
1244 dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1245 dst_reg->type = PTR_TO_STACK;
1246 dst_reg->imm = insn->imm;
1247 return 0;
1be7f75d
AS
1248 } else if (is_pointer_value(env, insn->dst_reg)) {
1249 verbose("R%d pointer arithmetic prohibited\n",
1250 insn->dst_reg);
1251 return -EACCES;
1252 } else if (BPF_SRC(insn->code) == BPF_X &&
1253 is_pointer_value(env, insn->src_reg)) {
1254 verbose("R%d pointer arithmetic prohibited\n",
1255 insn->src_reg);
1256 return -EACCES;
1257 }
17a52670 1258
1a0dc1ac
AS
1259 /* mark dest operand */
1260 mark_reg_unknown_value(regs, insn->dst_reg);
17a52670
AS
1261 }
1262
1263 return 0;
1264}
1265
1266static int check_cond_jmp_op(struct verifier_env *env,
1267 struct bpf_insn *insn, int *insn_idx)
1268{
1a0dc1ac 1269 struct reg_state *regs = env->cur_state.regs, *dst_reg;
17a52670
AS
1270 struct verifier_state *other_branch;
1271 u8 opcode = BPF_OP(insn->code);
1272 int err;
1273
1274 if (opcode > BPF_EXIT) {
1275 verbose("invalid BPF_JMP opcode %x\n", opcode);
1276 return -EINVAL;
1277 }
1278
1279 if (BPF_SRC(insn->code) == BPF_X) {
1280 if (insn->imm != 0) {
1281 verbose("BPF_JMP uses reserved fields\n");
1282 return -EINVAL;
1283 }
1284
1285 /* check src1 operand */
1286 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1287 if (err)
1288 return err;
1be7f75d
AS
1289
1290 if (is_pointer_value(env, insn->src_reg)) {
1291 verbose("R%d pointer comparison prohibited\n",
1292 insn->src_reg);
1293 return -EACCES;
1294 }
17a52670
AS
1295 } else {
1296 if (insn->src_reg != BPF_REG_0) {
1297 verbose("BPF_JMP uses reserved fields\n");
1298 return -EINVAL;
1299 }
1300 }
1301
1302 /* check src2 operand */
1303 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1304 if (err)
1305 return err;
1306
1a0dc1ac
AS
1307 dst_reg = &regs[insn->dst_reg];
1308
17a52670
AS
1309 /* detect if R == 0 where R was initialized to zero earlier */
1310 if (BPF_SRC(insn->code) == BPF_K &&
1311 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1a0dc1ac 1312 dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
17a52670
AS
1313 if (opcode == BPF_JEQ) {
1314 /* if (imm == imm) goto pc+off;
1315 * only follow the goto, ignore fall-through
1316 */
1317 *insn_idx += insn->off;
1318 return 0;
1319 } else {
1320 /* if (imm != imm) goto pc+off;
1321 * only follow fall-through branch, since
1322 * that's where the program will go
1323 */
1324 return 0;
1325 }
1326 }
1327
1328 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1329 if (!other_branch)
1330 return -EFAULT;
1331
1332 /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
1333 if (BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac
AS
1334 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1335 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
17a52670
AS
1336 if (opcode == BPF_JEQ) {
1337 /* next fallthrough insn can access memory via
1338 * this register
1339 */
1340 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1341 /* branch targer cannot access it, since reg == 0 */
1342 other_branch->regs[insn->dst_reg].type = CONST_IMM;
1343 other_branch->regs[insn->dst_reg].imm = 0;
1344 } else {
1345 other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1346 regs[insn->dst_reg].type = CONST_IMM;
1347 regs[insn->dst_reg].imm = 0;
1348 }
1be7f75d
AS
1349 } else if (is_pointer_value(env, insn->dst_reg)) {
1350 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
1351 return -EACCES;
17a52670
AS
1352 } else if (BPF_SRC(insn->code) == BPF_K &&
1353 (opcode == BPF_JEQ || opcode == BPF_JNE)) {
1354
1355 if (opcode == BPF_JEQ) {
1356 /* detect if (R == imm) goto
1357 * and in the target state recognize that R = imm
1358 */
1359 other_branch->regs[insn->dst_reg].type = CONST_IMM;
1360 other_branch->regs[insn->dst_reg].imm = insn->imm;
1361 } else {
1362 /* detect if (R != imm) goto
1363 * and in the fall-through state recognize that R = imm
1364 */
1365 regs[insn->dst_reg].type = CONST_IMM;
1366 regs[insn->dst_reg].imm = insn->imm;
1367 }
1368 }
1369 if (log_level)
1a0dc1ac 1370 print_verifier_state(&env->cur_state);
17a52670
AS
1371 return 0;
1372}
1373
0246e64d
AS
1374/* return the map pointer stored inside BPF_LD_IMM64 instruction */
1375static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
1376{
1377 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
1378
1379 return (struct bpf_map *) (unsigned long) imm64;
1380}
1381
17a52670
AS
1382/* verify BPF_LD_IMM64 instruction */
1383static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
1384{
1385 struct reg_state *regs = env->cur_state.regs;
1386 int err;
1387
1388 if (BPF_SIZE(insn->code) != BPF_DW) {
1389 verbose("invalid BPF_LD_IMM insn\n");
1390 return -EINVAL;
1391 }
1392 if (insn->off != 0) {
1393 verbose("BPF_LD_IMM64 uses reserved fields\n");
1394 return -EINVAL;
1395 }
1396
1397 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1398 if (err)
1399 return err;
1400
1401 if (insn->src_reg == 0)
1402 /* generic move 64-bit immediate into a register */
1403 return 0;
1404
1405 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1406 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
1407
1408 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
1409 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
1410 return 0;
1411}
1412
96be4325
DB
1413static bool may_access_skb(enum bpf_prog_type type)
1414{
1415 switch (type) {
1416 case BPF_PROG_TYPE_SOCKET_FILTER:
1417 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 1418 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
1419 return true;
1420 default:
1421 return false;
1422 }
1423}
1424
ddd872bc
AS
1425/* verify safety of LD_ABS|LD_IND instructions:
1426 * - they can only appear in the programs where ctx == skb
1427 * - since they are wrappers of function calls, they scratch R1-R5 registers,
1428 * preserve R6-R9, and store return value into R0
1429 *
1430 * Implicit input:
1431 * ctx == skb == R6 == CTX
1432 *
1433 * Explicit input:
1434 * SRC == any register
1435 * IMM == 32-bit immediate
1436 *
1437 * Output:
1438 * R0 - 8/16/32-bit skb data converted to cpu endianness
1439 */
1440static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
1441{
1442 struct reg_state *regs = env->cur_state.regs;
1443 u8 mode = BPF_MODE(insn->code);
1444 struct reg_state *reg;
1445 int i, err;
1446
24701ece 1447 if (!may_access_skb(env->prog->type)) {
1a0dc1ac 1448 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
1449 return -EINVAL;
1450 }
1451
1452 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 1453 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 1454 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1a0dc1ac 1455 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
1456 return -EINVAL;
1457 }
1458
1459 /* check whether implicit source operand (register R6) is readable */
1460 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
1461 if (err)
1462 return err;
1463
1464 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
1465 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1466 return -EINVAL;
1467 }
1468
1469 if (mode == BPF_IND) {
1470 /* check explicit source operand */
1471 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1472 if (err)
1473 return err;
1474 }
1475
1476 /* reset caller saved regs to unreadable */
1477 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1478 reg = regs + caller_saved[i];
1479 reg->type = NOT_INIT;
1480 reg->imm = 0;
1481 }
1482
1483 /* mark destination R0 register as readable, since it contains
1484 * the value fetched from the packet
1485 */
1486 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1487 return 0;
1488}
1489
475fb78f
AS
1490/* non-recursive DFS pseudo code
1491 * 1 procedure DFS-iterative(G,v):
1492 * 2 label v as discovered
1493 * 3 let S be a stack
1494 * 4 S.push(v)
1495 * 5 while S is not empty
1496 * 6 t <- S.pop()
1497 * 7 if t is what we're looking for:
1498 * 8 return t
1499 * 9 for all edges e in G.adjacentEdges(t) do
1500 * 10 if edge e is already labelled
1501 * 11 continue with the next edge
1502 * 12 w <- G.adjacentVertex(t,e)
1503 * 13 if vertex w is not discovered and not explored
1504 * 14 label e as tree-edge
1505 * 15 label w as discovered
1506 * 16 S.push(w)
1507 * 17 continue at 5
1508 * 18 else if vertex w is discovered
1509 * 19 label e as back-edge
1510 * 20 else
1511 * 21 // vertex w is explored
1512 * 22 label e as forward- or cross-edge
1513 * 23 label t as explored
1514 * 24 S.pop()
1515 *
1516 * convention:
1517 * 0x10 - discovered
1518 * 0x11 - discovered and fall-through edge labelled
1519 * 0x12 - discovered and fall-through and branch edges labelled
1520 * 0x20 - explored
1521 */
1522
1523enum {
1524 DISCOVERED = 0x10,
1525 EXPLORED = 0x20,
1526 FALLTHROUGH = 1,
1527 BRANCH = 2,
1528};
1529
f1bca824
AS
1530#define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
1531
475fb78f
AS
1532static int *insn_stack; /* stack of insns to process */
1533static int cur_stack; /* current stack index */
1534static int *insn_state;
1535
1536/* t, w, e - match pseudo-code above:
1537 * t - index of current instruction
1538 * w - next instruction
1539 * e - edge
1540 */
1541static int push_insn(int t, int w, int e, struct verifier_env *env)
1542{
1543 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
1544 return 0;
1545
1546 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
1547 return 0;
1548
1549 if (w < 0 || w >= env->prog->len) {
1550 verbose("jump out of range from insn %d to %d\n", t, w);
1551 return -EINVAL;
1552 }
1553
f1bca824
AS
1554 if (e == BRANCH)
1555 /* mark branch target for state pruning */
1556 env->explored_states[w] = STATE_LIST_MARK;
1557
475fb78f
AS
1558 if (insn_state[w] == 0) {
1559 /* tree-edge */
1560 insn_state[t] = DISCOVERED | e;
1561 insn_state[w] = DISCOVERED;
1562 if (cur_stack >= env->prog->len)
1563 return -E2BIG;
1564 insn_stack[cur_stack++] = w;
1565 return 1;
1566 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
1567 verbose("back-edge from insn %d to %d\n", t, w);
1568 return -EINVAL;
1569 } else if (insn_state[w] == EXPLORED) {
1570 /* forward- or cross-edge */
1571 insn_state[t] = DISCOVERED | e;
1572 } else {
1573 verbose("insn state internal bug\n");
1574 return -EFAULT;
1575 }
1576 return 0;
1577}
1578
1579/* non-recursive depth-first-search to detect loops in BPF program
1580 * loop == back-edge in directed graph
1581 */
1582static int check_cfg(struct verifier_env *env)
1583{
1584 struct bpf_insn *insns = env->prog->insnsi;
1585 int insn_cnt = env->prog->len;
1586 int ret = 0;
1587 int i, t;
1588
1589 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1590 if (!insn_state)
1591 return -ENOMEM;
1592
1593 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1594 if (!insn_stack) {
1595 kfree(insn_state);
1596 return -ENOMEM;
1597 }
1598
1599 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
1600 insn_stack[0] = 0; /* 0 is the first instruction */
1601 cur_stack = 1;
1602
1603peek_stack:
1604 if (cur_stack == 0)
1605 goto check_state;
1606 t = insn_stack[cur_stack - 1];
1607
1608 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
1609 u8 opcode = BPF_OP(insns[t].code);
1610
1611 if (opcode == BPF_EXIT) {
1612 goto mark_explored;
1613 } else if (opcode == BPF_CALL) {
1614 ret = push_insn(t, t + 1, FALLTHROUGH, env);
1615 if (ret == 1)
1616 goto peek_stack;
1617 else if (ret < 0)
1618 goto err_free;
07016151
DB
1619 if (t + 1 < insn_cnt)
1620 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
1621 } else if (opcode == BPF_JA) {
1622 if (BPF_SRC(insns[t].code) != BPF_K) {
1623 ret = -EINVAL;
1624 goto err_free;
1625 }
1626 /* unconditional jump with single edge */
1627 ret = push_insn(t, t + insns[t].off + 1,
1628 FALLTHROUGH, env);
1629 if (ret == 1)
1630 goto peek_stack;
1631 else if (ret < 0)
1632 goto err_free;
f1bca824
AS
1633 /* tell verifier to check for equivalent states
1634 * after every call and jump
1635 */
c3de6317
AS
1636 if (t + 1 < insn_cnt)
1637 env->explored_states[t + 1] = STATE_LIST_MARK;
475fb78f
AS
1638 } else {
1639 /* conditional jump with two edges */
1640 ret = push_insn(t, t + 1, FALLTHROUGH, env);
1641 if (ret == 1)
1642 goto peek_stack;
1643 else if (ret < 0)
1644 goto err_free;
1645
1646 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
1647 if (ret == 1)
1648 goto peek_stack;
1649 else if (ret < 0)
1650 goto err_free;
1651 }
1652 } else {
1653 /* all other non-branch instructions with single
1654 * fall-through edge
1655 */
1656 ret = push_insn(t, t + 1, FALLTHROUGH, env);
1657 if (ret == 1)
1658 goto peek_stack;
1659 else if (ret < 0)
1660 goto err_free;
1661 }
1662
1663mark_explored:
1664 insn_state[t] = EXPLORED;
1665 if (cur_stack-- <= 0) {
1666 verbose("pop stack internal bug\n");
1667 ret = -EFAULT;
1668 goto err_free;
1669 }
1670 goto peek_stack;
1671
1672check_state:
1673 for (i = 0; i < insn_cnt; i++) {
1674 if (insn_state[i] != EXPLORED) {
1675 verbose("unreachable insn %d\n", i);
1676 ret = -EINVAL;
1677 goto err_free;
1678 }
1679 }
1680 ret = 0; /* cfg looks good */
1681
1682err_free:
1683 kfree(insn_state);
1684 kfree(insn_stack);
1685 return ret;
1686}
1687
f1bca824
AS
1688/* compare two verifier states
1689 *
1690 * all states stored in state_list are known to be valid, since
1691 * verifier reached 'bpf_exit' instruction through them
1692 *
1693 * this function is called when verifier exploring different branches of
1694 * execution popped from the state stack. If it sees an old state that has
1695 * more strict register state and more strict stack state then this execution
1696 * branch doesn't need to be explored further, since verifier already
1697 * concluded that more strict state leads to valid finish.
1698 *
1699 * Therefore two states are equivalent if register state is more conservative
1700 * and explored stack state is more conservative than the current one.
1701 * Example:
1702 * explored current
1703 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
1704 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
1705 *
1706 * In other words if current stack state (one being explored) has more
1707 * valid slots than old one that already passed validation, it means
1708 * the verifier can stop exploring and conclude that current state is valid too
1709 *
1710 * Similarly with registers. If explored state has register type as invalid
1711 * whereas register type in current state is meaningful, it means that
1712 * the current state will reach 'bpf_exit' instruction safely
1713 */
1714static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
1715{
1a0dc1ac 1716 struct reg_state *rold, *rcur;
f1bca824
AS
1717 int i;
1718
1719 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
1720 rold = &old->regs[i];
1721 rcur = &cur->regs[i];
1722
1723 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
1724 continue;
1725
1726 if (rold->type == NOT_INIT ||
1727 (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
1728 continue;
1729
1730 return false;
f1bca824
AS
1731 }
1732
1733 for (i = 0; i < MAX_BPF_STACK; i++) {
9c399760
AS
1734 if (old->stack_slot_type[i] == STACK_INVALID)
1735 continue;
1736 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
1737 /* Ex: old explored (safe) state has STACK_SPILL in
1738 * this stack slot, but current has has STACK_MISC ->
1739 * this verifier states are not equivalent,
1740 * return false to continue verification of this path
1741 */
f1bca824 1742 return false;
9c399760
AS
1743 if (i % BPF_REG_SIZE)
1744 continue;
1745 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
1746 &cur->spilled_regs[i / BPF_REG_SIZE],
1747 sizeof(old->spilled_regs[0])))
1748 /* when explored and current stack slot types are
1749 * the same, check that stored pointers types
1750 * are the same as well.
1751 * Ex: explored safe path could have stored
1752 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
1753 * but current path has stored:
1754 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
1755 * such verifier states are not equivalent.
1756 * return false to continue verification of this path
1757 */
1758 return false;
1759 else
1760 continue;
f1bca824
AS
1761 }
1762 return true;
1763}
1764
1765static int is_state_visited(struct verifier_env *env, int insn_idx)
1766{
1767 struct verifier_state_list *new_sl;
1768 struct verifier_state_list *sl;
1769
1770 sl = env->explored_states[insn_idx];
1771 if (!sl)
1772 /* this 'insn_idx' instruction wasn't marked, so we will not
1773 * be doing state search here
1774 */
1775 return 0;
1776
1777 while (sl != STATE_LIST_MARK) {
1778 if (states_equal(&sl->state, &env->cur_state))
1779 /* reached equivalent register/stack state,
1780 * prune the search
1781 */
1782 return 1;
1783 sl = sl->next;
1784 }
1785
1786 /* there were no equivalent states, remember current one.
1787 * technically the current state is not proven to be safe yet,
1788 * but it will either reach bpf_exit (which means it's safe) or
1789 * it will be rejected. Since there are no loops, we won't be
1790 * seeing this 'insn_idx' instruction again on the way to bpf_exit
1791 */
1792 new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
1793 if (!new_sl)
1794 return -ENOMEM;
1795
1796 /* add new state to the head of linked list */
1797 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
1798 new_sl->next = env->explored_states[insn_idx];
1799 env->explored_states[insn_idx] = new_sl;
1800 return 0;
1801}
1802
17a52670
AS
1803static int do_check(struct verifier_env *env)
1804{
1805 struct verifier_state *state = &env->cur_state;
1806 struct bpf_insn *insns = env->prog->insnsi;
1807 struct reg_state *regs = state->regs;
1808 int insn_cnt = env->prog->len;
1809 int insn_idx, prev_insn_idx = 0;
1810 int insn_processed = 0;
1811 bool do_print_state = false;
1812
1813 init_reg_state(regs);
1814 insn_idx = 0;
1815 for (;;) {
1816 struct bpf_insn *insn;
1817 u8 class;
1818 int err;
1819
1820 if (insn_idx >= insn_cnt) {
1821 verbose("invalid insn idx %d insn_cnt %d\n",
1822 insn_idx, insn_cnt);
1823 return -EFAULT;
1824 }
1825
1826 insn = &insns[insn_idx];
1827 class = BPF_CLASS(insn->code);
1828
07016151 1829 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17a52670
AS
1830 verbose("BPF program is too large. Proccessed %d insn\n",
1831 insn_processed);
1832 return -E2BIG;
1833 }
1834
f1bca824
AS
1835 err = is_state_visited(env, insn_idx);
1836 if (err < 0)
1837 return err;
1838 if (err == 1) {
1839 /* found equivalent state, can prune the search */
1840 if (log_level) {
1841 if (do_print_state)
1842 verbose("\nfrom %d to %d: safe\n",
1843 prev_insn_idx, insn_idx);
1844 else
1845 verbose("%d: safe\n", insn_idx);
1846 }
1847 goto process_bpf_exit;
1848 }
1849
17a52670
AS
1850 if (log_level && do_print_state) {
1851 verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
1a0dc1ac 1852 print_verifier_state(&env->cur_state);
17a52670
AS
1853 do_print_state = false;
1854 }
1855
1856 if (log_level) {
1857 verbose("%d: ", insn_idx);
1858 print_bpf_insn(insn);
1859 }
1860
1861 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 1862 err = check_alu_op(env, insn);
17a52670
AS
1863 if (err)
1864 return err;
1865
1866 } else if (class == BPF_LDX) {
9bac3d6d
AS
1867 enum bpf_reg_type src_reg_type;
1868
1869 /* check for reserved fields is already done */
1870
17a52670
AS
1871 /* check src operand */
1872 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1873 if (err)
1874 return err;
1875
1876 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1877 if (err)
1878 return err;
1879
725f9dcd
AS
1880 src_reg_type = regs[insn->src_reg].type;
1881
17a52670
AS
1882 /* check that memory (src_reg + off) is readable,
1883 * the state of dst_reg will be updated by this func
1884 */
1885 err = check_mem_access(env, insn->src_reg, insn->off,
1886 BPF_SIZE(insn->code), BPF_READ,
1887 insn->dst_reg);
1888 if (err)
1889 return err;
1890
725f9dcd
AS
1891 if (BPF_SIZE(insn->code) != BPF_W) {
1892 insn_idx++;
1893 continue;
1894 }
9bac3d6d 1895
725f9dcd 1896 if (insn->imm == 0) {
9bac3d6d
AS
1897 /* saw a valid insn
1898 * dst_reg = *(u32 *)(src_reg + off)
1899 * use reserved 'imm' field to mark this insn
1900 */
1901 insn->imm = src_reg_type;
1902
1903 } else if (src_reg_type != insn->imm &&
1904 (src_reg_type == PTR_TO_CTX ||
1905 insn->imm == PTR_TO_CTX)) {
1906 /* ABuser program is trying to use the same insn
1907 * dst_reg = *(u32*) (src_reg + off)
1908 * with different pointer types:
1909 * src_reg == ctx in one branch and
1910 * src_reg == stack|map in some other branch.
1911 * Reject it.
1912 */
1913 verbose("same insn cannot be used with different pointers\n");
1914 return -EINVAL;
1915 }
1916
17a52670 1917 } else if (class == BPF_STX) {
d691f9e8
AS
1918 enum bpf_reg_type dst_reg_type;
1919
17a52670
AS
1920 if (BPF_MODE(insn->code) == BPF_XADD) {
1921 err = check_xadd(env, insn);
1922 if (err)
1923 return err;
1924 insn_idx++;
1925 continue;
1926 }
1927
17a52670
AS
1928 /* check src1 operand */
1929 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1930 if (err)
1931 return err;
1932 /* check src2 operand */
1933 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1934 if (err)
1935 return err;
1936
d691f9e8
AS
1937 dst_reg_type = regs[insn->dst_reg].type;
1938
17a52670
AS
1939 /* check that memory (dst_reg + off) is writeable */
1940 err = check_mem_access(env, insn->dst_reg, insn->off,
1941 BPF_SIZE(insn->code), BPF_WRITE,
1942 insn->src_reg);
1943 if (err)
1944 return err;
1945
d691f9e8
AS
1946 if (insn->imm == 0) {
1947 insn->imm = dst_reg_type;
1948 } else if (dst_reg_type != insn->imm &&
1949 (dst_reg_type == PTR_TO_CTX ||
1950 insn->imm == PTR_TO_CTX)) {
1951 verbose("same insn cannot be used with different pointers\n");
1952 return -EINVAL;
1953 }
1954
17a52670
AS
1955 } else if (class == BPF_ST) {
1956 if (BPF_MODE(insn->code) != BPF_MEM ||
1957 insn->src_reg != BPF_REG_0) {
1958 verbose("BPF_ST uses reserved fields\n");
1959 return -EINVAL;
1960 }
1961 /* check src operand */
1962 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1963 if (err)
1964 return err;
1965
1966 /* check that memory (dst_reg + off) is writeable */
1967 err = check_mem_access(env, insn->dst_reg, insn->off,
1968 BPF_SIZE(insn->code), BPF_WRITE,
1969 -1);
1970 if (err)
1971 return err;
1972
1973 } else if (class == BPF_JMP) {
1974 u8 opcode = BPF_OP(insn->code);
1975
1976 if (opcode == BPF_CALL) {
1977 if (BPF_SRC(insn->code) != BPF_K ||
1978 insn->off != 0 ||
1979 insn->src_reg != BPF_REG_0 ||
1980 insn->dst_reg != BPF_REG_0) {
1981 verbose("BPF_CALL uses reserved fields\n");
1982 return -EINVAL;
1983 }
1984
1985 err = check_call(env, insn->imm);
1986 if (err)
1987 return err;
1988
1989 } else if (opcode == BPF_JA) {
1990 if (BPF_SRC(insn->code) != BPF_K ||
1991 insn->imm != 0 ||
1992 insn->src_reg != BPF_REG_0 ||
1993 insn->dst_reg != BPF_REG_0) {
1994 verbose("BPF_JA uses reserved fields\n");
1995 return -EINVAL;
1996 }
1997
1998 insn_idx += insn->off + 1;
1999 continue;
2000
2001 } else if (opcode == BPF_EXIT) {
2002 if (BPF_SRC(insn->code) != BPF_K ||
2003 insn->imm != 0 ||
2004 insn->src_reg != BPF_REG_0 ||
2005 insn->dst_reg != BPF_REG_0) {
2006 verbose("BPF_EXIT uses reserved fields\n");
2007 return -EINVAL;
2008 }
2009
2010 /* eBPF calling convetion is such that R0 is used
2011 * to return the value from eBPF program.
2012 * Make sure that it's readable at this time
2013 * of bpf_exit, which means that program wrote
2014 * something into it earlier
2015 */
2016 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2017 if (err)
2018 return err;
2019
1be7f75d
AS
2020 if (is_pointer_value(env, BPF_REG_0)) {
2021 verbose("R0 leaks addr as return value\n");
2022 return -EACCES;
2023 }
2024
f1bca824 2025process_bpf_exit:
17a52670
AS
2026 insn_idx = pop_stack(env, &prev_insn_idx);
2027 if (insn_idx < 0) {
2028 break;
2029 } else {
2030 do_print_state = true;
2031 continue;
2032 }
2033 } else {
2034 err = check_cond_jmp_op(env, insn, &insn_idx);
2035 if (err)
2036 return err;
2037 }
2038 } else if (class == BPF_LD) {
2039 u8 mode = BPF_MODE(insn->code);
2040
2041 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
2042 err = check_ld_abs(env, insn);
2043 if (err)
2044 return err;
2045
17a52670
AS
2046 } else if (mode == BPF_IMM) {
2047 err = check_ld_imm(env, insn);
2048 if (err)
2049 return err;
2050
2051 insn_idx++;
2052 } else {
2053 verbose("invalid BPF_LD mode\n");
2054 return -EINVAL;
2055 }
2056 } else {
2057 verbose("unknown insn class %d\n", class);
2058 return -EINVAL;
2059 }
2060
2061 insn_idx++;
2062 }
2063
1a0dc1ac 2064 verbose("processed %d insns\n", insn_processed);
17a52670
AS
2065 return 0;
2066}
2067
0246e64d
AS
2068/* look for pseudo eBPF instructions that access map FDs and
2069 * replace them with actual map pointers
2070 */
2071static int replace_map_fd_with_map_ptr(struct verifier_env *env)
2072{
2073 struct bpf_insn *insn = env->prog->insnsi;
2074 int insn_cnt = env->prog->len;
2075 int i, j;
2076
2077 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 2078 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 2079 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
9bac3d6d
AS
2080 verbose("BPF_LDX uses reserved fields\n");
2081 return -EINVAL;
2082 }
2083
d691f9e8
AS
2084 if (BPF_CLASS(insn->code) == BPF_STX &&
2085 ((BPF_MODE(insn->code) != BPF_MEM &&
2086 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2087 verbose("BPF_STX uses reserved fields\n");
2088 return -EINVAL;
2089 }
2090
0246e64d
AS
2091 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2092 struct bpf_map *map;
2093 struct fd f;
2094
2095 if (i == insn_cnt - 1 || insn[1].code != 0 ||
2096 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2097 insn[1].off != 0) {
2098 verbose("invalid bpf_ld_imm64 insn\n");
2099 return -EINVAL;
2100 }
2101
2102 if (insn->src_reg == 0)
2103 /* valid generic load 64-bit imm */
2104 goto next_insn;
2105
2106 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2107 verbose("unrecognized bpf_ld_imm64 insn\n");
2108 return -EINVAL;
2109 }
2110
2111 f = fdget(insn->imm);
c2101297 2112 map = __bpf_map_get(f);
0246e64d
AS
2113 if (IS_ERR(map)) {
2114 verbose("fd %d is not pointing to valid bpf_map\n",
2115 insn->imm);
0246e64d
AS
2116 return PTR_ERR(map);
2117 }
2118
2119 /* store map pointer inside BPF_LD_IMM64 instruction */
2120 insn[0].imm = (u32) (unsigned long) map;
2121 insn[1].imm = ((u64) (unsigned long) map) >> 32;
2122
2123 /* check whether we recorded this map already */
2124 for (j = 0; j < env->used_map_cnt; j++)
2125 if (env->used_maps[j] == map) {
2126 fdput(f);
2127 goto next_insn;
2128 }
2129
2130 if (env->used_map_cnt >= MAX_USED_MAPS) {
2131 fdput(f);
2132 return -E2BIG;
2133 }
2134
0246e64d
AS
2135 /* hold the map. If the program is rejected by verifier,
2136 * the map will be released by release_maps() or it
2137 * will be used by the valid program until it's unloaded
2138 * and all maps are released in free_bpf_prog_info()
2139 */
92117d84
AS
2140 map = bpf_map_inc(map, false);
2141 if (IS_ERR(map)) {
2142 fdput(f);
2143 return PTR_ERR(map);
2144 }
2145 env->used_maps[env->used_map_cnt++] = map;
2146
0246e64d
AS
2147 fdput(f);
2148next_insn:
2149 insn++;
2150 i++;
2151 }
2152 }
2153
2154 /* now all pseudo BPF_LD_IMM64 instructions load valid
2155 * 'struct bpf_map *' into a register instead of user map_fd.
2156 * These pointers will be used later by verifier to validate map access.
2157 */
2158 return 0;
2159}
2160
2161/* drop refcnt of maps used by the rejected program */
2162static void release_maps(struct verifier_env *env)
2163{
2164 int i;
2165
2166 for (i = 0; i < env->used_map_cnt; i++)
2167 bpf_map_put(env->used_maps[i]);
2168}
2169
2170/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2171static void convert_pseudo_ld_imm64(struct verifier_env *env)
2172{
2173 struct bpf_insn *insn = env->prog->insnsi;
2174 int insn_cnt = env->prog->len;
2175 int i;
2176
2177 for (i = 0; i < insn_cnt; i++, insn++)
2178 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2179 insn->src_reg = 0;
2180}
2181
9bac3d6d
AS
2182static void adjust_branches(struct bpf_prog *prog, int pos, int delta)
2183{
2184 struct bpf_insn *insn = prog->insnsi;
2185 int insn_cnt = prog->len;
2186 int i;
2187
2188 for (i = 0; i < insn_cnt; i++, insn++) {
2189 if (BPF_CLASS(insn->code) != BPF_JMP ||
2190 BPF_OP(insn->code) == BPF_CALL ||
2191 BPF_OP(insn->code) == BPF_EXIT)
2192 continue;
2193
2194 /* adjust offset of jmps if necessary */
2195 if (i < pos && i + insn->off + 1 > pos)
2196 insn->off += delta;
a1b14d27 2197 else if (i > pos + delta && i + insn->off + 1 <= pos + delta)
9bac3d6d
AS
2198 insn->off -= delta;
2199 }
2200}
2201
2202/* convert load instructions that access fields of 'struct __sk_buff'
2203 * into sequence of instructions that access fields of 'struct sk_buff'
2204 */
2205static int convert_ctx_accesses(struct verifier_env *env)
2206{
2207 struct bpf_insn *insn = env->prog->insnsi;
2208 int insn_cnt = env->prog->len;
2209 struct bpf_insn insn_buf[16];
2210 struct bpf_prog *new_prog;
2211 u32 cnt;
2212 int i;
d691f9e8 2213 enum bpf_access_type type;
9bac3d6d
AS
2214
2215 if (!env->prog->aux->ops->convert_ctx_access)
2216 return 0;
2217
2218 for (i = 0; i < insn_cnt; i++, insn++) {
d691f9e8
AS
2219 if (insn->code == (BPF_LDX | BPF_MEM | BPF_W))
2220 type = BPF_READ;
2221 else if (insn->code == (BPF_STX | BPF_MEM | BPF_W))
2222 type = BPF_WRITE;
2223 else
9bac3d6d
AS
2224 continue;
2225
2226 if (insn->imm != PTR_TO_CTX) {
2227 /* clear internal mark */
2228 insn->imm = 0;
2229 continue;
2230 }
2231
2232 cnt = env->prog->aux->ops->
d691f9e8 2233 convert_ctx_access(type, insn->dst_reg, insn->src_reg,
ff936a04 2234 insn->off, insn_buf, env->prog);
9bac3d6d
AS
2235 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
2236 verbose("bpf verifier is misconfigured\n");
2237 return -EINVAL;
2238 }
2239
2240 if (cnt == 1) {
2241 memcpy(insn, insn_buf, sizeof(*insn));
2242 continue;
2243 }
2244
2245 /* several new insns need to be inserted. Make room for them */
2246 insn_cnt += cnt - 1;
2247 new_prog = bpf_prog_realloc(env->prog,
2248 bpf_prog_size(insn_cnt),
2249 GFP_USER);
2250 if (!new_prog)
2251 return -ENOMEM;
2252
2253 new_prog->len = insn_cnt;
2254
2255 memmove(new_prog->insnsi + i + cnt, new_prog->insns + i + 1,
2256 sizeof(*insn) * (insn_cnt - i - cnt));
2257
2258 /* copy substitute insns in place of load instruction */
2259 memcpy(new_prog->insnsi + i, insn_buf, sizeof(*insn) * cnt);
2260
2261 /* adjust branches in the whole program */
2262 adjust_branches(new_prog, i, cnt - 1);
2263
2264 /* keep walking new program and skip insns we just inserted */
2265 env->prog = new_prog;
2266 insn = new_prog->insnsi + i + cnt - 1;
2267 i += cnt - 1;
2268 }
2269
2270 return 0;
2271}
2272
f1bca824
AS
2273static void free_states(struct verifier_env *env)
2274{
2275 struct verifier_state_list *sl, *sln;
2276 int i;
2277
2278 if (!env->explored_states)
2279 return;
2280
2281 for (i = 0; i < env->prog->len; i++) {
2282 sl = env->explored_states[i];
2283
2284 if (sl)
2285 while (sl != STATE_LIST_MARK) {
2286 sln = sl->next;
2287 kfree(sl);
2288 sl = sln;
2289 }
2290 }
2291
2292 kfree(env->explored_states);
2293}
2294
9bac3d6d 2295int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
51580e79 2296{
cbd35700
AS
2297 char __user *log_ubuf = NULL;
2298 struct verifier_env *env;
51580e79
AS
2299 int ret = -EINVAL;
2300
9bac3d6d 2301 if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
cbd35700
AS
2302 return -E2BIG;
2303
2304 /* 'struct verifier_env' can be global, but since it's not small,
2305 * allocate/free it every time bpf_check() is called
2306 */
2307 env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
2308 if (!env)
2309 return -ENOMEM;
2310
9bac3d6d 2311 env->prog = *prog;
0246e64d 2312
cbd35700
AS
2313 /* grab the mutex to protect few globals used by verifier */
2314 mutex_lock(&bpf_verifier_lock);
2315
2316 if (attr->log_level || attr->log_buf || attr->log_size) {
2317 /* user requested verbose verifier output
2318 * and supplied buffer to store the verification trace
2319 */
2320 log_level = attr->log_level;
2321 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
2322 log_size = attr->log_size;
2323 log_len = 0;
2324
2325 ret = -EINVAL;
2326 /* log_* values have to be sane */
2327 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
2328 log_level == 0 || log_ubuf == NULL)
2329 goto free_env;
2330
2331 ret = -ENOMEM;
2332 log_buf = vmalloc(log_size);
2333 if (!log_buf)
2334 goto free_env;
2335 } else {
2336 log_level = 0;
2337 }
2338
0246e64d
AS
2339 ret = replace_map_fd_with_map_ptr(env);
2340 if (ret < 0)
2341 goto skip_full_check;
2342
9bac3d6d 2343 env->explored_states = kcalloc(env->prog->len,
f1bca824
AS
2344 sizeof(struct verifier_state_list *),
2345 GFP_USER);
2346 ret = -ENOMEM;
2347 if (!env->explored_states)
2348 goto skip_full_check;
2349
475fb78f
AS
2350 ret = check_cfg(env);
2351 if (ret < 0)
2352 goto skip_full_check;
2353
1be7f75d
AS
2354 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2355
17a52670 2356 ret = do_check(env);
cbd35700 2357
0246e64d 2358skip_full_check:
17a52670 2359 while (pop_stack(env, NULL) >= 0);
f1bca824 2360 free_states(env);
0246e64d 2361
9bac3d6d
AS
2362 if (ret == 0)
2363 /* program is valid, convert *(u32*)(ctx + off) accesses */
2364 ret = convert_ctx_accesses(env);
2365
cbd35700
AS
2366 if (log_level && log_len >= log_size - 1) {
2367 BUG_ON(log_len >= log_size);
2368 /* verifier log exceeded user supplied buffer */
2369 ret = -ENOSPC;
2370 /* fall through to return what was recorded */
2371 }
2372
2373 /* copy verifier log back to user space including trailing zero */
2374 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
2375 ret = -EFAULT;
2376 goto free_log_buf;
2377 }
2378
0246e64d
AS
2379 if (ret == 0 && env->used_map_cnt) {
2380 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
2381 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
2382 sizeof(env->used_maps[0]),
2383 GFP_KERNEL);
0246e64d 2384
9bac3d6d 2385 if (!env->prog->aux->used_maps) {
0246e64d
AS
2386 ret = -ENOMEM;
2387 goto free_log_buf;
2388 }
2389
9bac3d6d 2390 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 2391 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 2392 env->prog->aux->used_map_cnt = env->used_map_cnt;
0246e64d
AS
2393
2394 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
2395 * bpf_ld_imm64 instructions
2396 */
2397 convert_pseudo_ld_imm64(env);
2398 }
cbd35700
AS
2399
2400free_log_buf:
2401 if (log_level)
2402 vfree(log_buf);
2403free_env:
9bac3d6d 2404 if (!env->prog->aux->used_maps)
0246e64d
AS
2405 /* if we didn't copy map pointers into bpf_prog_info, release
2406 * them now. Otherwise free_bpf_prog_info() will release them.
2407 */
2408 release_maps(env);
9bac3d6d 2409 *prog = env->prog;
cbd35700
AS
2410 kfree(env);
2411 mutex_unlock(&bpf_verifier_lock);
51580e79
AS
2412 return ret;
2413}