ee86a77dc40b6eaa2662bd63d5b5c2a1622391ba
[cascardo/linux.git] / kernel / bpf / verifier.c
1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
2  * Copyright (c) 2016 Facebook
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of version 2 of the GNU General Public
6  * License as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11  * General Public License for more details.
12  */
13 #include <linux/kernel.h>
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/bpf.h>
17 #include <linux/bpf_verifier.h>
18 #include <linux/filter.h>
19 #include <net/netlink.h>
20 #include <linux/file.h>
21 #include <linux/vmalloc.h>
22
23 /* bpf_check() is a static code analyzer that walks eBPF program
24  * instruction by instruction and updates register/stack state.
25  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
26  *
27  * The first pass is depth-first-search to check that the program is a DAG.
28  * It rejects the following programs:
29  * - larger than BPF_MAXINSNS insns
30  * - if loop is present (detected via back-edge)
31  * - unreachable insns exist (shouldn't be a forest. program = one function)
32  * - out of bounds or malformed jumps
33  * The second pass is all possible path descent from the 1st insn.
34  * Since it's analyzing all pathes through the program, the length of the
35  * analysis is limited to 32k insn, which may be hit even if total number of
36  * insn is less then 4K, but there are too many branches that change stack/regs.
37  * Number of 'branches to be analyzed' is limited to 1k
38  *
39  * On entry to each instruction, each register has a type, and the instruction
40  * changes the types of the registers depending on instruction semantics.
41  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
42  * copied to R1.
43  *
44  * All registers are 64-bit.
45  * R0 - return register
46  * R1-R5 argument passing registers
47  * R6-R9 callee saved registers
48  * R10 - frame pointer read-only
49  *
50  * At the start of BPF program the register R1 contains a pointer to bpf_context
51  * and has type PTR_TO_CTX.
52  *
53  * Verifier tracks arithmetic operations on pointers in case:
54  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
55  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
56  * 1st insn copies R10 (which has FRAME_PTR) type into R1
57  * and 2nd arithmetic instruction is pattern matched to recognize
58  * that it wants to construct a pointer to some element within stack.
59  * So after 2nd insn, the register R1 has type PTR_TO_STACK
60  * (and -20 constant is saved for further stack bounds checking).
61  * Meaning that this reg is a pointer to stack plus known immediate constant.
62  *
63  * Most of the time the registers have UNKNOWN_VALUE type, which
64  * means the register has some value, but it's not a valid pointer.
65  * (like pointer plus pointer becomes UNKNOWN_VALUE type)
66  *
67  * When verifier sees load or store instructions the type of base register
68  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
69  * types recognized by check_mem_access() function.
70  *
71  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
72  * and the range of [ptr, ptr + map's value_size) is accessible.
73  *
74  * registers used to pass values to function calls are checked against
75  * function argument constraints.
76  *
77  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
78  * It means that the register type passed to this function must be
79  * PTR_TO_STACK and it will be used inside the function as
80  * 'pointer to map element key'
81  *
82  * For example the argument constraints for bpf_map_lookup_elem():
83  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
84  *   .arg1_type = ARG_CONST_MAP_PTR,
85  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
86  *
87  * ret_type says that this function returns 'pointer to map elem value or null'
88  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
89  * 2nd argument should be a pointer to stack, which will be used inside
90  * the helper function as a pointer to map element key.
91  *
92  * On the kernel side the helper function looks like:
93  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
94  * {
95  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
96  *    void *key = (void *) (unsigned long) r2;
97  *    void *value;
98  *
99  *    here kernel can access 'key' and 'map' pointers safely, knowing that
100  *    [key, key + map->key_size) bytes are valid and were initialized on
101  *    the stack of eBPF program.
102  * }
103  *
104  * Corresponding eBPF program may look like:
105  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
106  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
107  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
108  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
109  * here verifier looks at prototype of map_lookup_elem() and sees:
110  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
111  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
112  *
113  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
114  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
115  * and were initialized prior to this call.
116  * If it's ok, then verifier allows this BPF_CALL insn and looks at
117  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
118  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
119  * returns ether pointer to map value or NULL.
120  *
121  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
122  * insn, the register holding that pointer in the true branch changes state to
123  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
124  * branch. See check_cond_jmp_op().
125  *
126  * After the call R0 is set to return type of the function and registers R1-R5
127  * are set to NOT_INIT to indicate that they are no longer readable.
128  */
129
130 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
131 struct bpf_verifier_stack_elem {
132         /* verifer state is 'st'
133          * before processing instruction 'insn_idx'
134          * and after processing instruction 'prev_insn_idx'
135          */
136         struct bpf_verifier_state st;
137         int insn_idx;
138         int prev_insn_idx;
139         struct bpf_verifier_stack_elem *next;
140 };
141
142 #define BPF_COMPLEXITY_LIMIT_INSNS      65536
143 #define BPF_COMPLEXITY_LIMIT_STACK      1024
144
145 struct bpf_call_arg_meta {
146         struct bpf_map *map_ptr;
147         bool raw_mode;
148         bool pkt_access;
149         int regno;
150         int access_size;
151 };
152
153 /* verbose verifier prints what it's seeing
154  * bpf_check() is called under lock, so no race to access these global vars
155  */
156 static u32 log_level, log_size, log_len;
157 static char *log_buf;
158
159 static DEFINE_MUTEX(bpf_verifier_lock);
160
161 /* log_level controls verbosity level of eBPF verifier.
162  * verbose() is used to dump the verification trace to the log, so the user
163  * can figure out what's wrong with the program
164  */
165 static __printf(1, 2) void verbose(const char *fmt, ...)
166 {
167         va_list args;
168
169         if (log_level == 0 || log_len >= log_size - 1)
170                 return;
171
172         va_start(args, fmt);
173         log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
174         va_end(args);
175 }
176
177 /* string representation of 'enum bpf_reg_type' */
178 static const char * const reg_type_str[] = {
179         [NOT_INIT]              = "?",
180         [UNKNOWN_VALUE]         = "inv",
181         [PTR_TO_CTX]            = "ctx",
182         [CONST_PTR_TO_MAP]      = "map_ptr",
183         [PTR_TO_MAP_VALUE]      = "map_value",
184         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
185         [FRAME_PTR]             = "fp",
186         [PTR_TO_STACK]          = "fp",
187         [CONST_IMM]             = "imm",
188         [PTR_TO_PACKET]         = "pkt",
189         [PTR_TO_PACKET_END]     = "pkt_end",
190 };
191
192 static void print_verifier_state(struct bpf_verifier_state *state)
193 {
194         struct bpf_reg_state *reg;
195         enum bpf_reg_type t;
196         int i;
197
198         for (i = 0; i < MAX_BPF_REG; i++) {
199                 reg = &state->regs[i];
200                 t = reg->type;
201                 if (t == NOT_INIT)
202                         continue;
203                 verbose(" R%d=%s", i, reg_type_str[t]);
204                 if (t == CONST_IMM || t == PTR_TO_STACK)
205                         verbose("%lld", reg->imm);
206                 else if (t == PTR_TO_PACKET)
207                         verbose("(id=%d,off=%d,r=%d)",
208                                 reg->id, reg->off, reg->range);
209                 else if (t == UNKNOWN_VALUE && reg->imm)
210                         verbose("%lld", reg->imm);
211                 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
212                          t == PTR_TO_MAP_VALUE_OR_NULL)
213                         verbose("(ks=%d,vs=%d)",
214                                 reg->map_ptr->key_size,
215                                 reg->map_ptr->value_size);
216         }
217         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
218                 if (state->stack_slot_type[i] == STACK_SPILL)
219                         verbose(" fp%d=%s", -MAX_BPF_STACK + i,
220                                 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
221         }
222         verbose("\n");
223 }
224
225 static const char *const bpf_class_string[] = {
226         [BPF_LD]    = "ld",
227         [BPF_LDX]   = "ldx",
228         [BPF_ST]    = "st",
229         [BPF_STX]   = "stx",
230         [BPF_ALU]   = "alu",
231         [BPF_JMP]   = "jmp",
232         [BPF_RET]   = "BUG",
233         [BPF_ALU64] = "alu64",
234 };
235
236 static const char *const bpf_alu_string[16] = {
237         [BPF_ADD >> 4]  = "+=",
238         [BPF_SUB >> 4]  = "-=",
239         [BPF_MUL >> 4]  = "*=",
240         [BPF_DIV >> 4]  = "/=",
241         [BPF_OR  >> 4]  = "|=",
242         [BPF_AND >> 4]  = "&=",
243         [BPF_LSH >> 4]  = "<<=",
244         [BPF_RSH >> 4]  = ">>=",
245         [BPF_NEG >> 4]  = "neg",
246         [BPF_MOD >> 4]  = "%=",
247         [BPF_XOR >> 4]  = "^=",
248         [BPF_MOV >> 4]  = "=",
249         [BPF_ARSH >> 4] = "s>>=",
250         [BPF_END >> 4]  = "endian",
251 };
252
253 static const char *const bpf_ldst_string[] = {
254         [BPF_W >> 3]  = "u32",
255         [BPF_H >> 3]  = "u16",
256         [BPF_B >> 3]  = "u8",
257         [BPF_DW >> 3] = "u64",
258 };
259
260 static const char *const bpf_jmp_string[16] = {
261         [BPF_JA >> 4]   = "jmp",
262         [BPF_JEQ >> 4]  = "==",
263         [BPF_JGT >> 4]  = ">",
264         [BPF_JGE >> 4]  = ">=",
265         [BPF_JSET >> 4] = "&",
266         [BPF_JNE >> 4]  = "!=",
267         [BPF_JSGT >> 4] = "s>",
268         [BPF_JSGE >> 4] = "s>=",
269         [BPF_CALL >> 4] = "call",
270         [BPF_EXIT >> 4] = "exit",
271 };
272
273 static void print_bpf_insn(struct bpf_insn *insn)
274 {
275         u8 class = BPF_CLASS(insn->code);
276
277         if (class == BPF_ALU || class == BPF_ALU64) {
278                 if (BPF_SRC(insn->code) == BPF_X)
279                         verbose("(%02x) %sr%d %s %sr%d\n",
280                                 insn->code, class == BPF_ALU ? "(u32) " : "",
281                                 insn->dst_reg,
282                                 bpf_alu_string[BPF_OP(insn->code) >> 4],
283                                 class == BPF_ALU ? "(u32) " : "",
284                                 insn->src_reg);
285                 else
286                         verbose("(%02x) %sr%d %s %s%d\n",
287                                 insn->code, class == BPF_ALU ? "(u32) " : "",
288                                 insn->dst_reg,
289                                 bpf_alu_string[BPF_OP(insn->code) >> 4],
290                                 class == BPF_ALU ? "(u32) " : "",
291                                 insn->imm);
292         } else if (class == BPF_STX) {
293                 if (BPF_MODE(insn->code) == BPF_MEM)
294                         verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
295                                 insn->code,
296                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
297                                 insn->dst_reg,
298                                 insn->off, insn->src_reg);
299                 else if (BPF_MODE(insn->code) == BPF_XADD)
300                         verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
301                                 insn->code,
302                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
303                                 insn->dst_reg, insn->off,
304                                 insn->src_reg);
305                 else
306                         verbose("BUG_%02x\n", insn->code);
307         } else if (class == BPF_ST) {
308                 if (BPF_MODE(insn->code) != BPF_MEM) {
309                         verbose("BUG_st_%02x\n", insn->code);
310                         return;
311                 }
312                 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
313                         insn->code,
314                         bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
315                         insn->dst_reg,
316                         insn->off, insn->imm);
317         } else if (class == BPF_LDX) {
318                 if (BPF_MODE(insn->code) != BPF_MEM) {
319                         verbose("BUG_ldx_%02x\n", insn->code);
320                         return;
321                 }
322                 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
323                         insn->code, insn->dst_reg,
324                         bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
325                         insn->src_reg, insn->off);
326         } else if (class == BPF_LD) {
327                 if (BPF_MODE(insn->code) == BPF_ABS) {
328                         verbose("(%02x) r0 = *(%s *)skb[%d]\n",
329                                 insn->code,
330                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
331                                 insn->imm);
332                 } else if (BPF_MODE(insn->code) == BPF_IND) {
333                         verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
334                                 insn->code,
335                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
336                                 insn->src_reg, insn->imm);
337                 } else if (BPF_MODE(insn->code) == BPF_IMM) {
338                         verbose("(%02x) r%d = 0x%x\n",
339                                 insn->code, insn->dst_reg, insn->imm);
340                 } else {
341                         verbose("BUG_ld_%02x\n", insn->code);
342                         return;
343                 }
344         } else if (class == BPF_JMP) {
345                 u8 opcode = BPF_OP(insn->code);
346
347                 if (opcode == BPF_CALL) {
348                         verbose("(%02x) call %d\n", insn->code, insn->imm);
349                 } else if (insn->code == (BPF_JMP | BPF_JA)) {
350                         verbose("(%02x) goto pc%+d\n",
351                                 insn->code, insn->off);
352                 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
353                         verbose("(%02x) exit\n", insn->code);
354                 } else if (BPF_SRC(insn->code) == BPF_X) {
355                         verbose("(%02x) if r%d %s r%d goto pc%+d\n",
356                                 insn->code, insn->dst_reg,
357                                 bpf_jmp_string[BPF_OP(insn->code) >> 4],
358                                 insn->src_reg, insn->off);
359                 } else {
360                         verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
361                                 insn->code, insn->dst_reg,
362                                 bpf_jmp_string[BPF_OP(insn->code) >> 4],
363                                 insn->imm, insn->off);
364                 }
365         } else {
366                 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
367         }
368 }
369
370 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
371 {
372         struct bpf_verifier_stack_elem *elem;
373         int insn_idx;
374
375         if (env->head == NULL)
376                 return -1;
377
378         memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
379         insn_idx = env->head->insn_idx;
380         if (prev_insn_idx)
381                 *prev_insn_idx = env->head->prev_insn_idx;
382         elem = env->head->next;
383         kfree(env->head);
384         env->head = elem;
385         env->stack_size--;
386         return insn_idx;
387 }
388
389 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
390                                              int insn_idx, int prev_insn_idx)
391 {
392         struct bpf_verifier_stack_elem *elem;
393
394         elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
395         if (!elem)
396                 goto err;
397
398         memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
399         elem->insn_idx = insn_idx;
400         elem->prev_insn_idx = prev_insn_idx;
401         elem->next = env->head;
402         env->head = elem;
403         env->stack_size++;
404         if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
405                 verbose("BPF program is too complex\n");
406                 goto err;
407         }
408         return &elem->st;
409 err:
410         /* pop all elements and return */
411         while (pop_stack(env, NULL) >= 0);
412         return NULL;
413 }
414
415 #define CALLER_SAVED_REGS 6
416 static const int caller_saved[CALLER_SAVED_REGS] = {
417         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
418 };
419
420 static void init_reg_state(struct bpf_reg_state *regs)
421 {
422         int i;
423
424         for (i = 0; i < MAX_BPF_REG; i++) {
425                 regs[i].type = NOT_INIT;
426                 regs[i].imm = 0;
427         }
428
429         /* frame pointer */
430         regs[BPF_REG_FP].type = FRAME_PTR;
431
432         /* 1st arg to a function */
433         regs[BPF_REG_1].type = PTR_TO_CTX;
434 }
435
436 static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
437 {
438         BUG_ON(regno >= MAX_BPF_REG);
439         regs[regno].type = UNKNOWN_VALUE;
440         regs[regno].imm = 0;
441 }
442
443 enum reg_arg_type {
444         SRC_OP,         /* register is used as source operand */
445         DST_OP,         /* register is used as destination operand */
446         DST_OP_NO_MARK  /* same as above, check only, don't mark */
447 };
448
449 static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
450                          enum reg_arg_type t)
451 {
452         if (regno >= MAX_BPF_REG) {
453                 verbose("R%d is invalid\n", regno);
454                 return -EINVAL;
455         }
456
457         if (t == SRC_OP) {
458                 /* check whether register used as source operand can be read */
459                 if (regs[regno].type == NOT_INIT) {
460                         verbose("R%d !read_ok\n", regno);
461                         return -EACCES;
462                 }
463         } else {
464                 /* check whether register used as dest operand can be written to */
465                 if (regno == BPF_REG_FP) {
466                         verbose("frame pointer is read only\n");
467                         return -EACCES;
468                 }
469                 if (t == DST_OP)
470                         mark_reg_unknown_value(regs, regno);
471         }
472         return 0;
473 }
474
475 static int bpf_size_to_bytes(int bpf_size)
476 {
477         if (bpf_size == BPF_W)
478                 return 4;
479         else if (bpf_size == BPF_H)
480                 return 2;
481         else if (bpf_size == BPF_B)
482                 return 1;
483         else if (bpf_size == BPF_DW)
484                 return 8;
485         else
486                 return -EINVAL;
487 }
488
489 static bool is_spillable_regtype(enum bpf_reg_type type)
490 {
491         switch (type) {
492         case PTR_TO_MAP_VALUE:
493         case PTR_TO_MAP_VALUE_OR_NULL:
494         case PTR_TO_STACK:
495         case PTR_TO_CTX:
496         case PTR_TO_PACKET:
497         case PTR_TO_PACKET_END:
498         case FRAME_PTR:
499         case CONST_PTR_TO_MAP:
500                 return true;
501         default:
502                 return false;
503         }
504 }
505
506 /* check_stack_read/write functions track spill/fill of registers,
507  * stack boundary and alignment are checked in check_mem_access()
508  */
509 static int check_stack_write(struct bpf_verifier_state *state, int off,
510                              int size, int value_regno)
511 {
512         int i;
513         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
514          * so it's aligned access and [off, off + size) are within stack limits
515          */
516
517         if (value_regno >= 0 &&
518             is_spillable_regtype(state->regs[value_regno].type)) {
519
520                 /* register containing pointer is being spilled into stack */
521                 if (size != BPF_REG_SIZE) {
522                         verbose("invalid size of register spill\n");
523                         return -EACCES;
524                 }
525
526                 /* save register state */
527                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
528                         state->regs[value_regno];
529
530                 for (i = 0; i < BPF_REG_SIZE; i++)
531                         state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
532         } else {
533                 /* regular write of data into stack */
534                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
535                         (struct bpf_reg_state) {};
536
537                 for (i = 0; i < size; i++)
538                         state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
539         }
540         return 0;
541 }
542
543 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
544                             int value_regno)
545 {
546         u8 *slot_type;
547         int i;
548
549         slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
550
551         if (slot_type[0] == STACK_SPILL) {
552                 if (size != BPF_REG_SIZE) {
553                         verbose("invalid size of register spill\n");
554                         return -EACCES;
555                 }
556                 for (i = 1; i < BPF_REG_SIZE; i++) {
557                         if (slot_type[i] != STACK_SPILL) {
558                                 verbose("corrupted spill memory\n");
559                                 return -EACCES;
560                         }
561                 }
562
563                 if (value_regno >= 0)
564                         /* restore register state from stack */
565                         state->regs[value_regno] =
566                                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
567                 return 0;
568         } else {
569                 for (i = 0; i < size; i++) {
570                         if (slot_type[i] != STACK_MISC) {
571                                 verbose("invalid read from stack off %d+%d size %d\n",
572                                         off, i, size);
573                                 return -EACCES;
574                         }
575                 }
576                 if (value_regno >= 0)
577                         /* have read misc data from the stack */
578                         mark_reg_unknown_value(state->regs, value_regno);
579                 return 0;
580         }
581 }
582
583 /* check read/write into map element returned by bpf_map_lookup_elem() */
584 static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
585                             int size)
586 {
587         struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
588
589         if (off < 0 || off + size > map->value_size) {
590                 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
591                         map->value_size, off, size);
592                 return -EACCES;
593         }
594         return 0;
595 }
596
597 #define MAX_PACKET_OFF 0xffff
598
599 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
600                                        const struct bpf_call_arg_meta *meta)
601 {
602         switch (env->prog->type) {
603         case BPF_PROG_TYPE_SCHED_CLS:
604         case BPF_PROG_TYPE_SCHED_ACT:
605         case BPF_PROG_TYPE_XDP:
606                 if (meta)
607                         return meta->pkt_access;
608
609                 env->seen_direct_write = true;
610                 return true;
611         default:
612                 return false;
613         }
614 }
615
616 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
617                                int size)
618 {
619         struct bpf_reg_state *regs = env->cur_state.regs;
620         struct bpf_reg_state *reg = &regs[regno];
621
622         off += reg->off;
623         if (off < 0 || size <= 0 || off + size > reg->range) {
624                 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
625                         off, size, regno, reg->id, reg->off, reg->range);
626                 return -EACCES;
627         }
628         return 0;
629 }
630
631 /* check access to 'struct bpf_context' fields */
632 static int check_ctx_access(struct bpf_verifier_env *env, int off, int size,
633                             enum bpf_access_type t, enum bpf_reg_type *reg_type)
634 {
635         /* for analyzer ctx accesses are already validated and converted */
636         if (env->analyzer_ops)
637                 return 0;
638
639         if (env->prog->aux->ops->is_valid_access &&
640             env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) {
641                 /* remember the offset of last byte accessed in ctx */
642                 if (env->prog->aux->max_ctx_offset < off + size)
643                         env->prog->aux->max_ctx_offset = off + size;
644                 return 0;
645         }
646
647         verbose("invalid bpf_context access off=%d size=%d\n", off, size);
648         return -EACCES;
649 }
650
651 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
652 {
653         if (env->allow_ptr_leaks)
654                 return false;
655
656         switch (env->cur_state.regs[regno].type) {
657         case UNKNOWN_VALUE:
658         case CONST_IMM:
659                 return false;
660         default:
661                 return true;
662         }
663 }
664
665 static int check_ptr_alignment(struct bpf_verifier_env *env,
666                                struct bpf_reg_state *reg, int off, int size)
667 {
668         if (reg->type != PTR_TO_PACKET) {
669                 if (off % size != 0) {
670                         verbose("misaligned access off %d size %d\n",
671                                 off, size);
672                         return -EACCES;
673                 } else {
674                         return 0;
675                 }
676         }
677
678         switch (env->prog->type) {
679         case BPF_PROG_TYPE_SCHED_CLS:
680         case BPF_PROG_TYPE_SCHED_ACT:
681         case BPF_PROG_TYPE_XDP:
682                 break;
683         default:
684                 verbose("verifier is misconfigured\n");
685                 return -EACCES;
686         }
687
688         if (IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
689                 /* misaligned access to packet is ok on x86,arm,arm64 */
690                 return 0;
691
692         if (reg->id && size != 1) {
693                 verbose("Unknown packet alignment. Only byte-sized access allowed\n");
694                 return -EACCES;
695         }
696
697         /* skb->data is NET_IP_ALIGN-ed */
698         if ((NET_IP_ALIGN + reg->off + off) % size != 0) {
699                 verbose("misaligned packet access off %d+%d+%d size %d\n",
700                         NET_IP_ALIGN, reg->off, off, size);
701                 return -EACCES;
702         }
703         return 0;
704 }
705
706 /* check whether memory at (regno + off) is accessible for t = (read | write)
707  * if t==write, value_regno is a register which value is stored into memory
708  * if t==read, value_regno is a register which will receive the value from memory
709  * if t==write && value_regno==-1, some unknown value is stored into memory
710  * if t==read && value_regno==-1, don't care what we read from memory
711  */
712 static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off,
713                             int bpf_size, enum bpf_access_type t,
714                             int value_regno)
715 {
716         struct bpf_verifier_state *state = &env->cur_state;
717         struct bpf_reg_state *reg = &state->regs[regno];
718         int size, err = 0;
719
720         if (reg->type == PTR_TO_STACK)
721                 off += reg->imm;
722
723         size = bpf_size_to_bytes(bpf_size);
724         if (size < 0)
725                 return size;
726
727         err = check_ptr_alignment(env, reg, off, size);
728         if (err)
729                 return err;
730
731         if (reg->type == PTR_TO_MAP_VALUE) {
732                 if (t == BPF_WRITE && value_regno >= 0 &&
733                     is_pointer_value(env, value_regno)) {
734                         verbose("R%d leaks addr into map\n", value_regno);
735                         return -EACCES;
736                 }
737                 err = check_map_access(env, regno, off, size);
738                 if (!err && t == BPF_READ && value_regno >= 0)
739                         mark_reg_unknown_value(state->regs, value_regno);
740
741         } else if (reg->type == PTR_TO_CTX) {
742                 enum bpf_reg_type reg_type = UNKNOWN_VALUE;
743
744                 if (t == BPF_WRITE && value_regno >= 0 &&
745                     is_pointer_value(env, value_regno)) {
746                         verbose("R%d leaks addr into ctx\n", value_regno);
747                         return -EACCES;
748                 }
749                 err = check_ctx_access(env, off, size, t, &reg_type);
750                 if (!err && t == BPF_READ && value_regno >= 0) {
751                         mark_reg_unknown_value(state->regs, value_regno);
752                         if (env->allow_ptr_leaks)
753                                 /* note that reg.[id|off|range] == 0 */
754                                 state->regs[value_regno].type = reg_type;
755                 }
756
757         } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
758                 if (off >= 0 || off < -MAX_BPF_STACK) {
759                         verbose("invalid stack off=%d size=%d\n", off, size);
760                         return -EACCES;
761                 }
762                 if (t == BPF_WRITE) {
763                         if (!env->allow_ptr_leaks &&
764                             state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
765                             size != BPF_REG_SIZE) {
766                                 verbose("attempt to corrupt spilled pointer on stack\n");
767                                 return -EACCES;
768                         }
769                         err = check_stack_write(state, off, size, value_regno);
770                 } else {
771                         err = check_stack_read(state, off, size, value_regno);
772                 }
773         } else if (state->regs[regno].type == PTR_TO_PACKET) {
774                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL)) {
775                         verbose("cannot write into packet\n");
776                         return -EACCES;
777                 }
778                 if (t == BPF_WRITE && value_regno >= 0 &&
779                     is_pointer_value(env, value_regno)) {
780                         verbose("R%d leaks addr into packet\n", value_regno);
781                         return -EACCES;
782                 }
783                 err = check_packet_access(env, regno, off, size);
784                 if (!err && t == BPF_READ && value_regno >= 0)
785                         mark_reg_unknown_value(state->regs, value_regno);
786         } else {
787                 verbose("R%d invalid mem access '%s'\n",
788                         regno, reg_type_str[reg->type]);
789                 return -EACCES;
790         }
791
792         if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
793             state->regs[value_regno].type == UNKNOWN_VALUE) {
794                 /* 1 or 2 byte load zero-extends, determine the number of
795                  * zero upper bits. Not doing it fo 4 byte load, since
796                  * such values cannot be added to ptr_to_packet anyway.
797                  */
798                 state->regs[value_regno].imm = 64 - size * 8;
799         }
800         return err;
801 }
802
803 static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn)
804 {
805         struct bpf_reg_state *regs = env->cur_state.regs;
806         int err;
807
808         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
809             insn->imm != 0) {
810                 verbose("BPF_XADD uses reserved fields\n");
811                 return -EINVAL;
812         }
813
814         /* check src1 operand */
815         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
816         if (err)
817                 return err;
818
819         /* check src2 operand */
820         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
821         if (err)
822                 return err;
823
824         /* check whether atomic_add can read the memory */
825         err = check_mem_access(env, insn->dst_reg, insn->off,
826                                BPF_SIZE(insn->code), BPF_READ, -1);
827         if (err)
828                 return err;
829
830         /* check whether atomic_add can write into the same memory */
831         return check_mem_access(env, insn->dst_reg, insn->off,
832                                 BPF_SIZE(insn->code), BPF_WRITE, -1);
833 }
834
835 /* when register 'regno' is passed into function that will read 'access_size'
836  * bytes from that pointer, make sure that it's within stack boundary
837  * and all elements of stack are initialized
838  */
839 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
840                                 int access_size, bool zero_size_allowed,
841                                 struct bpf_call_arg_meta *meta)
842 {
843         struct bpf_verifier_state *state = &env->cur_state;
844         struct bpf_reg_state *regs = state->regs;
845         int off, i;
846
847         if (regs[regno].type != PTR_TO_STACK) {
848                 if (zero_size_allowed && access_size == 0 &&
849                     regs[regno].type == CONST_IMM &&
850                     regs[regno].imm  == 0)
851                         return 0;
852
853                 verbose("R%d type=%s expected=%s\n", regno,
854                         reg_type_str[regs[regno].type],
855                         reg_type_str[PTR_TO_STACK]);
856                 return -EACCES;
857         }
858
859         off = regs[regno].imm;
860         if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
861             access_size <= 0) {
862                 verbose("invalid stack type R%d off=%d access_size=%d\n",
863                         regno, off, access_size);
864                 return -EACCES;
865         }
866
867         if (meta && meta->raw_mode) {
868                 meta->access_size = access_size;
869                 meta->regno = regno;
870                 return 0;
871         }
872
873         for (i = 0; i < access_size; i++) {
874                 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
875                         verbose("invalid indirect read from stack off %d+%d size %d\n",
876                                 off, i, access_size);
877                         return -EACCES;
878                 }
879         }
880         return 0;
881 }
882
883 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
884                           enum bpf_arg_type arg_type,
885                           struct bpf_call_arg_meta *meta)
886 {
887         struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
888         enum bpf_reg_type expected_type, type = reg->type;
889         int err = 0;
890
891         if (arg_type == ARG_DONTCARE)
892                 return 0;
893
894         if (type == NOT_INIT) {
895                 verbose("R%d !read_ok\n", regno);
896                 return -EACCES;
897         }
898
899         if (arg_type == ARG_ANYTHING) {
900                 if (is_pointer_value(env, regno)) {
901                         verbose("R%d leaks addr into helper function\n", regno);
902                         return -EACCES;
903                 }
904                 return 0;
905         }
906
907         if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta)) {
908                 verbose("helper access to the packet is not allowed\n");
909                 return -EACCES;
910         }
911
912         if (arg_type == ARG_PTR_TO_MAP_KEY ||
913             arg_type == ARG_PTR_TO_MAP_VALUE) {
914                 expected_type = PTR_TO_STACK;
915                 if (type != PTR_TO_PACKET && type != expected_type)
916                         goto err_type;
917         } else if (arg_type == ARG_CONST_STACK_SIZE ||
918                    arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
919                 expected_type = CONST_IMM;
920                 if (type != expected_type)
921                         goto err_type;
922         } else if (arg_type == ARG_CONST_MAP_PTR) {
923                 expected_type = CONST_PTR_TO_MAP;
924                 if (type != expected_type)
925                         goto err_type;
926         } else if (arg_type == ARG_PTR_TO_CTX) {
927                 expected_type = PTR_TO_CTX;
928                 if (type != expected_type)
929                         goto err_type;
930         } else if (arg_type == ARG_PTR_TO_STACK ||
931                    arg_type == ARG_PTR_TO_RAW_STACK) {
932                 expected_type = PTR_TO_STACK;
933                 /* One exception here. In case function allows for NULL to be
934                  * passed in as argument, it's a CONST_IMM type. Final test
935                  * happens during stack boundary checking.
936                  */
937                 if (type == CONST_IMM && reg->imm == 0)
938                         /* final test in check_stack_boundary() */;
939                 else if (type != PTR_TO_PACKET && type != expected_type)
940                         goto err_type;
941                 meta->raw_mode = arg_type == ARG_PTR_TO_RAW_STACK;
942         } else {
943                 verbose("unsupported arg_type %d\n", arg_type);
944                 return -EFAULT;
945         }
946
947         if (arg_type == ARG_CONST_MAP_PTR) {
948                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
949                 meta->map_ptr = reg->map_ptr;
950         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
951                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
952                  * check that [key, key + map->key_size) are within
953                  * stack limits and initialized
954                  */
955                 if (!meta->map_ptr) {
956                         /* in function declaration map_ptr must come before
957                          * map_key, so that it's verified and known before
958                          * we have to check map_key here. Otherwise it means
959                          * that kernel subsystem misconfigured verifier
960                          */
961                         verbose("invalid map_ptr to access map->key\n");
962                         return -EACCES;
963                 }
964                 if (type == PTR_TO_PACKET)
965                         err = check_packet_access(env, regno, 0,
966                                                   meta->map_ptr->key_size);
967                 else
968                         err = check_stack_boundary(env, regno,
969                                                    meta->map_ptr->key_size,
970                                                    false, NULL);
971         } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
972                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
973                  * check [value, value + map->value_size) validity
974                  */
975                 if (!meta->map_ptr) {
976                         /* kernel subsystem misconfigured verifier */
977                         verbose("invalid map_ptr to access map->value\n");
978                         return -EACCES;
979                 }
980                 if (type == PTR_TO_PACKET)
981                         err = check_packet_access(env, regno, 0,
982                                                   meta->map_ptr->value_size);
983                 else
984                         err = check_stack_boundary(env, regno,
985                                                    meta->map_ptr->value_size,
986                                                    false, NULL);
987         } else if (arg_type == ARG_CONST_STACK_SIZE ||
988                    arg_type == ARG_CONST_STACK_SIZE_OR_ZERO) {
989                 bool zero_size_allowed = (arg_type == ARG_CONST_STACK_SIZE_OR_ZERO);
990
991                 /* bpf_xxx(..., buf, len) call will access 'len' bytes
992                  * from stack pointer 'buf'. Check it
993                  * note: regno == len, regno - 1 == buf
994                  */
995                 if (regno == 0) {
996                         /* kernel subsystem misconfigured verifier */
997                         verbose("ARG_CONST_STACK_SIZE cannot be first argument\n");
998                         return -EACCES;
999                 }
1000                 if (regs[regno - 1].type == PTR_TO_PACKET)
1001                         err = check_packet_access(env, regno - 1, 0, reg->imm);
1002                 else
1003                         err = check_stack_boundary(env, regno - 1, reg->imm,
1004                                                    zero_size_allowed, meta);
1005         }
1006
1007         return err;
1008 err_type:
1009         verbose("R%d type=%s expected=%s\n", regno,
1010                 reg_type_str[type], reg_type_str[expected_type]);
1011         return -EACCES;
1012 }
1013
1014 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1015 {
1016         if (!map)
1017                 return 0;
1018
1019         /* We need a two way check, first is from map perspective ... */
1020         switch (map->map_type) {
1021         case BPF_MAP_TYPE_PROG_ARRAY:
1022                 if (func_id != BPF_FUNC_tail_call)
1023                         goto error;
1024                 break;
1025         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1026                 if (func_id != BPF_FUNC_perf_event_read &&
1027                     func_id != BPF_FUNC_perf_event_output)
1028                         goto error;
1029                 break;
1030         case BPF_MAP_TYPE_STACK_TRACE:
1031                 if (func_id != BPF_FUNC_get_stackid)
1032                         goto error;
1033                 break;
1034         case BPF_MAP_TYPE_CGROUP_ARRAY:
1035                 if (func_id != BPF_FUNC_skb_under_cgroup &&
1036                     func_id != BPF_FUNC_current_task_under_cgroup)
1037                         goto error;
1038                 break;
1039         default:
1040                 break;
1041         }
1042
1043         /* ... and second from the function itself. */
1044         switch (func_id) {
1045         case BPF_FUNC_tail_call:
1046                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1047                         goto error;
1048                 break;
1049         case BPF_FUNC_perf_event_read:
1050         case BPF_FUNC_perf_event_output:
1051                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1052                         goto error;
1053                 break;
1054         case BPF_FUNC_get_stackid:
1055                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1056                         goto error;
1057                 break;
1058         case BPF_FUNC_current_task_under_cgroup:
1059         case BPF_FUNC_skb_under_cgroup:
1060                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1061                         goto error;
1062                 break;
1063         default:
1064                 break;
1065         }
1066
1067         return 0;
1068 error:
1069         verbose("cannot pass map_type %d into func %d\n",
1070                 map->map_type, func_id);
1071         return -EINVAL;
1072 }
1073
1074 static int check_raw_mode(const struct bpf_func_proto *fn)
1075 {
1076         int count = 0;
1077
1078         if (fn->arg1_type == ARG_PTR_TO_RAW_STACK)
1079                 count++;
1080         if (fn->arg2_type == ARG_PTR_TO_RAW_STACK)
1081                 count++;
1082         if (fn->arg3_type == ARG_PTR_TO_RAW_STACK)
1083                 count++;
1084         if (fn->arg4_type == ARG_PTR_TO_RAW_STACK)
1085                 count++;
1086         if (fn->arg5_type == ARG_PTR_TO_RAW_STACK)
1087                 count++;
1088
1089         return count > 1 ? -EINVAL : 0;
1090 }
1091
1092 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1093 {
1094         struct bpf_verifier_state *state = &env->cur_state;
1095         struct bpf_reg_state *regs = state->regs, *reg;
1096         int i;
1097
1098         for (i = 0; i < MAX_BPF_REG; i++)
1099                 if (regs[i].type == PTR_TO_PACKET ||
1100                     regs[i].type == PTR_TO_PACKET_END)
1101                         mark_reg_unknown_value(regs, i);
1102
1103         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1104                 if (state->stack_slot_type[i] != STACK_SPILL)
1105                         continue;
1106                 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1107                 if (reg->type != PTR_TO_PACKET &&
1108                     reg->type != PTR_TO_PACKET_END)
1109                         continue;
1110                 reg->type = UNKNOWN_VALUE;
1111                 reg->imm = 0;
1112         }
1113 }
1114
1115 static int check_call(struct bpf_verifier_env *env, int func_id)
1116 {
1117         struct bpf_verifier_state *state = &env->cur_state;
1118         const struct bpf_func_proto *fn = NULL;
1119         struct bpf_reg_state *regs = state->regs;
1120         struct bpf_reg_state *reg;
1121         struct bpf_call_arg_meta meta;
1122         bool changes_data;
1123         int i, err;
1124
1125         /* find function prototype */
1126         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1127                 verbose("invalid func %d\n", func_id);
1128                 return -EINVAL;
1129         }
1130
1131         if (env->prog->aux->ops->get_func_proto)
1132                 fn = env->prog->aux->ops->get_func_proto(func_id);
1133
1134         if (!fn) {
1135                 verbose("unknown func %d\n", func_id);
1136                 return -EINVAL;
1137         }
1138
1139         /* eBPF programs must be GPL compatible to use GPL-ed functions */
1140         if (!env->prog->gpl_compatible && fn->gpl_only) {
1141                 verbose("cannot call GPL only function from proprietary program\n");
1142                 return -EINVAL;
1143         }
1144
1145         changes_data = bpf_helper_changes_skb_data(fn->func);
1146
1147         memset(&meta, 0, sizeof(meta));
1148         meta.pkt_access = fn->pkt_access;
1149
1150         /* We only support one arg being in raw mode at the moment, which
1151          * is sufficient for the helper functions we have right now.
1152          */
1153         err = check_raw_mode(fn);
1154         if (err) {
1155                 verbose("kernel subsystem misconfigured func %d\n", func_id);
1156                 return err;
1157         }
1158
1159         /* check args */
1160         err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1161         if (err)
1162                 return err;
1163         err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1164         if (err)
1165                 return err;
1166         err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1167         if (err)
1168                 return err;
1169         err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1170         if (err)
1171                 return err;
1172         err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1173         if (err)
1174                 return err;
1175
1176         /* Mark slots with STACK_MISC in case of raw mode, stack offset
1177          * is inferred from register state.
1178          */
1179         for (i = 0; i < meta.access_size; i++) {
1180                 err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1);
1181                 if (err)
1182                         return err;
1183         }
1184
1185         /* reset caller saved regs */
1186         for (i = 0; i < CALLER_SAVED_REGS; i++) {
1187                 reg = regs + caller_saved[i];
1188                 reg->type = NOT_INIT;
1189                 reg->imm = 0;
1190         }
1191
1192         /* update return register */
1193         if (fn->ret_type == RET_INTEGER) {
1194                 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1195         } else if (fn->ret_type == RET_VOID) {
1196                 regs[BPF_REG_0].type = NOT_INIT;
1197         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1198                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1199                 /* remember map_ptr, so that check_map_access()
1200                  * can check 'value_size' boundary of memory access
1201                  * to map element returned from bpf_map_lookup_elem()
1202                  */
1203                 if (meta.map_ptr == NULL) {
1204                         verbose("kernel subsystem misconfigured verifier\n");
1205                         return -EINVAL;
1206                 }
1207                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
1208         } else {
1209                 verbose("unknown return type %d of func %d\n",
1210                         fn->ret_type, func_id);
1211                 return -EINVAL;
1212         }
1213
1214         err = check_map_func_compatibility(meta.map_ptr, func_id);
1215         if (err)
1216                 return err;
1217
1218         if (changes_data)
1219                 clear_all_pkt_pointers(env);
1220         return 0;
1221 }
1222
1223 static int check_packet_ptr_add(struct bpf_verifier_env *env,
1224                                 struct bpf_insn *insn)
1225 {
1226         struct bpf_reg_state *regs = env->cur_state.regs;
1227         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1228         struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1229         struct bpf_reg_state tmp_reg;
1230         s32 imm;
1231
1232         if (BPF_SRC(insn->code) == BPF_K) {
1233                 /* pkt_ptr += imm */
1234                 imm = insn->imm;
1235
1236 add_imm:
1237                 if (imm <= 0) {
1238                         verbose("addition of negative constant to packet pointer is not allowed\n");
1239                         return -EACCES;
1240                 }
1241                 if (imm >= MAX_PACKET_OFF ||
1242                     imm + dst_reg->off >= MAX_PACKET_OFF) {
1243                         verbose("constant %d is too large to add to packet pointer\n",
1244                                 imm);
1245                         return -EACCES;
1246                 }
1247                 /* a constant was added to pkt_ptr.
1248                  * Remember it while keeping the same 'id'
1249                  */
1250                 dst_reg->off += imm;
1251         } else {
1252                 if (src_reg->type == PTR_TO_PACKET) {
1253                         /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1254                         tmp_reg = *dst_reg;  /* save r7 state */
1255                         *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1256                         src_reg = &tmp_reg;  /* pretend it's src_reg state */
1257                         /* if the checks below reject it, the copy won't matter,
1258                          * since we're rejecting the whole program. If all ok,
1259                          * then imm22 state will be added to r7
1260                          * and r7 will be pkt(id=0,off=22,r=62) while
1261                          * r6 will stay as pkt(id=0,off=0,r=62)
1262                          */
1263                 }
1264
1265                 if (src_reg->type == CONST_IMM) {
1266                         /* pkt_ptr += reg where reg is known constant */
1267                         imm = src_reg->imm;
1268                         goto add_imm;
1269                 }
1270                 /* disallow pkt_ptr += reg
1271                  * if reg is not uknown_value with guaranteed zero upper bits
1272                  * otherwise pkt_ptr may overflow and addition will become
1273                  * subtraction which is not allowed
1274                  */
1275                 if (src_reg->type != UNKNOWN_VALUE) {
1276                         verbose("cannot add '%s' to ptr_to_packet\n",
1277                                 reg_type_str[src_reg->type]);
1278                         return -EACCES;
1279                 }
1280                 if (src_reg->imm < 48) {
1281                         verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1282                                 src_reg->imm);
1283                         return -EACCES;
1284                 }
1285                 /* dst_reg stays as pkt_ptr type and since some positive
1286                  * integer value was added to the pointer, increment its 'id'
1287                  */
1288                 dst_reg->id = ++env->id_gen;
1289
1290                 /* something was added to pkt_ptr, set range and off to zero */
1291                 dst_reg->off = 0;
1292                 dst_reg->range = 0;
1293         }
1294         return 0;
1295 }
1296
1297 static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
1298 {
1299         struct bpf_reg_state *regs = env->cur_state.regs;
1300         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1301         u8 opcode = BPF_OP(insn->code);
1302         s64 imm_log2;
1303
1304         /* for type == UNKNOWN_VALUE:
1305          * imm > 0 -> number of zero upper bits
1306          * imm == 0 -> don't track which is the same as all bits can be non-zero
1307          */
1308
1309         if (BPF_SRC(insn->code) == BPF_X) {
1310                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1311
1312                 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1313                     dst_reg->imm && opcode == BPF_ADD) {
1314                         /* dreg += sreg
1315                          * where both have zero upper bits. Adding them
1316                          * can only result making one more bit non-zero
1317                          * in the larger value.
1318                          * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1319                          *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1320                          */
1321                         dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1322                         dst_reg->imm--;
1323                         return 0;
1324                 }
1325                 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1326                     dst_reg->imm && opcode == BPF_ADD) {
1327                         /* dreg += sreg
1328                          * where dreg has zero upper bits and sreg is const.
1329                          * Adding them can only result making one more bit
1330                          * non-zero in the larger value.
1331                          */
1332                         imm_log2 = __ilog2_u64((long long)src_reg->imm);
1333                         dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1334                         dst_reg->imm--;
1335                         return 0;
1336                 }
1337                 /* all other cases non supported yet, just mark dst_reg */
1338                 dst_reg->imm = 0;
1339                 return 0;
1340         }
1341
1342         /* sign extend 32-bit imm into 64-bit to make sure that
1343          * negative values occupy bit 63. Note ilog2() would have
1344          * been incorrect, since sizeof(insn->imm) == 4
1345          */
1346         imm_log2 = __ilog2_u64((long long)insn->imm);
1347
1348         if (dst_reg->imm && opcode == BPF_LSH) {
1349                 /* reg <<= imm
1350                  * if reg was a result of 2 byte load, then its imm == 48
1351                  * which means that upper 48 bits are zero and shifting this reg
1352                  * left by 4 would mean that upper 44 bits are still zero
1353                  */
1354                 dst_reg->imm -= insn->imm;
1355         } else if (dst_reg->imm && opcode == BPF_MUL) {
1356                 /* reg *= imm
1357                  * if multiplying by 14 subtract 4
1358                  * This is conservative calculation of upper zero bits.
1359                  * It's not trying to special case insn->imm == 1 or 0 cases
1360                  */
1361                 dst_reg->imm -= imm_log2 + 1;
1362         } else if (opcode == BPF_AND) {
1363                 /* reg &= imm */
1364                 dst_reg->imm = 63 - imm_log2;
1365         } else if (dst_reg->imm && opcode == BPF_ADD) {
1366                 /* reg += imm */
1367                 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1368                 dst_reg->imm--;
1369         } else if (opcode == BPF_RSH) {
1370                 /* reg >>= imm
1371                  * which means that after right shift, upper bits will be zero
1372                  * note that verifier already checked that
1373                  * 0 <= imm < 64 for shift insn
1374                  */
1375                 dst_reg->imm += insn->imm;
1376                 if (unlikely(dst_reg->imm > 64))
1377                         /* some dumb code did:
1378                          * r2 = *(u32 *)mem;
1379                          * r2 >>= 32;
1380                          * and all bits are zero now */
1381                         dst_reg->imm = 64;
1382         } else {
1383                 /* all other alu ops, means that we don't know what will
1384                  * happen to the value, mark it with unknown number of zero bits
1385                  */
1386                 dst_reg->imm = 0;
1387         }
1388
1389         if (dst_reg->imm < 0) {
1390                 /* all 64 bits of the register can contain non-zero bits
1391                  * and such value cannot be added to ptr_to_packet, since it
1392                  * may overflow, mark it as unknown to avoid further eval
1393                  */
1394                 dst_reg->imm = 0;
1395         }
1396         return 0;
1397 }
1398
1399 static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1400                                 struct bpf_insn *insn)
1401 {
1402         struct bpf_reg_state *regs = env->cur_state.regs;
1403         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1404         struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1405         u8 opcode = BPF_OP(insn->code);
1406
1407         /* dst_reg->type == CONST_IMM here, simulate execution of 'add' insn.
1408          * Don't care about overflow or negative values, just add them
1409          */
1410         if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K)
1411                 dst_reg->imm += insn->imm;
1412         else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1413                  src_reg->type == CONST_IMM)
1414                 dst_reg->imm += src_reg->imm;
1415         else
1416                 mark_reg_unknown_value(regs, insn->dst_reg);
1417         return 0;
1418 }
1419
1420 /* check validity of 32-bit and 64-bit arithmetic operations */
1421 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
1422 {
1423         struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1424         u8 opcode = BPF_OP(insn->code);
1425         int err;
1426
1427         if (opcode == BPF_END || opcode == BPF_NEG) {
1428                 if (opcode == BPF_NEG) {
1429                         if (BPF_SRC(insn->code) != 0 ||
1430                             insn->src_reg != BPF_REG_0 ||
1431                             insn->off != 0 || insn->imm != 0) {
1432                                 verbose("BPF_NEG uses reserved fields\n");
1433                                 return -EINVAL;
1434                         }
1435                 } else {
1436                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1437                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1438                                 verbose("BPF_END uses reserved fields\n");
1439                                 return -EINVAL;
1440                         }
1441                 }
1442
1443                 /* check src operand */
1444                 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1445                 if (err)
1446                         return err;
1447
1448                 if (is_pointer_value(env, insn->dst_reg)) {
1449                         verbose("R%d pointer arithmetic prohibited\n",
1450                                 insn->dst_reg);
1451                         return -EACCES;
1452                 }
1453
1454                 /* check dest operand */
1455                 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1456                 if (err)
1457                         return err;
1458
1459         } else if (opcode == BPF_MOV) {
1460
1461                 if (BPF_SRC(insn->code) == BPF_X) {
1462                         if (insn->imm != 0 || insn->off != 0) {
1463                                 verbose("BPF_MOV uses reserved fields\n");
1464                                 return -EINVAL;
1465                         }
1466
1467                         /* check src operand */
1468                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1469                         if (err)
1470                                 return err;
1471                 } else {
1472                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1473                                 verbose("BPF_MOV uses reserved fields\n");
1474                                 return -EINVAL;
1475                         }
1476                 }
1477
1478                 /* check dest operand */
1479                 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1480                 if (err)
1481                         return err;
1482
1483                 if (BPF_SRC(insn->code) == BPF_X) {
1484                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
1485                                 /* case: R1 = R2
1486                                  * copy register state to dest reg
1487                                  */
1488                                 regs[insn->dst_reg] = regs[insn->src_reg];
1489                         } else {
1490                                 if (is_pointer_value(env, insn->src_reg)) {
1491                                         verbose("R%d partial copy of pointer\n",
1492                                                 insn->src_reg);
1493                                         return -EACCES;
1494                                 }
1495                                 regs[insn->dst_reg].type = UNKNOWN_VALUE;
1496                                 regs[insn->dst_reg].map_ptr = NULL;
1497                         }
1498                 } else {
1499                         /* case: R = imm
1500                          * remember the value we stored into this reg
1501                          */
1502                         regs[insn->dst_reg].type = CONST_IMM;
1503                         regs[insn->dst_reg].imm = insn->imm;
1504                 }
1505
1506         } else if (opcode > BPF_END) {
1507                 verbose("invalid BPF_ALU opcode %x\n", opcode);
1508                 return -EINVAL;
1509
1510         } else {        /* all other ALU ops: and, sub, xor, add, ... */
1511
1512                 if (BPF_SRC(insn->code) == BPF_X) {
1513                         if (insn->imm != 0 || insn->off != 0) {
1514                                 verbose("BPF_ALU uses reserved fields\n");
1515                                 return -EINVAL;
1516                         }
1517                         /* check src1 operand */
1518                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1519                         if (err)
1520                                 return err;
1521                 } else {
1522                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1523                                 verbose("BPF_ALU uses reserved fields\n");
1524                                 return -EINVAL;
1525                         }
1526                 }
1527
1528                 /* check src2 operand */
1529                 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1530                 if (err)
1531                         return err;
1532
1533                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
1534                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
1535                         verbose("div by zero\n");
1536                         return -EINVAL;
1537                 }
1538
1539                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
1540                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
1541                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
1542
1543                         if (insn->imm < 0 || insn->imm >= size) {
1544                                 verbose("invalid shift %d\n", insn->imm);
1545                                 return -EINVAL;
1546                         }
1547                 }
1548
1549                 /* check dest operand */
1550                 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
1551                 if (err)
1552                         return err;
1553
1554                 dst_reg = &regs[insn->dst_reg];
1555
1556                 /* pattern match 'bpf_add Rx, imm' instruction */
1557                 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
1558                     dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
1559                         dst_reg->type = PTR_TO_STACK;
1560                         dst_reg->imm = insn->imm;
1561                         return 0;
1562                 } else if (opcode == BPF_ADD &&
1563                            BPF_CLASS(insn->code) == BPF_ALU64 &&
1564                            (dst_reg->type == PTR_TO_PACKET ||
1565                             (BPF_SRC(insn->code) == BPF_X &&
1566                              regs[insn->src_reg].type == PTR_TO_PACKET))) {
1567                         /* ptr_to_packet += K|X */
1568                         return check_packet_ptr_add(env, insn);
1569                 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1570                            dst_reg->type == UNKNOWN_VALUE &&
1571                            env->allow_ptr_leaks) {
1572                         /* unknown += K|X */
1573                         return evaluate_reg_alu(env, insn);
1574                 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
1575                            dst_reg->type == CONST_IMM &&
1576                            env->allow_ptr_leaks) {
1577                         /* reg_imm += K|X */
1578                         return evaluate_reg_imm_alu(env, insn);
1579                 } else if (is_pointer_value(env, insn->dst_reg)) {
1580                         verbose("R%d pointer arithmetic prohibited\n",
1581                                 insn->dst_reg);
1582                         return -EACCES;
1583                 } else if (BPF_SRC(insn->code) == BPF_X &&
1584                            is_pointer_value(env, insn->src_reg)) {
1585                         verbose("R%d pointer arithmetic prohibited\n",
1586                                 insn->src_reg);
1587                         return -EACCES;
1588                 }
1589
1590                 /* mark dest operand */
1591                 mark_reg_unknown_value(regs, insn->dst_reg);
1592         }
1593
1594         return 0;
1595 }
1596
1597 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
1598                                    struct bpf_reg_state *dst_reg)
1599 {
1600         struct bpf_reg_state *regs = state->regs, *reg;
1601         int i;
1602
1603         /* LLVM can generate two kind of checks:
1604          *
1605          * Type 1:
1606          *
1607          *   r2 = r3;
1608          *   r2 += 8;
1609          *   if (r2 > pkt_end) goto <handle exception>
1610          *   <access okay>
1611          *
1612          *   Where:
1613          *     r2 == dst_reg, pkt_end == src_reg
1614          *     r2=pkt(id=n,off=8,r=0)
1615          *     r3=pkt(id=n,off=0,r=0)
1616          *
1617          * Type 2:
1618          *
1619          *   r2 = r3;
1620          *   r2 += 8;
1621          *   if (pkt_end >= r2) goto <access okay>
1622          *   <handle exception>
1623          *
1624          *   Where:
1625          *     pkt_end == dst_reg, r2 == src_reg
1626          *     r2=pkt(id=n,off=8,r=0)
1627          *     r3=pkt(id=n,off=0,r=0)
1628          *
1629          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
1630          * so that range of bytes [r3, r3 + 8) is safe to access.
1631          */
1632
1633         for (i = 0; i < MAX_BPF_REG; i++)
1634                 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
1635                         regs[i].range = dst_reg->off;
1636
1637         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1638                 if (state->stack_slot_type[i] != STACK_SPILL)
1639                         continue;
1640                 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1641                 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
1642                         reg->range = dst_reg->off;
1643         }
1644 }
1645
1646 static int check_cond_jmp_op(struct bpf_verifier_env *env,
1647                              struct bpf_insn *insn, int *insn_idx)
1648 {
1649         struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
1650         struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
1651         u8 opcode = BPF_OP(insn->code);
1652         int err;
1653
1654         if (opcode > BPF_EXIT) {
1655                 verbose("invalid BPF_JMP opcode %x\n", opcode);
1656                 return -EINVAL;
1657         }
1658
1659         if (BPF_SRC(insn->code) == BPF_X) {
1660                 if (insn->imm != 0) {
1661                         verbose("BPF_JMP uses reserved fields\n");
1662                         return -EINVAL;
1663                 }
1664
1665                 /* check src1 operand */
1666                 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1667                 if (err)
1668                         return err;
1669
1670                 if (is_pointer_value(env, insn->src_reg)) {
1671                         verbose("R%d pointer comparison prohibited\n",
1672                                 insn->src_reg);
1673                         return -EACCES;
1674                 }
1675         } else {
1676                 if (insn->src_reg != BPF_REG_0) {
1677                         verbose("BPF_JMP uses reserved fields\n");
1678                         return -EINVAL;
1679                 }
1680         }
1681
1682         /* check src2 operand */
1683         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1684         if (err)
1685                 return err;
1686
1687         dst_reg = &regs[insn->dst_reg];
1688
1689         /* detect if R == 0 where R was initialized to zero earlier */
1690         if (BPF_SRC(insn->code) == BPF_K &&
1691             (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1692             dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
1693                 if (opcode == BPF_JEQ) {
1694                         /* if (imm == imm) goto pc+off;
1695                          * only follow the goto, ignore fall-through
1696                          */
1697                         *insn_idx += insn->off;
1698                         return 0;
1699                 } else {
1700                         /* if (imm != imm) goto pc+off;
1701                          * only follow fall-through branch, since
1702                          * that's where the program will go
1703                          */
1704                         return 0;
1705                 }
1706         }
1707
1708         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
1709         if (!other_branch)
1710                 return -EFAULT;
1711
1712         /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
1713         if (BPF_SRC(insn->code) == BPF_K &&
1714             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
1715             dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
1716                 if (opcode == BPF_JEQ) {
1717                         /* next fallthrough insn can access memory via
1718                          * this register
1719                          */
1720                         regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1721                         /* branch targer cannot access it, since reg == 0 */
1722                         mark_reg_unknown_value(other_branch->regs,
1723                                                insn->dst_reg);
1724                 } else {
1725                         other_branch->regs[insn->dst_reg].type = PTR_TO_MAP_VALUE;
1726                         mark_reg_unknown_value(regs, insn->dst_reg);
1727                 }
1728         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
1729                    dst_reg->type == PTR_TO_PACKET &&
1730                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
1731                 find_good_pkt_pointers(this_branch, dst_reg);
1732         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
1733                    dst_reg->type == PTR_TO_PACKET_END &&
1734                    regs[insn->src_reg].type == PTR_TO_PACKET) {
1735                 find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
1736         } else if (is_pointer_value(env, insn->dst_reg)) {
1737                 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
1738                 return -EACCES;
1739         }
1740         if (log_level)
1741                 print_verifier_state(this_branch);
1742         return 0;
1743 }
1744
1745 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
1746 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
1747 {
1748         u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
1749
1750         return (struct bpf_map *) (unsigned long) imm64;
1751 }
1752
1753 /* verify BPF_LD_IMM64 instruction */
1754 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
1755 {
1756         struct bpf_reg_state *regs = env->cur_state.regs;
1757         int err;
1758
1759         if (BPF_SIZE(insn->code) != BPF_DW) {
1760                 verbose("invalid BPF_LD_IMM insn\n");
1761                 return -EINVAL;
1762         }
1763         if (insn->off != 0) {
1764                 verbose("BPF_LD_IMM64 uses reserved fields\n");
1765                 return -EINVAL;
1766         }
1767
1768         err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1769         if (err)
1770                 return err;
1771
1772         if (insn->src_reg == 0)
1773                 /* generic move 64-bit immediate into a register */
1774                 return 0;
1775
1776         /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
1777         BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
1778
1779         regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
1780         regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
1781         return 0;
1782 }
1783
1784 static bool may_access_skb(enum bpf_prog_type type)
1785 {
1786         switch (type) {
1787         case BPF_PROG_TYPE_SOCKET_FILTER:
1788         case BPF_PROG_TYPE_SCHED_CLS:
1789         case BPF_PROG_TYPE_SCHED_ACT:
1790                 return true;
1791         default:
1792                 return false;
1793         }
1794 }
1795
1796 /* verify safety of LD_ABS|LD_IND instructions:
1797  * - they can only appear in the programs where ctx == skb
1798  * - since they are wrappers of function calls, they scratch R1-R5 registers,
1799  *   preserve R6-R9, and store return value into R0
1800  *
1801  * Implicit input:
1802  *   ctx == skb == R6 == CTX
1803  *
1804  * Explicit input:
1805  *   SRC == any register
1806  *   IMM == 32-bit immediate
1807  *
1808  * Output:
1809  *   R0 - 8/16/32-bit skb data converted to cpu endianness
1810  */
1811 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
1812 {
1813         struct bpf_reg_state *regs = env->cur_state.regs;
1814         u8 mode = BPF_MODE(insn->code);
1815         struct bpf_reg_state *reg;
1816         int i, err;
1817
1818         if (!may_access_skb(env->prog->type)) {
1819                 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
1820                 return -EINVAL;
1821         }
1822
1823         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
1824             BPF_SIZE(insn->code) == BPF_DW ||
1825             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
1826                 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
1827                 return -EINVAL;
1828         }
1829
1830         /* check whether implicit source operand (register R6) is readable */
1831         err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
1832         if (err)
1833                 return err;
1834
1835         if (regs[BPF_REG_6].type != PTR_TO_CTX) {
1836                 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
1837                 return -EINVAL;
1838         }
1839
1840         if (mode == BPF_IND) {
1841                 /* check explicit source operand */
1842                 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1843                 if (err)
1844                         return err;
1845         }
1846
1847         /* reset caller saved regs to unreadable */
1848         for (i = 0; i < CALLER_SAVED_REGS; i++) {
1849                 reg = regs + caller_saved[i];
1850                 reg->type = NOT_INIT;
1851                 reg->imm = 0;
1852         }
1853
1854         /* mark destination R0 register as readable, since it contains
1855          * the value fetched from the packet
1856          */
1857         regs[BPF_REG_0].type = UNKNOWN_VALUE;
1858         return 0;
1859 }
1860
1861 /* non-recursive DFS pseudo code
1862  * 1  procedure DFS-iterative(G,v):
1863  * 2      label v as discovered
1864  * 3      let S be a stack
1865  * 4      S.push(v)
1866  * 5      while S is not empty
1867  * 6            t <- S.pop()
1868  * 7            if t is what we're looking for:
1869  * 8                return t
1870  * 9            for all edges e in G.adjacentEdges(t) do
1871  * 10               if edge e is already labelled
1872  * 11                   continue with the next edge
1873  * 12               w <- G.adjacentVertex(t,e)
1874  * 13               if vertex w is not discovered and not explored
1875  * 14                   label e as tree-edge
1876  * 15                   label w as discovered
1877  * 16                   S.push(w)
1878  * 17                   continue at 5
1879  * 18               else if vertex w is discovered
1880  * 19                   label e as back-edge
1881  * 20               else
1882  * 21                   // vertex w is explored
1883  * 22                   label e as forward- or cross-edge
1884  * 23           label t as explored
1885  * 24           S.pop()
1886  *
1887  * convention:
1888  * 0x10 - discovered
1889  * 0x11 - discovered and fall-through edge labelled
1890  * 0x12 - discovered and fall-through and branch edges labelled
1891  * 0x20 - explored
1892  */
1893
1894 enum {
1895         DISCOVERED = 0x10,
1896         EXPLORED = 0x20,
1897         FALLTHROUGH = 1,
1898         BRANCH = 2,
1899 };
1900
1901 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
1902
1903 static int *insn_stack; /* stack of insns to process */
1904 static int cur_stack;   /* current stack index */
1905 static int *insn_state;
1906
1907 /* t, w, e - match pseudo-code above:
1908  * t - index of current instruction
1909  * w - next instruction
1910  * e - edge
1911  */
1912 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
1913 {
1914         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
1915                 return 0;
1916
1917         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
1918                 return 0;
1919
1920         if (w < 0 || w >= env->prog->len) {
1921                 verbose("jump out of range from insn %d to %d\n", t, w);
1922                 return -EINVAL;
1923         }
1924
1925         if (e == BRANCH)
1926                 /* mark branch target for state pruning */
1927                 env->explored_states[w] = STATE_LIST_MARK;
1928
1929         if (insn_state[w] == 0) {
1930                 /* tree-edge */
1931                 insn_state[t] = DISCOVERED | e;
1932                 insn_state[w] = DISCOVERED;
1933                 if (cur_stack >= env->prog->len)
1934                         return -E2BIG;
1935                 insn_stack[cur_stack++] = w;
1936                 return 1;
1937         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
1938                 verbose("back-edge from insn %d to %d\n", t, w);
1939                 return -EINVAL;
1940         } else if (insn_state[w] == EXPLORED) {
1941                 /* forward- or cross-edge */
1942                 insn_state[t] = DISCOVERED | e;
1943         } else {
1944                 verbose("insn state internal bug\n");
1945                 return -EFAULT;
1946         }
1947         return 0;
1948 }
1949
1950 /* non-recursive depth-first-search to detect loops in BPF program
1951  * loop == back-edge in directed graph
1952  */
1953 static int check_cfg(struct bpf_verifier_env *env)
1954 {
1955         struct bpf_insn *insns = env->prog->insnsi;
1956         int insn_cnt = env->prog->len;
1957         int ret = 0;
1958         int i, t;
1959
1960         insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1961         if (!insn_state)
1962                 return -ENOMEM;
1963
1964         insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
1965         if (!insn_stack) {
1966                 kfree(insn_state);
1967                 return -ENOMEM;
1968         }
1969
1970         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
1971         insn_stack[0] = 0; /* 0 is the first instruction */
1972         cur_stack = 1;
1973
1974 peek_stack:
1975         if (cur_stack == 0)
1976                 goto check_state;
1977         t = insn_stack[cur_stack - 1];
1978
1979         if (BPF_CLASS(insns[t].code) == BPF_JMP) {
1980                 u8 opcode = BPF_OP(insns[t].code);
1981
1982                 if (opcode == BPF_EXIT) {
1983                         goto mark_explored;
1984                 } else if (opcode == BPF_CALL) {
1985                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
1986                         if (ret == 1)
1987                                 goto peek_stack;
1988                         else if (ret < 0)
1989                                 goto err_free;
1990                         if (t + 1 < insn_cnt)
1991                                 env->explored_states[t + 1] = STATE_LIST_MARK;
1992                 } else if (opcode == BPF_JA) {
1993                         if (BPF_SRC(insns[t].code) != BPF_K) {
1994                                 ret = -EINVAL;
1995                                 goto err_free;
1996                         }
1997                         /* unconditional jump with single edge */
1998                         ret = push_insn(t, t + insns[t].off + 1,
1999                                         FALLTHROUGH, env);
2000                         if (ret == 1)
2001                                 goto peek_stack;
2002                         else if (ret < 0)
2003                                 goto err_free;
2004                         /* tell verifier to check for equivalent states
2005                          * after every call and jump
2006                          */
2007                         if (t + 1 < insn_cnt)
2008                                 env->explored_states[t + 1] = STATE_LIST_MARK;
2009                 } else {
2010                         /* conditional jump with two edges */
2011                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
2012                         if (ret == 1)
2013                                 goto peek_stack;
2014                         else if (ret < 0)
2015                                 goto err_free;
2016
2017                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2018                         if (ret == 1)
2019                                 goto peek_stack;
2020                         else if (ret < 0)
2021                                 goto err_free;
2022                 }
2023         } else {
2024                 /* all other non-branch instructions with single
2025                  * fall-through edge
2026                  */
2027                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2028                 if (ret == 1)
2029                         goto peek_stack;
2030                 else if (ret < 0)
2031                         goto err_free;
2032         }
2033
2034 mark_explored:
2035         insn_state[t] = EXPLORED;
2036         if (cur_stack-- <= 0) {
2037                 verbose("pop stack internal bug\n");
2038                 ret = -EFAULT;
2039                 goto err_free;
2040         }
2041         goto peek_stack;
2042
2043 check_state:
2044         for (i = 0; i < insn_cnt; i++) {
2045                 if (insn_state[i] != EXPLORED) {
2046                         verbose("unreachable insn %d\n", i);
2047                         ret = -EINVAL;
2048                         goto err_free;
2049                 }
2050         }
2051         ret = 0; /* cfg looks good */
2052
2053 err_free:
2054         kfree(insn_state);
2055         kfree(insn_stack);
2056         return ret;
2057 }
2058
2059 /* the following conditions reduce the number of explored insns
2060  * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2061  */
2062 static bool compare_ptrs_to_packet(struct bpf_reg_state *old,
2063                                    struct bpf_reg_state *cur)
2064 {
2065         if (old->id != cur->id)
2066                 return false;
2067
2068         /* old ptr_to_packet is more conservative, since it allows smaller
2069          * range. Ex:
2070          * old(off=0,r=10) is equal to cur(off=0,r=20), because
2071          * old(off=0,r=10) means that with range=10 the verifier proceeded
2072          * further and found no issues with the program. Now we're in the same
2073          * spot with cur(off=0,r=20), so we're safe too, since anything further
2074          * will only be looking at most 10 bytes after this pointer.
2075          */
2076         if (old->off == cur->off && old->range < cur->range)
2077                 return true;
2078
2079         /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2080          * since both cannot be used for packet access and safe(old)
2081          * pointer has smaller off that could be used for further
2082          * 'if (ptr > data_end)' check
2083          * Ex:
2084          * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2085          * that we cannot access the packet.
2086          * The safe range is:
2087          * [ptr, ptr + range - off)
2088          * so whenever off >=range, it means no safe bytes from this pointer.
2089          * When comparing old->off <= cur->off, it means that older code
2090          * went with smaller offset and that offset was later
2091          * used to figure out the safe range after 'if (ptr > data_end)' check
2092          * Say, 'old' state was explored like:
2093          * ... R3(off=0, r=0)
2094          * R4 = R3 + 20
2095          * ... now R4(off=20,r=0)  <-- here
2096          * if (R4 > data_end)
2097          * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2098          * ... the code further went all the way to bpf_exit.
2099          * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2100          * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2101          * goes further, such cur_R4 will give larger safe packet range after
2102          * 'if (R4 > data_end)' and all further insn were already good with r=20,
2103          * so they will be good with r=30 and we can prune the search.
2104          */
2105         if (old->off <= cur->off &&
2106             old->off >= old->range && cur->off >= cur->range)
2107                 return true;
2108
2109         return false;
2110 }
2111
2112 /* compare two verifier states
2113  *
2114  * all states stored in state_list are known to be valid, since
2115  * verifier reached 'bpf_exit' instruction through them
2116  *
2117  * this function is called when verifier exploring different branches of
2118  * execution popped from the state stack. If it sees an old state that has
2119  * more strict register state and more strict stack state then this execution
2120  * branch doesn't need to be explored further, since verifier already
2121  * concluded that more strict state leads to valid finish.
2122  *
2123  * Therefore two states are equivalent if register state is more conservative
2124  * and explored stack state is more conservative than the current one.
2125  * Example:
2126  *       explored                   current
2127  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2128  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2129  *
2130  * In other words if current stack state (one being explored) has more
2131  * valid slots than old one that already passed validation, it means
2132  * the verifier can stop exploring and conclude that current state is valid too
2133  *
2134  * Similarly with registers. If explored state has register type as invalid
2135  * whereas register type in current state is meaningful, it means that
2136  * the current state will reach 'bpf_exit' instruction safely
2137  */
2138 static bool states_equal(struct bpf_verifier_state *old,
2139                          struct bpf_verifier_state *cur)
2140 {
2141         struct bpf_reg_state *rold, *rcur;
2142         int i;
2143
2144         for (i = 0; i < MAX_BPF_REG; i++) {
2145                 rold = &old->regs[i];
2146                 rcur = &cur->regs[i];
2147
2148                 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2149                         continue;
2150
2151                 if (rold->type == NOT_INIT ||
2152                     (rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT))
2153                         continue;
2154
2155                 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2156                     compare_ptrs_to_packet(rold, rcur))
2157                         continue;
2158
2159                 return false;
2160         }
2161
2162         for (i = 0; i < MAX_BPF_STACK; i++) {
2163                 if (old->stack_slot_type[i] == STACK_INVALID)
2164                         continue;
2165                 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2166                         /* Ex: old explored (safe) state has STACK_SPILL in
2167                          * this stack slot, but current has has STACK_MISC ->
2168                          * this verifier states are not equivalent,
2169                          * return false to continue verification of this path
2170                          */
2171                         return false;
2172                 if (i % BPF_REG_SIZE)
2173                         continue;
2174                 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2175                            &cur->spilled_regs[i / BPF_REG_SIZE],
2176                            sizeof(old->spilled_regs[0])))
2177                         /* when explored and current stack slot types are
2178                          * the same, check that stored pointers types
2179                          * are the same as well.
2180                          * Ex: explored safe path could have stored
2181                          * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
2182                          * but current path has stored:
2183                          * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
2184                          * such verifier states are not equivalent.
2185                          * return false to continue verification of this path
2186                          */
2187                         return false;
2188                 else
2189                         continue;
2190         }
2191         return true;
2192 }
2193
2194 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
2195 {
2196         struct bpf_verifier_state_list *new_sl;
2197         struct bpf_verifier_state_list *sl;
2198
2199         sl = env->explored_states[insn_idx];
2200         if (!sl)
2201                 /* this 'insn_idx' instruction wasn't marked, so we will not
2202                  * be doing state search here
2203                  */
2204                 return 0;
2205
2206         while (sl != STATE_LIST_MARK) {
2207                 if (states_equal(&sl->state, &env->cur_state))
2208                         /* reached equivalent register/stack state,
2209                          * prune the search
2210                          */
2211                         return 1;
2212                 sl = sl->next;
2213         }
2214
2215         /* there were no equivalent states, remember current one.
2216          * technically the current state is not proven to be safe yet,
2217          * but it will either reach bpf_exit (which means it's safe) or
2218          * it will be rejected. Since there are no loops, we won't be
2219          * seeing this 'insn_idx' instruction again on the way to bpf_exit
2220          */
2221         new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
2222         if (!new_sl)
2223                 return -ENOMEM;
2224
2225         /* add new state to the head of linked list */
2226         memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2227         new_sl->next = env->explored_states[insn_idx];
2228         env->explored_states[insn_idx] = new_sl;
2229         return 0;
2230 }
2231
2232 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2233                                   int insn_idx, int prev_insn_idx)
2234 {
2235         if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2236                 return 0;
2237
2238         return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2239 }
2240
2241 static int do_check(struct bpf_verifier_env *env)
2242 {
2243         struct bpf_verifier_state *state = &env->cur_state;
2244         struct bpf_insn *insns = env->prog->insnsi;
2245         struct bpf_reg_state *regs = state->regs;
2246         int insn_cnt = env->prog->len;
2247         int insn_idx, prev_insn_idx = 0;
2248         int insn_processed = 0;
2249         bool do_print_state = false;
2250
2251         init_reg_state(regs);
2252         insn_idx = 0;
2253         for (;;) {
2254                 struct bpf_insn *insn;
2255                 u8 class;
2256                 int err;
2257
2258                 if (insn_idx >= insn_cnt) {
2259                         verbose("invalid insn idx %d insn_cnt %d\n",
2260                                 insn_idx, insn_cnt);
2261                         return -EFAULT;
2262                 }
2263
2264                 insn = &insns[insn_idx];
2265                 class = BPF_CLASS(insn->code);
2266
2267                 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2268                         verbose("BPF program is too large. Proccessed %d insn\n",
2269                                 insn_processed);
2270                         return -E2BIG;
2271                 }
2272
2273                 err = is_state_visited(env, insn_idx);
2274                 if (err < 0)
2275                         return err;
2276                 if (err == 1) {
2277                         /* found equivalent state, can prune the search */
2278                         if (log_level) {
2279                                 if (do_print_state)
2280                                         verbose("\nfrom %d to %d: safe\n",
2281                                                 prev_insn_idx, insn_idx);
2282                                 else
2283                                         verbose("%d: safe\n", insn_idx);
2284                         }
2285                         goto process_bpf_exit;
2286                 }
2287
2288                 if (log_level && do_print_state) {
2289                         verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx);
2290                         print_verifier_state(&env->cur_state);
2291                         do_print_state = false;
2292                 }
2293
2294                 if (log_level) {
2295                         verbose("%d: ", insn_idx);
2296                         print_bpf_insn(insn);
2297                 }
2298
2299                 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2300                 if (err)
2301                         return err;
2302
2303                 if (class == BPF_ALU || class == BPF_ALU64) {
2304                         err = check_alu_op(env, insn);
2305                         if (err)
2306                                 return err;
2307
2308                 } else if (class == BPF_LDX) {
2309                         enum bpf_reg_type *prev_src_type, src_reg_type;
2310
2311                         /* check for reserved fields is already done */
2312
2313                         /* check src operand */
2314                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2315                         if (err)
2316                                 return err;
2317
2318                         err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2319                         if (err)
2320                                 return err;
2321
2322                         src_reg_type = regs[insn->src_reg].type;
2323
2324                         /* check that memory (src_reg + off) is readable,
2325                          * the state of dst_reg will be updated by this func
2326                          */
2327                         err = check_mem_access(env, insn->src_reg, insn->off,
2328                                                BPF_SIZE(insn->code), BPF_READ,
2329                                                insn->dst_reg);
2330                         if (err)
2331                                 return err;
2332
2333                         if (BPF_SIZE(insn->code) != BPF_W &&
2334                             BPF_SIZE(insn->code) != BPF_DW) {
2335                                 insn_idx++;
2336                                 continue;
2337                         }
2338
2339                         prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
2340
2341                         if (*prev_src_type == NOT_INIT) {
2342                                 /* saw a valid insn
2343                                  * dst_reg = *(u32 *)(src_reg + off)
2344                                  * save type to validate intersecting paths
2345                                  */
2346                                 *prev_src_type = src_reg_type;
2347
2348                         } else if (src_reg_type != *prev_src_type &&
2349                                    (src_reg_type == PTR_TO_CTX ||
2350                                     *prev_src_type == PTR_TO_CTX)) {
2351                                 /* ABuser program is trying to use the same insn
2352                                  * dst_reg = *(u32*) (src_reg + off)
2353                                  * with different pointer types:
2354                                  * src_reg == ctx in one branch and
2355                                  * src_reg == stack|map in some other branch.
2356                                  * Reject it.
2357                                  */
2358                                 verbose("same insn cannot be used with different pointers\n");
2359                                 return -EINVAL;
2360                         }
2361
2362                 } else if (class == BPF_STX) {
2363                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
2364
2365                         if (BPF_MODE(insn->code) == BPF_XADD) {
2366                                 err = check_xadd(env, insn);
2367                                 if (err)
2368                                         return err;
2369                                 insn_idx++;
2370                                 continue;
2371                         }
2372
2373                         /* check src1 operand */
2374                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2375                         if (err)
2376                                 return err;
2377                         /* check src2 operand */
2378                         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2379                         if (err)
2380                                 return err;
2381
2382                         dst_reg_type = regs[insn->dst_reg].type;
2383
2384                         /* check that memory (dst_reg + off) is writeable */
2385                         err = check_mem_access(env, insn->dst_reg, insn->off,
2386                                                BPF_SIZE(insn->code), BPF_WRITE,
2387                                                insn->src_reg);
2388                         if (err)
2389                                 return err;
2390
2391                         prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
2392
2393                         if (*prev_dst_type == NOT_INIT) {
2394                                 *prev_dst_type = dst_reg_type;
2395                         } else if (dst_reg_type != *prev_dst_type &&
2396                                    (dst_reg_type == PTR_TO_CTX ||
2397                                     *prev_dst_type == PTR_TO_CTX)) {
2398                                 verbose("same insn cannot be used with different pointers\n");
2399                                 return -EINVAL;
2400                         }
2401
2402                 } else if (class == BPF_ST) {
2403                         if (BPF_MODE(insn->code) != BPF_MEM ||
2404                             insn->src_reg != BPF_REG_0) {
2405                                 verbose("BPF_ST uses reserved fields\n");
2406                                 return -EINVAL;
2407                         }
2408                         /* check src operand */
2409                         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2410                         if (err)
2411                                 return err;
2412
2413                         /* check that memory (dst_reg + off) is writeable */
2414                         err = check_mem_access(env, insn->dst_reg, insn->off,
2415                                                BPF_SIZE(insn->code), BPF_WRITE,
2416                                                -1);
2417                         if (err)
2418                                 return err;
2419
2420                 } else if (class == BPF_JMP) {
2421                         u8 opcode = BPF_OP(insn->code);
2422
2423                         if (opcode == BPF_CALL) {
2424                                 if (BPF_SRC(insn->code) != BPF_K ||
2425                                     insn->off != 0 ||
2426                                     insn->src_reg != BPF_REG_0 ||
2427                                     insn->dst_reg != BPF_REG_0) {
2428                                         verbose("BPF_CALL uses reserved fields\n");
2429                                         return -EINVAL;
2430                                 }
2431
2432                                 err = check_call(env, insn->imm);
2433                                 if (err)
2434                                         return err;
2435
2436                         } else if (opcode == BPF_JA) {
2437                                 if (BPF_SRC(insn->code) != BPF_K ||
2438                                     insn->imm != 0 ||
2439                                     insn->src_reg != BPF_REG_0 ||
2440                                     insn->dst_reg != BPF_REG_0) {
2441                                         verbose("BPF_JA uses reserved fields\n");
2442                                         return -EINVAL;
2443                                 }
2444
2445                                 insn_idx += insn->off + 1;
2446                                 continue;
2447
2448                         } else if (opcode == BPF_EXIT) {
2449                                 if (BPF_SRC(insn->code) != BPF_K ||
2450                                     insn->imm != 0 ||
2451                                     insn->src_reg != BPF_REG_0 ||
2452                                     insn->dst_reg != BPF_REG_0) {
2453                                         verbose("BPF_EXIT uses reserved fields\n");
2454                                         return -EINVAL;
2455                                 }
2456
2457                                 /* eBPF calling convetion is such that R0 is used
2458                                  * to return the value from eBPF program.
2459                                  * Make sure that it's readable at this time
2460                                  * of bpf_exit, which means that program wrote
2461                                  * something into it earlier
2462                                  */
2463                                 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
2464                                 if (err)
2465                                         return err;
2466
2467                                 if (is_pointer_value(env, BPF_REG_0)) {
2468                                         verbose("R0 leaks addr as return value\n");
2469                                         return -EACCES;
2470                                 }
2471
2472 process_bpf_exit:
2473                                 insn_idx = pop_stack(env, &prev_insn_idx);
2474                                 if (insn_idx < 0) {
2475                                         break;
2476                                 } else {
2477                                         do_print_state = true;
2478                                         continue;
2479                                 }
2480                         } else {
2481                                 err = check_cond_jmp_op(env, insn, &insn_idx);
2482                                 if (err)
2483                                         return err;
2484                         }
2485                 } else if (class == BPF_LD) {
2486                         u8 mode = BPF_MODE(insn->code);
2487
2488                         if (mode == BPF_ABS || mode == BPF_IND) {
2489                                 err = check_ld_abs(env, insn);
2490                                 if (err)
2491                                         return err;
2492
2493                         } else if (mode == BPF_IMM) {
2494                                 err = check_ld_imm(env, insn);
2495                                 if (err)
2496                                         return err;
2497
2498                                 insn_idx++;
2499                         } else {
2500                                 verbose("invalid BPF_LD mode\n");
2501                                 return -EINVAL;
2502                         }
2503                 } else {
2504                         verbose("unknown insn class %d\n", class);
2505                         return -EINVAL;
2506                 }
2507
2508                 insn_idx++;
2509         }
2510
2511         verbose("processed %d insns\n", insn_processed);
2512         return 0;
2513 }
2514
2515 static int check_map_prog_compatibility(struct bpf_map *map,
2516                                         struct bpf_prog *prog)
2517
2518 {
2519         if (prog->type == BPF_PROG_TYPE_PERF_EVENT &&
2520             (map->map_type == BPF_MAP_TYPE_HASH ||
2521              map->map_type == BPF_MAP_TYPE_PERCPU_HASH) &&
2522             (map->map_flags & BPF_F_NO_PREALLOC)) {
2523                 verbose("perf_event programs can only use preallocated hash map\n");
2524                 return -EINVAL;
2525         }
2526         return 0;
2527 }
2528
2529 /* look for pseudo eBPF instructions that access map FDs and
2530  * replace them with actual map pointers
2531  */
2532 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
2533 {
2534         struct bpf_insn *insn = env->prog->insnsi;
2535         int insn_cnt = env->prog->len;
2536         int i, j, err;
2537
2538         for (i = 0; i < insn_cnt; i++, insn++) {
2539                 if (BPF_CLASS(insn->code) == BPF_LDX &&
2540                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
2541                         verbose("BPF_LDX uses reserved fields\n");
2542                         return -EINVAL;
2543                 }
2544
2545                 if (BPF_CLASS(insn->code) == BPF_STX &&
2546                     ((BPF_MODE(insn->code) != BPF_MEM &&
2547                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
2548                         verbose("BPF_STX uses reserved fields\n");
2549                         return -EINVAL;
2550                 }
2551
2552                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
2553                         struct bpf_map *map;
2554                         struct fd f;
2555
2556                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
2557                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
2558                             insn[1].off != 0) {
2559                                 verbose("invalid bpf_ld_imm64 insn\n");
2560                                 return -EINVAL;
2561                         }
2562
2563                         if (insn->src_reg == 0)
2564                                 /* valid generic load 64-bit imm */
2565                                 goto next_insn;
2566
2567                         if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
2568                                 verbose("unrecognized bpf_ld_imm64 insn\n");
2569                                 return -EINVAL;
2570                         }
2571
2572                         f = fdget(insn->imm);
2573                         map = __bpf_map_get(f);
2574                         if (IS_ERR(map)) {
2575                                 verbose("fd %d is not pointing to valid bpf_map\n",
2576                                         insn->imm);
2577                                 return PTR_ERR(map);
2578                         }
2579
2580                         err = check_map_prog_compatibility(map, env->prog);
2581                         if (err) {
2582                                 fdput(f);
2583                                 return err;
2584                         }
2585
2586                         /* store map pointer inside BPF_LD_IMM64 instruction */
2587                         insn[0].imm = (u32) (unsigned long) map;
2588                         insn[1].imm = ((u64) (unsigned long) map) >> 32;
2589
2590                         /* check whether we recorded this map already */
2591                         for (j = 0; j < env->used_map_cnt; j++)
2592                                 if (env->used_maps[j] == map) {
2593                                         fdput(f);
2594                                         goto next_insn;
2595                                 }
2596
2597                         if (env->used_map_cnt >= MAX_USED_MAPS) {
2598                                 fdput(f);
2599                                 return -E2BIG;
2600                         }
2601
2602                         /* hold the map. If the program is rejected by verifier,
2603                          * the map will be released by release_maps() or it
2604                          * will be used by the valid program until it's unloaded
2605                          * and all maps are released in free_bpf_prog_info()
2606                          */
2607                         map = bpf_map_inc(map, false);
2608                         if (IS_ERR(map)) {
2609                                 fdput(f);
2610                                 return PTR_ERR(map);
2611                         }
2612                         env->used_maps[env->used_map_cnt++] = map;
2613
2614                         fdput(f);
2615 next_insn:
2616                         insn++;
2617                         i++;
2618                 }
2619         }
2620
2621         /* now all pseudo BPF_LD_IMM64 instructions load valid
2622          * 'struct bpf_map *' into a register instead of user map_fd.
2623          * These pointers will be used later by verifier to validate map access.
2624          */
2625         return 0;
2626 }
2627
2628 /* drop refcnt of maps used by the rejected program */
2629 static void release_maps(struct bpf_verifier_env *env)
2630 {
2631         int i;
2632
2633         for (i = 0; i < env->used_map_cnt; i++)
2634                 bpf_map_put(env->used_maps[i]);
2635 }
2636
2637 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
2638 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
2639 {
2640         struct bpf_insn *insn = env->prog->insnsi;
2641         int insn_cnt = env->prog->len;
2642         int i;
2643
2644         for (i = 0; i < insn_cnt; i++, insn++)
2645                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
2646                         insn->src_reg = 0;
2647 }
2648
2649 /* convert load instructions that access fields of 'struct __sk_buff'
2650  * into sequence of instructions that access fields of 'struct sk_buff'
2651  */
2652 static int convert_ctx_accesses(struct bpf_verifier_env *env)
2653 {
2654         const struct bpf_verifier_ops *ops = env->prog->aux->ops;
2655         const int insn_cnt = env->prog->len;
2656         struct bpf_insn insn_buf[16], *insn;
2657         struct bpf_prog *new_prog;
2658         enum bpf_access_type type;
2659         int i, cnt, delta = 0;
2660
2661         if (ops->gen_prologue) {
2662                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
2663                                         env->prog);
2664                 if (cnt >= ARRAY_SIZE(insn_buf)) {
2665                         verbose("bpf verifier is misconfigured\n");
2666                         return -EINVAL;
2667                 } else if (cnt) {
2668                         new_prog = bpf_patch_insn_single(env->prog, 0,
2669                                                          insn_buf, cnt);
2670                         if (!new_prog)
2671                                 return -ENOMEM;
2672                         env->prog = new_prog;
2673                         delta += cnt - 1;
2674                 }
2675         }
2676
2677         if (!ops->convert_ctx_access)
2678                 return 0;
2679
2680         insn = env->prog->insnsi + delta;
2681
2682         for (i = 0; i < insn_cnt; i++, insn++) {
2683                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
2684                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
2685                         type = BPF_READ;
2686                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
2687                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
2688                         type = BPF_WRITE;
2689                 else
2690                         continue;
2691
2692                 if (env->insn_aux_data[i].ptr_type != PTR_TO_CTX)
2693                         continue;
2694
2695                 cnt = ops->convert_ctx_access(type, insn->dst_reg, insn->src_reg,
2696                                               insn->off, insn_buf, env->prog);
2697                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
2698                         verbose("bpf verifier is misconfigured\n");
2699                         return -EINVAL;
2700                 }
2701
2702                 new_prog = bpf_patch_insn_single(env->prog, i + delta, insn_buf,
2703                                                  cnt);
2704                 if (!new_prog)
2705                         return -ENOMEM;
2706
2707                 delta += cnt - 1;
2708
2709                 /* keep walking new program and skip insns we just inserted */
2710                 env->prog = new_prog;
2711                 insn      = new_prog->insnsi + i + delta;
2712         }
2713
2714         return 0;
2715 }
2716
2717 static void free_states(struct bpf_verifier_env *env)
2718 {
2719         struct bpf_verifier_state_list *sl, *sln;
2720         int i;
2721
2722         if (!env->explored_states)
2723                 return;
2724
2725         for (i = 0; i < env->prog->len; i++) {
2726                 sl = env->explored_states[i];
2727
2728                 if (sl)
2729                         while (sl != STATE_LIST_MARK) {
2730                                 sln = sl->next;
2731                                 kfree(sl);
2732                                 sl = sln;
2733                         }
2734         }
2735
2736         kfree(env->explored_states);
2737 }
2738
2739 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
2740 {
2741         char __user *log_ubuf = NULL;
2742         struct bpf_verifier_env *env;
2743         int ret = -EINVAL;
2744
2745         if ((*prog)->len <= 0 || (*prog)->len > BPF_MAXINSNS)
2746                 return -E2BIG;
2747
2748         /* 'struct bpf_verifier_env' can be global, but since it's not small,
2749          * allocate/free it every time bpf_check() is called
2750          */
2751         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
2752         if (!env)
2753                 return -ENOMEM;
2754
2755         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
2756                                      (*prog)->len);
2757         ret = -ENOMEM;
2758         if (!env->insn_aux_data)
2759                 goto err_free_env;
2760         env->prog = *prog;
2761
2762         /* grab the mutex to protect few globals used by verifier */
2763         mutex_lock(&bpf_verifier_lock);
2764
2765         if (attr->log_level || attr->log_buf || attr->log_size) {
2766                 /* user requested verbose verifier output
2767                  * and supplied buffer to store the verification trace
2768                  */
2769                 log_level = attr->log_level;
2770                 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
2771                 log_size = attr->log_size;
2772                 log_len = 0;
2773
2774                 ret = -EINVAL;
2775                 /* log_* values have to be sane */
2776                 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
2777                     log_level == 0 || log_ubuf == NULL)
2778                         goto err_unlock;
2779
2780                 ret = -ENOMEM;
2781                 log_buf = vmalloc(log_size);
2782                 if (!log_buf)
2783                         goto err_unlock;
2784         } else {
2785                 log_level = 0;
2786         }
2787
2788         ret = replace_map_fd_with_map_ptr(env);
2789         if (ret < 0)
2790                 goto skip_full_check;
2791
2792         env->explored_states = kcalloc(env->prog->len,
2793                                        sizeof(struct bpf_verifier_state_list *),
2794                                        GFP_USER);
2795         ret = -ENOMEM;
2796         if (!env->explored_states)
2797                 goto skip_full_check;
2798
2799         ret = check_cfg(env);
2800         if (ret < 0)
2801                 goto skip_full_check;
2802
2803         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2804
2805         ret = do_check(env);
2806
2807 skip_full_check:
2808         while (pop_stack(env, NULL) >= 0);
2809         free_states(env);
2810
2811         if (ret == 0)
2812                 /* program is valid, convert *(u32*)(ctx + off) accesses */
2813                 ret = convert_ctx_accesses(env);
2814
2815         if (log_level && log_len >= log_size - 1) {
2816                 BUG_ON(log_len >= log_size);
2817                 /* verifier log exceeded user supplied buffer */
2818                 ret = -ENOSPC;
2819                 /* fall through to return what was recorded */
2820         }
2821
2822         /* copy verifier log back to user space including trailing zero */
2823         if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
2824                 ret = -EFAULT;
2825                 goto free_log_buf;
2826         }
2827
2828         if (ret == 0 && env->used_map_cnt) {
2829                 /* if program passed verifier, update used_maps in bpf_prog_info */
2830                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
2831                                                           sizeof(env->used_maps[0]),
2832                                                           GFP_KERNEL);
2833
2834                 if (!env->prog->aux->used_maps) {
2835                         ret = -ENOMEM;
2836                         goto free_log_buf;
2837                 }
2838
2839                 memcpy(env->prog->aux->used_maps, env->used_maps,
2840                        sizeof(env->used_maps[0]) * env->used_map_cnt);
2841                 env->prog->aux->used_map_cnt = env->used_map_cnt;
2842
2843                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
2844                  * bpf_ld_imm64 instructions
2845                  */
2846                 convert_pseudo_ld_imm64(env);
2847         }
2848
2849 free_log_buf:
2850         if (log_level)
2851                 vfree(log_buf);
2852         if (!env->prog->aux->used_maps)
2853                 /* if we didn't copy map pointers into bpf_prog_info, release
2854                  * them now. Otherwise free_bpf_prog_info() will release them.
2855                  */
2856                 release_maps(env);
2857         *prog = env->prog;
2858 err_unlock:
2859         mutex_unlock(&bpf_verifier_lock);
2860         vfree(env->insn_aux_data);
2861 err_free_env:
2862         kfree(env);
2863         return ret;
2864 }
2865
2866 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
2867                  void *priv)
2868 {
2869         struct bpf_verifier_env *env;
2870         int ret;
2871
2872         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
2873         if (!env)
2874                 return -ENOMEM;
2875
2876         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
2877                                      prog->len);
2878         ret = -ENOMEM;
2879         if (!env->insn_aux_data)
2880                 goto err_free_env;
2881         env->prog = prog;
2882         env->analyzer_ops = ops;
2883         env->analyzer_priv = priv;
2884
2885         /* grab the mutex to protect few globals used by verifier */
2886         mutex_lock(&bpf_verifier_lock);
2887
2888         log_level = 0;
2889
2890         env->explored_states = kcalloc(env->prog->len,
2891                                        sizeof(struct bpf_verifier_state_list *),
2892                                        GFP_KERNEL);
2893         ret = -ENOMEM;
2894         if (!env->explored_states)
2895                 goto skip_full_check;
2896
2897         ret = check_cfg(env);
2898         if (ret < 0)
2899                 goto skip_full_check;
2900
2901         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
2902
2903         ret = do_check(env);
2904
2905 skip_full_check:
2906         while (pop_stack(env, NULL) >= 0);
2907         free_states(env);
2908
2909         mutex_unlock(&bpf_verifier_lock);
2910         vfree(env->insn_aux_data);
2911 err_free_env:
2912         kfree(env);
2913         return ret;
2914 }
2915 EXPORT_SYMBOL_GPL(bpf_analyzer);