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