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