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