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