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