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