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