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