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