GNU Linux-libre 4.14.324-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         __update_reg_bounds(dst_reg);
2743         __reg_deduce_bounds(dst_reg);
2744         __reg_bound_offset(dst_reg);
2745         return 0;
2746 }
2747
2748 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
2749  * and var_off.
2750  */
2751 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
2752                                    struct bpf_insn *insn)
2753 {
2754         struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg;
2755         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
2756         u8 opcode = BPF_OP(insn->code);
2757
2758         dst_reg = &regs[insn->dst_reg];
2759         src_reg = NULL;
2760         if (dst_reg->type != SCALAR_VALUE)
2761                 ptr_reg = dst_reg;
2762         if (BPF_SRC(insn->code) == BPF_X) {
2763                 src_reg = &regs[insn->src_reg];
2764                 if (src_reg->type != SCALAR_VALUE) {
2765                         if (dst_reg->type != SCALAR_VALUE) {
2766                                 /* Combining two pointers by any ALU op yields
2767                                  * an arbitrary scalar. Disallow all math except
2768                                  * pointer subtraction
2769                                  */
2770                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
2771                                         mark_reg_unknown(regs, insn->dst_reg);
2772                                         return 0;
2773                                 }
2774                                 verbose("R%d pointer %s pointer prohibited\n",
2775                                         insn->dst_reg,
2776                                         bpf_alu_string[opcode >> 4]);
2777                                 return -EACCES;
2778                         } else {
2779                                 /* scalar += pointer
2780                                  * This is legal, but we have to reverse our
2781                                  * src/dest handling in computing the range
2782                                  */
2783                                 return adjust_ptr_min_max_vals(env, insn,
2784                                                                src_reg, dst_reg);
2785                         }
2786                 } else if (ptr_reg) {
2787                         /* pointer += scalar */
2788                         return adjust_ptr_min_max_vals(env, insn,
2789                                                        dst_reg, src_reg);
2790                 }
2791         } else {
2792                 /* Pretend the src is a reg with a known value, since we only
2793                  * need to be able to read from this state.
2794                  */
2795                 off_reg.type = SCALAR_VALUE;
2796                 __mark_reg_known(&off_reg, insn->imm);
2797                 src_reg = &off_reg;
2798                 if (ptr_reg) /* pointer += K */
2799                         return adjust_ptr_min_max_vals(env, insn,
2800                                                        ptr_reg, src_reg);
2801         }
2802
2803         /* Got here implies adding two SCALAR_VALUEs */
2804         if (WARN_ON_ONCE(ptr_reg)) {
2805                 print_verifier_state(env->cur_state);
2806                 verbose("verifier internal error: unexpected ptr_reg\n");
2807                 return -EINVAL;
2808         }
2809         if (WARN_ON(!src_reg)) {
2810                 print_verifier_state(env->cur_state);
2811                 verbose("verifier internal error: no src_reg\n");
2812                 return -EINVAL;
2813         }
2814         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
2815 }
2816
2817 /* check validity of 32-bit and 64-bit arithmetic operations */
2818 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
2819 {
2820         struct bpf_reg_state *regs = cur_regs(env);
2821         u8 opcode = BPF_OP(insn->code);
2822         int err;
2823
2824         if (opcode == BPF_END || opcode == BPF_NEG) {
2825                 if (opcode == BPF_NEG) {
2826                         if (BPF_SRC(insn->code) != 0 ||
2827                             insn->src_reg != BPF_REG_0 ||
2828                             insn->off != 0 || insn->imm != 0) {
2829                                 verbose("BPF_NEG uses reserved fields\n");
2830                                 return -EINVAL;
2831                         }
2832                 } else {
2833                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
2834                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
2835                             BPF_CLASS(insn->code) == BPF_ALU64) {
2836                                 verbose("BPF_END uses reserved fields\n");
2837                                 return -EINVAL;
2838                         }
2839                 }
2840
2841                 /* check src operand */
2842                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2843                 if (err)
2844                         return err;
2845
2846                 if (is_pointer_value(env, insn->dst_reg)) {
2847                         verbose("R%d pointer arithmetic prohibited\n",
2848                                 insn->dst_reg);
2849                         return -EACCES;
2850                 }
2851
2852                 /* check dest operand */
2853                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
2854                 if (err)
2855                         return err;
2856
2857         } else if (opcode == BPF_MOV) {
2858
2859                 if (BPF_SRC(insn->code) == BPF_X) {
2860                         if (insn->imm != 0 || insn->off != 0) {
2861                                 verbose("BPF_MOV uses reserved fields\n");
2862                                 return -EINVAL;
2863                         }
2864
2865                         /* check src operand */
2866                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
2867                         if (err)
2868                                 return err;
2869                 } else {
2870                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2871                                 verbose("BPF_MOV uses reserved fields\n");
2872                                 return -EINVAL;
2873                         }
2874                 }
2875
2876                 /* check dest operand */
2877                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
2878                 if (err)
2879                         return err;
2880
2881                 if (BPF_SRC(insn->code) == BPF_X) {
2882                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
2883                                 /* case: R1 = R2
2884                                  * copy register state to dest reg
2885                                  */
2886                                 regs[insn->dst_reg] = regs[insn->src_reg];
2887                                 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
2888                         } else {
2889                                 /* R1 = (u32) R2 */
2890                                 if (is_pointer_value(env, insn->src_reg)) {
2891                                         verbose("R%d partial copy of pointer\n",
2892                                                 insn->src_reg);
2893                                         return -EACCES;
2894                                 }
2895                                 mark_reg_unknown(regs, insn->dst_reg);
2896                                 coerce_reg_to_size(&regs[insn->dst_reg], 4);
2897                         }
2898                 } else {
2899                         /* case: R = imm
2900                          * remember the value we stored into this reg
2901                          */
2902                         regs[insn->dst_reg].type = SCALAR_VALUE;
2903                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
2904                                 __mark_reg_known(regs + insn->dst_reg,
2905                                                  insn->imm);
2906                         } else {
2907                                 __mark_reg_known(regs + insn->dst_reg,
2908                                                  (u32)insn->imm);
2909                         }
2910                 }
2911
2912         } else if (opcode > BPF_END) {
2913                 verbose("invalid BPF_ALU opcode %x\n", opcode);
2914                 return -EINVAL;
2915
2916         } else {        /* all other ALU ops: and, sub, xor, add, ... */
2917
2918                 if (BPF_SRC(insn->code) == BPF_X) {
2919                         if (insn->imm != 0 || insn->off != 0) {
2920                                 verbose("BPF_ALU uses reserved fields\n");
2921                                 return -EINVAL;
2922                         }
2923                         /* check src1 operand */
2924                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
2925                         if (err)
2926                                 return err;
2927                 } else {
2928                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
2929                                 verbose("BPF_ALU uses reserved fields\n");
2930                                 return -EINVAL;
2931                         }
2932                 }
2933
2934                 /* check src2 operand */
2935                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
2936                 if (err)
2937                         return err;
2938
2939                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
2940                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
2941                         verbose("div by zero\n");
2942                         return -EINVAL;
2943                 }
2944
2945                 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
2946                         verbose("BPF_ARSH not supported for 32 bit ALU\n");
2947                         return -EINVAL;
2948                 }
2949
2950                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
2951                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
2952                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
2953
2954                         if (insn->imm < 0 || insn->imm >= size) {
2955                                 verbose("invalid shift %d\n", insn->imm);
2956                                 return -EINVAL;
2957                         }
2958                 }
2959
2960                 /* check dest operand */
2961                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
2962                 if (err)
2963                         return err;
2964
2965                 return adjust_reg_min_max_vals(env, insn);
2966         }
2967
2968         return 0;
2969 }
2970
2971 static void find_good_pkt_pointers(struct bpf_verifier_state *state,
2972                                    struct bpf_reg_state *dst_reg,
2973                                    bool range_right_open)
2974 {
2975         struct bpf_reg_state *regs = state->regs, *reg;
2976         u16 new_range;
2977         int i;
2978
2979         if (dst_reg->off < 0 ||
2980             (dst_reg->off == 0 && range_right_open))
2981                 /* This doesn't give us any range */
2982                 return;
2983
2984         if (dst_reg->umax_value > MAX_PACKET_OFF ||
2985             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
2986                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
2987                  * than pkt_end, but that's because it's also less than pkt.
2988                  */
2989                 return;
2990
2991         new_range = dst_reg->off;
2992         if (range_right_open)
2993                 new_range++;
2994
2995         /* Examples for register markings:
2996          *
2997          * pkt_data in dst register:
2998          *
2999          *   r2 = r3;
3000          *   r2 += 8;
3001          *   if (r2 > pkt_end) goto <handle exception>
3002          *   <access okay>
3003          *
3004          *   r2 = r3;
3005          *   r2 += 8;
3006          *   if (r2 < pkt_end) goto <access okay>
3007          *   <handle exception>
3008          *
3009          *   Where:
3010          *     r2 == dst_reg, pkt_end == src_reg
3011          *     r2=pkt(id=n,off=8,r=0)
3012          *     r3=pkt(id=n,off=0,r=0)
3013          *
3014          * pkt_data in src register:
3015          *
3016          *   r2 = r3;
3017          *   r2 += 8;
3018          *   if (pkt_end >= r2) goto <access okay>
3019          *   <handle exception>
3020          *
3021          *   r2 = r3;
3022          *   r2 += 8;
3023          *   if (pkt_end <= r2) goto <handle exception>
3024          *   <access okay>
3025          *
3026          *   Where:
3027          *     pkt_end == dst_reg, r2 == src_reg
3028          *     r2=pkt(id=n,off=8,r=0)
3029          *     r3=pkt(id=n,off=0,r=0)
3030          *
3031          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3032          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3033          * and [r3, r3 + 8-1) respectively is safe to access depending on
3034          * the check.
3035          */
3036
3037         /* If our ids match, then we must have the same max_value.  And we
3038          * don't care about the other reg's fixed offset, since if it's too big
3039          * the range won't allow anything.
3040          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3041          */
3042         for (i = 0; i < MAX_BPF_REG; i++)
3043                 if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id)
3044                         /* keep the maximum range already checked */
3045                         regs[i].range = max(regs[i].range, new_range);
3046
3047         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3048                 if (state->stack[i].slot_type[0] != STACK_SPILL)
3049                         continue;
3050                 reg = &state->stack[i].spilled_ptr;
3051                 if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id)
3052                         reg->range = max(reg->range, new_range);
3053         }
3054 }
3055
3056 /* Adjusts the register min/max values in the case that the dst_reg is the
3057  * variable register that we are working on, and src_reg is a constant or we're
3058  * simply doing a BPF_K check.
3059  * In JEQ/JNE cases we also adjust the var_off values.
3060  */
3061 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3062                             struct bpf_reg_state *false_reg, u64 val,
3063                             u8 opcode)
3064 {
3065         /* If the dst_reg is a pointer, we can't learn anything about its
3066          * variable offset from the compare (unless src_reg were a pointer into
3067          * the same object, but we don't bother with that.
3068          * Since false_reg and true_reg have the same type by construction, we
3069          * only need to check one of them for pointerness.
3070          */
3071         if (__is_pointer_value(false, false_reg))
3072                 return;
3073
3074         switch (opcode) {
3075         case BPF_JEQ:
3076                 /* If this is false then we know nothing Jon Snow, but if it is
3077                  * true then we know for sure.
3078                  */
3079                 __mark_reg_known(true_reg, val);
3080                 break;
3081         case BPF_JNE:
3082                 /* If this is true we know nothing Jon Snow, but if it is false
3083                  * we know the value for sure;
3084                  */
3085                 __mark_reg_known(false_reg, val);
3086                 break;
3087         case BPF_JGT:
3088                 false_reg->umax_value = min(false_reg->umax_value, val);
3089                 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3090                 break;
3091         case BPF_JSGT:
3092                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3093                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3094                 break;
3095         case BPF_JLT:
3096                 false_reg->umin_value = max(false_reg->umin_value, val);
3097                 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3098                 break;
3099         case BPF_JSLT:
3100                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3101                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3102                 break;
3103         case BPF_JGE:
3104                 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3105                 true_reg->umin_value = max(true_reg->umin_value, val);
3106                 break;
3107         case BPF_JSGE:
3108                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3109                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3110                 break;
3111         case BPF_JLE:
3112                 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3113                 true_reg->umax_value = min(true_reg->umax_value, val);
3114                 break;
3115         case BPF_JSLE:
3116                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3117                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3118                 break;
3119         default:
3120                 break;
3121         }
3122
3123         __reg_deduce_bounds(false_reg);
3124         __reg_deduce_bounds(true_reg);
3125         /* We might have learned some bits from the bounds. */
3126         __reg_bound_offset(false_reg);
3127         __reg_bound_offset(true_reg);
3128         /* Intersecting with the old var_off might have improved our bounds
3129          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3130          * then new var_off is (0; 0x7f...fc) which improves our umax.
3131          */
3132         __update_reg_bounds(false_reg);
3133         __update_reg_bounds(true_reg);
3134 }
3135
3136 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
3137  * the variable reg.
3138  */
3139 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3140                                 struct bpf_reg_state *false_reg, u64 val,
3141                                 u8 opcode)
3142 {
3143         if (__is_pointer_value(false, false_reg))
3144                 return;
3145
3146         switch (opcode) {
3147         case BPF_JEQ:
3148                 /* If this is false then we know nothing Jon Snow, but if it is
3149                  * true then we know for sure.
3150                  */
3151                 __mark_reg_known(true_reg, val);
3152                 break;
3153         case BPF_JNE:
3154                 /* If this is true we know nothing Jon Snow, but if it is false
3155                  * we know the value for sure;
3156                  */
3157                 __mark_reg_known(false_reg, val);
3158                 break;
3159         case BPF_JGT:
3160                 true_reg->umax_value = min(true_reg->umax_value, val - 1);
3161                 false_reg->umin_value = max(false_reg->umin_value, val);
3162                 break;
3163         case BPF_JSGT:
3164                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1);
3165                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val);
3166                 break;
3167         case BPF_JLT:
3168                 true_reg->umin_value = max(true_reg->umin_value, val + 1);
3169                 false_reg->umax_value = min(false_reg->umax_value, val);
3170                 break;
3171         case BPF_JSLT:
3172                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1);
3173                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val);
3174                 break;
3175         case BPF_JGE:
3176                 true_reg->umax_value = min(true_reg->umax_value, val);
3177                 false_reg->umin_value = max(false_reg->umin_value, val + 1);
3178                 break;
3179         case BPF_JSGE:
3180                 true_reg->smax_value = min_t(s64, true_reg->smax_value, val);
3181                 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1);
3182                 break;
3183         case BPF_JLE:
3184                 true_reg->umin_value = max(true_reg->umin_value, val);
3185                 false_reg->umax_value = min(false_reg->umax_value, val - 1);
3186                 break;
3187         case BPF_JSLE:
3188                 true_reg->smin_value = max_t(s64, true_reg->smin_value, val);
3189                 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1);
3190                 break;
3191         default:
3192                 break;
3193         }
3194
3195         __reg_deduce_bounds(false_reg);
3196         __reg_deduce_bounds(true_reg);
3197         /* We might have learned some bits from the bounds. */
3198         __reg_bound_offset(false_reg);
3199         __reg_bound_offset(true_reg);
3200         /* Intersecting with the old var_off might have improved our bounds
3201          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3202          * then new var_off is (0; 0x7f...fc) which improves our umax.
3203          */
3204         __update_reg_bounds(false_reg);
3205         __update_reg_bounds(true_reg);
3206 }
3207
3208 /* Regs are known to be equal, so intersect their min/max/var_off */
3209 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
3210                                   struct bpf_reg_state *dst_reg)
3211 {
3212         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
3213                                                         dst_reg->umin_value);
3214         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
3215                                                         dst_reg->umax_value);
3216         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
3217                                                         dst_reg->smin_value);
3218         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
3219                                                         dst_reg->smax_value);
3220         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
3221                                                              dst_reg->var_off);
3222         /* We might have learned new bounds from the var_off. */
3223         __update_reg_bounds(src_reg);
3224         __update_reg_bounds(dst_reg);
3225         /* We might have learned something about the sign bit. */
3226         __reg_deduce_bounds(src_reg);
3227         __reg_deduce_bounds(dst_reg);
3228         /* We might have learned some bits from the bounds. */
3229         __reg_bound_offset(src_reg);
3230         __reg_bound_offset(dst_reg);
3231         /* Intersecting with the old var_off might have improved our bounds
3232          * slightly.  e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
3233          * then new var_off is (0; 0x7f...fc) which improves our umax.
3234          */
3235         __update_reg_bounds(src_reg);
3236         __update_reg_bounds(dst_reg);
3237 }
3238
3239 static void reg_combine_min_max(struct bpf_reg_state *true_src,
3240                                 struct bpf_reg_state *true_dst,
3241                                 struct bpf_reg_state *false_src,
3242                                 struct bpf_reg_state *false_dst,
3243                                 u8 opcode)
3244 {
3245         switch (opcode) {
3246         case BPF_JEQ:
3247                 __reg_combine_min_max(true_src, true_dst);
3248                 break;
3249         case BPF_JNE:
3250                 __reg_combine_min_max(false_src, false_dst);
3251                 break;
3252         }
3253 }
3254
3255 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
3256                          bool is_null)
3257 {
3258         struct bpf_reg_state *reg = &regs[regno];
3259
3260         if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
3261                 /* Old offset (both fixed and variable parts) should
3262                  * have been known-zero, because we don't allow pointer
3263                  * arithmetic on pointers that might be NULL.
3264                  */
3265                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
3266                                  !tnum_equals_const(reg->var_off, 0) ||
3267                                  reg->off)) {
3268                         __mark_reg_known_zero(reg);
3269                         reg->off = 0;
3270                 }
3271                 if (is_null) {
3272                         reg->type = SCALAR_VALUE;
3273                 } else if (reg->map_ptr->inner_map_meta) {
3274                         reg->type = CONST_PTR_TO_MAP;
3275                         reg->map_ptr = reg->map_ptr->inner_map_meta;
3276                 } else {
3277                         reg->type = PTR_TO_MAP_VALUE;
3278                 }
3279                 /* We don't need id from this point onwards anymore, thus we
3280                  * should better reset it, so that state pruning has chances
3281                  * to take effect.
3282                  */
3283                 reg->id = 0;
3284         }
3285 }
3286
3287 /* The logic is similar to find_good_pkt_pointers(), both could eventually
3288  * be folded together at some point.
3289  */
3290 static void mark_map_regs(struct bpf_verifier_state *state, u32 regno,
3291                           bool is_null)
3292 {
3293         struct bpf_reg_state *regs = state->regs;
3294         u32 id = regs[regno].id;
3295         int i;
3296
3297         for (i = 0; i < MAX_BPF_REG; i++)
3298                 mark_map_reg(regs, i, id, is_null);
3299
3300         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3301                 if (state->stack[i].slot_type[0] != STACK_SPILL)
3302                         continue;
3303                 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
3304         }
3305 }
3306
3307 static int check_cond_jmp_op(struct bpf_verifier_env *env,
3308                              struct bpf_insn *insn, int *insn_idx)
3309 {
3310         struct bpf_verifier_state *other_branch, *this_branch = env->cur_state;
3311         struct bpf_reg_state *regs = this_branch->regs, *dst_reg;
3312         u8 opcode = BPF_OP(insn->code);
3313         int err;
3314
3315         if (opcode > BPF_JSLE) {
3316                 verbose("invalid BPF_JMP opcode %x\n", opcode);
3317                 return -EINVAL;
3318         }
3319
3320         if (BPF_SRC(insn->code) == BPF_X) {
3321                 if (insn->imm != 0) {
3322                         verbose("BPF_JMP uses reserved fields\n");
3323                         return -EINVAL;
3324                 }
3325
3326                 /* check src1 operand */
3327                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3328                 if (err)
3329                         return err;
3330
3331                 if (is_pointer_value(env, insn->src_reg)) {
3332                         verbose("R%d pointer comparison prohibited\n",
3333                                 insn->src_reg);
3334                         return -EACCES;
3335                 }
3336         } else {
3337                 if (insn->src_reg != BPF_REG_0) {
3338                         verbose("BPF_JMP uses reserved fields\n");
3339                         return -EINVAL;
3340                 }
3341         }
3342
3343         /* check src2 operand */
3344         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3345         if (err)
3346                 return err;
3347
3348         dst_reg = &regs[insn->dst_reg];
3349
3350         /* detect if R == 0 where R was initialized to zero earlier */
3351         if (BPF_SRC(insn->code) == BPF_K &&
3352             (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3353             dst_reg->type == SCALAR_VALUE &&
3354             tnum_equals_const(dst_reg->var_off, insn->imm)) {
3355                 if (opcode == BPF_JEQ) {
3356                         /* if (imm == imm) goto pc+off;
3357                          * only follow the goto, ignore fall-through
3358                          */
3359                         *insn_idx += insn->off;
3360                         return 0;
3361                 } else {
3362                         /* if (imm != imm) goto pc+off;
3363                          * only follow fall-through branch, since
3364                          * that's where the program will go
3365                          */
3366                         return 0;
3367                 }
3368         }
3369
3370         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
3371                                   false);
3372         if (!other_branch)
3373                 return -EFAULT;
3374
3375         /* detect if we are comparing against a constant value so we can adjust
3376          * our min/max values for our dst register.
3377          * this is only legit if both are scalars (or pointers to the same
3378          * object, I suppose, but we don't support that right now), because
3379          * otherwise the different base pointers mean the offsets aren't
3380          * comparable.
3381          */
3382         if (BPF_SRC(insn->code) == BPF_X) {
3383                 if (dst_reg->type == SCALAR_VALUE &&
3384                     regs[insn->src_reg].type == SCALAR_VALUE) {
3385                         if (tnum_is_const(regs[insn->src_reg].var_off))
3386                                 reg_set_min_max(&other_branch->regs[insn->dst_reg],
3387                                                 dst_reg, regs[insn->src_reg].var_off.value,
3388                                                 opcode);
3389                         else if (tnum_is_const(dst_reg->var_off))
3390                                 reg_set_min_max_inv(&other_branch->regs[insn->src_reg],
3391                                                     &regs[insn->src_reg],
3392                                                     dst_reg->var_off.value, opcode);
3393                         else if (opcode == BPF_JEQ || opcode == BPF_JNE)
3394                                 /* Comparing for equality, we can combine knowledge */
3395                                 reg_combine_min_max(&other_branch->regs[insn->src_reg],
3396                                                     &other_branch->regs[insn->dst_reg],
3397                                                     &regs[insn->src_reg],
3398                                                     &regs[insn->dst_reg], opcode);
3399                 }
3400         } else if (dst_reg->type == SCALAR_VALUE) {
3401                 reg_set_min_max(&other_branch->regs[insn->dst_reg],
3402                                         dst_reg, insn->imm, opcode);
3403         }
3404
3405         /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */
3406         if (BPF_SRC(insn->code) == BPF_K &&
3407             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
3408             dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3409                 /* Mark all identical map registers in each branch as either
3410                  * safe or unknown depending R == 0 or R != 0 conditional.
3411                  */
3412                 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
3413                 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
3414         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3415                    dst_reg->type == PTR_TO_PACKET &&
3416                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3417                 /* pkt_data' > pkt_end */
3418                 find_good_pkt_pointers(this_branch, dst_reg, false);
3419         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT &&
3420                    dst_reg->type == PTR_TO_PACKET_END &&
3421                    regs[insn->src_reg].type == PTR_TO_PACKET) {
3422                 /* pkt_end > pkt_data' */
3423                 find_good_pkt_pointers(other_branch, &regs[insn->src_reg], true);
3424         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3425                    dst_reg->type == PTR_TO_PACKET &&
3426                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3427                 /* pkt_data' < pkt_end */
3428                 find_good_pkt_pointers(other_branch, dst_reg, true);
3429         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLT &&
3430                    dst_reg->type == PTR_TO_PACKET_END &&
3431                    regs[insn->src_reg].type == PTR_TO_PACKET) {
3432                 /* pkt_end < pkt_data' */
3433                 find_good_pkt_pointers(this_branch, &regs[insn->src_reg], false);
3434         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3435                    dst_reg->type == PTR_TO_PACKET &&
3436                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3437                 /* pkt_data' >= pkt_end */
3438                 find_good_pkt_pointers(this_branch, dst_reg, true);
3439         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE &&
3440                    dst_reg->type == PTR_TO_PACKET_END &&
3441                    regs[insn->src_reg].type == PTR_TO_PACKET) {
3442                 /* pkt_end >= pkt_data' */
3443                 find_good_pkt_pointers(other_branch, &regs[insn->src_reg], false);
3444         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3445                    dst_reg->type == PTR_TO_PACKET &&
3446                    regs[insn->src_reg].type == PTR_TO_PACKET_END) {
3447                 /* pkt_data' <= pkt_end */
3448                 find_good_pkt_pointers(other_branch, dst_reg, false);
3449         } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JLE &&
3450                    dst_reg->type == PTR_TO_PACKET_END &&
3451                    regs[insn->src_reg].type == PTR_TO_PACKET) {
3452                 /* pkt_end <= pkt_data' */
3453                 find_good_pkt_pointers(this_branch, &regs[insn->src_reg], true);
3454         } else if (is_pointer_value(env, insn->dst_reg)) {
3455                 verbose("R%d pointer comparison prohibited\n", insn->dst_reg);
3456                 return -EACCES;
3457         }
3458         if (log_level)
3459                 print_verifier_state(this_branch);
3460         return 0;
3461 }
3462
3463 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
3464 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
3465 {
3466         u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
3467
3468         return (struct bpf_map *) (unsigned long) imm64;
3469 }
3470
3471 /* verify BPF_LD_IMM64 instruction */
3472 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
3473 {
3474         struct bpf_reg_state *regs = cur_regs(env);
3475         int err;
3476
3477         if (BPF_SIZE(insn->code) != BPF_DW) {
3478                 verbose("invalid BPF_LD_IMM insn\n");
3479                 return -EINVAL;
3480         }
3481         if (insn->off != 0) {
3482                 verbose("BPF_LD_IMM64 uses reserved fields\n");
3483                 return -EINVAL;
3484         }
3485
3486         err = check_reg_arg(env, insn->dst_reg, DST_OP);
3487         if (err)
3488                 return err;
3489
3490         if (insn->src_reg == 0) {
3491                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
3492
3493                 regs[insn->dst_reg].type = SCALAR_VALUE;
3494                 __mark_reg_known(&regs[insn->dst_reg], imm);
3495                 return 0;
3496         }
3497
3498         /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
3499         BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
3500
3501         regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
3502         regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
3503         return 0;
3504 }
3505
3506 static bool may_access_skb(enum bpf_prog_type type)
3507 {
3508         switch (type) {
3509         case BPF_PROG_TYPE_SOCKET_FILTER:
3510         case BPF_PROG_TYPE_SCHED_CLS:
3511         case BPF_PROG_TYPE_SCHED_ACT:
3512                 return true;
3513         default:
3514                 return false;
3515         }
3516 }
3517
3518 /* verify safety of LD_ABS|LD_IND instructions:
3519  * - they can only appear in the programs where ctx == skb
3520  * - since they are wrappers of function calls, they scratch R1-R5 registers,
3521  *   preserve R6-R9, and store return value into R0
3522  *
3523  * Implicit input:
3524  *   ctx == skb == R6 == CTX
3525  *
3526  * Explicit input:
3527  *   SRC == any register
3528  *   IMM == 32-bit immediate
3529  *
3530  * Output:
3531  *   R0 - 8/16/32-bit skb data converted to cpu endianness
3532  */
3533 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
3534 {
3535         struct bpf_reg_state *regs = cur_regs(env);
3536         static const int ctx_reg = BPF_REG_6;
3537         u8 mode = BPF_MODE(insn->code);
3538         int i, err;
3539
3540         if (!may_access_skb(env->prog->type)) {
3541                 verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
3542                 return -EINVAL;
3543         }
3544
3545         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
3546             BPF_SIZE(insn->code) == BPF_DW ||
3547             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
3548                 verbose("BPF_LD_[ABS|IND] uses reserved fields\n");
3549                 return -EINVAL;
3550         }
3551
3552         /* check whether implicit source operand (register R6) is readable */
3553         err = check_reg_arg(env, ctx_reg, SRC_OP);
3554         if (err)
3555                 return err;
3556
3557         if (regs[ctx_reg].type != PTR_TO_CTX) {
3558                 verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
3559                 return -EINVAL;
3560         }
3561
3562         if (mode == BPF_IND) {
3563                 /* check explicit source operand */
3564                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3565                 if (err)
3566                         return err;
3567         }
3568
3569         err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
3570         if (err < 0)
3571                 return err;
3572
3573         /* reset caller saved regs to unreadable */
3574         for (i = 0; i < CALLER_SAVED_REGS; i++) {
3575                 mark_reg_not_init(regs, caller_saved[i]);
3576                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
3577         }
3578
3579         /* mark destination R0 register as readable, since it contains
3580          * the value fetched from the packet.
3581          * Already marked as written above.
3582          */
3583         mark_reg_unknown(regs, BPF_REG_0);
3584         return 0;
3585 }
3586
3587 /* non-recursive DFS pseudo code
3588  * 1  procedure DFS-iterative(G,v):
3589  * 2      label v as discovered
3590  * 3      let S be a stack
3591  * 4      S.push(v)
3592  * 5      while S is not empty
3593  * 6            t <- S.pop()
3594  * 7            if t is what we're looking for:
3595  * 8                return t
3596  * 9            for all edges e in G.adjacentEdges(t) do
3597  * 10               if edge e is already labelled
3598  * 11                   continue with the next edge
3599  * 12               w <- G.adjacentVertex(t,e)
3600  * 13               if vertex w is not discovered and not explored
3601  * 14                   label e as tree-edge
3602  * 15                   label w as discovered
3603  * 16                   S.push(w)
3604  * 17                   continue at 5
3605  * 18               else if vertex w is discovered
3606  * 19                   label e as back-edge
3607  * 20               else
3608  * 21                   // vertex w is explored
3609  * 22                   label e as forward- or cross-edge
3610  * 23           label t as explored
3611  * 24           S.pop()
3612  *
3613  * convention:
3614  * 0x10 - discovered
3615  * 0x11 - discovered and fall-through edge labelled
3616  * 0x12 - discovered and fall-through and branch edges labelled
3617  * 0x20 - explored
3618  */
3619
3620 enum {
3621         DISCOVERED = 0x10,
3622         EXPLORED = 0x20,
3623         FALLTHROUGH = 1,
3624         BRANCH = 2,
3625 };
3626
3627 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
3628
3629 static int *insn_stack; /* stack of insns to process */
3630 static int cur_stack;   /* current stack index */
3631 static int *insn_state;
3632
3633 /* t, w, e - match pseudo-code above:
3634  * t - index of current instruction
3635  * w - next instruction
3636  * e - edge
3637  */
3638 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
3639 {
3640         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
3641                 return 0;
3642
3643         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
3644                 return 0;
3645
3646         if (w < 0 || w >= env->prog->len) {
3647                 verbose("jump out of range from insn %d to %d\n", t, w);
3648                 return -EINVAL;
3649         }
3650
3651         if (e == BRANCH)
3652                 /* mark branch target for state pruning */
3653                 env->explored_states[w] = STATE_LIST_MARK;
3654
3655         if (insn_state[w] == 0) {
3656                 /* tree-edge */
3657                 insn_state[t] = DISCOVERED | e;
3658                 insn_state[w] = DISCOVERED;
3659                 if (cur_stack >= env->prog->len)
3660                         return -E2BIG;
3661                 insn_stack[cur_stack++] = w;
3662                 return 1;
3663         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
3664                 verbose("back-edge from insn %d to %d\n", t, w);
3665                 return -EINVAL;
3666         } else if (insn_state[w] == EXPLORED) {
3667                 /* forward- or cross-edge */
3668                 insn_state[t] = DISCOVERED | e;
3669         } else {
3670                 verbose("insn state internal bug\n");
3671                 return -EFAULT;
3672         }
3673         return 0;
3674 }
3675
3676 /* non-recursive depth-first-search to detect loops in BPF program
3677  * loop == back-edge in directed graph
3678  */
3679 static int check_cfg(struct bpf_verifier_env *env)
3680 {
3681         struct bpf_insn *insns = env->prog->insnsi;
3682         int insn_cnt = env->prog->len;
3683         int ret = 0;
3684         int i, t;
3685
3686         insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3687         if (!insn_state)
3688                 return -ENOMEM;
3689
3690         insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
3691         if (!insn_stack) {
3692                 kfree(insn_state);
3693                 return -ENOMEM;
3694         }
3695
3696         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
3697         insn_stack[0] = 0; /* 0 is the first instruction */
3698         cur_stack = 1;
3699
3700 peek_stack:
3701         if (cur_stack == 0)
3702                 goto check_state;
3703         t = insn_stack[cur_stack - 1];
3704
3705         if (BPF_CLASS(insns[t].code) == BPF_JMP) {
3706                 u8 opcode = BPF_OP(insns[t].code);
3707
3708                 if (opcode == BPF_EXIT) {
3709                         goto mark_explored;
3710                 } else if (opcode == BPF_CALL) {
3711                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
3712                         if (ret == 1)
3713                                 goto peek_stack;
3714                         else if (ret < 0)
3715                                 goto err_free;
3716                         if (t + 1 < insn_cnt)
3717                                 env->explored_states[t + 1] = STATE_LIST_MARK;
3718                 } else if (opcode == BPF_JA) {
3719                         if (BPF_SRC(insns[t].code) != BPF_K) {
3720                                 ret = -EINVAL;
3721                                 goto err_free;
3722                         }
3723                         /* unconditional jump with single edge */
3724                         ret = push_insn(t, t + insns[t].off + 1,
3725                                         FALLTHROUGH, env);
3726                         if (ret == 1)
3727                                 goto peek_stack;
3728                         else if (ret < 0)
3729                                 goto err_free;
3730                         /* tell verifier to check for equivalent states
3731                          * after every call and jump
3732                          */
3733                         if (t + 1 < insn_cnt)
3734                                 env->explored_states[t + 1] = STATE_LIST_MARK;
3735                 } else {
3736                         /* conditional jump with two edges */
3737                         env->explored_states[t] = STATE_LIST_MARK;
3738                         ret = push_insn(t, t + 1, FALLTHROUGH, env);
3739                         if (ret == 1)
3740                                 goto peek_stack;
3741                         else if (ret < 0)
3742                                 goto err_free;
3743
3744                         ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
3745                         if (ret == 1)
3746                                 goto peek_stack;
3747                         else if (ret < 0)
3748                                 goto err_free;
3749                 }
3750         } else {
3751                 /* all other non-branch instructions with single
3752                  * fall-through edge
3753                  */
3754                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
3755                 if (ret == 1)
3756                         goto peek_stack;
3757                 else if (ret < 0)
3758                         goto err_free;
3759         }
3760
3761 mark_explored:
3762         insn_state[t] = EXPLORED;
3763         if (cur_stack-- <= 0) {
3764                 verbose("pop stack internal bug\n");
3765                 ret = -EFAULT;
3766                 goto err_free;
3767         }
3768         goto peek_stack;
3769
3770 check_state:
3771         for (i = 0; i < insn_cnt; i++) {
3772                 if (insn_state[i] != EXPLORED) {
3773                         verbose("unreachable insn %d\n", i);
3774                         ret = -EINVAL;
3775                         goto err_free;
3776                 }
3777         }
3778         ret = 0; /* cfg looks good */
3779
3780 err_free:
3781         kfree(insn_state);
3782         kfree(insn_stack);
3783         return ret;
3784 }
3785
3786 /* check %cur's range satisfies %old's */
3787 static bool range_within(struct bpf_reg_state *old,
3788                          struct bpf_reg_state *cur)
3789 {
3790         return old->umin_value <= cur->umin_value &&
3791                old->umax_value >= cur->umax_value &&
3792                old->smin_value <= cur->smin_value &&
3793                old->smax_value >= cur->smax_value;
3794 }
3795
3796 /* Maximum number of register states that can exist at once */
3797 #define ID_MAP_SIZE     (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
3798 struct idpair {
3799         u32 old;
3800         u32 cur;
3801 };
3802
3803 /* If in the old state two registers had the same id, then they need to have
3804  * the same id in the new state as well.  But that id could be different from
3805  * the old state, so we need to track the mapping from old to new ids.
3806  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
3807  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
3808  * regs with a different old id could still have new id 9, we don't care about
3809  * that.
3810  * So we look through our idmap to see if this old id has been seen before.  If
3811  * so, we require the new id to match; otherwise, we add the id pair to the map.
3812  */
3813 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
3814 {
3815         unsigned int i;
3816
3817         for (i = 0; i < ID_MAP_SIZE; i++) {
3818                 if (!idmap[i].old) {
3819                         /* Reached an empty slot; haven't seen this id before */
3820                         idmap[i].old = old_id;
3821                         idmap[i].cur = cur_id;
3822                         return true;
3823                 }
3824                 if (idmap[i].old == old_id)
3825                         return idmap[i].cur == cur_id;
3826         }
3827         /* We ran out of idmap slots, which should be impossible */
3828         WARN_ON_ONCE(1);
3829         return false;
3830 }
3831
3832 /* Returns true if (rold safe implies rcur safe) */
3833 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
3834                     struct idpair *idmap)
3835 {
3836         if (!(rold->live & REG_LIVE_READ))
3837                 /* explored state didn't use this */
3838                 return true;
3839
3840         if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0)
3841                 return true;
3842
3843         if (rold->type == NOT_INIT)
3844                 /* explored state can't have used this */
3845                 return true;
3846         if (rcur->type == NOT_INIT)
3847                 return false;
3848         switch (rold->type) {
3849         case SCALAR_VALUE:
3850                 if (rcur->type == SCALAR_VALUE) {
3851                         /* new val must satisfy old val knowledge */
3852                         return range_within(rold, rcur) &&
3853                                tnum_in(rold->var_off, rcur->var_off);
3854                 } else {
3855                         /* We're trying to use a pointer in place of a scalar.
3856                          * Even if the scalar was unbounded, this could lead to
3857                          * pointer leaks because scalars are allowed to leak
3858                          * while pointers are not. We could make this safe in
3859                          * special cases if root is calling us, but it's
3860                          * probably not worth the hassle.
3861                          */
3862                         return false;
3863                 }
3864         case PTR_TO_MAP_VALUE:
3865                 /* If the new min/max/var_off satisfy the old ones and
3866                  * everything else matches, we are OK.
3867                  * We don't care about the 'id' value, because nothing
3868                  * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
3869                  */
3870                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
3871                        range_within(rold, rcur) &&
3872                        tnum_in(rold->var_off, rcur->var_off);
3873         case PTR_TO_MAP_VALUE_OR_NULL:
3874                 /* a PTR_TO_MAP_VALUE could be safe to use as a
3875                  * PTR_TO_MAP_VALUE_OR_NULL into the same map.
3876                  * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
3877                  * checked, doing so could have affected others with the same
3878                  * id, and we can't check for that because we lost the id when
3879                  * we converted to a PTR_TO_MAP_VALUE.
3880                  */
3881                 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
3882                         return false;
3883                 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
3884                         return false;
3885                 /* Check our ids match any regs they're supposed to */
3886                 return check_ids(rold->id, rcur->id, idmap);
3887         case PTR_TO_PACKET:
3888                 if (rcur->type != PTR_TO_PACKET)
3889                         return false;
3890                 /* We must have at least as much range as the old ptr
3891                  * did, so that any accesses which were safe before are
3892                  * still safe.  This is true even if old range < old off,
3893                  * since someone could have accessed through (ptr - k), or
3894                  * even done ptr -= k in a register, to get a safe access.
3895                  */
3896                 if (rold->range > rcur->range)
3897                         return false;
3898                 /* If the offsets don't match, we can't trust our alignment;
3899                  * nor can we be sure that we won't fall out of range.
3900                  */
3901                 if (rold->off != rcur->off)
3902                         return false;
3903                 /* id relations must be preserved */
3904                 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
3905                         return false;
3906                 /* new val must satisfy old val knowledge */
3907                 return range_within(rold, rcur) &&
3908                        tnum_in(rold->var_off, rcur->var_off);
3909         case PTR_TO_CTX:
3910         case CONST_PTR_TO_MAP:
3911         case PTR_TO_STACK:
3912         case PTR_TO_PACKET_END:
3913                 /* Only valid matches are exact, which memcmp() above
3914                  * would have accepted
3915                  */
3916         default:
3917                 /* Don't know what's going on, just say it's not safe */
3918                 return false;
3919         }
3920
3921         /* Shouldn't get here; if we do, say it's not safe */
3922         WARN_ON_ONCE(1);
3923         return false;
3924 }
3925
3926 static bool stacksafe(struct bpf_verifier_state *old,
3927                       struct bpf_verifier_state *cur,
3928                       struct idpair *idmap)
3929 {
3930         int i, spi;
3931
3932         /* if explored stack has more populated slots than current stack
3933          * such stacks are not equivalent
3934          */
3935         if (old->allocated_stack > cur->allocated_stack)
3936                 return false;
3937
3938         /* walk slots of the explored stack and ignore any additional
3939          * slots in the current stack, since explored(safe) state
3940          * didn't use them
3941          */
3942         for (i = 0; i < old->allocated_stack; i++) {
3943                 spi = i / BPF_REG_SIZE;
3944
3945                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
3946                         continue;
3947                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
3948                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
3949                         /* Ex: old explored (safe) state has STACK_SPILL in
3950                          * this stack slot, but current has has STACK_MISC ->
3951                          * this verifier states are not equivalent,
3952                          * return false to continue verification of this path
3953                          */
3954                         return false;
3955                 if (i % BPF_REG_SIZE)
3956                         continue;
3957                 if (old->stack[spi].slot_type[0] != STACK_SPILL)
3958                         continue;
3959                 if (!regsafe(&old->stack[spi].spilled_ptr,
3960                              &cur->stack[spi].spilled_ptr,
3961                              idmap))
3962                         /* when explored and current stack slot are both storing
3963                          * spilled registers, check that stored pointers types
3964                          * are the same as well.
3965                          * Ex: explored safe path could have stored
3966                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
3967                          * but current path has stored:
3968                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
3969                          * such verifier states are not equivalent.
3970                          * return false to continue verification of this path
3971                          */
3972                         return false;
3973         }
3974         return true;
3975 }
3976
3977 /* compare two verifier states
3978  *
3979  * all states stored in state_list are known to be valid, since
3980  * verifier reached 'bpf_exit' instruction through them
3981  *
3982  * this function is called when verifier exploring different branches of
3983  * execution popped from the state stack. If it sees an old state that has
3984  * more strict register state and more strict stack state then this execution
3985  * branch doesn't need to be explored further, since verifier already
3986  * concluded that more strict state leads to valid finish.
3987  *
3988  * Therefore two states are equivalent if register state is more conservative
3989  * and explored stack state is more conservative than the current one.
3990  * Example:
3991  *       explored                   current
3992  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
3993  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
3994  *
3995  * In other words if current stack state (one being explored) has more
3996  * valid slots than old one that already passed validation, it means
3997  * the verifier can stop exploring and conclude that current state is valid too
3998  *
3999  * Similarly with registers. If explored state has register type as invalid
4000  * whereas register type in current state is meaningful, it means that
4001  * the current state will reach 'bpf_exit' instruction safely
4002  */
4003 static bool states_equal(struct bpf_verifier_env *env,
4004                          struct bpf_verifier_state *old,
4005                          struct bpf_verifier_state *cur)
4006 {
4007         struct idpair *idmap;
4008         bool ret = false;
4009         int i;
4010
4011         /* Verification state from speculative execution simulation
4012          * must never prune a non-speculative execution one.
4013          */
4014         if (old->speculative && !cur->speculative)
4015                 return false;
4016
4017         idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
4018         /* If we failed to allocate the idmap, just say it's not safe */
4019         if (!idmap)
4020                 return false;
4021
4022         for (i = 0; i < MAX_BPF_REG; i++) {
4023                 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
4024                         goto out_free;
4025         }
4026
4027         if (!stacksafe(old, cur, idmap))
4028                 goto out_free;
4029         ret = true;
4030 out_free:
4031         kfree(idmap);
4032         return ret;
4033 }
4034
4035 /* A write screens off any subsequent reads; but write marks come from the
4036  * straight-line code between a state and its parent.  When we arrive at a
4037  * jump target (in the first iteration of the propagate_liveness() loop),
4038  * we didn't arrive by the straight-line code, so read marks in state must
4039  * propagate to parent regardless of state's write marks.
4040  */
4041 static bool do_propagate_liveness(const struct bpf_verifier_state *state,
4042                                   struct bpf_verifier_state *parent)
4043 {
4044         bool writes = parent == state->parent; /* Observe write marks */
4045         bool touched = false; /* any changes made? */
4046         int i;
4047
4048         if (!parent)
4049                 return touched;
4050         /* Propagate read liveness of registers... */
4051         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
4052         /* We don't need to worry about FP liveness because it's read-only */
4053         for (i = 0; i < BPF_REG_FP; i++) {
4054                 if (parent->regs[i].live & REG_LIVE_READ)
4055                         continue;
4056                 if (writes && (state->regs[i].live & REG_LIVE_WRITTEN))
4057                         continue;
4058                 if (state->regs[i].live & REG_LIVE_READ) {
4059                         parent->regs[i].live |= REG_LIVE_READ;
4060                         touched = true;
4061                 }
4062         }
4063         /* ... and stack slots */
4064         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
4065                     i < parent->allocated_stack / BPF_REG_SIZE; i++) {
4066                 if (parent->stack[i].slot_type[0] != STACK_SPILL)
4067                         continue;
4068                 if (state->stack[i].slot_type[0] != STACK_SPILL)
4069                         continue;
4070                 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
4071                         continue;
4072                 if (writes &&
4073                     (state->stack[i].spilled_ptr.live & REG_LIVE_WRITTEN))
4074                         continue;
4075                 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) {
4076                         parent->stack[i].spilled_ptr.live |= REG_LIVE_READ;
4077                         touched = true;
4078                 }
4079         }
4080         return touched;
4081 }
4082
4083 /* "parent" is "a state from which we reach the current state", but initially
4084  * it is not the state->parent (i.e. "the state whose straight-line code leads
4085  * to the current state"), instead it is the state that happened to arrive at
4086  * a (prunable) equivalent of the current state.  See comment above
4087  * do_propagate_liveness() for consequences of this.
4088  * This function is just a more efficient way of calling mark_reg_read() or
4089  * mark_stack_slot_read() on each reg in "parent" that is read in "state",
4090  * though it requires that parent != state->parent in the call arguments.
4091  */
4092 static void propagate_liveness(const struct bpf_verifier_state *state,
4093                                struct bpf_verifier_state *parent)
4094 {
4095         while (do_propagate_liveness(state, parent)) {
4096                 /* Something changed, so we need to feed those changes onward */
4097                 state = parent;
4098                 parent = state->parent;
4099         }
4100 }
4101
4102 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
4103 {
4104         struct bpf_verifier_state_list *new_sl;
4105         struct bpf_verifier_state_list *sl;
4106         struct bpf_verifier_state *cur = env->cur_state;
4107         int i, err;
4108
4109         sl = env->explored_states[insn_idx];
4110         if (!sl)
4111                 /* this 'insn_idx' instruction wasn't marked, so we will not
4112                  * be doing state search here
4113                  */
4114                 return 0;
4115
4116         while (sl != STATE_LIST_MARK) {
4117                 if (states_equal(env, &sl->state, cur)) {
4118                         /* reached equivalent register/stack state,
4119                          * prune the search.
4120                          * Registers read by the continuation are read by us.
4121                          * If we have any write marks in env->cur_state, they
4122                          * will prevent corresponding reads in the continuation
4123                          * from reaching our parent (an explored_state).  Our
4124                          * own state will get the read marks recorded, but
4125                          * they'll be immediately forgotten as we're pruning
4126                          * this state and will pop a new one.
4127                          */
4128                         propagate_liveness(&sl->state, cur);
4129                         return 1;
4130                 }
4131                 sl = sl->next;
4132         }
4133
4134         /* there were no equivalent states, remember current one.
4135          * technically the current state is not proven to be safe yet,
4136          * but it will either reach bpf_exit (which means it's safe) or
4137          * it will be rejected. Since there are no loops, we won't be
4138          * seeing this 'insn_idx' instruction again on the way to bpf_exit
4139          */
4140         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
4141         if (!new_sl)
4142                 return -ENOMEM;
4143
4144         /* add new state to the head of linked list */
4145         err = copy_verifier_state(&new_sl->state, cur);
4146         if (err) {
4147                 free_verifier_state(&new_sl->state, false);
4148                 kfree(new_sl);
4149                 return err;
4150         }
4151         new_sl->next = env->explored_states[insn_idx];
4152         env->explored_states[insn_idx] = new_sl;
4153         /* connect new state to parentage chain */
4154         cur->parent = &new_sl->state;
4155         /* clear write marks in current state: the writes we did are not writes
4156          * our child did, so they don't screen off its reads from us.
4157          * (There are no read marks in current state, because reads always mark
4158          * their parent and current state never has children yet.  Only
4159          * explored_states can get read marks.)
4160          */
4161         for (i = 0; i < BPF_REG_FP; i++)
4162                 cur->regs[i].live = REG_LIVE_NONE;
4163         for (i = 0; i < cur->allocated_stack / BPF_REG_SIZE; i++)
4164                 if (cur->stack[i].slot_type[0] == STACK_SPILL)
4165                         cur->stack[i].spilled_ptr.live = REG_LIVE_NONE;
4166         return 0;
4167 }
4168
4169 static int ext_analyzer_insn_hook(struct bpf_verifier_env *env,
4170                                   int insn_idx, int prev_insn_idx)
4171 {
4172         if (!env->analyzer_ops || !env->analyzer_ops->insn_hook)
4173                 return 0;
4174
4175         return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx);
4176 }
4177
4178 static int do_check(struct bpf_verifier_env *env)
4179 {
4180         struct bpf_verifier_state *state;
4181         struct bpf_insn *insns = env->prog->insnsi;
4182         struct bpf_reg_state *regs;
4183         int insn_cnt = env->prog->len;
4184         int insn_processed = 0;
4185         bool do_print_state = false;
4186
4187         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
4188         if (!state)
4189                 return -ENOMEM;
4190         env->cur_state = state;
4191         init_reg_state(state->regs);
4192         state->parent = NULL;
4193         for (;;) {
4194                 struct bpf_insn *insn;
4195                 u8 class;
4196                 int err;
4197
4198                 if (env->insn_idx >= insn_cnt) {
4199                         verbose("invalid insn idx %d insn_cnt %d\n",
4200                                 env->insn_idx, insn_cnt);
4201                         return -EFAULT;
4202                 }
4203
4204                 insn = &insns[env->insn_idx];
4205                 class = BPF_CLASS(insn->code);
4206
4207                 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
4208                         verbose("BPF program is too large. Processed %d insn\n",
4209                                 insn_processed);
4210                         return -E2BIG;
4211                 }
4212
4213                 err = is_state_visited(env, env->insn_idx);
4214                 if (err < 0)
4215                         return err;
4216                 if (err == 1) {
4217                         /* found equivalent state, can prune the search */
4218                         if (log_level) {
4219                                 if (do_print_state)
4220                                         verbose("\nfrom %d to %d%s: safe\n",
4221                                                 env->prev_insn_idx, env->insn_idx,
4222                                                 env->cur_state->speculative ?
4223                                                 " (speculative execution)" : "");
4224                                 else
4225                                         verbose("%d: safe\n", env->insn_idx);
4226                         }
4227                         goto process_bpf_exit;
4228                 }
4229
4230                 if (need_resched())
4231                         cond_resched();
4232
4233                 if (log_level > 1 || (log_level && do_print_state)) {
4234                         if (log_level > 1)
4235                                 verbose("%d:", env->insn_idx);
4236                         else
4237                                 verbose("\nfrom %d to %d%s:",
4238                                         env->prev_insn_idx, env->insn_idx,
4239                                         env->cur_state->speculative ?
4240                                         " (speculative execution)" : "");
4241                         print_verifier_state(env->cur_state);
4242                         do_print_state = false;
4243                 }
4244
4245                 if (log_level) {
4246                         verbose("%d: ", env->insn_idx);
4247                         print_bpf_insn(env, insn);
4248                 }
4249
4250                 err = ext_analyzer_insn_hook(env, env->insn_idx, env->prev_insn_idx);
4251                 if (err)
4252                         return err;
4253
4254                 regs = cur_regs(env);
4255                 env->insn_aux_data[env->insn_idx].seen = true;
4256                 if (class == BPF_ALU || class == BPF_ALU64) {
4257                         err = check_alu_op(env, insn);
4258                         if (err)
4259                                 return err;
4260
4261                 } else if (class == BPF_LDX) {
4262                         enum bpf_reg_type *prev_src_type, src_reg_type;
4263
4264                         /* check for reserved fields is already done */
4265
4266                         /* check src operand */
4267                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4268                         if (err)
4269                                 return err;
4270
4271                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
4272                         if (err)
4273                                 return err;
4274
4275                         src_reg_type = regs[insn->src_reg].type;
4276
4277                         /* check that memory (src_reg + off) is readable,
4278                          * the state of dst_reg will be updated by this func
4279                          */
4280                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
4281                                                insn->off, BPF_SIZE(insn->code),
4282                                                BPF_READ, insn->dst_reg, false);
4283                         if (err)
4284                                 return err;
4285
4286                         prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4287
4288                         if (*prev_src_type == NOT_INIT) {
4289                                 /* saw a valid insn
4290                                  * dst_reg = *(u32 *)(src_reg + off)
4291                                  * save type to validate intersecting paths
4292                                  */
4293                                 *prev_src_type = src_reg_type;
4294
4295                         } else if (src_reg_type != *prev_src_type &&
4296                                    (src_reg_type == PTR_TO_CTX ||
4297                                     *prev_src_type == PTR_TO_CTX)) {
4298                                 /* ABuser program is trying to use the same insn
4299                                  * dst_reg = *(u32*) (src_reg + off)
4300                                  * with different pointer types:
4301                                  * src_reg == ctx in one branch and
4302                                  * src_reg == stack|map in some other branch.
4303                                  * Reject it.
4304                                  */
4305                                 verbose("same insn cannot be used with different pointers\n");
4306                                 return -EINVAL;
4307                         }
4308
4309                 } else if (class == BPF_STX) {
4310                         enum bpf_reg_type *prev_dst_type, dst_reg_type;
4311
4312                         if (BPF_MODE(insn->code) == BPF_XADD) {
4313                                 err = check_xadd(env, env->insn_idx, insn);
4314                                 if (err)
4315                                         return err;
4316                                 env->insn_idx++;
4317                                 continue;
4318                         }
4319
4320                         /* check src1 operand */
4321                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
4322                         if (err)
4323                                 return err;
4324                         /* check src2 operand */
4325                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4326                         if (err)
4327                                 return err;
4328
4329                         dst_reg_type = regs[insn->dst_reg].type;
4330
4331                         /* check that memory (dst_reg + off) is writeable */
4332                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4333                                                insn->off, BPF_SIZE(insn->code),
4334                                                BPF_WRITE, insn->src_reg, false);
4335                         if (err)
4336                                 return err;
4337
4338                         prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
4339
4340                         if (*prev_dst_type == NOT_INIT) {
4341                                 *prev_dst_type = dst_reg_type;
4342                         } else if (dst_reg_type != *prev_dst_type &&
4343                                    (dst_reg_type == PTR_TO_CTX ||
4344                                     *prev_dst_type == PTR_TO_CTX)) {
4345                                 verbose("same insn cannot be used with different pointers\n");
4346                                 return -EINVAL;
4347                         }
4348
4349                 } else if (class == BPF_ST) {
4350                         if (BPF_MODE(insn->code) != BPF_MEM ||
4351                             insn->src_reg != BPF_REG_0) {
4352                                 verbose("BPF_ST uses reserved fields\n");
4353                                 return -EINVAL;
4354                         }
4355                         /* check src operand */
4356                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4357                         if (err)
4358                                 return err;
4359
4360                         if (is_ctx_reg(env, insn->dst_reg)) {
4361                                 verbose("BPF_ST stores into R%d context is not allowed\n",
4362                                         insn->dst_reg);
4363                                 return -EACCES;
4364                         }
4365
4366                         /* check that memory (dst_reg + off) is writeable */
4367                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
4368                                                insn->off, BPF_SIZE(insn->code),
4369                                                BPF_WRITE, -1, false);
4370                         if (err)
4371                                 return err;
4372
4373                 } else if (class == BPF_JMP) {
4374                         u8 opcode = BPF_OP(insn->code);
4375
4376                         if (opcode == BPF_CALL) {
4377                                 if (BPF_SRC(insn->code) != BPF_K ||
4378                                     insn->off != 0 ||
4379                                     insn->src_reg != BPF_REG_0 ||
4380                                     insn->dst_reg != BPF_REG_0) {
4381                                         verbose("BPF_CALL uses reserved fields\n");
4382                                         return -EINVAL;
4383                                 }
4384
4385                                 err = check_call(env, insn->imm, env->insn_idx);
4386                                 if (err)
4387                                         return err;
4388
4389                         } else if (opcode == BPF_JA) {
4390                                 if (BPF_SRC(insn->code) != BPF_K ||
4391                                     insn->imm != 0 ||
4392                                     insn->src_reg != BPF_REG_0 ||
4393                                     insn->dst_reg != BPF_REG_0) {
4394                                         verbose("BPF_JA uses reserved fields\n");
4395                                         return -EINVAL;
4396                                 }
4397
4398                                 env->insn_idx += insn->off + 1;
4399                                 continue;
4400
4401                         } else if (opcode == BPF_EXIT) {
4402                                 if (BPF_SRC(insn->code) != BPF_K ||
4403                                     insn->imm != 0 ||
4404                                     insn->src_reg != BPF_REG_0 ||
4405                                     insn->dst_reg != BPF_REG_0) {
4406                                         verbose("BPF_EXIT uses reserved fields\n");
4407                                         return -EINVAL;
4408                                 }
4409
4410                                 /* eBPF calling convetion is such that R0 is used
4411                                  * to return the value from eBPF program.
4412                                  * Make sure that it's readable at this time
4413                                  * of bpf_exit, which means that program wrote
4414                                  * something into it earlier
4415                                  */
4416                                 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4417                                 if (err)
4418                                         return err;
4419
4420                                 if (is_pointer_value(env, BPF_REG_0)) {
4421                                         verbose("R0 leaks addr as return value\n");
4422                                         return -EACCES;
4423                                 }
4424
4425 process_bpf_exit:
4426                                 err = pop_stack(env, &env->prev_insn_idx, &env->insn_idx);
4427                                 if (err < 0) {
4428                                         if (err != -ENOENT)
4429                                                 return err;
4430                                         break;
4431                                 } else {
4432                                         do_print_state = true;
4433                                         continue;
4434                                 }
4435                         } else {
4436                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
4437                                 if (err)
4438                                         return err;
4439                         }
4440                 } else if (class == BPF_LD) {
4441                         u8 mode = BPF_MODE(insn->code);
4442
4443                         if (mode == BPF_ABS || mode == BPF_IND) {
4444                                 err = check_ld_abs(env, insn);
4445                                 if (err)
4446                                         return err;
4447
4448                         } else if (mode == BPF_IMM) {
4449                                 err = check_ld_imm(env, insn);
4450                                 if (err)
4451                                         return err;
4452
4453                                 env->insn_idx++;
4454                                 env->insn_aux_data[env->insn_idx].seen = true;
4455                         } else {
4456                                 verbose("invalid BPF_LD mode\n");
4457                                 return -EINVAL;
4458                         }
4459                 } else {
4460                         verbose("unknown insn class %d\n", class);
4461                         return -EINVAL;
4462                 }
4463
4464                 env->insn_idx++;
4465         }
4466
4467         verbose("processed %d insns, stack depth %d\n",
4468                 insn_processed, env->prog->aux->stack_depth);
4469         return 0;
4470 }
4471
4472 static int check_map_prealloc(struct bpf_map *map)
4473 {
4474         return (map->map_type != BPF_MAP_TYPE_HASH &&
4475                 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
4476                 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
4477                 !(map->map_flags & BPF_F_NO_PREALLOC);
4478 }
4479
4480 static int check_map_prog_compatibility(struct bpf_map *map,
4481                                         struct bpf_prog *prog)
4482
4483 {
4484         /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
4485          * preallocated hash maps, since doing memory allocation
4486          * in overflow_handler can crash depending on where nmi got
4487          * triggered.
4488          */
4489         if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
4490                 if (!check_map_prealloc(map)) {
4491                         verbose("perf_event programs can only use preallocated hash map\n");
4492                         return -EINVAL;
4493                 }
4494                 if (map->inner_map_meta &&
4495                     !check_map_prealloc(map->inner_map_meta)) {
4496                         verbose("perf_event programs can only use preallocated inner hash map\n");
4497                         return -EINVAL;
4498                 }
4499         }
4500         return 0;
4501 }
4502
4503 /* look for pseudo eBPF instructions that access map FDs and
4504  * replace them with actual map pointers
4505  */
4506 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
4507 {
4508         struct bpf_insn *insn = env->prog->insnsi;
4509         int insn_cnt = env->prog->len;
4510         int i, j, err;
4511
4512         err = bpf_prog_calc_tag(env->prog);
4513         if (err)
4514                 return err;
4515
4516         for (i = 0; i < insn_cnt; i++, insn++) {
4517                 if (BPF_CLASS(insn->code) == BPF_LDX &&
4518                     (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
4519                         verbose("BPF_LDX uses reserved fields\n");
4520                         return -EINVAL;
4521                 }
4522
4523                 if (BPF_CLASS(insn->code) == BPF_STX &&
4524                     ((BPF_MODE(insn->code) != BPF_MEM &&
4525                       BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
4526                         verbose("BPF_STX uses reserved fields\n");
4527                         return -EINVAL;
4528                 }
4529
4530                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
4531                         struct bpf_map *map;
4532                         struct fd f;
4533
4534                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
4535                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
4536                             insn[1].off != 0) {
4537                                 verbose("invalid bpf_ld_imm64 insn\n");
4538                                 return -EINVAL;
4539                         }
4540
4541                         if (insn->src_reg == 0)
4542                                 /* valid generic load 64-bit imm */
4543                                 goto next_insn;
4544
4545                         if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
4546                                 verbose("unrecognized bpf_ld_imm64 insn\n");
4547                                 return -EINVAL;
4548                         }
4549
4550                         f = fdget(insn->imm);
4551                         map = __bpf_map_get(f);
4552                         if (IS_ERR(map)) {
4553                                 verbose("fd %d is not pointing to valid bpf_map\n",
4554                                         insn->imm);
4555                                 return PTR_ERR(map);
4556                         }
4557
4558                         err = check_map_prog_compatibility(map, env->prog);
4559                         if (err) {
4560                                 fdput(f);
4561                                 return err;
4562                         }
4563
4564                         /* store map pointer inside BPF_LD_IMM64 instruction */
4565                         insn[0].imm = (u32) (unsigned long) map;
4566                         insn[1].imm = ((u64) (unsigned long) map) >> 32;
4567
4568                         /* check whether we recorded this map already */
4569                         for (j = 0; j < env->used_map_cnt; j++)
4570                                 if (env->used_maps[j] == map) {
4571                                         fdput(f);
4572                                         goto next_insn;
4573                                 }
4574
4575                         if (env->used_map_cnt >= MAX_USED_MAPS) {
4576                                 fdput(f);
4577                                 return -E2BIG;
4578                         }
4579
4580                         /* hold the map. If the program is rejected by verifier,
4581                          * the map will be released by release_maps() or it
4582                          * will be used by the valid program until it's unloaded
4583                          * and all maps are released in free_used_maps()
4584                          */
4585                         map = bpf_map_inc(map, false);
4586                         if (IS_ERR(map)) {
4587                                 fdput(f);
4588                                 return PTR_ERR(map);
4589                         }
4590                         env->used_maps[env->used_map_cnt++] = map;
4591
4592                         fdput(f);
4593 next_insn:
4594                         insn++;
4595                         i++;
4596                 }
4597         }
4598
4599         /* now all pseudo BPF_LD_IMM64 instructions load valid
4600          * 'struct bpf_map *' into a register instead of user map_fd.
4601          * These pointers will be used later by verifier to validate map access.
4602          */
4603         return 0;
4604 }
4605
4606 /* drop refcnt of maps used by the rejected program */
4607 static void release_maps(struct bpf_verifier_env *env)
4608 {
4609         int i;
4610
4611         for (i = 0; i < env->used_map_cnt; i++)
4612                 bpf_map_put(env->used_maps[i]);
4613 }
4614
4615 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
4616 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
4617 {
4618         struct bpf_insn *insn = env->prog->insnsi;
4619         int insn_cnt = env->prog->len;
4620         int i;
4621
4622         for (i = 0; i < insn_cnt; i++, insn++)
4623                 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
4624                         insn->src_reg = 0;
4625 }
4626
4627 /* single env->prog->insni[off] instruction was replaced with the range
4628  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
4629  * [0, off) and [off, end) to new locations, so the patched range stays zero
4630  */
4631 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
4632                                 u32 off, u32 cnt)
4633 {
4634         struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
4635         int i;
4636
4637         if (cnt == 1)
4638                 return 0;
4639         new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len);
4640         if (!new_data)
4641                 return -ENOMEM;
4642         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
4643         memcpy(new_data + off + cnt - 1, old_data + off,
4644                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
4645         for (i = off; i < off + cnt - 1; i++)
4646                 new_data[i].seen = true;
4647         env->insn_aux_data = new_data;
4648         vfree(old_data);
4649         return 0;
4650 }
4651
4652 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
4653                                             const struct bpf_insn *patch, u32 len)
4654 {
4655         struct bpf_prog *new_prog;
4656
4657         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4658         if (!new_prog)
4659                 return NULL;
4660         if (adjust_insn_aux_data(env, new_prog->len, off, len))
4661                 return NULL;
4662         return new_prog;
4663 }
4664
4665 /* The verifier does more data flow analysis than llvm and will not explore
4666  * branches that are dead at run time. Malicious programs can have dead code
4667  * too. Therefore replace all dead at-run-time code with nops.
4668  */
4669 static void sanitize_dead_code(struct bpf_verifier_env *env)
4670 {
4671         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
4672         struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0);
4673         struct bpf_insn *insn = env->prog->insnsi;
4674         const int insn_cnt = env->prog->len;
4675         int i;
4676
4677         for (i = 0; i < insn_cnt; i++) {
4678                 if (aux_data[i].seen)
4679                         continue;
4680                 memcpy(insn + i, &nop, sizeof(nop));
4681         }
4682 }
4683
4684 /* convert load instructions that access fields of 'struct __sk_buff'
4685  * into sequence of instructions that access fields of 'struct sk_buff'
4686  */
4687 static int convert_ctx_accesses(struct bpf_verifier_env *env)
4688 {
4689         const struct bpf_verifier_ops *ops = env->prog->aux->ops;
4690         int i, cnt, size, ctx_field_size, delta = 0;
4691         const int insn_cnt = env->prog->len;
4692         struct bpf_insn insn_buf[16], *insn;
4693         struct bpf_prog *new_prog;
4694         enum bpf_access_type type;
4695         bool is_narrower_load;
4696         u32 target_size;
4697
4698         if (ops->gen_prologue) {
4699                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
4700                                         env->prog);
4701                 if (cnt >= ARRAY_SIZE(insn_buf)) {
4702                         verbose("bpf verifier is misconfigured\n");
4703                         return -EINVAL;
4704                 } else if (cnt) {
4705                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
4706                         if (!new_prog)
4707                                 return -ENOMEM;
4708
4709                         env->prog = new_prog;
4710                         delta += cnt - 1;
4711                 }
4712         }
4713
4714         if (!ops->convert_ctx_access)
4715                 return 0;
4716
4717         insn = env->prog->insnsi + delta;
4718
4719         for (i = 0; i < insn_cnt; i++, insn++) {
4720                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
4721                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
4722                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
4723                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
4724                         type = BPF_READ;
4725                 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
4726                          insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
4727                          insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
4728                          insn->code == (BPF_STX | BPF_MEM | BPF_DW))
4729                         type = BPF_WRITE;
4730                 else
4731                         continue;
4732
4733                 if (type == BPF_WRITE &&
4734                     env->insn_aux_data[i + delta].sanitize_stack_off) {
4735                         struct bpf_insn patch[] = {
4736                                 /* Sanitize suspicious stack slot with zero.
4737                                  * There are no memory dependencies for this store,
4738                                  * since it's only using frame pointer and immediate
4739                                  * constant of zero
4740                                  */
4741                                 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
4742                                            env->insn_aux_data[i + delta].sanitize_stack_off,
4743                                            0),
4744                                 /* the original STX instruction will immediately
4745                                  * overwrite the same stack slot with appropriate value
4746                                  */
4747                                 *insn,
4748                         };
4749
4750                         cnt = ARRAY_SIZE(patch);
4751                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
4752                         if (!new_prog)
4753                                 return -ENOMEM;
4754
4755                         delta    += cnt - 1;
4756                         env->prog = new_prog;
4757                         insn      = new_prog->insnsi + i + delta;
4758                         continue;
4759                 }
4760
4761                 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
4762                         continue;
4763
4764                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
4765                 size = BPF_LDST_BYTES(insn);
4766
4767                 /* If the read access is a narrower load of the field,
4768                  * convert to a 4/8-byte load, to minimum program type specific
4769                  * convert_ctx_access changes. If conversion is successful,
4770                  * we will apply proper mask to the result.
4771                  */
4772                 is_narrower_load = size < ctx_field_size;
4773                 if (is_narrower_load) {
4774                         u32 off = insn->off;
4775                         u8 size_code;
4776
4777                         if (type == BPF_WRITE) {
4778                                 verbose("bpf verifier narrow ctx access misconfigured\n");
4779                                 return -EINVAL;
4780                         }
4781
4782                         size_code = BPF_H;
4783                         if (ctx_field_size == 4)
4784                                 size_code = BPF_W;
4785                         else if (ctx_field_size == 8)
4786                                 size_code = BPF_DW;
4787
4788                         insn->off = off & ~(ctx_field_size - 1);
4789                         insn->code = BPF_LDX | BPF_MEM | size_code;
4790                 }
4791
4792                 target_size = 0;
4793                 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
4794                                               &target_size);
4795                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
4796                     (ctx_field_size && !target_size)) {
4797                         verbose("bpf verifier is misconfigured\n");
4798                         return -EINVAL;
4799                 }
4800
4801                 if (is_narrower_load && size < target_size) {
4802                         if (ctx_field_size <= 4)
4803                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
4804                                                                 (1 << size * 8) - 1);
4805                         else
4806                                 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
4807                                                                 (1 << size * 8) - 1);
4808                 }
4809
4810                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4811                 if (!new_prog)
4812                         return -ENOMEM;
4813
4814                 delta += cnt - 1;
4815
4816                 /* keep walking new program and skip insns we just inserted */
4817                 env->prog = new_prog;
4818                 insn      = new_prog->insnsi + i + delta;
4819         }
4820
4821         return 0;
4822 }
4823
4824 /* fixup insn->imm field of bpf_call instructions
4825  * and inline eligible helpers as explicit sequence of BPF instructions
4826  *
4827  * this function is called after eBPF program passed verification
4828  */
4829 static int fixup_bpf_calls(struct bpf_verifier_env *env)
4830 {
4831         struct bpf_prog *prog = env->prog;
4832         struct bpf_insn *insn = prog->insnsi;
4833         const struct bpf_func_proto *fn;
4834         const int insn_cnt = prog->len;
4835         struct bpf_insn insn_buf[16];
4836         struct bpf_prog *new_prog;
4837         struct bpf_map *map_ptr;
4838         int i, cnt, delta = 0;
4839         struct bpf_insn_aux_data *aux;
4840
4841         for (i = 0; i < insn_cnt; i++, insn++) {
4842                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
4843                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
4844                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
4845                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
4846                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
4847                         struct bpf_insn mask_and_div[] = {
4848                                 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
4849                                 /* [R,W]x div 0 -> 0 */
4850                                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 2),
4851                                 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
4852                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
4853                                 BPF_ALU_REG(BPF_CLASS(insn->code), BPF_XOR, insn->dst_reg, insn->dst_reg),
4854                         };
4855                         struct bpf_insn mask_and_mod[] = {
4856                                 BPF_MOV_REG(BPF_CLASS(insn->code), BPF_REG_AX, insn->src_reg),
4857                                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 1 + (is64 ? 0 : 1)),
4858                                 BPF_RAW_REG(*insn, insn->dst_reg, BPF_REG_AX),
4859                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
4860                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
4861                         };
4862                         struct bpf_insn *patchlet;
4863
4864                         if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
4865                             insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
4866                                 patchlet = mask_and_div;
4867                                 cnt = ARRAY_SIZE(mask_and_div);
4868                         } else {
4869                                 patchlet = mask_and_mod;
4870                                 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 2 : 0);
4871                         }
4872
4873                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
4874                         if (!new_prog)
4875                                 return -ENOMEM;
4876
4877                         delta    += cnt - 1;
4878                         env->prog = prog = new_prog;
4879                         insn      = new_prog->insnsi + i + delta;
4880                         continue;
4881                 }
4882
4883                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
4884                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
4885                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
4886                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
4887                         struct bpf_insn insn_buf[16];
4888                         struct bpf_insn *patch = &insn_buf[0];
4889                         bool issrc, isneg, isimm;
4890                         u32 off_reg;
4891
4892                         aux = &env->insn_aux_data[i + delta];
4893                         if (!aux->alu_state ||
4894                             aux->alu_state == BPF_ALU_NON_POINTER)
4895                                 continue;
4896
4897                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
4898                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
4899                                 BPF_ALU_SANITIZE_SRC;
4900                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
4901
4902                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
4903                         if (isimm) {
4904                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
4905                         } else {
4906                                 if (isneg)
4907                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4908                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
4909                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
4910                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
4911                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
4912                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
4913                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
4914                         }
4915                         if (!issrc)
4916                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
4917                         insn->src_reg = BPF_REG_AX;
4918                         if (isneg)
4919                                 insn->code = insn->code == code_add ?
4920                                              code_sub : code_add;
4921                         *patch++ = *insn;
4922                         if (issrc && isneg && !isimm)
4923                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
4924                         cnt = patch - insn_buf;
4925
4926                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4927                         if (!new_prog)
4928                                 return -ENOMEM;
4929
4930                         delta    += cnt - 1;
4931                         env->prog = prog = new_prog;
4932                         insn      = new_prog->insnsi + i + delta;
4933                         continue;
4934                 }
4935
4936                 if (insn->code != (BPF_JMP | BPF_CALL))
4937                         continue;
4938
4939                 if (insn->imm == BPF_FUNC_get_route_realm)
4940                         prog->dst_needed = 1;
4941                 if (insn->imm == BPF_FUNC_get_prandom_u32)
4942                         bpf_user_rnd_init_once();
4943                 if (insn->imm == BPF_FUNC_tail_call) {
4944                         /* If we tail call into other programs, we
4945                          * cannot make any assumptions since they can
4946                          * be replaced dynamically during runtime in
4947                          * the program array.
4948                          */
4949                         prog->cb_access = 1;
4950                         env->prog->aux->stack_depth = MAX_BPF_STACK;
4951
4952                         /* mark bpf_tail_call as different opcode to avoid
4953                          * conditional branch in the interpeter for every normal
4954                          * call and to prevent accidental JITing by JIT compiler
4955                          * that doesn't support bpf_tail_call yet
4956                          */
4957                         insn->imm = 0;
4958                         insn->code = BPF_JMP | BPF_TAIL_CALL;
4959
4960                         /* instead of changing every JIT dealing with tail_call
4961                          * emit two extra insns:
4962                          * if (index >= max_entries) goto out;
4963                          * index &= array->index_mask;
4964                          * to avoid out-of-bounds cpu speculation
4965                          */
4966                         map_ptr = env->insn_aux_data[i + delta].map_ptr;
4967                         if (map_ptr == BPF_MAP_PTR_POISON) {
4968                                 verbose("tail_call obusing map_ptr\n");
4969                                 return -EINVAL;
4970                         }
4971                         if (!map_ptr->unpriv_array)
4972                                 continue;
4973                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
4974                                                   map_ptr->max_entries, 2);
4975                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
4976                                                     container_of(map_ptr,
4977                                                                  struct bpf_array,
4978                                                                  map)->index_mask);
4979                         insn_buf[2] = *insn;
4980                         cnt = 3;
4981                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
4982                         if (!new_prog)
4983                                 return -ENOMEM;
4984
4985                         delta    += cnt - 1;
4986                         env->prog = prog = new_prog;
4987                         insn      = new_prog->insnsi + i + delta;
4988                         continue;
4989                 }
4990
4991                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
4992                  * handlers are currently limited to 64 bit only.
4993                  */
4994                 if (ebpf_jit_enabled() && BITS_PER_LONG == 64 &&
4995                     insn->imm == BPF_FUNC_map_lookup_elem) {
4996                         map_ptr = env->insn_aux_data[i + delta].map_ptr;
4997                         if (map_ptr == BPF_MAP_PTR_POISON ||
4998                             !map_ptr->ops->map_gen_lookup)
4999                                 goto patch_call_imm;
5000
5001                         cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf);
5002                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
5003                                 verbose("bpf verifier is misconfigured\n");
5004                                 return -EINVAL;
5005                         }
5006
5007                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
5008                                                        cnt);
5009                         if (!new_prog)
5010                                 return -ENOMEM;
5011
5012                         delta += cnt - 1;
5013
5014                         /* keep walking new program and skip insns we just inserted */
5015                         env->prog = prog = new_prog;
5016                         insn      = new_prog->insnsi + i + delta;
5017                         continue;
5018                 }
5019
5020                 if (insn->imm == BPF_FUNC_redirect_map) {
5021                         /* Note, we cannot use prog directly as imm as subsequent
5022                          * rewrites would still change the prog pointer. The only
5023                          * stable address we can use is aux, which also works with
5024                          * prog clones during blinding.
5025                          */
5026                         u64 addr = (unsigned long)prog->aux;
5027                         struct bpf_insn r4_ld[] = {
5028                                 BPF_LD_IMM64(BPF_REG_4, addr),
5029                                 *insn,
5030                         };
5031                         cnt = ARRAY_SIZE(r4_ld);
5032
5033                         new_prog = bpf_patch_insn_data(env, i + delta, r4_ld, cnt);
5034                         if (!new_prog)
5035                                 return -ENOMEM;
5036
5037                         delta    += cnt - 1;
5038                         env->prog = prog = new_prog;
5039                         insn      = new_prog->insnsi + i + delta;
5040                 }
5041 patch_call_imm:
5042                 fn = prog->aux->ops->get_func_proto(insn->imm);
5043                 /* all functions that have prototype and verifier allowed
5044                  * programs to call them, must be real in-kernel functions
5045                  */
5046                 if (!fn->func) {
5047                         verbose("kernel subsystem misconfigured func %s#%d\n",
5048                                 func_id_name(insn->imm), insn->imm);
5049                         return -EFAULT;
5050                 }
5051                 insn->imm = fn->func - __bpf_call_base;
5052         }
5053
5054         return 0;
5055 }
5056
5057 static void free_states(struct bpf_verifier_env *env)
5058 {
5059         struct bpf_verifier_state_list *sl, *sln;
5060         int i;
5061
5062         if (!env->explored_states)
5063                 return;
5064
5065         for (i = 0; i < env->prog->len; i++) {
5066                 sl = env->explored_states[i];
5067
5068                 if (sl)
5069                         while (sl != STATE_LIST_MARK) {
5070                                 sln = sl->next;
5071                                 free_verifier_state(&sl->state, false);
5072                                 kfree(sl);
5073                                 sl = sln;
5074                         }
5075         }
5076
5077         kfree(env->explored_states);
5078 }
5079
5080 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
5081 {
5082         char __user *log_ubuf = NULL;
5083         struct bpf_verifier_env *env;
5084         int ret = -EINVAL;
5085
5086         /* 'struct bpf_verifier_env' can be global, but since it's not small,
5087          * allocate/free it every time bpf_check() is called
5088          */
5089         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5090         if (!env)
5091                 return -ENOMEM;
5092
5093         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5094                                      (*prog)->len);
5095         ret = -ENOMEM;
5096         if (!env->insn_aux_data)
5097                 goto err_free_env;
5098         env->prog = *prog;
5099
5100         /* grab the mutex to protect few globals used by verifier */
5101         mutex_lock(&bpf_verifier_lock);
5102
5103         if (attr->log_level || attr->log_buf || attr->log_size) {
5104                 /* user requested verbose verifier output
5105                  * and supplied buffer to store the verification trace
5106                  */
5107                 log_level = attr->log_level;
5108                 log_ubuf = (char __user *) (unsigned long) attr->log_buf;
5109                 log_size = attr->log_size;
5110                 log_len = 0;
5111
5112                 ret = -EINVAL;
5113                 /* log_* values have to be sane */
5114                 if (log_size < 128 || log_size > UINT_MAX >> 8 ||
5115                     log_level == 0 || log_ubuf == NULL)
5116                         goto err_unlock;
5117
5118                 ret = -ENOMEM;
5119                 log_buf = vmalloc(log_size);
5120                 if (!log_buf)
5121                         goto err_unlock;
5122         } else {
5123                 log_level = 0;
5124         }
5125
5126         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
5127         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5128                 env->strict_alignment = true;
5129
5130         ret = replace_map_fd_with_map_ptr(env);
5131         if (ret < 0)
5132                 goto skip_full_check;
5133
5134         env->explored_states = kcalloc(env->prog->len,
5135                                        sizeof(struct bpf_verifier_state_list *),
5136                                        GFP_USER);
5137         ret = -ENOMEM;
5138         if (!env->explored_states)
5139                 goto skip_full_check;
5140
5141         ret = check_cfg(env);
5142         if (ret < 0)
5143                 goto skip_full_check;
5144
5145         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5146
5147         ret = do_check(env);
5148         if (env->cur_state) {
5149                 free_verifier_state(env->cur_state, true);
5150                 env->cur_state = NULL;
5151         }
5152
5153 skip_full_check:
5154         while (!pop_stack(env, NULL, NULL));
5155         free_states(env);
5156
5157         if (ret == 0)
5158                 sanitize_dead_code(env);
5159
5160         if (ret == 0)
5161                 /* program is valid, convert *(u32*)(ctx + off) accesses */
5162                 ret = convert_ctx_accesses(env);
5163
5164         if (ret == 0)
5165                 ret = fixup_bpf_calls(env);
5166
5167         if (log_level && log_len >= log_size - 1) {
5168                 BUG_ON(log_len >= log_size);
5169                 /* verifier log exceeded user supplied buffer */
5170                 ret = -ENOSPC;
5171                 /* fall through to return what was recorded */
5172         }
5173
5174         /* copy verifier log back to user space including trailing zero */
5175         if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) {
5176                 ret = -EFAULT;
5177                 goto free_log_buf;
5178         }
5179
5180         if (ret == 0 && env->used_map_cnt) {
5181                 /* if program passed verifier, update used_maps in bpf_prog_info */
5182                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
5183                                                           sizeof(env->used_maps[0]),
5184                                                           GFP_KERNEL);
5185
5186                 if (!env->prog->aux->used_maps) {
5187                         ret = -ENOMEM;
5188                         goto free_log_buf;
5189                 }
5190
5191                 memcpy(env->prog->aux->used_maps, env->used_maps,
5192                        sizeof(env->used_maps[0]) * env->used_map_cnt);
5193                 env->prog->aux->used_map_cnt = env->used_map_cnt;
5194
5195                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
5196                  * bpf_ld_imm64 instructions
5197                  */
5198                 convert_pseudo_ld_imm64(env);
5199         }
5200
5201 free_log_buf:
5202         if (log_level)
5203                 vfree(log_buf);
5204         if (!env->prog->aux->used_maps)
5205                 /* if we didn't copy map pointers into bpf_prog_info, release
5206                  * them now. Otherwise free_used_maps() will release them.
5207                  */
5208                 release_maps(env);
5209         *prog = env->prog;
5210 err_unlock:
5211         mutex_unlock(&bpf_verifier_lock);
5212         vfree(env->insn_aux_data);
5213 err_free_env:
5214         kfree(env);
5215         return ret;
5216 }
5217
5218 int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops,
5219                  void *priv)
5220 {
5221         struct bpf_verifier_env *env;
5222         int ret;
5223
5224         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
5225         if (!env)
5226                 return -ENOMEM;
5227
5228         env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) *
5229                                      prog->len);
5230         ret = -ENOMEM;
5231         if (!env->insn_aux_data)
5232                 goto err_free_env;
5233         env->prog = prog;
5234         env->analyzer_ops = ops;
5235         env->analyzer_priv = priv;
5236
5237         /* grab the mutex to protect few globals used by verifier */
5238         mutex_lock(&bpf_verifier_lock);
5239
5240         log_level = 0;
5241
5242         env->strict_alignment = false;
5243         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
5244                 env->strict_alignment = true;
5245
5246         env->explored_states = kcalloc(env->prog->len,
5247                                        sizeof(struct bpf_verifier_state_list *),
5248                                        GFP_KERNEL);
5249         ret = -ENOMEM;
5250         if (!env->explored_states)
5251                 goto skip_full_check;
5252
5253         ret = check_cfg(env);
5254         if (ret < 0)
5255                 goto skip_full_check;
5256
5257         env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
5258
5259         ret = do_check(env);
5260         if (env->cur_state) {
5261                 free_verifier_state(env->cur_state, true);
5262                 env->cur_state = NULL;
5263         }
5264
5265 skip_full_check:
5266         while (!pop_stack(env, NULL, NULL));
5267         free_states(env);
5268
5269         mutex_unlock(&bpf_verifier_lock);
5270         vfree(env->insn_aux_data);
5271 err_free_env:
5272         kfree(env);
5273         return ret;
5274 }
5275 EXPORT_SYMBOL_GPL(bpf_analyzer);