]> asedeno.scripts.mit.edu Git - linux.git/blob - kernel/bpf/verifier.c
eb1a596aebd30755fa72a1cf5294badc04b76140
[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 #include <linux/bsearch.h>
24 #include <linux/sort.h>
25
26 #include "disasm.h"
27
28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
29 #define BPF_PROG_TYPE(_id, _name) \
30         [_id] = & _name ## _verifier_ops,
31 #define BPF_MAP_TYPE(_id, _ops)
32 #include <linux/bpf_types.h>
33 #undef BPF_PROG_TYPE
34 #undef BPF_MAP_TYPE
35 };
36
37 /* bpf_check() is a static code analyzer that walks eBPF program
38  * instruction by instruction and updates register/stack state.
39  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
40  *
41  * The first pass is depth-first-search to check that the program is a DAG.
42  * It rejects the following programs:
43  * - larger than BPF_MAXINSNS insns
44  * - if loop is present (detected via back-edge)
45  * - unreachable insns exist (shouldn't be a forest. program = one function)
46  * - out of bounds or malformed jumps
47  * The second pass is all possible path descent from the 1st insn.
48  * Since it's analyzing all pathes through the program, the length of the
49  * analysis is limited to 64k insn, which may be hit even if total number of
50  * insn is less then 4K, but there are too many branches that change stack/regs.
51  * Number of 'branches to be analyzed' is limited to 1k
52  *
53  * On entry to each instruction, each register has a type, and the instruction
54  * changes the types of the registers depending on instruction semantics.
55  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
56  * copied to R1.
57  *
58  * All registers are 64-bit.
59  * R0 - return register
60  * R1-R5 argument passing registers
61  * R6-R9 callee saved registers
62  * R10 - frame pointer read-only
63  *
64  * At the start of BPF program the register R1 contains a pointer to bpf_context
65  * and has type PTR_TO_CTX.
66  *
67  * Verifier tracks arithmetic operations on pointers in case:
68  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
69  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
70  * 1st insn copies R10 (which has FRAME_PTR) type into R1
71  * and 2nd arithmetic instruction is pattern matched to recognize
72  * that it wants to construct a pointer to some element within stack.
73  * So after 2nd insn, the register R1 has type PTR_TO_STACK
74  * (and -20 constant is saved for further stack bounds checking).
75  * Meaning that this reg is a pointer to stack plus known immediate constant.
76  *
77  * Most of the time the registers have SCALAR_VALUE type, which
78  * means the register has some value, but it's not a valid pointer.
79  * (like pointer plus pointer becomes SCALAR_VALUE type)
80  *
81  * When verifier sees load or store instructions the type of base register
82  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
83  * types recognized by check_mem_access() function.
84  *
85  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
86  * and the range of [ptr, ptr + map's value_size) is accessible.
87  *
88  * registers used to pass values to function calls are checked against
89  * function argument constraints.
90  *
91  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
92  * It means that the register type passed to this function must be
93  * PTR_TO_STACK and it will be used inside the function as
94  * 'pointer to map element key'
95  *
96  * For example the argument constraints for bpf_map_lookup_elem():
97  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
98  *   .arg1_type = ARG_CONST_MAP_PTR,
99  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
100  *
101  * ret_type says that this function returns 'pointer to map elem value or null'
102  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
103  * 2nd argument should be a pointer to stack, which will be used inside
104  * the helper function as a pointer to map element key.
105  *
106  * On the kernel side the helper function looks like:
107  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
108  * {
109  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
110  *    void *key = (void *) (unsigned long) r2;
111  *    void *value;
112  *
113  *    here kernel can access 'key' and 'map' pointers safely, knowing that
114  *    [key, key + map->key_size) bytes are valid and were initialized on
115  *    the stack of eBPF program.
116  * }
117  *
118  * Corresponding eBPF program may look like:
119  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
120  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
121  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
122  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
123  * here verifier looks at prototype of map_lookup_elem() and sees:
124  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
125  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
126  *
127  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
128  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
129  * and were initialized prior to this call.
130  * If it's ok, then verifier allows this BPF_CALL insn and looks at
131  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
132  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
133  * returns ether pointer to map value or NULL.
134  *
135  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
136  * insn, the register holding that pointer in the true branch changes state to
137  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
138  * branch. See check_cond_jmp_op().
139  *
140  * After the call R0 is set to return type of the function and registers R1-R5
141  * are set to NOT_INIT to indicate that they are no longer readable.
142  */
143
144 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
145 struct bpf_verifier_stack_elem {
146         /* verifer state is 'st'
147          * before processing instruction 'insn_idx'
148          * and after processing instruction 'prev_insn_idx'
149          */
150         struct bpf_verifier_state st;
151         int insn_idx;
152         int prev_insn_idx;
153         struct bpf_verifier_stack_elem *next;
154 };
155
156 #define BPF_COMPLEXITY_LIMIT_INSNS      131072
157 #define BPF_COMPLEXITY_LIMIT_STACK      1024
158
159 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA)
160
161 struct bpf_call_arg_meta {
162         struct bpf_map *map_ptr;
163         bool raw_mode;
164         bool pkt_access;
165         int regno;
166         int access_size;
167 };
168
169 static DEFINE_MUTEX(bpf_verifier_lock);
170
171 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
172                        va_list args)
173 {
174         unsigned int n;
175
176         n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
177
178         WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
179                   "verifier log line truncated - local buffer too short\n");
180
181         n = min(log->len_total - log->len_used - 1, n);
182         log->kbuf[n] = '\0';
183
184         if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
185                 log->len_used += n;
186         else
187                 log->ubuf = NULL;
188 }
189
190 /* log_level controls verbosity level of eBPF verifier.
191  * bpf_verifier_log_write() is used to dump the verification trace to the log,
192  * so the user can figure out what's wrong with the program
193  */
194 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
195                                            const char *fmt, ...)
196 {
197         va_list args;
198
199         if (!bpf_verifier_log_needed(&env->log))
200                 return;
201
202         va_start(args, fmt);
203         bpf_verifier_vlog(&env->log, fmt, args);
204         va_end(args);
205 }
206 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
207
208 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
209 {
210         struct bpf_verifier_env *env = private_data;
211         va_list args;
212
213         if (!bpf_verifier_log_needed(&env->log))
214                 return;
215
216         va_start(args, fmt);
217         bpf_verifier_vlog(&env->log, fmt, args);
218         va_end(args);
219 }
220
221 static bool type_is_pkt_pointer(enum bpf_reg_type type)
222 {
223         return type == PTR_TO_PACKET ||
224                type == PTR_TO_PACKET_META;
225 }
226
227 /* string representation of 'enum bpf_reg_type' */
228 static const char * const reg_type_str[] = {
229         [NOT_INIT]              = "?",
230         [SCALAR_VALUE]          = "inv",
231         [PTR_TO_CTX]            = "ctx",
232         [CONST_PTR_TO_MAP]      = "map_ptr",
233         [PTR_TO_MAP_VALUE]      = "map_value",
234         [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
235         [PTR_TO_STACK]          = "fp",
236         [PTR_TO_PACKET]         = "pkt",
237         [PTR_TO_PACKET_META]    = "pkt_meta",
238         [PTR_TO_PACKET_END]     = "pkt_end",
239 };
240
241 static void print_liveness(struct bpf_verifier_env *env,
242                            enum bpf_reg_liveness live)
243 {
244         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
245             verbose(env, "_");
246         if (live & REG_LIVE_READ)
247                 verbose(env, "r");
248         if (live & REG_LIVE_WRITTEN)
249                 verbose(env, "w");
250 }
251
252 static struct bpf_func_state *func(struct bpf_verifier_env *env,
253                                    const struct bpf_reg_state *reg)
254 {
255         struct bpf_verifier_state *cur = env->cur_state;
256
257         return cur->frame[reg->frameno];
258 }
259
260 static void print_verifier_state(struct bpf_verifier_env *env,
261                                  const struct bpf_func_state *state)
262 {
263         const struct bpf_reg_state *reg;
264         enum bpf_reg_type t;
265         int i;
266
267         if (state->frameno)
268                 verbose(env, " frame%d:", state->frameno);
269         for (i = 0; i < MAX_BPF_REG; i++) {
270                 reg = &state->regs[i];
271                 t = reg->type;
272                 if (t == NOT_INIT)
273                         continue;
274                 verbose(env, " R%d", i);
275                 print_liveness(env, reg->live);
276                 verbose(env, "=%s", reg_type_str[t]);
277                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
278                     tnum_is_const(reg->var_off)) {
279                         /* reg->off should be 0 for SCALAR_VALUE */
280                         verbose(env, "%lld", reg->var_off.value + reg->off);
281                         if (t == PTR_TO_STACK)
282                                 verbose(env, ",call_%d", func(env, reg)->callsite);
283                 } else {
284                         verbose(env, "(id=%d", reg->id);
285                         if (t != SCALAR_VALUE)
286                                 verbose(env, ",off=%d", reg->off);
287                         if (type_is_pkt_pointer(t))
288                                 verbose(env, ",r=%d", reg->range);
289                         else if (t == CONST_PTR_TO_MAP ||
290                                  t == PTR_TO_MAP_VALUE ||
291                                  t == PTR_TO_MAP_VALUE_OR_NULL)
292                                 verbose(env, ",ks=%d,vs=%d",
293                                         reg->map_ptr->key_size,
294                                         reg->map_ptr->value_size);
295                         if (tnum_is_const(reg->var_off)) {
296                                 /* Typically an immediate SCALAR_VALUE, but
297                                  * could be a pointer whose offset is too big
298                                  * for reg->off
299                                  */
300                                 verbose(env, ",imm=%llx", reg->var_off.value);
301                         } else {
302                                 if (reg->smin_value != reg->umin_value &&
303                                     reg->smin_value != S64_MIN)
304                                         verbose(env, ",smin_value=%lld",
305                                                 (long long)reg->smin_value);
306                                 if (reg->smax_value != reg->umax_value &&
307                                     reg->smax_value != S64_MAX)
308                                         verbose(env, ",smax_value=%lld",
309                                                 (long long)reg->smax_value);
310                                 if (reg->umin_value != 0)
311                                         verbose(env, ",umin_value=%llu",
312                                                 (unsigned long long)reg->umin_value);
313                                 if (reg->umax_value != U64_MAX)
314                                         verbose(env, ",umax_value=%llu",
315                                                 (unsigned long long)reg->umax_value);
316                                 if (!tnum_is_unknown(reg->var_off)) {
317                                         char tn_buf[48];
318
319                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
320                                         verbose(env, ",var_off=%s", tn_buf);
321                                 }
322                         }
323                         verbose(env, ")");
324                 }
325         }
326         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
327                 if (state->stack[i].slot_type[0] == STACK_SPILL) {
328                         verbose(env, " fp%d",
329                                 (-i - 1) * BPF_REG_SIZE);
330                         print_liveness(env, state->stack[i].spilled_ptr.live);
331                         verbose(env, "=%s",
332                                 reg_type_str[state->stack[i].spilled_ptr.type]);
333                 }
334                 if (state->stack[i].slot_type[0] == STACK_ZERO)
335                         verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
336         }
337         verbose(env, "\n");
338 }
339
340 static int copy_stack_state(struct bpf_func_state *dst,
341                             const struct bpf_func_state *src)
342 {
343         if (!src->stack)
344                 return 0;
345         if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
346                 /* internal bug, make state invalid to reject the program */
347                 memset(dst, 0, sizeof(*dst));
348                 return -EFAULT;
349         }
350         memcpy(dst->stack, src->stack,
351                sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
352         return 0;
353 }
354
355 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
356  * make it consume minimal amount of memory. check_stack_write() access from
357  * the program calls into realloc_func_state() to grow the stack size.
358  * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
359  * which this function copies over. It points to previous bpf_verifier_state
360  * which is never reallocated
361  */
362 static int realloc_func_state(struct bpf_func_state *state, int size,
363                               bool copy_old)
364 {
365         u32 old_size = state->allocated_stack;
366         struct bpf_stack_state *new_stack;
367         int slot = size / BPF_REG_SIZE;
368
369         if (size <= old_size || !size) {
370                 if (copy_old)
371                         return 0;
372                 state->allocated_stack = slot * BPF_REG_SIZE;
373                 if (!size && old_size) {
374                         kfree(state->stack);
375                         state->stack = NULL;
376                 }
377                 return 0;
378         }
379         new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
380                                   GFP_KERNEL);
381         if (!new_stack)
382                 return -ENOMEM;
383         if (copy_old) {
384                 if (state->stack)
385                         memcpy(new_stack, state->stack,
386                                sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
387                 memset(new_stack + old_size / BPF_REG_SIZE, 0,
388                        sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
389         }
390         state->allocated_stack = slot * BPF_REG_SIZE;
391         kfree(state->stack);
392         state->stack = new_stack;
393         return 0;
394 }
395
396 static void free_func_state(struct bpf_func_state *state)
397 {
398         if (!state)
399                 return;
400         kfree(state->stack);
401         kfree(state);
402 }
403
404 static void free_verifier_state(struct bpf_verifier_state *state,
405                                 bool free_self)
406 {
407         int i;
408
409         for (i = 0; i <= state->curframe; i++) {
410                 free_func_state(state->frame[i]);
411                 state->frame[i] = NULL;
412         }
413         if (free_self)
414                 kfree(state);
415 }
416
417 /* copy verifier state from src to dst growing dst stack space
418  * when necessary to accommodate larger src stack
419  */
420 static int copy_func_state(struct bpf_func_state *dst,
421                            const struct bpf_func_state *src)
422 {
423         int err;
424
425         err = realloc_func_state(dst, src->allocated_stack, false);
426         if (err)
427                 return err;
428         memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
429         return copy_stack_state(dst, src);
430 }
431
432 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
433                                const struct bpf_verifier_state *src)
434 {
435         struct bpf_func_state *dst;
436         int i, err;
437
438         /* if dst has more stack frames then src frame, free them */
439         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
440                 free_func_state(dst_state->frame[i]);
441                 dst_state->frame[i] = NULL;
442         }
443         dst_state->curframe = src->curframe;
444         dst_state->parent = src->parent;
445         for (i = 0; i <= src->curframe; i++) {
446                 dst = dst_state->frame[i];
447                 if (!dst) {
448                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
449                         if (!dst)
450                                 return -ENOMEM;
451                         dst_state->frame[i] = dst;
452                 }
453                 err = copy_func_state(dst, src->frame[i]);
454                 if (err)
455                         return err;
456         }
457         return 0;
458 }
459
460 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
461                      int *insn_idx)
462 {
463         struct bpf_verifier_state *cur = env->cur_state;
464         struct bpf_verifier_stack_elem *elem, *head = env->head;
465         int err;
466
467         if (env->head == NULL)
468                 return -ENOENT;
469
470         if (cur) {
471                 err = copy_verifier_state(cur, &head->st);
472                 if (err)
473                         return err;
474         }
475         if (insn_idx)
476                 *insn_idx = head->insn_idx;
477         if (prev_insn_idx)
478                 *prev_insn_idx = head->prev_insn_idx;
479         elem = head->next;
480         free_verifier_state(&head->st, false);
481         kfree(head);
482         env->head = elem;
483         env->stack_size--;
484         return 0;
485 }
486
487 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
488                                              int insn_idx, int prev_insn_idx)
489 {
490         struct bpf_verifier_state *cur = env->cur_state;
491         struct bpf_verifier_stack_elem *elem;
492         int err;
493
494         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
495         if (!elem)
496                 goto err;
497
498         elem->insn_idx = insn_idx;
499         elem->prev_insn_idx = prev_insn_idx;
500         elem->next = env->head;
501         env->head = elem;
502         env->stack_size++;
503         err = copy_verifier_state(&elem->st, cur);
504         if (err)
505                 goto err;
506         if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
507                 verbose(env, "BPF program is too complex\n");
508                 goto err;
509         }
510         return &elem->st;
511 err:
512         free_verifier_state(env->cur_state, true);
513         env->cur_state = NULL;
514         /* pop all elements and return */
515         while (!pop_stack(env, NULL, NULL));
516         return NULL;
517 }
518
519 #define CALLER_SAVED_REGS 6
520 static const int caller_saved[CALLER_SAVED_REGS] = {
521         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
522 };
523
524 static void __mark_reg_not_init(struct bpf_reg_state *reg);
525
526 /* Mark the unknown part of a register (variable offset or scalar value) as
527  * known to have the value @imm.
528  */
529 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
530 {
531         reg->id = 0;
532         reg->var_off = tnum_const(imm);
533         reg->smin_value = (s64)imm;
534         reg->smax_value = (s64)imm;
535         reg->umin_value = imm;
536         reg->umax_value = imm;
537 }
538
539 /* Mark the 'variable offset' part of a register as zero.  This should be
540  * used only on registers holding a pointer type.
541  */
542 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
543 {
544         __mark_reg_known(reg, 0);
545 }
546
547 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
548 {
549         __mark_reg_known(reg, 0);
550         reg->off = 0;
551         reg->type = SCALAR_VALUE;
552 }
553
554 static void mark_reg_known_zero(struct bpf_verifier_env *env,
555                                 struct bpf_reg_state *regs, u32 regno)
556 {
557         if (WARN_ON(regno >= MAX_BPF_REG)) {
558                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
559                 /* Something bad happened, let's kill all regs */
560                 for (regno = 0; regno < MAX_BPF_REG; regno++)
561                         __mark_reg_not_init(regs + regno);
562                 return;
563         }
564         __mark_reg_known_zero(regs + regno);
565 }
566
567 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
568 {
569         return type_is_pkt_pointer(reg->type);
570 }
571
572 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
573 {
574         return reg_is_pkt_pointer(reg) ||
575                reg->type == PTR_TO_PACKET_END;
576 }
577
578 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
579 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
580                                     enum bpf_reg_type which)
581 {
582         /* The register can already have a range from prior markings.
583          * This is fine as long as it hasn't been advanced from its
584          * origin.
585          */
586         return reg->type == which &&
587                reg->id == 0 &&
588                reg->off == 0 &&
589                tnum_equals_const(reg->var_off, 0);
590 }
591
592 /* Attempts to improve min/max values based on var_off information */
593 static void __update_reg_bounds(struct bpf_reg_state *reg)
594 {
595         /* min signed is max(sign bit) | min(other bits) */
596         reg->smin_value = max_t(s64, reg->smin_value,
597                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
598         /* max signed is min(sign bit) | max(other bits) */
599         reg->smax_value = min_t(s64, reg->smax_value,
600                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
601         reg->umin_value = max(reg->umin_value, reg->var_off.value);
602         reg->umax_value = min(reg->umax_value,
603                               reg->var_off.value | reg->var_off.mask);
604 }
605
606 /* Uses signed min/max values to inform unsigned, and vice-versa */
607 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
608 {
609         /* Learn sign from signed bounds.
610          * If we cannot cross the sign boundary, then signed and unsigned bounds
611          * are the same, so combine.  This works even in the negative case, e.g.
612          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
613          */
614         if (reg->smin_value >= 0 || reg->smax_value < 0) {
615                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
616                                                           reg->umin_value);
617                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
618                                                           reg->umax_value);
619                 return;
620         }
621         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
622          * boundary, so we must be careful.
623          */
624         if ((s64)reg->umax_value >= 0) {
625                 /* Positive.  We can't learn anything from the smin, but smax
626                  * is positive, hence safe.
627                  */
628                 reg->smin_value = reg->umin_value;
629                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
630                                                           reg->umax_value);
631         } else if ((s64)reg->umin_value < 0) {
632                 /* Negative.  We can't learn anything from the smax, but smin
633                  * is negative, hence safe.
634                  */
635                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
636                                                           reg->umin_value);
637                 reg->smax_value = reg->umax_value;
638         }
639 }
640
641 /* Attempts to improve var_off based on unsigned min/max information */
642 static void __reg_bound_offset(struct bpf_reg_state *reg)
643 {
644         reg->var_off = tnum_intersect(reg->var_off,
645                                       tnum_range(reg->umin_value,
646                                                  reg->umax_value));
647 }
648
649 /* Reset the min/max bounds of a register */
650 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
651 {
652         reg->smin_value = S64_MIN;
653         reg->smax_value = S64_MAX;
654         reg->umin_value = 0;
655         reg->umax_value = U64_MAX;
656 }
657
658 /* Mark a register as having a completely unknown (scalar) value. */
659 static void __mark_reg_unknown(struct bpf_reg_state *reg)
660 {
661         reg->type = SCALAR_VALUE;
662         reg->id = 0;
663         reg->off = 0;
664         reg->var_off = tnum_unknown;
665         reg->frameno = 0;
666         __mark_reg_unbounded(reg);
667 }
668
669 static void mark_reg_unknown(struct bpf_verifier_env *env,
670                              struct bpf_reg_state *regs, u32 regno)
671 {
672         if (WARN_ON(regno >= MAX_BPF_REG)) {
673                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
674                 /* Something bad happened, let's kill all regs except FP */
675                 for (regno = 0; regno < BPF_REG_FP; regno++)
676                         __mark_reg_not_init(regs + regno);
677                 return;
678         }
679         __mark_reg_unknown(regs + regno);
680 }
681
682 static void __mark_reg_not_init(struct bpf_reg_state *reg)
683 {
684         __mark_reg_unknown(reg);
685         reg->type = NOT_INIT;
686 }
687
688 static void mark_reg_not_init(struct bpf_verifier_env *env,
689                               struct bpf_reg_state *regs, u32 regno)
690 {
691         if (WARN_ON(regno >= MAX_BPF_REG)) {
692                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
693                 /* Something bad happened, let's kill all regs except FP */
694                 for (regno = 0; regno < BPF_REG_FP; regno++)
695                         __mark_reg_not_init(regs + regno);
696                 return;
697         }
698         __mark_reg_not_init(regs + regno);
699 }
700
701 static void init_reg_state(struct bpf_verifier_env *env,
702                            struct bpf_func_state *state)
703 {
704         struct bpf_reg_state *regs = state->regs;
705         int i;
706
707         for (i = 0; i < MAX_BPF_REG; i++) {
708                 mark_reg_not_init(env, regs, i);
709                 regs[i].live = REG_LIVE_NONE;
710         }
711
712         /* frame pointer */
713         regs[BPF_REG_FP].type = PTR_TO_STACK;
714         mark_reg_known_zero(env, regs, BPF_REG_FP);
715         regs[BPF_REG_FP].frameno = state->frameno;
716
717         /* 1st arg to a function */
718         regs[BPF_REG_1].type = PTR_TO_CTX;
719         mark_reg_known_zero(env, regs, BPF_REG_1);
720 }
721
722 #define BPF_MAIN_FUNC (-1)
723 static void init_func_state(struct bpf_verifier_env *env,
724                             struct bpf_func_state *state,
725                             int callsite, int frameno, int subprogno)
726 {
727         state->callsite = callsite;
728         state->frameno = frameno;
729         state->subprogno = subprogno;
730         init_reg_state(env, state);
731 }
732
733 enum reg_arg_type {
734         SRC_OP,         /* register is used as source operand */
735         DST_OP,         /* register is used as destination operand */
736         DST_OP_NO_MARK  /* same as above, check only, don't mark */
737 };
738
739 static int cmp_subprogs(const void *a, const void *b)
740 {
741         return *(int *)a - *(int *)b;
742 }
743
744 static int find_subprog(struct bpf_verifier_env *env, int off)
745 {
746         u32 *p;
747
748         p = bsearch(&off, env->subprog_starts, env->subprog_cnt,
749                     sizeof(env->subprog_starts[0]), cmp_subprogs);
750         if (!p)
751                 return -ENOENT;
752         return p - env->subprog_starts;
753
754 }
755
756 static int add_subprog(struct bpf_verifier_env *env, int off)
757 {
758         int insn_cnt = env->prog->len;
759         int ret;
760
761         if (off >= insn_cnt || off < 0) {
762                 verbose(env, "call to invalid destination\n");
763                 return -EINVAL;
764         }
765         ret = find_subprog(env, off);
766         if (ret >= 0)
767                 return 0;
768         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
769                 verbose(env, "too many subprograms\n");
770                 return -E2BIG;
771         }
772         env->subprog_starts[env->subprog_cnt++] = off;
773         sort(env->subprog_starts, env->subprog_cnt,
774              sizeof(env->subprog_starts[0]), cmp_subprogs, NULL);
775         return 0;
776 }
777
778 static int check_subprogs(struct bpf_verifier_env *env)
779 {
780         int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
781         struct bpf_insn *insn = env->prog->insnsi;
782         int insn_cnt = env->prog->len;
783
784         /* determine subprog starts. The end is one before the next starts */
785         for (i = 0; i < insn_cnt; i++) {
786                 if (insn[i].code != (BPF_JMP | BPF_CALL))
787                         continue;
788                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
789                         continue;
790                 if (!env->allow_ptr_leaks) {
791                         verbose(env, "function calls to other bpf functions are allowed for root only\n");
792                         return -EPERM;
793                 }
794                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
795                         verbose(env, "function calls in offloaded programs are not supported yet\n");
796                         return -EINVAL;
797                 }
798                 ret = add_subprog(env, i + insn[i].imm + 1);
799                 if (ret < 0)
800                         return ret;
801         }
802
803         if (env->log.level > 1)
804                 for (i = 0; i < env->subprog_cnt; i++)
805                         verbose(env, "func#%d @%d\n", i, env->subprog_starts[i]);
806
807         /* now check that all jumps are within the same subprog */
808         subprog_start = 0;
809         if (env->subprog_cnt == cur_subprog)
810                 subprog_end = insn_cnt;
811         else
812                 subprog_end = env->subprog_starts[cur_subprog++];
813         for (i = 0; i < insn_cnt; i++) {
814                 u8 code = insn[i].code;
815
816                 if (BPF_CLASS(code) != BPF_JMP)
817                         goto next;
818                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
819                         goto next;
820                 off = i + insn[i].off + 1;
821                 if (off < subprog_start || off >= subprog_end) {
822                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
823                         return -EINVAL;
824                 }
825 next:
826                 if (i == subprog_end - 1) {
827                         /* to avoid fall-through from one subprog into another
828                          * the last insn of the subprog should be either exit
829                          * or unconditional jump back
830                          */
831                         if (code != (BPF_JMP | BPF_EXIT) &&
832                             code != (BPF_JMP | BPF_JA)) {
833                                 verbose(env, "last insn is not an exit or jmp\n");
834                                 return -EINVAL;
835                         }
836                         subprog_start = subprog_end;
837                         if (env->subprog_cnt == cur_subprog)
838                                 subprog_end = insn_cnt;
839                         else
840                                 subprog_end = env->subprog_starts[cur_subprog++];
841                 }
842         }
843         return 0;
844 }
845
846 static
847 struct bpf_verifier_state *skip_callee(struct bpf_verifier_env *env,
848                                        const struct bpf_verifier_state *state,
849                                        struct bpf_verifier_state *parent,
850                                        u32 regno)
851 {
852         struct bpf_verifier_state *tmp = NULL;
853
854         /* 'parent' could be a state of caller and
855          * 'state' could be a state of callee. In such case
856          * parent->curframe < state->curframe
857          * and it's ok for r1 - r5 registers
858          *
859          * 'parent' could be a callee's state after it bpf_exit-ed.
860          * In such case parent->curframe > state->curframe
861          * and it's ok for r0 only
862          */
863         if (parent->curframe == state->curframe ||
864             (parent->curframe < state->curframe &&
865              regno >= BPF_REG_1 && regno <= BPF_REG_5) ||
866             (parent->curframe > state->curframe &&
867                regno == BPF_REG_0))
868                 return parent;
869
870         if (parent->curframe > state->curframe &&
871             regno >= BPF_REG_6) {
872                 /* for callee saved regs we have to skip the whole chain
873                  * of states that belong to callee and mark as LIVE_READ
874                  * the registers before the call
875                  */
876                 tmp = parent;
877                 while (tmp && tmp->curframe != state->curframe) {
878                         tmp = tmp->parent;
879                 }
880                 if (!tmp)
881                         goto bug;
882                 parent = tmp;
883         } else {
884                 goto bug;
885         }
886         return parent;
887 bug:
888         verbose(env, "verifier bug regno %d tmp %p\n", regno, tmp);
889         verbose(env, "regno %d parent frame %d current frame %d\n",
890                 regno, parent->curframe, state->curframe);
891         return NULL;
892 }
893
894 static int mark_reg_read(struct bpf_verifier_env *env,
895                          const struct bpf_verifier_state *state,
896                          struct bpf_verifier_state *parent,
897                          u32 regno)
898 {
899         bool writes = parent == state->parent; /* Observe write marks */
900
901         if (regno == BPF_REG_FP)
902                 /* We don't need to worry about FP liveness because it's read-only */
903                 return 0;
904
905         while (parent) {
906                 /* if read wasn't screened by an earlier write ... */
907                 if (writes && state->frame[state->curframe]->regs[regno].live & REG_LIVE_WRITTEN)
908                         break;
909                 parent = skip_callee(env, state, parent, regno);
910                 if (!parent)
911                         return -EFAULT;
912                 /* ... then we depend on parent's value */
913                 parent->frame[parent->curframe]->regs[regno].live |= REG_LIVE_READ;
914                 state = parent;
915                 parent = state->parent;
916                 writes = true;
917         }
918         return 0;
919 }
920
921 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
922                          enum reg_arg_type t)
923 {
924         struct bpf_verifier_state *vstate = env->cur_state;
925         struct bpf_func_state *state = vstate->frame[vstate->curframe];
926         struct bpf_reg_state *regs = state->regs;
927
928         if (regno >= MAX_BPF_REG) {
929                 verbose(env, "R%d is invalid\n", regno);
930                 return -EINVAL;
931         }
932
933         if (t == SRC_OP) {
934                 /* check whether register used as source operand can be read */
935                 if (regs[regno].type == NOT_INIT) {
936                         verbose(env, "R%d !read_ok\n", regno);
937                         return -EACCES;
938                 }
939                 return mark_reg_read(env, vstate, vstate->parent, regno);
940         } else {
941                 /* check whether register used as dest operand can be written to */
942                 if (regno == BPF_REG_FP) {
943                         verbose(env, "frame pointer is read only\n");
944                         return -EACCES;
945                 }
946                 regs[regno].live |= REG_LIVE_WRITTEN;
947                 if (t == DST_OP)
948                         mark_reg_unknown(env, regs, regno);
949         }
950         return 0;
951 }
952
953 static bool is_spillable_regtype(enum bpf_reg_type type)
954 {
955         switch (type) {
956         case PTR_TO_MAP_VALUE:
957         case PTR_TO_MAP_VALUE_OR_NULL:
958         case PTR_TO_STACK:
959         case PTR_TO_CTX:
960         case PTR_TO_PACKET:
961         case PTR_TO_PACKET_META:
962         case PTR_TO_PACKET_END:
963         case CONST_PTR_TO_MAP:
964                 return true;
965         default:
966                 return false;
967         }
968 }
969
970 /* Does this register contain a constant zero? */
971 static bool register_is_null(struct bpf_reg_state *reg)
972 {
973         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
974 }
975
976 /* check_stack_read/write functions track spill/fill of registers,
977  * stack boundary and alignment are checked in check_mem_access()
978  */
979 static int check_stack_write(struct bpf_verifier_env *env,
980                              struct bpf_func_state *state, /* func where register points to */
981                              int off, int size, int value_regno)
982 {
983         struct bpf_func_state *cur; /* state of the current function */
984         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
985         enum bpf_reg_type type;
986
987         err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
988                                  true);
989         if (err)
990                 return err;
991         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
992          * so it's aligned access and [off, off + size) are within stack limits
993          */
994         if (!env->allow_ptr_leaks &&
995             state->stack[spi].slot_type[0] == STACK_SPILL &&
996             size != BPF_REG_SIZE) {
997                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
998                 return -EACCES;
999         }
1000
1001         cur = env->cur_state->frame[env->cur_state->curframe];
1002         if (value_regno >= 0 &&
1003             is_spillable_regtype((type = cur->regs[value_regno].type))) {
1004
1005                 /* register containing pointer is being spilled into stack */
1006                 if (size != BPF_REG_SIZE) {
1007                         verbose(env, "invalid size of register spill\n");
1008                         return -EACCES;
1009                 }
1010
1011                 if (state != cur && type == PTR_TO_STACK) {
1012                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1013                         return -EINVAL;
1014                 }
1015
1016                 /* save register state */
1017                 state->stack[spi].spilled_ptr = cur->regs[value_regno];
1018                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1019
1020                 for (i = 0; i < BPF_REG_SIZE; i++)
1021                         state->stack[spi].slot_type[i] = STACK_SPILL;
1022         } else {
1023                 u8 type = STACK_MISC;
1024
1025                 /* regular write of data into stack */
1026                 state->stack[spi].spilled_ptr = (struct bpf_reg_state) {};
1027
1028                 /* only mark the slot as written if all 8 bytes were written
1029                  * otherwise read propagation may incorrectly stop too soon
1030                  * when stack slots are partially written.
1031                  * This heuristic means that read propagation will be
1032                  * conservative, since it will add reg_live_read marks
1033                  * to stack slots all the way to first state when programs
1034                  * writes+reads less than 8 bytes
1035                  */
1036                 if (size == BPF_REG_SIZE)
1037                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1038
1039                 /* when we zero initialize stack slots mark them as such */
1040                 if (value_regno >= 0 &&
1041                     register_is_null(&cur->regs[value_regno]))
1042                         type = STACK_ZERO;
1043
1044                 for (i = 0; i < size; i++)
1045                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1046                                 type;
1047         }
1048         return 0;
1049 }
1050
1051 /* registers of every function are unique and mark_reg_read() propagates
1052  * the liveness in the following cases:
1053  * - from callee into caller for R1 - R5 that were used as arguments
1054  * - from caller into callee for R0 that used as result of the call
1055  * - from caller to the same caller skipping states of the callee for R6 - R9,
1056  *   since R6 - R9 are callee saved by implicit function prologue and
1057  *   caller's R6 != callee's R6, so when we propagate liveness up to
1058  *   parent states we need to skip callee states for R6 - R9.
1059  *
1060  * stack slot marking is different, since stacks of caller and callee are
1061  * accessible in both (since caller can pass a pointer to caller's stack to
1062  * callee which can pass it to another function), hence mark_stack_slot_read()
1063  * has to propagate the stack liveness to all parent states at given frame number.
1064  * Consider code:
1065  * f1() {
1066  *   ptr = fp - 8;
1067  *   *ptr = ctx;
1068  *   call f2 {
1069  *      .. = *ptr;
1070  *   }
1071  *   .. = *ptr;
1072  * }
1073  * First *ptr is reading from f1's stack and mark_stack_slot_read() has
1074  * to mark liveness at the f1's frame and not f2's frame.
1075  * Second *ptr is also reading from f1's stack and mark_stack_slot_read() has
1076  * to propagate liveness to f2 states at f1's frame level and further into
1077  * f1 states at f1's frame level until write into that stack slot
1078  */
1079 static void mark_stack_slot_read(struct bpf_verifier_env *env,
1080                                  const struct bpf_verifier_state *state,
1081                                  struct bpf_verifier_state *parent,
1082                                  int slot, int frameno)
1083 {
1084         bool writes = parent == state->parent; /* Observe write marks */
1085
1086         while (parent) {
1087                 if (parent->frame[frameno]->allocated_stack <= slot * BPF_REG_SIZE)
1088                         /* since LIVE_WRITTEN mark is only done for full 8-byte
1089                          * write the read marks are conservative and parent
1090                          * state may not even have the stack allocated. In such case
1091                          * end the propagation, since the loop reached beginning
1092                          * of the function
1093                          */
1094                         break;
1095                 /* if read wasn't screened by an earlier write ... */
1096                 if (writes && state->frame[frameno]->stack[slot].spilled_ptr.live & REG_LIVE_WRITTEN)
1097                         break;
1098                 /* ... then we depend on parent's value */
1099                 parent->frame[frameno]->stack[slot].spilled_ptr.live |= REG_LIVE_READ;
1100                 state = parent;
1101                 parent = state->parent;
1102                 writes = true;
1103         }
1104 }
1105
1106 static int check_stack_read(struct bpf_verifier_env *env,
1107                             struct bpf_func_state *reg_state /* func where register points to */,
1108                             int off, int size, int value_regno)
1109 {
1110         struct bpf_verifier_state *vstate = env->cur_state;
1111         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1112         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1113         u8 *stype;
1114
1115         if (reg_state->allocated_stack <= slot) {
1116                 verbose(env, "invalid read from stack off %d+0 size %d\n",
1117                         off, size);
1118                 return -EACCES;
1119         }
1120         stype = reg_state->stack[spi].slot_type;
1121
1122         if (stype[0] == STACK_SPILL) {
1123                 if (size != BPF_REG_SIZE) {
1124                         verbose(env, "invalid size of register spill\n");
1125                         return -EACCES;
1126                 }
1127                 for (i = 1; i < BPF_REG_SIZE; i++) {
1128                         if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1129                                 verbose(env, "corrupted spill memory\n");
1130                                 return -EACCES;
1131                         }
1132                 }
1133
1134                 if (value_regno >= 0) {
1135                         /* restore register state from stack */
1136                         state->regs[value_regno] = reg_state->stack[spi].spilled_ptr;
1137                         /* mark reg as written since spilled pointer state likely
1138                          * has its liveness marks cleared by is_state_visited()
1139                          * which resets stack/reg liveness for state transitions
1140                          */
1141                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1142                 }
1143                 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1144                                      reg_state->frameno);
1145                 return 0;
1146         } else {
1147                 int zeros = 0;
1148
1149                 for (i = 0; i < size; i++) {
1150                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1151                                 continue;
1152                         if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1153                                 zeros++;
1154                                 continue;
1155                         }
1156                         verbose(env, "invalid read from stack off %d+%d size %d\n",
1157                                 off, i, size);
1158                         return -EACCES;
1159                 }
1160                 mark_stack_slot_read(env, vstate, vstate->parent, spi,
1161                                      reg_state->frameno);
1162                 if (value_regno >= 0) {
1163                         if (zeros == size) {
1164                                 /* any size read into register is zero extended,
1165                                  * so the whole register == const_zero
1166                                  */
1167                                 __mark_reg_const_zero(&state->regs[value_regno]);
1168                         } else {
1169                                 /* have read misc data from the stack */
1170                                 mark_reg_unknown(env, state->regs, value_regno);
1171                         }
1172                         state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1173                 }
1174                 return 0;
1175         }
1176 }
1177
1178 /* check read/write into map element returned by bpf_map_lookup_elem() */
1179 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1180                               int size, bool zero_size_allowed)
1181 {
1182         struct bpf_reg_state *regs = cur_regs(env);
1183         struct bpf_map *map = regs[regno].map_ptr;
1184
1185         if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1186             off + size > map->value_size) {
1187                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1188                         map->value_size, off, size);
1189                 return -EACCES;
1190         }
1191         return 0;
1192 }
1193
1194 /* check read/write into a map element with possible variable offset */
1195 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1196                             int off, int size, bool zero_size_allowed)
1197 {
1198         struct bpf_verifier_state *vstate = env->cur_state;
1199         struct bpf_func_state *state = vstate->frame[vstate->curframe];
1200         struct bpf_reg_state *reg = &state->regs[regno];
1201         int err;
1202
1203         /* We may have adjusted the register to this map value, so we
1204          * need to try adding each of min_value and max_value to off
1205          * to make sure our theoretical access will be safe.
1206          */
1207         if (env->log.level)
1208                 print_verifier_state(env, state);
1209         /* The minimum value is only important with signed
1210          * comparisons where we can't assume the floor of a
1211          * value is 0.  If we are using signed variables for our
1212          * index'es we need to make sure that whatever we use
1213          * will have a set floor within our range.
1214          */
1215         if (reg->smin_value < 0) {
1216                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1217                         regno);
1218                 return -EACCES;
1219         }
1220         err = __check_map_access(env, regno, reg->smin_value + off, size,
1221                                  zero_size_allowed);
1222         if (err) {
1223                 verbose(env, "R%d min value is outside of the array range\n",
1224                         regno);
1225                 return err;
1226         }
1227
1228         /* If we haven't set a max value then we need to bail since we can't be
1229          * sure we won't do bad things.
1230          * If reg->umax_value + off could overflow, treat that as unbounded too.
1231          */
1232         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1233                 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1234                         regno);
1235                 return -EACCES;
1236         }
1237         err = __check_map_access(env, regno, reg->umax_value + off, size,
1238                                  zero_size_allowed);
1239         if (err)
1240                 verbose(env, "R%d max value is outside of the array range\n",
1241                         regno);
1242         return err;
1243 }
1244
1245 #define MAX_PACKET_OFF 0xffff
1246
1247 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1248                                        const struct bpf_call_arg_meta *meta,
1249                                        enum bpf_access_type t)
1250 {
1251         switch (env->prog->type) {
1252         case BPF_PROG_TYPE_LWT_IN:
1253         case BPF_PROG_TYPE_LWT_OUT:
1254                 /* dst_input() and dst_output() can't write for now */
1255                 if (t == BPF_WRITE)
1256                         return false;
1257                 /* fallthrough */
1258         case BPF_PROG_TYPE_SCHED_CLS:
1259         case BPF_PROG_TYPE_SCHED_ACT:
1260         case BPF_PROG_TYPE_XDP:
1261         case BPF_PROG_TYPE_LWT_XMIT:
1262         case BPF_PROG_TYPE_SK_SKB:
1263         case BPF_PROG_TYPE_SK_MSG:
1264                 if (meta)
1265                         return meta->pkt_access;
1266
1267                 env->seen_direct_write = true;
1268                 return true;
1269         default:
1270                 return false;
1271         }
1272 }
1273
1274 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1275                                  int off, int size, bool zero_size_allowed)
1276 {
1277         struct bpf_reg_state *regs = cur_regs(env);
1278         struct bpf_reg_state *reg = &regs[regno];
1279
1280         if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1281             (u64)off + size > reg->range) {
1282                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1283                         off, size, regno, reg->id, reg->off, reg->range);
1284                 return -EACCES;
1285         }
1286         return 0;
1287 }
1288
1289 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1290                                int size, bool zero_size_allowed)
1291 {
1292         struct bpf_reg_state *regs = cur_regs(env);
1293         struct bpf_reg_state *reg = &regs[regno];
1294         int err;
1295
1296         /* We may have added a variable offset to the packet pointer; but any
1297          * reg->range we have comes after that.  We are only checking the fixed
1298          * offset.
1299          */
1300
1301         /* We don't allow negative numbers, because we aren't tracking enough
1302          * detail to prove they're safe.
1303          */
1304         if (reg->smin_value < 0) {
1305                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1306                         regno);
1307                 return -EACCES;
1308         }
1309         err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1310         if (err) {
1311                 verbose(env, "R%d offset is outside of the packet\n", regno);
1312                 return err;
1313         }
1314         return err;
1315 }
1316
1317 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
1318 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1319                             enum bpf_access_type t, enum bpf_reg_type *reg_type)
1320 {
1321         struct bpf_insn_access_aux info = {
1322                 .reg_type = *reg_type,
1323         };
1324
1325         if (env->ops->is_valid_access &&
1326             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1327                 /* A non zero info.ctx_field_size indicates that this field is a
1328                  * candidate for later verifier transformation to load the whole
1329                  * field and then apply a mask when accessed with a narrower
1330                  * access than actual ctx access size. A zero info.ctx_field_size
1331                  * will only allow for whole field access and rejects any other
1332                  * type of narrower access.
1333                  */
1334                 *reg_type = info.reg_type;
1335
1336                 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1337                 /* remember the offset of last byte accessed in ctx */
1338                 if (env->prog->aux->max_ctx_offset < off + size)
1339                         env->prog->aux->max_ctx_offset = off + size;
1340                 return 0;
1341         }
1342
1343         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1344         return -EACCES;
1345 }
1346
1347 static bool __is_pointer_value(bool allow_ptr_leaks,
1348                                const struct bpf_reg_state *reg)
1349 {
1350         if (allow_ptr_leaks)
1351                 return false;
1352
1353         return reg->type != SCALAR_VALUE;
1354 }
1355
1356 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1357 {
1358         return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1359 }
1360
1361 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1362 {
1363         const struct bpf_reg_state *reg = cur_regs(env) + regno;
1364
1365         return reg->type == PTR_TO_CTX;
1366 }
1367
1368 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1369 {
1370         const struct bpf_reg_state *reg = cur_regs(env) + regno;
1371
1372         return type_is_pkt_pointer(reg->type);
1373 }
1374
1375 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1376                                    const struct bpf_reg_state *reg,
1377                                    int off, int size, bool strict)
1378 {
1379         struct tnum reg_off;
1380         int ip_align;
1381
1382         /* Byte size accesses are always allowed. */
1383         if (!strict || size == 1)
1384                 return 0;
1385
1386         /* For platforms that do not have a Kconfig enabling
1387          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1388          * NET_IP_ALIGN is universally set to '2'.  And on platforms
1389          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1390          * to this code only in strict mode where we want to emulate
1391          * the NET_IP_ALIGN==2 checking.  Therefore use an
1392          * unconditional IP align value of '2'.
1393          */
1394         ip_align = 2;
1395
1396         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1397         if (!tnum_is_aligned(reg_off, size)) {
1398                 char tn_buf[48];
1399
1400                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1401                 verbose(env,
1402                         "misaligned packet access off %d+%s+%d+%d size %d\n",
1403                         ip_align, tn_buf, reg->off, off, size);
1404                 return -EACCES;
1405         }
1406
1407         return 0;
1408 }
1409
1410 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1411                                        const struct bpf_reg_state *reg,
1412                                        const char *pointer_desc,
1413                                        int off, int size, bool strict)
1414 {
1415         struct tnum reg_off;
1416
1417         /* Byte size accesses are always allowed. */
1418         if (!strict || size == 1)
1419                 return 0;
1420
1421         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1422         if (!tnum_is_aligned(reg_off, size)) {
1423                 char tn_buf[48];
1424
1425                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1426                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1427                         pointer_desc, tn_buf, reg->off, off, size);
1428                 return -EACCES;
1429         }
1430
1431         return 0;
1432 }
1433
1434 static int check_ptr_alignment(struct bpf_verifier_env *env,
1435                                const struct bpf_reg_state *reg, int off,
1436                                int size, bool strict_alignment_once)
1437 {
1438         bool strict = env->strict_alignment || strict_alignment_once;
1439         const char *pointer_desc = "";
1440
1441         switch (reg->type) {
1442         case PTR_TO_PACKET:
1443         case PTR_TO_PACKET_META:
1444                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1445                  * right in front, treat it the very same way.
1446                  */
1447                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1448         case PTR_TO_MAP_VALUE:
1449                 pointer_desc = "value ";
1450                 break;
1451         case PTR_TO_CTX:
1452                 pointer_desc = "context ";
1453                 break;
1454         case PTR_TO_STACK:
1455                 pointer_desc = "stack ";
1456                 /* The stack spill tracking logic in check_stack_write()
1457                  * and check_stack_read() relies on stack accesses being
1458                  * aligned.
1459                  */
1460                 strict = true;
1461                 break;
1462         default:
1463                 break;
1464         }
1465         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1466                                            strict);
1467 }
1468
1469 static int update_stack_depth(struct bpf_verifier_env *env,
1470                               const struct bpf_func_state *func,
1471                               int off)
1472 {
1473         u16 stack = env->subprog_stack_depth[func->subprogno];
1474
1475         if (stack >= -off)
1476                 return 0;
1477
1478         /* update known max for given subprogram */
1479         env->subprog_stack_depth[func->subprogno] = -off;
1480         return 0;
1481 }
1482
1483 /* starting from main bpf function walk all instructions of the function
1484  * and recursively walk all callees that given function can call.
1485  * Ignore jump and exit insns.
1486  * Since recursion is prevented by check_cfg() this algorithm
1487  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1488  */
1489 static int check_max_stack_depth(struct bpf_verifier_env *env)
1490 {
1491         int depth = 0, frame = 0, subprog = 0, i = 0, subprog_end;
1492         struct bpf_insn *insn = env->prog->insnsi;
1493         int insn_cnt = env->prog->len;
1494         int ret_insn[MAX_CALL_FRAMES];
1495         int ret_prog[MAX_CALL_FRAMES];
1496
1497 process_func:
1498         /* round up to 32-bytes, since this is granularity
1499          * of interpreter stack size
1500          */
1501         depth += round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1502         if (depth > MAX_BPF_STACK) {
1503                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1504                         frame + 1, depth);
1505                 return -EACCES;
1506         }
1507 continue_func:
1508         if (env->subprog_cnt == subprog)
1509                 subprog_end = insn_cnt;
1510         else
1511                 subprog_end = env->subprog_starts[subprog];
1512         for (; i < subprog_end; i++) {
1513                 if (insn[i].code != (BPF_JMP | BPF_CALL))
1514                         continue;
1515                 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1516                         continue;
1517                 /* remember insn and function to return to */
1518                 ret_insn[frame] = i + 1;
1519                 ret_prog[frame] = subprog;
1520
1521                 /* find the callee */
1522                 i = i + insn[i].imm + 1;
1523                 subprog = find_subprog(env, i);
1524                 if (subprog < 0) {
1525                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1526                                   i);
1527                         return -EFAULT;
1528                 }
1529                 subprog++;
1530                 frame++;
1531                 if (frame >= MAX_CALL_FRAMES) {
1532                         WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1533                         return -EFAULT;
1534                 }
1535                 goto process_func;
1536         }
1537         /* end of for() loop means the last insn of the 'subprog'
1538          * was reached. Doesn't matter whether it was JA or EXIT
1539          */
1540         if (frame == 0)
1541                 return 0;
1542         depth -= round_up(max_t(u32, env->subprog_stack_depth[subprog], 1), 32);
1543         frame--;
1544         i = ret_insn[frame];
1545         subprog = ret_prog[frame];
1546         goto continue_func;
1547 }
1548
1549 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1550 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1551                                   const struct bpf_insn *insn, int idx)
1552 {
1553         int start = idx + insn->imm + 1, subprog;
1554
1555         subprog = find_subprog(env, start);
1556         if (subprog < 0) {
1557                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1558                           start);
1559                 return -EFAULT;
1560         }
1561         subprog++;
1562         return env->subprog_stack_depth[subprog];
1563 }
1564 #endif
1565
1566 /* truncate register to smaller size (in bytes)
1567  * must be called with size < BPF_REG_SIZE
1568  */
1569 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1570 {
1571         u64 mask;
1572
1573         /* clear high bits in bit representation */
1574         reg->var_off = tnum_cast(reg->var_off, size);
1575
1576         /* fix arithmetic bounds */
1577         mask = ((u64)1 << (size * 8)) - 1;
1578         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1579                 reg->umin_value &= mask;
1580                 reg->umax_value &= mask;
1581         } else {
1582                 reg->umin_value = 0;
1583                 reg->umax_value = mask;
1584         }
1585         reg->smin_value = reg->umin_value;
1586         reg->smax_value = reg->umax_value;
1587 }
1588
1589 /* check whether memory at (regno + off) is accessible for t = (read | write)
1590  * if t==write, value_regno is a register which value is stored into memory
1591  * if t==read, value_regno is a register which will receive the value from memory
1592  * if t==write && value_regno==-1, some unknown value is stored into memory
1593  * if t==read && value_regno==-1, don't care what we read from memory
1594  */
1595 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1596                             int off, int bpf_size, enum bpf_access_type t,
1597                             int value_regno, bool strict_alignment_once)
1598 {
1599         struct bpf_reg_state *regs = cur_regs(env);
1600         struct bpf_reg_state *reg = regs + regno;
1601         struct bpf_func_state *state;
1602         int size, err = 0;
1603
1604         size = bpf_size_to_bytes(bpf_size);
1605         if (size < 0)
1606                 return size;
1607
1608         /* alignment checks will add in reg->off themselves */
1609         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1610         if (err)
1611                 return err;
1612
1613         /* for access checks, reg->off is just part of off */
1614         off += reg->off;
1615
1616         if (reg->type == PTR_TO_MAP_VALUE) {
1617                 if (t == BPF_WRITE && value_regno >= 0 &&
1618                     is_pointer_value(env, value_regno)) {
1619                         verbose(env, "R%d leaks addr into map\n", value_regno);
1620                         return -EACCES;
1621                 }
1622
1623                 err = check_map_access(env, regno, off, size, false);
1624                 if (!err && t == BPF_READ && value_regno >= 0)
1625                         mark_reg_unknown(env, regs, value_regno);
1626
1627         } else if (reg->type == PTR_TO_CTX) {
1628                 enum bpf_reg_type reg_type = SCALAR_VALUE;
1629
1630                 if (t == BPF_WRITE && value_regno >= 0 &&
1631                     is_pointer_value(env, value_regno)) {
1632                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
1633                         return -EACCES;
1634                 }
1635                 /* ctx accesses must be at a fixed offset, so that we can
1636                  * determine what type of data were returned.
1637                  */
1638                 if (reg->off) {
1639                         verbose(env,
1640                                 "dereference of modified ctx ptr R%d off=%d+%d, ctx+const is allowed, ctx+const+const is not\n",
1641                                 regno, reg->off, off - reg->off);
1642                         return -EACCES;
1643                 }
1644                 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1645                         char tn_buf[48];
1646
1647                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1648                         verbose(env,
1649                                 "variable ctx access var_off=%s off=%d size=%d",
1650                                 tn_buf, off, size);
1651                         return -EACCES;
1652                 }
1653                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type);
1654                 if (!err && t == BPF_READ && value_regno >= 0) {
1655                         /* ctx access returns either a scalar, or a
1656                          * PTR_TO_PACKET[_META,_END]. In the latter
1657                          * case, we know the offset is zero.
1658                          */
1659                         if (reg_type == SCALAR_VALUE)
1660                                 mark_reg_unknown(env, regs, value_regno);
1661                         else
1662                                 mark_reg_known_zero(env, regs,
1663                                                     value_regno);
1664                         regs[value_regno].id = 0;
1665                         regs[value_regno].off = 0;
1666                         regs[value_regno].range = 0;
1667                         regs[value_regno].type = reg_type;
1668                 }
1669
1670         } else if (reg->type == PTR_TO_STACK) {
1671                 /* stack accesses must be at a fixed offset, so that we can
1672                  * determine what type of data were returned.
1673                  * See check_stack_read().
1674                  */
1675                 if (!tnum_is_const(reg->var_off)) {
1676                         char tn_buf[48];
1677
1678                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1679                         verbose(env, "variable stack access var_off=%s off=%d size=%d",
1680                                 tn_buf, off, size);
1681                         return -EACCES;
1682                 }
1683                 off += reg->var_off.value;
1684                 if (off >= 0 || off < -MAX_BPF_STACK) {
1685                         verbose(env, "invalid stack off=%d size=%d\n", off,
1686                                 size);
1687                         return -EACCES;
1688                 }
1689
1690                 state = func(env, reg);
1691                 err = update_stack_depth(env, state, off);
1692                 if (err)
1693                         return err;
1694
1695                 if (t == BPF_WRITE)
1696                         err = check_stack_write(env, state, off, size,
1697                                                 value_regno);
1698                 else
1699                         err = check_stack_read(env, state, off, size,
1700                                                value_regno);
1701         } else if (reg_is_pkt_pointer(reg)) {
1702                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1703                         verbose(env, "cannot write into packet\n");
1704                         return -EACCES;
1705                 }
1706                 if (t == BPF_WRITE && value_regno >= 0 &&
1707                     is_pointer_value(env, value_regno)) {
1708                         verbose(env, "R%d leaks addr into packet\n",
1709                                 value_regno);
1710                         return -EACCES;
1711                 }
1712                 err = check_packet_access(env, regno, off, size, false);
1713                 if (!err && t == BPF_READ && value_regno >= 0)
1714                         mark_reg_unknown(env, regs, value_regno);
1715         } else {
1716                 verbose(env, "R%d invalid mem access '%s'\n", regno,
1717                         reg_type_str[reg->type]);
1718                 return -EACCES;
1719         }
1720
1721         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1722             regs[value_regno].type == SCALAR_VALUE) {
1723                 /* b/h/w load zero-extends, mark upper bits as known 0 */
1724                 coerce_reg_to_size(&regs[value_regno], size);
1725         }
1726         return err;
1727 }
1728
1729 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1730 {
1731         int err;
1732
1733         if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1734             insn->imm != 0) {
1735                 verbose(env, "BPF_XADD uses reserved fields\n");
1736                 return -EINVAL;
1737         }
1738
1739         /* check src1 operand */
1740         err = check_reg_arg(env, insn->src_reg, SRC_OP);
1741         if (err)
1742                 return err;
1743
1744         /* check src2 operand */
1745         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1746         if (err)
1747                 return err;
1748
1749         if (is_pointer_value(env, insn->src_reg)) {
1750                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1751                 return -EACCES;
1752         }
1753
1754         if (is_ctx_reg(env, insn->dst_reg) ||
1755             is_pkt_reg(env, insn->dst_reg)) {
1756                 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1757                         insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1758                         "context" : "packet");
1759                 return -EACCES;
1760         }
1761
1762         /* check whether atomic_add can read the memory */
1763         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1764                                BPF_SIZE(insn->code), BPF_READ, -1, true);
1765         if (err)
1766                 return err;
1767
1768         /* check whether atomic_add can write into the same memory */
1769         return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1770                                 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1771 }
1772
1773 /* when register 'regno' is passed into function that will read 'access_size'
1774  * bytes from that pointer, make sure that it's within stack boundary
1775  * and all elements of stack are initialized.
1776  * Unlike most pointer bounds-checking functions, this one doesn't take an
1777  * 'off' argument, so it has to add in reg->off itself.
1778  */
1779 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1780                                 int access_size, bool zero_size_allowed,
1781                                 struct bpf_call_arg_meta *meta)
1782 {
1783         struct bpf_reg_state *reg = cur_regs(env) + regno;
1784         struct bpf_func_state *state = func(env, reg);
1785         int off, i, slot, spi;
1786
1787         if (reg->type != PTR_TO_STACK) {
1788                 /* Allow zero-byte read from NULL, regardless of pointer type */
1789                 if (zero_size_allowed && access_size == 0 &&
1790                     register_is_null(reg))
1791                         return 0;
1792
1793                 verbose(env, "R%d type=%s expected=%s\n", regno,
1794                         reg_type_str[reg->type],
1795                         reg_type_str[PTR_TO_STACK]);
1796                 return -EACCES;
1797         }
1798
1799         /* Only allow fixed-offset stack reads */
1800         if (!tnum_is_const(reg->var_off)) {
1801                 char tn_buf[48];
1802
1803                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1804                 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1805                         regno, tn_buf);
1806                 return -EACCES;
1807         }
1808         off = reg->off + reg->var_off.value;
1809         if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1810             access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1811                 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1812                         regno, off, access_size);
1813                 return -EACCES;
1814         }
1815
1816         if (meta && meta->raw_mode) {
1817                 meta->access_size = access_size;
1818                 meta->regno = regno;
1819                 return 0;
1820         }
1821
1822         for (i = 0; i < access_size; i++) {
1823                 u8 *stype;
1824
1825                 slot = -(off + i) - 1;
1826                 spi = slot / BPF_REG_SIZE;
1827                 if (state->allocated_stack <= slot)
1828                         goto err;
1829                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1830                 if (*stype == STACK_MISC)
1831                         goto mark;
1832                 if (*stype == STACK_ZERO) {
1833                         /* helper can write anything into the stack */
1834                         *stype = STACK_MISC;
1835                         goto mark;
1836                 }
1837 err:
1838                 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1839                         off, i, access_size);
1840                 return -EACCES;
1841 mark:
1842                 /* reading any byte out of 8-byte 'spill_slot' will cause
1843                  * the whole slot to be marked as 'read'
1844                  */
1845                 mark_stack_slot_read(env, env->cur_state, env->cur_state->parent,
1846                                      spi, state->frameno);
1847         }
1848         return update_stack_depth(env, state, off);
1849 }
1850
1851 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1852                                    int access_size, bool zero_size_allowed,
1853                                    struct bpf_call_arg_meta *meta)
1854 {
1855         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1856
1857         switch (reg->type) {
1858         case PTR_TO_PACKET:
1859         case PTR_TO_PACKET_META:
1860                 return check_packet_access(env, regno, reg->off, access_size,
1861                                            zero_size_allowed);
1862         case PTR_TO_MAP_VALUE:
1863                 return check_map_access(env, regno, reg->off, access_size,
1864                                         zero_size_allowed);
1865         default: /* scalar_value|ptr_to_stack or invalid ptr */
1866                 return check_stack_boundary(env, regno, access_size,
1867                                             zero_size_allowed, meta);
1868         }
1869 }
1870
1871 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1872 {
1873         return type == ARG_PTR_TO_MEM ||
1874                type == ARG_PTR_TO_MEM_OR_NULL ||
1875                type == ARG_PTR_TO_UNINIT_MEM;
1876 }
1877
1878 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1879 {
1880         return type == ARG_CONST_SIZE ||
1881                type == ARG_CONST_SIZE_OR_ZERO;
1882 }
1883
1884 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1885                           enum bpf_arg_type arg_type,
1886                           struct bpf_call_arg_meta *meta)
1887 {
1888         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
1889         enum bpf_reg_type expected_type, type = reg->type;
1890         int err = 0;
1891
1892         if (arg_type == ARG_DONTCARE)
1893                 return 0;
1894
1895         err = check_reg_arg(env, regno, SRC_OP);
1896         if (err)
1897                 return err;
1898
1899         if (arg_type == ARG_ANYTHING) {
1900                 if (is_pointer_value(env, regno)) {
1901                         verbose(env, "R%d leaks addr into helper function\n",
1902                                 regno);
1903                         return -EACCES;
1904                 }
1905                 return 0;
1906         }
1907
1908         if (type_is_pkt_pointer(type) &&
1909             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1910                 verbose(env, "helper access to the packet is not allowed\n");
1911                 return -EACCES;
1912         }
1913
1914         if (arg_type == ARG_PTR_TO_MAP_KEY ||
1915             arg_type == ARG_PTR_TO_MAP_VALUE) {
1916                 expected_type = PTR_TO_STACK;
1917                 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1918                     type != expected_type)
1919                         goto err_type;
1920         } else if (arg_type == ARG_CONST_SIZE ||
1921                    arg_type == ARG_CONST_SIZE_OR_ZERO) {
1922                 expected_type = SCALAR_VALUE;
1923                 if (type != expected_type)
1924                         goto err_type;
1925         } else if (arg_type == ARG_CONST_MAP_PTR) {
1926                 expected_type = CONST_PTR_TO_MAP;
1927                 if (type != expected_type)
1928                         goto err_type;
1929         } else if (arg_type == ARG_PTR_TO_CTX) {
1930                 expected_type = PTR_TO_CTX;
1931                 if (type != expected_type)
1932                         goto err_type;
1933         } else if (arg_type_is_mem_ptr(arg_type)) {
1934                 expected_type = PTR_TO_STACK;
1935                 /* One exception here. In case function allows for NULL to be
1936                  * passed in as argument, it's a SCALAR_VALUE type. Final test
1937                  * happens during stack boundary checking.
1938                  */
1939                 if (register_is_null(reg) &&
1940                     arg_type == ARG_PTR_TO_MEM_OR_NULL)
1941                         /* final test in check_stack_boundary() */;
1942                 else if (!type_is_pkt_pointer(type) &&
1943                          type != PTR_TO_MAP_VALUE &&
1944                          type != expected_type)
1945                         goto err_type;
1946                 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1947         } else {
1948                 verbose(env, "unsupported arg_type %d\n", arg_type);
1949                 return -EFAULT;
1950         }
1951
1952         if (arg_type == ARG_CONST_MAP_PTR) {
1953                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1954                 meta->map_ptr = reg->map_ptr;
1955         } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1956                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1957                  * check that [key, key + map->key_size) are within
1958                  * stack limits and initialized
1959                  */
1960                 if (!meta->map_ptr) {
1961                         /* in function declaration map_ptr must come before
1962                          * map_key, so that it's verified and known before
1963                          * we have to check map_key here. Otherwise it means
1964                          * that kernel subsystem misconfigured verifier
1965                          */
1966                         verbose(env, "invalid map_ptr to access map->key\n");
1967                         return -EACCES;
1968                 }
1969                 err = check_helper_mem_access(env, regno,
1970                                               meta->map_ptr->key_size, false,
1971                                               NULL);
1972         } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1973                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1974                  * check [value, value + map->value_size) validity
1975                  */
1976                 if (!meta->map_ptr) {
1977                         /* kernel subsystem misconfigured verifier */
1978                         verbose(env, "invalid map_ptr to access map->value\n");
1979                         return -EACCES;
1980                 }
1981                 err = check_helper_mem_access(env, regno,
1982                                               meta->map_ptr->value_size, false,
1983                                               NULL);
1984         } else if (arg_type_is_mem_size(arg_type)) {
1985                 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1986
1987                 /* The register is SCALAR_VALUE; the access check
1988                  * happens using its boundaries.
1989                  */
1990                 if (!tnum_is_const(reg->var_off))
1991                         /* For unprivileged variable accesses, disable raw
1992                          * mode so that the program is required to
1993                          * initialize all the memory that the helper could
1994                          * just partially fill up.
1995                          */
1996                         meta = NULL;
1997
1998                 if (reg->smin_value < 0) {
1999                         verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2000                                 regno);
2001                         return -EACCES;
2002                 }
2003
2004                 if (reg->umin_value == 0) {
2005                         err = check_helper_mem_access(env, regno - 1, 0,
2006                                                       zero_size_allowed,
2007                                                       meta);
2008                         if (err)
2009                                 return err;
2010                 }
2011
2012                 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2013                         verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2014                                 regno);
2015                         return -EACCES;
2016                 }
2017                 err = check_helper_mem_access(env, regno - 1,
2018                                               reg->umax_value,
2019                                               zero_size_allowed, meta);
2020         }
2021
2022         return err;
2023 err_type:
2024         verbose(env, "R%d type=%s expected=%s\n", regno,
2025                 reg_type_str[type], reg_type_str[expected_type]);
2026         return -EACCES;
2027 }
2028
2029 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2030                                         struct bpf_map *map, int func_id)
2031 {
2032         if (!map)
2033                 return 0;
2034
2035         /* We need a two way check, first is from map perspective ... */
2036         switch (map->map_type) {
2037         case BPF_MAP_TYPE_PROG_ARRAY:
2038                 if (func_id != BPF_FUNC_tail_call)
2039                         goto error;
2040                 break;
2041         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2042                 if (func_id != BPF_FUNC_perf_event_read &&
2043                     func_id != BPF_FUNC_perf_event_output &&
2044                     func_id != BPF_FUNC_perf_event_read_value)
2045                         goto error;
2046                 break;
2047         case BPF_MAP_TYPE_STACK_TRACE:
2048                 if (func_id != BPF_FUNC_get_stackid)
2049                         goto error;
2050                 break;
2051         case BPF_MAP_TYPE_CGROUP_ARRAY:
2052                 if (func_id != BPF_FUNC_skb_under_cgroup &&
2053                     func_id != BPF_FUNC_current_task_under_cgroup)
2054                         goto error;
2055                 break;
2056         /* devmap returns a pointer to a live net_device ifindex that we cannot
2057          * allow to be modified from bpf side. So do not allow lookup elements
2058          * for now.
2059          */
2060         case BPF_MAP_TYPE_DEVMAP:
2061                 if (func_id != BPF_FUNC_redirect_map)
2062                         goto error;
2063                 break;
2064         /* Restrict bpf side of cpumap, open when use-cases appear */
2065         case BPF_MAP_TYPE_CPUMAP:
2066                 if (func_id != BPF_FUNC_redirect_map)
2067                         goto error;
2068                 break;
2069         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2070         case BPF_MAP_TYPE_HASH_OF_MAPS:
2071                 if (func_id != BPF_FUNC_map_lookup_elem)
2072                         goto error;
2073                 break;
2074         case BPF_MAP_TYPE_SOCKMAP:
2075                 if (func_id != BPF_FUNC_sk_redirect_map &&
2076                     func_id != BPF_FUNC_sock_map_update &&
2077                     func_id != BPF_FUNC_map_delete_elem &&
2078                     func_id != BPF_FUNC_msg_redirect_map)
2079                         goto error;
2080                 break;
2081         default:
2082                 break;
2083         }
2084
2085         /* ... and second from the function itself. */
2086         switch (func_id) {
2087         case BPF_FUNC_tail_call:
2088                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2089                         goto error;
2090                 if (env->subprog_cnt) {
2091                         verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2092                         return -EINVAL;
2093                 }
2094                 break;
2095         case BPF_FUNC_perf_event_read:
2096         case BPF_FUNC_perf_event_output:
2097         case BPF_FUNC_perf_event_read_value:
2098                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2099                         goto error;
2100                 break;
2101         case BPF_FUNC_get_stackid:
2102                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2103                         goto error;
2104                 break;
2105         case BPF_FUNC_current_task_under_cgroup:
2106         case BPF_FUNC_skb_under_cgroup:
2107                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2108                         goto error;
2109                 break;
2110         case BPF_FUNC_redirect_map:
2111                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2112                     map->map_type != BPF_MAP_TYPE_CPUMAP)
2113                         goto error;
2114                 break;
2115         case BPF_FUNC_sk_redirect_map:
2116         case BPF_FUNC_msg_redirect_map:
2117                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2118                         goto error;
2119                 break;
2120         case BPF_FUNC_sock_map_update:
2121                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2122                         goto error;
2123                 break;
2124         default:
2125                 break;
2126         }
2127
2128         return 0;
2129 error:
2130         verbose(env, "cannot pass map_type %d into func %s#%d\n",
2131                 map->map_type, func_id_name(func_id), func_id);
2132         return -EINVAL;
2133 }
2134
2135 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2136 {
2137         int count = 0;
2138
2139         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2140                 count++;
2141         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2142                 count++;
2143         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2144                 count++;
2145         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2146                 count++;
2147         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2148                 count++;
2149
2150         /* We only support one arg being in raw mode at the moment,
2151          * which is sufficient for the helper functions we have
2152          * right now.
2153          */
2154         return count <= 1;
2155 }
2156
2157 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2158                                     enum bpf_arg_type arg_next)
2159 {
2160         return (arg_type_is_mem_ptr(arg_curr) &&
2161                 !arg_type_is_mem_size(arg_next)) ||
2162                (!arg_type_is_mem_ptr(arg_curr) &&
2163                 arg_type_is_mem_size(arg_next));
2164 }
2165
2166 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2167 {
2168         /* bpf_xxx(..., buf, len) call will access 'len'
2169          * bytes from memory 'buf'. Both arg types need
2170          * to be paired, so make sure there's no buggy
2171          * helper function specification.
2172          */
2173         if (arg_type_is_mem_size(fn->arg1_type) ||
2174             arg_type_is_mem_ptr(fn->arg5_type)  ||
2175             check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2176             check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2177             check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2178             check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2179                 return false;
2180
2181         return true;
2182 }
2183
2184 static int check_func_proto(const struct bpf_func_proto *fn)
2185 {
2186         return check_raw_mode_ok(fn) &&
2187                check_arg_pair_ok(fn) ? 0 : -EINVAL;
2188 }
2189
2190 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2191  * are now invalid, so turn them into unknown SCALAR_VALUE.
2192  */
2193 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2194                                      struct bpf_func_state *state)
2195 {
2196         struct bpf_reg_state *regs = state->regs, *reg;
2197         int i;
2198
2199         for (i = 0; i < MAX_BPF_REG; i++)
2200                 if (reg_is_pkt_pointer_any(&regs[i]))
2201                         mark_reg_unknown(env, regs, i);
2202
2203         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2204                 if (state->stack[i].slot_type[0] != STACK_SPILL)
2205                         continue;
2206                 reg = &state->stack[i].spilled_ptr;
2207                 if (reg_is_pkt_pointer_any(reg))
2208                         __mark_reg_unknown(reg);
2209         }
2210 }
2211
2212 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2213 {
2214         struct bpf_verifier_state *vstate = env->cur_state;
2215         int i;
2216
2217         for (i = 0; i <= vstate->curframe; i++)
2218                 __clear_all_pkt_pointers(env, vstate->frame[i]);
2219 }
2220
2221 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2222                            int *insn_idx)
2223 {
2224         struct bpf_verifier_state *state = env->cur_state;
2225         struct bpf_func_state *caller, *callee;
2226         int i, subprog, target_insn;
2227
2228         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2229                 verbose(env, "the call stack of %d frames is too deep\n",
2230                         state->curframe + 2);
2231                 return -E2BIG;
2232         }
2233
2234         target_insn = *insn_idx + insn->imm;
2235         subprog = find_subprog(env, target_insn + 1);
2236         if (subprog < 0) {
2237                 verbose(env, "verifier bug. No program starts at insn %d\n",
2238                         target_insn + 1);
2239                 return -EFAULT;
2240         }
2241
2242         caller = state->frame[state->curframe];
2243         if (state->frame[state->curframe + 1]) {
2244                 verbose(env, "verifier bug. Frame %d already allocated\n",
2245                         state->curframe + 1);
2246                 return -EFAULT;
2247         }
2248
2249         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2250         if (!callee)
2251                 return -ENOMEM;
2252         state->frame[state->curframe + 1] = callee;
2253
2254         /* callee cannot access r0, r6 - r9 for reading and has to write
2255          * into its own stack before reading from it.
2256          * callee can read/write into caller's stack
2257          */
2258         init_func_state(env, callee,
2259                         /* remember the callsite, it will be used by bpf_exit */
2260                         *insn_idx /* callsite */,
2261                         state->curframe + 1 /* frameno within this callchain */,
2262                         subprog + 1 /* subprog number within this prog */);
2263
2264         /* copy r1 - r5 args that callee can access */
2265         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2266                 callee->regs[i] = caller->regs[i];
2267
2268         /* after the call regsiters r0 - r5 were scratched */
2269         for (i = 0; i < CALLER_SAVED_REGS; i++) {
2270                 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2271                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2272         }
2273
2274         /* only increment it after check_reg_arg() finished */
2275         state->curframe++;
2276
2277         /* and go analyze first insn of the callee */
2278         *insn_idx = target_insn;
2279
2280         if (env->log.level) {
2281                 verbose(env, "caller:\n");
2282                 print_verifier_state(env, caller);
2283                 verbose(env, "callee:\n");
2284                 print_verifier_state(env, callee);
2285         }
2286         return 0;
2287 }
2288
2289 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2290 {
2291         struct bpf_verifier_state *state = env->cur_state;
2292         struct bpf_func_state *caller, *callee;
2293         struct bpf_reg_state *r0;
2294
2295         callee = state->frame[state->curframe];
2296         r0 = &callee->regs[BPF_REG_0];
2297         if (r0->type == PTR_TO_STACK) {
2298                 /* technically it's ok to return caller's stack pointer
2299                  * (or caller's caller's pointer) back to the caller,
2300                  * since these pointers are valid. Only current stack
2301                  * pointer will be invalid as soon as function exits,
2302                  * but let's be conservative
2303                  */
2304                 verbose(env, "cannot return stack pointer to the caller\n");
2305                 return -EINVAL;
2306         }
2307
2308         state->curframe--;
2309         caller = state->frame[state->curframe];
2310         /* return to the caller whatever r0 had in the callee */
2311         caller->regs[BPF_REG_0] = *r0;
2312
2313         *insn_idx = callee->callsite + 1;
2314         if (env->log.level) {
2315                 verbose(env, "returning from callee:\n");
2316                 print_verifier_state(env, callee);
2317                 verbose(env, "to caller at %d:\n", *insn_idx);
2318                 print_verifier_state(env, caller);
2319         }
2320         /* clear everything in the callee */
2321         free_func_state(callee);
2322         state->frame[state->curframe + 1] = NULL;
2323         return 0;
2324 }
2325
2326 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2327 {
2328         const struct bpf_func_proto *fn = NULL;
2329         struct bpf_reg_state *regs;
2330         struct bpf_call_arg_meta meta;
2331         bool changes_data;
2332         int i, err;
2333
2334         /* find function prototype */
2335         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2336                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2337                         func_id);
2338                 return -EINVAL;
2339         }
2340
2341         if (env->ops->get_func_proto)
2342                 fn = env->ops->get_func_proto(func_id, env->prog);
2343         if (!fn) {
2344                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2345                         func_id);
2346                 return -EINVAL;
2347         }
2348
2349         /* eBPF programs must be GPL compatible to use GPL-ed functions */
2350         if (!env->prog->gpl_compatible && fn->gpl_only) {
2351                 verbose(env, "cannot call GPL only function from proprietary program\n");
2352                 return -EINVAL;
2353         }
2354
2355         /* With LD_ABS/IND some JITs save/restore skb from r1. */
2356         changes_data = bpf_helper_changes_pkt_data(fn->func);
2357         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2358                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2359                         func_id_name(func_id), func_id);
2360                 return -EINVAL;
2361         }
2362
2363         memset(&meta, 0, sizeof(meta));
2364         meta.pkt_access = fn->pkt_access;
2365
2366         err = check_func_proto(fn);
2367         if (err) {
2368                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2369                         func_id_name(func_id), func_id);
2370                 return err;
2371         }
2372
2373         /* check args */
2374         err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2375         if (err)
2376                 return err;
2377         err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2378         if (err)
2379                 return err;
2380         if (func_id == BPF_FUNC_tail_call) {
2381                 if (meta.map_ptr == NULL) {
2382                         verbose(env, "verifier bug\n");
2383                         return -EINVAL;
2384                 }
2385                 env->insn_aux_data[insn_idx].map_ptr = meta.map_ptr;
2386         }
2387         err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2388         if (err)
2389                 return err;
2390         err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2391         if (err)
2392                 return err;
2393         err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2394         if (err)
2395                 return err;
2396
2397         /* Mark slots with STACK_MISC in case of raw mode, stack offset
2398          * is inferred from register state.
2399          */
2400         for (i = 0; i < meta.access_size; i++) {
2401                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2402                                        BPF_WRITE, -1, false);
2403                 if (err)
2404                         return err;
2405         }
2406
2407         regs = cur_regs(env);
2408         /* reset caller saved regs */
2409         for (i = 0; i < CALLER_SAVED_REGS; i++) {
2410                 mark_reg_not_init(env, regs, caller_saved[i]);
2411                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2412         }
2413
2414         /* update return register (already marked as written above) */
2415         if (fn->ret_type == RET_INTEGER) {
2416                 /* sets type to SCALAR_VALUE */
2417                 mark_reg_unknown(env, regs, BPF_REG_0);
2418         } else if (fn->ret_type == RET_VOID) {
2419                 regs[BPF_REG_0].type = NOT_INIT;
2420         } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) {
2421                 struct bpf_insn_aux_data *insn_aux;
2422
2423                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2424                 /* There is no offset yet applied, variable or fixed */
2425                 mark_reg_known_zero(env, regs, BPF_REG_0);
2426                 regs[BPF_REG_0].off = 0;
2427                 /* remember map_ptr, so that check_map_access()
2428                  * can check 'value_size' boundary of memory access
2429                  * to map element returned from bpf_map_lookup_elem()
2430                  */
2431                 if (meta.map_ptr == NULL) {
2432                         verbose(env,
2433                                 "kernel subsystem misconfigured verifier\n");
2434                         return -EINVAL;
2435                 }
2436                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2437                 regs[BPF_REG_0].id = ++env->id_gen;
2438                 insn_aux = &env->insn_aux_data[insn_idx];
2439                 if (!insn_aux->map_ptr)
2440                         insn_aux->map_ptr = meta.map_ptr;
2441                 else if (insn_aux->map_ptr != meta.map_ptr)
2442                         insn_aux->map_ptr = BPF_MAP_PTR_POISON;
2443         } else {
2444                 verbose(env, "unknown return type %d of func %s#%d\n",
2445                         fn->ret_type, func_id_name(func_id), func_id);
2446                 return -EINVAL;
2447         }
2448
2449         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2450         if (err)
2451                 return err;
2452
2453         if (changes_data)
2454                 clear_all_pkt_pointers(env);
2455         return 0;
2456 }
2457
2458 static bool signed_add_overflows(s64 a, s64 b)
2459 {
2460         /* Do the add in u64, where overflow is well-defined */
2461         s64 res = (s64)((u64)a + (u64)b);
2462
2463         if (b < 0)
2464                 return res > a;
2465         return res < a;
2466 }
2467
2468 static bool signed_sub_overflows(s64 a, s64 b)
2469 {
2470         /* Do the sub in u64, where overflow is well-defined */
2471         s64 res = (s64)((u64)a - (u64)b);
2472
2473         if (b < 0)
2474                 return res < a;
2475         return res > a;
2476 }
2477
2478 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2479                                   const struct bpf_reg_state *reg,
2480                                   enum bpf_reg_type type)
2481 {
2482         bool known = tnum_is_const(reg->var_off);
2483         s64 val = reg->var_off.value;
2484         s64 smin = reg->smin_value;
2485
2486         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2487                 verbose(env, "math between %s pointer and %lld is not allowed\n",
2488                         reg_type_str[type], val);
2489                 return false;
2490         }
2491
2492         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2493                 verbose(env, "%s pointer offset %d is not allowed\n",
2494                         reg_type_str[type], reg->off);
2495                 return false;
2496         }
2497
2498         if (smin == S64_MIN) {
2499                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2500                         reg_type_str[type]);
2501                 return false;
2502         }
2503
2504         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2505                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2506                         smin, reg_type_str[type]);
2507                 return false;
2508         }
2509
2510         return true;
2511 }
2512
2513 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2514  * Caller should also handle BPF_MOV case separately.
2515  * If we return -EACCES, caller may want to try again treating pointer as a
2516  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
2517  */
2518 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2519                                    struct bpf_insn *insn,
2520                                    const struct bpf_reg_state *ptr_reg,
2521                                    const struct bpf_reg_state *off_reg)
2522 {
2523         struct bpf_verifier_state *vstate = env->cur_state;
2524         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2525         struct bpf_reg_state *regs = state->regs, *dst_reg;
2526         bool known = tnum_is_const(off_reg->var_off);
2527         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2528             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2529         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2530             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2531         u8 opcode = BPF_OP(insn->code);
2532         u32 dst = insn->dst_reg;
2533
2534         dst_reg = &regs[dst];
2535
2536         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2537             smin_val > smax_val || umin_val > umax_val) {
2538                 /* Taint dst register if offset had invalid bounds derived from
2539                  * e.g. dead branches.
2540                  */
2541                 __mark_reg_unknown(dst_reg);
2542                 return 0;
2543         }
2544
2545         if (BPF_CLASS(insn->code) != BPF_ALU64) {
2546                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2547                 verbose(env,
2548                         "R%d 32-bit pointer arithmetic prohibited\n",
2549                         dst);
2550                 return -EACCES;
2551         }
2552
2553         if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
2554                 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
2555                         dst);
2556                 return -EACCES;
2557         }
2558         if (ptr_reg->type == CONST_PTR_TO_MAP) {
2559                 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
2560                         dst);
2561                 return -EACCES;
2562         }
2563         if (ptr_reg->type == PTR_TO_PACKET_END) {
2564                 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
2565                         dst);
2566                 return -EACCES;
2567         }
2568
2569         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
2570          * The id may be overwritten later if we create a new variable offset.
2571          */
2572         dst_reg->type = ptr_reg->type;
2573         dst_reg->id = ptr_reg->id;
2574
2575         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
2576             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
2577                 return -EINVAL;
2578
2579         switch (opcode) {
2580         case BPF_ADD:
2581                 /* We can take a fixed offset as long as it doesn't overflow
2582                  * the s32 'off' field
2583                  */
2584                 if (known && (ptr_reg->off + smin_val ==
2585                               (s64)(s32)(ptr_reg->off + smin_val))) {
2586                         /* pointer += K.  Accumulate it into fixed offset */
2587                         dst_reg->smin_value = smin_ptr;
2588                         dst_reg->smax_value = smax_ptr;
2589                         dst_reg->umin_value = umin_ptr;
2590                         dst_reg->umax_value = umax_ptr;
2591                         dst_reg->var_off = ptr_reg->var_off;
2592                         dst_reg->off = ptr_reg->off + smin_val;
2593                         dst_reg->range = ptr_reg->range;
2594                         break;
2595                 }
2596                 /* A new variable offset is created.  Note that off_reg->off
2597                  * == 0, since it's a scalar.
2598                  * dst_reg gets the pointer type and since some positive
2599                  * integer value was added to the pointer, give it a new 'id'
2600                  * if it's a PTR_TO_PACKET.
2601                  * this creates a new 'base' pointer, off_reg (variable) gets
2602                  * added into the variable offset, and we copy the fixed offset
2603                  * from ptr_reg.
2604                  */
2605                 if (signed_add_overflows(smin_ptr, smin_val) ||
2606                     signed_add_overflows(smax_ptr, smax_val)) {
2607                         dst_reg->smin_value = S64_MIN;
2608                         dst_reg->smax_value = S64_MAX;
2609                 } else {
2610                         dst_reg->smin_value = smin_ptr + smin_val;
2611                         dst_reg->smax_value = smax_ptr + smax_val;
2612                 }
2613                 if (umin_ptr + umin_val < umin_ptr ||
2614                     umax_ptr + umax_val < umax_ptr) {
2615                         dst_reg->umin_value = 0;
2616                         dst_reg->umax_value = U64_MAX;
2617                 } else {
2618                         dst_reg->umin_value = umin_ptr + umin_val;
2619                         dst_reg->umax_value = umax_ptr + umax_val;
2620                 }
2621                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
2622                 dst_reg->off = ptr_reg->off;
2623                 if (reg_is_pkt_pointer(ptr_reg)) {
2624                         dst_reg->id = ++env->id_gen;
2625                         /* something was added to pkt_ptr, set range to zero */
2626                         dst_reg->range = 0;
2627                 }
2628                 break;
2629         case BPF_SUB:
2630                 if (dst_reg == off_reg) {
2631                         /* scalar -= pointer.  Creates an unknown scalar */
2632                         verbose(env, "R%d tried to subtract pointer from scalar\n",
2633                                 dst);
2634                         return -EACCES;
2635                 }
2636                 /* We don't allow subtraction from FP, because (according to
2637                  * test_verifier.c test "invalid fp arithmetic", JITs might not
2638                  * be able to deal with it.
2639                  */
2640                 if (ptr_reg->type == PTR_TO_STACK) {
2641                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
2642                                 dst);
2643                         return -EACCES;
2644                 }
2645                 if (known && (ptr_reg->off - smin_val ==
2646                               (s64)(s32)(ptr_reg->off - smin_val))) {
2647                         /* pointer -= K.  Subtract it from fixed offset */
2648                         dst_reg->smin_value = smin_ptr;
2649                         dst_reg->smax_value = smax_ptr;
2650                         dst_reg->umin_value = umin_ptr;
2651                         dst_reg->umax_value = umax_ptr;
2652                         dst_reg->var_off = ptr_reg->var_off;
2653                         dst_reg->id = ptr_reg->id;
2654                         dst_reg->off = ptr_reg->off - smin_val;
2655                         dst_reg->range = ptr_reg->range;
2656                         break;
2657                 }
2658                 /* A new variable offset is created.  If the subtrahend is known
2659                  * nonnegative, then any reg->range we had before is still good.
2660                  */
2661                 if (signed_sub_overflows(smin_ptr, smax_val) ||
2662                     signed_sub_overflows(smax_ptr, smin_val)) {
2663                         /* Overflow possible, we know nothing */
2664                         dst_reg->smin_value = S64_MIN;
2665                         dst_reg->smax_value = S64_MAX;
2666                 } else {
2667                         dst_reg->smin_value = smin_ptr - smax_val;
2668                         dst_reg->smax_value = smax_ptr - smin_val;
2669                 }
2670                 if (umin_ptr < umax_val) {
2671                         /* Overflow possible, we know nothing */
2672                         dst_reg->umin_value = 0;
2673                         dst_reg->umax_value = U64_MAX;
2674                 } else {
2675                         /* Cannot overflow (as long as bounds are consistent) */
2676                         dst_reg->umin_value = umin_ptr - umax_val;
2677                         dst_reg->umax_value = umax_ptr - umin_val;
2678                 }
2679                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
2680                 dst_reg->off = ptr_reg->off;
2681                 if (reg_is_pkt_pointer(ptr_reg)) {
2682                         dst_reg->id = ++env->id_gen;
2683                         /* something was added to pkt_ptr, set range to zero */
2684                         if (smin_val < 0)
2685                                 dst_reg->range = 0;
2686                 }
2687                 break;
2688         case BPF_AND:
2689         case BPF_OR:
2690         case BPF_XOR:
2691                 /* bitwise ops on pointers are troublesome, prohibit. */
2692                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
2693                         dst, bpf_alu_string[opcode >> 4]);
2694                 return -EACCES;
2695         default:
2696                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
2697                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
2698                         dst, bpf_alu_string[opcode >> 4]);
2699                 return -EACCES;
2700         }
2701
2702         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
2703                 return -EINVAL;
2704
2705         __update_reg_bounds(dst_reg);
2706         __reg_deduce_bounds(dst_reg);
2707         __reg_bound_offset(dst_reg);
2708         return 0;
2709 }
2710
2711 /* WARNING: This function does calculations on 64-bit values, but the actual
2712  * execution may occur on 32-bit values. Therefore, things like bitshifts
2713  * need extra checks in the 32-bit case.
2714  */
2715 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
2716                                       struct bpf_insn *insn,
2717                                       struct bpf_reg_state *dst_reg,
2718                                       struct bpf_reg_state src_reg)
2719 {
2720         struct bpf_reg_state *regs = cur_regs(env);
2721         u8 opcode = BPF_OP(insn->code);
2722         bool src_known, dst_known;
2723         s64 smin_val, smax_val;
2724         u64 umin_val, umax_val;
2725         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
2726
2727         smin_val = src_reg.smin_value;
2728         smax_val = src_reg.smax_value;
2729         umin_val = src_reg.umin_value;
2730         umax_val = src_reg.umax_value;
2731         src_known = tnum_is_const(src_reg.var_off);
2732         dst_known = tnum_is_const(dst_reg->var_off);
2733
2734         if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
2735             smin_val > smax_val || umin_val > umax_val) {
2736                 /* Taint dst register if offset had invalid bounds derived from
2737                  * e.g. dead branches.
2738                  */
2739                 __mark_reg_unknown(dst_reg);
2740                 return 0;
2741         }
2742
2743         if (!src_known &&
2744             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
2745                 __mark_reg_unknown(dst_reg);
2746                 return 0;
2747         }
2748
2749         switch (opcode) {
2750         case BPF_ADD:
2751                 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
2752                     signed_add_overflows(dst_reg->smax_value, smax_val)) {
2753                         dst_reg->smin_value = S64_MIN;
2754                         dst_reg->smax_value = S64_MAX;
2755                 } else {
2756                         dst_reg->smin_value += smin_val;
2757                         dst_reg->smax_value += smax_val;
2758                 }
2759                 if (dst_reg->umin_value + umin_val < umin_val ||
2760                     dst_reg->umax_value + umax_val < umax_val) {
2761                         dst_reg->umin_value = 0;
2762                         dst_reg->umax_value = U64_MAX;
2763                 } else {
2764                         dst_reg->umin_value += umin_val;
2765                         dst_reg->umax_value += umax_val;
2766                 }
2767                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
2768                 break;
2769         case BPF_SUB:
2770                 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
2771                     signed_sub_overflows(dst_reg->smax_value, smin_val)) {
2772                         /* Overflow possible, we know nothing */
2773                         dst_reg->smin_value = S64_MIN;
2774                         dst_reg->smax_value = S64_MAX;
2775                 } else {
2776                         dst_reg->smin_value -= smax_val;
2777                         dst_reg->smax_value -= smin_val;
2778                 }
2779                 if (dst_reg->umin_value < umax_val) {
2780                         /* Overflow possible, we know nothing */
2781                         dst_reg->umin_value = 0;
2782                         dst_reg->umax_value = U64_MAX;
2783                 } else {
2784                         /* Cannot overflow (as long as bounds are consistent) */
2785                         dst_reg->umin_value -= umax_val;
2786                         dst_reg->umax_value -= umin_val;
2787                 }
2788                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
2789                 break;
2790         case BPF_MUL:
2791                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
2792                 if (smin_val < 0 || dst_reg->smin_value < 0) {
2793                         /* Ain't nobody got time to multiply that sign */
2794                         __mark_reg_unbounded(dst_reg);
2795                         __update_reg_bounds(dst_reg);
2796                         break;
2797                 }
2798                 /* Both values are positive, so we can work with unsigned and
2799                  * copy the result to signed (unless it exceeds S64_MAX).
2800                  */
2801                 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
2802                         /* Potential overflow, we know nothing */
2803                         __mark_reg_unbounded(dst_reg);
2804                         /* (except what we can learn from the var_off) */
2805                         __update_reg_bounds(dst_reg);
2806                         break;
2807                 }
2808                 dst_reg->umin_value *= umin_val;
2809                 dst_reg->umax_value *= umax_val;
2810                 if (dst_reg->umax_value > S64_MAX) {
2811                         /* Overflow possible, we know nothing */
2812                         dst_reg->smin_value = S64_MIN;
2813                         dst_reg->smax_value = S64_MAX;
2814                 } else {
2815                         dst_reg->smin_value = dst_reg->umin_value;
2816                         dst_reg->smax_value = dst_reg->umax_value;
2817                 }
2818                 break;
2819         case BPF_AND:
2820                 if (src_known && dst_known) {
2821                         __mark_reg_known(dst_reg, dst_reg->var_off.value &
2822                                                   src_reg.var_off.value);
2823                         break;
2824                 }
2825                 /* We get our minimum from the var_off, since that's inherently
2826                  * bitwise.  Our maximum is the minimum of the operands' maxima.
2827                  */
2828                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
2829                 dst_reg->umin_value = dst_reg->var_off.value;
2830                 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
2831                 if (dst_reg->smin_value < 0 || smin_val < 0) {
2832                         /* Lose signed bounds when ANDing negative numbers,
2833                          * ain't nobody got time for that.
2834                          */
2835                         dst_reg->smin_value = S64_MIN;
2836                         dst_reg->smax_value = S64_MAX;
2837                 } else {
2838                         /* ANDing two positives gives a positive, so safe to
2839                          * cast result into s64.
2840                          */
2841                         dst_reg->smin_value = dst_reg->umin_value;
2842                         dst_reg->smax_value = dst_reg->umax_value;
2843                 }
2844                 /* We may learn something more from the var_off */
2845                 __update_reg_bounds(dst_reg);
2846                 break;
2847         case BPF_OR:
2848                 if (src_known && dst_known) {
2849                         __mark_reg_known(dst_reg, dst_reg->var_off.value |
2850                                                   src_reg.var_off.value);
2851                         break;
2852                 }
2853                 /* We get our maximum from the var_off, and our minimum is the
2854                  * maximum of the operands' minima
2855                  */
2856                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
2857                 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
2858                 dst_reg->umax_value = dst_reg->var_off.value |
2859                                       dst_reg->var_off.mask;
2860                 if (dst_reg->smin_value < 0 || smin_val < 0) {
2861                         /* Lose signed bounds when ORing negative numbers,
2862                          * ain't nobody got time for that.
2863                          */
2864                         dst_reg->smin_value = S64_MIN;
2865                         dst_reg->smax_value = S64_MAX;
2866                 } else {
2867                         /* ORing two positives gives a positive, so safe to
2868                          * cast result into s64.
2869                          */
2870                         dst_reg->smin_value = dst_reg->umin_value;
2871                         dst_reg->smax_value = dst_reg->umax_value;
2872                 }
2873                 /* We may learn something more from the var_off */
2874                 __update_reg_bounds(dst_reg);
2875                 break;
2876         case BPF_LSH:
2877                 if (umax_val >= insn_bitness) {
2878                         /* Shifts greater than 31 or 63 are undefined.
2879                          * This includes shifts by a negative number.
2880                          */
2881                         mark_reg_unknown(env, regs, insn->dst_reg);
2882                         break;
2883                 }
2884                 /* We lose all sign bit information (except what we can pick
2885                  * up from var_off)
2886                  */
2887                 dst_reg->smin_value = S64_MIN;
2888                 dst_reg->smax_value = S64_MAX;
2889                 /* If we might shift our top bit out, then we know nothing */
2890                 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
2891                         dst_reg->umin_value = 0;
2892                         dst_reg->umax_value = U64_MAX;
2893                 } else {
2894                         dst_reg->umin_value <<= umin_val;
2895                         dst_reg->umax_value <<= umax_val;
2896                 }
2897                 if (src_known)
2898                         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
2899                 else
2900                         dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val);
2901                 /* We may learn something more from the var_off */
2902                 __update_reg_bounds(dst_reg);
2903                 break;
2904         case BPF_RSH:
2905                 if (umax_val >= insn_bitness) {
2906                         /* Shifts greater than 31 or 63 are undefined.
2907                          * This includes shifts by a negative number.
2908                          */
2909                         mark_reg_unknown(env, regs, insn->dst_reg);
2910                         break;
2911                 }
2912                 /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
2913                  * be negative, then either:
2914                  * 1) src_reg might be zero, so the sign bit of the result is
2915                  *    unknown, so we lose our signed bounds
2916                  * 2) it's known negative, thus the unsigned bounds capture the
2917                  *    signed bounds
2918                  * 3) the signed bounds cross zero, so they tell us nothing
2919                  *    about the result
2920                  * If the value in dst_reg is known nonnegative, then again the
2921                  * unsigned bounts capture the signed bounds.
2922                  * Thus, in all cases it suffices to blow away our signed bounds
2923                  * and rely on inferring new ones from the unsigned bounds and
2924                  * var_off of the result.
2925                  */
2926                 dst_reg->smin_value = S64_MIN;
2927                 dst_reg->smax_value = S64_MAX;
2928                 if (src_known)
2929                         dst_reg->var_off = tnum_rshift(dst_reg->var_off,
2930                                                        umin_val);
2931                 else
2932                         dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val);
2933                 dst_reg->umin_value >>= umax_val;
2934                 dst_reg->umax_value >>= umin_val;
2935                 /* We may learn something more from the var_off */
2936                 __update_reg_bounds(dst_reg);
2937                 break;
2938         default:
2939                 mark_reg_unknown(env, regs, insn->dst_reg);
2940                 break;
2941         }
2942
2943         if (BPF_CLASS(insn->code) != BPF_ALU64) {
2944                 /* 32-bit ALU ops are (32,32)->32 */
2945                 coerce_reg_to_size(dst_reg, 4);
2946                 coerce_reg_to_size(&src_reg, 4);
2947         }
2948
2949         __reg_deduce_bounds(dst_reg);
2950         __reg_bound_offset(dst_reg);
2951         return 0;
2952 }
2953
2954 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2955  * and var_off.
2956  */
2957 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2958                                    struct bpf_insn *insn)
2959 {
2960         struct bpf_verifier_state *vstate = env->cur_state;
2961         struct bpf_func_state *state = vstate->frame[vstate->curframe];
2962         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
2963         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2964         u8 opcode = BPF_OP(insn->code);
2965
2966         dst_reg = &regs[insn->dst_reg];
2967         src_reg = NULL;
2968         if (dst_reg->type != SCALAR_VALUE)
2969                 ptr_reg = dst_reg;
2970         if (BPF_SRC(insn->code) == BPF_X) {
2971                 src_reg = &regs[insn->src_reg];
2972                 if (src_reg->type != SCALAR_VALUE) {
2973                         if (dst_reg->type != SCALAR_VALUE) {
2974                                 /* Combining two pointers by any ALU op yields
2975                                  * an arbitrary scalar. Disallow all math except
2976                                  * pointer subtraction
2977                                  */
2978                                 if (opcode == BPF_SUB){
2979                                         mark_reg_unknown(env, regs, insn->dst_reg);
2980                                         return 0;
2981                                 }
2982                                 verbose(env, "R%d pointer %s pointer prohibited\n",
2983                                         insn->dst_reg,
2984                                         bpf_alu_string[opcode >> 4]);
2985                                 return -EACCES;
2986                         } else {
2987                                 /* scalar += pointer
2988                                  * This is legal, but we have to reverse our
2989                                  * src/dest handling in computing the range
2990                                  */
2991                                 return adjust_ptr_min_max_vals(env, insn,
2992                                                                src_reg, dst_reg);
2993                         }
2994                 } else if (ptr_reg) {
2995                         /* pointer += scalar */
2996                         return adjust_ptr_min_max_vals(env, insn,
2997                                                        dst_reg, src_reg);
2998                 }
2999         } else {
3000                 /* Pretend the src is a reg with a known value, since we only
3001                  * need to be able to read from this state.
3002                  */
3003                 off_reg.type = SCALAR_VALUE;
3004                 __mark_reg_known(&off_reg, insn->imm);
3005                 src_reg = &off_reg;
3006                 if (ptr_reg) /* pointer += K */
3007                         return adjust_ptr_min_max_vals(env, insn,
3008                                                        ptr_reg, src_reg);
3009         }
3010
3011         /* Got here implies adding two SCALAR_VALUEs */
3012         if (WARN_ON_ONCE(ptr_reg)) {
3013                 print_verifier_state(env, state);
3014                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3015                 return -EINVAL;
3016         }
3017         if (WARN_ON(!src_reg)) {
3018                 print_verifier_state(env, state);
3019                 verbose(env, "verifier internal error: no src_reg\n");
3020                 return -EINVAL;
3021         }
3022         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3023 }
3024
3025 /* check validity of 32-bit and 64-bit arithmetic operations */
3026 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3027 {
3028         struct bpf_reg_state *regs = cur_regs(env);
3029         u8 opcode = BPF_OP(insn->code);
3030         int err;
3031
3032         if (opcode == BPF_END || opcode == BPF_NEG) {
3033                 if (opcode == BPF_NEG) {
3034                         if (BPF_SRC(insn->code) != 0 ||
3035                             insn->src_reg != BPF_REG_0 ||
3036                             insn->off != 0 || insn->imm != 0) {
3037                                 verbose(env, "BPF_NEG uses reserved fields\n");
3038                                 return -EINVAL;
3039                         }
3040                 } else {
3041                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3042                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3043                             BPF_CLASS(insn->code) == BPF_ALU64) {
3044                                 verbose(env, "BPF_END uses reserved fields\n");
3045                                 return -EINVAL;
3046                         }
3047                 }
3048
3049                 /* check src operand */
3050                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3051                 if (err)
3052                         return err;
3053
3054                 if (is_pointer_value(env, insn->dst_reg)) {
3055                         verbose(env, "R%d pointer arithmetic prohibited\n",
3056                                 insn->dst_reg);
3057                         return -EACCES;
3058                 }
3059
3060                 /* check dest operand */
3061                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3062                 if (err)
3063                         return err;
3064
3065         } else if (opcode == BPF_MOV) {
3066
3067                 if (BPF_SRC(insn->code) == BPF_X) {
3068                         if (insn->imm != 0 || insn->off != 0) {
3069                                 verbose(env, "BPF_MOV uses reserved fields\n");
3070                                 return -EINVAL;
3071                         }
3072
3073                         /* check src operand */
3074                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
3075                         if (err)
3076                                 return err;
3077                 } else {
3078                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3079                                 verbose(env, "BPF_MOV uses reserved fields\n");
3080                                 return -EINVAL;
3081                         }
3082                 }
3083
3084                 /* check dest operand */
3085                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3086                 if (err)
3087                         return err;
3088
3089                 if (BPF_SRC(insn->code) == BPF_X) {
3090                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
3091                                 /* case: R1 = R2
3092                                  * copy register state to dest reg
3093                                  */
3094                                 regs[insn->dst_reg] = regs[insn->src_reg];
3095                                 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
3096                         } else {
3097                                 /* R1 = (u32) R2 */
3098                                 if (is_pointer_value(env, insn->src_reg)) {
3099                                         verbose(env,
3100                                                 "R%d partial copy of pointer\n",
3101                                                 insn->src_reg);
3102                                         return -EACCES;
3103                                 }
3104                                 mark_reg_unknown(env, regs, insn->dst_reg);
3105                                 coerce_reg_to_size(&regs[insn->dst_reg], 4);
3106                         }
3107                 } else {
3108                         /* case: R = imm
3109                          * remember the value we stored into this reg
3110                          */
3111                         regs[insn->dst_reg].type = SCALAR_VALUE;
3112                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
3113                                 __mark_reg_known(regs + insn->dst_reg,
3114                                                  insn->imm);
3115                         } else {
3116                                 __mark_reg_known(regs + insn->dst_reg,
3117                                                  (u32)insn->imm);
3118                         }
3119                 }
3120
3121         } else if (opcode > BPF_END) {
3122                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3123                 return -EINVAL;
3124
3125         } else {        /* all other ALU ops: and, sub, xor, add, ... */
3126
3127                 if (BPF_SRC(insn->code) == BPF_X) {
3128                         if (insn->imm != 0 || insn->off != 0) {
3129                                 verbose(env, "BPF_ALU uses reserved fields\n");
3130                                 return -EINVAL;
3131                         }
3132                         /* check src1 operand */
3133                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
3134                         if (err)
3135                                 return err;
3136                 } else {
3137                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3138                                 verbose(env, "BPF_ALU uses reserved fields\n");
3139                                 return -EINVAL;
3140                         }
3141                 }
3142
3143                 /* check src2 operand */
3144                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3145                 if (err)
3146                         return err;
3147
3148                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3149                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3150                         verbose(env, "div by zero\n");
3151                         return -EINVAL;
3152                 }
3153
3154                 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3155                         verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3156                         return -EINVAL;
3157                 }
3158
3159                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3160                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3161                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3162
3163                         if (insn->imm < 0 || insn->imm >= size) {
3164                                 verbose(env, "invalid shift %d\n", insn->imm);
3165                                 return -EINVAL;
3166                         }
3167                 }
3168
3169                 /* check dest operand */
3170                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3171                 if (err)
3172                         return err;
3173
3174                 return adjust_reg_min_max_vals(env, insn);
3175         }
3176
3177         return 0;
3178 }
3179
3180 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3181                                    struct bpf_reg_state *dst_reg,
3182                                    enum bpf_reg_type type,
3183                                    bool range_right_open)
3184 {
3185         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3186         struct bpf_reg_state *regs = state->regs, *reg;
3187         u16 new_range;
3188         int i, j;
3189
3190         if (dst_reg->off < 0 ||
3191             (dst_reg->off == 0 && range_right_open))
3192                 /* This doesn't give us any range */
3193                 return;
3194
3195         if (dst_reg->umax_value > MAX_PACKET_OFF ||
3196             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3197                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
3198                  * than pkt_end, but that's because it's also less than pkt.
3199                  */
3200                 return;
3201
3202         new_range = dst_reg->off;
3203         if (range_right_open)
3204                 new_range--;
3205
3206         /* Examples for register markings:
3207          *
3208          * pkt_data in dst register:
3209          *
3210          *   r2 = r3;
3211          *   r2 += 8;
3212          *   if (r2 > pkt_end) goto <handle exception>
3213          *   <access okay>
3214          *
3215          *   r2 = r3;
3216          *   r2 += 8;
3217          *   if (r2 < pkt_end) goto <access okay>
3218          *   <handle exception>
3219          *
3220          *   Where:
3221          *     r2 == dst_reg, pkt_end == src_reg
3222          *     r2=pkt(id=n,off=8,r=0)
3223          *     r3=pkt(id=n,off=0,r=0)
3224          *
3225          * pkt_data in src register:
3226          *
3227          *   r2 = r3;
3228          *   r2 += 8;
3229          *   if (pkt_end >= r2) goto <access okay>
3230          *   <handle exception>
3231          *
3232          *   r2 = r3;
3233          *   r2 += 8;
3234          *   if (pkt_end <= r2) goto <handle exception>
3235          *   <access okay>
3236          *
3237          *   Where:
3238          *     pkt_end == dst_reg, r2 == src_reg
3239          *     r2=pkt(id=n,off=8,r=0)
3240          *     r3=pkt(id=n,off=0,r=0)
3241          *
3242          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3243          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3244          * and [r3, r3 + 8-1) respectively is safe to access depending on
3245          * the check.
3246          */
3247
3248         /* If our ids match, then we must have the same max_value.  And we
3249          * don't care about the other reg's fixed offset, since if it's too big
3250          * the range won't allow anything.
3251          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3252          */
3253         for (i = 0; i < MAX_BPF_REG; i++)
3254                 if (regs[i].type == type && regs[i].id == dst_reg->id)
3255                         /* keep the maximum range already checked */
3256                         regs[i].range = max(regs[i].range, new_range);
3257
3258         for (j = 0; j <= vstate->curframe; j++) {
3259                 state = vstate->frame[j];
3260                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3261                         if (state->stack[i].slot_type[0] != STACK_SPILL)
3262                                 continue;
3263                         reg = &state->stack[i].spilled_ptr;
3264                         if (reg->type == type && reg->id == dst_reg->id)
3265                                 reg->range = max(reg->range, new_range);
3266                 }
3267         }
3268 }
3269
3270 /* Adjusts the register min/max values in the case that the dst_reg is the
3271  * variable register that we are working on, and src_reg is a constant or we're
3272  * simply doing a BPF_K check.
3273  * In JEQ/JNE cases we also adjust the var_off values.
3274  */
3275 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3276                             struct bpf_reg_state *false_reg, u64 val,
3277                             u8 opcode)
3278 {
3279         /* If the dst_reg is a pointer, we can't learn anything about its
3280          * variable offset from the compare (unless src_reg were a pointer into
3281          * the same object, but we don't bother with that.
3282          * Since false_reg and true_reg have the same type by construction, we
3283          * only need to check one of them for pointerness.
3284          */
3285         if (__is_pointer_value(false, false_reg))
3286                 return;
3287
3288         switch (opcode) {
3289         case BPF_JEQ:
3290                 /* If this is false then we know nothing Jon Snow, but if it is
3291                  * true then we know for sure.
3292                  */
3293                 __mark_reg_known(true_reg, val);
3294                 break;
3295         case BPF_JNE:
3296                 /* If this is true we know nothing Jon Snow, but if it is false
3297                  * we know the value for sure;
3298                  */
3299                 __mark_reg_known(false_reg, val);
3300                 break;
3301         case BPF_JGT:
3302                 false_reg->umax_value = min(false_reg->umax_value, val);
3303                 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3304                 break;
3305         case BPF_JSGT:
3306                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3307                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3308                 break;
3309         case BPF_JLT:
3310                 false_reg->umin_value = max(false_reg->umin_value, val);
3311                 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3312                 break;
3313         case BPF_JSLT:
3314                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3315                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3316                 break;
3317         case BPF_JGE:
3318                 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3319                 true_reg->umin_value = max(true_reg->umin_value, val);
3320                 break;
3321         case BPF_JSGE:
3322                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3323                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3324                 break;
3325         case BPF_JLE:
3326                 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3327                 true_reg->umax_value = min(true_reg->umax_value, val);
3328                 break;
3329         case BPF_JSLE:
3330                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3331                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3332                 break;
3333         default:
3334                 break;
3335         }
3336
3337         __reg_deduce_bounds(false_reg);
3338         __reg_deduce_bounds(true_reg);
3339         /* We might have learned some bits from the bounds. */
3340         __reg_bound_offset(false_reg);
3341         __reg_bound_offset(true_reg);
3342         /* Intersecting with the old var_off might have improved our bounds
3343          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3344          * then new var_off is (0; 0x7f...fc) which improves our umax.
3345          */
3346         __update_reg_bounds(false_reg);
3347         __update_reg_bounds(true_reg);
3348 }
3349
3350 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3351  * the variable reg.
3352  */
3353 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3354                                 struct bpf_reg_state *false_reg, u64 val,
3355                                 u8 opcode)
3356 {
3357         if (__is_pointer_value(false, false_reg))
3358                 return;
3359
3360         switch (opcode) {
3361         case BPF_JEQ:
3362                 /* If this is false then we know nothing Jon Snow, but if it is
3363                  * true then we know for sure.
3364                  */
3365                 __mark_reg_known(true_reg, val);
3366                 break;
3367         case BPF_JNE:
3368                 /* If this is true we know nothing Jon Snow, but if it is false
3369                  * we know the value for sure;
3370                  */
3371                 __mark_reg_known(false_reg, val);
3372                 break;
3373         case BPF_JGT:
3374                 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3375                 false_reg->umin_value = max(false_reg->umin_value, val);
3376                 break;
3377         case BPF_JSGT:
3378                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3379                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3380                 break;
3381         case BPF_JLT:
3382                 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3383                 false_reg->umax_value = min(false_reg->umax_value, val);
3384                 break;
3385         case BPF_JSLT:
3386                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3387                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3388                 break;
3389         case BPF_JGE:
3390                 true_reg->umax_value = min(true_reg->umax_value, val);
3391                 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3392                 break;
3393         case BPF_JSGE:
3394                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3395                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3396                 break;
3397         case BPF_JLE:
3398                 true_reg->umin_value = max(true_reg->umin_value, val);
3399                 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3400                 break;
3401         case BPF_JSLE:
3402                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3403                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3404                 break;
3405         default:
3406                 break;
3407         }
3408
3409         __reg_deduce_bounds(false_reg);
3410         __reg_deduce_bounds(true_reg);
3411         /* We might have learned some bits from the bounds. */
3412         __reg_bound_offset(false_reg);
3413         __reg_bound_offset(true_reg);
3414         /* Intersecting with the old var_off might have improved our bounds
3415          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3416          * then new var_off is (0; 0x7f...fc) which improves our umax.
3417          */
3418         __update_reg_bounds(false_reg);
3419         __update_reg_bounds(true_reg);
3420 }
3421
3422 /* Regs are known to be equal, so intersect their min/max/var_off */
3423 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3424                                   struct bpf_reg_state *dst_reg)
3425 {
3426         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3427                                                         dst_reg->umin_value);
3428         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3429                                                         dst_reg->umax_value);
3430         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3431                                                         dst_reg->smin_value);
3432         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3433                                                         dst_reg->smax_value);
3434         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3435                                                              dst_reg->var_off);
3436         /* We might have learned new bounds from the var_off. */
3437         __update_reg_bounds(src_reg);
3438         __update_reg_bounds(dst_reg);
3439         /* We might have learned something about the sign bit. */
3440         __reg_deduce_bounds(src_reg);
3441         __reg_deduce_bounds(dst_reg);
3442         /* We might have learned some bits from the bounds. */
3443         __reg_bound_offset(src_reg);
3444         __reg_bound_offset(dst_reg);
3445         /* Intersecting with the old var_off might have improved our bounds
3446          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3447          * then new var_off is (0; 0x7f...fc) which improves our umax.
3448          */
3449         __update_reg_bounds(src_reg);
3450         __update_reg_bounds(dst_reg);
3451 }
3452
3453 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3454                                 struct bpf_reg_state *true_dst,
3455                                 struct bpf_reg_state *false_src,
3456                                 struct bpf_reg_state *false_dst,
3457                                 u8 opcode)
3458 {
3459         switch (opcode) {
3460         case BPF_JEQ:
3461                 __reg_combine_min_max(true_src, true_dst);
3462                 break;
3463         case BPF_JNE:
3464                 __reg_combine_min_max(false_src, false_dst);
3465                 break;
3466         }
3467 }
3468
3469 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3470                          bool is_null)
3471 {
3472         struct bpf_reg_state *reg = &regs[regno];
3473
3474         if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3475                 /* Old offset (both fixed and variable parts) should
3476                  * have been known-zero, because we don't allow pointer
3477                  * arithmetic on pointers that might be NULL.
3478                  */
3479                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3480                                  !tnum_equals_const(reg->var_off, 0) ||
3481                                  reg->off)) {
3482                         __mark_reg_known_zero(reg);
3483                         reg->off = 0;
3484                 }
3485                 if (is_null) {
3486                         reg->type = SCALAR_VALUE;
3487                 } else if (reg->map_ptr->inner_map_meta) {
3488                         reg->type = CONST_PTR_TO_MAP;
3489                         reg->map_ptr = reg->map_ptr->inner_map_meta;
3490                 } else {
3491                         reg->type = PTR_TO_MAP_VALUE;
3492                 }
3493                 /* We don't need id from this point onwards anymore, thus we
3494                  * should better reset it, so that state pruning has chances
3495                  * to take effect.
3496                  */
3497                 reg->id = 0;
3498         }
3499 }
3500
3501 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3502  * be folded together at some point.
3503  */
3504 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
3505                           bool is_null)
3506 {
3507         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3508         struct bpf_reg_state *regs = state->regs;
3509         u32 id = regs[regno].id;
3510         int i, j;
3511
3512         for (i = 0; i < MAX_BPF_REG; i++)
3513                 mark_map_reg(regs, i, id, is_null);
3514
3515         for (j = 0; j <= vstate->curframe; j++) {
3516                 state = vstate->frame[j];
3517                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3518                         if (state->stack[i].slot_type[0] != STACK_SPILL)
3519                                 continue;
3520                         mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3521                 }
3522         }
3523 }
3524
3525 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
3526                                    struct bpf_reg_state *dst_reg,
3527                                    struct bpf_reg_state *src_reg,
3528                                    struct bpf_verifier_state *this_branch,
3529                                    struct bpf_verifier_state *other_branch)
3530 {
3531         if (BPF_SRC(insn->code) != BPF_X)
3532                 return false;
3533
3534         switch (BPF_OP(insn->code)) {
3535         case BPF_JGT:
3536                 if ((dst_reg->type == PTR_TO_PACKET &&
3537                      src_reg->type == PTR_TO_PACKET_END) ||
3538                     (dst_reg->type == PTR_TO_PACKET_META &&
3539                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3540                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
3541                         find_good_pkt_pointers(this_branch, dst_reg,
3542                                                dst_reg->type, false);
3543                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3544                             src_reg->type == PTR_TO_PACKET) ||
3545                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3546                             src_reg->type == PTR_TO_PACKET_META)) {
3547                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
3548                         find_good_pkt_pointers(other_branch, src_reg,
3549                                                src_reg->type, true);
3550                 } else {
3551                         return false;
3552                 }
3553                 break;
3554         case BPF_JLT:
3555                 if ((dst_reg->type == PTR_TO_PACKET &&
3556                      src_reg->type == PTR_TO_PACKET_END) ||
3557                     (dst_reg->type == PTR_TO_PACKET_META &&
3558                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3559                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
3560                         find_good_pkt_pointers(other_branch, dst_reg,
3561                                                dst_reg->type, true);
3562                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3563                             src_reg->type == PTR_TO_PACKET) ||
3564                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3565                             src_reg->type == PTR_TO_PACKET_META)) {
3566                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
3567                         find_good_pkt_pointers(this_branch, src_reg,
3568                                                src_reg->type, false);
3569                 } else {
3570                         return false;
3571                 }
3572                 break;
3573         case BPF_JGE:
3574                 if ((dst_reg->type == PTR_TO_PACKET &&
3575                      src_reg->type == PTR_TO_PACKET_END) ||
3576                     (dst_reg->type == PTR_TO_PACKET_META &&
3577                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3578                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
3579                         find_good_pkt_pointers(this_branch, dst_reg,
3580                                                dst_reg->type, true);
3581                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3582                             src_reg->type == PTR_TO_PACKET) ||
3583                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3584                             src_reg->type == PTR_TO_PACKET_META)) {
3585                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
3586                         find_good_pkt_pointers(other_branch, src_reg,
3587                                                src_reg->type, false);
3588                 } else {
3589                         return false;
3590                 }
3591                 break;
3592         case BPF_JLE:
3593                 if ((dst_reg->type == PTR_TO_PACKET &&
3594                      src_reg->type == PTR_TO_PACKET_END) ||
3595                     (dst_reg->type == PTR_TO_PACKET_META &&
3596                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
3597                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
3598                         find_good_pkt_pointers(other_branch, dst_reg,
3599                                                dst_reg->type, false);
3600                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
3601                             src_reg->type == PTR_TO_PACKET) ||
3602                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
3603                             src_reg->type == PTR_TO_PACKET_META)) {
3604                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
3605                         find_good_pkt_pointers(this_branch, src_reg,
3606                                                src_reg->type, true);
3607                 } else {
3608                         return false;
3609                 }
3610                 break;
3611         default:
3612                 return false;
3613         }
3614
3615         return true;
3616 }
3617
3618 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3619                              struct bpf_insn *insn, int *insn_idx)
3620 {
3621         struct bpf_verifier_state *this_branch = env->cur_state;
3622         struct bpf_verifier_state *other_branch;
3623         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
3624         struct bpf_reg_state *dst_reg, *other_branch_regs;
3625         u8 opcode = BPF_OP(insn->code);
3626         int err;
3627
3628         if (opcode > BPF_JSLE) {
3629                 verbose(env, "invalid BPF_JMP opcode %x\n", opcode);
3630                 return -EINVAL;
3631         }
3632
3633         if (BPF_SRC(insn->code) == BPF_X) {
3634                 if (insn->imm != 0) {
3635                         verbose(env, "BPF_JMP uses reserved fields\n");
3636                         return -EINVAL;
3637                 }
3638
3639                 /* check src1 operand */
3640                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3641                 if (err)
3642                         return err;
3643
3644                 if (is_pointer_value(env, insn->src_reg)) {
3645                         verbose(env, "R%d pointer comparison prohibited\n",
3646                                 insn->src_reg);
3647                         return -EACCES;
3648                 }
3649         } else {
3650                 if (insn->src_reg != BPF_REG_0) {
3651                         verbose(env, "BPF_JMP uses reserved fields\n");
3652                         return -EINVAL;
3653                 }
3654         }
3655
3656         /* check src2 operand */
3657         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3658         if (err)
3659                 return err;
3660
3661         dst_reg = &regs[insn->dst_reg];
3662
3663         /* detect if R == 0 where R was initialized to zero earlier */
3664         if (BPF_SRC(insn->code) == BPF_K &&
3665             (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3666             dst_reg->type == SCALAR_VALUE &&
3667             tnum_is_const(dst_reg->var_off)) {
3668                 if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) ||
3669                     (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) {
3670                         /* if (imm == imm) goto pc+off;
3671                          * only follow the goto, ignore fall-through
3672                          */
3673                         *insn_idx += insn->off;
3674                         return 0;
3675                 } else {
3676                         /* if (imm != imm) goto pc+off;
3677                          * only follow fall-through branch, since
3678                          * that's where the program will go
3679                          */
3680                         return 0;
3681                 }
3682         }
3683
3684         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx);
3685         if (!other_branch)
3686                 return -EFAULT;
3687         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
3688
3689         /* detect if we are comparing against a constant value so we can adjust
3690          * our min/max values for our dst register.
3691          * this is only legit if both are scalars (or pointers to the same
3692          * object, I suppose, but we don't support that right now), because
3693          * otherwise the different base pointers mean the offsets aren't
3694          * comparable.
3695          */
3696         if (BPF_SRC(insn->code) == BPF_X) {
3697                 if (dst_reg->type == SCALAR_VALUE &&
3698                     regs[insn->src_reg].type == SCALAR_VALUE) {
3699                         if (tnum_is_const(regs[insn->src_reg].var_off))
3700                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3701                                                 dst_reg, regs[insn->src_reg].var_off.value,
3702                                                 opcode);
3703                         else if (tnum_is_const(dst_reg->var_off))
3704                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
3705                                                     &regs[insn->src_reg],
3706                                                     dst_reg->var_off.value, opcode);
3707                         else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3708                                 /* Comparing for equality, we can combine knowledge */
3709                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
3710                                                     &other_branch_regs[insn->dst_reg],
3711                                                     &regs[insn->src_reg],
3712                                                     &regs[insn->dst_reg], opcode);
3713                 }
3714         } else if (dst_reg->type == SCALAR_VALUE) {
3715                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3716                                         dst_reg, insn->imm, opcode);
3717         }
3718
3719         /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3720         if (BPF_SRC(insn->code) == BPF_K &&
3721             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3722             dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3723                 /* Mark all identical map registers in each branch as either
3724                  * safe or unknown depending R == 0 or R != 0 conditional.
3725                  */
3726                 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3727                 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3728         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
3729                                            this_branch, other_branch) &&
3730                    is_pointer_value(env, insn->dst_reg)) {
3731                 verbose(env, "R%d pointer comparison prohibited\n",
3732                         insn->dst_reg);
3733                 return -EACCES;
3734         }
3735         if (env->log.level)
3736                 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
3737         return 0;
3738 }
3739
3740 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3741 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3742 {
3743         u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3744
3745         return (struct bpf_map *) (unsigned long) imm64;
3746 }
3747
3748 /* verify BPF_LD_IMM64 instruction */
3749 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3750 {
3751         struct bpf_reg_state *regs = cur_regs(env);
3752         int err;
3753
3754         if (BPF_SIZE(insn->code) != BPF_DW) {
3755                 verbose(env, "invalid BPF_LD_IMM insn\n");
3756                 return -EINVAL;
3757         }
3758         if (insn->off != 0) {
3759                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
3760                 return -EINVAL;
3761         }
3762
3763         err = check_reg_arg(env, insn->dst_reg, DST_OP);
3764         if (err)
3765                 return err;
3766
3767         if (insn->src_reg == 0) {
3768                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3769
3770                 regs[insn->dst_reg].type = SCALAR_VALUE;
3771                 __mark_reg_known(&regs[insn->dst_reg], imm);
3772                 return 0;
3773         }
3774
3775         /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3776         BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3777
3778         regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3779         regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3780         return 0;
3781 }
3782
3783 static bool may_access_skb(enum bpf_prog_type type)
3784 {
3785         switch (type) {
3786         case BPF_PROG_TYPE_SOCKET_FILTER:
3787         case BPF_PROG_TYPE_SCHED_CLS:
3788         case BPF_PROG_TYPE_SCHED_ACT:
3789                 return true;
3790         default:
3791                 return false;
3792         }
3793 }
3794
3795 /* verify safety of LD_ABS|LD_IND instructions:
3796  * - they can only appear in the programs where ctx == skb
3797  * - since they are wrappers of function calls, they scratch R1-R5 registers,
3798  *   preserve R6-R9, and store return value into R0
3799  *
3800  * Implicit input:
3801  *   ctx == skb == R6 == CTX
3802  *
3803  * Explicit input:
3804  *   SRC == any register
3805  *   IMM == 32-bit immediate
3806  *
3807  * Output:
3808  *   R0 - 8/16/32-bit skb data converted to cpu endianness
3809  */
3810 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3811 {
3812         struct bpf_reg_state *regs = cur_regs(env);
3813         u8 mode = BPF_MODE(insn->code);
3814         int i, err;
3815
3816         if (!may_access_skb(env->prog->type)) {
3817                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3818                 return -EINVAL;
3819         }
3820
3821         if (env->subprog_cnt) {
3822                 /* when program has LD_ABS insn JITs and interpreter assume
3823                  * that r1 == ctx == skb which is not the case for callees
3824                  * that can have arbitrary arguments. It's problematic
3825                  * for main prog as well since JITs would need to analyze
3826                  * all functions in order to make proper register save/restore
3827                  * decisions in the main prog. Hence disallow LD_ABS with calls
3828                  */
3829                 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
3830                 return -EINVAL;
3831         }
3832
3833         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3834             BPF_SIZE(insn->code) == BPF_DW ||
3835             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3836                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
3837                 return -EINVAL;
3838         }
3839
3840         /* check whether implicit source operand (register R6) is readable */
3841         err = check_reg_arg(env, BPF_REG_6, SRC_OP);
3842         if (err)
3843                 return err;
3844
3845         if (regs[BPF_REG_6].type != PTR_TO_CTX) {
3846                 verbose(env,
3847                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3848                 return -EINVAL;
3849         }
3850
3851         if (mode == BPF_IND) {
3852                 /* check explicit source operand */
3853                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3854                 if (err)
3855                         return err;
3856         }
3857
3858         /* reset caller saved regs to unreadable */
3859         for (i = 0; i < CALLER_SAVED_REGS; i++) {
3860                 mark_reg_not_init(env, regs, caller_saved[i]);
3861                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3862         }
3863
3864         /* mark destination R0 register as readable, since it contains
3865          * the value fetched from the packet.
3866          * Already marked as written above.
3867          */
3868         mark_reg_unknown(env, regs, BPF_REG_0);
3869         return 0;
3870 }
3871
3872 static int check_return_code(struct bpf_verifier_env *env)
3873 {
3874         struct bpf_reg_state *reg;
3875         struct tnum range = tnum_range(0, 1);
3876
3877         switch (env->prog->type) {
3878         case BPF_PROG_TYPE_CGROUP_SKB:
3879         case BPF_PROG_TYPE_CGROUP_SOCK:
3880         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3881         case BPF_PROG_TYPE_SOCK_OPS:
3882         case BPF_PROG_TYPE_CGROUP_DEVICE:
3883                 break;
3884         default:
3885                 return 0;
3886         }
3887
3888         reg = cur_regs(env) + BPF_REG_0;
3889         if (reg->type != SCALAR_VALUE) {
3890                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
3891                         reg_type_str[reg->type]);
3892                 return -EINVAL;
3893         }
3894
3895         if (!tnum_in(range, reg->var_off)) {
3896                 verbose(env, "At program exit the register R0 ");
3897                 if (!tnum_is_unknown(reg->var_off)) {
3898                         char tn_buf[48];
3899
3900                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3901                         verbose(env, "has value %s", tn_buf);
3902                 } else {
3903                         verbose(env, "has unknown scalar value");
3904                 }
3905                 verbose(env, " should have been 0 or 1\n");
3906                 return -EINVAL;
3907         }
3908         return 0;
3909 }
3910
3911 /* non-recursive DFS pseudo code
3912  * 1  procedure DFS-iterative(G,v):
3913  * 2      label v as discovered
3914  * 3      let S be a stack
3915  * 4      S.push(v)
3916  * 5      while S is not empty
3917  * 6            t <- S.pop()
3918  * 7            if t is what we're looking for:
3919  * 8                return t
3920  * 9            for all edges e in G.adjacentEdges(t) do
3921  * 10               if edge e is already labelled
3922  * 11                   continue with the next edge
3923  * 12               w <- G.adjacentVertex(t,e)
3924  * 13               if vertex w is not discovered and not explored
3925  * 14                   label e as tree-edge
3926  * 15                   label w as discovered
3927  * 16                   S.push(w)
3928  * 17                   continue at 5
3929  * 18               else if vertex w is discovered
3930  * 19                   label e as back-edge
3931  * 20               else
3932  * 21                   // vertex w is explored
3933  * 22                   label e as forward- or cross-edge
3934  * 23           label t as explored
3935  * 24           S.pop()
3936  *
3937  * convention:
3938  * 0x10 - discovered
3939  * 0x11 - discovered and fall-through edge labelled
3940  * 0x12 - discovered and fall-through and branch edges labelled
3941  * 0x20 - explored
3942  */
3943
3944 enum {
3945         DISCOVERED = 0x10,
3946         EXPLORED = 0x20,
3947         FALLTHROUGH = 1,
3948         BRANCH = 2,
3949 };
3950
3951 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3952
3953 static int *insn_stack; /* stack of insns to process */
3954 static int cur_stack;   /* current stack index */
3955 static int *insn_state;
3956
3957 /* t, w, e - match pseudo-code above:
3958  * t - index of current instruction
3959  * w - next instruction
3960  * e - edge
3961  */
3962 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3963 {
3964         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3965                 return 0;
3966
3967         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3968                 return 0;
3969
3970         if (w < 0 || w >= env->prog->len) {
3971                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
3972                 return -EINVAL;
3973         }
3974
3975         if (e == BRANCH)
3976                 /* mark branch target for state pruning */
3977                 env->explored_states[w] = STATE_LIST_MARK;
3978
3979         if (insn_state[w] == 0) {
3980                 /* tree-edge */
3981                 insn_state[t] = DISCOVERED | e;
3982                 insn_state[w] = DISCOVERED;
3983                 if (cur_stack >= env->prog->len)
3984                         return -E2BIG;
3985                 insn_stack[cur_stack++] = w;
3986                 return 1;
3987         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3988                 verbose(env, "back-edge from insn %d to %d\n", t, w);
3989                 return -EINVAL;
3990         } else if (insn_state[w] == EXPLORED) {
3991                 /* forward- or cross-edge */
3992                 insn_state[t] = DISCOVERED | e;
3993         } else {
3994                 verbose(env, "insn state internal bug\n");
3995                 return -EFAULT;
3996         }
3997         return 0;
3998 }
3999
4000 /* non-recursive depth-first-search to detect loops in BPF program
4001  * loop == back-edge in directed graph
4002  */
4003 static int check_cfg(struct bpf_verifier_env *env)
4004 {
4005         struct bpf_insn *insns = env->prog->insnsi;
4006         int insn_cnt = env->prog->len;
4007         int ret = 0;
4008         int i, t;
4009
4010         ret = check_subprogs(env);
4011         if (ret < 0)
4012                 return ret;
4013
4014         insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4015         if (!insn_state)
4016                 return -ENOMEM;
4017
4018         insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4019         if (!insn_stack) {
4020                 kfree(insn_state);
4021                 return -ENOMEM;
4022         }
4023
4024         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4025         insn_stack[0] = 0; /* 0 is the first instruction */
4026         cur_stack = 1;
4027
4028 peek_stack:
4029         if (cur_stack == 0)
4030                 goto check_state;
4031         t = insn_stack[cur_stack - 1];
4032
4033         if (BPF_CLASS(insns[t].code) == BPF_JMP) {
4034                 u8 opcode = BPF_OP(insns[t].code);
4035
4036                 if (opcode == BPF_EXIT) {
4037                         goto mark_explored;
4038                 } else if (opcode == BPF_CALL) {
4039                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
4040                         if (ret == 1)
4041                                 goto peek_stack;
4042                         else if (ret < 0)
4043                                 goto err_free;
4044                         if (t + 1 < insn_cnt)
4045                                 env->explored_states[t + 1] = STATE_LIST_MARK;
4046                         if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4047                                 env->explored_states[t] = STATE_LIST_MARK;
4048                                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4049                                 if (ret == 1)
4050                                         goto peek_stack;
4051                                 else if (ret < 0)
4052                                         goto err_free;
4053                         }
4054                 } else if (opcode == BPF_JA) {
4055                         if (BPF_SRC(insns[t].code) != BPF_K) {
4056                                 ret = -EINVAL;
4057                                 goto err_free;
4058                         }
4059                         /* unconditional jump with single edge */
4060                         ret = push_insn(t, t + insns[t].off + 1,
4061                                         FALLTHROUGH, env);
4062                         if (ret == 1)
4063                                 goto peek_stack;
4064                         else if (ret < 0)
4065                                 goto err_free;
4066                         /* tell verifier to check for equivalent states
4067                          * after every call and jump
4068                          */
4069                         if (t + 1 < insn_cnt)
4070                                 env->explored_states[t + 1] = STATE_LIST_MARK;
4071                 } else {
4072                         /* conditional jump with two edges */
4073                         env->explored_states[t] = STATE_LIST_MARK;
4074                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
4075                         if (ret == 1)
4076                                 goto peek_stack;
4077                         else if (ret < 0)
4078                                 goto err_free;
4079
4080                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4081                         if (ret == 1)
4082                                 goto peek_stack;
4083                         else if (ret < 0)
4084                                 goto err_free;
4085                 }
4086         } else {
4087                 /* all other non-branch instructions with single
4088                  * fall-through edge
4089                  */
4090                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4091                 if (ret == 1)
4092                         goto peek_stack;
4093                 else if (ret < 0)
4094                         goto err_free;
4095         }
4096
4097 mark_explored:
4098         insn_state[t] = EXPLORED;
4099         if (cur_stack-- <= 0) {
4100                 verbose(env, "pop stack internal bug\n");
4101                 ret = -EFAULT;
4102                 goto err_free;
4103         }
4104         goto peek_stack;
4105
4106 check_state:
4107         for (i = 0; i < insn_cnt; i++) {
4108                 if (insn_state[i] != EXPLORED) {
4109                         verbose(env, "unreachable insn %d\n", i);
4110                         ret = -EINVAL;
4111                         goto err_free;
4112                 }
4113         }
4114         ret = 0; /* cfg looks good */
4115
4116 err_free:
4117         kfree(insn_state);
4118         kfree(insn_stack);
4119         return ret;
4120 }
4121
4122 /* check %cur's range satisfies %old's */
4123 static bool range_within(struct bpf_reg_state *old,
4124                          struct bpf_reg_state *cur)
4125 {
4126         return old->umin_value <= cur->umin_value &&
4127                old->umax_value >= cur->umax_value &&
4128                old->smin_value <= cur->smin_value &&
4129                old->smax_value >= cur->smax_value;
4130 }
4131
4132 /* Maximum number of register states that can exist at once */
4133 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4134 struct idpair {
4135         u32 old;
4136         u32 cur;
4137 };
4138
4139 /* If in the old state two registers had the same id, then they need to have
4140  * the same id in the new state as well.  But that id could be different from
4141  * the old state, so we need to track the mapping from old to new ids.
4142  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4143  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
4144  * regs with a different old id could still have new id 9, we don't care about
4145  * that.
4146  * So we look through our idmap to see if this old id has been seen before.  If
4147  * so, we require the new id to match; otherwise, we add the id pair to the map.
4148  */
4149 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4150 {
4151         unsigned int i;
4152
4153         for (i = 0; i < ID_MAP_SIZE; i++) {
4154                 if (!idmap[i].old) {
4155                         /* Reached an empty slot; haven't seen this id before */
4156                         idmap[i].old = old_id;
4157                         idmap[i].cur = cur_id;
4158                         return true;
4159                 }
4160                 if (idmap[i].old == old_id)
4161                         return idmap[i].cur == cur_id;
4162         }
4163         /* We ran out of idmap slots, which should be impossible */
4164         WARN_ON_ONCE(1);
4165         return false;
4166 }
4167
4168 /* Returns true if (rold safe implies rcur safe) */
4169 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4170                     struct idpair *idmap)
4171 {
4172         bool equal;
4173
4174         if (!(rold->live & REG_LIVE_READ))
4175                 /* explored state didn't use this */
4176                 return true;
4177
4178         equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, frameno)) == 0;
4179
4180         if (rold->type == PTR_TO_STACK)
4181                 /* two stack pointers are equal only if they're pointing to
4182                  * the same stack frame, since fp-8 in foo != fp-8 in bar
4183                  */
4184                 return equal && rold->frameno == rcur->frameno;
4185
4186         if (equal)
4187                 return true;
4188
4189         if (rold->type == NOT_INIT)
4190                 /* explored state can't have used this */
4191                 return true;
4192         if (rcur->type == NOT_INIT)
4193                 return false;
4194         switch (rold->type) {
4195         case SCALAR_VALUE:
4196                 if (rcur->type == SCALAR_VALUE) {
4197                         /* new val must satisfy old val knowledge */
4198                         return range_within(rold, rcur) &&
4199                                tnum_in(rold->var_off, rcur->var_off);
4200                 } else {
4201                         /* We're trying to use a pointer in place of a scalar.
4202                          * Even if the scalar was unbounded, this could lead to
4203                          * pointer leaks because scalars are allowed to leak
4204                          * while pointers are not. We could make this safe in
4205                          * special cases if root is calling us, but it's
4206                          * probably not worth the hassle.
4207                          */
4208                         return false;
4209                 }
4210         case PTR_TO_MAP_VALUE:
4211                 /* If the new min/max/var_off satisfy the old ones and
4212                  * everything else matches, we are OK.
4213                  * We don't care about the 'id' value, because nothing
4214                  * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4215                  */
4216                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4217                        range_within(rold, rcur) &&
4218                        tnum_in(rold->var_off, rcur->var_off);
4219         case PTR_TO_MAP_VALUE_OR_NULL:
4220                 /* a PTR_TO_MAP_VALUE could be safe to use as a
4221                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4222                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4223                  * checked, doing so could have affected others with the same
4224                  * id, and we can't check for that because we lost the id when
4225                  * we converted to a PTR_TO_MAP_VALUE.
4226                  */
4227                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
4228                         return false;
4229                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
4230                         return false;
4231                 /* Check our ids match any regs they're supposed to */
4232                 return check_ids(rold->id, rcur->id, idmap);
4233         case PTR_TO_PACKET_META:
4234         case PTR_TO_PACKET:
4235                 if (rcur->type != rold->type)
4236                         return false;
4237                 /* We must have at least as much range as the old ptr
4238                  * did, so that any accesses which were safe before are
4239                  * still safe.  This is true even if old range < old off,
4240                  * since someone could have accessed through (ptr - k), or
4241                  * even done ptr -= k in a register, to get a safe access.
4242                  */
4243                 if (rold->range > rcur->range)
4244                         return false;
4245                 /* If the offsets don't match, we can't trust our alignment;
4246                  * nor can we be sure that we won't fall out of range.
4247                  */
4248                 if (rold->off != rcur->off)
4249                         return false;
4250                 /* id relations must be preserved */
4251                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
4252                         return false;
4253                 /* new val must satisfy old val knowledge */
4254                 return range_within(rold, rcur) &&
4255                        tnum_in(rold->var_off, rcur->var_off);
4256         case PTR_TO_CTX:
4257         case CONST_PTR_TO_MAP:
4258         case PTR_TO_PACKET_END:
4259                 /* Only valid matches are exact, which memcmp() above
4260                  * would have accepted
4261                  */
4262         default:
4263                 /* Don't know what's going on, just say it's not safe */
4264                 return false;
4265         }
4266
4267         /* Shouldn't get here; if we do, say it's not safe */
4268         WARN_ON_ONCE(1);
4269         return false;
4270 }
4271
4272 static bool stacksafe(struct bpf_func_state *old,
4273                       struct bpf_func_state *cur,
4274                       struct idpair *idmap)
4275 {
4276         int i, spi;
4277
4278         /* if explored stack has more populated slots than current stack
4279          * such stacks are not equivalent
4280          */
4281         if (old->allocated_stack > cur->allocated_stack)
4282                 return false;
4283
4284         /* walk slots of the explored stack and ignore any additional
4285          * slots in the current stack, since explored(safe) state
4286          * didn't use them
4287          */
4288         for (i = 0; i < old->allocated_stack; i++) {
4289                 spi = i / BPF_REG_SIZE;
4290
4291                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
4292                         /* explored state didn't use this */
4293                         continue;
4294
4295                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
4296                         continue;
4297                 /* if old state was safe with misc data in the stack
4298                  * it will be safe with zero-initialized stack.
4299                  * The opposite is not true
4300                  */
4301                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
4302                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
4303                         continue;
4304                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
4305                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
4306                         /* Ex: old explored (safe) state has STACK_SPILL in
4307                          * this stack slot, but current has has STACK_MISC ->
4308                          * this verifier states are not equivalent,
4309                          * return false to continue verification of this path
4310                          */
4311                         return false;
4312                 if (i % BPF_REG_SIZE)
4313                         continue;
4314                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
4315                         continue;
4316                 if (!regsafe(&old->stack[spi].spilled_ptr,
4317                              &cur->stack[spi].spilled_ptr,
4318                              idmap))
4319                         /* when explored and current stack slot are both storing
4320                          * spilled registers, check that stored pointers types
4321                          * are the same as well.
4322                          * Ex: explored safe path could have stored
4323                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
4324                          * but current path has stored:
4325                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
4326                          * such verifier states are not equivalent.
4327                          * return false to continue verification of this path
4328                          */
4329                         return false;
4330         }
4331         return true;
4332 }
4333
4334 /* compare two verifier states
4335  *
4336  * all states stored in state_list are known to be valid, since
4337  * verifier reached 'bpf_exit' instruction through them
4338  *
4339  * this function is called when verifier exploring different branches of
4340  * execution popped from the state stack. If it sees an old state that has
4341  * more strict register state and more strict stack state then this execution
4342  * branch doesn't need to be explored further, since verifier already
4343  * concluded that more strict state leads to valid finish.
4344  *
4345  * Therefore two states are equivalent if register state is more conservative
4346  * and explored stack state is more conservative than the current one.
4347  * Example:
4348  *       explored                   current
4349  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
4350  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
4351  *
4352  * In other words if current stack state (one being explored) has more
4353  * valid slots than old one that already passed validation, it means
4354  * the verifier can stop exploring and conclude that current state is valid too
4355  *
4356  * Similarly with registers. If explored state has register type as invalid
4357  * whereas register type in current state is meaningful, it means that
4358  * the current state will reach 'bpf_exit' instruction safely
4359  */
4360 static bool func_states_equal(struct bpf_func_state *old,
4361                               struct bpf_func_state *cur)
4362 {
4363         struct idpair *idmap;
4364         bool ret = false;
4365         int i;
4366
4367         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4368         /* If we failed to allocate the idmap, just say it's not safe */
4369         if (!idmap)
4370                 return false;
4371
4372         for (i = 0; i < MAX_BPF_REG; i++) {
4373                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4374                         goto out_free;
4375         }
4376
4377         if (!stacksafe(old, cur, idmap))
4378                 goto out_free;
4379         ret = true;
4380 out_free:
4381         kfree(idmap);
4382         return ret;
4383 }
4384
4385 static bool states_equal(struct bpf_verifier_env *env,
4386                          struct bpf_verifier_state *old,
4387                          struct bpf_verifier_state *cur)
4388 {
4389         int i;
4390
4391         if (old->curframe != cur->curframe)
4392                 return false;
4393
4394         /* for states to be equal callsites have to be the same
4395          * and all frame states need to be equivalent
4396          */
4397         for (i = 0; i <= old->curframe; i++) {
4398                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
4399                         return false;
4400                 if (!func_states_equal(old->frame[i], cur->frame[i]))
4401                         return false;
4402         }
4403         return true;
4404 }
4405
4406 /* A write screens off any subsequent reads; but write marks come from the
4407  * straight-line code between a state and its parent.  When we arrive at an
4408  * equivalent state (jump target or such) we didn't arrive by the straight-line
4409  * code, so read marks in the state must propagate to the parent regardless
4410  * of the state's write marks. That's what 'parent == state->parent' comparison
4411  * in mark_reg_read() and mark_stack_slot_read() is for.
4412  */
4413 static int propagate_liveness(struct bpf_verifier_env *env,
4414                               const struct bpf_verifier_state *vstate,
4415                               struct bpf_verifier_state *vparent)
4416 {
4417         int i, frame, err = 0;
4418         struct bpf_func_state *state, *parent;
4419
4420         if (vparent->curframe != vstate->curframe) {
4421                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
4422                      vparent->curframe, vstate->curframe);
4423                 return -EFAULT;
4424         }
4425         /* Propagate read liveness of registers... */
4426         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4427         /* We don't need to worry about FP liveness because it's read-only */
4428         for (i = 0; i < BPF_REG_FP; i++) {
4429                 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
4430                         continue;
4431                 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
4432                         err = mark_reg_read(env, vstate, vparent, i);
4433                         if (err)
4434                                 return err;
4435                 }
4436         }
4437
4438         /* ... and stack slots */
4439         for (frame = 0; frame <= vstate->curframe; frame++) {
4440                 state = vstate->frame[frame];
4441                 parent = vparent->frame[frame];
4442                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4443                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4444                         if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4445                                 continue;
4446                         if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
4447                                 mark_stack_slot_read(env, vstate, vparent, i, frame);
4448                 }
4449         }
4450         return err;
4451 }
4452
4453 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4454 {
4455         struct bpf_verifier_state_list *new_sl;
4456         struct bpf_verifier_state_list *sl;
4457         struct bpf_verifier_state *cur = env->cur_state;
4458         int i, j, err;
4459
4460         sl = env->explored_states[insn_idx];
4461         if (!sl)
4462                 /* this 'insn_idx' instruction wasn't marked, so we will not
4463                  * be doing state search here
4464                  */
4465                 return 0;
4466
4467         while (sl != STATE_LIST_MARK) {
4468                 if (states_equal(env, &sl->state, cur)) {
4469                         /* reached equivalent register/stack state,
4470                          * prune the search.
4471                          * Registers read by the continuation are read by us.
4472                          * If we have any write marks in env->cur_state, they
4473                          * will prevent corresponding reads in the continuation
4474                          * from reaching our parent (an explored_state).  Our
4475                          * own state will get the read marks recorded, but
4476                          * they'll be immediately forgotten as we're pruning
4477                          * this state and will pop a new one.
4478                          */
4479                         err = propagate_liveness(env, &sl->state, cur);
4480                         if (err)
4481                                 return err;
4482                         return 1;
4483                 }
4484                 sl = sl->next;
4485         }
4486
4487         /* there were no equivalent states, remember current one.
4488          * technically the current state is not proven to be safe yet,
4489          * but it will either reach outer most bpf_exit (which means it's safe)
4490          * or it will be rejected. Since there are no loops, we won't be
4491          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
4492          * again on the way to bpf_exit
4493          */
4494         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4495         if (!new_sl)
4496                 return -ENOMEM;
4497
4498         /* add new state to the head of linked list */
4499         err = copy_verifier_state(&new_sl->state, cur);
4500         if (err) {
4501                 free_verifier_state(&new_sl->state, false);
4502                 kfree(new_sl);
4503                 return err;
4504         }
4505         new_sl->next = env->explored_states[insn_idx];
4506         env->explored_states[insn_idx] = new_sl;
4507         /* connect new state to parentage chain */
4508         cur->parent = &new_sl->state;
4509         /* clear write marks in current state: the writes we did are not writes
4510          * our child did, so they don't screen off its reads from us.
4511          * (There are no read marks in current state, because reads always mark
4512          * their parent and current state never has children yet.  Only
4513          * explored_states can get read marks.)
4514          */
4515         for (i = 0; i < BPF_REG_FP; i++)
4516                 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
4517
4518         /* all stack frames are accessible from callee, clear them all */
4519         for (j = 0; j <= cur->curframe; j++) {
4520                 struct bpf_func_state *frame = cur->frame[j];
4521
4522                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++)
4523                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4524         }
4525         return 0;
4526 }
4527
4528 static int do_check(struct bpf_verifier_env *env)
4529 {
4530         struct bpf_verifier_state *state;
4531         struct bpf_insn *insns = env->prog->insnsi;
4532         struct bpf_reg_state *regs;
4533         int insn_cnt = env->prog->len, i;
4534         int insn_idx, prev_insn_idx = 0;
4535         int insn_processed = 0;
4536         bool do_print_state = false;
4537
4538         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4539         if (!state)
4540                 return -ENOMEM;
4541         state->curframe = 0;
4542         state->parent = NULL;
4543         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
4544         if (!state->frame[0]) {
4545                 kfree(state);
4546                 return -ENOMEM;
4547         }
4548         env->cur_state = state;
4549         init_func_state(env, state->frame[0],
4550                         BPF_MAIN_FUNC /* callsite */,
4551                         0 /* frameno */,
4552                         0 /* subprogno, zero == main subprog */);
4553         insn_idx = 0;
4554         for (;;) {
4555                 struct bpf_insn *insn;
4556                 u8 class;
4557                 int err;
4558
4559                 if (insn_idx >= insn_cnt) {
4560                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
4561                                 insn_idx, insn_cnt);
4562                         return -EFAULT;
4563                 }
4564
4565                 insn = &insns[insn_idx];
4566                 class = BPF_CLASS(insn->code);
4567
4568                 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4569                         verbose(env,
4570                                 "BPF program is too large. Processed %d insn\n",
4571                                 insn_processed);
4572                         return -E2BIG;
4573                 }
4574
4575                 err = is_state_visited(env, insn_idx);
4576                 if (err < 0)
4577                         return err;
4578                 if (err == 1) {
4579                         /* found equivalent state, can prune the search */
4580                         if (env->log.level) {
4581                                 if (do_print_state)
4582                                         verbose(env, "\nfrom %d to %d: safe\n",
4583                                                 prev_insn_idx, insn_idx);
4584                                 else
4585                                         verbose(env, "%d: safe\n", insn_idx);
4586                         }
4587                         goto process_bpf_exit;
4588                 }
4589
4590                 if (need_resched())
4591                         cond_resched();
4592
4593                 if (env->log.level > 1 || (env->log.level && do_print_state)) {
4594                         if (env->log.level > 1)
4595                                 verbose(env, "%d:", insn_idx);
4596                         else
4597                                 verbose(env, "\nfrom %d to %d:",
4598                                         prev_insn_idx, insn_idx);
4599                         print_verifier_state(env, state->frame[state->curframe]);
4600                         do_print_state = false;
4601                 }
4602
4603                 if (env->log.level) {
4604                         const struct bpf_insn_cbs cbs = {
4605                                 .cb_print       = verbose,
4606                                 .private_data   = env,
4607                         };
4608
4609                         verbose(env, "%d: ", insn_idx);
4610                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
4611                 }
4612
4613                 if (bpf_prog_is_dev_bound(env->prog->aux)) {
4614                         err = bpf_prog_offload_verify_insn(env, insn_idx,
4615                                                            prev_insn_idx);
4616                         if (err)
4617                                 return err;
4618                 }
4619
4620                 regs = cur_regs(env);
4621                 env->insn_aux_data[insn_idx].seen = true;
4622                 if (class == BPF_ALU || class == BPF_ALU64) {
4623                         err = check_alu_op(env, insn);
4624                         if (err)
4625                                 return err;
4626
4627                 } else if (class == BPF_LDX) {
4628                         enum bpf_reg_type *prev_src_type, src_reg_type;
4629
4630                         /* check for reserved fields is already done */
4631
4632                         /* check src operand */
4633                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4634                         if (err)
4635                                 return err;
4636
4637                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4638                         if (err)
4639                                 return err;
4640
4641                         src_reg_type = regs[insn->src_reg].type;
4642
4643                         /* check that memory (src_reg + off) is readable,
4644                          * the state of dst_reg will be updated by this func
4645                          */
4646                         err = check_mem_access(env, insn_idx, insn->src_reg, insn->off,
4647                                                BPF_SIZE(insn->code), BPF_READ,
4648                                                insn->dst_reg, false);
4649                         if (err)
4650                                 return err;
4651
4652                         prev_src_type = &env->insn_aux_data[insn_idx].ptr_type;
4653
4654                         if (*prev_src_type == NOT_INIT) {
4655                                 /* saw a valid insn
4656                                  * dst_reg = *(u32 *)(src_reg + off)
4657                                  * save type to validate intersecting paths
4658                                  */
4659                                 *prev_src_type = src_reg_type;
4660
4661                         } else if (src_reg_type != *prev_src_type &&
4662                                    (src_reg_type == PTR_TO_CTX ||
4663                                     *prev_src_type == PTR_TO_CTX)) {
4664                                 /* ABuser program is trying to use the same insn
4665                                  * dst_reg = *(u32*) (src_reg + off)
4666                                  * with different pointer types:
4667                                  * src_reg == ctx in one branch and
4668                                  * src_reg == stack|map in some other branch.
4669                                  * Reject it.
4670                                  */
4671                                 verbose(env, "same insn cannot be used with different pointers\n");
4672                                 return -EINVAL;
4673                         }
4674
4675                 } else if (class == BPF_STX) {
4676                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
4677
4678                         if (BPF_MODE(insn->code) == BPF_XADD) {
4679                                 err = check_xadd(env, insn_idx, insn);
4680                                 if (err)
4681                                         return err;
4682                                 insn_idx++;
4683                                 continue;
4684                         }
4685
4686                         /* check src1 operand */
4687                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4688                         if (err)
4689                                 return err;
4690                         /* check src2 operand */
4691                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4692                         if (err)
4693                                 return err;
4694
4695                         dst_reg_type = regs[insn->dst_reg].type;
4696
4697                         /* check that memory (dst_reg + off) is writeable */
4698                         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4699                                                BPF_SIZE(insn->code), BPF_WRITE,
4700                                                insn->src_reg, false);
4701                         if (err)
4702                                 return err;
4703
4704                         prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type;
4705
4706                         if (*prev_dst_type == NOT_INIT) {
4707                                 *prev_dst_type = dst_reg_type;
4708                         } else if (dst_reg_type != *prev_dst_type &&
4709                                    (dst_reg_type == PTR_TO_CTX ||
4710                                     *prev_dst_type == PTR_TO_CTX)) {
4711                                 verbose(env, "same insn cannot be used with different pointers\n");
4712                                 return -EINVAL;
4713                         }
4714
4715                 } else if (class == BPF_ST) {
4716                         if (BPF_MODE(insn->code) != BPF_MEM ||
4717                             insn->src_reg != BPF_REG_0) {
4718                                 verbose(env, "BPF_ST uses reserved fields\n");
4719                                 return -EINVAL;
4720                         }
4721                         /* check src operand */
4722                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4723                         if (err)
4724                                 return err;
4725
4726                         if (is_ctx_reg(env, insn->dst_reg)) {
4727                                 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
4728                                         insn->dst_reg);
4729                                 return -EACCES;
4730                         }
4731
4732                         /* check that memory (dst_reg + off) is writeable */
4733                         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4734                                                BPF_SIZE(insn->code), BPF_WRITE,
4735                                                -1, false);
4736                         if (err)
4737                                 return err;
4738
4739                 } else if (class == BPF_JMP) {
4740                         u8 opcode = BPF_OP(insn->code);
4741
4742                         if (opcode == BPF_CALL) {
4743                                 if (BPF_SRC(insn->code) != BPF_K ||
4744                                     insn->off != 0 ||
4745                                     (insn->src_reg != BPF_REG_0 &&
4746                                      insn->src_reg != BPF_PSEUDO_CALL) ||
4747                                     insn->dst_reg != BPF_REG_0) {
4748                                         verbose(env, "BPF_CALL uses reserved fields\n");
4749                                         return -EINVAL;
4750                                 }
4751
4752                                 if (insn->src_reg == BPF_PSEUDO_CALL)
4753                                         err = check_func_call(env, insn, &insn_idx);
4754                                 else
4755                                         err = check_helper_call(env, insn->imm, insn_idx);
4756                                 if (err)
4757                                         return err;
4758
4759                         } else if (opcode == BPF_JA) {
4760                                 if (BPF_SRC(insn->code) != BPF_K ||
4761                                     insn->imm != 0 ||
4762                                     insn->src_reg != BPF_REG_0 ||
4763                                     insn->dst_reg != BPF_REG_0) {
4764                                         verbose(env, "BPF_JA uses reserved fields\n");
4765                                         return -EINVAL;
4766                                 }
4767
4768                                 insn_idx += insn->off + 1;
4769                                 continue;
4770
4771                         } else if (opcode == BPF_EXIT) {
4772                                 if (BPF_SRC(insn->code) != BPF_K ||
4773                                     insn->imm != 0 ||
4774                                     insn->src_reg != BPF_REG_0 ||
4775                                     insn->dst_reg != BPF_REG_0) {
4776                                         verbose(env, "BPF_EXIT uses reserved fields\n");
4777                                         return -EINVAL;
4778                                 }
4779
4780                                 if (state->curframe) {
4781                                         /* exit from nested function */
4782                                         prev_insn_idx = insn_idx;
4783                                         err = prepare_func_exit(env, &insn_idx);
4784                                         if (err)
4785                                                 return err;
4786                                         do_print_state = true;
4787                                         continue;
4788                                 }
4789
4790                                 /* eBPF calling convetion is such that R0 is used
4791                                  * to return the value from eBPF program.
4792                                  * Make sure that it's readable at this time
4793                                  * of bpf_exit, which means that program wrote
4794                                  * something into it earlier
4795                                  */
4796                                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4797                                 if (err)
4798                                         return err;
4799
4800                                 if (is_pointer_value(env, BPF_REG_0)) {
4801                                         verbose(env, "R0 leaks addr as return value\n");
4802                                         return -EACCES;
4803                                 }
4804
4805                                 err = check_return_code(env);
4806                                 if (err)
4807                                         return err;
4808 process_bpf_exit:
4809                                 err = pop_stack(env, &prev_insn_idx, &insn_idx);
4810                                 if (err < 0) {
4811                                         if (err != -ENOENT)
4812                                                 return err;
4813                                         break;
4814                                 } else {
4815                                         do_print_state = true;
4816                                         continue;
4817                                 }
4818                         } else {
4819                                 err = check_cond_jmp_op(env, insn, &insn_idx);
4820                                 if (err)
4821                                         return err;
4822                         }
4823                 } else if (class == BPF_LD) {
4824                         u8 mode = BPF_MODE(insn->code);
4825
4826                         if (mode == BPF_ABS || mode == BPF_IND) {
4827                                 err = check_ld_abs(env, insn);
4828                                 if (err)
4829                                         return err;
4830
4831                         } else if (mode == BPF_IMM) {
4832                                 err = check_ld_imm(env, insn);
4833                                 if (err)
4834                                         return err;
4835
4836                                 insn_idx++;
4837                                 env->insn_aux_data[insn_idx].seen = true;
4838                         } else {
4839                                 verbose(env, "invalid BPF_LD mode\n");
4840                                 return -EINVAL;
4841                         }
4842                 } else {
4843                         verbose(env, "unknown insn class %d\n", class);
4844                         return -EINVAL;
4845                 }
4846
4847                 insn_idx++;
4848         }
4849
4850         verbose(env, "processed %d insns (limit %d), stack depth ",
4851                 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
4852         for (i = 0; i < env->subprog_cnt + 1; i++) {
4853                 u32 depth = env->subprog_stack_depth[i];
4854
4855                 verbose(env, "%d", depth);
4856                 if (i + 1 < env->subprog_cnt + 1)
4857                         verbose(env, "+");
4858         }
4859         verbose(env, "\n");
4860         env->prog->aux->stack_depth = env->subprog_stack_depth[0];
4861         return 0;
4862 }
4863
4864 static int check_map_prealloc(struct bpf_map *map)
4865 {
4866         return (map->map_type != BPF_MAP_TYPE_HASH &&
4867                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4868                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4869                 !(map->map_flags & BPF_F_NO_PREALLOC);
4870 }
4871
4872 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
4873                                         struct bpf_map *map,
4874                                         struct bpf_prog *prog)
4875
4876 {
4877         /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4878          * preallocated hash maps, since doing memory allocation
4879          * in overflow_handler can crash depending on where nmi got
4880          * triggered.
4881          */
4882         if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4883                 if (!check_map_prealloc(map)) {
4884                         verbose(env, "perf_event programs can only use preallocated hash map\n");
4885                         return -EINVAL;
4886                 }
4887                 if (map->inner_map_meta &&
4888                     !check_map_prealloc(map->inner_map_meta)) {
4889                         verbose(env, "perf_event programs can only use preallocated inner hash map\n");
4890                         return -EINVAL;
4891                 }
4892         }
4893
4894         if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
4895             !bpf_offload_dev_match(prog, map)) {
4896                 verbose(env, "offload device mismatch between prog and map\n");
4897                 return -EINVAL;
4898         }
4899
4900         return 0;
4901 }
4902
4903 /* look for pseudo eBPF instructions that access map FDs and
4904  * replace them with actual map pointers
4905  */
4906 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4907 {
4908         struct bpf_insn *insn = env->prog->insnsi;
4909         int insn_cnt = env->prog->len;
4910         int i, j, err;
4911
4912         err = bpf_prog_calc_tag(env->prog);
4913         if (err)
4914                 return err;
4915
4916         for (i = 0; i < insn_cnt; i++, insn++) {
4917                 if (BPF_CLASS(insn->code) == BPF_LDX &&
4918                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4919                         verbose(env, "BPF_LDX uses reserved fields\n");
4920                         return -EINVAL;
4921                 }
4922
4923                 if (BPF_CLASS(insn->code) == BPF_STX &&
4924                     ((BPF_MODE(insn->code) != BPF_MEM &&
4925                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4926                         verbose(env, "BPF_STX uses reserved fields\n");
4927                         return -EINVAL;
4928                 }
4929
4930                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4931                         struct bpf_map *map;
4932                         struct fd f;
4933
4934                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
4935                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4936                             insn[1].off != 0) {
4937                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
4938                                 return -EINVAL;
4939                         }
4940
4941                         if (insn->src_reg == 0)
4942                                 /* valid generic load 64-bit imm */
4943                                 goto next_insn;
4944
4945                         if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4946                                 verbose(env,
4947                                         "unrecognized bpf_ld_imm64 insn\n");
4948                                 return -EINVAL;
4949                         }
4950
4951                         f = fdget(insn->imm);
4952                         map = __bpf_map_get(f);
4953                         if (IS_ERR(map)) {
4954                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
4955                                         insn->imm);
4956                                 return PTR_ERR(map);
4957                         }
4958
4959                         err = check_map_prog_compatibility(env, map, env->prog);
4960                         if (err) {
4961                                 fdput(f);
4962                                 return err;
4963                         }
4964
4965                         /* store map pointer inside BPF_LD_IMM64 instruction */
4966                         insn[0].imm = (u32) (unsigned long) map;
4967                         insn[1].imm = ((u64) (unsigned long) map) >> 32;
4968
4969                         /* check whether we recorded this map already */
4970                         for (j = 0; j < env->used_map_cnt; j++)
4971                                 if (env->used_maps[j] == map) {
4972                                         fdput(f);
4973                                         goto next_insn;
4974                                 }
4975
4976                         if (env->used_map_cnt >= MAX_USED_MAPS) {
4977                                 fdput(f);
4978                                 return -E2BIG;
4979                         }
4980
4981                         /* hold the map. If the program is rejected by verifier,
4982                          * the map will be released by release_maps() or it
4983                          * will be used by the valid program until it's unloaded
4984                          * and all maps are released in free_bpf_prog_info()
4985                          */
4986                         map = bpf_map_inc(map, false);
4987                         if (IS_ERR(map)) {
4988                                 fdput(f);
4989                                 return PTR_ERR(map);
4990                         }
4991                         env->used_maps[env->used_map_cnt++] = map;
4992
4993                         fdput(f);
4994 next_insn:
4995                         insn++;
4996                         i++;
4997                         continue;
4998                 }
4999
5000                 /* Basic sanity check before we invest more work here. */
5001                 if (!bpf_opcode_in_insntable(insn->code)) {
5002                         verbose(env, "unknown opcode %02x\n", insn->code);
5003                         return -EINVAL;
5004                 }
5005         }
5006
5007         /* now all pseudo BPF_LD_IMM64 instructions load valid
5008          * 'struct bpf_map *' into a register instead of user map_fd.
5009          * These pointers will be used later by verifier to validate map access.
5010          */
5011         return 0;
5012 }
5013
5014 /* drop refcnt of maps used by the rejected program */
5015 static void release_maps(struct bpf_verifier_env *env)
5016 {
5017         int i;
5018
5019         for (i = 0; i < env->used_map_cnt; i++)
5020                 bpf_map_put(env->used_maps[i]);
5021 }
5022
5023 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
5024 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5025 {
5026         struct bpf_insn *insn = env->prog->insnsi;
5027         int insn_cnt = env->prog->len;
5028         int i;
5029
5030         for (i = 0; i < insn_cnt; i++, insn++)
5031                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5032                         insn->src_reg = 0;
5033 }
5034
5035 /* single env->prog->insni[off] instruction was replaced with the range
5036  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
5037  * [0, off) and [off, end) to new locations, so the patched range stays zero
5038  */
5039 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5040                                 u32 off, u32 cnt)
5041 {
5042         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5043         int i;
5044
5045         if (cnt == 1)
5046                 return 0;
5047         new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
5048         if (!new_data)
5049                 return -ENOMEM;
5050         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5051         memcpy(new_data + off + cnt - 1, old_data + off,
5052                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5053         for (i = off; i < off + cnt - 1; i++)
5054                 new_data[i].seen = true;
5055         env->insn_aux_data = new_data;
5056         vfree(old_data);
5057         return 0;
5058 }
5059
5060 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5061 {
5062         int i;
5063
5064         if (len == 1)
5065                 return;
5066         for (i = 0; i < env->subprog_cnt; i++) {
5067                 if (env->subprog_starts[i] < off)
5068                         continue;
5069                 env->subprog_starts[i] += len - 1;
5070         }
5071 }
5072
5073 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5074                                             const struct bpf_insn *patch, u32 len)
5075 {
5076         struct bpf_prog *new_prog;
5077
5078         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5079         if (!new_prog)
5080                 return NULL;
5081         if (adjust_insn_aux_data(env, new_prog->len, off, len))
5082                 return NULL;
5083         adjust_subprog_starts(env, off, len);
5084         return new_prog;
5085 }
5086
5087 /* The verifier does more data flow analysis than llvm and will not
5088  * explore branches that are dead at run time. Malicious programs can
5089  * have dead code too. Therefore replace all dead at-run-time code
5090  * with 'ja -1'.
5091  *
5092  * Just nops are not optimal, e.g. if they would sit at the end of the
5093  * program and through another bug we would manage to jump there, then
5094  * we'd execute beyond program memory otherwise. Returning exception
5095  * code also wouldn't work since we can have subprogs where the dead
5096  * code could be located.
5097  */
5098 static void sanitize_dead_code(struct bpf_verifier_env *env)
5099 {
5100         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5101         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5102         struct bpf_insn *insn = env->prog->insnsi;
5103         const int insn_cnt = env->prog->len;
5104         int i;
5105
5106         for (i = 0; i < insn_cnt; i++) {
5107                 if (aux_data[i].seen)
5108                         continue;
5109                 memcpy(insn + i, &trap, sizeof(trap));
5110         }
5111 }
5112
5113 /* convert load instructions that access fields of 'struct __sk_buff'
5114  * into sequence of instructions that access fields of 'struct sk_buff'
5115  */
5116 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5117 {
5118         const struct bpf_verifier_ops *ops = env->ops;
5119         int i, cnt, size, ctx_field_size, delta = 0;
5120         const int insn_cnt = env->prog->len;
5121         struct bpf_insn insn_buf[16], *insn;
5122         struct bpf_prog *new_prog;
5123         enum bpf_access_type type;
5124         bool is_narrower_load;
5125         u32 target_size;
5126
5127         if (ops->gen_prologue) {
5128                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5129                                         env->prog);
5130                 if (cnt >= ARRAY_SIZE(insn_buf)) {
5131                         verbose(env, "bpf verifier is misconfigured\n");
5132                         return -EINVAL;
5133                 } else if (cnt) {
5134                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5135                         if (!new_prog)
5136                                 return -ENOMEM;
5137
5138                         env->prog = new_prog;
5139                         delta += cnt - 1;
5140                 }
5141         }
5142
5143         if (!ops->convert_ctx_access)
5144                 return 0;
5145
5146         insn = env->prog->insnsi + delta;
5147
5148         for (i = 0; i < insn_cnt; i++, insn++) {
5149                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5150                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5151                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5152                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
5153                         type = BPF_READ;
5154                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5155                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5156                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5157                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
5158                         type = BPF_WRITE;
5159                 else
5160                         continue;
5161
5162                 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
5163                         continue;
5164
5165                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
5166                 size = BPF_LDST_BYTES(insn);
5167
5168                 /* If the read access is a narrower load of the field,
5169                  * convert to a 4/8-byte load, to minimum program type specific
5170                  * convert_ctx_access changes. If conversion is successful,
5171                  * we will apply proper mask to the result.
5172                  */
5173                 is_narrower_load = size < ctx_field_size;
5174                 if (is_narrower_load) {
5175                         u32 off = insn->off;
5176                         u8 size_code;
5177
5178                         if (type == BPF_WRITE) {
5179                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
5180                                 return -EINVAL;
5181                         }
5182
5183                         size_code = BPF_H;
5184                         if (ctx_field_size == 4)
5185                                 size_code = BPF_W;
5186                         else if (ctx_field_size == 8)
5187                                 size_code = BPF_DW;
5188
5189                         insn->off = off & ~(ctx_field_size - 1);
5190                         insn->code = BPF_LDX | BPF_MEM | size_code;
5191                 }
5192
5193                 target_size = 0;
5194                 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
5195                                               &target_size);
5196                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
5197                     (ctx_field_size && !target_size)) {
5198                         verbose(env, "bpf verifier is misconfigured\n");
5199                         return -EINVAL;
5200                 }
5201
5202                 if (is_narrower_load && size < target_size) {
5203                         if (ctx_field_size <= 4)
5204                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
5205                                                                 (1 << size * 8) - 1);
5206                         else
5207                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
5208                                                                 (1 << size * 8) - 1);
5209                 }
5210
5211                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5212                 if (!new_prog)
5213                         return -ENOMEM;
5214
5215                 delta += cnt - 1;
5216
5217                 /* keep walking new program and skip insns we just inserted */
5218                 env->prog = new_prog;
5219                 insn      = new_prog->insnsi + i + delta;
5220         }
5221
5222         return 0;
5223 }
5224
5225 static int jit_subprogs(struct bpf_verifier_env *env)
5226 {
5227         struct bpf_prog *prog = env->prog, **func, *tmp;
5228         int i, j, subprog_start, subprog_end = 0, len, subprog;
5229         struct bpf_insn *insn;
5230         void *old_bpf_func;
5231         int err = -ENOMEM;
5232
5233         if (env->subprog_cnt == 0)
5234                 return 0;
5235
5236         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5237                 if (insn->code != (BPF_JMP | BPF_CALL) ||
5238                     insn->src_reg != BPF_PSEUDO_CALL)
5239                         continue;
5240                 subprog = find_subprog(env, i + insn->imm + 1);
5241                 if (subprog < 0) {
5242                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5243                                   i + insn->imm + 1);
5244                         return -EFAULT;
5245                 }
5246                 /* temporarily remember subprog id inside insn instead of
5247                  * aux_data, since next loop will split up all insns into funcs
5248                  */
5249                 insn->off = subprog + 1;
5250                 /* remember original imm in case JIT fails and fallback
5251                  * to interpreter will be needed
5252                  */
5253                 env->insn_aux_data[i].call_imm = insn->imm;
5254                 /* point imm to __bpf_call_base+1 from JITs point of view */
5255                 insn->imm = 1;
5256         }
5257
5258         func = kzalloc(sizeof(prog) * (env->subprog_cnt + 1), GFP_KERNEL);
5259         if (!func)
5260                 return -ENOMEM;
5261
5262         for (i = 0; i <= env->subprog_cnt; i++) {
5263                 subprog_start = subprog_end;
5264                 if (env->subprog_cnt == i)
5265                         subprog_end = prog->len;
5266                 else
5267                         subprog_end = env->subprog_starts[i];
5268
5269                 len = subprog_end - subprog_start;
5270                 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
5271                 if (!func[i])
5272                         goto out_free;
5273                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
5274                        len * sizeof(struct bpf_insn));
5275                 func[i]->type = prog->type;
5276                 func[i]->len = len;
5277                 if (bpf_prog_calc_tag(func[i]))
5278                         goto out_free;
5279                 func[i]->is_func = 1;
5280                 /* Use bpf_prog_F_tag to indicate functions in stack traces.
5281                  * Long term would need debug info to populate names
5282                  */
5283                 func[i]->aux->name[0] = 'F';
5284                 func[i]->aux->stack_depth = env->subprog_stack_depth[i];
5285                 func[i]->jit_requested = 1;
5286                 func[i] = bpf_int_jit_compile(func[i]);
5287                 if (!func[i]->jited) {
5288                         err = -ENOTSUPP;
5289                         goto out_free;
5290                 }
5291                 cond_resched();
5292         }
5293         /* at this point all bpf functions were successfully JITed
5294          * now populate all bpf_calls with correct addresses and
5295          * run last pass of JIT
5296          */
5297         for (i = 0; i <= env->subprog_cnt; i++) {
5298                 insn = func[i]->insnsi;
5299                 for (j = 0; j < func[i]->len; j++, insn++) {
5300                         if (insn->code != (BPF_JMP | BPF_CALL) ||
5301                             insn->src_reg != BPF_PSEUDO_CALL)
5302                                 continue;
5303                         subprog = insn->off;
5304                         insn->off = 0;
5305                         insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5306                                 func[subprog]->bpf_func -
5307                                 __bpf_call_base;
5308                 }
5309         }
5310         for (i = 0; i <= env->subprog_cnt; i++) {
5311                 old_bpf_func = func[i]->bpf_func;
5312                 tmp = bpf_int_jit_compile(func[i]);
5313                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
5314                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
5315                         err = -EFAULT;
5316                         goto out_free;
5317                 }
5318                 cond_resched();
5319         }
5320
5321         /* finally lock prog and jit images for all functions and
5322          * populate kallsysm
5323          */
5324         for (i = 0; i <= env->subprog_cnt; i++) {
5325                 bpf_prog_lock_ro(func[i]);
5326                 bpf_prog_kallsyms_add(func[i]);
5327         }
5328
5329         /* Last step: make now unused interpreter insns from main
5330          * prog consistent for later dump requests, so they can
5331          * later look the same as if they were interpreted only.
5332          */
5333         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5334                 unsigned long addr;
5335
5336                 if (insn->code != (BPF_JMP | BPF_CALL) ||
5337                     insn->src_reg != BPF_PSEUDO_CALL)
5338                         continue;
5339                 insn->off = env->insn_aux_data[i].call_imm;
5340                 subprog = find_subprog(env, i + insn->off + 1);
5341                 addr  = (unsigned long)func[subprog + 1]->bpf_func;
5342                 addr &= PAGE_MASK;
5343                 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
5344                             addr - __bpf_call_base;
5345         }
5346
5347         prog->jited = 1;
5348         prog->bpf_func = func[0]->bpf_func;
5349         prog->aux->func = func;
5350         prog->aux->func_cnt = env->subprog_cnt + 1;
5351         return 0;
5352 out_free:
5353         for (i = 0; i <= env->subprog_cnt; i++)
5354                 if (func[i])
5355                         bpf_jit_free(func[i]);
5356         kfree(func);
5357         /* cleanup main prog to be interpreted */
5358         prog->jit_requested = 0;
5359         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
5360                 if (insn->code != (BPF_JMP | BPF_CALL) ||
5361                     insn->src_reg != BPF_PSEUDO_CALL)
5362                         continue;
5363                 insn->off = 0;
5364                 insn->imm = env->insn_aux_data[i].call_imm;
5365         }
5366         return err;
5367 }
5368
5369 static int fixup_call_args(struct bpf_verifier_env *env)
5370 {
5371 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5372         struct bpf_prog *prog = env->prog;
5373         struct bpf_insn *insn = prog->insnsi;
5374         int i, depth;
5375 #endif
5376         int err;
5377
5378         err = 0;
5379         if (env->prog->jit_requested) {
5380                 err = jit_subprogs(env);
5381                 if (err == 0)
5382                         return 0;
5383         }
5384 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5385         for (i = 0; i < prog->len; i++, insn++) {
5386                 if (insn->code != (BPF_JMP | BPF_CALL) ||
5387                     insn->src_reg != BPF_PSEUDO_CALL)
5388                         continue;
5389                 depth = get_callee_stack_depth(env, insn, i);
5390                 if (depth < 0)
5391                         return depth;
5392                 bpf_patch_call_args(insn, depth);
5393         }
5394         err = 0;
5395 #endif
5396         return err;
5397 }
5398
5399 /* fixup insn->imm field of bpf_call instructions
5400  * and inline eligible helpers as explicit sequence of BPF instructions
5401  *
5402  * this function is called after eBPF program passed verification
5403  */
5404 static int fixup_bpf_calls(struct bpf_verifier_env *env)
5405 {
5406         struct bpf_prog *prog = env->prog;
5407         struct bpf_insn *insn = prog->insnsi;
5408         const struct bpf_func_proto *fn;
5409         const int insn_cnt = prog->len;
5410         struct bpf_insn insn_buf[16];
5411         struct bpf_prog *new_prog;
5412         struct bpf_map *map_ptr;
5413         int i, cnt, delta = 0;
5414
5415         for (i = 0; i < insn_cnt; i++, insn++) {
5416                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
5417                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5418                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
5419                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5420                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
5421                         struct bpf_insn mask_and_div[] = {
5422                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5423                                 /* Rx div 0 -> 0 */
5424                                 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
5425                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
5426                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
5427                                 *insn,
5428                         };
5429                         struct bpf_insn mask_and_mod[] = {
5430                                 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
5431                                 /* Rx mod 0 -> Rx */
5432                                 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
5433                                 *insn,
5434                         };
5435                         struct bpf_insn *patchlet;
5436
5437                         if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
5438                             insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
5439                                 patchlet = mask_and_div + (is64 ? 1 : 0);
5440                                 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
5441                         } else {
5442                                 patchlet = mask_and_mod + (is64 ? 1 : 0);
5443                                 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
5444                         }
5445
5446                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
5447                         if (!new_prog)
5448                                 return -ENOMEM;
5449
5450                         delta    += cnt - 1;
5451                         env->prog = prog = new_prog;
5452                         insn      = new_prog->insnsi + i + delta;
5453                         continue;
5454                 }
5455
5456                 if (insn->code != (BPF_JMP | BPF_CALL))
5457                         continue;
5458                 if (insn->src_reg == BPF_PSEUDO_CALL)
5459                         continue;
5460
5461                 if (insn->imm == BPF_FUNC_get_route_realm)
5462                         prog->dst_needed = 1;
5463                 if (insn->imm == BPF_FUNC_get_prandom_u32)
5464                         bpf_user_rnd_init_once();
5465                 if (insn->imm == BPF_FUNC_override_return)
5466                         prog->kprobe_override = 1;
5467                 if (insn->imm == BPF_FUNC_tail_call) {
5468                         /* If we tail call into other programs, we
5469                          * cannot make any assumptions since they can
5470                          * be replaced dynamically during runtime in
5471                          * the program array.
5472                          */
5473                         prog->cb_access = 1;
5474                         env->prog->aux->stack_depth = MAX_BPF_STACK;
5475
5476                         /* mark bpf_tail_call as different opcode to avoid
5477                          * conditional branch in the interpeter for every normal
5478                          * call and to prevent accidental JITing by JIT compiler
5479                          * that doesn't support bpf_tail_call yet
5480                          */
5481                         insn->imm = 0;
5482                         insn->code = BPF_JMP | BPF_TAIL_CALL;
5483
5484                         /* instead of changing every JIT dealing with tail_call
5485                          * emit two extra insns:
5486                          * if (index >= max_entries) goto out;
5487                          * index &= array->index_mask;
5488                          * to avoid out-of-bounds cpu speculation
5489                          */
5490                         map_ptr = env->insn_aux_data[i + delta].map_ptr;
5491                         if (map_ptr == BPF_MAP_PTR_POISON) {
5492                                 verbose(env, "tail_call abusing map_ptr\n");
5493                                 return -EINVAL;
5494                         }
5495                         if (!map_ptr->unpriv_array)
5496                                 continue;
5497                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
5498                                                   map_ptr->max_entries, 2);
5499                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
5500                                                     container_of(map_ptr,
5501                                                                  struct bpf_array,
5502                                                                  map)->index_mask);
5503                         insn_buf[2] = *insn;
5504                         cnt = 3;
5505                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
5506                         if (!new_prog)
5507                                 return -ENOMEM;
5508
5509                         delta    += cnt - 1;
5510                         env->prog = prog = new_prog;
5511                         insn      = new_prog->insnsi + i + delta;
5512                         continue;
5513                 }
5514
5515                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
5516                  * handlers are currently limited to 64 bit only.
5517                  */
5518                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
5519                     insn->imm == BPF_FUNC_map_lookup_elem) {
5520                         map_ptr = env->insn_aux_data[i + delta].map_ptr;
5521                         if (map_ptr == BPF_MAP_PTR_POISON ||
5522                             !map_ptr->ops->map_gen_lookup)
5523                                 goto patch_call_imm;
5524
5525                         cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5526                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5527                                 verbose(env, "bpf verifier is misconfigured\n");
5528                                 return -EINVAL;
5529                         }
5530
5531                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5532                                                        cnt);
5533                         if (!new_prog)
5534                                 return -ENOMEM;
5535
5536                         delta += cnt - 1;
5537
5538                         /* keep walking new program and skip insns we just inserted */
5539                         env->prog = prog = new_prog;
5540                         insn      = new_prog->insnsi + i + delta;
5541                         continue;
5542                 }
5543
5544                 if (insn->imm == BPF_FUNC_redirect_map) {
5545                         /* Note, we cannot use prog directly as imm as subsequent
5546                          * rewrites would still change the prog pointer. The only
5547                          * stable address we can use is aux, which also works with
5548                          * prog clones during blinding.
5549                          */
5550                         u64 addr = (unsigned long)prog->aux;
5551                         struct bpf_insn r4_ld[] = {
5552                                 BPF_LD_IMM64(BPF_REG_4, addr),
5553                                 *insn,
5554                         };
5555                         cnt = ARRAY_SIZE(r4_ld);
5556
5557                         new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5558                         if (!new_prog)
5559                                 return -ENOMEM;
5560
5561                         delta    += cnt - 1;
5562                         env->prog = prog = new_prog;
5563                         insn      = new_prog->insnsi + i + delta;
5564                 }
5565 patch_call_imm:
5566                 fn = env->ops->get_func_proto(insn->imm, env->prog);
5567                 /* all functions that have prototype and verifier allowed
5568                  * programs to call them, must be real in-kernel functions
5569                  */
5570                 if (!fn->func) {
5571                         verbose(env,
5572                                 "kernel subsystem misconfigured func %s#%d\n",
5573                                 func_id_name(insn->imm), insn->imm);
5574                         return -EFAULT;
5575                 }
5576                 insn->imm = fn->func - __bpf_call_base;
5577         }
5578
5579         return 0;
5580 }
5581
5582 static void free_states(struct bpf_verifier_env *env)
5583 {
5584         struct bpf_verifier_state_list *sl, *sln;
5585         int i;
5586
5587         if (!env->explored_states)
5588                 return;
5589
5590         for (i = 0; i < env->prog->len; i++) {
5591                 sl = env->explored_states[i];
5592
5593                 if (sl)
5594                         while (sl != STATE_LIST_MARK) {
5595                                 sln = sl->next;
5596                                 free_verifier_state(&sl->state, false);
5597                                 kfree(sl);
5598                                 sl = sln;
5599                         }
5600         }
5601
5602         kfree(env->explored_states);
5603 }
5604
5605 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5606 {
5607         struct bpf_verifier_env *env;
5608         struct bpf_verifier_log *log;
5609         int ret = -EINVAL;
5610
5611         /* no program is valid */
5612         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
5613                 return -EINVAL;
5614
5615         /* 'struct bpf_verifier_env' can be global, but since it's not small,
5616          * allocate/free it every time bpf_check() is called
5617          */
5618         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5619         if (!env)
5620                 return -ENOMEM;
5621         log = &env->log;
5622
5623         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5624                                      (*prog)->len);
5625         ret = -ENOMEM;
5626         if (!env->insn_aux_data)
5627                 goto err_free_env;
5628         env->prog = *prog;
5629         env->ops = bpf_verifier_ops[env->prog->type];
5630
5631         /* grab the mutex to protect few globals used by verifier */
5632         mutex_lock(&bpf_verifier_lock);
5633
5634         if (attr->log_level || attr->log_buf || attr->log_size) {
5635                 /* user requested verbose verifier output
5636                  * and supplied buffer to store the verification trace
5637                  */
5638                 log->level = attr->log_level;
5639                 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
5640                 log->len_total = attr->log_size;
5641
5642                 ret = -EINVAL;
5643                 /* log attributes have to be sane */
5644                 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
5645                     !log->level || !log->ubuf)
5646                         goto err_unlock;
5647         }
5648
5649         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5650         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5651                 env->strict_alignment = true;
5652
5653         if (bpf_prog_is_dev_bound(env->prog->aux)) {
5654                 ret = bpf_prog_offload_verifier_prep(env);
5655                 if (ret)
5656                         goto err_unlock;
5657         }
5658
5659         ret = replace_map_fd_with_map_ptr(env);
5660         if (ret < 0)
5661                 goto skip_full_check;
5662
5663         env->explored_states = kcalloc(env->prog->len,
5664                                        sizeof(struct bpf_verifier_state_list *),
5665                                        GFP_USER);
5666         ret = -ENOMEM;
5667         if (!env->explored_states)
5668                 goto skip_full_check;
5669
5670         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5671
5672         ret = check_cfg(env);
5673         if (ret < 0)
5674                 goto skip_full_check;
5675
5676         ret = do_check(env);
5677         if (env->cur_state) {
5678                 free_verifier_state(env->cur_state, true);
5679                 env->cur_state = NULL;
5680         }
5681
5682 skip_full_check:
5683         while (!pop_stack(env, NULL, NULL));
5684         free_states(env);
5685
5686         if (ret == 0)
5687                 sanitize_dead_code(env);
5688
5689         if (ret == 0)
5690                 ret = check_max_stack_depth(env);
5691
5692         if (ret == 0)
5693                 /* program is valid, convert *(u32*)(ctx + off) accesses */
5694                 ret = convert_ctx_accesses(env);
5695
5696         if (ret == 0)
5697                 ret = fixup_bpf_calls(env);
5698
5699         if (ret == 0)
5700                 ret = fixup_call_args(env);
5701
5702         if (log->level && bpf_verifier_log_full(log))
5703                 ret = -ENOSPC;
5704         if (log->level && !log->ubuf) {
5705                 ret = -EFAULT;
5706                 goto err_release_maps;
5707         }
5708
5709         if (ret == 0 && env->used_map_cnt) {
5710                 /* if program passed verifier, update used_maps in bpf_prog_info */
5711                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5712                                                           sizeof(env->used_maps[0]),
5713                                                           GFP_KERNEL);
5714
5715                 if (!env->prog->aux->used_maps) {
5716                         ret = -ENOMEM;
5717                         goto err_release_maps;
5718                 }
5719
5720                 memcpy(env->prog->aux->used_maps, env->used_maps,
5721                        sizeof(env->used_maps[0]) * env->used_map_cnt);
5722                 env->prog->aux->used_map_cnt = env->used_map_cnt;
5723
5724                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5725                  * bpf_ld_imm64 instructions
5726                  */
5727                 convert_pseudo_ld_imm64(env);
5728         }
5729
5730 err_release_maps:
5731         if (!env->prog->aux->used_maps)
5732                 /* if we didn't copy map pointers into bpf_prog_info, release
5733                  * them now. Otherwise free_bpf_prog_info() will release them.
5734                  */
5735                 release_maps(env);
5736         *prog = env->prog;
5737 err_unlock:
5738         mutex_unlock(&bpf_verifier_lock);
5739         vfree(env->insn_aux_data);
5740 err_free_env:
5741         kfree(env);
5742         return ret;
5743 }