]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - kernel/bpf/verifier.c
Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[karo-tx-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 #include <linux/stringify.h>
23
24 /* bpf_check() is a static code analyzer that walks eBPF program
25  * instruction by instruction and updates register/stack state.
26  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
27  *
28  * The first pass is depth-first-search to check that the program is a DAG.
29  * It rejects the following programs:
30  * - larger than BPF_MAXINSNS insns
31  * - if loop is present (detected via back-edge)
32  * - unreachable insns exist (shouldn't be a forest. program = one function)
33  * - out of bounds or malformed jumps
34  * The second pass is all possible path descent from the 1st insn.
35  * Since it's analyzing all pathes through the program, the length of the
36  * analysis is limited to 64k insn, which may be hit even if total number of
37  * insn is less then 4K, but there are too many branches that change stack/regs.
38  * Number of 'branches to be analyzed' is limited to 1k
39  *
40  * On entry to each instruction, each register has a type, and the instruction
41  * changes the types of the registers depending on instruction semantics.
42  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
43  * copied to R1.
44  *
45  * All registers are 64-bit.
46  * R0 - return register
47  * R1-R5 argument passing registers
48  * R6-R9 callee saved registers
49  * R10 - frame pointer read-only
50  *
51  * At the start of BPF program the register R1 contains a pointer to bpf_context
52  * and has type PTR_TO_CTX.
53  *
54  * Verifier tracks arithmetic operations on pointers in case:
55  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
56  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
57  * 1st insn copies R10 (which has FRAME_PTR) type into R1
58  * and 2nd arithmetic instruction is pattern matched to recognize
59  * that it wants to construct a pointer to some element within stack.
60  * So after 2nd insn, the register R1 has type PTR_TO_STACK
61  * (and -20 constant is saved for further stack bounds checking).
62  * Meaning that this reg is a pointer to stack plus known immediate constant.
63  *
64  * Most of the time the registers have UNKNOWN_VALUE type, which
65  * means the register has some value, but it's not a valid pointer.
66  * (like pointer plus pointer becomes UNKNOWN_VALUE type)
67  *
68  * When verifier sees load or store instructions the type of base register
69  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer
70  * types recognized by check_mem_access() function.
71  *
72  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
73  * and the range of [ptr, ptr + map's value_size) is accessible.
74  *
75  * registers used to pass values to function calls are checked against
76  * function argument constraints.
77  *
78  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
79  * It means that the register type passed to this function must be
80  * PTR_TO_STACK and it will be used inside the function as
81  * 'pointer to map element key'
82  *
83  * For example the argument constraints for bpf_map_lookup_elem():
84  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
85  *   .arg1_type = ARG_CONST_MAP_PTR,
86  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
87  *
88  * ret_type says that this function returns 'pointer to map elem value or null'
89  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
90  * 2nd argument should be a pointer to stack, which will be used inside
91  * the helper function as a pointer to map element key.
92  *
93  * On the kernel side the helper function looks like:
94  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
95  * {
96  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
97  *    void *key = (void *) (unsigned long) r2;
98  *    void *value;
99  *
100  *    here kernel can access 'key' and 'map' pointers safely, knowing that
101  *    [key, key + map->key_size) bytes are valid and were initialized on
102  *    the stack of eBPF program.
103  * }
104  *
105  * Corresponding eBPF program may look like:
106  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
107  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
108  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
109  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
110  * here verifier looks at prototype of map_lookup_elem() and sees:
111  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
112  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
113  *
114  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
115  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
116  * and were initialized prior to this call.
117  * If it's ok, then verifier allows this BPF_CALL insn and looks at
118  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
119  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
120  * returns ether pointer to map value or NULL.
121  *
122  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
123  * insn, the register holding that pointer in the true branch changes state to
124  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
125  * branch. See check_cond_jmp_op().
126  *
127  * After the call R0 is set to return type of the function and registers R1-R5
128  * are set to NOT_INIT to indicate that they are no longer readable.
129  */
130
131 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
132 struct bpf_verifier_stack_elem {
133         /* verifer state is 'st'
134          * before processing instruction 'insn_idx'
135          * and after processing instruction 'prev_insn_idx'
136          */
137         struct bpf_verifier_state st;
138         int insn_idx;
139         int prev_insn_idx;
140         struct bpf_verifier_stack_elem *next;
141 };
142
143 #define BPF_COMPLEXITY_LIMIT_INSNS      98304
144 #define BPF_COMPLEXITY_LIMIT_STACK      1024
145
146 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
147
148 struct bpf_call_arg_meta {
149         struct bpf_map *map_ptr;
150         bool raw_mode;
151         bool pkt_access;
152         int regno;
153         int access_size;
154 };
155
156 /* verbose verifier prints what it's seeing
157  * bpf_check() is called under lock, so no race to access these global vars
158  */
159 static u32 log_level, log_size, log_len;
160 static char *log_buf;
161
162 static DEFINE_MUTEX(bpf_verifier_lock);
163
164 /* log_level controls verbosity level of eBPF verifier.
165  * verbose() is used to dump the verification trace to the log, so the user
166  * can figure out what's wrong with the program
167  */
168 static __printf(1, 2) void verbose(const char *fmt, ...)
169 {
170         va_list args;
171
172         if (log_level == 0 || log_len >= log_size - 1)
173                 return;
174
175         va_start(args, fmt);
176         log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args);
177         va_end(args);
178 }
179
180 /* string representation of 'enum bpf_reg_type' */
181 static const char * const reg_type_str[] = {
182         [NOT_INIT]              = "?",
183         [UNKNOWN_VALUE]         = "inv",
184         [PTR_TO_CTX]            = "ctx",
185         [CONST_PTR_TO_MAP]      = "map_ptr",
186         [PTR_TO_MAP_VALUE]      = "map_value",
187         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
188         [PTR_TO_MAP_VALUE_ADJ]  = "map_value_adj",
189         [FRAME_PTR]             = "fp",
190         [PTR_TO_STACK]          = "fp",
191         [CONST_IMM]             = "imm",
192         [PTR_TO_PACKET]         = "pkt",
193         [PTR_TO_PACKET_END]     = "pkt_end",
194 };
195
196 #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x)
197 static const char * const func_id_str[] = {
198         __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN)
199 };
200 #undef __BPF_FUNC_STR_FN
201
202 static const char *func_id_name(int id)
203 {
204         BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID);
205
206         if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id])
207                 return func_id_str[id];
208         else
209                 return "unknown";
210 }
211
212 static void print_verifier_state(struct bpf_verifier_state *state)
213 {
214         struct bpf_reg_state *reg;
215         enum bpf_reg_type t;
216         int i;
217
218         for (i = 0; i < MAX_BPF_REG; i++) {
219                 reg = &state->regs[i];
220                 t = reg->type;
221                 if (t == NOT_INIT)
222                         continue;
223                 verbose(" R%d=%s", i, reg_type_str[t]);
224                 if (t == CONST_IMM || t == PTR_TO_STACK)
225                         verbose("%lld", reg->imm);
226                 else if (t == PTR_TO_PACKET)
227                         verbose("(id=%d,off=%d,r=%d)",
228                                 reg->id, reg->off, reg->range);
229                 else if (t == UNKNOWN_VALUE && reg->imm)
230                         verbose("%lld", reg->imm);
231                 else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE ||
232                          t == PTR_TO_MAP_VALUE_OR_NULL ||
233                          t == PTR_TO_MAP_VALUE_ADJ)
234                         verbose("(ks=%d,vs=%d,id=%u)",
235                                 reg->map_ptr->key_size,
236                                 reg->map_ptr->value_size,
237                                 reg->id);
238                 if (reg->min_value != BPF_REGISTER_MIN_RANGE)
239                         verbose(",min_value=%lld",
240                                 (long long)reg->min_value);
241                 if (reg->max_value != BPF_REGISTER_MAX_RANGE)
242                         verbose(",max_value=%llu",
243                                 (unsigned long long)reg->max_value);
244                 if (reg->min_align)
245                         verbose(",min_align=%u", reg->min_align);
246                 if (reg->aux_off)
247                         verbose(",aux_off=%u", reg->aux_off);
248                 if (reg->aux_off_align)
249                         verbose(",aux_off_align=%u", reg->aux_off_align);
250         }
251         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
252                 if (state->stack_slot_type[i] == STACK_SPILL)
253                         verbose(" fp%d=%s", -MAX_BPF_STACK + i,
254                                 reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]);
255         }
256         verbose("\n");
257 }
258
259 static const char *const bpf_class_string[] = {
260         [BPF_LD]    = "ld",
261         [BPF_LDX]   = "ldx",
262         [BPF_ST]    = "st",
263         [BPF_STX]   = "stx",
264         [BPF_ALU]   = "alu",
265         [BPF_JMP]   = "jmp",
266         [BPF_RET]   = "BUG",
267         [BPF_ALU64] = "alu64",
268 };
269
270 static const char *const bpf_alu_string[16] = {
271         [BPF_ADD >> 4]  = "+=",
272         [BPF_SUB >> 4]  = "-=",
273         [BPF_MUL >> 4]  = "*=",
274         [BPF_DIV >> 4]  = "/=",
275         [BPF_OR  >> 4]  = "|=",
276         [BPF_AND >> 4]  = "&=",
277         [BPF_LSH >> 4]  = "<<=",
278         [BPF_RSH >> 4]  = ">>=",
279         [BPF_NEG >> 4]  = "neg",
280         [BPF_MOD >> 4]  = "%=",
281         [BPF_XOR >> 4]  = "^=",
282         [BPF_MOV >> 4]  = "=",
283         [BPF_ARSH >> 4] = "s>>=",
284         [BPF_END >> 4]  = "endian",
285 };
286
287 static const char *const bpf_ldst_string[] = {
288         [BPF_W >> 3]  = "u32",
289         [BPF_H >> 3]  = "u16",
290         [BPF_B >> 3]  = "u8",
291         [BPF_DW >> 3] = "u64",
292 };
293
294 static const char *const bpf_jmp_string[16] = {
295         [BPF_JA >> 4]   = "jmp",
296         [BPF_JEQ >> 4]  = "==",
297         [BPF_JGT >> 4]  = ">",
298         [BPF_JGE >> 4]  = ">=",
299         [BPF_JSET >> 4] = "&",
300         [BPF_JNE >> 4]  = "!=",
301         [BPF_JSGT >> 4] = "s>",
302         [BPF_JSGE >> 4] = "s>=",
303         [BPF_CALL >> 4] = "call",
304         [BPF_EXIT >> 4] = "exit",
305 };
306
307 static void print_bpf_insn(const struct bpf_verifier_env *env,
308                            const struct bpf_insn *insn)
309 {
310         u8 class = BPF_CLASS(insn->code);
311
312         if (class == BPF_ALU || class == BPF_ALU64) {
313                 if (BPF_SRC(insn->code) == BPF_X)
314                         verbose("(%02x) %sr%d %s %sr%d\n",
315                                 insn->code, class == BPF_ALU ? "(u32) " : "",
316                                 insn->dst_reg,
317                                 bpf_alu_string[BPF_OP(insn->code) >> 4],
318                                 class == BPF_ALU ? "(u32) " : "",
319                                 insn->src_reg);
320                 else
321                         verbose("(%02x) %sr%d %s %s%d\n",
322                                 insn->code, class == BPF_ALU ? "(u32) " : "",
323                                 insn->dst_reg,
324                                 bpf_alu_string[BPF_OP(insn->code) >> 4],
325                                 class == BPF_ALU ? "(u32) " : "",
326                                 insn->imm);
327         } else if (class == BPF_STX) {
328                 if (BPF_MODE(insn->code) == BPF_MEM)
329                         verbose("(%02x) *(%s *)(r%d %+d) = r%d\n",
330                                 insn->code,
331                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
332                                 insn->dst_reg,
333                                 insn->off, insn->src_reg);
334                 else if (BPF_MODE(insn->code) == BPF_XADD)
335                         verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n",
336                                 insn->code,
337                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
338                                 insn->dst_reg, insn->off,
339                                 insn->src_reg);
340                 else
341                         verbose("BUG_%02x\n", insn->code);
342         } else if (class == BPF_ST) {
343                 if (BPF_MODE(insn->code) != BPF_MEM) {
344                         verbose("BUG_st_%02x\n", insn->code);
345                         return;
346                 }
347                 verbose("(%02x) *(%s *)(r%d %+d) = %d\n",
348                         insn->code,
349                         bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
350                         insn->dst_reg,
351                         insn->off, insn->imm);
352         } else if (class == BPF_LDX) {
353                 if (BPF_MODE(insn->code) != BPF_MEM) {
354                         verbose("BUG_ldx_%02x\n", insn->code);
355                         return;
356                 }
357                 verbose("(%02x) r%d = *(%s *)(r%d %+d)\n",
358                         insn->code, insn->dst_reg,
359                         bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
360                         insn->src_reg, insn->off);
361         } else if (class == BPF_LD) {
362                 if (BPF_MODE(insn->code) == BPF_ABS) {
363                         verbose("(%02x) r0 = *(%s *)skb[%d]\n",
364                                 insn->code,
365                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
366                                 insn->imm);
367                 } else if (BPF_MODE(insn->code) == BPF_IND) {
368                         verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n",
369                                 insn->code,
370                                 bpf_ldst_string[BPF_SIZE(insn->code) >> 3],
371                                 insn->src_reg, insn->imm);
372                 } else if (BPF_MODE(insn->code) == BPF_IMM &&
373                            BPF_SIZE(insn->code) == BPF_DW) {
374                         /* At this point, we already made sure that the second
375                          * part of the ldimm64 insn is accessible.
376                          */
377                         u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
378                         bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD;
379
380                         if (map_ptr && !env->allow_ptr_leaks)
381                                 imm = 0;
382
383                         verbose("(%02x) r%d = 0x%llx\n", insn->code,
384                                 insn->dst_reg, (unsigned long long)imm);
385                 } else {
386                         verbose("BUG_ld_%02x\n", insn->code);
387                         return;
388                 }
389         } else if (class == BPF_JMP) {
390                 u8 opcode = BPF_OP(insn->code);
391
392                 if (opcode == BPF_CALL) {
393                         verbose("(%02x) call %s#%d\n", insn->code,
394                                 func_id_name(insn->imm), insn->imm);
395                 } else if (insn->code == (BPF_JMP | BPF_JA)) {
396                         verbose("(%02x) goto pc%+d\n",
397                                 insn->code, insn->off);
398                 } else if (insn->code == (BPF_JMP | BPF_EXIT)) {
399                         verbose("(%02x) exit\n", insn->code);
400                 } else if (BPF_SRC(insn->code) == BPF_X) {
401                         verbose("(%02x) if r%d %s r%d goto pc%+d\n",
402                                 insn->code, insn->dst_reg,
403                                 bpf_jmp_string[BPF_OP(insn->code) >> 4],
404                                 insn->src_reg, insn->off);
405                 } else {
406                         verbose("(%02x) if r%d %s 0x%x goto pc%+d\n",
407                                 insn->code, insn->dst_reg,
408                                 bpf_jmp_string[BPF_OP(insn->code) >> 4],
409                                 insn->imm, insn->off);
410                 }
411         } else {
412                 verbose("(%02x) %s\n", insn->code, bpf_class_string[class]);
413         }
414 }
415
416 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx)
417 {
418         struct bpf_verifier_stack_elem *elem;
419         int insn_idx;
420
421         if (env->head == NULL)
422                 return -1;
423
424         memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state));
425         insn_idx = env->head->insn_idx;
426         if (prev_insn_idx)
427                 *prev_insn_idx = env->head->prev_insn_idx;
428         elem = env->head->next;
429         kfree(env->head);
430         env->head = elem;
431         env->stack_size--;
432         return insn_idx;
433 }
434
435 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
436                                              int insn_idx, int prev_insn_idx)
437 {
438         struct bpf_verifier_stack_elem *elem;
439
440         elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
441         if (!elem)
442                 goto err;
443
444         memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state));
445         elem->insn_idx = insn_idx;
446         elem->prev_insn_idx = prev_insn_idx;
447         elem->next = env->head;
448         env->head = elem;
449         env->stack_size++;
450         if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
451                 verbose("BPF program is too complex\n");
452                 goto err;
453         }
454         return &elem->st;
455 err:
456         /* pop all elements and return */
457         while (pop_stack(env, NULL) >= 0);
458         return NULL;
459 }
460
461 #define CALLER_SAVED_REGS 6
462 static const int caller_saved[CALLER_SAVED_REGS] = {
463         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
464 };
465
466 static void mark_reg_not_init(struct bpf_reg_state *regs, u32 regno)
467 {
468         BUG_ON(regno >= MAX_BPF_REG);
469
470         memset(&regs[regno], 0, sizeof(regs[regno]));
471         regs[regno].type = NOT_INIT;
472         regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
473         regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
474 }
475
476 static void init_reg_state(struct bpf_reg_state *regs)
477 {
478         int i;
479
480         for (i = 0; i < MAX_BPF_REG; i++)
481                 mark_reg_not_init(regs, i);
482
483         /* frame pointer */
484         regs[BPF_REG_FP].type = FRAME_PTR;
485
486         /* 1st arg to a function */
487         regs[BPF_REG_1].type = PTR_TO_CTX;
488 }
489
490 static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
491 {
492         regs[regno].type = UNKNOWN_VALUE;
493         regs[regno].id = 0;
494         regs[regno].imm = 0;
495 }
496
497 static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno)
498 {
499         BUG_ON(regno >= MAX_BPF_REG);
500         __mark_reg_unknown_value(regs, regno);
501 }
502
503 static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno)
504 {
505         regs[regno].min_value = BPF_REGISTER_MIN_RANGE;
506         regs[regno].max_value = BPF_REGISTER_MAX_RANGE;
507         regs[regno].min_align = 0;
508 }
509
510 static void mark_reg_unknown_value_and_range(struct bpf_reg_state *regs,
511                                              u32 regno)
512 {
513         mark_reg_unknown_value(regs, regno);
514         reset_reg_range_values(regs, regno);
515 }
516
517 enum reg_arg_type {
518         SRC_OP,         /* register is used as source operand */
519         DST_OP,         /* register is used as destination operand */
520         DST_OP_NO_MARK  /* same as above, check only, don't mark */
521 };
522
523 static int check_reg_arg(struct bpf_reg_state *regs, u32 regno,
524                          enum reg_arg_type t)
525 {
526         if (regno >= MAX_BPF_REG) {
527                 verbose("R%d is invalid\n", regno);
528                 return -EINVAL;
529         }
530
531         if (t == SRC_OP) {
532                 /* check whether register used as source operand can be read */
533                 if (regs[regno].type == NOT_INIT) {
534                         verbose("R%d !read_ok\n", regno);
535                         return -EACCES;
536                 }
537         } else {
538                 /* check whether register used as dest operand can be written to */
539                 if (regno == BPF_REG_FP) {
540                         verbose("frame pointer is read only\n");
541                         return -EACCES;
542                 }
543                 if (t == DST_OP)
544                         mark_reg_unknown_value(regs, regno);
545         }
546         return 0;
547 }
548
549 static int bpf_size_to_bytes(int bpf_size)
550 {
551         if (bpf_size == BPF_W)
552                 return 4;
553         else if (bpf_size == BPF_H)
554                 return 2;
555         else if (bpf_size == BPF_B)
556                 return 1;
557         else if (bpf_size == BPF_DW)
558                 return 8;
559         else
560                 return -EINVAL;
561 }
562
563 static bool is_spillable_regtype(enum bpf_reg_type type)
564 {
565         switch (type) {
566         case PTR_TO_MAP_VALUE:
567         case PTR_TO_MAP_VALUE_OR_NULL:
568         case PTR_TO_MAP_VALUE_ADJ:
569         case PTR_TO_STACK:
570         case PTR_TO_CTX:
571         case PTR_TO_PACKET:
572         case PTR_TO_PACKET_END:
573         case FRAME_PTR:
574         case CONST_PTR_TO_MAP:
575                 return true;
576         default:
577                 return false;
578         }
579 }
580
581 /* check_stack_read/write functions track spill/fill of registers,
582  * stack boundary and alignment are checked in check_mem_access()
583  */
584 static int check_stack_write(struct bpf_verifier_state *state, int off,
585                              int size, int value_regno)
586 {
587         int i;
588         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
589          * so it's aligned access and [off, off + size) are within stack limits
590          */
591
592         if (value_regno >= 0 &&
593             is_spillable_regtype(state->regs[value_regno].type)) {
594
595                 /* register containing pointer is being spilled into stack */
596                 if (size != BPF_REG_SIZE) {
597                         verbose("invalid size of register spill\n");
598                         return -EACCES;
599                 }
600
601                 /* save register state */
602                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
603                         state->regs[value_regno];
604
605                 for (i = 0; i < BPF_REG_SIZE; i++)
606                         state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL;
607         } else {
608                 /* regular write of data into stack */
609                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] =
610                         (struct bpf_reg_state) {};
611
612                 for (i = 0; i < size; i++)
613                         state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC;
614         }
615         return 0;
616 }
617
618 static int check_stack_read(struct bpf_verifier_state *state, int off, int size,
619                             int value_regno)
620 {
621         u8 *slot_type;
622         int i;
623
624         slot_type = &state->stack_slot_type[MAX_BPF_STACK + off];
625
626         if (slot_type[0] == STACK_SPILL) {
627                 if (size != BPF_REG_SIZE) {
628                         verbose("invalid size of register spill\n");
629                         return -EACCES;
630                 }
631                 for (i = 1; i < BPF_REG_SIZE; i++) {
632                         if (slot_type[i] != STACK_SPILL) {
633                                 verbose("corrupted spill memory\n");
634                                 return -EACCES;
635                         }
636                 }
637
638                 if (value_regno >= 0)
639                         /* restore register state from stack */
640                         state->regs[value_regno] =
641                                 state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE];
642                 return 0;
643         } else {
644                 for (i = 0; i < size; i++) {
645                         if (slot_type[i] != STACK_MISC) {
646                                 verbose("invalid read from stack off %d+%d size %d\n",
647                                         off, i, size);
648                                 return -EACCES;
649                         }
650                 }
651                 if (value_regno >= 0)
652                         /* have read misc data from the stack */
653                         mark_reg_unknown_value_and_range(state->regs,
654                                                          value_regno);
655                 return 0;
656         }
657 }
658
659 /* check read/write into map element returned by bpf_map_lookup_elem() */
660 static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
661                             int size)
662 {
663         struct bpf_map *map = env->cur_state.regs[regno].map_ptr;
664
665         if (off < 0 || size <= 0 || off + size > map->value_size) {
666                 verbose("invalid access to map value, value_size=%d off=%d size=%d\n",
667                         map->value_size, off, size);
668                 return -EACCES;
669         }
670         return 0;
671 }
672
673 /* check read/write into an adjusted map element */
674 static int check_map_access_adj(struct bpf_verifier_env *env, u32 regno,
675                                 int off, int size)
676 {
677         struct bpf_verifier_state *state = &env->cur_state;
678         struct bpf_reg_state *reg = &state->regs[regno];
679         int err;
680
681         /* We adjusted the register to this map value, so we
682          * need to change off and size to min_value and max_value
683          * respectively to make sure our theoretical access will be
684          * safe.
685          */
686         if (log_level)
687                 print_verifier_state(state);
688         env->varlen_map_value_access = true;
689         /* The minimum value is only important with signed
690          * comparisons where we can't assume the floor of a
691          * value is 0.  If we are using signed variables for our
692          * index'es we need to make sure that whatever we use
693          * will have a set floor within our range.
694          */
695         if (reg->min_value < 0) {
696                 verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
697                         regno);
698                 return -EACCES;
699         }
700         err = check_map_access(env, regno, reg->min_value + off, size);
701         if (err) {
702                 verbose("R%d min value is outside of the array range\n",
703                         regno);
704                 return err;
705         }
706
707         /* If we haven't set a max value then we need to bail
708          * since we can't be sure we won't do bad things.
709          */
710         if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
711                 verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n",
712                         regno);
713                 return -EACCES;
714         }
715         return check_map_access(env, regno, reg->max_value + off, size);
716 }
717
718 #define MAX_PACKET_OFF 0xffff
719
720 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
721                                        const struct bpf_call_arg_meta *meta,
722                                        enum bpf_access_type t)
723 {
724         switch (env->prog->type) {
725         case BPF_PROG_TYPE_LWT_IN:
726         case BPF_PROG_TYPE_LWT_OUT:
727                 /* dst_input() and dst_output() can't write for now */
728                 if (t == BPF_WRITE)
729                         return false;
730                 /* fallthrough */
731         case BPF_PROG_TYPE_SCHED_CLS:
732         case BPF_PROG_TYPE_SCHED_ACT:
733         case BPF_PROG_TYPE_XDP:
734         case BPF_PROG_TYPE_LWT_XMIT:
735                 if (meta)
736                         return meta->pkt_access;
737
738                 env->seen_direct_write = true;
739                 return true;
740         default:
741                 return false;
742         }
743 }
744
745 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
746                                int size)
747 {
748         struct bpf_reg_state *regs = env->cur_state.regs;
749         struct bpf_reg_state *reg = &regs[regno];
750
751         off += reg->off;
752         if (off < 0 || size <= 0 || off + size > reg->range) {
753                 verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
754                         off, size, regno, reg->id, reg->off, reg->range);
755                 return -EACCES;
756         }
757         return 0;
758 }
759
760 /* check access to 'struct bpf_context' fields */
761 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
762                             enum bpf_access_type t, enum bpf_reg_type *reg_type)
763 {
764         struct bpf_insn_access_aux info = { .reg_type = *reg_type };
765
766         /* for analyzer ctx accesses are already validated and converted */
767         if (env->analyzer_ops)
768                 return 0;
769
770         if (env->prog->aux->ops->is_valid_access &&
771             env->prog->aux->ops->is_valid_access(off, size, t, &info)) {
772                 /* a non zero info.ctx_field_size indicates:
773                  * . For this field, the prog type specific ctx conversion algorithm
774                  *   only supports whole field access.
775                  * . This ctx access is a candiate for later verifier transformation
776                  *   to load the whole field and then apply a mask to get correct result.
777                  * a non zero info.converted_op_size indicates perceived actual converted
778                  * value width in convert_ctx_access.
779                  */
780                 if ((info.ctx_field_size && !info.converted_op_size) ||
781                     (!info.ctx_field_size &&  info.converted_op_size)) {
782                         verbose("verifier bug in is_valid_access prog type=%u off=%d size=%d\n",
783                                 env->prog->type, off, size);
784                         return -EACCES;
785                 }
786
787                 if (info.ctx_field_size) {
788                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
789                         env->insn_aux_data[insn_idx].converted_op_size = info.converted_op_size;
790                 }
791                 *reg_type = info.reg_type;
792
793                 /* remember the offset of last byte accessed in ctx */
794                 if (env->prog->aux->max_ctx_offset < off + size)
795                         env->prog->aux->max_ctx_offset = off + size;
796                 return 0;
797         }
798
799         verbose("invalid bpf_context access off=%d size=%d\n", off, size);
800         return -EACCES;
801 }
802
803 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
804 {
805         if (env->allow_ptr_leaks)
806                 return false;
807
808         switch (env->cur_state.regs[regno].type) {
809         case UNKNOWN_VALUE:
810         case CONST_IMM:
811                 return false;
812         default:
813                 return true;
814         }
815 }
816
817 static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg,
818                                    int off, int size, bool strict)
819 {
820         int ip_align;
821         int reg_off;
822
823         /* Byte size accesses are always allowed. */
824         if (!strict || size == 1)
825                 return 0;
826
827         reg_off = reg->off;
828         if (reg->id) {
829                 if (reg->aux_off_align % size) {
830                         verbose("Packet access is only %u byte aligned, %d byte access not allowed\n",
831                                 reg->aux_off_align, size);
832                         return -EACCES;
833                 }
834                 reg_off += reg->aux_off;
835         }
836
837         /* For platforms that do not have a Kconfig enabling
838          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
839          * NET_IP_ALIGN is universally set to '2'.  And on platforms
840          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
841          * to this code only in strict mode where we want to emulate
842          * the NET_IP_ALIGN==2 checking.  Therefore use an
843          * unconditional IP align value of '2'.
844          */
845         ip_align = 2;
846         if ((ip_align + reg_off + off) % size != 0) {
847                 verbose("misaligned packet access off %d+%d+%d size %d\n",
848                         ip_align, reg_off, off, size);
849                 return -EACCES;
850         }
851
852         return 0;
853 }
854
855 static int check_val_ptr_alignment(const struct bpf_reg_state *reg,
856                                    int size, bool strict)
857 {
858         if (strict && size != 1) {
859                 verbose("Unknown alignment. Only byte-sized access allowed in value access.\n");
860                 return -EACCES;
861         }
862
863         return 0;
864 }
865
866 static int check_ptr_alignment(struct bpf_verifier_env *env,
867                                const struct bpf_reg_state *reg,
868                                int off, int size)
869 {
870         bool strict = env->strict_alignment;
871
872         switch (reg->type) {
873         case PTR_TO_PACKET:
874                 return check_pkt_ptr_alignment(reg, off, size, strict);
875         case PTR_TO_MAP_VALUE_ADJ:
876                 return check_val_ptr_alignment(reg, size, strict);
877         default:
878                 if (off % size != 0) {
879                         verbose("misaligned access off %d size %d\n",
880                                 off, size);
881                         return -EACCES;
882                 }
883
884                 return 0;
885         }
886 }
887
888 /* check whether memory at (regno + off) is accessible for t = (read | write)
889  * if t==write, value_regno is a register which value is stored into memory
890  * if t==read, value_regno is a register which will receive the value from memory
891  * if t==write && value_regno==-1, some unknown value is stored into memory
892  * if t==read && value_regno==-1, don't care what we read from memory
893  */
894 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, int off,
895                             int bpf_size, enum bpf_access_type t,
896                             int value_regno)
897 {
898         struct bpf_verifier_state *state = &env->cur_state;
899         struct bpf_reg_state *reg = &state->regs[regno];
900         int size, err = 0;
901
902         if (reg->type == PTR_TO_STACK)
903                 off += reg->imm;
904
905         size = bpf_size_to_bytes(bpf_size);
906         if (size < 0)
907                 return size;
908
909         err = check_ptr_alignment(env, reg, off, size);
910         if (err)
911                 return err;
912
913         if (reg->type == PTR_TO_MAP_VALUE ||
914             reg->type == PTR_TO_MAP_VALUE_ADJ) {
915                 if (t == BPF_WRITE && value_regno >= 0 &&
916                     is_pointer_value(env, value_regno)) {
917                         verbose("R%d leaks addr into map\n", value_regno);
918                         return -EACCES;
919                 }
920
921                 if (reg->type == PTR_TO_MAP_VALUE_ADJ)
922                         err = check_map_access_adj(env, regno, off, size);
923                 else
924                         err = check_map_access(env, regno, off, size);
925                 if (!err && t == BPF_READ && value_regno >= 0)
926                         mark_reg_unknown_value_and_range(state->regs,
927                                                          value_regno);
928
929         } else if (reg->type == PTR_TO_CTX) {
930                 enum bpf_reg_type reg_type = UNKNOWN_VALUE;
931
932                 if (t == BPF_WRITE && value_regno >= 0 &&
933                     is_pointer_value(env, value_regno)) {
934                         verbose("R%d leaks addr into ctx\n", value_regno);
935                         return -EACCES;
936                 }
937                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
938                 if (!err && t == BPF_READ && value_regno >= 0) {
939                         mark_reg_unknown_value_and_range(state->regs,
940                                                          value_regno);
941                         /* note that reg.[id|off|range] == 0 */
942                         state->regs[value_regno].type = reg_type;
943                         state->regs[value_regno].aux_off = 0;
944                         state->regs[value_regno].aux_off_align = 0;
945                 }
946
947         } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) {
948                 if (off >= 0 || off < -MAX_BPF_STACK) {
949                         verbose("invalid stack off=%d size=%d\n", off, size);
950                         return -EACCES;
951                 }
952
953                 if (env->prog->aux->stack_depth < -off)
954                         env->prog->aux->stack_depth = -off;
955
956                 if (t == BPF_WRITE) {
957                         if (!env->allow_ptr_leaks &&
958                             state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL &&
959                             size != BPF_REG_SIZE) {
960                                 verbose("attempt to corrupt spilled pointer on stack\n");
961                                 return -EACCES;
962                         }
963                         err = check_stack_write(state, off, size, value_regno);
964                 } else {
965                         err = check_stack_read(state, off, size, value_regno);
966                 }
967         } else if (state->regs[regno].type == PTR_TO_PACKET) {
968                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
969                         verbose("cannot write into packet\n");
970                         return -EACCES;
971                 }
972                 if (t == BPF_WRITE && value_regno >= 0 &&
973                     is_pointer_value(env, value_regno)) {
974                         verbose("R%d leaks addr into packet\n", value_regno);
975                         return -EACCES;
976                 }
977                 err = check_packet_access(env, regno, off, size);
978                 if (!err && t == BPF_READ && value_regno >= 0)
979                         mark_reg_unknown_value_and_range(state->regs,
980                                                          value_regno);
981         } else {
982                 verbose("R%d invalid mem access '%s'\n",
983                         regno, reg_type_str[reg->type]);
984                 return -EACCES;
985         }
986
987         if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks &&
988             state->regs[value_regno].type == UNKNOWN_VALUE) {
989                 /* 1 or 2 byte load zero-extends, determine the number of
990                  * zero upper bits. Not doing it fo 4 byte load, since
991                  * such values cannot be added to ptr_to_packet anyway.
992                  */
993                 state->regs[value_regno].imm = 64 - size * 8;
994         }
995         return err;
996 }
997
998 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
999 {
1000         struct bpf_reg_state *regs = env->cur_state.regs;
1001         int err;
1002
1003         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1004             insn->imm != 0) {
1005                 verbose("BPF_XADD uses reserved fields\n");
1006                 return -EINVAL;
1007         }
1008
1009         /* check src1 operand */
1010         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1011         if (err)
1012                 return err;
1013
1014         /* check src2 operand */
1015         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1016         if (err)
1017                 return err;
1018
1019         if (is_pointer_value(env, insn->src_reg)) {
1020                 verbose("R%d leaks addr into mem\n", insn->src_reg);
1021                 return -EACCES;
1022         }
1023
1024         /* check whether atomic_add can read the memory */
1025         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1026                                BPF_SIZE(insn->code), BPF_READ, -1);
1027         if (err)
1028                 return err;
1029
1030         /* check whether atomic_add can write into the same memory */
1031         return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1032                                 BPF_SIZE(insn->code), BPF_WRITE, -1);
1033 }
1034
1035 /* when register 'regno' is passed into function that will read 'access_size'
1036  * bytes from that pointer, make sure that it's within stack boundary
1037  * and all elements of stack are initialized
1038  */
1039 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1040                                 int access_size, bool zero_size_allowed,
1041                                 struct bpf_call_arg_meta *meta)
1042 {
1043         struct bpf_verifier_state *state = &env->cur_state;
1044         struct bpf_reg_state *regs = state->regs;
1045         int off, i;
1046
1047         if (regs[regno].type != PTR_TO_STACK) {
1048                 if (zero_size_allowed && access_size == 0 &&
1049                     regs[regno].type == CONST_IMM &&
1050                     regs[regno].imm  == 0)
1051                         return 0;
1052
1053                 verbose("R%d type=%s expected=%s\n", regno,
1054                         reg_type_str[regs[regno].type],
1055                         reg_type_str[PTR_TO_STACK]);
1056                 return -EACCES;
1057         }
1058
1059         off = regs[regno].imm;
1060         if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1061             access_size <= 0) {
1062                 verbose("invalid stack type R%d off=%d access_size=%d\n",
1063                         regno, off, access_size);
1064                 return -EACCES;
1065         }
1066
1067         if (env->prog->aux->stack_depth < -off)
1068                 env->prog->aux->stack_depth = -off;
1069
1070         if (meta && meta->raw_mode) {
1071                 meta->access_size = access_size;
1072                 meta->regno = regno;
1073                 return 0;
1074         }
1075
1076         for (i = 0; i < access_size; i++) {
1077                 if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) {
1078                         verbose("invalid indirect read from stack off %d+%d size %d\n",
1079                                 off, i, access_size);
1080                         return -EACCES;
1081                 }
1082         }
1083         return 0;
1084 }
1085
1086 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1087                                    int access_size, bool zero_size_allowed,
1088                                    struct bpf_call_arg_meta *meta)
1089 {
1090         struct bpf_reg_state *regs = env->cur_state.regs;
1091
1092         switch (regs[regno].type) {
1093         case PTR_TO_PACKET:
1094                 return check_packet_access(env, regno, 0, access_size);
1095         case PTR_TO_MAP_VALUE:
1096                 return check_map_access(env, regno, 0, access_size);
1097         case PTR_TO_MAP_VALUE_ADJ:
1098                 return check_map_access_adj(env, regno, 0, access_size);
1099         default: /* const_imm|ptr_to_stack or invalid ptr */
1100                 return check_stack_boundary(env, regno, access_size,
1101                                             zero_size_allowed, meta);
1102         }
1103 }
1104
1105 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1106                           enum bpf_arg_type arg_type,
1107                           struct bpf_call_arg_meta *meta)
1108 {
1109         struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno];
1110         enum bpf_reg_type expected_type, type = reg->type;
1111         int err = 0;
1112
1113         if (arg_type == ARG_DONTCARE)
1114                 return 0;
1115
1116         if (type == NOT_INIT) {
1117                 verbose("R%d !read_ok\n", regno);
1118                 return -EACCES;
1119         }
1120
1121         if (arg_type == ARG_ANYTHING) {
1122                 if (is_pointer_value(env, regno)) {
1123                         verbose("R%d leaks addr into helper function\n", regno);
1124                         return -EACCES;
1125                 }
1126                 return 0;
1127         }
1128
1129         if (type == PTR_TO_PACKET &&
1130             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1131                 verbose("helper access to the packet is not allowed\n");
1132                 return -EACCES;
1133         }
1134
1135         if (arg_type == ARG_PTR_TO_MAP_KEY ||
1136             arg_type == ARG_PTR_TO_MAP_VALUE) {
1137                 expected_type = PTR_TO_STACK;
1138                 if (type != PTR_TO_PACKET && type != expected_type)
1139                         goto err_type;
1140         } else if (arg_type == ARG_CONST_SIZE ||
1141                    arg_type == ARG_CONST_SIZE_OR_ZERO) {
1142                 expected_type = CONST_IMM;
1143                 /* One exception. Allow UNKNOWN_VALUE registers when the
1144                  * boundaries are known and don't cause unsafe memory accesses
1145                  */
1146                 if (type != UNKNOWN_VALUE && type != expected_type)
1147                         goto err_type;
1148         } else if (arg_type == ARG_CONST_MAP_PTR) {
1149                 expected_type = CONST_PTR_TO_MAP;
1150                 if (type != expected_type)
1151                         goto err_type;
1152         } else if (arg_type == ARG_PTR_TO_CTX) {
1153                 expected_type = PTR_TO_CTX;
1154                 if (type != expected_type)
1155                         goto err_type;
1156         } else if (arg_type == ARG_PTR_TO_MEM ||
1157                    arg_type == ARG_PTR_TO_UNINIT_MEM) {
1158                 expected_type = PTR_TO_STACK;
1159                 /* One exception here. In case function allows for NULL to be
1160                  * passed in as argument, it's a CONST_IMM type. Final test
1161                  * happens during stack boundary checking.
1162                  */
1163                 if (type == CONST_IMM && reg->imm == 0)
1164                         /* final test in check_stack_boundary() */;
1165                 else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE &&
1166                          type != PTR_TO_MAP_VALUE_ADJ && type != expected_type)
1167                         goto err_type;
1168                 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1169         } else {
1170                 verbose("unsupported arg_type %d\n", arg_type);
1171                 return -EFAULT;
1172         }
1173
1174         if (arg_type == ARG_CONST_MAP_PTR) {
1175                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1176                 meta->map_ptr = reg->map_ptr;
1177         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1178                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1179                  * check that [key, key + map->key_size) are within
1180                  * stack limits and initialized
1181                  */
1182                 if (!meta->map_ptr) {
1183                         /* in function declaration map_ptr must come before
1184                          * map_key, so that it's verified and known before
1185                          * we have to check map_key here. Otherwise it means
1186                          * that kernel subsystem misconfigured verifier
1187                          */
1188                         verbose("invalid map_ptr to access map->key\n");
1189                         return -EACCES;
1190                 }
1191                 if (type == PTR_TO_PACKET)
1192                         err = check_packet_access(env, regno, 0,
1193                                                   meta->map_ptr->key_size);
1194                 else
1195                         err = check_stack_boundary(env, regno,
1196                                                    meta->map_ptr->key_size,
1197                                                    false, NULL);
1198         } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1199                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1200                  * check [value, value + map->value_size) validity
1201                  */
1202                 if (!meta->map_ptr) {
1203                         /* kernel subsystem misconfigured verifier */
1204                         verbose("invalid map_ptr to access map->value\n");
1205                         return -EACCES;
1206                 }
1207                 if (type == PTR_TO_PACKET)
1208                         err = check_packet_access(env, regno, 0,
1209                                                   meta->map_ptr->value_size);
1210                 else
1211                         err = check_stack_boundary(env, regno,
1212                                                    meta->map_ptr->value_size,
1213                                                    false, NULL);
1214         } else if (arg_type == ARG_CONST_SIZE ||
1215                    arg_type == ARG_CONST_SIZE_OR_ZERO) {
1216                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1217
1218                 /* bpf_xxx(..., buf, len) call will access 'len' bytes
1219                  * from stack pointer 'buf'. Check it
1220                  * note: regno == len, regno - 1 == buf
1221                  */
1222                 if (regno == 0) {
1223                         /* kernel subsystem misconfigured verifier */
1224                         verbose("ARG_CONST_SIZE cannot be first argument\n");
1225                         return -EACCES;
1226                 }
1227
1228                 /* If the register is UNKNOWN_VALUE, the access check happens
1229                  * using its boundaries. Otherwise, just use its imm
1230                  */
1231                 if (type == UNKNOWN_VALUE) {
1232                         /* For unprivileged variable accesses, disable raw
1233                          * mode so that the program is required to
1234                          * initialize all the memory that the helper could
1235                          * just partially fill up.
1236                          */
1237                         meta = NULL;
1238
1239                         if (reg->min_value < 0) {
1240                                 verbose("R%d min value is negative, either use unsigned or 'var &= const'\n",
1241                                         regno);
1242                                 return -EACCES;
1243                         }
1244
1245                         if (reg->min_value == 0) {
1246                                 err = check_helper_mem_access(env, regno - 1, 0,
1247                                                               zero_size_allowed,
1248                                                               meta);
1249                                 if (err)
1250                                         return err;
1251                         }
1252
1253                         if (reg->max_value == BPF_REGISTER_MAX_RANGE) {
1254                                 verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
1255                                         regno);
1256                                 return -EACCES;
1257                         }
1258                         err = check_helper_mem_access(env, regno - 1,
1259                                                       reg->max_value,
1260                                                       zero_size_allowed, meta);
1261                         if (err)
1262                                 return err;
1263                 } else {
1264                         /* register is CONST_IMM */
1265                         err = check_helper_mem_access(env, regno - 1, reg->imm,
1266                                                       zero_size_allowed, meta);
1267                 }
1268         }
1269
1270         return err;
1271 err_type:
1272         verbose("R%d type=%s expected=%s\n", regno,
1273                 reg_type_str[type], reg_type_str[expected_type]);
1274         return -EACCES;
1275 }
1276
1277 static int check_map_func_compatibility(struct bpf_map *map, int func_id)
1278 {
1279         if (!map)
1280                 return 0;
1281
1282         /* We need a two way check, first is from map perspective ... */
1283         switch (map->map_type) {
1284         case BPF_MAP_TYPE_PROG_ARRAY:
1285                 if (func_id != BPF_FUNC_tail_call)
1286                         goto error;
1287                 break;
1288         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1289                 if (func_id != BPF_FUNC_perf_event_read &&
1290                     func_id != BPF_FUNC_perf_event_output)
1291                         goto error;
1292                 break;
1293         case BPF_MAP_TYPE_STACK_TRACE:
1294                 if (func_id != BPF_FUNC_get_stackid)
1295                         goto error;
1296                 break;
1297         case BPF_MAP_TYPE_CGROUP_ARRAY:
1298                 if (func_id != BPF_FUNC_skb_under_cgroup &&
1299                     func_id != BPF_FUNC_current_task_under_cgroup)
1300                         goto error;
1301                 break;
1302         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1303         case BPF_MAP_TYPE_HASH_OF_MAPS:
1304                 if (func_id != BPF_FUNC_map_lookup_elem)
1305                         goto error;
1306         default:
1307                 break;
1308         }
1309
1310         /* ... and second from the function itself. */
1311         switch (func_id) {
1312         case BPF_FUNC_tail_call:
1313                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1314                         goto error;
1315                 break;
1316         case BPF_FUNC_perf_event_read:
1317         case BPF_FUNC_perf_event_output:
1318                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
1319                         goto error;
1320                 break;
1321         case BPF_FUNC_get_stackid:
1322                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
1323                         goto error;
1324                 break;
1325         case BPF_FUNC_current_task_under_cgroup:
1326         case BPF_FUNC_skb_under_cgroup:
1327                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
1328                         goto error;
1329                 break;
1330         default:
1331                 break;
1332         }
1333
1334         return 0;
1335 error:
1336         verbose("cannot pass map_type %d into func %s#%d\n",
1337                 map->map_type, func_id_name(func_id), func_id);
1338         return -EINVAL;
1339 }
1340
1341 static int check_raw_mode(const struct bpf_func_proto *fn)
1342 {
1343         int count = 0;
1344
1345         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
1346                 count++;
1347         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
1348                 count++;
1349         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
1350                 count++;
1351         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
1352                 count++;
1353         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
1354                 count++;
1355
1356         return count > 1 ? -EINVAL : 0;
1357 }
1358
1359 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
1360 {
1361         struct bpf_verifier_state *state = &env->cur_state;
1362         struct bpf_reg_state *regs = state->regs, *reg;
1363         int i;
1364
1365         for (i = 0; i < MAX_BPF_REG; i++)
1366                 if (regs[i].type == PTR_TO_PACKET ||
1367                     regs[i].type == PTR_TO_PACKET_END)
1368                         mark_reg_unknown_value(regs, i);
1369
1370         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
1371                 if (state->stack_slot_type[i] != STACK_SPILL)
1372                         continue;
1373                 reg = &state->spilled_regs[i / BPF_REG_SIZE];
1374                 if (reg->type != PTR_TO_PACKET &&
1375                     reg->type != PTR_TO_PACKET_END)
1376                         continue;
1377                 __mark_reg_unknown_value(state->spilled_regs,
1378                                          i / BPF_REG_SIZE);
1379         }
1380 }
1381
1382 static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
1383 {
1384         struct bpf_verifier_state *state = &env->cur_state;
1385         const struct bpf_func_proto *fn = NULL;
1386         struct bpf_reg_state *regs = state->regs;
1387         struct bpf_call_arg_meta meta;
1388         bool changes_data;
1389         int i, err;
1390
1391         /* find function prototype */
1392         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
1393                 verbose("invalid func %s#%d\n", func_id_name(func_id), func_id);
1394                 return -EINVAL;
1395         }
1396
1397         if (env->prog->aux->ops->get_func_proto)
1398                 fn = env->prog->aux->ops->get_func_proto(func_id);
1399
1400         if (!fn) {
1401                 verbose("unknown func %s#%d\n", func_id_name(func_id), func_id);
1402                 return -EINVAL;
1403         }
1404
1405         /* eBPF programs must be GPL compatible to use GPL-ed functions */
1406         if (!env->prog->gpl_compatible && fn->gpl_only) {
1407                 verbose("cannot call GPL only function from proprietary program\n");
1408                 return -EINVAL;
1409         }
1410
1411         changes_data = bpf_helper_changes_pkt_data(fn->func);
1412
1413         memset(&meta, 0, sizeof(meta));
1414         meta.pkt_access = fn->pkt_access;
1415
1416         /* We only support one arg being in raw mode at the moment, which
1417          * is sufficient for the helper functions we have right now.
1418          */
1419         err = check_raw_mode(fn);
1420         if (err) {
1421                 verbose("kernel subsystem misconfigured func %s#%d\n",
1422                         func_id_name(func_id), func_id);
1423                 return err;
1424         }
1425
1426         /* check args */
1427         err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
1428         if (err)
1429                 return err;
1430         err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
1431         if (err)
1432                 return err;
1433         err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
1434         if (err)
1435                 return err;
1436         err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
1437         if (err)
1438                 return err;
1439         err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
1440         if (err)
1441                 return err;
1442
1443         /* Mark slots with STACK_MISC in case of raw mode, stack offset
1444          * is inferred from register state.
1445          */
1446         for (i = 0; i < meta.access_size; i++) {
1447                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, BPF_WRITE, -1);
1448                 if (err)
1449                         return err;
1450         }
1451
1452         /* reset caller saved regs */
1453         for (i = 0; i < CALLER_SAVED_REGS; i++)
1454                 mark_reg_not_init(regs, caller_saved[i]);
1455
1456         /* update return register */
1457         if (fn->ret_type == RET_INTEGER) {
1458                 regs[BPF_REG_0].type = UNKNOWN_VALUE;
1459         } else if (fn->ret_type == RET_VOID) {
1460                 regs[BPF_REG_0].type = NOT_INIT;
1461         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
1462                 struct bpf_insn_aux_data *insn_aux;
1463
1464                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
1465                 regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0;
1466                 /* remember map_ptr, so that check_map_access()
1467                  * can check 'value_size' boundary of memory access
1468                  * to map element returned from bpf_map_lookup_elem()
1469                  */
1470                 if (meta.map_ptr == NULL) {
1471                         verbose("kernel subsystem misconfigured verifier\n");
1472                         return -EINVAL;
1473                 }
1474                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
1475                 regs[BPF_REG_0].id = ++env->id_gen;
1476                 insn_aux = &env->insn_aux_data[insn_idx];
1477                 if (!insn_aux->map_ptr)
1478                         insn_aux->map_ptr = meta.map_ptr;
1479                 else if (insn_aux->map_ptr != meta.map_ptr)
1480                         insn_aux->map_ptr = BPF_MAP_PTR_POISON;
1481         } else {
1482                 verbose("unknown return type %d of func %s#%d\n",
1483                         fn->ret_type, func_id_name(func_id), func_id);
1484                 return -EINVAL;
1485         }
1486
1487         err = check_map_func_compatibility(meta.map_ptr, func_id);
1488         if (err)
1489                 return err;
1490
1491         if (changes_data)
1492                 clear_all_pkt_pointers(env);
1493         return 0;
1494 }
1495
1496 static int check_packet_ptr_add(struct bpf_verifier_env *env,
1497                                 struct bpf_insn *insn)
1498 {
1499         struct bpf_reg_state *regs = env->cur_state.regs;
1500         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1501         struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1502         struct bpf_reg_state tmp_reg;
1503         s32 imm;
1504
1505         if (BPF_SRC(insn->code) == BPF_K) {
1506                 /* pkt_ptr += imm */
1507                 imm = insn->imm;
1508
1509 add_imm:
1510                 if (imm < 0) {
1511                         verbose("addition of negative constant to packet pointer is not allowed\n");
1512                         return -EACCES;
1513                 }
1514                 if (imm >= MAX_PACKET_OFF ||
1515                     imm + dst_reg->off >= MAX_PACKET_OFF) {
1516                         verbose("constant %d is too large to add to packet pointer\n",
1517                                 imm);
1518                         return -EACCES;
1519                 }
1520                 /* a constant was added to pkt_ptr.
1521                  * Remember it while keeping the same 'id'
1522                  */
1523                 dst_reg->off += imm;
1524         } else {
1525                 bool had_id;
1526
1527                 if (src_reg->type == PTR_TO_PACKET) {
1528                         /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */
1529                         tmp_reg = *dst_reg;  /* save r7 state */
1530                         *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */
1531                         src_reg = &tmp_reg;  /* pretend it's src_reg state */
1532                         /* if the checks below reject it, the copy won't matter,
1533                          * since we're rejecting the whole program. If all ok,
1534                          * then imm22 state will be added to r7
1535                          * and r7 will be pkt(id=0,off=22,r=62) while
1536                          * r6 will stay as pkt(id=0,off=0,r=62)
1537                          */
1538                 }
1539
1540                 if (src_reg->type == CONST_IMM) {
1541                         /* pkt_ptr += reg where reg is known constant */
1542                         imm = src_reg->imm;
1543                         goto add_imm;
1544                 }
1545                 /* disallow pkt_ptr += reg
1546                  * if reg is not uknown_value with guaranteed zero upper bits
1547                  * otherwise pkt_ptr may overflow and addition will become
1548                  * subtraction which is not allowed
1549                  */
1550                 if (src_reg->type != UNKNOWN_VALUE) {
1551                         verbose("cannot add '%s' to ptr_to_packet\n",
1552                                 reg_type_str[src_reg->type]);
1553                         return -EACCES;
1554                 }
1555                 if (src_reg->imm < 48) {
1556                         verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n",
1557                                 src_reg->imm);
1558                         return -EACCES;
1559                 }
1560
1561                 had_id = (dst_reg->id != 0);
1562
1563                 /* dst_reg stays as pkt_ptr type and since some positive
1564                  * integer value was added to the pointer, increment its 'id'
1565                  */
1566                 dst_reg->id = ++env->id_gen;
1567
1568                 /* something was added to pkt_ptr, set range to zero */
1569                 dst_reg->aux_off += dst_reg->off;
1570                 dst_reg->off = 0;
1571                 dst_reg->range = 0;
1572                 if (had_id)
1573                         dst_reg->aux_off_align = min(dst_reg->aux_off_align,
1574                                                      src_reg->min_align);
1575                 else
1576                         dst_reg->aux_off_align = src_reg->min_align;
1577         }
1578         return 0;
1579 }
1580
1581 static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn)
1582 {
1583         struct bpf_reg_state *regs = env->cur_state.regs;
1584         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1585         u8 opcode = BPF_OP(insn->code);
1586         s64 imm_log2;
1587
1588         /* for type == UNKNOWN_VALUE:
1589          * imm > 0 -> number of zero upper bits
1590          * imm == 0 -> don't track which is the same as all bits can be non-zero
1591          */
1592
1593         if (BPF_SRC(insn->code) == BPF_X) {
1594                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1595
1596                 if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 &&
1597                     dst_reg->imm && opcode == BPF_ADD) {
1598                         /* dreg += sreg
1599                          * where both have zero upper bits. Adding them
1600                          * can only result making one more bit non-zero
1601                          * in the larger value.
1602                          * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47)
1603                          *     0xffff (imm=48) + 0xffff = 0x1fffe (imm=47)
1604                          */
1605                         dst_reg->imm = min(dst_reg->imm, src_reg->imm);
1606                         dst_reg->imm--;
1607                         return 0;
1608                 }
1609                 if (src_reg->type == CONST_IMM && src_reg->imm > 0 &&
1610                     dst_reg->imm && opcode == BPF_ADD) {
1611                         /* dreg += sreg
1612                          * where dreg has zero upper bits and sreg is const.
1613                          * Adding them can only result making one more bit
1614                          * non-zero in the larger value.
1615                          */
1616                         imm_log2 = __ilog2_u64((long long)src_reg->imm);
1617                         dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1618                         dst_reg->imm--;
1619                         return 0;
1620                 }
1621                 /* all other cases non supported yet, just mark dst_reg */
1622                 dst_reg->imm = 0;
1623                 return 0;
1624         }
1625
1626         /* sign extend 32-bit imm into 64-bit to make sure that
1627          * negative values occupy bit 63. Note ilog2() would have
1628          * been incorrect, since sizeof(insn->imm) == 4
1629          */
1630         imm_log2 = __ilog2_u64((long long)insn->imm);
1631
1632         if (dst_reg->imm && opcode == BPF_LSH) {
1633                 /* reg <<= imm
1634                  * if reg was a result of 2 byte load, then its imm == 48
1635                  * which means that upper 48 bits are zero and shifting this reg
1636                  * left by 4 would mean that upper 44 bits are still zero
1637                  */
1638                 dst_reg->imm -= insn->imm;
1639         } else if (dst_reg->imm && opcode == BPF_MUL) {
1640                 /* reg *= imm
1641                  * if multiplying by 14 subtract 4
1642                  * This is conservative calculation of upper zero bits.
1643                  * It's not trying to special case insn->imm == 1 or 0 cases
1644                  */
1645                 dst_reg->imm -= imm_log2 + 1;
1646         } else if (opcode == BPF_AND) {
1647                 /* reg &= imm */
1648                 dst_reg->imm = 63 - imm_log2;
1649         } else if (dst_reg->imm && opcode == BPF_ADD) {
1650                 /* reg += imm */
1651                 dst_reg->imm = min(dst_reg->imm, 63 - imm_log2);
1652                 dst_reg->imm--;
1653         } else if (opcode == BPF_RSH) {
1654                 /* reg >>= imm
1655                  * which means that after right shift, upper bits will be zero
1656                  * note that verifier already checked that
1657                  * 0 <= imm < 64 for shift insn
1658                  */
1659                 dst_reg->imm += insn->imm;
1660                 if (unlikely(dst_reg->imm > 64))
1661                         /* some dumb code did:
1662                          * r2 = *(u32 *)mem;
1663                          * r2 >>= 32;
1664                          * and all bits are zero now */
1665                         dst_reg->imm = 64;
1666         } else {
1667                 /* all other alu ops, means that we don't know what will
1668                  * happen to the value, mark it with unknown number of zero bits
1669                  */
1670                 dst_reg->imm = 0;
1671         }
1672
1673         if (dst_reg->imm < 0) {
1674                 /* all 64 bits of the register can contain non-zero bits
1675                  * and such value cannot be added to ptr_to_packet, since it
1676                  * may overflow, mark it as unknown to avoid further eval
1677                  */
1678                 dst_reg->imm = 0;
1679         }
1680         return 0;
1681 }
1682
1683 static int evaluate_reg_imm_alu(struct bpf_verifier_env *env,
1684                                 struct bpf_insn *insn)
1685 {
1686         struct bpf_reg_state *regs = env->cur_state.regs;
1687         struct bpf_reg_state *dst_reg = &regs[insn->dst_reg];
1688         struct bpf_reg_state *src_reg = &regs[insn->src_reg];
1689         u8 opcode = BPF_OP(insn->code);
1690         u64 dst_imm = dst_reg->imm;
1691
1692         /* dst_reg->type == CONST_IMM here. Simulate execution of insns
1693          * containing ALU ops. Don't care about overflow or negative
1694          * values, just add/sub/... them; registers are in u64.
1695          */
1696         if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K) {
1697                 dst_imm += insn->imm;
1698         } else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X &&
1699                    src_reg->type == CONST_IMM) {
1700                 dst_imm += src_reg->imm;
1701         } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_K) {
1702                 dst_imm -= insn->imm;
1703         } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_X &&
1704                    src_reg->type == CONST_IMM) {
1705                 dst_imm -= src_reg->imm;
1706         } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_K) {
1707                 dst_imm *= insn->imm;
1708         } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_X &&
1709                    src_reg->type == CONST_IMM) {
1710                 dst_imm *= src_reg->imm;
1711         } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_K) {
1712                 dst_imm |= insn->imm;
1713         } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_X &&
1714                    src_reg->type == CONST_IMM) {
1715                 dst_imm |= src_reg->imm;
1716         } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_K) {
1717                 dst_imm &= insn->imm;
1718         } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_X &&
1719                    src_reg->type == CONST_IMM) {
1720                 dst_imm &= src_reg->imm;
1721         } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_K) {
1722                 dst_imm >>= insn->imm;
1723         } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_X &&
1724                    src_reg->type == CONST_IMM) {
1725                 dst_imm >>= src_reg->imm;
1726         } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_K) {
1727                 dst_imm <<= insn->imm;
1728         } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_X &&
1729                    src_reg->type == CONST_IMM) {
1730                 dst_imm <<= src_reg->imm;
1731         } else {
1732                 mark_reg_unknown_value(regs, insn->dst_reg);
1733                 goto out;
1734         }
1735
1736         dst_reg->imm = dst_imm;
1737 out:
1738         return 0;
1739 }
1740
1741 static void check_reg_overflow(struct bpf_reg_state *reg)
1742 {
1743         if (reg->max_value > BPF_REGISTER_MAX_RANGE)
1744                 reg->max_value = BPF_REGISTER_MAX_RANGE;
1745         if (reg->min_value < BPF_REGISTER_MIN_RANGE ||
1746             reg->min_value > BPF_REGISTER_MAX_RANGE)
1747                 reg->min_value = BPF_REGISTER_MIN_RANGE;
1748 }
1749
1750 static u32 calc_align(u32 imm)
1751 {
1752         if (!imm)
1753                 return 1U << 31;
1754         return imm - ((imm - 1) & imm);
1755 }
1756
1757 static void adjust_reg_min_max_vals(struct bpf_verifier_env *env,
1758                                     struct bpf_insn *insn)
1759 {
1760         struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1761         s64 min_val = BPF_REGISTER_MIN_RANGE;
1762         u64 max_val = BPF_REGISTER_MAX_RANGE;
1763         u8 opcode = BPF_OP(insn->code);
1764         u32 dst_align, src_align;
1765
1766         dst_reg = &regs[insn->dst_reg];
1767         src_align = 0;
1768         if (BPF_SRC(insn->code) == BPF_X) {
1769                 check_reg_overflow(&regs[insn->src_reg]);
1770                 min_val = regs[insn->src_reg].min_value;
1771                 max_val = regs[insn->src_reg].max_value;
1772
1773                 /* If the source register is a random pointer then the
1774                  * min_value/max_value values represent the range of the known
1775                  * accesses into that value, not the actual min/max value of the
1776                  * register itself.  In this case we have to reset the reg range
1777                  * values so we know it is not safe to look at.
1778                  */
1779                 if (regs[insn->src_reg].type != CONST_IMM &&
1780                     regs[insn->src_reg].type != UNKNOWN_VALUE) {
1781                         min_val = BPF_REGISTER_MIN_RANGE;
1782                         max_val = BPF_REGISTER_MAX_RANGE;
1783                         src_align = 0;
1784                 } else {
1785                         src_align = regs[insn->src_reg].min_align;
1786                 }
1787         } else if (insn->imm < BPF_REGISTER_MAX_RANGE &&
1788                    (s64)insn->imm > BPF_REGISTER_MIN_RANGE) {
1789                 min_val = max_val = insn->imm;
1790                 src_align = calc_align(insn->imm);
1791         }
1792
1793         dst_align = dst_reg->min_align;
1794
1795         /* We don't know anything about what was done to this register, mark it
1796          * as unknown.
1797          */
1798         if (min_val == BPF_REGISTER_MIN_RANGE &&
1799             max_val == BPF_REGISTER_MAX_RANGE) {
1800                 reset_reg_range_values(regs, insn->dst_reg);
1801                 return;
1802         }
1803
1804         /* If one of our values was at the end of our ranges then we can't just
1805          * do our normal operations to the register, we need to set the values
1806          * to the min/max since they are undefined.
1807          */
1808         if (min_val == BPF_REGISTER_MIN_RANGE)
1809                 dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1810         if (max_val == BPF_REGISTER_MAX_RANGE)
1811                 dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1812
1813         switch (opcode) {
1814         case BPF_ADD:
1815                 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1816                         dst_reg->min_value += min_val;
1817                 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1818                         dst_reg->max_value += max_val;
1819                 dst_reg->min_align = min(src_align, dst_align);
1820                 break;
1821         case BPF_SUB:
1822                 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1823                         dst_reg->min_value -= min_val;
1824                 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1825                         dst_reg->max_value -= max_val;
1826                 dst_reg->min_align = min(src_align, dst_align);
1827                 break;
1828         case BPF_MUL:
1829                 if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1830                         dst_reg->min_value *= min_val;
1831                 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1832                         dst_reg->max_value *= max_val;
1833                 dst_reg->min_align = max(src_align, dst_align);
1834                 break;
1835         case BPF_AND:
1836                 /* Disallow AND'ing of negative numbers, ain't nobody got time
1837                  * for that.  Otherwise the minimum is 0 and the max is the max
1838                  * value we could AND against.
1839                  */
1840                 if (min_val < 0)
1841                         dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1842                 else
1843                         dst_reg->min_value = 0;
1844                 dst_reg->max_value = max_val;
1845                 dst_reg->min_align = max(src_align, dst_align);
1846                 break;
1847         case BPF_LSH:
1848                 /* Gotta have special overflow logic here, if we're shifting
1849                  * more than MAX_RANGE then just assume we have an invalid
1850                  * range.
1851                  */
1852                 if (min_val > ilog2(BPF_REGISTER_MAX_RANGE)) {
1853                         dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1854                         dst_reg->min_align = 1;
1855                 } else {
1856                         if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE)
1857                                 dst_reg->min_value <<= min_val;
1858                         if (!dst_reg->min_align)
1859                                 dst_reg->min_align = 1;
1860                         dst_reg->min_align <<= min_val;
1861                 }
1862                 if (max_val > ilog2(BPF_REGISTER_MAX_RANGE))
1863                         dst_reg->max_value = BPF_REGISTER_MAX_RANGE;
1864                 else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1865                         dst_reg->max_value <<= max_val;
1866                 break;
1867         case BPF_RSH:
1868                 /* RSH by a negative number is undefined, and the BPF_RSH is an
1869                  * unsigned shift, so make the appropriate casts.
1870                  */
1871                 if (min_val < 0 || dst_reg->min_value < 0) {
1872                         dst_reg->min_value = BPF_REGISTER_MIN_RANGE;
1873                 } else {
1874                         dst_reg->min_value =
1875                                 (u64)(dst_reg->min_value) >> min_val;
1876                 }
1877                 if (min_val < 0) {
1878                         dst_reg->min_align = 1;
1879                 } else {
1880                         dst_reg->min_align >>= (u64) min_val;
1881                         if (!dst_reg->min_align)
1882                                 dst_reg->min_align = 1;
1883                 }
1884                 if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE)
1885                         dst_reg->max_value >>= max_val;
1886                 break;
1887         default:
1888                 reset_reg_range_values(regs, insn->dst_reg);
1889                 break;
1890         }
1891
1892         check_reg_overflow(dst_reg);
1893 }
1894
1895 /* check validity of 32-bit and 64-bit arithmetic operations */
1896 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
1897 {
1898         struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg;
1899         u8 opcode = BPF_OP(insn->code);
1900         int err;
1901
1902         if (opcode == BPF_END || opcode == BPF_NEG) {
1903                 if (opcode == BPF_NEG) {
1904                         if (BPF_SRC(insn->code) != 0 ||
1905                             insn->src_reg != BPF_REG_0 ||
1906                             insn->off != 0 || insn->imm != 0) {
1907                                 verbose("BPF_NEG uses reserved fields\n");
1908                                 return -EINVAL;
1909                         }
1910                 } else {
1911                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
1912                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) {
1913                                 verbose("BPF_END uses reserved fields\n");
1914                                 return -EINVAL;
1915                         }
1916                 }
1917
1918                 /* check src operand */
1919                 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
1920                 if (err)
1921                         return err;
1922
1923                 if (is_pointer_value(env, insn->dst_reg)) {
1924                         verbose("R%d pointer arithmetic prohibited\n",
1925                                 insn->dst_reg);
1926                         return -EACCES;
1927                 }
1928
1929                 /* check dest operand */
1930                 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1931                 if (err)
1932                         return err;
1933
1934         } else if (opcode == BPF_MOV) {
1935
1936                 if (BPF_SRC(insn->code) == BPF_X) {
1937                         if (insn->imm != 0 || insn->off != 0) {
1938                                 verbose("BPF_MOV uses reserved fields\n");
1939                                 return -EINVAL;
1940                         }
1941
1942                         /* check src operand */
1943                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
1944                         if (err)
1945                                 return err;
1946                 } else {
1947                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
1948                                 verbose("BPF_MOV uses reserved fields\n");
1949                                 return -EINVAL;
1950                         }
1951                 }
1952
1953                 /* check dest operand */
1954                 err = check_reg_arg(regs, insn->dst_reg, DST_OP);
1955                 if (err)
1956                         return err;
1957
1958                 /* we are setting our register to something new, we need to
1959                  * reset its range values.
1960                  */
1961                 reset_reg_range_values(regs, insn->dst_reg);
1962
1963                 if (BPF_SRC(insn->code) == BPF_X) {
1964                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
1965                                 /* case: R1 = R2
1966                                  * copy register state to dest reg
1967                                  */
1968                                 regs[insn->dst_reg] = regs[insn->src_reg];
1969                         } else {
1970                                 if (is_pointer_value(env, insn->src_reg)) {
1971                                         verbose("R%d partial copy of pointer\n",
1972                                                 insn->src_reg);
1973                                         return -EACCES;
1974                                 }
1975                                 mark_reg_unknown_value(regs, insn->dst_reg);
1976                         }
1977                 } else {
1978                         /* case: R = imm
1979                          * remember the value we stored into this reg
1980                          */
1981                         regs[insn->dst_reg].type = CONST_IMM;
1982                         regs[insn->dst_reg].imm = insn->imm;
1983                         regs[insn->dst_reg].id = 0;
1984                         regs[insn->dst_reg].max_value = insn->imm;
1985                         regs[insn->dst_reg].min_value = insn->imm;
1986                         regs[insn->dst_reg].min_align = calc_align(insn->imm);
1987                 }
1988
1989         } else if (opcode > BPF_END) {
1990                 verbose("invalid BPF_ALU opcode %x\n", opcode);
1991                 return -EINVAL;
1992
1993         } else {        /* all other ALU ops: and, sub, xor, add, ... */
1994
1995                 if (BPF_SRC(insn->code) == BPF_X) {
1996                         if (insn->imm != 0 || insn->off != 0) {
1997                                 verbose("BPF_ALU uses reserved fields\n");
1998                                 return -EINVAL;
1999                         }
2000                         /* check src1 operand */
2001                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2002                         if (err)
2003                                 return err;
2004                 } else {
2005                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2006                                 verbose("BPF_ALU uses reserved fields\n");
2007                                 return -EINVAL;
2008                         }
2009                 }
2010
2011                 /* check src2 operand */
2012                 err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2013                 if (err)
2014                         return err;
2015
2016                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2017                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
2018                         verbose("div by zero\n");
2019                         return -EINVAL;
2020                 }
2021
2022                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2023                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2024                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2025
2026                         if (insn->imm < 0 || insn->imm >= size) {
2027                                 verbose("invalid shift %d\n", insn->imm);
2028                                 return -EINVAL;
2029                         }
2030                 }
2031
2032                 /* check dest operand */
2033                 err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
2034                 if (err)
2035                         return err;
2036
2037                 dst_reg = &regs[insn->dst_reg];
2038
2039                 /* first we want to adjust our ranges. */
2040                 adjust_reg_min_max_vals(env, insn);
2041
2042                 /* pattern match 'bpf_add Rx, imm' instruction */
2043                 if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 &&
2044                     dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) {
2045                         dst_reg->type = PTR_TO_STACK;
2046                         dst_reg->imm = insn->imm;
2047                         return 0;
2048                 } else if (opcode == BPF_ADD &&
2049                            BPF_CLASS(insn->code) == BPF_ALU64 &&
2050                            dst_reg->type == PTR_TO_STACK &&
2051                            ((BPF_SRC(insn->code) == BPF_X &&
2052                              regs[insn->src_reg].type == CONST_IMM) ||
2053                             BPF_SRC(insn->code) == BPF_K)) {
2054                         if (BPF_SRC(insn->code) == BPF_X)
2055                                 dst_reg->imm += regs[insn->src_reg].imm;
2056                         else
2057                                 dst_reg->imm += insn->imm;
2058                         return 0;
2059                 } else if (opcode == BPF_ADD &&
2060                            BPF_CLASS(insn->code) == BPF_ALU64 &&
2061                            (dst_reg->type == PTR_TO_PACKET ||
2062                             (BPF_SRC(insn->code) == BPF_X &&
2063                              regs[insn->src_reg].type == PTR_TO_PACKET))) {
2064                         /* ptr_to_packet += K|X */
2065                         return check_packet_ptr_add(env, insn);
2066                 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
2067                            dst_reg->type == UNKNOWN_VALUE &&
2068                            env->allow_ptr_leaks) {
2069                         /* unknown += K|X */
2070                         return evaluate_reg_alu(env, insn);
2071                 } else if (BPF_CLASS(insn->code) == BPF_ALU64 &&
2072                            dst_reg->type == CONST_IMM &&
2073                            env->allow_ptr_leaks) {
2074                         /* reg_imm += K|X */
2075                         return evaluate_reg_imm_alu(env, insn);
2076                 } else if (is_pointer_value(env, insn->dst_reg)) {
2077                         verbose("R%d pointer arithmetic prohibited\n",
2078                                 insn->dst_reg);
2079                         return -EACCES;
2080                 } else if (BPF_SRC(insn->code) == BPF_X &&
2081                            is_pointer_value(env, insn->src_reg)) {
2082                         verbose("R%d pointer arithmetic prohibited\n",
2083                                 insn->src_reg);
2084                         return -EACCES;
2085                 }
2086
2087                 /* If we did pointer math on a map value then just set it to our
2088                  * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or
2089                  * loads to this register appropriately, otherwise just mark the
2090                  * register as unknown.
2091                  */
2092                 if (env->allow_ptr_leaks &&
2093                     BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD &&
2094                     (dst_reg->type == PTR_TO_MAP_VALUE ||
2095                      dst_reg->type == PTR_TO_MAP_VALUE_ADJ))
2096                         dst_reg->type = PTR_TO_MAP_VALUE_ADJ;
2097                 else
2098                         mark_reg_unknown_value(regs, insn->dst_reg);
2099         }
2100
2101         return 0;
2102 }
2103
2104 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2105                                    struct bpf_reg_state *dst_reg)
2106 {
2107         struct bpf_reg_state *regs = state->regs, *reg;
2108         int i;
2109
2110         /* LLVM can generate two kind of checks:
2111          *
2112          * Type 1:
2113          *
2114          *   r2 = r3;
2115          *   r2 += 8;
2116          *   if (r2 > pkt_end) goto <handle exception>
2117          *   <access okay>
2118          *
2119          *   Where:
2120          *     r2 == dst_reg, pkt_end == src_reg
2121          *     r2=pkt(id=n,off=8,r=0)
2122          *     r3=pkt(id=n,off=0,r=0)
2123          *
2124          * Type 2:
2125          *
2126          *   r2 = r3;
2127          *   r2 += 8;
2128          *   if (pkt_end >= r2) goto <access okay>
2129          *   <handle exception>
2130          *
2131          *   Where:
2132          *     pkt_end == dst_reg, r2 == src_reg
2133          *     r2=pkt(id=n,off=8,r=0)
2134          *     r3=pkt(id=n,off=0,r=0)
2135          *
2136          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
2137          * so that range of bytes [r3, r3 + 8) is safe to access.
2138          */
2139
2140         for (i = 0; i < MAX_BPF_REG; i++)
2141                 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
2142                         /* keep the maximum range already checked */
2143                         regs[i].range = max(regs[i].range, dst_reg->off);
2144
2145         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2146                 if (state->stack_slot_type[i] != STACK_SPILL)
2147                         continue;
2148                 reg = &state->spilled_regs[i / BPF_REG_SIZE];
2149                 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
2150                         reg->range = max(reg->range, dst_reg->off);
2151         }
2152 }
2153
2154 /* Adjusts the register min/max values in the case that the dst_reg is the
2155  * variable register that we are working on, and src_reg is a constant or we're
2156  * simply doing a BPF_K check.
2157  */
2158 static void reg_set_min_max(struct bpf_reg_state *true_reg,
2159                             struct bpf_reg_state *false_reg, u64 val,
2160                             u8 opcode)
2161 {
2162         switch (opcode) {
2163         case BPF_JEQ:
2164                 /* If this is false then we know nothing Jon Snow, but if it is
2165                  * true then we know for sure.
2166                  */
2167                 true_reg->max_value = true_reg->min_value = val;
2168                 break;
2169         case BPF_JNE:
2170                 /* If this is true we know nothing Jon Snow, but if it is false
2171                  * we know the value for sure;
2172                  */
2173                 false_reg->max_value = false_reg->min_value = val;
2174                 break;
2175         case BPF_JGT:
2176                 /* Unsigned comparison, the minimum value is 0. */
2177                 false_reg->min_value = 0;
2178                 /* fallthrough */
2179         case BPF_JSGT:
2180                 /* If this is false then we know the maximum val is val,
2181                  * otherwise we know the min val is val+1.
2182                  */
2183                 false_reg->max_value = val;
2184                 true_reg->min_value = val + 1;
2185                 break;
2186         case BPF_JGE:
2187                 /* Unsigned comparison, the minimum value is 0. */
2188                 false_reg->min_value = 0;
2189                 /* fallthrough */
2190         case BPF_JSGE:
2191                 /* If this is false then we know the maximum value is val - 1,
2192                  * otherwise we know the mimimum value is val.
2193                  */
2194                 false_reg->max_value = val - 1;
2195                 true_reg->min_value = val;
2196                 break;
2197         default:
2198                 break;
2199         }
2200
2201         check_reg_overflow(false_reg);
2202         check_reg_overflow(true_reg);
2203 }
2204
2205 /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg
2206  * is the variable reg.
2207  */
2208 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
2209                                 struct bpf_reg_state *false_reg, u64 val,
2210                                 u8 opcode)
2211 {
2212         switch (opcode) {
2213         case BPF_JEQ:
2214                 /* If this is false then we know nothing Jon Snow, but if it is
2215                  * true then we know for sure.
2216                  */
2217                 true_reg->max_value = true_reg->min_value = val;
2218                 break;
2219         case BPF_JNE:
2220                 /* If this is true we know nothing Jon Snow, but if it is false
2221                  * we know the value for sure;
2222                  */
2223                 false_reg->max_value = false_reg->min_value = val;
2224                 break;
2225         case BPF_JGT:
2226                 /* Unsigned comparison, the minimum value is 0. */
2227                 true_reg->min_value = 0;
2228                 /* fallthrough */
2229         case BPF_JSGT:
2230                 /*
2231                  * If this is false, then the val is <= the register, if it is
2232                  * true the register <= to the val.
2233                  */
2234                 false_reg->min_value = val;
2235                 true_reg->max_value = val - 1;
2236                 break;
2237         case BPF_JGE:
2238                 /* Unsigned comparison, the minimum value is 0. */
2239                 true_reg->min_value = 0;
2240                 /* fallthrough */
2241         case BPF_JSGE:
2242                 /* If this is false then constant < register, if it is true then
2243                  * the register < constant.
2244                  */
2245                 false_reg->min_value = val + 1;
2246                 true_reg->max_value = val;
2247                 break;
2248         default:
2249                 break;
2250         }
2251
2252         check_reg_overflow(false_reg);
2253         check_reg_overflow(true_reg);
2254 }
2255
2256 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
2257                          enum bpf_reg_type type)
2258 {
2259         struct bpf_reg_state *reg = &regs[regno];
2260
2261         if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
2262                 if (type == UNKNOWN_VALUE) {
2263                         __mark_reg_unknown_value(regs, regno);
2264                 } else if (reg->map_ptr->inner_map_meta) {
2265                         reg->type = CONST_PTR_TO_MAP;
2266                         reg->map_ptr = reg->map_ptr->inner_map_meta;
2267                 } else {
2268                         reg->type = type;
2269                 }
2270                 /* We don't need id from this point onwards anymore, thus we
2271                  * should better reset it, so that state pruning has chances
2272                  * to take effect.
2273                  */
2274                 reg->id = 0;
2275         }
2276 }
2277
2278 /* The logic is similar to find_good_pkt_pointers(), both could eventually
2279  * be folded together at some point.
2280  */
2281 static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
2282                           enum bpf_reg_type type)
2283 {
2284         struct bpf_reg_state *regs = state->regs;
2285         u32 id = regs[regno].id;
2286         int i;
2287
2288         for (i = 0; i < MAX_BPF_REG; i++)
2289                 mark_map_reg(regs, i, id, type);
2290
2291         for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) {
2292                 if (state->stack_slot_type[i] != STACK_SPILL)
2293                         continue;
2294                 mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type);
2295         }
2296 }
2297
2298 static int check_cond_jmp_op(struct bpf_verifier_env *env,
2299                              struct bpf_insn *insn, int *insn_idx)
2300 {
2301         struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state;
2302         struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
2303         u8 opcode = BPF_OP(insn->code);
2304         int err;
2305
2306         if (opcode > BPF_EXIT) {
2307                 verbose("invalid BPF_JMP opcode %x\n", opcode);
2308                 return -EINVAL;
2309         }
2310
2311         if (BPF_SRC(insn->code) == BPF_X) {
2312                 if (insn->imm != 0) {
2313                         verbose("BPF_JMP uses reserved fields\n");
2314                         return -EINVAL;
2315                 }
2316
2317                 /* check src1 operand */
2318                 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2319                 if (err)
2320                         return err;
2321
2322                 if (is_pointer_value(env, insn->src_reg)) {
2323                         verbose("R%d pointer comparison prohibited\n",
2324                                 insn->src_reg);
2325                         return -EACCES;
2326                 }
2327         } else {
2328                 if (insn->src_reg != BPF_REG_0) {
2329                         verbose("BPF_JMP uses reserved fields\n");
2330                         return -EINVAL;
2331                 }
2332         }
2333
2334         /* check src2 operand */
2335         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
2336         if (err)
2337                 return err;
2338
2339         dst_reg = &regs[insn->dst_reg];
2340
2341         /* detect if R == 0 where R was initialized to zero earlier */
2342         if (BPF_SRC(insn->code) == BPF_K &&
2343             (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2344             dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) {
2345                 if (opcode == BPF_JEQ) {
2346                         /* if (imm == imm) goto pc+off;
2347                          * only follow the goto, ignore fall-through
2348                          */
2349                         *insn_idx += insn->off;
2350                         return 0;
2351                 } else {
2352                         /* if (imm != imm) goto pc+off;
2353                          * only follow fall-through branch, since
2354                          * that's where the program will go
2355                          */
2356                         return 0;
2357                 }
2358         }
2359
2360         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
2361         if (!other_branch)
2362                 return -EFAULT;
2363
2364         /* detect if we are comparing against a constant value so we can adjust
2365          * our min/max values for our dst register.
2366          */
2367         if (BPF_SRC(insn->code) == BPF_X) {
2368                 if (regs[insn->src_reg].type == CONST_IMM)
2369                         reg_set_min_max(&other_branch->regs[insn->dst_reg],
2370                                         dst_reg, regs[insn->src_reg].imm,
2371                                         opcode);
2372                 else if (dst_reg->type == CONST_IMM)
2373                         reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
2374                                             &regs[insn->src_reg], dst_reg->imm,
2375                                             opcode);
2376         } else {
2377                 reg_set_min_max(&other_branch->regs[insn->dst_reg],
2378                                         dst_reg, insn->imm, opcode);
2379         }
2380
2381         /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
2382         if (BPF_SRC(insn->code) == BPF_K &&
2383             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
2384             dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2385                 /* Mark all identical map registers in each branch as either
2386                  * safe or unknown depending R == 0 or R != 0 conditional.
2387                  */
2388                 mark_map_regs(this_branch, insn->dst_reg,
2389                               opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE);
2390                 mark_map_regs(other_branch, insn->dst_reg,
2391                               opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE);
2392         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
2393                    dst_reg->type == PTR_TO_PACKET &&
2394                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
2395                 find_good_pkt_pointers(this_branch, dst_reg);
2396         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
2397                    dst_reg->type == PTR_TO_PACKET_END &&
2398                    regs[insn->src_reg].type == PTR_TO_PACKET) {
2399                 find_good_pkt_pointers(other_branch, &regs[insn->src_reg]);
2400         } else if (is_pointer_value(env, insn->dst_reg)) {
2401                 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
2402                 return -EACCES;
2403         }
2404         if (log_level)
2405                 print_verifier_state(this_branch);
2406         return 0;
2407 }
2408
2409 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
2410 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
2411 {
2412         u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
2413
2414         return (struct bpf_map *) (unsigned long) imm64;
2415 }
2416
2417 /* verify BPF_LD_IMM64 instruction */
2418 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
2419 {
2420         struct bpf_reg_state *regs = env->cur_state.regs;
2421         int err;
2422
2423         if (BPF_SIZE(insn->code) != BPF_DW) {
2424                 verbose("invalid BPF_LD_IMM insn\n");
2425                 return -EINVAL;
2426         }
2427         if (insn->off != 0) {
2428                 verbose("BPF_LD_IMM64 uses reserved fields\n");
2429                 return -EINVAL;
2430         }
2431
2432         err = check_reg_arg(regs, insn->dst_reg, DST_OP);
2433         if (err)
2434                 return err;
2435
2436         if (insn->src_reg == 0) {
2437                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
2438
2439                 regs[insn->dst_reg].type = CONST_IMM;
2440                 regs[insn->dst_reg].imm = imm;
2441                 regs[insn->dst_reg].id = 0;
2442                 return 0;
2443         }
2444
2445         /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
2446         BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
2447
2448         regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
2449         regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
2450         return 0;
2451 }
2452
2453 static bool may_access_skb(enum bpf_prog_type type)
2454 {
2455         switch (type) {
2456         case BPF_PROG_TYPE_SOCKET_FILTER:
2457         case BPF_PROG_TYPE_SCHED_CLS:
2458         case BPF_PROG_TYPE_SCHED_ACT:
2459                 return true;
2460         default:
2461                 return false;
2462         }
2463 }
2464
2465 /* verify safety of LD_ABS|LD_IND instructions:
2466  * - they can only appear in the programs where ctx == skb
2467  * - since they are wrappers of function calls, they scratch R1-R5 registers,
2468  *   preserve R6-R9, and store return value into R0
2469  *
2470  * Implicit input:
2471  *   ctx == skb == R6 == CTX
2472  *
2473  * Explicit input:
2474  *   SRC == any register
2475  *   IMM == 32-bit immediate
2476  *
2477  * Output:
2478  *   R0 - 8/16/32-bit skb data converted to cpu endianness
2479  */
2480 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
2481 {
2482         struct bpf_reg_state *regs = env->cur_state.regs;
2483         u8 mode = BPF_MODE(insn->code);
2484         int i, err;
2485
2486         if (!may_access_skb(env->prog->type)) {
2487                 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
2488                 return -EINVAL;
2489         }
2490
2491         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
2492             BPF_SIZE(insn->code) == BPF_DW ||
2493             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
2494                 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
2495                 return -EINVAL;
2496         }
2497
2498         /* check whether implicit source operand (register R6) is readable */
2499         err = check_reg_arg(regs, BPF_REG_6, SRC_OP);
2500         if (err)
2501                 return err;
2502
2503         if (regs[BPF_REG_6].type != PTR_TO_CTX) {
2504                 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
2505                 return -EINVAL;
2506         }
2507
2508         if (mode == BPF_IND) {
2509                 /* check explicit source operand */
2510                 err = check_reg_arg(regs, insn->src_reg, SRC_OP);
2511                 if (err)
2512                         return err;
2513         }
2514
2515         /* reset caller saved regs to unreadable */
2516         for (i = 0; i < CALLER_SAVED_REGS; i++)
2517                 mark_reg_not_init(regs, caller_saved[i]);
2518
2519         /* mark destination R0 register as readable, since it contains
2520          * the value fetched from the packet
2521          */
2522         regs[BPF_REG_0].type = UNKNOWN_VALUE;
2523         return 0;
2524 }
2525
2526 /* non-recursive DFS pseudo code
2527  * 1  procedure DFS-iterative(G,v):
2528  * 2      label v as discovered
2529  * 3      let S be a stack
2530  * 4      S.push(v)
2531  * 5      while S is not empty
2532  * 6            t <- S.pop()
2533  * 7            if t is what we're looking for:
2534  * 8                return t
2535  * 9            for all edges e in G.adjacentEdges(t) do
2536  * 10               if edge e is already labelled
2537  * 11                   continue with the next edge
2538  * 12               w <- G.adjacentVertex(t,e)
2539  * 13               if vertex w is not discovered and not explored
2540  * 14                   label e as tree-edge
2541  * 15                   label w as discovered
2542  * 16                   S.push(w)
2543  * 17                   continue at 5
2544  * 18               else if vertex w is discovered
2545  * 19                   label e as back-edge
2546  * 20               else
2547  * 21                   // vertex w is explored
2548  * 22                   label e as forward- or cross-edge
2549  * 23           label t as explored
2550  * 24           S.pop()
2551  *
2552  * convention:
2553  * 0x10 - discovered
2554  * 0x11 - discovered and fall-through edge labelled
2555  * 0x12 - discovered and fall-through and branch edges labelled
2556  * 0x20 - explored
2557  */
2558
2559 enum {
2560         DISCOVERED = 0x10,
2561         EXPLORED = 0x20,
2562         FALLTHROUGH = 1,
2563         BRANCH = 2,
2564 };
2565
2566 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
2567
2568 static int *insn_stack; /* stack of insns to process */
2569 static int cur_stack;   /* current stack index */
2570 static int *insn_state;
2571
2572 /* t, w, e - match pseudo-code above:
2573  * t - index of current instruction
2574  * w - next instruction
2575  * e - edge
2576  */
2577 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
2578 {
2579         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
2580                 return 0;
2581
2582         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
2583                 return 0;
2584
2585         if (w < 0 || w >= env->prog->len) {
2586                 verbose("jump out of range from insn %d to %d\n", t, w);
2587                 return -EINVAL;
2588         }
2589
2590         if (e == BRANCH)
2591                 /* mark branch target for state pruning */
2592                 env->explored_states[w] = STATE_LIST_MARK;
2593
2594         if (insn_state[w] == 0) {
2595                 /* tree-edge */
2596                 insn_state[t] = DISCOVERED | e;
2597                 insn_state[w] = DISCOVERED;
2598                 if (cur_stack >= env->prog->len)
2599                         return -E2BIG;
2600                 insn_stack[cur_stack++] = w;
2601                 return 1;
2602         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2603                 verbose("back-edge from insn %d to %d\n", t, w);
2604                 return -EINVAL;
2605         } else if (insn_state[w] == EXPLORED) {
2606                 /* forward- or cross-edge */
2607                 insn_state[t] = DISCOVERED | e;
2608         } else {
2609                 verbose("insn state internal bug\n");
2610                 return -EFAULT;
2611         }
2612         return 0;
2613 }
2614
2615 /* non-recursive depth-first-search to detect loops in BPF program
2616  * loop == back-edge in directed graph
2617  */
2618 static int check_cfg(struct bpf_verifier_env *env)
2619 {
2620         struct bpf_insn *insns = env->prog->insnsi;
2621         int insn_cnt = env->prog->len;
2622         int ret = 0;
2623         int i, t;
2624
2625         insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2626         if (!insn_state)
2627                 return -ENOMEM;
2628
2629         insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
2630         if (!insn_stack) {
2631                 kfree(insn_state);
2632                 return -ENOMEM;
2633         }
2634
2635         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
2636         insn_stack[0] = 0; /* 0 is the first instruction */
2637         cur_stack = 1;
2638
2639 peek_stack:
2640         if (cur_stack == 0)
2641                 goto check_state;
2642         t = insn_stack[cur_stack - 1];
2643
2644         if (BPF_CLASS(insns[t].code) == BPF_JMP) {
2645                 u8 opcode = BPF_OP(insns[t].code);
2646
2647                 if (opcode == BPF_EXIT) {
2648                         goto mark_explored;
2649                 } else if (opcode == BPF_CALL) {
2650                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
2651                         if (ret == 1)
2652                                 goto peek_stack;
2653                         else if (ret < 0)
2654                                 goto err_free;
2655                         if (t + 1 < insn_cnt)
2656                                 env->explored_states[t + 1] = STATE_LIST_MARK;
2657                 } else if (opcode == BPF_JA) {
2658                         if (BPF_SRC(insns[t].code) != BPF_K) {
2659                                 ret = -EINVAL;
2660                                 goto err_free;
2661                         }
2662                         /* unconditional jump with single edge */
2663                         ret = push_insn(t, t + insns[t].off + 1,
2664                                         FALLTHROUGH, env);
2665                         if (ret == 1)
2666                                 goto peek_stack;
2667                         else if (ret < 0)
2668                                 goto err_free;
2669                         /* tell verifier to check for equivalent states
2670                          * after every call and jump
2671                          */
2672                         if (t + 1 < insn_cnt)
2673                                 env->explored_states[t + 1] = STATE_LIST_MARK;
2674                 } else {
2675                         /* conditional jump with two edges */
2676                         env->explored_states[t] = STATE_LIST_MARK;
2677                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
2678                         if (ret == 1)
2679                                 goto peek_stack;
2680                         else if (ret < 0)
2681                                 goto err_free;
2682
2683                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
2684                         if (ret == 1)
2685                                 goto peek_stack;
2686                         else if (ret < 0)
2687                                 goto err_free;
2688                 }
2689         } else {
2690                 /* all other non-branch instructions with single
2691                  * fall-through edge
2692                  */
2693                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
2694                 if (ret == 1)
2695                         goto peek_stack;
2696                 else if (ret < 0)
2697                         goto err_free;
2698         }
2699
2700 mark_explored:
2701         insn_state[t] = EXPLORED;
2702         if (cur_stack-- <= 0) {
2703                 verbose("pop stack internal bug\n");
2704                 ret = -EFAULT;
2705                 goto err_free;
2706         }
2707         goto peek_stack;
2708
2709 check_state:
2710         for (i = 0; i < insn_cnt; i++) {
2711                 if (insn_state[i] != EXPLORED) {
2712                         verbose("unreachable insn %d\n", i);
2713                         ret = -EINVAL;
2714                         goto err_free;
2715                 }
2716         }
2717         ret = 0; /* cfg looks good */
2718
2719 err_free:
2720         kfree(insn_state);
2721         kfree(insn_stack);
2722         return ret;
2723 }
2724
2725 /* the following conditions reduce the number of explored insns
2726  * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet
2727  */
2728 static bool compare_ptrs_to_packet(struct bpf_verifier_env *env,
2729                                    struct bpf_reg_state *old,
2730                                    struct bpf_reg_state *cur)
2731 {
2732         if (old->id != cur->id)
2733                 return false;
2734
2735         /* old ptr_to_packet is more conservative, since it allows smaller
2736          * range. Ex:
2737          * old(off=0,r=10) is equal to cur(off=0,r=20), because
2738          * old(off=0,r=10) means that with range=10 the verifier proceeded
2739          * further and found no issues with the program. Now we're in the same
2740          * spot with cur(off=0,r=20), so we're safe too, since anything further
2741          * will only be looking at most 10 bytes after this pointer.
2742          */
2743         if (old->off == cur->off && old->range < cur->range)
2744                 return true;
2745
2746         /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0)
2747          * since both cannot be used for packet access and safe(old)
2748          * pointer has smaller off that could be used for further
2749          * 'if (ptr > data_end)' check
2750          * Ex:
2751          * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean
2752          * that we cannot access the packet.
2753          * The safe range is:
2754          * [ptr, ptr + range - off)
2755          * so whenever off >=range, it means no safe bytes from this pointer.
2756          * When comparing old->off <= cur->off, it means that older code
2757          * went with smaller offset and that offset was later
2758          * used to figure out the safe range after 'if (ptr > data_end)' check
2759          * Say, 'old' state was explored like:
2760          * ... R3(off=0, r=0)
2761          * R4 = R3 + 20
2762          * ... now R4(off=20,r=0)  <-- here
2763          * if (R4 > data_end)
2764          * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access.
2765          * ... the code further went all the way to bpf_exit.
2766          * Now the 'cur' state at the mark 'here' has R4(off=30,r=0).
2767          * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier
2768          * goes further, such cur_R4 will give larger safe packet range after
2769          * 'if (R4 > data_end)' and all further insn were already good with r=20,
2770          * so they will be good with r=30 and we can prune the search.
2771          */
2772         if (!env->strict_alignment && old->off <= cur->off &&
2773             old->off >= old->range && cur->off >= cur->range)
2774                 return true;
2775
2776         return false;
2777 }
2778
2779 /* compare two verifier states
2780  *
2781  * all states stored in state_list are known to be valid, since
2782  * verifier reached 'bpf_exit' instruction through them
2783  *
2784  * this function is called when verifier exploring different branches of
2785  * execution popped from the state stack. If it sees an old state that has
2786  * more strict register state and more strict stack state then this execution
2787  * branch doesn't need to be explored further, since verifier already
2788  * concluded that more strict state leads to valid finish.
2789  *
2790  * Therefore two states are equivalent if register state is more conservative
2791  * and explored stack state is more conservative than the current one.
2792  * Example:
2793  *       explored                   current
2794  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
2795  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
2796  *
2797  * In other words if current stack state (one being explored) has more
2798  * valid slots than old one that already passed validation, it means
2799  * the verifier can stop exploring and conclude that current state is valid too
2800  *
2801  * Similarly with registers. If explored state has register type as invalid
2802  * whereas register type in current state is meaningful, it means that
2803  * the current state will reach 'bpf_exit' instruction safely
2804  */
2805 static bool states_equal(struct bpf_verifier_env *env,
2806                          struct bpf_verifier_state *old,
2807                          struct bpf_verifier_state *cur)
2808 {
2809         bool varlen_map_access = env->varlen_map_value_access;
2810         struct bpf_reg_state *rold, *rcur;
2811         int i;
2812
2813         for (i = 0; i < MAX_BPF_REG; i++) {
2814                 rold = &old->regs[i];
2815                 rcur = &cur->regs[i];
2816
2817                 if (memcmp(rold, rcur, sizeof(*rold)) == 0)
2818                         continue;
2819
2820                 /* If the ranges were not the same, but everything else was and
2821                  * we didn't do a variable access into a map then we are a-ok.
2822                  */
2823                 if (!varlen_map_access &&
2824                     memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0)
2825                         continue;
2826
2827                 /* If we didn't map access then again we don't care about the
2828                  * mismatched range values and it's ok if our old type was
2829                  * UNKNOWN and we didn't go to a NOT_INIT'ed reg.
2830                  */
2831                 if (rold->type == NOT_INIT ||
2832                     (!varlen_map_access && rold->type == UNKNOWN_VALUE &&
2833                      rcur->type != NOT_INIT))
2834                         continue;
2835
2836                 /* Don't care about the reg->id in this case. */
2837                 if (rold->type == PTR_TO_MAP_VALUE_OR_NULL &&
2838                     rcur->type == PTR_TO_MAP_VALUE_OR_NULL &&
2839                     rold->map_ptr == rcur->map_ptr)
2840                         continue;
2841
2842                 if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET &&
2843                     compare_ptrs_to_packet(env, rold, rcur))
2844                         continue;
2845
2846                 return false;
2847         }
2848
2849         for (i = 0; i < MAX_BPF_STACK; i++) {
2850                 if (old->stack_slot_type[i] == STACK_INVALID)
2851                         continue;
2852                 if (old->stack_slot_type[i] != cur->stack_slot_type[i])
2853                         /* Ex: old explored (safe) state has STACK_SPILL in
2854                          * this stack slot, but current has has STACK_MISC ->
2855                          * this verifier states are not equivalent,
2856                          * return false to continue verification of this path
2857                          */
2858                         return false;
2859                 if (i % BPF_REG_SIZE)
2860                         continue;
2861                 if (old->stack_slot_type[i] != STACK_SPILL)
2862                         continue;
2863                 if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE],
2864                            &cur->spilled_regs[i / BPF_REG_SIZE],
2865                            sizeof(old->spilled_regs[0])))
2866                         /* when explored and current stack slot types are
2867                          * the same, check that stored pointers types
2868                          * are the same as well.
2869                          * Ex: explored safe path could have stored
2870                          * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8}
2871                          * but current path has stored:
2872                          * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16}
2873                          * such verifier states are not equivalent.
2874                          * return false to continue verification of this path
2875                          */
2876                         return false;
2877                 else
2878                         continue;
2879         }
2880         return true;
2881 }
2882
2883 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
2884 {
2885         struct bpf_verifier_state_list *new_sl;
2886         struct bpf_verifier_state_list *sl;
2887
2888         sl = env->explored_states[insn_idx];
2889         if (!sl)
2890                 /* this 'insn_idx' instruction wasn't marked, so we will not
2891                  * be doing state search here
2892                  */
2893                 return 0;
2894
2895         while (sl != STATE_LIST_MARK) {
2896                 if (states_equal(env, &sl->state, &env->cur_state))
2897                         /* reached equivalent register/stack state,
2898                          * prune the search
2899                          */
2900                         return 1;
2901                 sl = sl->next;
2902         }
2903
2904         /* there were no equivalent states, remember current one.
2905          * technically the current state is not proven to be safe yet,
2906          * but it will either reach bpf_exit (which means it's safe) or
2907          * it will be rejected. Since there are no loops, we won't be
2908          * seeing this 'insn_idx' instruction again on the way to bpf_exit
2909          */
2910         new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER);
2911         if (!new_sl)
2912                 return -ENOMEM;
2913
2914         /* add new state to the head of linked list */
2915         memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state));
2916         new_sl->next = env->explored_states[insn_idx];
2917         env->explored_states[insn_idx] = new_sl;
2918         return 0;
2919 }
2920
2921 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
2922                                   int insn_idx, int prev_insn_idx)
2923 {
2924         if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
2925                 return 0;
2926
2927         return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
2928 }
2929
2930 static int do_check(struct bpf_verifier_env *env)
2931 {
2932         struct bpf_verifier_state *state = &env->cur_state;
2933         struct bpf_insn *insns = env->prog->insnsi;
2934         struct bpf_reg_state *regs = state->regs;
2935         int insn_cnt = env->prog->len;
2936         int insn_idx, prev_insn_idx = 0;
2937         int insn_processed = 0;
2938         bool do_print_state = false;
2939
2940         init_reg_state(regs);
2941         insn_idx = 0;
2942         env->varlen_map_value_access = false;
2943         for (;;) {
2944                 struct bpf_insn *insn;
2945                 u8 class;
2946                 int err;
2947
2948                 if (insn_idx >= insn_cnt) {
2949                         verbose("invalid insn idx %d insn_cnt %d\n",
2950                                 insn_idx, insn_cnt);
2951                         return -EFAULT;
2952                 }
2953
2954                 insn = &insns[insn_idx];
2955                 class = BPF_CLASS(insn->code);
2956
2957                 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
2958                         verbose("BPF program is too large. Processed %d insn\n",
2959                                 insn_processed);
2960                         return -E2BIG;
2961                 }
2962
2963                 err = is_state_visited(env, insn_idx);
2964                 if (err < 0)
2965                         return err;
2966                 if (err == 1) {
2967                         /* found equivalent state, can prune the search */
2968                         if (log_level) {
2969                                 if (do_print_state)
2970                                         verbose("\nfrom %d to %d: safe\n",
2971                                                 prev_insn_idx, insn_idx);
2972                                 else
2973                                         verbose("%d: safe\n", insn_idx);
2974                         }
2975                         goto process_bpf_exit;
2976                 }
2977
2978                 if (need_resched())
2979                         cond_resched();
2980
2981                 if (log_level > 1 || (log_level && do_print_state)) {
2982                         if (log_level > 1)
2983                                 verbose("%d:", insn_idx);
2984                         else
2985                                 verbose("\nfrom %d to %d:",
2986                                         prev_insn_idx, insn_idx);
2987                         print_verifier_state(&env->cur_state);
2988                         do_print_state = false;
2989                 }
2990
2991                 if (log_level) {
2992                         verbose("%d: ", insn_idx);
2993                         print_bpf_insn(env, insn);
2994                 }
2995
2996                 err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);
2997                 if (err)
2998                         return err;
2999
3000                 if (class == BPF_ALU || class == BPF_ALU64) {
3001                         err = check_alu_op(env, insn);
3002                         if (err)
3003                                 return err;
3004
3005                 } else if (class == BPF_LDX) {
3006                         enum bpf_reg_type *prev_src_type, src_reg_type;
3007
3008                         /* check for reserved fields is already done */
3009
3010                         /* check src operand */
3011                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
3012                         if (err)
3013                                 return err;
3014
3015                         err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK);
3016                         if (err)
3017                                 return err;
3018
3019                         src_reg_type = regs[insn->src_reg].type;
3020
3021                         /* check that memory (src_reg + off) is readable,
3022                          * the state of dst_reg will be updated by this func
3023                          */
3024                         err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
3025                                                BPF_SIZE(insn->code), BPF_READ,
3026                                                insn->dst_reg);
3027                         if (err)
3028                                 return err;
3029
3030                         prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
3031
3032                         if (*prev_src_type == NOT_INIT) {
3033                                 /* saw a valid insn
3034                                  * dst_reg = *(u32 *)(src_reg + off)
3035                                  * save type to validate intersecting paths
3036                                  */
3037                                 *prev_src_type = src_reg_type;
3038
3039                         } else if (src_reg_type != *prev_src_type &&
3040                                    (src_reg_type == PTR_TO_CTX ||
3041                                     *prev_src_type == PTR_TO_CTX)) {
3042                                 /* ABuser program is trying to use the same insn
3043                                  * dst_reg = *(u32*) (src_reg + off)
3044                                  * with different pointer types:
3045                                  * src_reg == ctx in one branch and
3046                                  * src_reg == stack|map in some other branch.
3047                                  * Reject it.
3048                                  */
3049                                 verbose("same insn cannot be used with different pointers\n");
3050                                 return -EINVAL;
3051                         }
3052
3053                 } else if (class == BPF_STX) {
3054                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
3055
3056                         if (BPF_MODE(insn->code) == BPF_XADD) {
3057                                 err = check_xadd(env, insn_idx, insn);
3058                                 if (err)
3059                                         return err;
3060                                 insn_idx++;
3061                                 continue;
3062                         }
3063
3064                         /* check src1 operand */
3065                         err = check_reg_arg(regs, insn->src_reg, SRC_OP);
3066                         if (err)
3067                                 return err;
3068                         /* check src2 operand */
3069                         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3070                         if (err)
3071                                 return err;
3072
3073                         dst_reg_type = regs[insn->dst_reg].type;
3074
3075                         /* check that memory (dst_reg + off) is writeable */
3076                         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3077                                                BPF_SIZE(insn->code), BPF_WRITE,
3078                                                insn->src_reg);
3079                         if (err)
3080                                 return err;
3081
3082                         prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
3083
3084                         if (*prev_dst_type == NOT_INIT) {
3085                                 *prev_dst_type = dst_reg_type;
3086                         } else if (dst_reg_type != *prev_dst_type &&
3087                                    (dst_reg_type == PTR_TO_CTX ||
3088                                     *prev_dst_type == PTR_TO_CTX)) {
3089                                 verbose("same insn cannot be used with different pointers\n");
3090                                 return -EINVAL;
3091                         }
3092
3093                 } else if (class == BPF_ST) {
3094                         if (BPF_MODE(insn->code) != BPF_MEM ||
3095                             insn->src_reg != BPF_REG_0) {
3096                                 verbose("BPF_ST uses reserved fields\n");
3097                                 return -EINVAL;
3098                         }
3099                         /* check src operand */
3100                         err = check_reg_arg(regs, insn->dst_reg, SRC_OP);
3101                         if (err)
3102                                 return err;
3103
3104                         /* check that memory (dst_reg + off) is writeable */
3105                         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
3106                                                BPF_SIZE(insn->code), BPF_WRITE,
3107                                                -1);
3108                         if (err)
3109                                 return err;
3110
3111                 } else if (class == BPF_JMP) {
3112                         u8 opcode = BPF_OP(insn->code);
3113
3114                         if (opcode == BPF_CALL) {
3115                                 if (BPF_SRC(insn->code) != BPF_K ||
3116                                     insn->off != 0 ||
3117                                     insn->src_reg != BPF_REG_0 ||
3118                                     insn->dst_reg != BPF_REG_0) {
3119                                         verbose("BPF_CALL uses reserved fields\n");
3120                                         return -EINVAL;
3121                                 }
3122
3123                                 err = check_call(env, insn->imm, insn_idx);
3124                                 if (err)
3125                                         return err;
3126
3127                         } else if (opcode == BPF_JA) {
3128                                 if (BPF_SRC(insn->code) != BPF_K ||
3129                                     insn->imm != 0 ||
3130                                     insn->src_reg != BPF_REG_0 ||
3131                                     insn->dst_reg != BPF_REG_0) {
3132                                         verbose("BPF_JA uses reserved fields\n");
3133                                         return -EINVAL;
3134                                 }
3135
3136                                 insn_idx += insn->off + 1;
3137                                 continue;
3138
3139                         } else if (opcode == BPF_EXIT) {
3140                                 if (BPF_SRC(insn->code) != BPF_K ||
3141                                     insn->imm != 0 ||
3142                                     insn->src_reg != BPF_REG_0 ||
3143                                     insn->dst_reg != BPF_REG_0) {
3144                                         verbose("BPF_EXIT uses reserved fields\n");
3145                                         return -EINVAL;
3146                                 }
3147
3148                                 /* eBPF calling convetion is such that R0 is used
3149                                  * to return the value from eBPF program.
3150                                  * Make sure that it's readable at this time
3151                                  * of bpf_exit, which means that program wrote
3152                                  * something into it earlier
3153                                  */
3154                                 err = check_reg_arg(regs, BPF_REG_0, SRC_OP);
3155                                 if (err)
3156                                         return err;
3157
3158                                 if (is_pointer_value(env, BPF_REG_0)) {
3159                                         verbose("R0 leaks addr as return value\n");
3160                                         return -EACCES;
3161                                 }
3162
3163 process_bpf_exit:
3164                                 insn_idx = pop_stack(env, &prev_insn_idx);
3165                                 if (insn_idx < 0) {
3166                                         break;
3167                                 } else {
3168                                         do_print_state = true;
3169                                         continue;
3170                                 }
3171                         } else {
3172                                 err = check_cond_jmp_op(env, insn, &insn_idx);
3173                                 if (err)
3174                                         return err;
3175                         }
3176                 } else if (class == BPF_LD) {
3177                         u8 mode = BPF_MODE(insn->code);
3178
3179                         if (mode == BPF_ABS || mode == BPF_IND) {
3180                                 err = check_ld_abs(env, insn);
3181                                 if (err)
3182                                         return err;
3183
3184                         } else if (mode == BPF_IMM) {
3185                                 err = check_ld_imm(env, insn);
3186                                 if (err)
3187                                         return err;
3188
3189                                 insn_idx++;
3190                         } else {
3191                                 verbose("invalid BPF_LD mode\n");
3192                                 return -EINVAL;
3193                         }
3194                         reset_reg_range_values(regs, insn->dst_reg);
3195                 } else {
3196                         verbose("unknown insn class %d\n", class);
3197                         return -EINVAL;
3198                 }
3199
3200                 insn_idx++;
3201         }
3202
3203         verbose("processed %d insns, stack depth %d\n",
3204                 insn_processed, env->prog->aux->stack_depth);
3205         return 0;
3206 }
3207
3208 static int check_map_prealloc(struct bpf_map *map)
3209 {
3210         return (map->map_type != BPF_MAP_TYPE_HASH &&
3211                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
3212                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
3213                 !(map->map_flags & BPF_F_NO_PREALLOC);
3214 }
3215
3216 static int check_map_prog_compatibility(struct bpf_map *map,
3217                                         struct bpf_prog *prog)
3218
3219 {
3220         /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
3221          * preallocated hash maps, since doing memory allocation
3222          * in overflow_handler can crash depending on where nmi got
3223          * triggered.
3224          */
3225         if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
3226                 if (!check_map_prealloc(map)) {
3227                         verbose("perf_event programs can only use preallocated hash map\n");
3228                         return -EINVAL;
3229                 }
3230                 if (map->inner_map_meta &&
3231                     !check_map_prealloc(map->inner_map_meta)) {
3232                         verbose("perf_event programs can only use preallocated inner hash map\n");
3233                         return -EINVAL;
3234                 }
3235         }
3236         return 0;
3237 }
3238
3239 /* look for pseudo eBPF instructions that access map FDs and
3240  * replace them with actual map pointers
3241  */
3242 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
3243 {
3244         struct bpf_insn *insn = env->prog->insnsi;
3245         int insn_cnt = env->prog->len;
3246         int i, j, err;
3247
3248         err = bpf_prog_calc_tag(env->prog);
3249         if (err)
3250                 return err;
3251
3252         for (i = 0; i < insn_cnt; i++, insn++) {
3253                 if (BPF_CLASS(insn->code) == BPF_LDX &&
3254                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
3255                         verbose("BPF_LDX uses reserved fields\n");
3256                         return -EINVAL;
3257                 }
3258
3259                 if (BPF_CLASS(insn->code) == BPF_STX &&
3260                     ((BPF_MODE(insn->code) != BPF_MEM &&
3261                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
3262                         verbose("BPF_STX uses reserved fields\n");
3263                         return -EINVAL;
3264                 }
3265
3266                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
3267                         struct bpf_map *map;
3268                         struct fd f;
3269
3270                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
3271                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
3272                             insn[1].off != 0) {
3273                                 verbose("invalid bpf_ld_imm64 insn\n");
3274                                 return -EINVAL;
3275                         }
3276
3277                         if (insn->src_reg == 0)
3278                                 /* valid generic load 64-bit imm */
3279                                 goto next_insn;
3280
3281                         if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
3282                                 verbose("unrecognized bpf_ld_imm64 insn\n");
3283                                 return -EINVAL;
3284                         }
3285
3286                         f = fdget(insn->imm);
3287                         map = __bpf_map_get(f);
3288                         if (IS_ERR(map)) {
3289                                 verbose("fd %d is not pointing to valid bpf_map\n",
3290                                         insn->imm);
3291                                 return PTR_ERR(map);
3292                         }
3293
3294                         err = check_map_prog_compatibility(map, env->prog);
3295                         if (err) {
3296                                 fdput(f);
3297                                 return err;
3298                         }
3299
3300                         /* store map pointer inside BPF_LD_IMM64 instruction */
3301                         insn[0].imm = (u32) (unsigned long) map;
3302                         insn[1].imm = ((u64) (unsigned long) map) >> 32;
3303
3304                         /* check whether we recorded this map already */
3305                         for (j = 0; j < env->used_map_cnt; j++)
3306                                 if (env->used_maps[j] == map) {
3307                                         fdput(f);
3308                                         goto next_insn;
3309                                 }
3310
3311                         if (env->used_map_cnt >= MAX_USED_MAPS) {
3312                                 fdput(f);
3313                                 return -E2BIG;
3314                         }
3315
3316                         /* hold the map. If the program is rejected by verifier,
3317                          * the map will be released by release_maps() or it
3318                          * will be used by the valid program until it's unloaded
3319                          * and all maps are released in free_bpf_prog_info()
3320                          */
3321                         map = bpf_map_inc(map, false);
3322                         if (IS_ERR(map)) {
3323                                 fdput(f);
3324                                 return PTR_ERR(map);
3325                         }
3326                         env->used_maps[env->used_map_cnt++] = map;
3327
3328                         fdput(f);
3329 next_insn:
3330                         insn++;
3331                         i++;
3332                 }
3333         }
3334
3335         /* now all pseudo BPF_LD_IMM64 instructions load valid
3336          * 'struct bpf_map *' into a register instead of user map_fd.
3337          * These pointers will be used later by verifier to validate map access.
3338          */
3339         return 0;
3340 }
3341
3342 /* drop refcnt of maps used by the rejected program */
3343 static void release_maps(struct bpf_verifier_env *env)
3344 {
3345         int i;
3346
3347         for (i = 0; i < env->used_map_cnt; i++)
3348                 bpf_map_put(env->used_maps[i]);
3349 }
3350
3351 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
3352 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
3353 {
3354         struct bpf_insn *insn = env->prog->insnsi;
3355         int insn_cnt = env->prog->len;
3356         int i;
3357
3358         for (i = 0; i < insn_cnt; i++, insn++)
3359                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
3360                         insn->src_reg = 0;
3361 }
3362
3363 /* single env->prog->insni[off] instruction was replaced with the range
3364  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
3365  * [0, off) and [off, end) to new locations, so the patched range stays zero
3366  */
3367 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
3368                                 u32 off, u32 cnt)
3369 {
3370         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
3371
3372         if (cnt == 1)
3373                 return 0;
3374         new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
3375         if (!new_data)
3376                 return -ENOMEM;
3377         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
3378         memcpy(new_data + off + cnt - 1, old_data + off,
3379                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
3380         env->insn_aux_data = new_data;
3381         vfree(old_data);
3382         return 0;
3383 }
3384
3385 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
3386                                             const struct bpf_insn *patch, u32 len)
3387 {
3388         struct bpf_prog *new_prog;
3389
3390         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
3391         if (!new_prog)
3392                 return NULL;
3393         if (adjust_insn_aux_data(env, new_prog->len, off, len))
3394                 return NULL;
3395         return new_prog;
3396 }
3397
3398 /* convert load instructions that access fields of 'struct __sk_buff'
3399  * into sequence of instructions that access fields of 'struct sk_buff'
3400  */
3401 static int convert_ctx_accesses(struct bpf_verifier_env *env)
3402 {
3403         const struct bpf_verifier_ops *ops = env->prog->aux->ops;
3404         const int insn_cnt = env->prog->len;
3405         struct bpf_insn insn_buf[16], *insn;
3406         struct bpf_prog *new_prog;
3407         enum bpf_access_type type;
3408         int i, cnt, off, size, ctx_field_size, converted_op_size, is_narrower_load, delta = 0;
3409
3410         if (ops->gen_prologue) {
3411                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
3412                                         env->prog);
3413                 if (cnt >= ARRAY_SIZE(insn_buf)) {
3414                         verbose("bpf verifier is misconfigured\n");
3415                         return -EINVAL;
3416                 } else if (cnt) {
3417                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
3418                         if (!new_prog)
3419                                 return -ENOMEM;
3420
3421                         env->prog = new_prog;
3422                         delta += cnt - 1;
3423                 }
3424         }
3425
3426         if (!ops->convert_ctx_access)
3427                 return 0;
3428
3429         insn = env->prog->insnsi + delta;
3430
3431         for (i = 0; i < insn_cnt; i++, insn++) {
3432                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
3433                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
3434                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
3435                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
3436                         type = BPF_READ;
3437                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
3438                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
3439                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
3440                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
3441                         type = BPF_WRITE;
3442                 else
3443                         continue;
3444
3445                 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
3446                         continue;
3447
3448                 off = insn->off;
3449                 size = bpf_size_to_bytes(BPF_SIZE(insn->code));
3450                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
3451                 converted_op_size = env->insn_aux_data[i + delta].converted_op_size;
3452                 is_narrower_load = type == BPF_READ && size < ctx_field_size;
3453
3454                 /* If the read access is a narrower load of the field,
3455                  * convert to a 4/8-byte load, to minimum program type specific
3456                  * convert_ctx_access changes. If conversion is successful,
3457                  * we will apply proper mask to the result.
3458                  */
3459                 if (is_narrower_load) {
3460                         int size_code = BPF_H;
3461
3462                         if (ctx_field_size == 4)
3463                                 size_code = BPF_W;
3464                         else if (ctx_field_size == 8)
3465                                 size_code = BPF_DW;
3466                         insn->off = off & ~(ctx_field_size - 1);
3467                         insn->code = BPF_LDX | BPF_MEM | size_code;
3468                 }
3469                 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog);
3470                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3471                         verbose("bpf verifier is misconfigured\n");
3472                         return -EINVAL;
3473                 }
3474                 if (is_narrower_load && size < converted_op_size) {
3475                         if (ctx_field_size <= 4)
3476                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
3477                                                         (1 << size * 8) - 1);
3478                         else
3479                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
3480                                                         (1 << size * 8) - 1);
3481                 }
3482
3483                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
3484                 if (!new_prog)
3485                         return -ENOMEM;
3486
3487                 delta += cnt - 1;
3488
3489                 /* keep walking new program and skip insns we just inserted */
3490                 env->prog = new_prog;
3491                 insn      = new_prog->insnsi + i + delta;
3492         }
3493
3494         return 0;
3495 }
3496
3497 /* fixup insn->imm field of bpf_call instructions
3498  * and inline eligible helpers as explicit sequence of BPF instructions
3499  *
3500  * this function is called after eBPF program passed verification
3501  */
3502 static int fixup_bpf_calls(struct bpf_verifier_env *env)
3503 {
3504         struct bpf_prog *prog = env->prog;
3505         struct bpf_insn *insn = prog->insnsi;
3506         const struct bpf_func_proto *fn;
3507         const int insn_cnt = prog->len;
3508         struct bpf_insn insn_buf[16];
3509         struct bpf_prog *new_prog;
3510         struct bpf_map *map_ptr;
3511         int i, cnt, delta = 0;
3512
3513         for (i = 0; i < insn_cnt; i++, insn++) {
3514                 if (insn->code != (BPF_JMP | BPF_CALL))
3515                         continue;
3516
3517                 if (insn->imm == BPF_FUNC_get_route_realm)
3518                         prog->dst_needed = 1;
3519                 if (insn->imm == BPF_FUNC_get_prandom_u32)
3520                         bpf_user_rnd_init_once();
3521                 if (insn->imm == BPF_FUNC_tail_call) {
3522                         /* If we tail call into other programs, we
3523                          * cannot make any assumptions since they can
3524                          * be replaced dynamically during runtime in
3525                          * the program array.
3526                          */
3527                         prog->cb_access = 1;
3528                         env->prog->aux->stack_depth = MAX_BPF_STACK;
3529
3530                         /* mark bpf_tail_call as different opcode to avoid
3531                          * conditional branch in the interpeter for every normal
3532                          * call and to prevent accidental JITing by JIT compiler
3533                          * that doesn't support bpf_tail_call yet
3534                          */
3535                         insn->imm = 0;
3536                         insn->code = BPF_JMP | BPF_TAIL_CALL;
3537                         continue;
3538                 }
3539
3540                 if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) {
3541                         map_ptr = env->insn_aux_data[i + delta].map_ptr;
3542                         if (map_ptr == BPF_MAP_PTR_POISON ||
3543                             !map_ptr->ops->map_gen_lookup)
3544                                 goto patch_call_imm;
3545
3546                         cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
3547                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
3548                                 verbose("bpf verifier is misconfigured\n");
3549                                 return -EINVAL;
3550                         }
3551
3552                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
3553                                                        cnt);
3554                         if (!new_prog)
3555                                 return -ENOMEM;
3556
3557                         delta += cnt - 1;
3558
3559                         /* keep walking new program and skip insns we just inserted */
3560                         env->prog = prog = new_prog;
3561                         insn      = new_prog->insnsi + i + delta;
3562                         continue;
3563                 }
3564
3565 patch_call_imm:
3566                 fn = prog->aux->ops->get_func_proto(insn->imm);
3567                 /* all functions that have prototype and verifier allowed
3568                  * programs to call them, must be real in-kernel functions
3569                  */
3570                 if (!fn->func) {
3571                         verbose("kernel subsystem misconfigured func %s#%d\n",
3572                                 func_id_name(insn->imm), insn->imm);
3573                         return -EFAULT;
3574                 }
3575                 insn->imm = fn->func - __bpf_call_base;
3576         }
3577
3578         return 0;
3579 }
3580
3581 static void free_states(struct bpf_verifier_env *env)
3582 {
3583         struct bpf_verifier_state_list *sl, *sln;
3584         int i;
3585
3586         if (!env->explored_states)
3587                 return;
3588
3589         for (i = 0; i < env->prog->len; i++) {
3590                 sl = env->explored_states[i];
3591
3592                 if (sl)
3593                         while (sl != STATE_LIST_MARK) {
3594                                 sln = sl->next;
3595                                 kfree(sl);
3596                                 sl = sln;
3597                         }
3598         }
3599
3600         kfree(env->explored_states);
3601 }
3602
3603 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
3604 {
3605         char __user *log_ubuf = NULL;
3606         struct bpf_verifier_env *env;
3607         int ret = -EINVAL;
3608
3609         /* 'struct bpf_verifier_env' can be global, but since it's not small,
3610          * allocate/free it every time bpf_check() is called
3611          */
3612         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3613         if (!env)
3614                 return -ENOMEM;
3615
3616         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3617                                      (*prog)->len);
3618         ret = -ENOMEM;
3619         if (!env->insn_aux_data)
3620                 goto err_free_env;
3621         env->prog = *prog;
3622
3623         /* grab the mutex to protect few globals used by verifier */
3624         mutex_lock(&bpf_verifier_lock);
3625
3626         if (attr->log_level || attr->log_buf || attr->log_size) {
3627                 /* user requested verbose verifier output
3628                  * and supplied buffer to store the verification trace
3629                  */
3630                 log_level = attr->log_level;
3631                 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
3632                 log_size = attr->log_size;
3633                 log_len = 0;
3634
3635                 ret = -EINVAL;
3636                 /* log_* values have to be sane */
3637                 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
3638                     log_level == 0 || log_ubuf == NULL)
3639                         goto err_unlock;
3640
3641                 ret = -ENOMEM;
3642                 log_buf = vmalloc(log_size);
3643                 if (!log_buf)
3644                         goto err_unlock;
3645         } else {
3646                 log_level = 0;
3647         }
3648
3649         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
3650         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
3651                 env->strict_alignment = true;
3652
3653         ret = replace_map_fd_with_map_ptr(env);
3654         if (ret < 0)
3655                 goto skip_full_check;
3656
3657         env->explored_states = kcalloc(env->prog->len,
3658                                        sizeof(struct bpf_verifier_state_list *),
3659                                        GFP_USER);
3660         ret = -ENOMEM;
3661         if (!env->explored_states)
3662                 goto skip_full_check;
3663
3664         ret = check_cfg(env);
3665         if (ret < 0)
3666                 goto skip_full_check;
3667
3668         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3669
3670         ret = do_check(env);
3671
3672 skip_full_check:
3673         while (pop_stack(env, NULL) >= 0);
3674         free_states(env);
3675
3676         if (ret == 0)
3677                 /* program is valid, convert *(u32*)(ctx + off) accesses */
3678                 ret = convert_ctx_accesses(env);
3679
3680         if (ret == 0)
3681                 ret = fixup_bpf_calls(env);
3682
3683         if (log_level && log_len >= log_size - 1) {
3684                 BUG_ON(log_len >= log_size);
3685                 /* verifier log exceeded user supplied buffer */
3686                 ret = -ENOSPC;
3687                 /* fall through to return what was recorded */
3688         }
3689
3690         /* copy verifier log back to user space including trailing zero */
3691         if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
3692                 ret = -EFAULT;
3693                 goto free_log_buf;
3694         }
3695
3696         if (ret == 0 && env->used_map_cnt) {
3697                 /* if program passed verifier, update used_maps in bpf_prog_info */
3698                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
3699                                                           sizeof(env->used_maps[0]),
3700                                                           GFP_KERNEL);
3701
3702                 if (!env->prog->aux->used_maps) {
3703                         ret = -ENOMEM;
3704                         goto free_log_buf;
3705                 }
3706
3707                 memcpy(env->prog->aux->used_maps, env->used_maps,
3708                        sizeof(env->used_maps[0]) * env->used_map_cnt);
3709                 env->prog->aux->used_map_cnt = env->used_map_cnt;
3710
3711                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
3712                  * bpf_ld_imm64 instructions
3713                  */
3714                 convert_pseudo_ld_imm64(env);
3715         }
3716
3717 free_log_buf:
3718         if (log_level)
3719                 vfree(log_buf);
3720         if (!env->prog->aux->used_maps)
3721                 /* if we didn't copy map pointers into bpf_prog_info, release
3722                  * them now. Otherwise free_bpf_prog_info() will release them.
3723                  */
3724                 release_maps(env);
3725         *prog = env->prog;
3726 err_unlock:
3727         mutex_unlock(&bpf_verifier_lock);
3728         vfree(env->insn_aux_data);
3729 err_free_env:
3730         kfree(env);
3731         return ret;
3732 }
3733
3734 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
3735                  void *priv)
3736 {
3737         struct bpf_verifier_env *env;
3738         int ret;
3739
3740         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
3741         if (!env)
3742                 return -ENOMEM;
3743
3744         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
3745                                      prog->len);
3746         ret = -ENOMEM;
3747         if (!env->insn_aux_data)
3748                 goto err_free_env;
3749         env->prog = prog;
3750         env->analyzer_ops = ops;
3751         env->analyzer_priv = priv;
3752
3753         /* grab the mutex to protect few globals used by verifier */
3754         mutex_lock(&bpf_verifier_lock);
3755
3756         log_level = 0;
3757
3758         env->strict_alignment = false;
3759         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
3760                 env->strict_alignment = true;
3761
3762         env->explored_states = kcalloc(env->prog->len,
3763                                        sizeof(struct bpf_verifier_state_list *),
3764                                        GFP_KERNEL);
3765         ret = -ENOMEM;
3766         if (!env->explored_states)
3767                 goto skip_full_check;
3768
3769         ret = check_cfg(env);
3770         if (ret < 0)
3771                 goto skip_full_check;
3772
3773         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
3774
3775         ret = do_check(env);
3776
3777 skip_full_check:
3778         while (pop_stack(env, NULL) >= 0);
3779         free_states(env);
3780
3781         mutex_unlock(&bpf_verifier_lock);
3782         vfree(env->insn_aux_data);
3783 err_free_env:
3784         kfree(env);
3785         return ret;
3786 }
3787 EXPORT_SYMBOL_GPL(bpf_analyzer);