1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
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.
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.
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>
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.
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
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
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
48 * At the start of BPF program the register R1 contains a pointer to bpf_context
49 * and has type PTR_TO_CTX.
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.
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)
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.
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.
72 * registers used to pass values to function calls are checked against
73 * function argument constraints.
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'
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,
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.
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)
93 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
94 * void *key = (void *) (unsigned long) r2;
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.
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
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.
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().
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.
128 /* types of values stored in eBPF registers */
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 */
142 enum bpf_reg_type type
;
144 /* valid when type == CONST_IMM | PTR_TO_STACK */
147 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
148 * PTR_TO_MAP_VALUE_OR_NULL
150 struct bpf_map
*map_ptr
;
154 enum bpf_stack_slot_type
{
155 STACK_INVALID
, /* nothing was stored in this stack slot */
156 STACK_SPILL
, /* register spilled into stack */
157 STACK_MISC
/* BPF program wrote some data into this slot */
160 #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
162 /* state of the program:
163 * type of all registers and stack info
165 struct verifier_state
{
166 struct reg_state regs
[MAX_BPF_REG
];
167 u8 stack_slot_type
[MAX_BPF_STACK
];
168 struct reg_state spilled_regs
[MAX_BPF_STACK
/ BPF_REG_SIZE
];
171 /* linked list of verifier states used to prune search */
172 struct verifier_state_list
{
173 struct verifier_state state
;
174 struct verifier_state_list
*next
;
177 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
178 struct verifier_stack_elem
{
179 /* verifer state is 'st'
180 * before processing instruction 'insn_idx'
181 * and after processing instruction 'prev_insn_idx'
183 struct verifier_state st
;
186 struct verifier_stack_elem
*next
;
189 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
191 /* single container for all structs
192 * one verifier_env per bpf_check() call
194 struct verifier_env
{
195 struct bpf_prog
*prog
; /* eBPF program being verified */
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 */
199 struct verifier_state_list
**explored_states
; /* search pruning optimization */
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 */
204 /* verbose verifier prints what it's seeing
205 * bpf_check() is called under lock, so no race to access these global vars
207 static u32 log_level
, log_size
, log_len
;
208 static char *log_buf
;
210 static DEFINE_MUTEX(bpf_verifier_lock
);
212 /* log_level controls verbosity level of eBPF verifier.
213 * verbose() is used to dump the verification trace to the log, so the user
214 * can figure out what's wrong with the program
216 static void verbose(const char *fmt
, ...)
220 if (log_level
== 0 || log_len
>= log_size
- 1)
224 log_len
+= vscnprintf(log_buf
+ log_len
, log_size
- log_len
, fmt
, args
);
228 /* string representation of 'enum bpf_reg_type' */
229 static const char * const reg_type_str
[] = {
231 [UNKNOWN_VALUE
] = "inv",
232 [PTR_TO_CTX
] = "ctx",
233 [CONST_PTR_TO_MAP
] = "map_ptr",
234 [PTR_TO_MAP_VALUE
] = "map_value",
235 [PTR_TO_MAP_VALUE_OR_NULL
] = "map_value_or_null",
237 [PTR_TO_STACK
] = "fp",
241 static void print_verifier_state(struct verifier_env
*env
)
246 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
247 t
= env
->cur_state
.regs
[i
].type
;
250 verbose(" R%d=%s", i
, reg_type_str
[t
]);
251 if (t
== CONST_IMM
|| t
== PTR_TO_STACK
)
252 verbose("%d", env
->cur_state
.regs
[i
].imm
);
253 else if (t
== CONST_PTR_TO_MAP
|| t
== PTR_TO_MAP_VALUE
||
254 t
== PTR_TO_MAP_VALUE_OR_NULL
)
255 verbose("(ks=%d,vs=%d)",
256 env
->cur_state
.regs
[i
].map_ptr
->key_size
,
257 env
->cur_state
.regs
[i
].map_ptr
->value_size
);
259 for (i
= 0; i
< MAX_BPF_STACK
; i
+= BPF_REG_SIZE
) {
260 if (env
->cur_state
.stack_slot_type
[i
] == STACK_SPILL
)
261 verbose(" fp%d=%s", -MAX_BPF_STACK
+ i
,
262 reg_type_str
[env
->cur_state
.spilled_regs
[i
/ BPF_REG_SIZE
].type
]);
267 static const char *const bpf_class_string
[] = {
275 [BPF_ALU64
] = "alu64",
278 static const char *const bpf_alu_string
[] = {
279 [BPF_ADD
>> 4] = "+=",
280 [BPF_SUB
>> 4] = "-=",
281 [BPF_MUL
>> 4] = "*=",
282 [BPF_DIV
>> 4] = "/=",
283 [BPF_OR
>> 4] = "|=",
284 [BPF_AND
>> 4] = "&=",
285 [BPF_LSH
>> 4] = "<<=",
286 [BPF_RSH
>> 4] = ">>=",
287 [BPF_NEG
>> 4] = "neg",
288 [BPF_MOD
>> 4] = "%=",
289 [BPF_XOR
>> 4] = "^=",
290 [BPF_MOV
>> 4] = "=",
291 [BPF_ARSH
>> 4] = "s>>=",
292 [BPF_END
>> 4] = "endian",
295 static const char *const bpf_ldst_string
[] = {
296 [BPF_W
>> 3] = "u32",
297 [BPF_H
>> 3] = "u16",
299 [BPF_DW
>> 3] = "u64",
302 static const char *const bpf_jmp_string
[] = {
303 [BPF_JA
>> 4] = "jmp",
304 [BPF_JEQ
>> 4] = "==",
305 [BPF_JGT
>> 4] = ">",
306 [BPF_JGE
>> 4] = ">=",
307 [BPF_JSET
>> 4] = "&",
308 [BPF_JNE
>> 4] = "!=",
309 [BPF_JSGT
>> 4] = "s>",
310 [BPF_JSGE
>> 4] = "s>=",
311 [BPF_CALL
>> 4] = "call",
312 [BPF_EXIT
>> 4] = "exit",
315 static void print_bpf_insn(struct bpf_insn
*insn
)
317 u8
class = BPF_CLASS(insn
->code
);
319 if (class == BPF_ALU
|| class == BPF_ALU64
) {
320 if (BPF_SRC(insn
->code
) == BPF_X
)
321 verbose("(%02x) %sr%d %s %sr%d\n",
322 insn
->code
, class == BPF_ALU
? "(u32) " : "",
324 bpf_alu_string
[BPF_OP(insn
->code
) >> 4],
325 class == BPF_ALU
? "(u32) " : "",
328 verbose("(%02x) %sr%d %s %s%d\n",
329 insn
->code
, class == BPF_ALU
? "(u32) " : "",
331 bpf_alu_string
[BPF_OP(insn
->code
) >> 4],
332 class == BPF_ALU
? "(u32) " : "",
334 } else if (class == BPF_STX
) {
335 if (BPF_MODE(insn
->code
) == BPF_MEM
)
336 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
338 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
340 insn
->off
, insn
->src_reg
);
341 else if (BPF_MODE(insn
->code
) == BPF_XADD
)
342 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
344 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
345 insn
->dst_reg
, insn
->off
,
348 verbose("BUG_%02x\n", insn
->code
);
349 } else if (class == BPF_ST
) {
350 if (BPF_MODE(insn
->code
) != BPF_MEM
) {
351 verbose("BUG_st_%02x\n", insn
->code
);
354 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
356 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
358 insn
->off
, insn
->imm
);
359 } else if (class == BPF_LDX
) {
360 if (BPF_MODE(insn
->code
) != BPF_MEM
) {
361 verbose("BUG_ldx_%02x\n", insn
->code
);
364 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
365 insn
->code
, insn
->dst_reg
,
366 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
367 insn
->src_reg
, insn
->off
);
368 } else if (class == BPF_LD
) {
369 if (BPF_MODE(insn
->code
) == BPF_ABS
) {
370 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
372 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
374 } else if (BPF_MODE(insn
->code
) == BPF_IND
) {
375 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
377 bpf_ldst_string
[BPF_SIZE(insn
->code
) >> 3],
378 insn
->src_reg
, insn
->imm
);
379 } else if (BPF_MODE(insn
->code
) == BPF_IMM
) {
380 verbose("(%02x) r%d = 0x%x\n",
381 insn
->code
, insn
->dst_reg
, insn
->imm
);
383 verbose("BUG_ld_%02x\n", insn
->code
);
386 } else if (class == BPF_JMP
) {
387 u8 opcode
= BPF_OP(insn
->code
);
389 if (opcode
== BPF_CALL
) {
390 verbose("(%02x) call %d\n", insn
->code
, insn
->imm
);
391 } else if (insn
->code
== (BPF_JMP
| BPF_JA
)) {
392 verbose("(%02x) goto pc%+d\n",
393 insn
->code
, insn
->off
);
394 } else if (insn
->code
== (BPF_JMP
| BPF_EXIT
)) {
395 verbose("(%02x) exit\n", insn
->code
);
396 } else if (BPF_SRC(insn
->code
) == BPF_X
) {
397 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
398 insn
->code
, insn
->dst_reg
,
399 bpf_jmp_string
[BPF_OP(insn
->code
) >> 4],
400 insn
->src_reg
, insn
->off
);
402 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
403 insn
->code
, insn
->dst_reg
,
404 bpf_jmp_string
[BPF_OP(insn
->code
) >> 4],
405 insn
->imm
, insn
->off
);
408 verbose("(%02x) %s\n", insn
->code
, bpf_class_string
[class]);
412 static int pop_stack(struct verifier_env
*env
, int *prev_insn_idx
)
414 struct verifier_stack_elem
*elem
;
417 if (env
->head
== NULL
)
420 memcpy(&env
->cur_state
, &env
->head
->st
, sizeof(env
->cur_state
));
421 insn_idx
= env
->head
->insn_idx
;
423 *prev_insn_idx
= env
->head
->prev_insn_idx
;
424 elem
= env
->head
->next
;
431 static struct verifier_state
*push_stack(struct verifier_env
*env
, int insn_idx
,
434 struct verifier_stack_elem
*elem
;
436 elem
= kmalloc(sizeof(struct verifier_stack_elem
), GFP_KERNEL
);
440 memcpy(&elem
->st
, &env
->cur_state
, sizeof(env
->cur_state
));
441 elem
->insn_idx
= insn_idx
;
442 elem
->prev_insn_idx
= prev_insn_idx
;
443 elem
->next
= env
->head
;
446 if (env
->stack_size
> 1024) {
447 verbose("BPF program is too complex\n");
452 /* pop all elements and return */
453 while (pop_stack(env
, NULL
) >= 0);
457 #define CALLER_SAVED_REGS 6
458 static const int caller_saved
[CALLER_SAVED_REGS
] = {
459 BPF_REG_0
, BPF_REG_1
, BPF_REG_2
, BPF_REG_3
, BPF_REG_4
, BPF_REG_5
462 static void init_reg_state(struct reg_state
*regs
)
466 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
467 regs
[i
].type
= NOT_INIT
;
469 regs
[i
].map_ptr
= NULL
;
473 regs
[BPF_REG_FP
].type
= FRAME_PTR
;
475 /* 1st arg to a function */
476 regs
[BPF_REG_1
].type
= PTR_TO_CTX
;
479 static void mark_reg_unknown_value(struct reg_state
*regs
, u32 regno
)
481 BUG_ON(regno
>= MAX_BPF_REG
);
482 regs
[regno
].type
= UNKNOWN_VALUE
;
484 regs
[regno
].map_ptr
= NULL
;
488 SRC_OP
, /* register is used as source operand */
489 DST_OP
, /* register is used as destination operand */
490 DST_OP_NO_MARK
/* same as above, check only, don't mark */
493 static int check_reg_arg(struct reg_state
*regs
, u32 regno
,
496 if (regno
>= MAX_BPF_REG
) {
497 verbose("R%d is invalid\n", regno
);
502 /* check whether register used as source operand can be read */
503 if (regs
[regno
].type
== NOT_INIT
) {
504 verbose("R%d !read_ok\n", regno
);
508 /* check whether register used as dest operand can be written to */
509 if (regno
== BPF_REG_FP
) {
510 verbose("frame pointer is read only\n");
514 mark_reg_unknown_value(regs
, regno
);
519 static int bpf_size_to_bytes(int bpf_size
)
521 if (bpf_size
== BPF_W
)
523 else if (bpf_size
== BPF_H
)
525 else if (bpf_size
== BPF_B
)
527 else if (bpf_size
== BPF_DW
)
533 /* check_stack_read/write functions track spill/fill of registers,
534 * stack boundary and alignment are checked in check_mem_access()
536 static int check_stack_write(struct verifier_state
*state
, int off
, int size
,
540 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
541 * so it's aligned access and [off, off + size) are within stack limits
544 if (value_regno
>= 0 &&
545 (state
->regs
[value_regno
].type
== PTR_TO_MAP_VALUE
||
546 state
->regs
[value_regno
].type
== PTR_TO_STACK
||
547 state
->regs
[value_regno
].type
== PTR_TO_CTX
)) {
549 /* register containing pointer is being spilled into stack */
550 if (size
!= BPF_REG_SIZE
) {
551 verbose("invalid size of register spill\n");
555 /* save register state */
556 state
->spilled_regs
[(MAX_BPF_STACK
+ off
) / BPF_REG_SIZE
] =
557 state
->regs
[value_regno
];
559 for (i
= 0; i
< BPF_REG_SIZE
; i
++)
560 state
->stack_slot_type
[MAX_BPF_STACK
+ off
+ i
] = STACK_SPILL
;
562 /* regular write of data into stack */
563 state
->spilled_regs
[(MAX_BPF_STACK
+ off
) / BPF_REG_SIZE
] =
564 (struct reg_state
) {};
566 for (i
= 0; i
< size
; i
++)
567 state
->stack_slot_type
[MAX_BPF_STACK
+ off
+ i
] = STACK_MISC
;
572 static int check_stack_read(struct verifier_state
*state
, int off
, int size
,
578 slot_type
= &state
->stack_slot_type
[MAX_BPF_STACK
+ off
];
580 if (slot_type
[0] == STACK_SPILL
) {
581 if (size
!= BPF_REG_SIZE
) {
582 verbose("invalid size of register spill\n");
585 for (i
= 1; i
< BPF_REG_SIZE
; i
++) {
586 if (slot_type
[i
] != STACK_SPILL
) {
587 verbose("corrupted spill memory\n");
592 if (value_regno
>= 0)
593 /* restore register state from stack */
594 state
->regs
[value_regno
] =
595 state
->spilled_regs
[(MAX_BPF_STACK
+ off
) / BPF_REG_SIZE
];
598 for (i
= 0; i
< size
; i
++) {
599 if (slot_type
[i
] != STACK_MISC
) {
600 verbose("invalid read from stack off %d+%d size %d\n",
605 if (value_regno
>= 0)
606 /* have read misc data from the stack */
607 mark_reg_unknown_value(state
->regs
, value_regno
);
612 /* check read/write into map element returned by bpf_map_lookup_elem() */
613 static int check_map_access(struct verifier_env
*env
, u32 regno
, int off
,
616 struct bpf_map
*map
= env
->cur_state
.regs
[regno
].map_ptr
;
618 if (off
< 0 || off
+ size
> map
->value_size
) {
619 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
620 map
->value_size
, off
, size
);
626 /* check access to 'struct bpf_context' fields */
627 static int check_ctx_access(struct verifier_env
*env
, int off
, int size
,
628 enum bpf_access_type t
)
630 if (env
->prog
->aux
->ops
->is_valid_access
&&
631 env
->prog
->aux
->ops
->is_valid_access(off
, size
, t
))
634 verbose("invalid bpf_context access off=%d size=%d\n", off
, size
);
638 /* check whether memory at (regno + off) is accessible for t = (read | write)
639 * if t==write, value_regno is a register which value is stored into memory
640 * if t==read, value_regno is a register which will receive the value from memory
641 * if t==write && value_regno==-1, some unknown value is stored into memory
642 * if t==read && value_regno==-1, don't care what we read from memory
644 static int check_mem_access(struct verifier_env
*env
, u32 regno
, int off
,
645 int bpf_size
, enum bpf_access_type t
,
648 struct verifier_state
*state
= &env
->cur_state
;
651 size
= bpf_size_to_bytes(bpf_size
);
655 if (off
% size
!= 0) {
656 verbose("misaligned access off %d size %d\n", off
, size
);
660 if (state
->regs
[regno
].type
== PTR_TO_MAP_VALUE
) {
661 err
= check_map_access(env
, regno
, off
, size
);
662 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
663 mark_reg_unknown_value(state
->regs
, value_regno
);
665 } else if (state
->regs
[regno
].type
== PTR_TO_CTX
) {
666 err
= check_ctx_access(env
, off
, size
, t
);
667 if (!err
&& t
== BPF_READ
&& value_regno
>= 0)
668 mark_reg_unknown_value(state
->regs
, value_regno
);
670 } else if (state
->regs
[regno
].type
== FRAME_PTR
) {
671 if (off
>= 0 || off
< -MAX_BPF_STACK
) {
672 verbose("invalid stack off=%d size=%d\n", off
, size
);
676 err
= check_stack_write(state
, off
, size
, value_regno
);
678 err
= check_stack_read(state
, off
, size
, value_regno
);
680 verbose("R%d invalid mem access '%s'\n",
681 regno
, reg_type_str
[state
->regs
[regno
].type
]);
687 static int check_xadd(struct verifier_env
*env
, struct bpf_insn
*insn
)
689 struct reg_state
*regs
= env
->cur_state
.regs
;
692 if ((BPF_SIZE(insn
->code
) != BPF_W
&& BPF_SIZE(insn
->code
) != BPF_DW
) ||
694 verbose("BPF_XADD uses reserved fields\n");
698 /* check src1 operand */
699 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
703 /* check src2 operand */
704 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
708 /* check whether atomic_add can read the memory */
709 err
= check_mem_access(env
, insn
->dst_reg
, insn
->off
,
710 BPF_SIZE(insn
->code
), BPF_READ
, -1);
714 /* check whether atomic_add can write into the same memory */
715 return check_mem_access(env
, insn
->dst_reg
, insn
->off
,
716 BPF_SIZE(insn
->code
), BPF_WRITE
, -1);
719 /* when register 'regno' is passed into function that will read 'access_size'
720 * bytes from that pointer, make sure that it's within stack boundary
721 * and all elements of stack are initialized
723 static int check_stack_boundary(struct verifier_env
*env
,
724 int regno
, int access_size
)
726 struct verifier_state
*state
= &env
->cur_state
;
727 struct reg_state
*regs
= state
->regs
;
730 if (regs
[regno
].type
!= PTR_TO_STACK
)
733 off
= regs
[regno
].imm
;
734 if (off
>= 0 || off
< -MAX_BPF_STACK
|| off
+ access_size
> 0 ||
736 verbose("invalid stack type R%d off=%d access_size=%d\n",
737 regno
, off
, access_size
);
741 for (i
= 0; i
< access_size
; i
++) {
742 if (state
->stack_slot_type
[MAX_BPF_STACK
+ off
+ i
] != STACK_MISC
) {
743 verbose("invalid indirect read from stack off %d+%d size %d\n",
744 off
, i
, access_size
);
751 static int check_func_arg(struct verifier_env
*env
, u32 regno
,
752 enum bpf_arg_type arg_type
, struct bpf_map
**mapp
)
754 struct reg_state
*reg
= env
->cur_state
.regs
+ regno
;
755 enum bpf_reg_type expected_type
;
758 if (arg_type
== ARG_DONTCARE
)
761 if (reg
->type
== NOT_INIT
) {
762 verbose("R%d !read_ok\n", regno
);
766 if (arg_type
== ARG_ANYTHING
)
769 if (arg_type
== ARG_PTR_TO_STACK
|| arg_type
== ARG_PTR_TO_MAP_KEY
||
770 arg_type
== ARG_PTR_TO_MAP_VALUE
) {
771 expected_type
= PTR_TO_STACK
;
772 } else if (arg_type
== ARG_CONST_STACK_SIZE
) {
773 expected_type
= CONST_IMM
;
774 } else if (arg_type
== ARG_CONST_MAP_PTR
) {
775 expected_type
= CONST_PTR_TO_MAP
;
777 verbose("unsupported arg_type %d\n", arg_type
);
781 if (reg
->type
!= expected_type
) {
782 verbose("R%d type=%s expected=%s\n", regno
,
783 reg_type_str
[reg
->type
], reg_type_str
[expected_type
]);
787 if (arg_type
== ARG_CONST_MAP_PTR
) {
788 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
789 *mapp
= reg
->map_ptr
;
791 } else if (arg_type
== ARG_PTR_TO_MAP_KEY
) {
792 /* bpf_map_xxx(..., map_ptr, ..., key) call:
793 * check that [key, key + map->key_size) are within
794 * stack limits and initialized
797 /* in function declaration map_ptr must come before
798 * map_key, so that it's verified and known before
799 * we have to check map_key here. Otherwise it means
800 * that kernel subsystem misconfigured verifier
802 verbose("invalid map_ptr to access map->key\n");
805 err
= check_stack_boundary(env
, regno
, (*mapp
)->key_size
);
807 } else if (arg_type
== ARG_PTR_TO_MAP_VALUE
) {
808 /* bpf_map_xxx(..., map_ptr, ..., value) call:
809 * check [value, value + map->value_size) validity
812 /* kernel subsystem misconfigured verifier */
813 verbose("invalid map_ptr to access map->value\n");
816 err
= check_stack_boundary(env
, regno
, (*mapp
)->value_size
);
818 } else if (arg_type
== ARG_CONST_STACK_SIZE
) {
819 /* bpf_xxx(..., buf, len) call will access 'len' bytes
820 * from stack pointer 'buf'. Check it
821 * note: regno == len, regno - 1 == buf
824 /* kernel subsystem misconfigured verifier */
825 verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
828 err
= check_stack_boundary(env
, regno
- 1, reg
->imm
);
834 static int check_call(struct verifier_env
*env
, int func_id
)
836 struct verifier_state
*state
= &env
->cur_state
;
837 const struct bpf_func_proto
*fn
= NULL
;
838 struct reg_state
*regs
= state
->regs
;
839 struct bpf_map
*map
= NULL
;
840 struct reg_state
*reg
;
843 /* find function prototype */
844 if (func_id
< 0 || func_id
>= __BPF_FUNC_MAX_ID
) {
845 verbose("invalid func %d\n", func_id
);
849 if (env
->prog
->aux
->ops
->get_func_proto
)
850 fn
= env
->prog
->aux
->ops
->get_func_proto(func_id
);
853 verbose("unknown func %d\n", func_id
);
857 /* eBPF programs must be GPL compatible to use GPL-ed functions */
858 if (!env
->prog
->gpl_compatible
&& fn
->gpl_only
) {
859 verbose("cannot call GPL only function from proprietary program\n");
864 err
= check_func_arg(env
, BPF_REG_1
, fn
->arg1_type
, &map
);
867 err
= check_func_arg(env
, BPF_REG_2
, fn
->arg2_type
, &map
);
870 err
= check_func_arg(env
, BPF_REG_3
, fn
->arg3_type
, &map
);
873 err
= check_func_arg(env
, BPF_REG_4
, fn
->arg4_type
, &map
);
876 err
= check_func_arg(env
, BPF_REG_5
, fn
->arg5_type
, &map
);
880 /* reset caller saved regs */
881 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
882 reg
= regs
+ caller_saved
[i
];
883 reg
->type
= NOT_INIT
;
887 /* update return register */
888 if (fn
->ret_type
== RET_INTEGER
) {
889 regs
[BPF_REG_0
].type
= UNKNOWN_VALUE
;
890 } else if (fn
->ret_type
== RET_VOID
) {
891 regs
[BPF_REG_0
].type
= NOT_INIT
;
892 } else if (fn
->ret_type
== RET_PTR_TO_MAP_VALUE_OR_NULL
) {
893 regs
[BPF_REG_0
].type
= PTR_TO_MAP_VALUE_OR_NULL
;
894 /* remember map_ptr, so that check_map_access()
895 * can check 'value_size' boundary of memory access
896 * to map element returned from bpf_map_lookup_elem()
899 verbose("kernel subsystem misconfigured verifier\n");
902 regs
[BPF_REG_0
].map_ptr
= map
;
904 verbose("unknown return type %d of func %d\n",
905 fn
->ret_type
, func_id
);
911 /* check validity of 32-bit and 64-bit arithmetic operations */
912 static int check_alu_op(struct reg_state
*regs
, struct bpf_insn
*insn
)
914 u8 opcode
= BPF_OP(insn
->code
);
917 if (opcode
== BPF_END
|| opcode
== BPF_NEG
) {
918 if (opcode
== BPF_NEG
) {
919 if (BPF_SRC(insn
->code
) != 0 ||
920 insn
->src_reg
!= BPF_REG_0
||
921 insn
->off
!= 0 || insn
->imm
!= 0) {
922 verbose("BPF_NEG uses reserved fields\n");
926 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
927 (insn
->imm
!= 16 && insn
->imm
!= 32 && insn
->imm
!= 64)) {
928 verbose("BPF_END uses reserved fields\n");
933 /* check src operand */
934 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
938 /* check dest operand */
939 err
= check_reg_arg(regs
, insn
->dst_reg
, DST_OP
);
943 } else if (opcode
== BPF_MOV
) {
945 if (BPF_SRC(insn
->code
) == BPF_X
) {
946 if (insn
->imm
!= 0 || insn
->off
!= 0) {
947 verbose("BPF_MOV uses reserved fields\n");
951 /* check src operand */
952 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
956 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
957 verbose("BPF_MOV uses reserved fields\n");
962 /* check dest operand */
963 err
= check_reg_arg(regs
, insn
->dst_reg
, DST_OP
);
967 if (BPF_SRC(insn
->code
) == BPF_X
) {
968 if (BPF_CLASS(insn
->code
) == BPF_ALU64
) {
970 * copy register state to dest reg
972 regs
[insn
->dst_reg
] = regs
[insn
->src_reg
];
974 regs
[insn
->dst_reg
].type
= UNKNOWN_VALUE
;
975 regs
[insn
->dst_reg
].map_ptr
= NULL
;
979 * remember the value we stored into this reg
981 regs
[insn
->dst_reg
].type
= CONST_IMM
;
982 regs
[insn
->dst_reg
].imm
= insn
->imm
;
985 } else if (opcode
> BPF_END
) {
986 verbose("invalid BPF_ALU opcode %x\n", opcode
);
989 } else { /* all other ALU ops: and, sub, xor, add, ... */
991 bool stack_relative
= false;
993 if (BPF_SRC(insn
->code
) == BPF_X
) {
994 if (insn
->imm
!= 0 || insn
->off
!= 0) {
995 verbose("BPF_ALU uses reserved fields\n");
998 /* check src1 operand */
999 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
1003 if (insn
->src_reg
!= BPF_REG_0
|| insn
->off
!= 0) {
1004 verbose("BPF_ALU uses reserved fields\n");
1009 /* check src2 operand */
1010 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
1014 if ((opcode
== BPF_MOD
|| opcode
== BPF_DIV
) &&
1015 BPF_SRC(insn
->code
) == BPF_K
&& insn
->imm
== 0) {
1016 verbose("div by zero\n");
1020 /* pattern match 'bpf_add Rx, imm' instruction */
1021 if (opcode
== BPF_ADD
&& BPF_CLASS(insn
->code
) == BPF_ALU64
&&
1022 regs
[insn
->dst_reg
].type
== FRAME_PTR
&&
1023 BPF_SRC(insn
->code
) == BPF_K
)
1024 stack_relative
= true;
1026 /* check dest operand */
1027 err
= check_reg_arg(regs
, insn
->dst_reg
, DST_OP
);
1031 if (stack_relative
) {
1032 regs
[insn
->dst_reg
].type
= PTR_TO_STACK
;
1033 regs
[insn
->dst_reg
].imm
= insn
->imm
;
1040 static int check_cond_jmp_op(struct verifier_env
*env
,
1041 struct bpf_insn
*insn
, int *insn_idx
)
1043 struct reg_state
*regs
= env
->cur_state
.regs
;
1044 struct verifier_state
*other_branch
;
1045 u8 opcode
= BPF_OP(insn
->code
);
1048 if (opcode
> BPF_EXIT
) {
1049 verbose("invalid BPF_JMP opcode %x\n", opcode
);
1053 if (BPF_SRC(insn
->code
) == BPF_X
) {
1054 if (insn
->imm
!= 0) {
1055 verbose("BPF_JMP uses reserved fields\n");
1059 /* check src1 operand */
1060 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
1064 if (insn
->src_reg
!= BPF_REG_0
) {
1065 verbose("BPF_JMP uses reserved fields\n");
1070 /* check src2 operand */
1071 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
1075 /* detect if R == 0 where R was initialized to zero earlier */
1076 if (BPF_SRC(insn
->code
) == BPF_K
&&
1077 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
) &&
1078 regs
[insn
->dst_reg
].type
== CONST_IMM
&&
1079 regs
[insn
->dst_reg
].imm
== insn
->imm
) {
1080 if (opcode
== BPF_JEQ
) {
1081 /* if (imm == imm) goto pc+off;
1082 * only follow the goto, ignore fall-through
1084 *insn_idx
+= insn
->off
;
1087 /* if (imm != imm) goto pc+off;
1088 * only follow fall-through branch, since
1089 * that's where the program will go
1095 other_branch
= push_stack(env
, *insn_idx
+ insn
->off
+ 1, *insn_idx
);
1099 /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
1100 if (BPF_SRC(insn
->code
) == BPF_K
&&
1101 insn
->imm
== 0 && (opcode
== BPF_JEQ
||
1102 opcode
== BPF_JNE
) &&
1103 regs
[insn
->dst_reg
].type
== PTR_TO_MAP_VALUE_OR_NULL
) {
1104 if (opcode
== BPF_JEQ
) {
1105 /* next fallthrough insn can access memory via
1108 regs
[insn
->dst_reg
].type
= PTR_TO_MAP_VALUE
;
1109 /* branch targer cannot access it, since reg == 0 */
1110 other_branch
->regs
[insn
->dst_reg
].type
= CONST_IMM
;
1111 other_branch
->regs
[insn
->dst_reg
].imm
= 0;
1113 other_branch
->regs
[insn
->dst_reg
].type
= PTR_TO_MAP_VALUE
;
1114 regs
[insn
->dst_reg
].type
= CONST_IMM
;
1115 regs
[insn
->dst_reg
].imm
= 0;
1117 } else if (BPF_SRC(insn
->code
) == BPF_K
&&
1118 (opcode
== BPF_JEQ
|| opcode
== BPF_JNE
)) {
1120 if (opcode
== BPF_JEQ
) {
1121 /* detect if (R == imm) goto
1122 * and in the target state recognize that R = imm
1124 other_branch
->regs
[insn
->dst_reg
].type
= CONST_IMM
;
1125 other_branch
->regs
[insn
->dst_reg
].imm
= insn
->imm
;
1127 /* detect if (R != imm) goto
1128 * and in the fall-through state recognize that R = imm
1130 regs
[insn
->dst_reg
].type
= CONST_IMM
;
1131 regs
[insn
->dst_reg
].imm
= insn
->imm
;
1135 print_verifier_state(env
);
1139 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
1140 static struct bpf_map
*ld_imm64_to_map_ptr(struct bpf_insn
*insn
)
1142 u64 imm64
= ((u64
) (u32
) insn
[0].imm
) | ((u64
) (u32
) insn
[1].imm
) << 32;
1144 return (struct bpf_map
*) (unsigned long) imm64
;
1147 /* verify BPF_LD_IMM64 instruction */
1148 static int check_ld_imm(struct verifier_env
*env
, struct bpf_insn
*insn
)
1150 struct reg_state
*regs
= env
->cur_state
.regs
;
1153 if (BPF_SIZE(insn
->code
) != BPF_DW
) {
1154 verbose("invalid BPF_LD_IMM insn\n");
1157 if (insn
->off
!= 0) {
1158 verbose("BPF_LD_IMM64 uses reserved fields\n");
1162 err
= check_reg_arg(regs
, insn
->dst_reg
, DST_OP
);
1166 if (insn
->src_reg
== 0)
1167 /* generic move 64-bit immediate into a register */
1170 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1171 BUG_ON(insn
->src_reg
!= BPF_PSEUDO_MAP_FD
);
1173 regs
[insn
->dst_reg
].type
= CONST_PTR_TO_MAP
;
1174 regs
[insn
->dst_reg
].map_ptr
= ld_imm64_to_map_ptr(insn
);
1178 static bool may_access_skb(enum bpf_prog_type type
)
1181 case BPF_PROG_TYPE_SOCKET_FILTER
:
1182 case BPF_PROG_TYPE_SCHED_CLS
:
1189 /* verify safety of LD_ABS|LD_IND instructions:
1190 * - they can only appear in the programs where ctx == skb
1191 * - since they are wrappers of function calls, they scratch R1-R5 registers,
1192 * preserve R6-R9, and store return value into R0
1195 * ctx == skb == R6 == CTX
1198 * SRC == any register
1199 * IMM == 32-bit immediate
1202 * R0 - 8/16/32-bit skb data converted to cpu endianness
1204 static int check_ld_abs(struct verifier_env
*env
, struct bpf_insn
*insn
)
1206 struct reg_state
*regs
= env
->cur_state
.regs
;
1207 u8 mode
= BPF_MODE(insn
->code
);
1208 struct reg_state
*reg
;
1211 if (!may_access_skb(env
->prog
->type
)) {
1212 verbose("BPF_LD_ABS|IND instructions not allowed for this program type\n");
1216 if (insn
->dst_reg
!= BPF_REG_0
|| insn
->off
!= 0 ||
1217 (mode
== BPF_ABS
&& insn
->src_reg
!= BPF_REG_0
)) {
1218 verbose("BPF_LD_ABS uses reserved fields\n");
1222 /* check whether implicit source operand (register R6) is readable */
1223 err
= check_reg_arg(regs
, BPF_REG_6
, SRC_OP
);
1227 if (regs
[BPF_REG_6
].type
!= PTR_TO_CTX
) {
1228 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1232 if (mode
== BPF_IND
) {
1233 /* check explicit source operand */
1234 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
1239 /* reset caller saved regs to unreadable */
1240 for (i
= 0; i
< CALLER_SAVED_REGS
; i
++) {
1241 reg
= regs
+ caller_saved
[i
];
1242 reg
->type
= NOT_INIT
;
1246 /* mark destination R0 register as readable, since it contains
1247 * the value fetched from the packet
1249 regs
[BPF_REG_0
].type
= UNKNOWN_VALUE
;
1253 /* non-recursive DFS pseudo code
1254 * 1 procedure DFS-iterative(G,v):
1255 * 2 label v as discovered
1256 * 3 let S be a stack
1258 * 5 while S is not empty
1260 * 7 if t is what we're looking for:
1262 * 9 for all edges e in G.adjacentEdges(t) do
1263 * 10 if edge e is already labelled
1264 * 11 continue with the next edge
1265 * 12 w <- G.adjacentVertex(t,e)
1266 * 13 if vertex w is not discovered and not explored
1267 * 14 label e as tree-edge
1268 * 15 label w as discovered
1271 * 18 else if vertex w is discovered
1272 * 19 label e as back-edge
1274 * 21 // vertex w is explored
1275 * 22 label e as forward- or cross-edge
1276 * 23 label t as explored
1281 * 0x11 - discovered and fall-through edge labelled
1282 * 0x12 - discovered and fall-through and branch edges labelled
1293 #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
1295 static int *insn_stack
; /* stack of insns to process */
1296 static int cur_stack
; /* current stack index */
1297 static int *insn_state
;
1299 /* t, w, e - match pseudo-code above:
1300 * t - index of current instruction
1301 * w - next instruction
1304 static int push_insn(int t
, int w
, int e
, struct verifier_env
*env
)
1306 if (e
== FALLTHROUGH
&& insn_state
[t
] >= (DISCOVERED
| FALLTHROUGH
))
1309 if (e
== BRANCH
&& insn_state
[t
] >= (DISCOVERED
| BRANCH
))
1312 if (w
< 0 || w
>= env
->prog
->len
) {
1313 verbose("jump out of range from insn %d to %d\n", t
, w
);
1318 /* mark branch target for state pruning */
1319 env
->explored_states
[w
] = STATE_LIST_MARK
;
1321 if (insn_state
[w
] == 0) {
1323 insn_state
[t
] = DISCOVERED
| e
;
1324 insn_state
[w
] = DISCOVERED
;
1325 if (cur_stack
>= env
->prog
->len
)
1327 insn_stack
[cur_stack
++] = w
;
1329 } else if ((insn_state
[w
] & 0xF0) == DISCOVERED
) {
1330 verbose("back-edge from insn %d to %d\n", t
, w
);
1332 } else if (insn_state
[w
] == EXPLORED
) {
1333 /* forward- or cross-edge */
1334 insn_state
[t
] = DISCOVERED
| e
;
1336 verbose("insn state internal bug\n");
1342 /* non-recursive depth-first-search to detect loops in BPF program
1343 * loop == back-edge in directed graph
1345 static int check_cfg(struct verifier_env
*env
)
1347 struct bpf_insn
*insns
= env
->prog
->insnsi
;
1348 int insn_cnt
= env
->prog
->len
;
1352 insn_state
= kcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
1356 insn_stack
= kcalloc(insn_cnt
, sizeof(int), GFP_KERNEL
);
1362 insn_state
[0] = DISCOVERED
; /* mark 1st insn as discovered */
1363 insn_stack
[0] = 0; /* 0 is the first instruction */
1369 t
= insn_stack
[cur_stack
- 1];
1371 if (BPF_CLASS(insns
[t
].code
) == BPF_JMP
) {
1372 u8 opcode
= BPF_OP(insns
[t
].code
);
1374 if (opcode
== BPF_EXIT
) {
1376 } else if (opcode
== BPF_CALL
) {
1377 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
1382 } else if (opcode
== BPF_JA
) {
1383 if (BPF_SRC(insns
[t
].code
) != BPF_K
) {
1387 /* unconditional jump with single edge */
1388 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1,
1394 /* tell verifier to check for equivalent states
1395 * after every call and jump
1397 env
->explored_states
[t
+ 1] = STATE_LIST_MARK
;
1399 /* conditional jump with two edges */
1400 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
1406 ret
= push_insn(t
, t
+ insns
[t
].off
+ 1, BRANCH
, env
);
1413 /* all other non-branch instructions with single
1416 ret
= push_insn(t
, t
+ 1, FALLTHROUGH
, env
);
1424 insn_state
[t
] = EXPLORED
;
1425 if (cur_stack
-- <= 0) {
1426 verbose("pop stack internal bug\n");
1433 for (i
= 0; i
< insn_cnt
; i
++) {
1434 if (insn_state
[i
] != EXPLORED
) {
1435 verbose("unreachable insn %d\n", i
);
1440 ret
= 0; /* cfg looks good */
1448 /* compare two verifier states
1450 * all states stored in state_list are known to be valid, since
1451 * verifier reached 'bpf_exit' instruction through them
1453 * this function is called when verifier exploring different branches of
1454 * execution popped from the state stack. If it sees an old state that has
1455 * more strict register state and more strict stack state then this execution
1456 * branch doesn't need to be explored further, since verifier already
1457 * concluded that more strict state leads to valid finish.
1459 * Therefore two states are equivalent if register state is more conservative
1460 * and explored stack state is more conservative than the current one.
1463 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
1464 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
1466 * In other words if current stack state (one being explored) has more
1467 * valid slots than old one that already passed validation, it means
1468 * the verifier can stop exploring and conclude that current state is valid too
1470 * Similarly with registers. If explored state has register type as invalid
1471 * whereas register type in current state is meaningful, it means that
1472 * the current state will reach 'bpf_exit' instruction safely
1474 static bool states_equal(struct verifier_state
*old
, struct verifier_state
*cur
)
1478 for (i
= 0; i
< MAX_BPF_REG
; i
++) {
1479 if (memcmp(&old
->regs
[i
], &cur
->regs
[i
],
1480 sizeof(old
->regs
[0])) != 0) {
1481 if (old
->regs
[i
].type
== NOT_INIT
||
1482 (old
->regs
[i
].type
== UNKNOWN_VALUE
&&
1483 cur
->regs
[i
].type
!= NOT_INIT
))
1489 for (i
= 0; i
< MAX_BPF_STACK
; i
++) {
1490 if (old
->stack_slot_type
[i
] == STACK_INVALID
)
1492 if (old
->stack_slot_type
[i
] != cur
->stack_slot_type
[i
])
1493 /* Ex: old explored (safe) state has STACK_SPILL in
1494 * this stack slot, but current has has STACK_MISC ->
1495 * this verifier states are not equivalent,
1496 * return false to continue verification of this path
1499 if (i
% BPF_REG_SIZE
)
1501 if (memcmp(&old
->spilled_regs
[i
/ BPF_REG_SIZE
],
1502 &cur
->spilled_regs
[i
/ BPF_REG_SIZE
],
1503 sizeof(old
->spilled_regs
[0])))
1504 /* when explored and current stack slot types are
1505 * the same, check that stored pointers types
1506 * are the same as well.
1507 * Ex: explored safe path could have stored
1508 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
1509 * but current path has stored:
1510 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
1511 * such verifier states are not equivalent.
1512 * return false to continue verification of this path
1521 static int is_state_visited(struct verifier_env
*env
, int insn_idx
)
1523 struct verifier_state_list
*new_sl
;
1524 struct verifier_state_list
*sl
;
1526 sl
= env
->explored_states
[insn_idx
];
1528 /* this 'insn_idx' instruction wasn't marked, so we will not
1529 * be doing state search here
1533 while (sl
!= STATE_LIST_MARK
) {
1534 if (states_equal(&sl
->state
, &env
->cur_state
))
1535 /* reached equivalent register/stack state,
1542 /* there were no equivalent states, remember current one.
1543 * technically the current state is not proven to be safe yet,
1544 * but it will either reach bpf_exit (which means it's safe) or
1545 * it will be rejected. Since there are no loops, we won't be
1546 * seeing this 'insn_idx' instruction again on the way to bpf_exit
1548 new_sl
= kmalloc(sizeof(struct verifier_state_list
), GFP_USER
);
1552 /* add new state to the head of linked list */
1553 memcpy(&new_sl
->state
, &env
->cur_state
, sizeof(env
->cur_state
));
1554 new_sl
->next
= env
->explored_states
[insn_idx
];
1555 env
->explored_states
[insn_idx
] = new_sl
;
1559 static int do_check(struct verifier_env
*env
)
1561 struct verifier_state
*state
= &env
->cur_state
;
1562 struct bpf_insn
*insns
= env
->prog
->insnsi
;
1563 struct reg_state
*regs
= state
->regs
;
1564 int insn_cnt
= env
->prog
->len
;
1565 int insn_idx
, prev_insn_idx
= 0;
1566 int insn_processed
= 0;
1567 bool do_print_state
= false;
1569 init_reg_state(regs
);
1572 struct bpf_insn
*insn
;
1576 if (insn_idx
>= insn_cnt
) {
1577 verbose("invalid insn idx %d insn_cnt %d\n",
1578 insn_idx
, insn_cnt
);
1582 insn
= &insns
[insn_idx
];
1583 class = BPF_CLASS(insn
->code
);
1585 if (++insn_processed
> 32768) {
1586 verbose("BPF program is too large. Proccessed %d insn\n",
1591 err
= is_state_visited(env
, insn_idx
);
1595 /* found equivalent state, can prune the search */
1598 verbose("\nfrom %d to %d: safe\n",
1599 prev_insn_idx
, insn_idx
);
1601 verbose("%d: safe\n", insn_idx
);
1603 goto process_bpf_exit
;
1606 if (log_level
&& do_print_state
) {
1607 verbose("\nfrom %d to %d:", prev_insn_idx
, insn_idx
);
1608 print_verifier_state(env
);
1609 do_print_state
= false;
1613 verbose("%d: ", insn_idx
);
1614 print_bpf_insn(insn
);
1617 if (class == BPF_ALU
|| class == BPF_ALU64
) {
1618 err
= check_alu_op(regs
, insn
);
1622 } else if (class == BPF_LDX
) {
1623 enum bpf_reg_type src_reg_type
;
1625 /* check for reserved fields is already done */
1627 /* check src operand */
1628 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
1632 err
= check_reg_arg(regs
, insn
->dst_reg
, DST_OP_NO_MARK
);
1636 /* check that memory (src_reg + off) is readable,
1637 * the state of dst_reg will be updated by this func
1639 err
= check_mem_access(env
, insn
->src_reg
, insn
->off
,
1640 BPF_SIZE(insn
->code
), BPF_READ
,
1645 src_reg_type
= regs
[insn
->src_reg
].type
;
1647 if (insn
->imm
== 0 && BPF_SIZE(insn
->code
) == BPF_W
) {
1649 * dst_reg = *(u32 *)(src_reg + off)
1650 * use reserved 'imm' field to mark this insn
1652 insn
->imm
= src_reg_type
;
1654 } else if (src_reg_type
!= insn
->imm
&&
1655 (src_reg_type
== PTR_TO_CTX
||
1656 insn
->imm
== PTR_TO_CTX
)) {
1657 /* ABuser program is trying to use the same insn
1658 * dst_reg = *(u32*) (src_reg + off)
1659 * with different pointer types:
1660 * src_reg == ctx in one branch and
1661 * src_reg == stack|map in some other branch.
1664 verbose("same insn cannot be used with different pointers\n");
1668 } else if (class == BPF_STX
) {
1669 if (BPF_MODE(insn
->code
) == BPF_XADD
) {
1670 err
= check_xadd(env
, insn
);
1677 if (BPF_MODE(insn
->code
) != BPF_MEM
||
1679 verbose("BPF_STX uses reserved fields\n");
1682 /* check src1 operand */
1683 err
= check_reg_arg(regs
, insn
->src_reg
, SRC_OP
);
1686 /* check src2 operand */
1687 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
1691 /* check that memory (dst_reg + off) is writeable */
1692 err
= check_mem_access(env
, insn
->dst_reg
, insn
->off
,
1693 BPF_SIZE(insn
->code
), BPF_WRITE
,
1698 } else if (class == BPF_ST
) {
1699 if (BPF_MODE(insn
->code
) != BPF_MEM
||
1700 insn
->src_reg
!= BPF_REG_0
) {
1701 verbose("BPF_ST uses reserved fields\n");
1704 /* check src operand */
1705 err
= check_reg_arg(regs
, insn
->dst_reg
, SRC_OP
);
1709 /* check that memory (dst_reg + off) is writeable */
1710 err
= check_mem_access(env
, insn
->dst_reg
, insn
->off
,
1711 BPF_SIZE(insn
->code
), BPF_WRITE
,
1716 } else if (class == BPF_JMP
) {
1717 u8 opcode
= BPF_OP(insn
->code
);
1719 if (opcode
== BPF_CALL
) {
1720 if (BPF_SRC(insn
->code
) != BPF_K
||
1722 insn
->src_reg
!= BPF_REG_0
||
1723 insn
->dst_reg
!= BPF_REG_0
) {
1724 verbose("BPF_CALL uses reserved fields\n");
1728 err
= check_call(env
, insn
->imm
);
1732 } else if (opcode
== BPF_JA
) {
1733 if (BPF_SRC(insn
->code
) != BPF_K
||
1735 insn
->src_reg
!= BPF_REG_0
||
1736 insn
->dst_reg
!= BPF_REG_0
) {
1737 verbose("BPF_JA uses reserved fields\n");
1741 insn_idx
+= insn
->off
+ 1;
1744 } else if (opcode
== BPF_EXIT
) {
1745 if (BPF_SRC(insn
->code
) != BPF_K
||
1747 insn
->src_reg
!= BPF_REG_0
||
1748 insn
->dst_reg
!= BPF_REG_0
) {
1749 verbose("BPF_EXIT uses reserved fields\n");
1753 /* eBPF calling convetion is such that R0 is used
1754 * to return the value from eBPF program.
1755 * Make sure that it's readable at this time
1756 * of bpf_exit, which means that program wrote
1757 * something into it earlier
1759 err
= check_reg_arg(regs
, BPF_REG_0
, SRC_OP
);
1764 insn_idx
= pop_stack(env
, &prev_insn_idx
);
1768 do_print_state
= true;
1772 err
= check_cond_jmp_op(env
, insn
, &insn_idx
);
1776 } else if (class == BPF_LD
) {
1777 u8 mode
= BPF_MODE(insn
->code
);
1779 if (mode
== BPF_ABS
|| mode
== BPF_IND
) {
1780 err
= check_ld_abs(env
, insn
);
1784 } else if (mode
== BPF_IMM
) {
1785 err
= check_ld_imm(env
, insn
);
1791 verbose("invalid BPF_LD mode\n");
1795 verbose("unknown insn class %d\n", class);
1805 /* look for pseudo eBPF instructions that access map FDs and
1806 * replace them with actual map pointers
1808 static int replace_map_fd_with_map_ptr(struct verifier_env
*env
)
1810 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1811 int insn_cnt
= env
->prog
->len
;
1814 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
1815 if (BPF_CLASS(insn
->code
) == BPF_LDX
&&
1816 (BPF_MODE(insn
->code
) != BPF_MEM
||
1818 verbose("BPF_LDX uses reserved fields\n");
1822 if (insn
[0].code
== (BPF_LD
| BPF_IMM
| BPF_DW
)) {
1823 struct bpf_map
*map
;
1826 if (i
== insn_cnt
- 1 || insn
[1].code
!= 0 ||
1827 insn
[1].dst_reg
!= 0 || insn
[1].src_reg
!= 0 ||
1829 verbose("invalid bpf_ld_imm64 insn\n");
1833 if (insn
->src_reg
== 0)
1834 /* valid generic load 64-bit imm */
1837 if (insn
->src_reg
!= BPF_PSEUDO_MAP_FD
) {
1838 verbose("unrecognized bpf_ld_imm64 insn\n");
1842 f
= fdget(insn
->imm
);
1844 map
= bpf_map_get(f
);
1846 verbose("fd %d is not pointing to valid bpf_map\n",
1849 return PTR_ERR(map
);
1852 /* store map pointer inside BPF_LD_IMM64 instruction */
1853 insn
[0].imm
= (u32
) (unsigned long) map
;
1854 insn
[1].imm
= ((u64
) (unsigned long) map
) >> 32;
1856 /* check whether we recorded this map already */
1857 for (j
= 0; j
< env
->used_map_cnt
; j
++)
1858 if (env
->used_maps
[j
] == map
) {
1863 if (env
->used_map_cnt
>= MAX_USED_MAPS
) {
1868 /* remember this map */
1869 env
->used_maps
[env
->used_map_cnt
++] = map
;
1871 /* hold the map. If the program is rejected by verifier,
1872 * the map will be released by release_maps() or it
1873 * will be used by the valid program until it's unloaded
1874 * and all maps are released in free_bpf_prog_info()
1876 atomic_inc(&map
->refcnt
);
1885 /* now all pseudo BPF_LD_IMM64 instructions load valid
1886 * 'struct bpf_map *' into a register instead of user map_fd.
1887 * These pointers will be used later by verifier to validate map access.
1892 /* drop refcnt of maps used by the rejected program */
1893 static void release_maps(struct verifier_env
*env
)
1897 for (i
= 0; i
< env
->used_map_cnt
; i
++)
1898 bpf_map_put(env
->used_maps
[i
]);
1901 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
1902 static void convert_pseudo_ld_imm64(struct verifier_env
*env
)
1904 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1905 int insn_cnt
= env
->prog
->len
;
1908 for (i
= 0; i
< insn_cnt
; i
++, insn
++)
1909 if (insn
->code
== (BPF_LD
| BPF_IMM
| BPF_DW
))
1913 static void adjust_branches(struct bpf_prog
*prog
, int pos
, int delta
)
1915 struct bpf_insn
*insn
= prog
->insnsi
;
1916 int insn_cnt
= prog
->len
;
1919 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
1920 if (BPF_CLASS(insn
->code
) != BPF_JMP
||
1921 BPF_OP(insn
->code
) == BPF_CALL
||
1922 BPF_OP(insn
->code
) == BPF_EXIT
)
1925 /* adjust offset of jmps if necessary */
1926 if (i
< pos
&& i
+ insn
->off
+ 1 > pos
)
1928 else if (i
> pos
&& i
+ insn
->off
+ 1 < pos
)
1933 /* convert load instructions that access fields of 'struct __sk_buff'
1934 * into sequence of instructions that access fields of 'struct sk_buff'
1936 static int convert_ctx_accesses(struct verifier_env
*env
)
1938 struct bpf_insn
*insn
= env
->prog
->insnsi
;
1939 int insn_cnt
= env
->prog
->len
;
1940 struct bpf_insn insn_buf
[16];
1941 struct bpf_prog
*new_prog
;
1945 if (!env
->prog
->aux
->ops
->convert_ctx_access
)
1948 for (i
= 0; i
< insn_cnt
; i
++, insn
++) {
1949 if (insn
->code
!= (BPF_LDX
| BPF_MEM
| BPF_W
))
1952 if (insn
->imm
!= PTR_TO_CTX
) {
1953 /* clear internal mark */
1958 cnt
= env
->prog
->aux
->ops
->
1959 convert_ctx_access(insn
->dst_reg
, insn
->src_reg
,
1960 insn
->off
, insn_buf
);
1961 if (cnt
== 0 || cnt
>= ARRAY_SIZE(insn_buf
)) {
1962 verbose("bpf verifier is misconfigured\n");
1967 memcpy(insn
, insn_buf
, sizeof(*insn
));
1971 /* several new insns need to be inserted. Make room for them */
1972 insn_cnt
+= cnt
- 1;
1973 new_prog
= bpf_prog_realloc(env
->prog
,
1974 bpf_prog_size(insn_cnt
),
1979 new_prog
->len
= insn_cnt
;
1981 memmove(new_prog
->insnsi
+ i
+ cnt
, new_prog
->insns
+ i
+ 1,
1982 sizeof(*insn
) * (insn_cnt
- i
- cnt
));
1984 /* copy substitute insns in place of load instruction */
1985 memcpy(new_prog
->insnsi
+ i
, insn_buf
, sizeof(*insn
) * cnt
);
1987 /* adjust branches in the whole program */
1988 adjust_branches(new_prog
, i
, cnt
- 1);
1990 /* keep walking new program and skip insns we just inserted */
1991 env
->prog
= new_prog
;
1992 insn
= new_prog
->insnsi
+ i
+ cnt
- 1;
1999 static void free_states(struct verifier_env
*env
)
2001 struct verifier_state_list
*sl
, *sln
;
2004 if (!env
->explored_states
)
2007 for (i
= 0; i
< env
->prog
->len
; i
++) {
2008 sl
= env
->explored_states
[i
];
2011 while (sl
!= STATE_LIST_MARK
) {
2018 kfree(env
->explored_states
);
2021 int bpf_check(struct bpf_prog
**prog
, union bpf_attr
*attr
)
2023 char __user
*log_ubuf
= NULL
;
2024 struct verifier_env
*env
;
2027 if ((*prog
)->len
<= 0 || (*prog
)->len
> BPF_MAXINSNS
)
2030 /* 'struct verifier_env' can be global, but since it's not small,
2031 * allocate/free it every time bpf_check() is called
2033 env
= kzalloc(sizeof(struct verifier_env
), GFP_KERNEL
);
2039 /* grab the mutex to protect few globals used by verifier */
2040 mutex_lock(&bpf_verifier_lock
);
2042 if (attr
->log_level
|| attr
->log_buf
|| attr
->log_size
) {
2043 /* user requested verbose verifier output
2044 * and supplied buffer to store the verification trace
2046 log_level
= attr
->log_level
;
2047 log_ubuf
= (char __user
*) (unsigned long) attr
->log_buf
;
2048 log_size
= attr
->log_size
;
2052 /* log_* values have to be sane */
2053 if (log_size
< 128 || log_size
> UINT_MAX
>> 8 ||
2054 log_level
== 0 || log_ubuf
== NULL
)
2058 log_buf
= vmalloc(log_size
);
2065 ret
= replace_map_fd_with_map_ptr(env
);
2067 goto skip_full_check
;
2069 env
->explored_states
= kcalloc(env
->prog
->len
,
2070 sizeof(struct verifier_state_list
*),
2073 if (!env
->explored_states
)
2074 goto skip_full_check
;
2076 ret
= check_cfg(env
);
2078 goto skip_full_check
;
2080 ret
= do_check(env
);
2083 while (pop_stack(env
, NULL
) >= 0);
2087 /* program is valid, convert *(u32*)(ctx + off) accesses */
2088 ret
= convert_ctx_accesses(env
);
2090 if (log_level
&& log_len
>= log_size
- 1) {
2091 BUG_ON(log_len
>= log_size
);
2092 /* verifier log exceeded user supplied buffer */
2094 /* fall through to return what was recorded */
2097 /* copy verifier log back to user space including trailing zero */
2098 if (log_level
&& copy_to_user(log_ubuf
, log_buf
, log_len
+ 1) != 0) {
2103 if (ret
== 0 && env
->used_map_cnt
) {
2104 /* if program passed verifier, update used_maps in bpf_prog_info */
2105 env
->prog
->aux
->used_maps
= kmalloc_array(env
->used_map_cnt
,
2106 sizeof(env
->used_maps
[0]),
2109 if (!env
->prog
->aux
->used_maps
) {
2114 memcpy(env
->prog
->aux
->used_maps
, env
->used_maps
,
2115 sizeof(env
->used_maps
[0]) * env
->used_map_cnt
);
2116 env
->prog
->aux
->used_map_cnt
= env
->used_map_cnt
;
2118 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
2119 * bpf_ld_imm64 instructions
2121 convert_pseudo_ld_imm64(env
);
2128 if (!env
->prog
->aux
->used_maps
)
2129 /* if we didn't copy map pointers into bpf_prog_info, release
2130 * them now. Otherwise free_bpf_prog_info() will release them.
2135 mutex_unlock(&bpf_verifier_lock
);