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/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
23 /* bpf_check() is a static code analyzer that walks eBPF program
24 * instruction by instruction and updates register/stack state.
25 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
27 * The first pass is depth-first-search to check that the program is a DAG.
28 * It rejects the following programs:
29 * - larger than BPF_MAXINSNS insns
30 * - if loop is present (detected via back-edge)
31 * - unreachable insns exist (shouldn't be a forest. program = one function)
32 * - out of bounds or malformed jumps
33 * The second pass is all possible path descent from the 1st insn.
34 * Since it's analyzing all pathes through the program, the length of the
35 * analysis is limited to 32k insn, which may be hit even if total number of
36 * insn is less then 4K, but there are too many branches that change stack/regs.
37 * Number of 'branches to be analyzed' is limited to 1k
39 * On entry to each instruction, each register has a type, and the instruction
40 * changes the types of the registers depending on instruction semantics.
41 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
44 * All registers are 64-bit.
45 * R0 - return register
46 * R1-R5 argument passing registers
47 * R6-R9 callee saved registers
48 * R10 - frame pointer read-only
50 * At the start of BPF program the register R1 contains a pointer to bpf_context
51 * and has type PTR_TO_CTX.
53 * Verifier tracks arithmetic operations on pointers in case:
54 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
55 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
56 * 1st insn copies R10 (which has FRAME_PTR) type into R1
57 * and 2nd arithmetic instruction is pattern matched to recognize
58 * that it wants to construct a pointer to some element within stack.
59 * So after 2nd insn, the register R1 has type PTR_TO_STACK
60 * (and -20 constant is saved for further stack bounds checking).
61 * Meaning that this reg is a pointer to stack plus known immediate constant.
63 * Most of the time the registers have UNKNOWN_VALUE type, which
64 * means the register has some value, but it's not a valid pointer.
65 * (like pointer plus pointer becomes UNKNOWN_VALUE type)
67 * When verifier sees load or store instructions the type of base register
68 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
69 * types recognized by check_mem_access() function.
71 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
72 * and the range of [ptr, ptr + map's value_size) is accessible.
74 * registers used to pass values to function calls are checked against
75 * function argument constraints.
77 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
78 * It means that the register type passed to this function must be
79 * PTR_TO_STACK and it will be used inside the function as
80 * 'pointer to map element key'
82 * For example the argument constraints for bpf_map_lookup_elem():
83 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
84 * .arg1_type = ARG_CONST_MAP_PTR,
85 * .arg2_type = ARG_PTR_TO_MAP_KEY,
87 * ret_type says that this function returns 'pointer to map elem value or null'
88 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
89 * 2nd argument should be a pointer to stack, which will be used inside
90 * the helper function as a pointer to map element key.
92 * On the kernel side the helper function looks like:
93 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
95 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
96 * void *key = (void *) (unsigned long) r2;
99 * here kernel can access 'key' and 'map' pointers safely, knowing that
100 * [key, key + map->key_size) bytes are valid and were initialized on
101 * the stack of eBPF program.
104 * Corresponding eBPF program may look like:
105 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
106 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
107 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
108 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
109 * here verifier looks at prototype of map_lookup_elem() and sees:
110 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
111 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
113 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
114 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
115 * and were initialized prior to this call.
116 * If it's ok, then verifier allows this BPF_CALL insn and looks at
117 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
118 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
119 * returns ether pointer to map value or NULL.
121 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
122 * insn, the register holding that pointer in the true branch changes state to
123 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
124 * branch. See check_cond_jmp_op().
126 * After the call R0 is set to return type of the function and registers R1-R5
127 * are set to NOT_INIT to indicate that they are no longer readable.
130 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
131 struct bpf_verifier_stack_elem {
132 /* verifer state is 'st'
133 * before processing instruction 'insn_idx'
134 * and after processing instruction 'prev_insn_idx'
136 struct bpf_verifier_state st;
139 struct bpf_verifier_stack_elem *next;
142 #define BPF_COMPLEXITY_LIMIT_INSNS 65536
143 #define BPF_COMPLEXITY_LIMIT_STACK 1024
145 struct bpf_call_arg_meta {
146 struct bpf_map *map_ptr;
153 /* verbose verifier prints what it's seeing
154 * bpf_check() is called under lock, so no race to access these global vars
156 static u32 log_level, log_size, log_len;
157 static char *log_buf;
159 static DEFINE_MUTEX(bpf_verifier_lock);
161 /* log_level controls verbosity level of eBPF verifier.
162 * verbose() is used to dump the verification trace to the log, so the user
163 * can figure out what's wrong with the program
165 static __printf(1, 2) void verbose(const char *fmt, ...)
169 if (log_level == 0 || log_len >= log_size - 1)
173 log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
177 /* string representation of 'enum bpf_reg_type' */
178 static const char * const reg_type_str[] = {
180 [UNKNOWN_VALUE] = "inv",
181 [PTR_TO_CTX] = "ctx",
182 [CONST_PTR_TO_MAP] = "map_ptr",
183 [PTR_TO_MAP_VALUE] = "map_value",
184 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
186 [PTR_TO_STACK] = "fp",
188 [PTR_TO_PACKET] = "pkt",
189 [PTR_TO_PACKET_END] = "pkt_end",
192 static void print_verifier_state(struct bpf_verifier_state *state)
194 struct bpf_reg_state *reg;
198 for (i = 0; i < MAX_BPF_REG; i++) {
199 reg = &state->regs[i];
203 verbose(" R%d=%s", i, reg_type_str[t]);
204 if (t == CONST_IMM || t == PTR_TO_STACK)
205 verbose("%lld", reg->imm);
206 else if (t == PTR_TO_PACKET)
207 verbose("(id=%d,off=%d,r=%d)",
208 reg->id, reg->off, reg->range);
209 else if (t == UNKNOWN_VALUE && reg->imm)
210 verbose("%lld", reg->imm);
211 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
212 t == PTR_TO_MAP_VALUE_OR_NULL)
213 verbose("(ks=%d,vs=%d)",
214 reg->map_ptr->key_size,
215 reg->map_ptr->value_size);
217 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
218 if (state->stack_slot_type[i] == STACK_SPILL)
219 verbose(" fp%d=%s", -MAX_BPF_STACK + i,
220 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
225 static const char *const bpf_class_string[] = {
233 [BPF_ALU64] = "alu64",
236 static const char *const bpf_alu_string[16] = {
237 [BPF_ADD >> 4] = "+=",
238 [BPF_SUB >> 4] = "-=",
239 [BPF_MUL >> 4] = "*=",
240 [BPF_DIV >> 4] = "/=",
241 [BPF_OR >> 4] = "|=",
242 [BPF_AND >> 4] = "&=",
243 [BPF_LSH >> 4] = "<<=",
244 [BPF_RSH >> 4] = ">>=",
245 [BPF_NEG >> 4] = "neg",
246 [BPF_MOD >> 4] = "%=",
247 [BPF_XOR >> 4] = "^=",
248 [BPF_MOV >> 4] = "=",
249 [BPF_ARSH >> 4] = "s>>=",
250 [BPF_END >> 4] = "endian",
253 static const char *const bpf_ldst_string[] = {
254 [BPF_W >> 3] = "u32",
255 [BPF_H >> 3] = "u16",
257 [BPF_DW >> 3] = "u64",
260 static const char *const bpf_jmp_string[16] = {
261 [BPF_JA >> 4] = "jmp",
262 [BPF_JEQ >> 4] = "==",
263 [BPF_JGT >> 4] = ">",
264 [BPF_JGE >> 4] = ">=",
265 [BPF_JSET >> 4] = "&",
266 [BPF_JNE >> 4] = "!=",
267 [BPF_JSGT >> 4] = "s>",
268 [BPF_JSGE >> 4] = "s>=",
269 [BPF_CALL >> 4] = "call",
270 [BPF_EXIT >> 4] = "exit",
273 static void print_bpf_insn(struct bpf_insn *insn)
275 u8 class = BPF_CLASS(insn->code);
277 if (class == BPF_ALU || class == BPF_ALU64) {
278 if (BPF_SRC(insn->code) == BPF_X)
279 verbose("(%02x) %sr%d %s %sr%d\n",
280 insn->code, class == BPF_ALU ? "(u32) " : "",
282 bpf_alu_string[BPF_OP(insn->code) >> 4],
283 class == BPF_ALU ? "(u32) " : "",
286 verbose("(%02x) %sr%d %s %s%d\n",
287 insn->code, class == BPF_ALU ? "(u32) " : "",
289 bpf_alu_string[BPF_OP(insn->code) >> 4],
290 class == BPF_ALU ? "(u32) " : "",
292 } else if (class == BPF_STX) {
293 if (BPF_MODE(insn->code) == BPF_MEM)
294 verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
296 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
298 insn->off, insn->src_reg);
299 else if (BPF_MODE(insn->code) == BPF_XADD)
300 verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
302 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
303 insn->dst_reg, insn->off,
306 verbose("BUG_%02x\n", insn->code);
307 } else if (class == BPF_ST) {
308 if (BPF_MODE(insn->code) != BPF_MEM) {
309 verbose("BUG_st_%02x\n", insn->code);
312 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
314 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
316 insn->off, insn->imm);
317 } else if (class == BPF_LDX) {
318 if (BPF_MODE(insn->code) != BPF_MEM) {
319 verbose("BUG_ldx_%02x\n", insn->code);
322 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
323 insn->code, insn->dst_reg,
324 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
325 insn->src_reg, insn->off);
326 } else if (class == BPF_LD) {
327 if (BPF_MODE(insn->code) == BPF_ABS) {
328 verbose("(%02x) r0 = *(%s *)skb[%d]\n",
330 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
332 } else if (BPF_MODE(insn->code) == BPF_IND) {
333 verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
335 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
336 insn->src_reg, insn->imm);
337 } else if (BPF_MODE(insn->code) == BPF_IMM) {
338 verbose("(%02x) r%d = 0x%x\n",
339 insn->code, insn->dst_reg, insn->imm);
341 verbose("BUG_ld_%02x\n", insn->code);
344 } else if (class == BPF_JMP) {
345 u8 opcode = BPF_OP(insn->code);
347 if (opcode == BPF_CALL) {
348 verbose("(%02x) call %d\n", insn->code, insn->imm);
349 } else if (insn->code == (BPF_JMP | BPF_JA)) {
350 verbose("(%02x) goto pc%+d\n",
351 insn->code, insn->off);
352 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
353 verbose("(%02x) exit\n", insn->code);
354 } else if (BPF_SRC(insn->code) == BPF_X) {
355 verbose("(%02x) if r%d %s r%d goto pc%+d\n",
356 insn->code, insn->dst_reg,
357 bpf_jmp_string[BPF_OP(insn->code) >> 4],
358 insn->src_reg, insn->off);
360 verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
361 insn->code, insn->dst_reg,
362 bpf_jmp_string[BPF_OP(insn->code) >> 4],
363 insn->imm, insn->off);
366 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
370 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
372 struct bpf_verifier_stack_elem *elem;
375 if (env->head == NULL)
378 memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
379 insn_idx = env->head->insn_idx;
381 *prev_insn_idx = env->head->prev_insn_idx;
382 elem = env->head->next;
389 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
390 int insn_idx, int prev_insn_idx)
392 struct bpf_verifier_stack_elem *elem;
394 elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
398 memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
399 elem->insn_idx = insn_idx;
400 elem->prev_insn_idx = prev_insn_idx;
401 elem->next = env->head;
404 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
405 verbose("BPF program is too complex\n");
410 /* pop all elements and return */
411 while (pop_stack(env, NULL) >= 0);
415 #define CALLER_SAVED_REGS 6
416 static const int caller_saved[CALLER_SAVED_REGS] = {
417 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
420 static void init_reg_state(struct bpf_reg_state *regs)
424 for (i = 0; i < MAX_BPF_REG; i++) {
425 regs[i].type = NOT_INIT;
430 regs[BPF_REG_FP].type = FRAME_PTR;
432 /* 1st arg to a function */
433 regs[BPF_REG_1].type = PTR_TO_CTX;
436 static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
438 BUG_ON(regno >= MAX_BPF_REG);
439 regs[regno].type = UNKNOWN_VALUE;
444 SRC_OP, /* register is used as source operand */
445 DST_OP, /* register is used as destination operand */
446 DST_OP_NO_MARK /* same as above, check only, don't mark */
449 static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
452 if (regno >= MAX_BPF_REG) {
453 verbose("R%d is invalid\n", regno);
458 /* check whether register used as source operand can be read */
459 if (regs[regno].type == NOT_INIT) {
460 verbose("R%d !read_ok\n", regno);
464 /* check whether register used as dest operand can be written to */
465 if (regno == BPF_REG_FP) {
466 verbose("frame pointer is read only\n");
470 mark_reg_unknown_value(regs, regno);
475 static int bpf_size_to_bytes(int bpf_size)
477 if (bpf_size == BPF_W)
479 else if (bpf_size == BPF_H)
481 else if (bpf_size == BPF_B)
483 else if (bpf_size == BPF_DW)
489 static bool is_spillable_regtype(enum bpf_reg_type type)
492 case PTR_TO_MAP_VALUE:
493 case PTR_TO_MAP_VALUE_OR_NULL:
497 case PTR_TO_PACKET_END:
499 case CONST_PTR_TO_MAP:
506 /* check_stack_read/write functions track spill/fill of registers,
507 * stack boundary and alignment are checked in check_mem_access()
509 static int check_stack_write(struct bpf_verifier_state *state, int off,
510 int size, int value_regno)
513 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
514 * so it's aligned access and [off, off + size) are within stack limits
517 if (value_regno >= 0 &&
518 is_spillable_regtype(state->regs[value_regno].type)) {
520 /* register containing pointer is being spilled into stack */
521 if (size != BPF_REG_SIZE) {
522 verbose("invalid size of register spill\n");
526 /* save register state */
527 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
528 state->regs[value_regno];
530 for (i = 0; i < BPF_REG_SIZE; i++)
531 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
533 /* regular write of data into stack */
534 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
535 (struct bpf_reg_state) {};
537 for (i = 0; i < size; i++)
538 state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
543 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
549 slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
551 if (slot_type[0] == STACK_SPILL) {
552 if (size != BPF_REG_SIZE) {
553 verbose("invalid size of register spill\n");
556 for (i = 1; i < BPF_REG_SIZE; i++) {
557 if (slot_type[i] != STACK_SPILL) {
558 verbose("corrupted spill memory\n");
563 if (value_regno >= 0)
564 /* restore register state from stack */
565 state->regs[value_regno] =
566 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
569 for (i = 0; i < size; i++) {
570 if (slot_type[i] != STACK_MISC) {
571 verbose("invalid read from stack off %d+%d size %d\n",
576 if (value_regno >= 0)
577 /* have read misc data from the stack */
578 mark_reg_unknown_value(state->regs, value_regno);
583 /* check read/write into map element returned by bpf_map_lookup_elem() */
584 static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
587 struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
589 if (off < 0 || off + size > map->value_size) {
590 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
591 map->value_size, off, size);
597 #define MAX_PACKET_OFF 0xffff
599 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
600 const struct bpf_call_arg_meta *meta)
602 switch (env->prog->type) {
603 case BPF_PROG_TYPE_SCHED_CLS:
604 case BPF_PROG_TYPE_SCHED_ACT:
605 case BPF_PROG_TYPE_XDP:
607 return meta->pkt_access;
609 env->seen_direct_write = true;
616 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
619 struct bpf_reg_state *regs = env->cur_state.regs;
620 struct bpf_reg_state *reg = ®s[regno];
623 if (off < 0 || size <= 0 || off + size > reg->range) {
624 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
625 off, size, regno, reg->id, reg->off, reg->range);
631 /* check access to 'struct bpf_context' fields */
632 static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
633 enum bpf_access_type t, enum bpf_reg_type *reg_type)
635 /* for analyzer ctx accesses are already validated and converted */
636 if (env->analyzer_ops)
639 if (env->prog->aux->ops->is_valid_access &&
640 env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
641 /* remember the offset of last byte accessed in ctx */
642 if (env->prog->aux->max_ctx_offset < off + size)
643 env->prog->aux->max_ctx_offset = off + size;
647 verbose("invalid bpf_context access off=%d size=%d\n", off, size);
651 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
653 if (env->allow_ptr_leaks)
656 switch (env->cur_state.regs[regno].type) {
665 static int check_ptr_alignment(struct bpf_verifier_env *env,
666 struct bpf_reg_state *reg, int off, int size)
668 if (reg->type != PTR_TO_PACKET) {
669 if (off % size != 0) {
670 verbose("misaligned access off %d size %d\n",
678 switch (env->prog->type) {
679 case BPF_PROG_TYPE_SCHED_CLS:
680 case BPF_PROG_TYPE_SCHED_ACT:
681 case BPF_PROG_TYPE_XDP:
684 verbose("verifier is misconfigured\n");
688 if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
689 /* misaligned access to packet is ok on x86,arm,arm64 */
692 if (reg->id && size != 1) {
693 verbose("Unknown packet alignment. Only byte-sized access allowed\n");
697 /* skb->data is NET_IP_ALIGN-ed */
698 if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
699 verbose("misaligned packet access off %d+%d+%d size %d\n",
700 NET_IP_ALIGN, reg->off, off, size);
706 /* check whether memory at (regno + off) is accessible for t = (read | write)
707 * if t==write, value_regno is a register which value is stored into memory
708 * if t==read, value_regno is a register which will receive the value from memory
709 * if t==write && value_regno==-1, some unknown value is stored into memory
710 * if t==read && value_regno==-1, don't care what we read from memory
712 static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
713 int bpf_size, enum bpf_access_type t,
716 struct bpf_verifier_state *state = &env->cur_state;
717 struct bpf_reg_state *reg = &state->regs[regno];
720 if (reg->type == PTR_TO_STACK)
723 size = bpf_size_to_bytes(bpf_size);
727 err = check_ptr_alignment(env, reg, off, size);
731 if (reg->type == PTR_TO_MAP_VALUE) {
732 if (t == BPF_WRITE && value_regno >= 0 &&
733 is_pointer_value(env, value_regno)) {
734 verbose("R%d leaks addr into map\n", value_regno);
737 err = check_map_access(env, regno, off, size);
738 if (!err && t == BPF_READ && value_regno >= 0)
739 mark_reg_unknown_value(state->regs, value_regno);
741 } else if (reg->type == PTR_TO_CTX) {
742 enum bpf_reg_type reg_type = UNKNOWN_VALUE;
744 if (t == BPF_WRITE && value_regno >= 0 &&
745 is_pointer_value(env, value_regno)) {
746 verbose("R%d leaks addr into ctx\n", value_regno);
749 err = check_ctx_access(env, off, size, t, ®_type);
750 if (!err && t == BPF_READ && value_regno >= 0) {
751 mark_reg_unknown_value(state->regs, value_regno);
752 if (env->allow_ptr_leaks)
753 /* note that reg.[id|off|range] == 0 */
754 state->regs[value_regno].type = reg_type;
757 } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
758 if (off >= 0 || off < -MAX_BPF_STACK) {
759 verbose("invalid stack off=%d size=%d\n", off, size);
762 if (t == BPF_WRITE) {
763 if (!env->allow_ptr_leaks &&
764 state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
765 size != BPF_REG_SIZE) {
766 verbose("attempt to corrupt spilled pointer on stack\n");
769 err = check_stack_write(state, off, size, value_regno);
771 err = check_stack_read(state, off, size, value_regno);
773 } else if (state->regs[regno].type == PTR_TO_PACKET) {
774 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
775 verbose("cannot write into packet\n");
778 if (t == BPF_WRITE && value_regno >= 0 &&
779 is_pointer_value(env, value_regno)) {
780 verbose("R%d leaks addr into packet\n", value_regno);
783 err = check_packet_access(env, regno, off, size);
784 if (!err && t == BPF_READ && value_regno >= 0)
785 mark_reg_unknown_value(state->regs, value_regno);
787 verbose("R%d invalid mem access '%s'\n",
788 regno, reg_type_str[reg->type]);
792 if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
793 state->regs[value_regno].type == UNKNOWN_VALUE) {
794 /* 1 or 2 byte load zero-extends, determine the number of
795 * zero upper bits. Not doing it fo 4 byte load, since
796 * such values cannot be added to ptr_to_packet anyway.
798 state->regs[value_regno].imm = 64 - size * 8;
803 static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
805 struct bpf_reg_state *regs = env->cur_state.regs;
808 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
810 verbose("BPF_XADD uses reserved fields\n");
814 /* check src1 operand */
815 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
819 /* check src2 operand */
820 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
824 /* check whether atomic_add can read the memory */
825 err = check_mem_access(env, insn->dst_reg, insn->off,
826 BPF_SIZE(insn->code), BPF_READ, -1);
830 /* check whether atomic_add can write into the same memory */
831 return check_mem_access(env, insn->dst_reg, insn->off,
832 BPF_SIZE(insn->code), BPF_WRITE, -1);
835 /* when register 'regno' is passed into function that will read 'access_size'
836 * bytes from that pointer, make sure that it's within stack boundary
837 * and all elements of stack are initialized
839 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
840 int access_size, bool zero_size_allowed,
841 struct bpf_call_arg_meta *meta)
843 struct bpf_verifier_state *state = &env->cur_state;
844 struct bpf_reg_state *regs = state->regs;
847 if (regs[regno].type != PTR_TO_STACK) {
848 if (zero_size_allowed && access_size == 0 &&
849 regs[regno].type == CONST_IMM &&
850 regs[regno].imm == 0)
853 verbose("R%d type=%s expected=%s\n", regno,
854 reg_type_str[regs[regno].type],
855 reg_type_str[PTR_TO_STACK]);
859 off = regs[regno].imm;
860 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
862 verbose("invalid stack type R%d off=%d access_size=%d\n",
863 regno, off, access_size);
867 if (meta && meta->raw_mode) {
868 meta->access_size = access_size;
873 for (i = 0; i < access_size; i++) {
874 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
875 verbose("invalid indirect read from stack off %d+%d size %d\n",
876 off, i, access_size);
883 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
884 enum bpf_arg_type arg_type,
885 struct bpf_call_arg_meta *meta)
887 struct bpf_reg_state *regs = env->cur_state.regs, *reg = ®s[regno];
888 enum bpf_reg_type expected_type, type = reg->type;
891 if (arg_type == ARG_DONTCARE)
894 if (type == NOT_INIT) {
895 verbose("R%d !read_ok\n", regno);
899 if (arg_type == ARG_ANYTHING) {
900 if (is_pointer_value(env, regno)) {
901 verbose("R%d leaks addr into helper function\n", regno);
907 if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
908 verbose("helper access to the packet is not allowed\n");
912 if (arg_type == ARG_PTR_TO_MAP_KEY ||
913 arg_type == ARG_PTR_TO_MAP_VALUE) {
914 expected_type = PTR_TO_STACK;
915 if (type != PTR_TO_PACKET && type != expected_type)
917 } else if (arg_type == ARG_CONST_STACK_SIZE ||
918 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
919 expected_type = CONST_IMM;
920 if (type != expected_type)
922 } else if (arg_type == ARG_CONST_MAP_PTR) {
923 expected_type = CONST_PTR_TO_MAP;
924 if (type != expected_type)
926 } else if (arg_type == ARG_PTR_TO_CTX) {
927 expected_type = PTR_TO_CTX;
928 if (type != expected_type)
930 } else if (arg_type == ARG_PTR_TO_STACK ||
931 arg_type == ARG_PTR_TO_RAW_STACK) {
932 expected_type = PTR_TO_STACK;
933 /* One exception here. In case function allows for NULL to be
934 * passed in as argument, it's a CONST_IMM type. Final test
935 * happens during stack boundary checking.
937 if (type == CONST_IMM && reg->imm == 0)
938 /* final test in check_stack_boundary() */;
939 else if (type != PTR_TO_PACKET && type != expected_type)
941 meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
943 verbose("unsupported arg_type %d\n", arg_type);
947 if (arg_type == ARG_CONST_MAP_PTR) {
948 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
949 meta->map_ptr = reg->map_ptr;
950 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
951 /* bpf_map_xxx(..., map_ptr, ..., key) call:
952 * check that [key, key + map->key_size) are within
953 * stack limits and initialized
955 if (!meta->map_ptr) {
956 /* in function declaration map_ptr must come before
957 * map_key, so that it's verified and known before
958 * we have to check map_key here. Otherwise it means
959 * that kernel subsystem misconfigured verifier
961 verbose("invalid map_ptr to access map->key\n");
964 if (type == PTR_TO_PACKET)
965 err = check_packet_access(env, regno, 0,
966 meta->map_ptr->key_size);
968 err = check_stack_boundary(env, regno,
969 meta->map_ptr->key_size,
971 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
972 /* bpf_map_xxx(..., map_ptr, ..., value) call:
973 * check [value, value + map->value_size) validity
975 if (!meta->map_ptr) {
976 /* kernel subsystem misconfigured verifier */
977 verbose("invalid map_ptr to access map->value\n");
980 if (type == PTR_TO_PACKET)
981 err = check_packet_access(env, regno, 0,
982 meta->map_ptr->value_size);
984 err = check_stack_boundary(env, regno,
985 meta->map_ptr->value_size,
987 } else if (arg_type == ARG_CONST_STACK_SIZE ||
988 arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
989 bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
991 /* bpf_xxx(..., buf, len) call will access 'len' bytes
992 * from stack pointer 'buf'. Check it
993 * note: regno == len, regno - 1 == buf
996 /* kernel subsystem misconfigured verifier */
997 verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
1000 if (regs[regno - 1].type == PTR_TO_PACKET)
1001 err = check_packet_access(env, regno - 1, 0, reg->imm);
1003 err = check_stack_boundary(env, regno - 1, reg->imm,
1004 zero_size_allowed, meta);
1009 verbose("R%d type=%s expected=%s\n", regno,
1010 reg_type_str[type], reg_type_str[expected_type]);
1014 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1019 /* We need a two way check, first is from map perspective ... */
1020 switch (map->map_type) {
1021 case BPF_MAP_TYPE_PROG_ARRAY:
1022 if (func_id != BPF_FUNC_tail_call)
1025 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1026 if (func_id != BPF_FUNC_perf_event_read &&
1027 func_id != BPF_FUNC_perf_event_output)
1030 case BPF_MAP_TYPE_STACK_TRACE:
1031 if (func_id != BPF_FUNC_get_stackid)
1034 case BPF_MAP_TYPE_CGROUP_ARRAY:
1035 if (func_id != BPF_FUNC_skb_under_cgroup &&
1036 func_id != BPF_FUNC_current_task_under_cgroup)
1043 /* ... and second from the function itself. */
1045 case BPF_FUNC_tail_call:
1046 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1049 case BPF_FUNC_perf_event_read:
1050 case BPF_FUNC_perf_event_output:
1051 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1054 case BPF_FUNC_get_stackid:
1055 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1058 case BPF_FUNC_current_task_under_cgroup:
1059 case BPF_FUNC_skb_under_cgroup:
1060 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1069 verbose("cannot pass map_type %d into func %d\n",
1070 map->map_type, func_id);
1074 static int check_raw_mode(const struct bpf_func_proto *fn)
1078 if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1080 if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1082 if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1084 if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1086 if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1089 return count > 1 ? -EINVAL : 0;
1092 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1094 struct bpf_verifier_state *state = &env->cur_state;
1095 struct bpf_reg_state *regs = state->regs, *reg;
1098 for (i = 0; i < MAX_BPF_REG; i++)
1099 if (regs[i].type == PTR_TO_PACKET ||
1100 regs[i].type == PTR_TO_PACKET_END)
1101 mark_reg_unknown_value(regs, i);
1103 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1104 if (state->stack_slot_type[i] != STACK_SPILL)
1106 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1107 if (reg->type != PTR_TO_PACKET &&
1108 reg->type != PTR_TO_PACKET_END)
1110 reg->type = UNKNOWN_VALUE;
1115 static int check_call(struct bpf_verifier_env *env, int func_id)
1117 struct bpf_verifier_state *state = &env->cur_state;
1118 const struct bpf_func_proto *fn = NULL;
1119 struct bpf_reg_state *regs = state->regs;
1120 struct bpf_reg_state *reg;
1121 struct bpf_call_arg_meta meta;
1125 /* find function prototype */
1126 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1127 verbose("invalid func %d\n", func_id);
1131 if (env->prog->aux->ops->get_func_proto)
1132 fn = env->prog->aux->ops->get_func_proto(func_id);
1135 verbose("unknown func %d\n", func_id);
1139 /* eBPF programs must be GPL compatible to use GPL-ed functions */
1140 if (!env->prog->gpl_compatible && fn->gpl_only) {
1141 verbose("cannot call GPL only function from proprietary program\n");
1145 changes_data = bpf_helper_changes_skb_data(fn->func);
1147 memset(&meta, 0, sizeof(meta));
1148 meta.pkt_access = fn->pkt_access;
1150 /* We only support one arg being in raw mode at the moment, which
1151 * is sufficient for the helper functions we have right now.
1153 err = check_raw_mode(fn);
1155 verbose("kernel subsystem misconfigured func %d\n", func_id);
1160 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1163 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1166 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1169 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1172 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1176 /* Mark slots with STACK_MISC in case of raw mode, stack offset
1177 * is inferred from register state.
1179 for (i = 0; i < meta.access_size; i++) {
1180 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1185 /* reset caller saved regs */
1186 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1187 reg = regs + caller_saved[i];
1188 reg->type = NOT_INIT;
1192 /* update return register */
1193 if (fn->ret_type == RET_INTEGER) {
1194 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1195 } else if (fn->ret_type == RET_VOID) {
1196 regs[BPF_REG_0].type = NOT_INIT;
1197 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1198 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1199 /* remember map_ptr, so that check_map_access()
1200 * can check 'value_size' boundary of memory access
1201 * to map element returned from bpf_map_lookup_elem()
1203 if (meta.map_ptr == NULL) {
1204 verbose("kernel subsystem misconfigured verifier\n");
1207 regs[BPF_REG_0].map_ptr = meta.map_ptr;
1209 verbose("unknown return type %d of func %d\n",
1210 fn->ret_type, func_id);
1214 err = check_map_func_compatibility(meta.map_ptr, func_id);
1219 clear_all_pkt_pointers(env);
1223 static int check_packet_ptr_add(struct bpf_verifier_env *env,
1224 struct bpf_insn *insn)
1226 struct bpf_reg_state *regs = env->cur_state.regs;
1227 struct bpf_reg_state *dst_reg = ®s[insn->dst_reg];
1228 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
1229 struct bpf_reg_state tmp_reg;
1232 if (BPF_SRC(insn->code) == BPF_K) {
1233 /* pkt_ptr += imm */
1238 verbose("addition of negative constant to packet pointer is not allowed\n");
1241 if (imm >= MAX_PACKET_OFF ||
1242 imm + dst_reg->off >= MAX_PACKET_OFF) {
1243 verbose("constant %d is too large to add to packet pointer\n",
1247 /* a constant was added to pkt_ptr.
1248 * Remember it while keeping the same 'id'
1250 dst_reg->off += imm;
1252 if (src_reg->type == PTR_TO_PACKET) {
1253 /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1254 tmp_reg = *dst_reg; /* save r7 state */
1255 *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1256 src_reg = &tmp_reg; /* pretend it's src_reg state */
1257 /* if the checks below reject it, the copy won't matter,
1258 * since we're rejecting the whole program. If all ok,
1259 * then imm22 state will be added to r7
1260 * and r7 will be pkt(id=0,off=22,r=62) while
1261 * r6 will stay as pkt(id=0,off=0,r=62)
1265 if (src_reg->type == CONST_IMM) {
1266 /* pkt_ptr += reg where reg is known constant */
1270 /* disallow pkt_ptr += reg
1271 * if reg is not uknown_value with guaranteed zero upper bits
1272 * otherwise pkt_ptr may overflow and addition will become
1273 * subtraction which is not allowed
1275 if (src_reg->type != UNKNOWN_VALUE) {
1276 verbose("cannot add '%s' to ptr_to_packet\n",
1277 reg_type_str[src_reg->type]);
1280 if (src_reg->imm < 48) {
1281 verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1285 /* dst_reg stays as pkt_ptr type and since some positive
1286 * integer value was added to the pointer, increment its 'id'
1288 dst_reg->id = ++env->id_gen;
1290 /* something was added to pkt_ptr, set range and off to zero */
1297 static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
1299 struct bpf_reg_state *regs = env->cur_state.regs;
1300 struct bpf_reg_state *dst_reg = ®s[insn->dst_reg];
1301 u8 opcode = BPF_OP(insn->code);
1304 /* for type == UNKNOWN_VALUE:
1305 * imm > 0 -> number of zero upper bits
1306 * imm == 0 -> don't track which is the same as all bits can be non-zero
1309 if (BPF_SRC(insn->code) == BPF_X) {
1310 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
1312 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1313 dst_reg->imm && opcode == BPF_ADD) {
1315 * where both have zero upper bits. Adding them
1316 * can only result making one more bit non-zero
1317 * in the larger value.
1318 * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1319 * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1321 dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1325 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1326 dst_reg->imm && opcode == BPF_ADD) {
1328 * where dreg has zero upper bits and sreg is const.
1329 * Adding them can only result making one more bit
1330 * non-zero in the larger value.
1332 imm_log2 = __ilog2_u64((long long)src_reg->imm);
1333 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1337 /* all other cases non supported yet, just mark dst_reg */
1342 /* sign extend 32-bit imm into 64-bit to make sure that
1343 * negative values occupy bit 63. Note ilog2() would have
1344 * been incorrect, since sizeof(insn->imm) == 4
1346 imm_log2 = __ilog2_u64((long long)insn->imm);
1348 if (dst_reg->imm && opcode == BPF_LSH) {
1350 * if reg was a result of 2 byte load, then its imm == 48
1351 * which means that upper 48 bits are zero and shifting this reg
1352 * left by 4 would mean that upper 44 bits are still zero
1354 dst_reg->imm -= insn->imm;
1355 } else if (dst_reg->imm && opcode == BPF_MUL) {
1357 * if multiplying by 14 subtract 4
1358 * This is conservative calculation of upper zero bits.
1359 * It's not trying to special case insn->imm == 1 or 0 cases
1361 dst_reg->imm -= imm_log2 + 1;
1362 } else if (opcode == BPF_AND) {
1364 dst_reg->imm = 63 - imm_log2;
1365 } else if (dst_reg->imm && opcode == BPF_ADD) {
1367 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1369 } else if (opcode == BPF_RSH) {
1371 * which means that after right shift, upper bits will be zero
1372 * note that verifier already checked that
1373 * 0 <= imm < 64 for shift insn
1375 dst_reg->imm += insn->imm;
1376 if (unlikely(dst_reg->imm > 64))
1377 /* some dumb code did:
1380 * and all bits are zero now */
1383 /* all other alu ops, means that we don't know what will
1384 * happen to the value, mark it with unknown number of zero bits
1389 if (dst_reg->imm < 0) {
1390 /* all 64 bits of the register can contain non-zero bits
1391 * and such value cannot be added to ptr_to_packet, since it
1392 * may overflow, mark it as unknown to avoid further eval
1399 static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1400 struct bpf_insn *insn)
1402 struct bpf_reg_state *regs = env->cur_state.regs;
1403 struct bpf_reg_state *dst_reg = ®s[insn->dst_reg];
1404 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
1405 u8 opcode = BPF_OP(insn->code);
1407 /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1408 * Don't care about overflow or negative values, just add them
1410 if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1411 dst_reg->imm += insn->imm;
1412 else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1413 src_reg->type == CONST_IMM)
1414 dst_reg->imm += src_reg->imm;
1416 mark_reg_unknown_value(regs, insn->dst_reg);
1420 /* check validity of 32-bit and 64-bit arithmetic operations */
1421 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
1423 struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1424 u8 opcode = BPF_OP(insn->code);
1427 if (opcode == BPF_END || opcode == BPF_NEG) {
1428 if (opcode == BPF_NEG) {
1429 if (BPF_SRC(insn->code) != 0 ||
1430 insn->src_reg != BPF_REG_0 ||
1431 insn->off != 0 || insn->imm != 0) {
1432 verbose("BPF_NEG uses reserved fields\n");
1436 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1437 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1438 verbose("BPF_END uses reserved fields\n");
1443 /* check src operand */
1444 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1448 if (is_pointer_value(env, insn->dst_reg)) {
1449 verbose("R%d pointer arithmetic prohibited\n",
1454 /* check dest operand */
1455 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1459 } else if (opcode == BPF_MOV) {
1461 if (BPF_SRC(insn->code) == BPF_X) {
1462 if (insn->imm != 0 || insn->off != 0) {
1463 verbose("BPF_MOV uses reserved fields\n");
1467 /* check src operand */
1468 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1472 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1473 verbose("BPF_MOV uses reserved fields\n");
1478 /* check dest operand */
1479 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1483 if (BPF_SRC(insn->code) == BPF_X) {
1484 if (BPF_CLASS(insn->code) == BPF_ALU64) {
1486 * copy register state to dest reg
1488 regs[insn->dst_reg] = regs[insn->src_reg];
1490 if (is_pointer_value(env, insn->src_reg)) {
1491 verbose("R%d partial copy of pointer\n",
1495 regs[insn->dst_reg].type = UNKNOWN_VALUE;
1496 regs[insn->dst_reg].map_ptr = NULL;
1500 * remember the value we stored into this reg
1502 regs[insn->dst_reg].type = CONST_IMM;
1503 regs[insn->dst_reg].imm = insn->imm;
1506 } else if (opcode > BPF_END) {
1507 verbose("invalid BPF_ALU opcode %x\n", opcode);
1510 } else { /* all other ALU ops: and, sub, xor, add, ... */
1512 if (BPF_SRC(insn->code) == BPF_X) {
1513 if (insn->imm != 0 || insn->off != 0) {
1514 verbose("BPF_ALU uses reserved fields\n");
1517 /* check src1 operand */
1518 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1522 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1523 verbose("BPF_ALU uses reserved fields\n");
1528 /* check src2 operand */
1529 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1533 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1534 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1535 verbose("div by zero\n");
1539 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1540 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1541 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1543 if (insn->imm < 0 || insn->imm >= size) {
1544 verbose("invalid shift %d\n", insn->imm);
1549 /* check dest operand */
1550 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1554 dst_reg = ®s[insn->dst_reg];
1556 /* pattern match 'bpf_add Rx, imm' instruction */
1557 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1558 dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1559 dst_reg->type = PTR_TO_STACK;
1560 dst_reg->imm = insn->imm;
1562 } else if (opcode == BPF_ADD &&
1563 BPF_CLASS(insn->code) == BPF_ALU64 &&
1564 (dst_reg->type == PTR_TO_PACKET ||
1565 (BPF_SRC(insn->code) == BPF_X &&
1566 regs[insn->src_reg].type == PTR_TO_PACKET))) {
1567 /* ptr_to_packet += K|X */
1568 return check_packet_ptr_add(env, insn);
1569 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1570 dst_reg->type == UNKNOWN_VALUE &&
1571 env->allow_ptr_leaks) {
1572 /* unknown += K|X */
1573 return evaluate_reg_alu(env, insn);
1574 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1575 dst_reg->type == CONST_IMM &&
1576 env->allow_ptr_leaks) {
1577 /* reg_imm += K|X */
1578 return evaluate_reg_imm_alu(env, insn);
1579 } else if (is_pointer_value(env, insn->dst_reg)) {
1580 verbose("R%d pointer arithmetic prohibited\n",
1583 } else if (BPF_SRC(insn->code) == BPF_X &&
1584 is_pointer_value(env, insn->src_reg)) {
1585 verbose("R%d pointer arithmetic prohibited\n",
1590 /* mark dest operand */
1591 mark_reg_unknown_value(regs, insn->dst_reg);
1597 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
1598 struct bpf_reg_state *dst_reg)
1600 struct bpf_reg_state *regs = state->regs, *reg;
1603 /* LLVM can generate two kind of checks:
1609 * if (r2 > pkt_end) goto <handle exception>
1613 * r2 == dst_reg, pkt_end == src_reg
1614 * r2=pkt(id=n,off=8,r=0)
1615 * r3=pkt(id=n,off=0,r=0)
1621 * if (pkt_end >= r2) goto <access okay>
1622 * <handle exception>
1625 * pkt_end == dst_reg, r2 == src_reg
1626 * r2=pkt(id=n,off=8,r=0)
1627 * r3=pkt(id=n,off=0,r=0)
1629 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1630 * so that range of bytes [r3, r3 + 8) is safe to access.
1633 for (i = 0; i < MAX_BPF_REG; i++)
1634 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1635 regs[i].range = dst_reg->off;
1637 for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1638 if (state->stack_slot_type[i] != STACK_SPILL)
1640 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1641 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1642 reg->range = dst_reg->off;
1646 static int check_cond_jmp_op(struct bpf_verifier_env *env,
1647 struct bpf_insn *insn, int *insn_idx)
1649 struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
1650 struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
1651 u8 opcode = BPF_OP(insn->code);
1654 if (opcode > BPF_EXIT) {
1655 verbose("invalid BPF_JMP opcode %x\n", opcode);
1659 if (BPF_SRC(insn->code) == BPF_X) {
1660 if (insn->imm != 0) {
1661 verbose("BPF_JMP uses reserved fields\n");
1665 /* check src1 operand */
1666 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1670 if (is_pointer_value(env, insn->src_reg)) {
1671 verbose("R%d pointer comparison prohibited\n",
1676 if (insn->src_reg != BPF_REG_0) {
1677 verbose("BPF_JMP uses reserved fields\n");
1682 /* check src2 operand */
1683 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1687 dst_reg = ®s[insn->dst_reg];
1689 /* detect if R == 0 where R was initialized to zero earlier */
1690 if (BPF_SRC(insn->code) == BPF_K &&
1691 (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1692 dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
1693 if (opcode == BPF_JEQ) {
1694 /* if (imm == imm) goto pc+off;
1695 * only follow the goto, ignore fall-through
1697 *insn_idx += insn->off;
1700 /* if (imm != imm) goto pc+off;
1701 * only follow fall-through branch, since
1702 * that's where the program will go
1708 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1712 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
1713 if (BPF_SRC(insn->code) == BPF_K &&
1714 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1715 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1716 if (opcode == BPF_JEQ) {
1717 /* next fallthrough insn can access memory via
1720 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1721 /* branch targer cannot access it, since reg == 0 */
1722 mark_reg_unknown_value(other_branch->regs,
1725 other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1726 mark_reg_unknown_value(regs, insn->dst_reg);
1728 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
1729 dst_reg->type == PTR_TO_PACKET &&
1730 regs[insn->src_reg].type == PTR_TO_PACKET_END) {
1731 find_good_pkt_pointers(this_branch, dst_reg);
1732 } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
1733 dst_reg->type == PTR_TO_PACKET_END &&
1734 regs[insn->src_reg].type == PTR_TO_PACKET) {
1735 find_good_pkt_pointers(other_branch, ®s[insn->src_reg]);
1736 } else if (is_pointer_value(env, insn->dst_reg)) {
1737 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
1741 print_verifier_state(this_branch);
1745 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
1746 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
1748 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
1750 return (struct bpf_map *) (unsigned long) imm64;
1753 /* verify BPF_LD_IMM64 instruction */
1754 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
1756 struct bpf_reg_state *regs = env->cur_state.regs;
1759 if (BPF_SIZE(insn->code) != BPF_DW) {
1760 verbose("invalid BPF_LD_IMM insn\n");
1763 if (insn->off != 0) {
1764 verbose("BPF_LD_IMM64 uses reserved fields\n");
1768 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1772 if (insn->src_reg == 0) {
1773 /* generic move 64-bit immediate into a register,
1774 * only analyzer needs to collect the ld_imm value.
1776 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
1778 if (!env->analyzer_ops)
1781 regs[insn->dst_reg].type = CONST_IMM;
1782 regs[insn->dst_reg].imm = imm;
1786 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1787 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
1789 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
1790 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
1794 static bool may_access_skb(enum bpf_prog_type type)
1797 case BPF_PROG_TYPE_SOCKET_FILTER:
1798 case BPF_PROG_TYPE_SCHED_CLS:
1799 case BPF_PROG_TYPE_SCHED_ACT:
1806 /* verify safety of LD_ABS|LD_IND instructions:
1807 * - they can only appear in the programs where ctx == skb
1808 * - since they are wrappers of function calls, they scratch R1-R5 registers,
1809 * preserve R6-R9, and store return value into R0
1812 * ctx == skb == R6 == CTX
1815 * SRC == any register
1816 * IMM == 32-bit immediate
1819 * R0 - 8/16/32-bit skb data converted to cpu endianness
1821 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
1823 struct bpf_reg_state *regs = env->cur_state.regs;
1824 u8 mode = BPF_MODE(insn->code);
1825 struct bpf_reg_state *reg;
1828 if (!may_access_skb(env->prog->type)) {
1829 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
1833 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
1834 BPF_SIZE(insn->code) == BPF_DW ||
1835 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1836 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
1840 /* check whether implicit source operand (register R6) is readable */
1841 err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
1845 if (regs[BPF_REG_6].type != PTR_TO_CTX) {
1846 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1850 if (mode == BPF_IND) {
1851 /* check explicit source operand */
1852 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1857 /* reset caller saved regs to unreadable */
1858 for (i = 0; i < CALLER_SAVED_REGS; i++) {
1859 reg = regs + caller_saved[i];
1860 reg->type = NOT_INIT;
1864 /* mark destination R0 register as readable, since it contains
1865 * the value fetched from the packet
1867 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1871 /* non-recursive DFS pseudo code
1872 * 1 procedure DFS-iterative(G,v):
1873 * 2 label v as discovered
1874 * 3 let S be a stack
1876 * 5 while S is not empty
1878 * 7 if t is what we're looking for:
1880 * 9 for all edges e in G.adjacentEdges(t) do
1881 * 10 if edge e is already labelled
1882 * 11 continue with the next edge
1883 * 12 w <- G.adjacentVertex(t,e)
1884 * 13 if vertex w is not discovered and not explored
1885 * 14 label e as tree-edge
1886 * 15 label w as discovered
1889 * 18 else if vertex w is discovered
1890 * 19 label e as back-edge
1892 * 21 // vertex w is explored
1893 * 22 label e as forward- or cross-edge
1894 * 23 label t as explored
1899 * 0x11 - discovered and fall-through edge labelled
1900 * 0x12 - discovered and fall-through and branch edges labelled
1911 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
1913 static int *insn_stack; /* stack of insns to process */
1914 static int cur_stack; /* current stack index */
1915 static int *insn_state;
1917 /* t, w, e - match pseudo-code above:
1918 * t - index of current instruction
1919 * w - next instruction
1922 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
1924 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
1927 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
1930 if (w < 0 || w >= env->prog->len) {
1931 verbose("jump out of range from insn %d to %d\n", t, w);
1936 /* mark branch target for state pruning */
1937 env->explored_states[w] = STATE_LIST_MARK;
1939 if (insn_state[w] == 0) {
1941 insn_state[t] = DISCOVERED | e;
1942 insn_state[w] = DISCOVERED;
1943 if (cur_stack >= env->prog->len)
1945 insn_stack[cur_stack++] = w;
1947 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
1948 verbose("back-edge from insn %d to %d\n", t, w);
1950 } else if (insn_state[w] == EXPLORED) {
1951 /* forward- or cross-edge */
1952 insn_state[t] = DISCOVERED | e;
1954 verbose("insn state internal bug\n");
1960 /* non-recursive depth-first-search to detect loops in BPF program
1961 * loop == back-edge in directed graph
1963 static int check_cfg(struct bpf_verifier_env *env)
1965 struct bpf_insn *insns = env->prog->insnsi;
1966 int insn_cnt = env->prog->len;
1970 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1974 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1980 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
1981 insn_stack[0] = 0; /* 0 is the first instruction */
1987 t = insn_stack[cur_stack - 1];
1989 if (BPF_CLASS(insns[t].code) == BPF_JMP) {
1990 u8 opcode = BPF_OP(insns[t].code);
1992 if (opcode == BPF_EXIT) {
1994 } else if (opcode == BPF_CALL) {
1995 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2000 if (t + 1 < insn_cnt)
2001 env->explored_states[t + 1] = STATE_LIST_MARK;
2002 } else if (opcode == BPF_JA) {
2003 if (BPF_SRC(insns[t].code) != BPF_K) {
2007 /* unconditional jump with single edge */
2008 ret = push_insn(t, t + insns[t].off + 1,
2014 /* tell verifier to check for equivalent states
2015 * after every call and jump
2017 if (t + 1 < insn_cnt)
2018 env->explored_states[t + 1] = STATE_LIST_MARK;
2020 /* conditional jump with two edges */
2021 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2027 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2034 /* all other non-branch instructions with single
2037 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2045 insn_state[t] = EXPLORED;
2046 if (cur_stack-- <= 0) {
2047 verbose("pop stack internal bug\n");
2054 for (i = 0; i < insn_cnt; i++) {
2055 if (insn_state[i] != EXPLORED) {
2056 verbose("unreachable insn %d\n", i);
2061 ret = 0; /* cfg looks good */
2069 /* the following conditions reduce the number of explored insns
2070 * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2072 static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
2073 struct bpf_reg_state *cur)
2075 if (old->id != cur->id)
2078 /* old ptr_to_packet is more conservative, since it allows smaller
2080 * old(off=0,r=10) is equal to cur(off=0,r=20), because
2081 * old(off=0,r=10) means that with range=10 the verifier proceeded
2082 * further and found no issues with the program. Now we're in the same
2083 * spot with cur(off=0,r=20), so we're safe too, since anything further
2084 * will only be looking at most 10 bytes after this pointer.
2086 if (old->off == cur->off && old->range < cur->range)
2089 /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2090 * since both cannot be used for packet access and safe(old)
2091 * pointer has smaller off that could be used for further
2092 * 'if (ptr > data_end)' check
2094 * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2095 * that we cannot access the packet.
2096 * The safe range is:
2097 * [ptr, ptr + range - off)
2098 * so whenever off >=range, it means no safe bytes from this pointer.
2099 * When comparing old->off <= cur->off, it means that older code
2100 * went with smaller offset and that offset was later
2101 * used to figure out the safe range after 'if (ptr > data_end)' check
2102 * Say, 'old' state was explored like:
2103 * ... R3(off=0, r=0)
2105 * ... now R4(off=20,r=0) <-- here
2106 * if (R4 > data_end)
2107 * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2108 * ... the code further went all the way to bpf_exit.
2109 * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2110 * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2111 * goes further, such cur_R4 will give larger safe packet range after
2112 * 'if (R4 > data_end)' and all further insn were already good with r=20,
2113 * so they will be good with r=30 and we can prune the search.
2115 if (old->off <= cur->off &&
2116 old->off >= old->range && cur->off >= cur->range)
2122 /* compare two verifier states
2124 * all states stored in state_list are known to be valid, since
2125 * verifier reached 'bpf_exit' instruction through them
2127 * this function is called when verifier exploring different branches of
2128 * execution popped from the state stack. If it sees an old state that has
2129 * more strict register state and more strict stack state then this execution
2130 * branch doesn't need to be explored further, since verifier already
2131 * concluded that more strict state leads to valid finish.
2133 * Therefore two states are equivalent if register state is more conservative
2134 * and explored stack state is more conservative than the current one.
2137 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2138 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2140 * In other words if current stack state (one being explored) has more
2141 * valid slots than old one that already passed validation, it means
2142 * the verifier can stop exploring and conclude that current state is valid too
2144 * Similarly with registers. If explored state has register type as invalid
2145 * whereas register type in current state is meaningful, it means that
2146 * the current state will reach 'bpf_exit' instruction safely
2148 static bool states_equal(struct bpf_verifier_state *old,
2149 struct bpf_verifier_state *cur)
2151 struct bpf_reg_state *rold, *rcur;
2154 for (i = 0; i < MAX_BPF_REG; i++) {
2155 rold = &old->regs[i];
2156 rcur = &cur->regs[i];
2158 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2161 if (rold->type == NOT_INIT ||
2162 (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2165 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2166 compare_ptrs_to_packet(rold, rcur))
2172 for (i = 0; i < MAX_BPF_STACK; i++) {
2173 if (old->stack_slot_type[i] == STACK_INVALID)
2175 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2176 /* Ex: old explored (safe) state has STACK_SPILL in
2177 * this stack slot, but current has has STACK_MISC ->
2178 * this verifier states are not equivalent,
2179 * return false to continue verification of this path
2182 if (i % BPF_REG_SIZE)
2184 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2185 &cur->spilled_regs[i / BPF_REG_SIZE],
2186 sizeof(old->spilled_regs[0])))
2187 /* when explored and current stack slot types are
2188 * the same, check that stored pointers types
2189 * are the same as well.
2190 * Ex: explored safe path could have stored
2191 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
2192 * but current path has stored:
2193 * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
2194 * such verifier states are not equivalent.
2195 * return false to continue verification of this path
2204 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
2206 struct bpf_verifier_state_list *new_sl;
2207 struct bpf_verifier_state_list *sl;
2209 sl = env->explored_states[insn_idx];
2211 /* this 'insn_idx' instruction wasn't marked, so we will not
2212 * be doing state search here
2216 while (sl != STATE_LIST_MARK) {
2217 if (states_equal(&sl->state, &env->cur_state))
2218 /* reached equivalent register/stack state,
2225 /* there were no equivalent states, remember current one.
2226 * technically the current state is not proven to be safe yet,
2227 * but it will either reach bpf_exit (which means it's safe) or
2228 * it will be rejected. Since there are no loops, we won't be
2229 * seeing this 'insn_idx' instruction again on the way to bpf_exit
2231 new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
2235 /* add new state to the head of linked list */
2236 memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2237 new_sl->next = env->explored_states[insn_idx];
2238 env->explored_states[insn_idx] = new_sl;
2242 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2243 int insn_idx, int prev_insn_idx)
2245 if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2248 return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2251 static int do_check(struct bpf_verifier_env *env)
2253 struct bpf_verifier_state *state = &env->cur_state;
2254 struct bpf_insn *insns = env->prog->insnsi;
2255 struct bpf_reg_state *regs = state->regs;
2256 int insn_cnt = env->prog->len;
2257 int insn_idx, prev_insn_idx = 0;
2258 int insn_processed = 0;
2259 bool do_print_state = false;
2261 init_reg_state(regs);
2264 struct bpf_insn *insn;
2268 if (insn_idx >= insn_cnt) {
2269 verbose("invalid insn idx %d insn_cnt %d\n",
2270 insn_idx, insn_cnt);
2274 insn = &insns[insn_idx];
2275 class = BPF_CLASS(insn->code);
2277 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2278 verbose("BPF program is too large. Proccessed %d insn\n",
2283 err = is_state_visited(env, insn_idx);
2287 /* found equivalent state, can prune the search */
2290 verbose("\nfrom %d to %d: safe\n",
2291 prev_insn_idx, insn_idx);
2293 verbose("%d: safe\n", insn_idx);
2295 goto process_bpf_exit;
2298 if (log_level && do_print_state) {
2299 verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2300 print_verifier_state(&env->cur_state);
2301 do_print_state = false;
2305 verbose("%d: ", insn_idx);
2306 print_bpf_insn(insn);
2309 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2313 if (class == BPF_ALU || class == BPF_ALU64) {
2314 err = check_alu_op(env, insn);
2318 } else if (class == BPF_LDX) {
2319 enum bpf_reg_type *prev_src_type, src_reg_type;
2321 /* check for reserved fields is already done */
2323 /* check src operand */
2324 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2328 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2332 src_reg_type = regs[insn->src_reg].type;
2334 /* check that memory (src_reg + off) is readable,
2335 * the state of dst_reg will be updated by this func
2337 err = check_mem_access(env, insn->src_reg, insn->off,
2338 BPF_SIZE(insn->code), BPF_READ,
2343 if (BPF_SIZE(insn->code) != BPF_W &&
2344 BPF_SIZE(insn->code) != BPF_DW) {
2349 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
2351 if (*prev_src_type == NOT_INIT) {
2353 * dst_reg = *(u32 *)(src_reg + off)
2354 * save type to validate intersecting paths
2356 *prev_src_type = src_reg_type;
2358 } else if (src_reg_type != *prev_src_type &&
2359 (src_reg_type == PTR_TO_CTX ||
2360 *prev_src_type == PTR_TO_CTX)) {
2361 /* ABuser program is trying to use the same insn
2362 * dst_reg = *(u32*) (src_reg + off)
2363 * with different pointer types:
2364 * src_reg == ctx in one branch and
2365 * src_reg == stack|map in some other branch.
2368 verbose("same insn cannot be used with different pointers\n");
2372 } else if (class == BPF_STX) {
2373 enum bpf_reg_type *prev_dst_type, dst_reg_type;
2375 if (BPF_MODE(insn->code) == BPF_XADD) {
2376 err = check_xadd(env, insn);
2383 /* check src1 operand */
2384 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2387 /* check src2 operand */
2388 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2392 dst_reg_type = regs[insn->dst_reg].type;
2394 /* check that memory (dst_reg + off) is writeable */
2395 err = check_mem_access(env, insn->dst_reg, insn->off,
2396 BPF_SIZE(insn->code), BPF_WRITE,
2401 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
2403 if (*prev_dst_type == NOT_INIT) {
2404 *prev_dst_type = dst_reg_type;
2405 } else if (dst_reg_type != *prev_dst_type &&
2406 (dst_reg_type == PTR_TO_CTX ||
2407 *prev_dst_type == PTR_TO_CTX)) {
2408 verbose("same insn cannot be used with different pointers\n");
2412 } else if (class == BPF_ST) {
2413 if (BPF_MODE(insn->code) != BPF_MEM ||
2414 insn->src_reg != BPF_REG_0) {
2415 verbose("BPF_ST uses reserved fields\n");
2418 /* check src operand */
2419 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2423 /* check that memory (dst_reg + off) is writeable */
2424 err = check_mem_access(env, insn->dst_reg, insn->off,
2425 BPF_SIZE(insn->code), BPF_WRITE,
2430 } else if (class == BPF_JMP) {
2431 u8 opcode = BPF_OP(insn->code);
2433 if (opcode == BPF_CALL) {
2434 if (BPF_SRC(insn->code) != BPF_K ||
2436 insn->src_reg != BPF_REG_0 ||
2437 insn->dst_reg != BPF_REG_0) {
2438 verbose("BPF_CALL uses reserved fields\n");
2442 err = check_call(env, insn->imm);
2446 } else if (opcode == BPF_JA) {
2447 if (BPF_SRC(insn->code) != BPF_K ||
2449 insn->src_reg != BPF_REG_0 ||
2450 insn->dst_reg != BPF_REG_0) {
2451 verbose("BPF_JA uses reserved fields\n");
2455 insn_idx += insn->off + 1;
2458 } else if (opcode == BPF_EXIT) {
2459 if (BPF_SRC(insn->code) != BPF_K ||
2461 insn->src_reg != BPF_REG_0 ||
2462 insn->dst_reg != BPF_REG_0) {
2463 verbose("BPF_EXIT uses reserved fields\n");
2467 /* eBPF calling convetion is such that R0 is used
2468 * to return the value from eBPF program.
2469 * Make sure that it's readable at this time
2470 * of bpf_exit, which means that program wrote
2471 * something into it earlier
2473 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2477 if (is_pointer_value(env, BPF_REG_0)) {
2478 verbose("R0 leaks addr as return value\n");
2483 insn_idx = pop_stack(env, &prev_insn_idx);
2487 do_print_state = true;
2491 err = check_cond_jmp_op(env, insn, &insn_idx);
2495 } else if (class == BPF_LD) {
2496 u8 mode = BPF_MODE(insn->code);
2498 if (mode == BPF_ABS || mode == BPF_IND) {
2499 err = check_ld_abs(env, insn);
2503 } else if (mode == BPF_IMM) {
2504 err = check_ld_imm(env, insn);
2510 verbose("invalid BPF_LD mode\n");
2514 verbose("unknown insn class %d\n", class);
2521 verbose("processed %d insns\n", insn_processed);
2525 static int check_map_prog_compatibility(struct bpf_map *map,
2526 struct bpf_prog *prog)
2529 if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
2530 (map->map_type == BPF_MAP_TYPE_HASH ||
2531 map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
2532 (map->map_flags & BPF_F_NO_PREALLOC)) {
2533 verbose("perf_event programs can only use preallocated hash map\n");
2539 /* look for pseudo eBPF instructions that access map FDs and
2540 * replace them with actual map pointers
2542 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
2544 struct bpf_insn *insn = env->prog->insnsi;
2545 int insn_cnt = env->prog->len;
2548 for (i = 0; i < insn_cnt; i++, insn++) {
2549 if (BPF_CLASS(insn->code) == BPF_LDX &&
2550 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
2551 verbose("BPF_LDX uses reserved fields\n");
2555 if (BPF_CLASS(insn->code) == BPF_STX &&
2556 ((BPF_MODE(insn->code) != BPF_MEM &&
2557 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2558 verbose("BPF_STX uses reserved fields\n");
2562 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2563 struct bpf_map *map;
2566 if (i == insn_cnt - 1 || insn[1].code != 0 ||
2567 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2569 verbose("invalid bpf_ld_imm64 insn\n");
2573 if (insn->src_reg == 0)
2574 /* valid generic load 64-bit imm */
2577 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2578 verbose("unrecognized bpf_ld_imm64 insn\n");
2582 f = fdget(insn->imm);
2583 map = __bpf_map_get(f);
2585 verbose("fd %d is not pointing to valid bpf_map\n",
2587 return PTR_ERR(map);
2590 err = check_map_prog_compatibility(map, env->prog);
2596 /* store map pointer inside BPF_LD_IMM64 instruction */
2597 insn[0].imm = (u32) (unsigned long) map;
2598 insn[1].imm = ((u64) (unsigned long) map) >> 32;
2600 /* check whether we recorded this map already */
2601 for (j = 0; j < env->used_map_cnt; j++)
2602 if (env->used_maps[j] == map) {
2607 if (env->used_map_cnt >= MAX_USED_MAPS) {
2612 /* hold the map. If the program is rejected by verifier,
2613 * the map will be released by release_maps() or it
2614 * will be used by the valid program until it's unloaded
2615 * and all maps are released in free_bpf_prog_info()
2617 map = bpf_map_inc(map, false);
2620 return PTR_ERR(map);
2622 env->used_maps[env->used_map_cnt++] = map;
2631 /* now all pseudo BPF_LD_IMM64 instructions load valid
2632 * 'struct bpf_map *' into a register instead of user map_fd.
2633 * These pointers will be used later by verifier to validate map access.
2638 /* drop refcnt of maps used by the rejected program */
2639 static void release_maps(struct bpf_verifier_env *env)
2643 for (i = 0; i < env->used_map_cnt; i++)
2644 bpf_map_put(env->used_maps[i]);
2647 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2648 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
2650 struct bpf_insn *insn = env->prog->insnsi;
2651 int insn_cnt = env->prog->len;
2654 for (i = 0; i < insn_cnt; i++, insn++)
2655 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2659 /* convert load instructions that access fields of 'struct __sk_buff'
2660 * into sequence of instructions that access fields of 'struct sk_buff'
2662 static int convert_ctx_accesses(struct bpf_verifier_env *env)
2664 const struct bpf_verifier_ops *ops = env->prog->aux->ops;
2665 const int insn_cnt = env->prog->len;
2666 struct bpf_insn insn_buf[16], *insn;
2667 struct bpf_prog *new_prog;
2668 enum bpf_access_type type;
2669 int i, cnt, delta = 0;
2671 if (ops->gen_prologue) {
2672 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
2674 if (cnt >= ARRAY_SIZE(insn_buf)) {
2675 verbose("bpf verifier is misconfigured\n");
2678 new_prog = bpf_patch_insn_single(env->prog, 0,
2682 env->prog = new_prog;
2687 if (!ops->convert_ctx_access)
2690 insn = env->prog->insnsi + delta;
2692 for (i = 0; i < insn_cnt; i++, insn++) {
2693 if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2694 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
2696 else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
2697 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
2702 if (env->insn_aux_data[i].ptr_type != PTR_TO_CTX)
2705 cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
2706 insn->off, insn_buf, env->prog);
2707 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
2708 verbose("bpf verifier is misconfigured\n");
2712 new_prog = bpf_patch_insn_single(env->prog, i + delta, insn_buf,
2719 /* keep walking new program and skip insns we just inserted */
2720 env->prog = new_prog;
2721 insn = new_prog->insnsi + i + delta;
2727 static void free_states(struct bpf_verifier_env *env)
2729 struct bpf_verifier_state_list *sl, *sln;
2732 if (!env->explored_states)
2735 for (i = 0; i < env->prog->len; i++) {
2736 sl = env->explored_states[i];
2739 while (sl != STATE_LIST_MARK) {
2746 kfree(env->explored_states);
2749 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
2751 char __user *log_ubuf = NULL;
2752 struct bpf_verifier_env *env;
2755 if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
2758 /* 'struct bpf_verifier_env' can be global, but since it's not small,
2759 * allocate/free it every time bpf_check() is called
2761 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
2765 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
2768 if (!env->insn_aux_data)
2772 /* grab the mutex to protect few globals used by verifier */
2773 mutex_lock(&bpf_verifier_lock);
2775 if (attr->log_level || attr->log_buf || attr->log_size) {
2776 /* user requested verbose verifier output
2777 * and supplied buffer to store the verification trace
2779 log_level = attr->log_level;
2780 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
2781 log_size = attr->log_size;
2785 /* log_* values have to be sane */
2786 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
2787 log_level == 0 || log_ubuf == NULL)
2791 log_buf = vmalloc(log_size);
2798 ret = replace_map_fd_with_map_ptr(env);
2800 goto skip_full_check;
2802 env->explored_states = kcalloc(env->prog->len,
2803 sizeof(struct bpf_verifier_state_list *),
2806 if (!env->explored_states)
2807 goto skip_full_check;
2809 ret = check_cfg(env);
2811 goto skip_full_check;
2813 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2815 ret = do_check(env);
2818 while (pop_stack(env, NULL) >= 0);
2822 /* program is valid, convert *(u32*)(ctx + off) accesses */
2823 ret = convert_ctx_accesses(env);
2825 if (log_level && log_len >= log_size - 1) {
2826 BUG_ON(log_len >= log_size);
2827 /* verifier log exceeded user supplied buffer */
2829 /* fall through to return what was recorded */
2832 /* copy verifier log back to user space including trailing zero */
2833 if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
2838 if (ret == 0 && env->used_map_cnt) {
2839 /* if program passed verifier, update used_maps in bpf_prog_info */
2840 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
2841 sizeof(env->used_maps[0]),
2844 if (!env->prog->aux->used_maps) {
2849 memcpy(env->prog->aux->used_maps, env->used_maps,
2850 sizeof(env->used_maps[0]) * env->used_map_cnt);
2851 env->prog->aux->used_map_cnt = env->used_map_cnt;
2853 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
2854 * bpf_ld_imm64 instructions
2856 convert_pseudo_ld_imm64(env);
2862 if (!env->prog->aux->used_maps)
2863 /* if we didn't copy map pointers into bpf_prog_info, release
2864 * them now. Otherwise free_bpf_prog_info() will release them.
2869 mutex_unlock(&bpf_verifier_lock);
2870 vfree(env->insn_aux_data);
2876 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
2879 struct bpf_verifier_env *env;
2882 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
2886 env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
2889 if (!env->insn_aux_data)
2892 env->analyzer_ops = ops;
2893 env->analyzer_priv = priv;
2895 /* grab the mutex to protect few globals used by verifier */
2896 mutex_lock(&bpf_verifier_lock);
2900 env->explored_states = kcalloc(env->prog->len,
2901 sizeof(struct bpf_verifier_state_list *),
2904 if (!env->explored_states)
2905 goto skip_full_check;
2907 ret = check_cfg(env);
2909 goto skip_full_check;
2911 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2913 ret = do_check(env);
2916 while (pop_stack(env, NULL) >= 0);
2919 mutex_unlock(&bpf_verifier_lock);
2920 vfree(env->insn_aux_data);
2925 EXPORT_SYMBOL_GPL(bpf_analyzer);