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