1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2 * Copyright (c) 2016 Facebook
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of version 2 of the GNU General Public
6 * License as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/filter.h>
18 #include <net/netlink.h>
19 #include <linux/file.h>
20 #include <linux/vmalloc.h>
22 /* bpf_check() is a static code analyzer that walks eBPF program
23 * instruction by instruction and updates register/stack state.
24 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
26 * The first pass is depth-first-search to check that the program is a DAG.
27 * It rejects the following programs:
28 * - larger than BPF_MAXINSNS insns
29 * - if loop is present (detected via back-edge)
30 * - unreachable insns exist (shouldn't be a forest. program = one function)
31 * - out of bounds or malformed jumps
32 * The second pass is all possible path descent from the 1st insn.
33 * Since it's analyzing all pathes through the program, the length of the
34 * analysis is limited to 32k insn, which may be hit even if total number of
35 * insn is less then 4K, but there are too many branches that change stack/regs.
36 * Number of 'branches to be analyzed' is limited to 1k
38 * On entry to each instruction, each register has a type, and the instruction
39 * changes the types of the registers depending on instruction semantics.
40 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
43 * All registers are 64-bit.
44 * R0 - return register
45 * R1-R5 argument passing registers
46 * R6-R9 callee saved registers
47 * R10 - frame pointer read-only
49 * At the start of BPF program the register R1 contains a pointer to bpf_context
50 * and has type PTR_TO_CTX.
52 * Verifier tracks arithmetic operations on pointers in case:
53 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
54 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
55 * 1st insn copies R10 (which has FRAME_PTR) type into R1
56 * and 2nd arithmetic instruction is pattern matched to recognize
57 * that it wants to construct a pointer to some element within stack.
58 * So after 2nd insn, the register R1 has type PTR_TO_STACK
59 * (and -20 constant is saved for further stack bounds checking).
60 * Meaning that this reg is a pointer to stack plus known immediate constant.
62 * Most of the time the registers have UNKNOWN_VALUE type, which
63 * means the register has some value, but it's not a valid pointer.
64 * (like pointer plus pointer becomes UNKNOWN_VALUE type)
66 * When verifier sees load or store instructions the type of base register
67 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
68 * types recognized by check_mem_access() function.
70 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
71 * and the range of [ptr, ptr + map's value_size) is accessible.
73 * registers used to pass values to function calls are checked against
74 * function argument constraints.
76 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
77 * It means that the register type passed to this function must be
78 * PTR_TO_STACK and it will be used inside the function as
79 * 'pointer to map element key'
81 * For example the argument constraints for bpf_map_lookup_elem():
82 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
83 * .arg1_type = ARG_CONST_MAP_PTR,
84 * .arg2_type = ARG_PTR_TO_MAP_KEY,
86 * ret_type says that this function returns 'pointer to map elem value or null'
87 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
88 * 2nd argument should be a pointer to stack, which will be used inside
89 * the helper function as a pointer to map element key.
91 * On the kernel side the helper function looks like:
92 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
94 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
95 * void *key = (void *) (unsigned long) r2;
98 * here kernel can access 'key' and 'map' pointers safely, knowing that
99 * [key, key + map->key_size) bytes are valid and were initialized on
100 * the stack of eBPF program.
103 * Corresponding eBPF program may look like:
104 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
105 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
106 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
107 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
108 * here verifier looks at prototype of map_lookup_elem() and sees:
109 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
110 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
112 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
113 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
114 * and were initialized prior to this call.
115 * If it's ok, then verifier allows this BPF_CALL insn and looks at
116 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
117 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
118 * returns ether pointer to map value or NULL.
120 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
121 * insn, the register holding that pointer in the true branch changes state to
122 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
123 * branch. See check_cond_jmp_op().
125 * After the call R0 is set to return type of the function and registers R1-R5
126 * are set to NOT_INIT to indicate that they are no longer readable.
129 /* types of values stored in eBPF registers */
131 NOT_INIT = 0, /* nothing was written into register */
132 UNKNOWN_VALUE, /* reg doesn't contain a valid pointer */
133 PTR_TO_CTX, /* reg points to bpf_context */
134 CONST_PTR_TO_MAP, /* reg points to struct bpf_map */
135 PTR_TO_MAP_VALUE, /* reg points to map element value */
136 PTR_TO_MAP_VALUE_OR_NULL,/* points to map elem value or NULL */
137 FRAME_PTR, /* reg == frame_pointer */
138 PTR_TO_STACK, /* reg == frame_pointer + imm */
139 CONST_IMM, /* constant integer value */
141 /* PTR_TO_PACKET represents:
144 * skb->data + (u16) var
145 * skb->data + (u16) var + imm
146 * if (range > 0) then [ptr, ptr + range - off) is safe to access
147 * if (id > 0) means that some 'var' was added
148 * if (off > 0) menas that 'imm' was added
151 PTR_TO_PACKET_END, /* skb->data + headlen */
155 enum bpf_reg_type type;
157 /* valid when type == CONST_IMM | PTR_TO_STACK | UNKNOWN_VALUE */
160 /* valid when type == PTR_TO_PACKET* */
167 /* valid when type == CONST_PTR_TO_MAP | PTR_TO_MAP_VALUE |
168 * PTR_TO_MAP_VALUE_OR_NULL
170 struct bpf_map *map_ptr;
174 enum bpf_stack_slot_type {
175 STACK_INVALID, /* nothing was stored in this stack slot */
176 STACK_SPILL, /* register spilled into stack */
177 STACK_MISC /* BPF program wrote some data into this slot */
180 #define BPF_REG_SIZE 8 /* size of eBPF register in bytes */
182 /* state of the program:
183 * type of all registers and stack info
185 struct verifier_state {
186 struct reg_state regs[MAX_BPF_REG];
187 u8 stack_slot_type[MAX_BPF_STACK];
188 struct reg_state spilled_regs[MAX_BPF_STACK / BPF_REG_SIZE];
191 /* linked list of verifier states used to prune search */
192 struct verifier_state_list {
193 struct verifier_state state;
194 struct verifier_state_list *next;
197 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
198 struct verifier_stack_elem {
199 /* verifer state is 'st'
200 * before processing instruction 'insn_idx'
201 * and after processing instruction 'prev_insn_idx'
203 struct verifier_state st;
206 struct verifier_stack_elem *next;
209 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
211 /* single container for all structs
212 * one verifier_env per bpf_check() call
214 struct verifier_env {
215 struct bpf_prog *prog; /* eBPF program being verified */
216 struct verifier_stack_elem *head; /* stack of verifier states to be processed */
217 int stack_size; /* number of states to be processed */
218 struct verifier_state cur_state; /* current verifier state */
219 struct verifier_state_list **explored_states; /* search pruning optimization */
220 struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
221 u32 used_map_cnt; /* number of used maps */
222 bool allow_ptr_leaks;
225 #define BPF_COMPLEXITY_LIMIT_INSNS 65536
226 #define BPF_COMPLEXITY_LIMIT_STACK 1024
228 struct bpf_call_arg_meta {
229 struct bpf_map *map_ptr;
235 /* verbose verifier prints what it's seeing
236 * bpf_check() is called under lock, so no race to access these global vars
238 static u32 log_level, log_size, log_len;
239 static char *log_buf;
241 static DEFINE_MUTEX(bpf_verifier_lock);
243 /* log_level controls verbosity level of eBPF verifier.
244 * verbose() is used to dump the verification trace to the log, so the user
245 * can figure out what's wrong with the program
247 static __printf(1, 2) void verbose(const char *fmt, ...)
251 if (log_level == 0 || log_len >= log_size - 1)
255 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
259 /* string representation of 'enum bpf_reg_type' */
260 static const char * const reg_type_str[] = {
262 [UNKNOWN_VALUE] = "inv",
263 [PTR_TO_CTX] = "ctx",
264 [CONST_PTR_TO_MAP] = "map_ptr",
265 [PTR_TO_MAP_VALUE] = "map_value",
266 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
268 [PTR_TO_STACK] = "fp",
270 [PTR_TO_PACKET] = "pkt",
271 [PTR_TO_PACKET_END] = "pkt_end",
274 static void print_verifier_state(struct verifier_state *state)
276 struct reg_state *reg;
280 for (i = 0; i < MAX_BPF_REG; i++) {
281 reg = &state->regs[i];
285 verbose(" R%d=%s", i, reg_type_str[t]);
286 if (t == CONST_IMM || t == PTR_TO_STACK)
287 verbose("%lld", reg->imm);
288 else if (t == PTR_TO_PACKET)
289 verbose("(id=%d,off=%d,r=%d)",
290 reg->id, reg->off, reg->range);
291 else if (t == UNKNOWN_VALUE && reg->imm)
292 verbose("%lld", reg->imm);
293 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
294 t == PTR_TO_MAP_VALUE_OR_NULL)
295 verbose("(ks=%d,vs=%d)",
296 reg->map_ptr->key_size,
297 reg->map_ptr->value_size);
299 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
300 if (state->stack_slot_type[i] == STACK_SPILL)
301 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
302 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
307 static const char *const bpf_class_string[] = {
315 [BPF_ALU64] = "alu64",
318 static const char *const bpf_alu_string[16] = {
319 [BPF_ADD >> 4] = "+=",
320 [BPF_SUB >> 4] = "-=",
321 [BPF_MUL >> 4] = "*=",
322 [BPF_DIV >> 4] = "/=",
323 [BPF_OR >> 4] = "|=",
324 [BPF_AND >> 4] = "&=",
325 [BPF_LSH >> 4] = "<<=",
326 [BPF_RSH >> 4] = ">>=",
327 [BPF_NEG >> 4] = "neg",
328 [BPF_MOD >> 4] = "%=",
329 [BPF_XOR >> 4] = "^=",
330 [BPF_MOV >> 4] = "=",
331 [BPF_ARSH >> 4] = "s>>=",
332 [BPF_END >> 4] = "endian",
335 static const char *const bpf_ldst_string[] = {
336 [BPF_W >> 3] = "u32",
337 [BPF_H >> 3] = "u16",
339 [BPF_DW >> 3] = "u64",
342 static const char *const bpf_jmp_string[16] = {
343 [BPF_JA >> 4] = "jmp",
344 [BPF_JEQ >> 4] = "==",
345 [BPF_JGT >> 4] = ">",
346 [BPF_JGE >> 4] = ">=",
347 [BPF_JSET >> 4] = "&",
348 [BPF_JNE >> 4] = "!=",
349 [BPF_JSGT >> 4] = "s>",
350 [BPF_JSGE >> 4] = "s>=",
351 [BPF_CALL >> 4] = "call",
352 [BPF_EXIT >> 4] = "exit",
355 static void print_bpf_insn(struct bpf_insn *insn)
357 u8 class = BPF_CLASS(insn->code);
359 if (class == BPF_ALU || class == BPF_ALU64) {
360 if (BPF_SRC(insn->code) == BPF_X)
361 verbose("(%02x) %sr%d %s %sr%d\n",
362 insn->code, class == BPF_ALU ? "(u32) " : "",
364 bpf_alu_string[BPF_OP(insn->code) >> 4],
365 class == BPF_ALU ? "(u32) " : "",
368 verbose("(%02x) %sr%d %s %s%d\n",
369 insn->code, class == BPF_ALU ? "(u32) " : "",
371 bpf_alu_string[BPF_OP(insn->code) >> 4],
372 class == BPF_ALU ? "(u32) " : "",
374 } else if (class == BPF_STX) {
375 if (BPF_MODE(insn->code) == BPF_MEM)
376 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
378 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
380 insn->off, insn->src_reg);
381 else if (BPF_MODE(insn->code) == BPF_XADD)
382 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
384 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
385 insn->dst_reg, insn->off,
388 verbose("BUG_%02x\n", insn->code);
389 } else if (class == BPF_ST) {
390 if (BPF_MODE(insn->code) != BPF_MEM) {
391 verbose("BUG_st_%02x\n", insn->code);
394 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
396 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
398 insn->off, insn->imm);
399 } else if (class == BPF_LDX) {
400 if (BPF_MODE(insn->code) != BPF_MEM) {
401 verbose("BUG_ldx_%02x\n", insn->code);
404 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
405 insn->code, insn->dst_reg,
406 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
407 insn->src_reg, insn->off);
408 } else if (class == BPF_LD) {
409 if (BPF_MODE(insn->code) == BPF_ABS) {
410 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
412 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
414 } else if (BPF_MODE(insn->code) == BPF_IND) {
415 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
417 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
418 insn->src_reg, insn->imm);
419 } else if (BPF_MODE(insn->code) == BPF_IMM) {
420 verbose("(%02x) r%d = 0x%x\n",
421 insn->code, insn->dst_reg, insn->imm);
423 verbose("BUG_ld_%02x\n", insn->code);
426 } else if (class == BPF_JMP) {
427 u8 opcode = BPF_OP(insn->code);
429 if (opcode == BPF_CALL) {
430 verbose("(%02x) call %d\n", insn->code, insn->imm);
431 } else if (insn->code == (BPF_JMP | BPF_JA)) {
432 verbose("(%02x) goto pc%+d\n",
433 insn->code, insn->off);
434 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
435 verbose("(%02x) exit\n", insn->code);
436 } else if (BPF_SRC(insn->code) == BPF_X) {
437 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
438 insn->code, insn->dst_reg,
439 bpf_jmp_string[BPF_OP(insn->code) >> 4],
440 insn->src_reg, insn->off);
442 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
443 insn->code, insn->dst_reg,
444 bpf_jmp_string[BPF_OP(insn->code) >> 4],
445 insn->imm, insn->off);
448 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
452 static int pop_stack(struct verifier_env *env, int *prev_insn_idx)
454 struct verifier_stack_elem *elem;
457 if (env->head == NULL)
460 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
461 insn_idx = env->head->insn_idx;
463 *prev_insn_idx = env->head->prev_insn_idx;
464 elem = env->head->next;
471 static struct verifier_state *push_stack(struct verifier_env *env, int insn_idx,
474 struct verifier_stack_elem *elem;
476 elem = kmalloc(sizeof(struct verifier_stack_elem), GFP_KERNEL);
480 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
481 elem->insn_idx = insn_idx;
482 elem->prev_insn_idx = prev_insn_idx;
483 elem->next = env->head;
486 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
487 verbose("BPF program is too complex\n");
492 /* pop all elements and return */
493 while (pop_stack(env, NULL) >= 0);
497 #define CALLER_SAVED_REGS 6
498 static const int caller_saved[CALLER_SAVED_REGS] = {
499 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
502 static void init_reg_state(struct reg_state *regs)
506 for (i = 0; i < MAX_BPF_REG; i++) {
507 regs[i].type = NOT_INIT;
512 regs[BPF_REG_FP].type = FRAME_PTR;
514 /* 1st arg to a function */
515 regs[BPF_REG_1].type = PTR_TO_CTX;
518 static void mark_reg_unknown_value(struct reg_state *regs, u32 regno)
520 BUG_ON(regno >= MAX_BPF_REG);
521 regs[regno].type = UNKNOWN_VALUE;
526 SRC_OP, /* register is used as source operand */
527 DST_OP, /* register is used as destination operand */
528 DST_OP_NO_MARK /* same as above, check only, don't mark */
531 static int check_reg_arg(struct reg_state *regs, u32 regno,
534 if (regno >= MAX_BPF_REG) {
535 verbose("R%d is invalid\n", regno);
540 /* check whether register used as source operand can be read */
541 if (regs[regno].type == NOT_INIT) {
542 verbose("R%d !read_ok\n", regno);
546 /* check whether register used as dest operand can be written to */
547 if (regno == BPF_REG_FP) {
548 verbose("frame pointer is read only\n");
552 mark_reg_unknown_value(regs, regno);
557 static int bpf_size_to_bytes(int bpf_size)
559 if (bpf_size == BPF_W)
561 else if (bpf_size == BPF_H)
563 else if (bpf_size == BPF_B)
565 else if (bpf_size == BPF_DW)
571 static bool is_spillable_regtype(enum bpf_reg_type type)
574 case PTR_TO_MAP_VALUE:
575 case PTR_TO_MAP_VALUE_OR_NULL:
579 case PTR_TO_PACKET_END:
581 case CONST_PTR_TO_MAP:
588 /* check_stack_read/write functions track spill/fill of registers,
589 * stack boundary and alignment are checked in check_mem_access()
591 static int check_stack_write(struct verifier_state *state, int off, int size,
595 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
596 * so it's aligned access and [off, off + size) are within stack limits
599 if (value_regno >= 0 &&
600 is_spillable_regtype(state->regs[value_regno].type)) {
602 /* register containing pointer is being spilled into stack */
603 if (size != BPF_REG_SIZE) {
604 verbose("invalid size of register spill\n");
608 /* save register state */
609 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
610 state->regs[value_regno];
612 for (i = 0; i < BPF_REG_SIZE; i++)
613 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
615 /* regular write of data into stack */
616 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
617 (struct reg_state) {};
619 for (i = 0; i < size; i++)
620 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
625 static int check_stack_read(struct verifier_state *state, int off, int size,
631 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
633 if (slot_type[0] == STACK_SPILL) {
634 if (size != BPF_REG_SIZE) {
635 verbose("invalid size of register spill\n");
638 for (i = 1; i < BPF_REG_SIZE; i++) {
639 if (slot_type[i] != STACK_SPILL) {
640 verbose("corrupted spill memory\n");
645 if (value_regno >= 0)
646 /* restore register state from stack */
647 state->regs[value_regno] =
648 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
651 for (i = 0; i < size; i++) {
652 if (slot_type[i] != STACK_MISC) {
653 verbose("invalid read from stack off %d+%d size %d\n",
658 if (value_regno >= 0)
659 /* have read misc data from the stack */
660 mark_reg_unknown_value(state->regs, value_regno);
665 /* check read/write into map element returned by bpf_map_lookup_elem() */
666 static int check_map_access(struct verifier_env *env, u32 regno, int off,
669 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
671 if (off < 0 || off + size > map->value_size) {
672 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
673 map->value_size, off, size);
679 #define MAX_PACKET_OFF 0xffff
681 static int check_packet_access(struct verifier_env *env, u32 regno, int off,
684 struct reg_state *regs = env->cur_state.regs;
685 struct reg_state *reg = ®s[regno];
686 int linear_size = (int) reg->range - (int) reg->off;
688 if (linear_size < 0 || linear_size >= MAX_PACKET_OFF) {
689 verbose("verifier bug\n");
692 if (off < 0 || off + size > linear_size) {
693 verbose("invalid access to packet, off=%d size=%d, allowed=%d\n",
694 off, size, linear_size);
700 /* check access to 'struct bpf_context' fields */
701 static int check_ctx_access(struct verifier_env *env, int off, int size,
702 enum bpf_access_type t)
704 if (env->prog->aux->ops->is_valid_access &&
705 env->prog->aux->ops->is_valid_access(off, size, t)) {
706 /* remember the offset of last byte accessed in ctx */
707 if (env->prog->aux->max_ctx_offset < off + size)
708 env->prog->aux->max_ctx_offset = off + size;
712 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
716 static bool is_pointer_value(struct verifier_env *env, int regno)
718 if (env->allow_ptr_leaks)
721 switch (env->cur_state.regs[regno].type) {
730 static int check_ptr_alignment(struct verifier_env *env, struct reg_state *reg,
733 if (reg->type != PTR_TO_PACKET) {
734 if (off % size != 0) {
735 verbose("misaligned access off %d size %d\n", off, size);
742 switch (env->prog->type) {
743 case BPF_PROG_TYPE_SCHED_CLS:
744 case BPF_PROG_TYPE_SCHED_ACT:
747 verbose("verifier is misconfigured\n");
751 if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
752 /* misaligned access to packet is ok on x86,arm,arm64 */
755 if (reg->id && size != 1) {
756 verbose("Unknown packet alignment. Only byte-sized access allowed\n");
760 /* skb->data is NET_IP_ALIGN-ed */
761 if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
762 verbose("misaligned packet access off %d+%d+%d size %d\n",
763 NET_IP_ALIGN, reg->off, off, size);
769 /* check whether memory at (regno + off) is accessible for t = (read | write)
770 * if t==write, value_regno is a register which value is stored into memory
771 * if t==read, value_regno is a register which will receive the value from memory
772 * if t==write && value_regno==-1, some unknown value is stored into memory
773 * if t==read && value_regno==-1, don't care what we read from memory
775 static int check_mem_access(struct verifier_env *env, u32 regno, int off,
776 int bpf_size, enum bpf_access_type t,
779 struct verifier_state *state = &env->cur_state;
780 struct reg_state *reg = &state->regs[regno];
783 if (reg->type == PTR_TO_STACK)
786 size = bpf_size_to_bytes(bpf_size);
790 err = check_ptr_alignment(env, reg, off, size);
794 if (reg->type == PTR_TO_MAP_VALUE) {
795 if (t == BPF_WRITE && value_regno >= 0 &&
796 is_pointer_value(env, value_regno)) {
797 verbose("R%d leaks addr into map\n", value_regno);
800 err = check_map_access(env, regno, off, size);
801 if (!err && t == BPF_READ && value_regno >= 0)
802 mark_reg_unknown_value(state->regs, value_regno);
804 } else if (reg->type == PTR_TO_CTX) {
805 if (t == BPF_WRITE && value_regno >= 0 &&
806 is_pointer_value(env, value_regno)) {
807 verbose("R%d leaks addr into ctx\n", value_regno);
810 err = check_ctx_access(env, off, size, t);
811 if (!err && t == BPF_READ && value_regno >= 0) {
812 mark_reg_unknown_value(state->regs, value_regno);
813 if (off == offsetof(struct __sk_buff, data) &&
814 env->allow_ptr_leaks)
815 /* note that reg.[id|off|range] == 0 */
816 state->regs[value_regno].type = PTR_TO_PACKET;
817 else if (off == offsetof(struct __sk_buff, data_end) &&
818 env->allow_ptr_leaks)
819 state->regs[value_regno].type = PTR_TO_PACKET_END;
822 } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
823 if (off >= 0 || off < -MAX_BPF_STACK) {
824 verbose("invalid stack off=%d size=%d\n", off, size);
827 if (t == BPF_WRITE) {
828 if (!env->allow_ptr_leaks &&
829 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
830 size != BPF_REG_SIZE) {
831 verbose("attempt to corrupt spilled pointer on stack\n");
834 err = check_stack_write(state, off, size, value_regno);
836 err = check_stack_read(state, off, size, value_regno);
838 } else if (state->regs[regno].type == PTR_TO_PACKET) {
839 if (t == BPF_WRITE) {
840 verbose("cannot write into packet\n");
843 err = check_packet_access(env, regno, off, size);
844 if (!err && t == BPF_READ && value_regno >= 0)
845 mark_reg_unknown_value(state->regs, value_regno);
847 verbose("R%d invalid mem access '%s'\n",
848 regno, reg_type_str[reg->type]);
852 if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
853 state->regs[value_regno].type == UNKNOWN_VALUE) {
854 /* 1 or 2 byte load zero-extends, determine the number of
855 * zero upper bits. Not doing it fo 4 byte load, since
856 * such values cannot be added to ptr_to_packet anyway.
858 state->regs[value_regno].imm = 64 - size * 8;
863 static int check_xadd(struct verifier_env *env, struct bpf_insn *insn)
865 struct reg_state *regs = env->cur_state.regs;
868 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
870 verbose("BPF_XADD uses reserved fields\n");
874 /* check src1 operand */
875 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
879 /* check src2 operand */
880 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
884 /* check whether atomic_add can read the memory */
885 err = check_mem_access(env, insn->dst_reg, insn->off,
886 BPF_SIZE(insn->code), BPF_READ, -1);
890 /* check whether atomic_add can write into the same memory */
891 return check_mem_access(env, insn->dst_reg, insn->off,
892 BPF_SIZE(insn->code), BPF_WRITE, -1);
895 /* when register 'regno' is passed into function that will read 'access_size'
896 * bytes from that pointer, make sure that it's within stack boundary
897 * and all elements of stack are initialized
899 static int check_stack_boundary(struct verifier_env *env, int regno,
900 int access_size, bool zero_size_allowed,
901 struct bpf_call_arg_meta *meta)
903 struct verifier_state *state = &env->cur_state;
904 struct reg_state *regs = state->regs;
907 if (regs[regno].type != PTR_TO_STACK) {
908 if (zero_size_allowed && access_size == 0 &&
909 regs[regno].type == CONST_IMM &&
910 regs[regno].imm == 0)
913 verbose("R%d type=%s expected=%s\n", regno,
914 reg_type_str[regs[regno].type],
915 reg_type_str[PTR_TO_STACK]);
919 off = regs[regno].imm;
920 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
922 verbose("invalid stack type R%d off=%d access_size=%d\n",
923 regno, off, access_size);
927 if (meta && meta->raw_mode) {
928 meta->access_size = access_size;
933 for (i = 0; i < access_size; i++) {
934 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
935 verbose("invalid indirect read from stack off %d+%d size %d\n",
936 off, i, access_size);
943 static int check_func_arg(struct verifier_env *env, u32 regno,
944 enum bpf_arg_type arg_type,
945 struct bpf_call_arg_meta *meta)
947 struct reg_state *reg = env->cur_state.regs + regno;
948 enum bpf_reg_type expected_type;
951 if (arg_type == ARG_DONTCARE)
954 if (reg->type == NOT_INIT) {
955 verbose("R%d !read_ok\n", regno);
959 if (arg_type == ARG_ANYTHING) {
960 if (is_pointer_value(env, regno)) {
961 verbose("R%d leaks addr into helper function\n", regno);
967 if (arg_type == ARG_PTR_TO_MAP_KEY ||
968 arg_type == ARG_PTR_TO_MAP_VALUE) {
969 expected_type = PTR_TO_STACK;
970 } else if (arg_type == ARG_CONST_STACK_SIZE ||
971 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
972 expected_type = CONST_IMM;
973 } else if (arg_type == ARG_CONST_MAP_PTR) {
974 expected_type = CONST_PTR_TO_MAP;
975 } else if (arg_type == ARG_PTR_TO_CTX) {
976 expected_type = PTR_TO_CTX;
977 } else if (arg_type == ARG_PTR_TO_STACK ||
978 arg_type == ARG_PTR_TO_RAW_STACK) {
979 expected_type = PTR_TO_STACK;
980 /* One exception here. In case function allows for NULL to be
981 * passed in as argument, it's a CONST_IMM type. Final test
982 * happens during stack boundary checking.
984 if (reg->type == CONST_IMM && reg->imm == 0)
985 expected_type = CONST_IMM;
986 meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
988 verbose("unsupported arg_type %d\n", arg_type);
992 if (reg->type != expected_type) {
993 verbose("R%d type=%s expected=%s\n", regno,
994 reg_type_str[reg->type], reg_type_str[expected_type]);
998 if (arg_type == ARG_CONST_MAP_PTR) {
999 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1000 meta->map_ptr = reg->map_ptr;
1001 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1002 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1003 * check that [key, key + map->key_size) are within
1004 * stack limits and initialized
1006 if (!meta->map_ptr) {
1007 /* in function declaration map_ptr must come before
1008 * map_key, so that it's verified and known before
1009 * we have to check map_key here. Otherwise it means
1010 * that kernel subsystem misconfigured verifier
1012 verbose("invalid map_ptr to access map->key\n");
1015 err = check_stack_boundary(env, regno, meta->map_ptr->key_size,
1017 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1018 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1019 * check [value, value + map->value_size) validity
1021 if (!meta->map_ptr) {
1022 /* kernel subsystem misconfigured verifier */
1023 verbose("invalid map_ptr to access map->value\n");
1026 err = check_stack_boundary(env, regno,
1027 meta->map_ptr->value_size,
1029 } else if (arg_type == ARG_CONST_STACK_SIZE ||
1030 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
1031 bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
1033 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1034 * from stack pointer 'buf'. Check it
1035 * note: regno == len, regno - 1 == buf
1038 /* kernel subsystem misconfigured verifier */
1039 verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1042 err = check_stack_boundary(env, regno - 1, reg->imm,
1043 zero_size_allowed, meta);
1049 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1054 /* We need a two way check, first is from map perspective ... */
1055 switch (map->map_type) {
1056 case BPF_MAP_TYPE_PROG_ARRAY:
1057 if (func_id != BPF_FUNC_tail_call)
1060 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1061 if (func_id != BPF_FUNC_perf_event_read &&
1062 func_id != BPF_FUNC_perf_event_output)
1065 case BPF_MAP_TYPE_STACK_TRACE:
1066 if (func_id != BPF_FUNC_get_stackid)
1073 /* ... and second from the function itself. */
1075 case BPF_FUNC_tail_call:
1076 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1079 case BPF_FUNC_perf_event_read:
1080 case BPF_FUNC_perf_event_output:
1081 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1084 case BPF_FUNC_get_stackid:
1085 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1094 verbose("cannot pass map_type %d into func %d\n",
1095 map->map_type, func_id);
1099 static int check_raw_mode(const struct bpf_func_proto *fn)
1103 if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1105 if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1107 if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1109 if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1111 if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1114 return count > 1 ? -EINVAL : 0;
1117 static void clear_all_pkt_pointers(struct verifier_env *env)
1119 struct verifier_state *state = &env->cur_state;
1120 struct reg_state *regs = state->regs, *reg;
1123 for (i = 0; i < MAX_BPF_REG; i++)
1124 if (regs[i].type == PTR_TO_PACKET ||
1125 regs[i].type == PTR_TO_PACKET_END)
1126 mark_reg_unknown_value(regs, i);
1128 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1129 if (state->stack_slot_type[i] != STACK_SPILL)
1131 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1132 if (reg->type != PTR_TO_PACKET &&
1133 reg->type != PTR_TO_PACKET_END)
1135 reg->type = UNKNOWN_VALUE;
1140 static int check_call(struct verifier_env *env, int func_id)
1142 struct verifier_state *state = &env->cur_state;
1143 const struct bpf_func_proto *fn = NULL;
1144 struct reg_state *regs = state->regs;
1145 struct reg_state *reg;
1146 struct bpf_call_arg_meta meta;
1150 /* find function prototype */
1151 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1152 verbose("invalid func %d\n", func_id);
1156 if (env->prog->aux->ops->get_func_proto)
1157 fn = env->prog->aux->ops->get_func_proto(func_id);
1160 verbose("unknown func %d\n", func_id);
1164 /* eBPF programs must be GPL compatible to use GPL-ed functions */
1165 if (!env->prog->gpl_compatible && fn->gpl_only) {
1166 verbose("cannot call GPL only function from proprietary program\n");
1170 changes_data = bpf_helper_changes_skb_data(fn->func);
1172 memset(&meta, 0, sizeof(meta));
1174 /* We only support one arg being in raw mode at the moment, which
1175 * is sufficient for the helper functions we have right now.
1177 err = check_raw_mode(fn);
1179 verbose("kernel subsystem misconfigured func %d\n", func_id);
1184 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1187 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1190 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1193 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1196 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1200 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1201 * is inferred from register state.
1203 for (i = 0; i < meta.access_size; i++) {
1204 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1209 /* reset caller saved regs */
1210 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1211 reg = regs + caller_saved[i];
1212 reg->type = NOT_INIT;
1216 /* update return register */
1217 if (fn->ret_type == RET_INTEGER) {
1218 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1219 } else if (fn->ret_type == RET_VOID) {
1220 regs[BPF_REG_0].type = NOT_INIT;
1221 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1222 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1223 /* remember map_ptr, so that check_map_access()
1224 * can check 'value_size' boundary of memory access
1225 * to map element returned from bpf_map_lookup_elem()
1227 if (meta.map_ptr == NULL) {
1228 verbose("kernel subsystem misconfigured verifier\n");
1231 regs[BPF_REG_0].map_ptr = meta.map_ptr;
1233 verbose("unknown return type %d of func %d\n",
1234 fn->ret_type, func_id);
1238 err = check_map_func_compatibility(meta.map_ptr, func_id);
1243 clear_all_pkt_pointers(env);
1247 static int check_packet_ptr_add(struct verifier_env *env, struct bpf_insn *insn)
1249 struct reg_state *regs = env->cur_state.regs;
1250 struct reg_state *dst_reg = ®s[insn->dst_reg];
1251 struct reg_state *src_reg = ®s[insn->src_reg];
1254 if (BPF_SRC(insn->code) == BPF_K) {
1255 /* pkt_ptr += imm */
1260 verbose("addition of negative constant to packet pointer is not allowed\n");
1263 if (imm >= MAX_PACKET_OFF ||
1264 imm + dst_reg->off >= MAX_PACKET_OFF) {
1265 verbose("constant %d is too large to add to packet pointer\n",
1269 /* a constant was added to pkt_ptr.
1270 * Remember it while keeping the same 'id'
1272 dst_reg->off += imm;
1274 if (src_reg->type == CONST_IMM) {
1275 /* pkt_ptr += reg where reg is known constant */
1279 /* disallow pkt_ptr += reg
1280 * if reg is not uknown_value with guaranteed zero upper bits
1281 * otherwise pkt_ptr may overflow and addition will become
1282 * subtraction which is not allowed
1284 if (src_reg->type != UNKNOWN_VALUE) {
1285 verbose("cannot add '%s' to ptr_to_packet\n",
1286 reg_type_str[src_reg->type]);
1289 if (src_reg->imm < 48) {
1290 verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1294 /* dst_reg stays as pkt_ptr type and since some positive
1295 * integer value was added to the pointer, increment its 'id'
1299 /* something was added to pkt_ptr, set range and off to zero */
1306 static int evaluate_reg_alu(struct verifier_env *env, struct bpf_insn *insn)
1308 struct reg_state *regs = env->cur_state.regs;
1309 struct reg_state *dst_reg = ®s[insn->dst_reg];
1310 u8 opcode = BPF_OP(insn->code);
1313 /* for type == UNKNOWN_VALUE:
1314 * imm > 0 -> number of zero upper bits
1315 * imm == 0 -> don't track which is the same as all bits can be non-zero
1318 if (BPF_SRC(insn->code) == BPF_X) {
1319 struct reg_state *src_reg = ®s[insn->src_reg];
1321 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1322 dst_reg->imm && opcode == BPF_ADD) {
1324 * where both have zero upper bits. Adding them
1325 * can only result making one more bit non-zero
1326 * in the larger value.
1327 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1328 * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1330 dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1334 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1335 dst_reg->imm && opcode == BPF_ADD) {
1337 * where dreg has zero upper bits and sreg is const.
1338 * Adding them can only result making one more bit
1339 * non-zero in the larger value.
1341 imm_log2 = __ilog2_u64((long long)src_reg->imm);
1342 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1346 /* all other cases non supported yet, just mark dst_reg */
1351 /* sign extend 32-bit imm into 64-bit to make sure that
1352 * negative values occupy bit 63. Note ilog2() would have
1353 * been incorrect, since sizeof(insn->imm) == 4
1355 imm_log2 = __ilog2_u64((long long)insn->imm);
1357 if (dst_reg->imm && opcode == BPF_LSH) {
1359 * if reg was a result of 2 byte load, then its imm == 48
1360 * which means that upper 48 bits are zero and shifting this reg
1361 * left by 4 would mean that upper 44 bits are still zero
1363 dst_reg->imm -= insn->imm;
1364 } else if (dst_reg->imm && opcode == BPF_MUL) {
1366 * if multiplying by 14 subtract 4
1367 * This is conservative calculation of upper zero bits.
1368 * It's not trying to special case insn->imm == 1 or 0 cases
1370 dst_reg->imm -= imm_log2 + 1;
1371 } else if (opcode == BPF_AND) {
1373 dst_reg->imm = 63 - imm_log2;
1374 } else if (dst_reg->imm && opcode == BPF_ADD) {
1376 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1378 } else if (opcode == BPF_RSH) {
1380 * which means that after right shift, upper bits will be zero
1381 * note that verifier already checked that
1382 * 0 <= imm < 64 for shift insn
1384 dst_reg->imm += insn->imm;
1385 if (unlikely(dst_reg->imm > 64))
1386 /* some dumb code did:
1389 * and all bits are zero now */
1392 /* all other alu ops, means that we don't know what will
1393 * happen to the value, mark it with unknown number of zero bits
1398 if (dst_reg->imm < 0) {
1399 /* all 64 bits of the register can contain non-zero bits
1400 * and such value cannot be added to ptr_to_packet, since it
1401 * may overflow, mark it as unknown to avoid further eval
1408 static int evaluate_reg_imm_alu(struct verifier_env *env, struct bpf_insn *insn)
1410 struct reg_state *regs = env->cur_state.regs;
1411 struct reg_state *dst_reg = ®s[insn->dst_reg];
1412 struct reg_state *src_reg = ®s[insn->src_reg];
1413 u8 opcode = BPF_OP(insn->code);
1415 /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1416 * Don't care about overflow or negative values, just add them
1418 if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1419 dst_reg->imm += insn->imm;
1420 else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1421 src_reg->type == CONST_IMM)
1422 dst_reg->imm += src_reg->imm;
1424 mark_reg_unknown_value(regs, insn->dst_reg);
1428 /* check validity of 32-bit and 64-bit arithmetic operations */
1429 static int check_alu_op(struct verifier_env *env, struct bpf_insn *insn)
1431 struct reg_state *regs = env->cur_state.regs, *dst_reg;
1432 u8 opcode = BPF_OP(insn->code);
1435 if (opcode == BPF_END || opcode == BPF_NEG) {
1436 if (opcode == BPF_NEG) {
1437 if (BPF_SRC(insn->code) != 0 ||
1438 insn->src_reg != BPF_REG_0 ||
1439 insn->off != 0 || insn->imm != 0) {
1440 verbose("BPF_NEG uses reserved fields\n");
1444 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1445 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1446 verbose("BPF_END uses reserved fields\n");
1451 /* check src operand */
1452 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1456 if (is_pointer_value(env, insn->dst_reg)) {
1457 verbose("R%d pointer arithmetic prohibited\n",
1462 /* check dest operand */
1463 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1467 } else if (opcode == BPF_MOV) {
1469 if (BPF_SRC(insn->code) == BPF_X) {
1470 if (insn->imm != 0 || insn->off != 0) {
1471 verbose("BPF_MOV uses reserved fields\n");
1475 /* check src operand */
1476 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1480 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1481 verbose("BPF_MOV uses reserved fields\n");
1486 /* check dest operand */
1487 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1491 if (BPF_SRC(insn->code) == BPF_X) {
1492 if (BPF_CLASS(insn->code) == BPF_ALU64) {
1494 * copy register state to dest reg
1496 regs[insn->dst_reg] = regs[insn->src_reg];
1498 if (is_pointer_value(env, insn->src_reg)) {
1499 verbose("R%d partial copy of pointer\n",
1503 regs[insn->dst_reg].type = UNKNOWN_VALUE;
1504 regs[insn->dst_reg].map_ptr = NULL;
1508 * remember the value we stored into this reg
1510 regs[insn->dst_reg].type = CONST_IMM;
1511 regs[insn->dst_reg].imm = insn->imm;
1514 } else if (opcode > BPF_END) {
1515 verbose("invalid BPF_ALU opcode %x\n", opcode);
1518 } else { /* all other ALU ops: and, sub, xor, add, ... */
1520 if (BPF_SRC(insn->code) == BPF_X) {
1521 if (insn->imm != 0 || insn->off != 0) {
1522 verbose("BPF_ALU uses reserved fields\n");
1525 /* check src1 operand */
1526 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1530 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1531 verbose("BPF_ALU uses reserved fields\n");
1536 /* check src2 operand */
1537 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1541 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1542 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1543 verbose("div by zero\n");
1547 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1548 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1549 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1551 if (insn->imm < 0 || insn->imm >= size) {
1552 verbose("invalid shift %d\n", insn->imm);
1557 /* check dest operand */
1558 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1562 dst_reg = ®s[insn->dst_reg];
1564 /* pattern match 'bpf_add Rx, imm' instruction */
1565 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1566 dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1567 dst_reg->type = PTR_TO_STACK;
1568 dst_reg->imm = insn->imm;
1570 } else if (opcode == BPF_ADD &&
1571 BPF_CLASS(insn->code) == BPF_ALU64 &&
1572 dst_reg->type == PTR_TO_PACKET) {
1573 /* ptr_to_packet += K|X */
1574 return check_packet_ptr_add(env, insn);
1575 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1576 dst_reg->type == UNKNOWN_VALUE &&
1577 env->allow_ptr_leaks) {
1578 /* unknown += K|X */
1579 return evaluate_reg_alu(env, insn);
1580 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1581 dst_reg->type == CONST_IMM &&
1582 env->allow_ptr_leaks) {
1583 /* reg_imm += K|X */
1584 return evaluate_reg_imm_alu(env, insn);
1585 } else if (is_pointer_value(env, insn->dst_reg)) {
1586 verbose("R%d pointer arithmetic prohibited\n",
1589 } else if (BPF_SRC(insn->code) == BPF_X &&
1590 is_pointer_value(env, insn->src_reg)) {
1591 verbose("R%d pointer arithmetic prohibited\n",
1596 /* mark dest operand */
1597 mark_reg_unknown_value(regs, insn->dst_reg);
1603 static void find_good_pkt_pointers(struct verifier_env *env,
1604 struct reg_state *dst_reg)
1606 struct verifier_state *state = &env->cur_state;
1607 struct reg_state *regs = state->regs, *reg;
1611 * if (r2 > pkt_end) goto somewhere
1612 * r2 == dst_reg, pkt_end == src_reg,
1613 * r2=pkt(id=n,off=8,r=0)
1614 * r3=pkt(id=n,off=0,r=0)
1615 * find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1616 * so that range of bytes [r3, r3 + 8) is safe to access
1618 for (i = 0; i < MAX_BPF_REG; i++)
1619 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1620 regs[i].range = dst_reg->off;
1622 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1623 if (state->stack_slot_type[i] != STACK_SPILL)
1625 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1626 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1627 reg->range = dst_reg->off;
1631 static int check_cond_jmp_op(struct verifier_env *env,
1632 struct bpf_insn *insn, int *insn_idx)
1634 struct reg_state *regs = env->cur_state.regs, *dst_reg;
1635 struct verifier_state *other_branch;
1636 u8 opcode = BPF_OP(insn->code);
1639 if (opcode > BPF_EXIT) {
1640 verbose("invalid BPF_JMP opcode %x\n", opcode);
1644 if (BPF_SRC(insn->code) == BPF_X) {
1645 if (insn->imm != 0) {
1646 verbose("BPF_JMP uses reserved fields\n");
1650 /* check src1 operand */
1651 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1655 if (is_pointer_value(env, insn->src_reg)) {
1656 verbose("R%d pointer comparison prohibited\n",
1661 if (insn->src_reg != BPF_REG_0) {
1662 verbose("BPF_JMP uses reserved fields\n");
1667 /* check src2 operand */
1668 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1672 dst_reg = ®s[insn->dst_reg];
1674 /* detect if R == 0 where R was initialized to zero earlier */
1675 if (BPF_SRC(insn->code) == BPF_K &&
1676 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1677 dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
1678 if (opcode == BPF_JEQ) {
1679 /* if (imm == imm) goto pc+off;
1680 * only follow the goto, ignore fall-through
1682 *insn_idx += insn->off;
1685 /* if (imm != imm) goto pc+off;
1686 * only follow fall-through branch, since
1687 * that's where the program will go
1693 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1697 /* detect if R == 0 where R is returned value from bpf_map_lookup_elem() */
1698 if (BPF_SRC(insn->code) == BPF_K &&
1699 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1700 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1701 if (opcode == BPF_JEQ) {
1702 /* next fallthrough insn can access memory via
1705 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1706 /* branch targer cannot access it, since reg == 0 */
1707 mark_reg_unknown_value(other_branch->regs,
1710 other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1711 mark_reg_unknown_value(regs, insn->dst_reg);
1713 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
1714 dst_reg->type == PTR_TO_PACKET &&
1715 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
1716 find_good_pkt_pointers(env, dst_reg);
1717 } else if (is_pointer_value(env, insn->dst_reg)) {
1718 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
1722 print_verifier_state(&env->cur_state);
1726 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
1727 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
1729 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
1731 return (struct bpf_map *) (unsigned long) imm64;
1734 /* verify BPF_LD_IMM64 instruction */
1735 static int check_ld_imm(struct verifier_env *env, struct bpf_insn *insn)
1737 struct reg_state *regs = env->cur_state.regs;
1740 if (BPF_SIZE(insn->code) != BPF_DW) {
1741 verbose("invalid BPF_LD_IMM insn\n");
1744 if (insn->off != 0) {
1745 verbose("BPF_LD_IMM64 uses reserved fields\n");
1749 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1753 if (insn->src_reg == 0)
1754 /* generic move 64-bit immediate into a register */
1757 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1758 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
1760 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
1761 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
1765 static bool may_access_skb(enum bpf_prog_type type)
1768 case BPF_PROG_TYPE_SOCKET_FILTER:
1769 case BPF_PROG_TYPE_SCHED_CLS:
1770 case BPF_PROG_TYPE_SCHED_ACT:
1777 /* verify safety of LD_ABS|LD_IND instructions:
1778 * - they can only appear in the programs where ctx == skb
1779 * - since they are wrappers of function calls, they scratch R1-R5 registers,
1780 * preserve R6-R9, and store return value into R0
1783 * ctx == skb == R6 == CTX
1786 * SRC == any register
1787 * IMM == 32-bit immediate
1790 * R0 - 8/16/32-bit skb data converted to cpu endianness
1792 static int check_ld_abs(struct verifier_env *env, struct bpf_insn *insn)
1794 struct reg_state *regs = env->cur_state.regs;
1795 u8 mode = BPF_MODE(insn->code);
1796 struct reg_state *reg;
1799 if (!may_access_skb(env->prog->type)) {
1800 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
1804 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
1805 BPF_SIZE(insn->code) == BPF_DW ||
1806 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1807 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
1811 /* check whether implicit source operand (register R6) is readable */
1812 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
1816 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
1817 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1821 if (mode == BPF_IND) {
1822 /* check explicit source operand */
1823 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1828 /* reset caller saved regs to unreadable */
1829 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1830 reg = regs + caller_saved[i];
1831 reg->type = NOT_INIT;
1835 /* mark destination R0 register as readable, since it contains
1836 * the value fetched from the packet
1838 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1842 /* non-recursive DFS pseudo code
1843 * 1 procedure DFS-iterative(G,v):
1844 * 2 label v as discovered
1845 * 3 let S be a stack
1847 * 5 while S is not empty
1849 * 7 if t is what we're looking for:
1851 * 9 for all edges e in G.adjacentEdges(t) do
1852 * 10 if edge e is already labelled
1853 * 11 continue with the next edge
1854 * 12 w <- G.adjacentVertex(t,e)
1855 * 13 if vertex w is not discovered and not explored
1856 * 14 label e as tree-edge
1857 * 15 label w as discovered
1860 * 18 else if vertex w is discovered
1861 * 19 label e as back-edge
1863 * 21 // vertex w is explored
1864 * 22 label e as forward- or cross-edge
1865 * 23 label t as explored
1870 * 0x11 - discovered and fall-through edge labelled
1871 * 0x12 - discovered and fall-through and branch edges labelled
1882 #define STATE_LIST_MARK ((struct verifier_state_list *) -1L)
1884 static int *insn_stack; /* stack of insns to process */
1885 static int cur_stack; /* current stack index */
1886 static int *insn_state;
1888 /* t, w, e - match pseudo-code above:
1889 * t - index of current instruction
1890 * w - next instruction
1893 static int push_insn(int t, int w, int e, struct verifier_env *env)
1895 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
1898 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
1901 if (w < 0 || w >= env->prog->len) {
1902 verbose("jump out of range from insn %d to %d\n", t, w);
1907 /* mark branch target for state pruning */
1908 env->explored_states[w] = STATE_LIST_MARK;
1910 if (insn_state[w] == 0) {
1912 insn_state[t] = DISCOVERED | e;
1913 insn_state[w] = DISCOVERED;
1914 if (cur_stack >= env->prog->len)
1916 insn_stack[cur_stack++] = w;
1918 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
1919 verbose("back-edge from insn %d to %d\n", t, w);
1921 } else if (insn_state[w] == EXPLORED) {
1922 /* forward- or cross-edge */
1923 insn_state[t] = DISCOVERED | e;
1925 verbose("insn state internal bug\n");
1931 /* non-recursive depth-first-search to detect loops in BPF program
1932 * loop == back-edge in directed graph
1934 static int check_cfg(struct verifier_env *env)
1936 struct bpf_insn *insns = env->prog->insnsi;
1937 int insn_cnt = env->prog->len;
1941 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1945 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1951 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
1952 insn_stack[0] = 0; /* 0 is the first instruction */
1958 t = insn_stack[cur_stack - 1];
1960 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
1961 u8 opcode = BPF_OP(insns[t].code);
1963 if (opcode == BPF_EXIT) {
1965 } else if (opcode == BPF_CALL) {
1966 ret = push_insn(t, t + 1, FALLTHROUGH, env);
1971 if (t + 1 < insn_cnt)
1972 env->explored_states[t + 1] = STATE_LIST_MARK;
1973 } else if (opcode == BPF_JA) {
1974 if (BPF_SRC(insns[t].code) != BPF_K) {
1978 /* unconditional jump with single edge */
1979 ret = push_insn(t, t + insns[t].off + 1,
1985 /* tell verifier to check for equivalent states
1986 * after every call and jump
1988 if (t + 1 < insn_cnt)
1989 env->explored_states[t + 1] = STATE_LIST_MARK;
1991 /* conditional jump with two edges */
1992 ret = push_insn(t, t + 1, FALLTHROUGH, env);
1998 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2005 /* all other non-branch instructions with single
2008 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2016 insn_state[t] = EXPLORED;
2017 if (cur_stack-- <= 0) {
2018 verbose("pop stack internal bug\n");
2025 for (i = 0; i < insn_cnt; i++) {
2026 if (insn_state[i] != EXPLORED) {
2027 verbose("unreachable insn %d\n", i);
2032 ret = 0; /* cfg looks good */
2040 /* the following conditions reduce the number of explored insns
2041 * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2043 static bool compare_ptrs_to_packet(struct reg_state *old, struct reg_state *cur)
2045 if (old->id != cur->id)
2048 /* old ptr_to_packet is more conservative, since it allows smaller
2050 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2051 * old(off=0,r=10) means that with range=10 the verifier proceeded
2052 * further and found no issues with the program. Now we're in the same
2053 * spot with cur(off=0,r=20), so we're safe too, since anything further
2054 * will only be looking at most 10 bytes after this pointer.
2056 if (old->off == cur->off && old->range < cur->range)
2059 /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2060 * since both cannot be used for packet access and safe(old)
2061 * pointer has smaller off that could be used for further
2062 * 'if (ptr > data_end)' check
2064 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2065 * that we cannot access the packet.
2066 * The safe range is:
2067 * [ptr, ptr + range - off)
2068 * so whenever off >=range, it means no safe bytes from this pointer.
2069 * When comparing old->off <= cur->off, it means that older code
2070 * went with smaller offset and that offset was later
2071 * used to figure out the safe range after 'if (ptr > data_end)' check
2072 * Say, 'old' state was explored like:
2073 * ... R3(off=0, r=0)
2075 * ... now R4(off=20,r=0) <-- here
2076 * if (R4 > data_end)
2077 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2078 * ... the code further went all the way to bpf_exit.
2079 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2080 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2081 * goes further, such cur_R4 will give larger safe packet range after
2082 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2083 * so they will be good with r=30 and we can prune the search.
2085 if (old->off <= cur->off &&
2086 old->off >= old->range && cur->off >= cur->range)
2092 /* compare two verifier states
2094 * all states stored in state_list are known to be valid, since
2095 * verifier reached 'bpf_exit' instruction through them
2097 * this function is called when verifier exploring different branches of
2098 * execution popped from the state stack. If it sees an old state that has
2099 * more strict register state and more strict stack state then this execution
2100 * branch doesn't need to be explored further, since verifier already
2101 * concluded that more strict state leads to valid finish.
2103 * Therefore two states are equivalent if register state is more conservative
2104 * and explored stack state is more conservative than the current one.
2107 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2108 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2110 * In other words if current stack state (one being explored) has more
2111 * valid slots than old one that already passed validation, it means
2112 * the verifier can stop exploring and conclude that current state is valid too
2114 * Similarly with registers. If explored state has register type as invalid
2115 * whereas register type in current state is meaningful, it means that
2116 * the current state will reach 'bpf_exit' instruction safely
2118 static bool states_equal(struct verifier_state *old, struct verifier_state *cur)
2120 struct reg_state *rold, *rcur;
2123 for (i = 0; i < MAX_BPF_REG; i++) {
2124 rold = &old->regs[i];
2125 rcur = &cur->regs[i];
2127 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2130 if (rold->type == NOT_INIT ||
2131 (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2134 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2135 compare_ptrs_to_packet(rold, rcur))
2141 for (i = 0; i < MAX_BPF_STACK; i++) {
2142 if (old->stack_slot_type[i] == STACK_INVALID)
2144 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2145 /* Ex: old explored (safe) state has STACK_SPILL in
2146 * this stack slot, but current has has STACK_MISC ->
2147 * this verifier states are not equivalent,
2148 * return false to continue verification of this path
2151 if (i % BPF_REG_SIZE)
2153 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2154 &cur->spilled_regs[i / BPF_REG_SIZE],
2155 sizeof(old->spilled_regs[0])))
2156 /* when explored and current stack slot types are
2157 * the same, check that stored pointers types
2158 * are the same as well.
2159 * Ex: explored safe path could have stored
2160 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -8}
2161 * but current path has stored:
2162 * (struct reg_state) {.type = PTR_TO_STACK, .imm = -16}
2163 * such verifier states are not equivalent.
2164 * return false to continue verification of this path
2173 static int is_state_visited(struct verifier_env *env, int insn_idx)
2175 struct verifier_state_list *new_sl;
2176 struct verifier_state_list *sl;
2178 sl = env->explored_states[insn_idx];
2180 /* this 'insn_idx' instruction wasn't marked, so we will not
2181 * be doing state search here
2185 while (sl != STATE_LIST_MARK) {
2186 if (states_equal(&sl->state, &env->cur_state))
2187 /* reached equivalent register/stack state,
2194 /* there were no equivalent states, remember current one.
2195 * technically the current state is not proven to be safe yet,
2196 * but it will either reach bpf_exit (which means it's safe) or
2197 * it will be rejected. Since there are no loops, we won't be
2198 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2200 new_sl = kmalloc(sizeof(struct verifier_state_list), GFP_USER);
2204 /* add new state to the head of linked list */
2205 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2206 new_sl->next = env->explored_states[insn_idx];
2207 env->explored_states[insn_idx] = new_sl;
2211 static int do_check(struct verifier_env *env)
2213 struct verifier_state *state = &env->cur_state;
2214 struct bpf_insn *insns = env->prog->insnsi;
2215 struct reg_state *regs = state->regs;
2216 int insn_cnt = env->prog->len;
2217 int insn_idx, prev_insn_idx = 0;
2218 int insn_processed = 0;
2219 bool do_print_state = false;
2221 init_reg_state(regs);
2224 struct bpf_insn *insn;
2228 if (insn_idx >= insn_cnt) {
2229 verbose("invalid insn idx %d insn_cnt %d\n",
2230 insn_idx, insn_cnt);
2234 insn = &insns[insn_idx];
2235 class = BPF_CLASS(insn->code);
2237 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2238 verbose("BPF program is too large. Proccessed %d insn\n",
2243 err = is_state_visited(env, insn_idx);
2247 /* found equivalent state, can prune the search */
2250 verbose("\nfrom %d to %d: safe\n",
2251 prev_insn_idx, insn_idx);
2253 verbose("%d: safe\n", insn_idx);
2255 goto process_bpf_exit;
2258 if (log_level && do_print_state) {
2259 verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2260 print_verifier_state(&env->cur_state);
2261 do_print_state = false;
2265 verbose("%d: ", insn_idx);
2266 print_bpf_insn(insn);
2269 if (class == BPF_ALU || class == BPF_ALU64) {
2270 err = check_alu_op(env, insn);
2274 } else if (class == BPF_LDX) {
2275 enum bpf_reg_type src_reg_type;
2277 /* check for reserved fields is already done */
2279 /* check src operand */
2280 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2284 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2288 src_reg_type = regs[insn->src_reg].type;
2290 /* check that memory (src_reg + off) is readable,
2291 * the state of dst_reg will be updated by this func
2293 err = check_mem_access(env, insn->src_reg, insn->off,
2294 BPF_SIZE(insn->code), BPF_READ,
2299 if (BPF_SIZE(insn->code) != BPF_W) {
2304 if (insn->imm == 0) {
2306 * dst_reg = *(u32 *)(src_reg + off)
2307 * use reserved 'imm' field to mark this insn
2309 insn->imm = src_reg_type;
2311 } else if (src_reg_type != insn->imm &&
2312 (src_reg_type == PTR_TO_CTX ||
2313 insn->imm == PTR_TO_CTX)) {
2314 /* ABuser program is trying to use the same insn
2315 * dst_reg = *(u32*) (src_reg + off)
2316 * with different pointer types:
2317 * src_reg == ctx in one branch and
2318 * src_reg == stack|map in some other branch.
2321 verbose("same insn cannot be used with different pointers\n");
2325 } else if (class == BPF_STX) {
2326 enum bpf_reg_type dst_reg_type;
2328 if (BPF_MODE(insn->code) == BPF_XADD) {
2329 err = check_xadd(env, insn);
2336 /* check src1 operand */
2337 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2340 /* check src2 operand */
2341 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2345 dst_reg_type = regs[insn->dst_reg].type;
2347 /* check that memory (dst_reg + off) is writeable */
2348 err = check_mem_access(env, insn->dst_reg, insn->off,
2349 BPF_SIZE(insn->code), BPF_WRITE,
2354 if (insn->imm == 0) {
2355 insn->imm = dst_reg_type;
2356 } else if (dst_reg_type != insn->imm &&
2357 (dst_reg_type == PTR_TO_CTX ||
2358 insn->imm == PTR_TO_CTX)) {
2359 verbose("same insn cannot be used with different pointers\n");
2363 } else if (class == BPF_ST) {
2364 if (BPF_MODE(insn->code) != BPF_MEM ||
2365 insn->src_reg != BPF_REG_0) {
2366 verbose("BPF_ST uses reserved fields\n");
2369 /* check src operand */
2370 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2374 /* check that memory (dst_reg + off) is writeable */
2375 err = check_mem_access(env, insn->dst_reg, insn->off,
2376 BPF_SIZE(insn->code), BPF_WRITE,
2381 } else if (class == BPF_JMP) {
2382 u8 opcode = BPF_OP(insn->code);
2384 if (opcode == BPF_CALL) {
2385 if (BPF_SRC(insn->code) != BPF_K ||
2387 insn->src_reg != BPF_REG_0 ||
2388 insn->dst_reg != BPF_REG_0) {
2389 verbose("BPF_CALL uses reserved fields\n");
2393 err = check_call(env, insn->imm);
2397 } else if (opcode == BPF_JA) {
2398 if (BPF_SRC(insn->code) != BPF_K ||
2400 insn->src_reg != BPF_REG_0 ||
2401 insn->dst_reg != BPF_REG_0) {
2402 verbose("BPF_JA uses reserved fields\n");
2406 insn_idx += insn->off + 1;
2409 } else if (opcode == BPF_EXIT) {
2410 if (BPF_SRC(insn->code) != BPF_K ||
2412 insn->src_reg != BPF_REG_0 ||
2413 insn->dst_reg != BPF_REG_0) {
2414 verbose("BPF_EXIT uses reserved fields\n");
2418 /* eBPF calling convetion is such that R0 is used
2419 * to return the value from eBPF program.
2420 * Make sure that it's readable at this time
2421 * of bpf_exit, which means that program wrote
2422 * something into it earlier
2424 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2428 if (is_pointer_value(env, BPF_REG_0)) {
2429 verbose("R0 leaks addr as return value\n");
2434 insn_idx = pop_stack(env, &prev_insn_idx);
2438 do_print_state = true;
2442 err = check_cond_jmp_op(env, insn, &insn_idx);
2446 } else if (class == BPF_LD) {
2447 u8 mode = BPF_MODE(insn->code);
2449 if (mode == BPF_ABS || mode == BPF_IND) {
2450 err = check_ld_abs(env, insn);
2454 } else if (mode == BPF_IMM) {
2455 err = check_ld_imm(env, insn);
2461 verbose("invalid BPF_LD mode\n");
2465 verbose("unknown insn class %d\n", class);
2472 verbose("processed %d insns\n", insn_processed);
2476 /* look for pseudo eBPF instructions that access map FDs and
2477 * replace them with actual map pointers
2479 static int replace_map_fd_with_map_ptr(struct verifier_env *env)
2481 struct bpf_insn *insn = env->prog->insnsi;
2482 int insn_cnt = env->prog->len;
2485 for (i = 0; i < insn_cnt; i++, insn++) {
2486 if (BPF_CLASS(insn->code) == BPF_LDX &&
2487 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
2488 verbose("BPF_LDX uses reserved fields\n");
2492 if (BPF_CLASS(insn->code) == BPF_STX &&
2493 ((BPF_MODE(insn->code) != BPF_MEM &&
2494 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2495 verbose("BPF_STX uses reserved fields\n");
2499 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2500 struct bpf_map *map;
2503 if (i == insn_cnt - 1 || insn[1].code != 0 ||
2504 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2506 verbose("invalid bpf_ld_imm64 insn\n");
2510 if (insn->src_reg == 0)
2511 /* valid generic load 64-bit imm */
2514 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2515 verbose("unrecognized bpf_ld_imm64 insn\n");
2519 f = fdget(insn->imm);
2520 map = __bpf_map_get(f);
2522 verbose("fd %d is not pointing to valid bpf_map\n",
2524 return PTR_ERR(map);
2527 /* store map pointer inside BPF_LD_IMM64 instruction */
2528 insn[0].imm = (u32) (unsigned long) map;
2529 insn[1].imm = ((u64) (unsigned long) map) >> 32;
2531 /* check whether we recorded this map already */
2532 for (j = 0; j < env->used_map_cnt; j++)
2533 if (env->used_maps[j] == map) {
2538 if (env->used_map_cnt >= MAX_USED_MAPS) {
2543 /* hold the map. If the program is rejected by verifier,
2544 * the map will be released by release_maps() or it
2545 * will be used by the valid program until it's unloaded
2546 * and all maps are released in free_bpf_prog_info()
2548 map = bpf_map_inc(map, false);
2551 return PTR_ERR(map);
2553 env->used_maps[env->used_map_cnt++] = map;
2562 /* now all pseudo BPF_LD_IMM64 instructions load valid
2563 * 'struct bpf_map *' into a register instead of user map_fd.
2564 * These pointers will be used later by verifier to validate map access.
2569 /* drop refcnt of maps used by the rejected program */
2570 static void release_maps(struct verifier_env *env)
2574 for (i = 0; i < env->used_map_cnt; i++)
2575 bpf_map_put(env->used_maps[i]);
2578 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2579 static void convert_pseudo_ld_imm64(struct verifier_env *env)
2581 struct bpf_insn *insn = env->prog->insnsi;
2582 int insn_cnt = env->prog->len;
2585 for (i = 0; i < insn_cnt; i++, insn++)
2586 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2590 /* convert load instructions that access fields of 'struct __sk_buff'
2591 * into sequence of instructions that access fields of 'struct sk_buff'
2593 static int convert_ctx_accesses(struct verifier_env *env)
2595 struct bpf_insn *insn = env->prog->insnsi;
2596 int insn_cnt = env->prog->len;
2597 struct bpf_insn insn_buf[16];
2598 struct bpf_prog *new_prog;
2599 enum bpf_access_type type;
2602 if (!env->prog->aux->ops->convert_ctx_access)
2605 for (i = 0; i < insn_cnt; i++, insn++) {
2606 u32 insn_delta, cnt;
2608 if (insn->code == (BPF_LDX | BPF_MEM | BPF_W))
2610 else if (insn->code == (BPF_STX | BPF_MEM | BPF_W))
2615 if (insn->imm != PTR_TO_CTX) {
2616 /* clear internal mark */
2621 cnt = env->prog->aux->ops->
2622 convert_ctx_access(type, insn->dst_reg, insn->src_reg,
2623 insn->off, insn_buf, env->prog);
2624 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
2625 verbose("bpf verifier is misconfigured\n");
2629 new_prog = bpf_patch_insn_single(env->prog, i, insn_buf, cnt);
2633 insn_delta = cnt - 1;
2635 /* keep walking new program and skip insns we just inserted */
2636 env->prog = new_prog;
2637 insn = new_prog->insnsi + i + insn_delta;
2639 insn_cnt += insn_delta;
2646 static void free_states(struct verifier_env *env)
2648 struct verifier_state_list *sl, *sln;
2651 if (!env->explored_states)
2654 for (i = 0; i < env->prog->len; i++) {
2655 sl = env->explored_states[i];
2658 while (sl != STATE_LIST_MARK) {
2665 kfree(env->explored_states);
2668 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
2670 char __user *log_ubuf = NULL;
2671 struct verifier_env *env;
2674 if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
2677 /* 'struct verifier_env' can be global, but since it's not small,
2678 * allocate/free it every time bpf_check() is called
2680 env = kzalloc(sizeof(struct verifier_env), GFP_KERNEL);
2686 /* grab the mutex to protect few globals used by verifier */
2687 mutex_lock(&bpf_verifier_lock);
2689 if (attr->log_level || attr->log_buf || attr->log_size) {
2690 /* user requested verbose verifier output
2691 * and supplied buffer to store the verification trace
2693 log_level = attr->log_level;
2694 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
2695 log_size = attr->log_size;
2699 /* log_* values have to be sane */
2700 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
2701 log_level == 0 || log_ubuf == NULL)
2705 log_buf = vmalloc(log_size);
2712 ret = replace_map_fd_with_map_ptr(env);
2714 goto skip_full_check;
2716 env->explored_states = kcalloc(env->prog->len,
2717 sizeof(struct verifier_state_list *),
2720 if (!env->explored_states)
2721 goto skip_full_check;
2723 ret = check_cfg(env);
2725 goto skip_full_check;
2727 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2729 ret = do_check(env);
2732 while (pop_stack(env, NULL) >= 0);
2736 /* program is valid, convert *(u32*)(ctx + off) accesses */
2737 ret = convert_ctx_accesses(env);
2739 if (log_level && log_len >= log_size - 1) {
2740 BUG_ON(log_len >= log_size);
2741 /* verifier log exceeded user supplied buffer */
2743 /* fall through to return what was recorded */
2746 /* copy verifier log back to user space including trailing zero */
2747 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
2752 if (ret == 0 && env->used_map_cnt) {
2753 /* if program passed verifier, update used_maps in bpf_prog_info */
2754 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
2755 sizeof(env->used_maps[0]),
2758 if (!env->prog->aux->used_maps) {
2763 memcpy(env->prog->aux->used_maps, env->used_maps,
2764 sizeof(env->used_maps[0]) * env->used_map_cnt);
2765 env->prog->aux->used_map_cnt = env->used_map_cnt;
2767 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
2768 * bpf_ld_imm64 instructions
2770 convert_pseudo_ld_imm64(env);
2777 if (!env->prog->aux->used_maps)
2778 /* if we didn't copy map pointers into bpf_prog_info, release
2779 * them now. Otherwise free_bpf_prog_info() will release them.
2784 mutex_unlock(&bpf_verifier_lock);