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