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/bsearch.h>
24 #include <linux/sort.h>
25 #include <linux/perf_event.h>
26
27 #include "disasm.h"
28
29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
30 #define BPF_PROG_TYPE(_id, _name) \
31 [_id] = & _name ## _verifier_ops,
32 #define BPF_MAP_TYPE(_id, _ops)
33 #include <linux/bpf_types.h>
34 #undef BPF_PROG_TYPE
35 #undef BPF_MAP_TYPE
36 };
37
38 /* bpf_check() is a static code analyzer that walks eBPF program
39 * instruction by instruction and updates register/stack state.
40 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
41 *
42 * The first pass is depth-first-search to check that the program is a DAG.
43 * It rejects the following programs:
44 * - larger than BPF_MAXINSNS insns
45 * - if loop is present (detected via back-edge)
46 * - unreachable insns exist (shouldn't be a forest. program = one function)
47 * - out of bounds or malformed jumps
48 * The second pass is all possible path descent from the 1st insn.
49 * Since it's analyzing all pathes through the program, the length of the
50 * analysis is limited to 64k insn, which may be hit even if total number of
51 * insn is less then 4K, but there are too many branches that change stack/regs.
52 * Number of 'branches to be analyzed' is limited to 1k
53 *
54 * On entry to each instruction, each register has a type, and the instruction
55 * changes the types of the registers depending on instruction semantics.
56 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
57 * copied to R1.
58 *
59 * All registers are 64-bit.
60 * R0 - return register
61 * R1-R5 argument passing registers
62 * R6-R9 callee saved registers
63 * R10 - frame pointer read-only
64 *
65 * At the start of BPF program the register R1 contains a pointer to bpf_context
66 * and has type PTR_TO_CTX.
67 *
68 * Verifier tracks arithmetic operations on pointers in case:
69 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
70 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
71 * 1st insn copies R10 (which has FRAME_PTR) type into R1
72 * and 2nd arithmetic instruction is pattern matched to recognize
73 * that it wants to construct a pointer to some element within stack.
74 * So after 2nd insn, the register R1 has type PTR_TO_STACK
75 * (and -20 constant is saved for further stack bounds checking).
76 * Meaning that this reg is a pointer to stack plus known immediate constant.
77 *
78 * Most of the time the registers have SCALAR_VALUE type, which
79 * means the register has some value, but it's not a valid pointer.
80 * (like pointer plus pointer becomes SCALAR_VALUE type)
81 *
82 * When verifier sees load or store instructions the type of base register
83 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK. These are three pointer
84 * types recognized by check_mem_access() function.
85 *
86 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
87 * and the range of [ptr, ptr + map's value_size) is accessible.
88 *
89 * registers used to pass values to function calls are checked against
90 * function argument constraints.
91 *
92 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
93 * It means that the register type passed to this function must be
94 * PTR_TO_STACK and it will be used inside the function as
95 * 'pointer to map element key'
96 *
97 * For example the argument constraints for bpf_map_lookup_elem():
98 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
99 * .arg1_type = ARG_CONST_MAP_PTR,
100 * .arg2_type = ARG_PTR_TO_MAP_KEY,
101 *
102 * ret_type says that this function returns 'pointer to map elem value or null'
103 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
104 * 2nd argument should be a pointer to stack, which will be used inside
105 * the helper function as a pointer to map element key.
106 *
107 * On the kernel side the helper function looks like:
108 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
109 * {
110 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
111 * void *key = (void *) (unsigned long) r2;
112 * void *value;
113 *
114 * here kernel can access 'key' and 'map' pointers safely, knowing that
115 * [key, key + map->key_size) bytes are valid and were initialized on
116 * the stack of eBPF program.
117 * }
118 *
119 * Corresponding eBPF program may look like:
120 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
121 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
122 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
123 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
124 * here verifier looks at prototype of map_lookup_elem() and sees:
125 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
126 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
127 *
128 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
129 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
130 * and were initialized prior to this call.
131 * If it's ok, then verifier allows this BPF_CALL insn and looks at
132 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
133 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
134 * returns ether pointer to map value or NULL.
135 *
136 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
137 * insn, the register holding that pointer in the true branch changes state to
138 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
139 * branch. See check_cond_jmp_op().
140 *
141 * After the call R0 is set to return type of the function and registers R1-R5
142 * are set to NOT_INIT to indicate that they are no longer readable.
143 */
144
145 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
146 struct bpf_verifier_stack_elem {
147 /* verifer state is 'st'
148 * before processing instruction 'insn_idx'
149 * and after processing instruction 'prev_insn_idx'
150 */
151 struct bpf_verifier_state st;
152 int insn_idx;
153 int prev_insn_idx;
154 struct bpf_verifier_stack_elem *next;
155 };
156
157 #define BPF_COMPLEXITY_LIMIT_INSNS 131072
158 #define BPF_COMPLEXITY_LIMIT_STACK 1024
159 #define BPF_COMPLEXITY_LIMIT_STATES 64
160
161 #define BPF_MAP_PTR_UNPRIV 1UL
162 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
163 POISON_POINTER_DELTA))
164 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
165
bpf_map_ptr_poisoned(const struct bpf_insn_aux_data * aux)166 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
167 {
168 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON;
169 }
170
bpf_map_ptr_unpriv(const struct bpf_insn_aux_data * aux)171 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
172 {
173 return aux->map_state & BPF_MAP_PTR_UNPRIV;
174 }
175
bpf_map_ptr_store(struct bpf_insn_aux_data * aux,const struct bpf_map * map,bool unpriv)176 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
177 const struct bpf_map *map, bool unpriv)
178 {
179 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
180 unpriv |= bpf_map_ptr_unpriv(aux);
181 aux->map_state = (unsigned long)map |
182 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
183 }
184
185 struct bpf_call_arg_meta {
186 struct bpf_map *map_ptr;
187 bool raw_mode;
188 bool pkt_access;
189 int regno;
190 int access_size;
191 u64 msize_max_value;
192 };
193
194 static DEFINE_MUTEX(bpf_verifier_lock);
195
bpf_verifier_vlog(struct bpf_verifier_log * log,const char * fmt,va_list args)196 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
197 va_list args)
198 {
199 unsigned int n;
200
201 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
202
203 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
204 "verifier log line truncated - local buffer too short\n");
205
206 n = min(log->len_total - log->len_used - 1, n);
207 log->kbuf[n] = '\0';
208
209 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
210 log->len_used += n;
211 else
212 log->ubuf = NULL;
213 }
214
215 /* log_level controls verbosity level of eBPF verifier.
216 * bpf_verifier_log_write() is used to dump the verification trace to the log,
217 * so the user can figure out what's wrong with the program
218 */
bpf_verifier_log_write(struct bpf_verifier_env * env,const char * fmt,...)219 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
220 const char *fmt, ...)
221 {
222 va_list args;
223
224 if (!bpf_verifier_log_needed(&env->log))
225 return;
226
227 va_start(args, fmt);
228 bpf_verifier_vlog(&env->log, fmt, args);
229 va_end(args);
230 }
231 EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
232
verbose(void * private_data,const char * fmt,...)233 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
234 {
235 struct bpf_verifier_env *env = private_data;
236 va_list args;
237
238 if (!bpf_verifier_log_needed(&env->log))
239 return;
240
241 va_start(args, fmt);
242 bpf_verifier_vlog(&env->log, fmt, args);
243 va_end(args);
244 }
245
type_is_pkt_pointer(enum bpf_reg_type type)246 static bool type_is_pkt_pointer(enum bpf_reg_type type)
247 {
248 return type == PTR_TO_PACKET ||
249 type == PTR_TO_PACKET_META;
250 }
251
252 /* string representation of 'enum bpf_reg_type' */
253 static const char * const reg_type_str[] = {
254 [NOT_INIT] = "?",
255 [SCALAR_VALUE] = "inv",
256 [PTR_TO_CTX] = "ctx",
257 [CONST_PTR_TO_MAP] = "map_ptr",
258 [PTR_TO_MAP_VALUE] = "map_value",
259 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
260 [PTR_TO_STACK] = "fp",
261 [PTR_TO_PACKET] = "pkt",
262 [PTR_TO_PACKET_META] = "pkt_meta",
263 [PTR_TO_PACKET_END] = "pkt_end",
264 };
265
print_liveness(struct bpf_verifier_env * env,enum bpf_reg_liveness live)266 static void print_liveness(struct bpf_verifier_env *env,
267 enum bpf_reg_liveness live)
268 {
269 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN))
270 verbose(env, "_");
271 if (live & REG_LIVE_READ)
272 verbose(env, "r");
273 if (live & REG_LIVE_WRITTEN)
274 verbose(env, "w");
275 }
276
func(struct bpf_verifier_env * env,const struct bpf_reg_state * reg)277 static struct bpf_func_state *func(struct bpf_verifier_env *env,
278 const struct bpf_reg_state *reg)
279 {
280 struct bpf_verifier_state *cur = env->cur_state;
281
282 return cur->frame[reg->frameno];
283 }
284
print_verifier_state(struct bpf_verifier_env * env,const struct bpf_func_state * state)285 static void print_verifier_state(struct bpf_verifier_env *env,
286 const struct bpf_func_state *state)
287 {
288 const struct bpf_reg_state *reg;
289 enum bpf_reg_type t;
290 int i;
291
292 if (state->frameno)
293 verbose(env, " frame%d:", state->frameno);
294 for (i = 0; i < MAX_BPF_REG; i++) {
295 reg = &state->regs[i];
296 t = reg->type;
297 if (t == NOT_INIT)
298 continue;
299 verbose(env, " R%d", i);
300 print_liveness(env, reg->live);
301 verbose(env, "=%s", reg_type_str[t]);
302 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
303 tnum_is_const(reg->var_off)) {
304 /* reg->off should be 0 for SCALAR_VALUE */
305 verbose(env, "%lld", reg->var_off.value + reg->off);
306 if (t == PTR_TO_STACK)
307 verbose(env, ",call_%d", func(env, reg)->callsite);
308 } else {
309 verbose(env, "(id=%d", reg->id);
310 if (t != SCALAR_VALUE)
311 verbose(env, ",off=%d", reg->off);
312 if (type_is_pkt_pointer(t))
313 verbose(env, ",r=%d", reg->range);
314 else if (t == CONST_PTR_TO_MAP ||
315 t == PTR_TO_MAP_VALUE ||
316 t == PTR_TO_MAP_VALUE_OR_NULL)
317 verbose(env, ",ks=%d,vs=%d",
318 reg->map_ptr->key_size,
319 reg->map_ptr->value_size);
320 if (tnum_is_const(reg->var_off)) {
321 /* Typically an immediate SCALAR_VALUE, but
322 * could be a pointer whose offset is too big
323 * for reg->off
324 */
325 verbose(env, ",imm=%llx", reg->var_off.value);
326 } else {
327 if (reg->smin_value != reg->umin_value &&
328 reg->smin_value != S64_MIN)
329 verbose(env, ",smin_value=%lld",
330 (long long)reg->smin_value);
331 if (reg->smax_value != reg->umax_value &&
332 reg->smax_value != S64_MAX)
333 verbose(env, ",smax_value=%lld",
334 (long long)reg->smax_value);
335 if (reg->umin_value != 0)
336 verbose(env, ",umin_value=%llu",
337 (unsigned long long)reg->umin_value);
338 if (reg->umax_value != U64_MAX)
339 verbose(env, ",umax_value=%llu",
340 (unsigned long long)reg->umax_value);
341 if (!tnum_is_unknown(reg->var_off)) {
342 char tn_buf[48];
343
344 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
345 verbose(env, ",var_off=%s", tn_buf);
346 }
347 }
348 verbose(env, ")");
349 }
350 }
351 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
352 if (state->stack[i].slot_type[0] == STACK_SPILL) {
353 verbose(env, " fp%d",
354 (-i - 1) * BPF_REG_SIZE);
355 print_liveness(env, state->stack[i].spilled_ptr.live);
356 verbose(env, "=%s",
357 reg_type_str[state->stack[i].spilled_ptr.type]);
358 }
359 if (state->stack[i].slot_type[0] == STACK_ZERO)
360 verbose(env, " fp%d=0", (-i - 1) * BPF_REG_SIZE);
361 }
362 verbose(env, "\n");
363 }
364
copy_stack_state(struct bpf_func_state * dst,const struct bpf_func_state * src)365 static int copy_stack_state(struct bpf_func_state *dst,
366 const struct bpf_func_state *src)
367 {
368 if (!src->stack)
369 return 0;
370 if (WARN_ON_ONCE(dst->allocated_stack < src->allocated_stack)) {
371 /* internal bug, make state invalid to reject the program */
372 memset(dst, 0, sizeof(*dst));
373 return -EFAULT;
374 }
375 memcpy(dst->stack, src->stack,
376 sizeof(*src->stack) * (src->allocated_stack / BPF_REG_SIZE));
377 return 0;
378 }
379
380 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to
381 * make it consume minimal amount of memory. check_stack_write() access from
382 * the program calls into realloc_func_state() to grow the stack size.
383 * Note there is a non-zero parent pointer inside each reg of bpf_verifier_state
384 * which this function copies over. It points to corresponding reg in previous
385 * bpf_verifier_state which is never reallocated
386 */
realloc_func_state(struct bpf_func_state * state,int size,bool copy_old)387 static int realloc_func_state(struct bpf_func_state *state, int size,
388 bool copy_old)
389 {
390 u32 old_size = state->allocated_stack;
391 struct bpf_stack_state *new_stack;
392 int slot = size / BPF_REG_SIZE;
393
394 if (size <= old_size || !size) {
395 if (copy_old)
396 return 0;
397 state->allocated_stack = slot * BPF_REG_SIZE;
398 if (!size && old_size) {
399 kfree(state->stack);
400 state->stack = NULL;
401 }
402 return 0;
403 }
404 new_stack = kmalloc_array(slot, sizeof(struct bpf_stack_state),
405 GFP_KERNEL);
406 if (!new_stack)
407 return -ENOMEM;
408 if (copy_old) {
409 if (state->stack)
410 memcpy(new_stack, state->stack,
411 sizeof(*new_stack) * (old_size / BPF_REG_SIZE));
412 memset(new_stack + old_size / BPF_REG_SIZE, 0,
413 sizeof(*new_stack) * (size - old_size) / BPF_REG_SIZE);
414 }
415 state->allocated_stack = slot * BPF_REG_SIZE;
416 kfree(state->stack);
417 state->stack = new_stack;
418 return 0;
419 }
420
free_func_state(struct bpf_func_state * state)421 static void free_func_state(struct bpf_func_state *state)
422 {
423 if (!state)
424 return;
425 kfree(state->stack);
426 kfree(state);
427 }
428
free_verifier_state(struct bpf_verifier_state * state,bool free_self)429 static void free_verifier_state(struct bpf_verifier_state *state,
430 bool free_self)
431 {
432 int i;
433
434 for (i = 0; i <= state->curframe; i++) {
435 free_func_state(state->frame[i]);
436 state->frame[i] = NULL;
437 }
438 if (free_self)
439 kfree(state);
440 }
441
442 /* copy verifier state from src to dst growing dst stack space
443 * when necessary to accommodate larger src stack
444 */
copy_func_state(struct bpf_func_state * dst,const struct bpf_func_state * src)445 static int copy_func_state(struct bpf_func_state *dst,
446 const struct bpf_func_state *src)
447 {
448 int err;
449
450 err = realloc_func_state(dst, src->allocated_stack, false);
451 if (err)
452 return err;
453 memcpy(dst, src, offsetof(struct bpf_func_state, allocated_stack));
454 return copy_stack_state(dst, src);
455 }
456
copy_verifier_state(struct bpf_verifier_state * dst_state,const struct bpf_verifier_state * src)457 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
458 const struct bpf_verifier_state *src)
459 {
460 struct bpf_func_state *dst;
461 int i, err;
462
463 /* if dst has more stack frames then src frame, free them */
464 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
465 free_func_state(dst_state->frame[i]);
466 dst_state->frame[i] = NULL;
467 }
468 dst_state->speculative = src->speculative;
469 dst_state->curframe = src->curframe;
470 for (i = 0; i <= src->curframe; i++) {
471 dst = dst_state->frame[i];
472 if (!dst) {
473 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
474 if (!dst)
475 return -ENOMEM;
476 dst_state->frame[i] = dst;
477 }
478 err = copy_func_state(dst, src->frame[i]);
479 if (err)
480 return err;
481 }
482 return 0;
483 }
484
pop_stack(struct bpf_verifier_env * env,int * prev_insn_idx,int * insn_idx)485 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
486 int *insn_idx)
487 {
488 struct bpf_verifier_state *cur = env->cur_state;
489 struct bpf_verifier_stack_elem *elem, *head = env->head;
490 int err;
491
492 if (env->head == NULL)
493 return -ENOENT;
494
495 if (cur) {
496 err = copy_verifier_state(cur, &head->st);
497 if (err)
498 return err;
499 }
500 if (insn_idx)
501 *insn_idx = head->insn_idx;
502 if (prev_insn_idx)
503 *prev_insn_idx = head->prev_insn_idx;
504 elem = head->next;
505 free_verifier_state(&head->st, false);
506 kfree(head);
507 env->head = elem;
508 env->stack_size--;
509 return 0;
510 }
511
push_stack(struct bpf_verifier_env * env,int insn_idx,int prev_insn_idx,bool speculative)512 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
513 int insn_idx, int prev_insn_idx,
514 bool speculative)
515 {
516 struct bpf_verifier_state *cur = env->cur_state;
517 struct bpf_verifier_stack_elem *elem;
518 int err;
519
520 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
521 if (!elem)
522 goto err;
523
524 elem->insn_idx = insn_idx;
525 elem->prev_insn_idx = prev_insn_idx;
526 elem->next = env->head;
527 env->head = elem;
528 env->stack_size++;
529 err = copy_verifier_state(&elem->st, cur);
530 if (err)
531 goto err;
532 elem->st.speculative |= speculative;
533 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) {
534 verbose(env, "BPF program is too complex\n");
535 goto err;
536 }
537 return &elem->st;
538 err:
539 free_verifier_state(env->cur_state, true);
540 env->cur_state = NULL;
541 /* pop all elements and return */
542 while (!pop_stack(env, NULL, NULL));
543 return NULL;
544 }
545
546 #define CALLER_SAVED_REGS 6
547 static const int caller_saved[CALLER_SAVED_REGS] = {
548 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
549 };
550
551 static void __mark_reg_not_init(struct bpf_reg_state *reg);
552
553 /* Mark the unknown part of a register (variable offset or scalar value) as
554 * known to have the value @imm.
555 */
__mark_reg_known(struct bpf_reg_state * reg,u64 imm)556 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
557 {
558 /* Clear id, off, and union(map_ptr, range) */
559 memset(((u8 *)reg) + sizeof(reg->type), 0,
560 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
561 reg->var_off = tnum_const(imm);
562 reg->smin_value = (s64)imm;
563 reg->smax_value = (s64)imm;
564 reg->umin_value = imm;
565 reg->umax_value = imm;
566 }
567
568 /* Mark the 'variable offset' part of a register as zero. This should be
569 * used only on registers holding a pointer type.
570 */
__mark_reg_known_zero(struct bpf_reg_state * reg)571 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
572 {
573 __mark_reg_known(reg, 0);
574 }
575
__mark_reg_const_zero(struct bpf_reg_state * reg)576 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
577 {
578 __mark_reg_known(reg, 0);
579 reg->type = SCALAR_VALUE;
580 }
581
mark_reg_known_zero(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)582 static void mark_reg_known_zero(struct bpf_verifier_env *env,
583 struct bpf_reg_state *regs, u32 regno)
584 {
585 if (WARN_ON(regno >= MAX_BPF_REG)) {
586 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
587 /* Something bad happened, let's kill all regs */
588 for (regno = 0; regno < MAX_BPF_REG; regno++)
589 __mark_reg_not_init(regs + regno);
590 return;
591 }
592 __mark_reg_known_zero(regs + regno);
593 }
594
reg_is_pkt_pointer(const struct bpf_reg_state * reg)595 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
596 {
597 return type_is_pkt_pointer(reg->type);
598 }
599
reg_is_pkt_pointer_any(const struct bpf_reg_state * reg)600 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
601 {
602 return reg_is_pkt_pointer(reg) ||
603 reg->type == PTR_TO_PACKET_END;
604 }
605
606 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
reg_is_init_pkt_pointer(const struct bpf_reg_state * reg,enum bpf_reg_type which)607 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
608 enum bpf_reg_type which)
609 {
610 /* The register can already have a range from prior markings.
611 * This is fine as long as it hasn't been advanced from its
612 * origin.
613 */
614 return reg->type == which &&
615 reg->id == 0 &&
616 reg->off == 0 &&
617 tnum_equals_const(reg->var_off, 0);
618 }
619
620 /* Attempts to improve min/max values based on var_off information */
__update_reg_bounds(struct bpf_reg_state * reg)621 static void __update_reg_bounds(struct bpf_reg_state *reg)
622 {
623 /* min signed is max(sign bit) | min(other bits) */
624 reg->smin_value = max_t(s64, reg->smin_value,
625 reg->var_off.value | (reg->var_off.mask & S64_MIN));
626 /* max signed is min(sign bit) | max(other bits) */
627 reg->smax_value = min_t(s64, reg->smax_value,
628 reg->var_off.value | (reg->var_off.mask & S64_MAX));
629 reg->umin_value = max(reg->umin_value, reg->var_off.value);
630 reg->umax_value = min(reg->umax_value,
631 reg->var_off.value | reg->var_off.mask);
632 }
633
634 /* Uses signed min/max values to inform unsigned, and vice-versa */
__reg_deduce_bounds(struct bpf_reg_state * reg)635 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
636 {
637 /* Learn sign from signed bounds.
638 * If we cannot cross the sign boundary, then signed and unsigned bounds
639 * are the same, so combine. This works even in the negative case, e.g.
640 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
641 */
642 if (reg->smin_value >= 0 || reg->smax_value < 0) {
643 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
644 reg->umin_value);
645 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
646 reg->umax_value);
647 return;
648 }
649 /* Learn sign from unsigned bounds. Signed bounds cross the sign
650 * boundary, so we must be careful.
651 */
652 if ((s64)reg->umax_value >= 0) {
653 /* Positive. We can't learn anything from the smin, but smax
654 * is positive, hence safe.
655 */
656 reg->smin_value = reg->umin_value;
657 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
658 reg->umax_value);
659 } else if ((s64)reg->umin_value < 0) {
660 /* Negative. We can't learn anything from the smax, but smin
661 * is negative, hence safe.
662 */
663 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
664 reg->umin_value);
665 reg->smax_value = reg->umax_value;
666 }
667 }
668
669 /* Attempts to improve var_off based on unsigned min/max information */
__reg_bound_offset(struct bpf_reg_state * reg)670 static void __reg_bound_offset(struct bpf_reg_state *reg)
671 {
672 reg->var_off = tnum_intersect(reg->var_off,
673 tnum_range(reg->umin_value,
674 reg->umax_value));
675 }
676
677 /* Reset the min/max bounds of a register */
__mark_reg_unbounded(struct bpf_reg_state * reg)678 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
679 {
680 reg->smin_value = S64_MIN;
681 reg->smax_value = S64_MAX;
682 reg->umin_value = 0;
683 reg->umax_value = U64_MAX;
684 }
685
686 /* Mark a register as having a completely unknown (scalar) value. */
__mark_reg_unknown(struct bpf_reg_state * reg)687 static void __mark_reg_unknown(struct bpf_reg_state *reg)
688 {
689 /*
690 * Clear type, id, off, and union(map_ptr, range) and
691 * padding between 'type' and union
692 */
693 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
694 reg->type = SCALAR_VALUE;
695 reg->var_off = tnum_unknown;
696 reg->frameno = 0;
697 __mark_reg_unbounded(reg);
698 }
699
mark_reg_unknown(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)700 static void mark_reg_unknown(struct bpf_verifier_env *env,
701 struct bpf_reg_state *regs, u32 regno)
702 {
703 if (WARN_ON(regno >= MAX_BPF_REG)) {
704 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
705 /* Something bad happened, let's kill all regs except FP */
706 for (regno = 0; regno < BPF_REG_FP; regno++)
707 __mark_reg_not_init(regs + regno);
708 return;
709 }
710 __mark_reg_unknown(regs + regno);
711 }
712
__mark_reg_not_init(struct bpf_reg_state * reg)713 static void __mark_reg_not_init(struct bpf_reg_state *reg)
714 {
715 __mark_reg_unknown(reg);
716 reg->type = NOT_INIT;
717 }
718
mark_reg_not_init(struct bpf_verifier_env * env,struct bpf_reg_state * regs,u32 regno)719 static void mark_reg_not_init(struct bpf_verifier_env *env,
720 struct bpf_reg_state *regs, u32 regno)
721 {
722 if (WARN_ON(regno >= MAX_BPF_REG)) {
723 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
724 /* Something bad happened, let's kill all regs except FP */
725 for (regno = 0; regno < BPF_REG_FP; regno++)
726 __mark_reg_not_init(regs + regno);
727 return;
728 }
729 __mark_reg_not_init(regs + regno);
730 }
731
init_reg_state(struct bpf_verifier_env * env,struct bpf_func_state * state)732 static void init_reg_state(struct bpf_verifier_env *env,
733 struct bpf_func_state *state)
734 {
735 struct bpf_reg_state *regs = state->regs;
736 int i;
737
738 for (i = 0; i < MAX_BPF_REG; i++) {
739 mark_reg_not_init(env, regs, i);
740 regs[i].live = REG_LIVE_NONE;
741 regs[i].parent = NULL;
742 }
743
744 /* frame pointer */
745 regs[BPF_REG_FP].type = PTR_TO_STACK;
746 mark_reg_known_zero(env, regs, BPF_REG_FP);
747 regs[BPF_REG_FP].frameno = state->frameno;
748
749 /* 1st arg to a function */
750 regs[BPF_REG_1].type = PTR_TO_CTX;
751 mark_reg_known_zero(env, regs, BPF_REG_1);
752 }
753
754 #define BPF_MAIN_FUNC (-1)
init_func_state(struct bpf_verifier_env * env,struct bpf_func_state * state,int callsite,int frameno,int subprogno)755 static void init_func_state(struct bpf_verifier_env *env,
756 struct bpf_func_state *state,
757 int callsite, int frameno, int subprogno)
758 {
759 state->callsite = callsite;
760 state->frameno = frameno;
761 state->subprogno = subprogno;
762 init_reg_state(env, state);
763 }
764
765 enum reg_arg_type {
766 SRC_OP, /* register is used as source operand */
767 DST_OP, /* register is used as destination operand */
768 DST_OP_NO_MARK /* same as above, check only, don't mark */
769 };
770
cmp_subprogs(const void * a,const void * b)771 static int cmp_subprogs(const void *a, const void *b)
772 {
773 return ((struct bpf_subprog_info *)a)->start -
774 ((struct bpf_subprog_info *)b)->start;
775 }
776
find_subprog(struct bpf_verifier_env * env,int off)777 static int find_subprog(struct bpf_verifier_env *env, int off)
778 {
779 struct bpf_subprog_info *p;
780
781 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
782 sizeof(env->subprog_info[0]), cmp_subprogs);
783 if (!p)
784 return -ENOENT;
785 return p - env->subprog_info;
786
787 }
788
add_subprog(struct bpf_verifier_env * env,int off)789 static int add_subprog(struct bpf_verifier_env *env, int off)
790 {
791 int insn_cnt = env->prog->len;
792 int ret;
793
794 if (off >= insn_cnt || off < 0) {
795 verbose(env, "call to invalid destination\n");
796 return -EINVAL;
797 }
798 ret = find_subprog(env, off);
799 if (ret >= 0)
800 return 0;
801 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
802 verbose(env, "too many subprograms\n");
803 return -E2BIG;
804 }
805 env->subprog_info[env->subprog_cnt++].start = off;
806 sort(env->subprog_info, env->subprog_cnt,
807 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
808 return 0;
809 }
810
check_subprogs(struct bpf_verifier_env * env)811 static int check_subprogs(struct bpf_verifier_env *env)
812 {
813 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
814 struct bpf_subprog_info *subprog = env->subprog_info;
815 struct bpf_insn *insn = env->prog->insnsi;
816 int insn_cnt = env->prog->len;
817
818 /* Add entry function. */
819 ret = add_subprog(env, 0);
820 if (ret < 0)
821 return ret;
822
823 /* determine subprog starts. The end is one before the next starts */
824 for (i = 0; i < insn_cnt; i++) {
825 if (insn[i].code != (BPF_JMP | BPF_CALL))
826 continue;
827 if (insn[i].src_reg != BPF_PSEUDO_CALL)
828 continue;
829 if (!env->allow_ptr_leaks) {
830 verbose(env, "function calls to other bpf functions are allowed for root only\n");
831 return -EPERM;
832 }
833 if (bpf_prog_is_dev_bound(env->prog->aux)) {
834 verbose(env, "function calls in offloaded programs are not supported yet\n");
835 return -EINVAL;
836 }
837 ret = add_subprog(env, i + insn[i].imm + 1);
838 if (ret < 0)
839 return ret;
840 }
841
842 /* Add a fake 'exit' subprog which could simplify subprog iteration
843 * logic. 'subprog_cnt' should not be increased.
844 */
845 subprog[env->subprog_cnt].start = insn_cnt;
846
847 if (env->log.level > 1)
848 for (i = 0; i < env->subprog_cnt; i++)
849 verbose(env, "func#%d @%d\n", i, subprog[i].start);
850
851 /* now check that all jumps are within the same subprog */
852 subprog_start = subprog[cur_subprog].start;
853 subprog_end = subprog[cur_subprog + 1].start;
854 for (i = 0; i < insn_cnt; i++) {
855 u8 code = insn[i].code;
856
857 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
858 goto next;
859 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
860 goto next;
861 off = i + insn[i].off + 1;
862 if (off < subprog_start || off >= subprog_end) {
863 verbose(env, "jump out of range from insn %d to %d\n", i, off);
864 return -EINVAL;
865 }
866 next:
867 if (i == subprog_end - 1) {
868 /* to avoid fall-through from one subprog into another
869 * the last insn of the subprog should be either exit
870 * or unconditional jump back
871 */
872 if (code != (BPF_JMP | BPF_EXIT) &&
873 code != (BPF_JMP | BPF_JA)) {
874 verbose(env, "last insn is not an exit or jmp\n");
875 return -EINVAL;
876 }
877 subprog_start = subprog_end;
878 cur_subprog++;
879 if (cur_subprog < env->subprog_cnt)
880 subprog_end = subprog[cur_subprog + 1].start;
881 }
882 }
883 return 0;
884 }
885
886 /* Parentage chain of this register (or stack slot) should take care of all
887 * issues like callee-saved registers, stack slot allocation time, etc.
888 */
mark_reg_read(struct bpf_verifier_env * env,const struct bpf_reg_state * state,struct bpf_reg_state * parent)889 static int mark_reg_read(struct bpf_verifier_env *env,
890 const struct bpf_reg_state *state,
891 struct bpf_reg_state *parent)
892 {
893 bool writes = parent == state->parent; /* Observe write marks */
894
895 while (parent) {
896 /* if read wasn't screened by an earlier write ... */
897 if (writes && state->live & REG_LIVE_WRITTEN)
898 break;
899 /* ... then we depend on parent's value */
900 parent->live |= REG_LIVE_READ;
901 state = parent;
902 parent = state->parent;
903 writes = true;
904 }
905 return 0;
906 }
907
check_reg_arg(struct bpf_verifier_env * env,u32 regno,enum reg_arg_type t)908 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
909 enum reg_arg_type t)
910 {
911 struct bpf_verifier_state *vstate = env->cur_state;
912 struct bpf_func_state *state = vstate->frame[vstate->curframe];
913 struct bpf_reg_state *regs = state->regs;
914
915 if (regno >= MAX_BPF_REG) {
916 verbose(env, "R%d is invalid\n", regno);
917 return -EINVAL;
918 }
919
920 if (t == SRC_OP) {
921 /* check whether register used as source operand can be read */
922 if (regs[regno].type == NOT_INIT) {
923 verbose(env, "R%d !read_ok\n", regno);
924 return -EACCES;
925 }
926 /* We don't need to worry about FP liveness because it's read-only */
927 if (regno != BPF_REG_FP)
928 return mark_reg_read(env, ®s[regno],
929 regs[regno].parent);
930 } else {
931 /* check whether register used as dest operand can be written to */
932 if (regno == BPF_REG_FP) {
933 verbose(env, "frame pointer is read only\n");
934 return -EACCES;
935 }
936 regs[regno].live |= REG_LIVE_WRITTEN;
937 if (t == DST_OP)
938 mark_reg_unknown(env, regs, regno);
939 }
940 return 0;
941 }
942
is_spillable_regtype(enum bpf_reg_type type)943 static bool is_spillable_regtype(enum bpf_reg_type type)
944 {
945 switch (type) {
946 case PTR_TO_MAP_VALUE:
947 case PTR_TO_MAP_VALUE_OR_NULL:
948 case PTR_TO_STACK:
949 case PTR_TO_CTX:
950 case PTR_TO_PACKET:
951 case PTR_TO_PACKET_META:
952 case PTR_TO_PACKET_END:
953 case CONST_PTR_TO_MAP:
954 return true;
955 default:
956 return false;
957 }
958 }
959
960 /* Does this register contain a constant zero? */
register_is_null(struct bpf_reg_state * reg)961 static bool register_is_null(struct bpf_reg_state *reg)
962 {
963 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
964 }
965
register_is_const(struct bpf_reg_state * reg)966 static bool register_is_const(struct bpf_reg_state *reg)
967 {
968 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
969 }
970
save_register_state(struct bpf_func_state * state,int spi,struct bpf_reg_state * reg)971 static void save_register_state(struct bpf_func_state *state,
972 int spi, struct bpf_reg_state *reg)
973 {
974 int i;
975
976 state->stack[spi].spilled_ptr = *reg;
977 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
978
979 for (i = 0; i < BPF_REG_SIZE; i++)
980 state->stack[spi].slot_type[i] = STACK_SPILL;
981 }
982
983 /* check_stack_read/write functions track spill/fill of registers,
984 * stack boundary and alignment are checked in check_mem_access()
985 */
check_stack_write(struct bpf_verifier_env * env,struct bpf_func_state * state,int off,int size,int value_regno,int insn_idx)986 static int check_stack_write(struct bpf_verifier_env *env,
987 struct bpf_func_state *state, /* func where register points to */
988 int off, int size, int value_regno, int insn_idx)
989 {
990 struct bpf_func_state *cur; /* state of the current function */
991 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
992 struct bpf_reg_state *reg = NULL;
993
994 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
995 true);
996 if (err)
997 return err;
998 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
999 * so it's aligned access and [off, off + size) are within stack limits
1000 */
1001 if (!env->allow_ptr_leaks &&
1002 state->stack[spi].slot_type[0] == STACK_SPILL &&
1003 size != BPF_REG_SIZE) {
1004 verbose(env, "attempt to corrupt spilled pointer on stack\n");
1005 return -EACCES;
1006 }
1007
1008 cur = env->cur_state->frame[env->cur_state->curframe];
1009 if (value_regno >= 0)
1010 reg = &cur->regs[value_regno];
1011 if (!env->allow_ptr_leaks) {
1012 bool sanitize = reg && is_spillable_regtype(reg->type);
1013
1014 for (i = 0; i < size; i++) {
1015 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
1016 sanitize = true;
1017 break;
1018 }
1019 }
1020
1021 if (sanitize)
1022 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
1023 }
1024
1025 if (reg && size == BPF_REG_SIZE && register_is_const(reg) &&
1026 !register_is_null(reg) && env->allow_ptr_leaks) {
1027 save_register_state(state, spi, reg);
1028 } else if (reg && is_spillable_regtype(reg->type)) {
1029 /* register containing pointer is being spilled into stack */
1030 if (size != BPF_REG_SIZE) {
1031 verbose(env, "invalid size of register spill\n");
1032 return -EACCES;
1033 }
1034
1035 if (state != cur && reg->type == PTR_TO_STACK) {
1036 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
1037 return -EINVAL;
1038 }
1039 save_register_state(state, spi, reg);
1040 } else {
1041 u8 type = STACK_MISC;
1042
1043 /* regular write of data into stack destroys any spilled ptr */
1044 state->stack[spi].spilled_ptr.type = NOT_INIT;
1045
1046 /* only mark the slot as written if all 8 bytes were written
1047 * otherwise read propagation may incorrectly stop too soon
1048 * when stack slots are partially written.
1049 * This heuristic means that read propagation will be
1050 * conservative, since it will add reg_live_read marks
1051 * to stack slots all the way to first state when programs
1052 * writes+reads less than 8 bytes
1053 */
1054 if (size == BPF_REG_SIZE)
1055 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1056
1057 /* when we zero initialize stack slots mark them as such */
1058 if (reg && register_is_null(reg))
1059 type = STACK_ZERO;
1060
1061 for (i = 0; i < size; i++)
1062 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
1063 type;
1064 }
1065 return 0;
1066 }
1067
check_stack_read(struct bpf_verifier_env * env,struct bpf_func_state * reg_state,int off,int size,int value_regno)1068 static int check_stack_read(struct bpf_verifier_env *env,
1069 struct bpf_func_state *reg_state /* func where register points to */,
1070 int off, int size, int value_regno)
1071 {
1072 struct bpf_verifier_state *vstate = env->cur_state;
1073 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1074 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
1075 struct bpf_reg_state *reg;
1076 u8 *stype;
1077
1078 if (reg_state->allocated_stack <= slot) {
1079 verbose(env, "invalid read from stack off %d+0 size %d\n",
1080 off, size);
1081 return -EACCES;
1082 }
1083 stype = reg_state->stack[spi].slot_type;
1084 reg = ®_state->stack[spi].spilled_ptr;
1085
1086 if (stype[0] == STACK_SPILL) {
1087 if (size != BPF_REG_SIZE) {
1088 if (reg->type != SCALAR_VALUE) {
1089 verbose(env, "invalid size of register fill\n");
1090 return -EACCES;
1091 }
1092 if (value_regno >= 0) {
1093 mark_reg_unknown(env, state->regs, value_regno);
1094 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1095 }
1096 mark_reg_read(env, reg, reg->parent);
1097 return 0;
1098 }
1099 for (i = 1; i < BPF_REG_SIZE; i++) {
1100 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
1101 verbose(env, "corrupted spill memory\n");
1102 return -EACCES;
1103 }
1104 }
1105
1106 if (value_regno >= 0) {
1107 /* restore register state from stack */
1108 state->regs[value_regno] = *reg;
1109 /* mark reg as written since spilled pointer state likely
1110 * has its liveness marks cleared by is_state_visited()
1111 * which resets stack/reg liveness for state transitions
1112 */
1113 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1114 }
1115 mark_reg_read(env, reg, reg->parent);
1116 } else {
1117 int zeros = 0;
1118
1119 for (i = 0; i < size; i++) {
1120 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC)
1121 continue;
1122 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) {
1123 zeros++;
1124 continue;
1125 }
1126 verbose(env, "invalid read from stack off %d+%d size %d\n",
1127 off, i, size);
1128 return -EACCES;
1129 }
1130 mark_reg_read(env, reg, reg->parent);
1131 if (value_regno >= 0) {
1132 if (zeros == size) {
1133 /* any size read into register is zero extended,
1134 * so the whole register == const_zero
1135 */
1136 __mark_reg_const_zero(&state->regs[value_regno]);
1137 } else {
1138 /* have read misc data from the stack */
1139 mark_reg_unknown(env, state->regs, value_regno);
1140 }
1141 state->regs[value_regno].live |= REG_LIVE_WRITTEN;
1142 }
1143 }
1144 return 0;
1145 }
1146
check_stack_access(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size)1147 static int check_stack_access(struct bpf_verifier_env *env,
1148 const struct bpf_reg_state *reg,
1149 int off, int size)
1150 {
1151 /* Stack accesses must be at a fixed offset, so that we
1152 * can determine what type of data were returned. See
1153 * check_stack_read().
1154 */
1155 if (!tnum_is_const(reg->var_off)) {
1156 char tn_buf[48];
1157
1158 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1159 verbose(env, "variable stack access var_off=%s off=%d size=%d\n",
1160 tn_buf, off, size);
1161 return -EACCES;
1162 }
1163
1164 if (off >= 0 || off < -MAX_BPF_STACK) {
1165 verbose(env, "invalid stack off=%d size=%d\n", off, size);
1166 return -EACCES;
1167 }
1168
1169 return 0;
1170 }
1171
1172 /* check read/write into map element returned by bpf_map_lookup_elem() */
__check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)1173 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off,
1174 int size, bool zero_size_allowed)
1175 {
1176 struct bpf_reg_state *regs = cur_regs(env);
1177 struct bpf_map *map = regs[regno].map_ptr;
1178
1179 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1180 off + size > map->value_size) {
1181 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
1182 map->value_size, off, size);
1183 return -EACCES;
1184 }
1185 return 0;
1186 }
1187
1188 /* check read/write into a map element with possible variable offset */
check_map_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)1189 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
1190 int off, int size, bool zero_size_allowed)
1191 {
1192 struct bpf_verifier_state *vstate = env->cur_state;
1193 struct bpf_func_state *state = vstate->frame[vstate->curframe];
1194 struct bpf_reg_state *reg = &state->regs[regno];
1195 int err;
1196
1197 /* We may have adjusted the register to this map value, so we
1198 * need to try adding each of min_value and max_value to off
1199 * to make sure our theoretical access will be safe.
1200 */
1201 if (env->log.level)
1202 print_verifier_state(env, state);
1203
1204 /* The minimum value is only important with signed
1205 * comparisons where we can't assume the floor of a
1206 * value is 0. If we are using signed variables for our
1207 * index'es we need to make sure that whatever we use
1208 * will have a set floor within our range.
1209 */
1210 if (reg->smin_value < 0 &&
1211 (reg->smin_value == S64_MIN ||
1212 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
1213 reg->smin_value + off < 0)) {
1214 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1215 regno);
1216 return -EACCES;
1217 }
1218 err = __check_map_access(env, regno, reg->smin_value + off, size,
1219 zero_size_allowed);
1220 if (err) {
1221 verbose(env, "R%d min value is outside of the array range\n",
1222 regno);
1223 return err;
1224 }
1225
1226 /* If we haven't set a max value then we need to bail since we can't be
1227 * sure we won't do bad things.
1228 * If reg->umax_value + off could overflow, treat that as unbounded too.
1229 */
1230 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
1231 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n",
1232 regno);
1233 return -EACCES;
1234 }
1235 err = __check_map_access(env, regno, reg->umax_value + off, size,
1236 zero_size_allowed);
1237 if (err)
1238 verbose(env, "R%d max value is outside of the array range\n",
1239 regno);
1240 return err;
1241 }
1242
1243 #define MAX_PACKET_OFF 0xffff
1244
may_access_direct_pkt_data(struct bpf_verifier_env * env,const struct bpf_call_arg_meta * meta,enum bpf_access_type t)1245 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
1246 const struct bpf_call_arg_meta *meta,
1247 enum bpf_access_type t)
1248 {
1249 switch (env->prog->type) {
1250 case BPF_PROG_TYPE_LWT_IN:
1251 case BPF_PROG_TYPE_LWT_OUT:
1252 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
1253 case BPF_PROG_TYPE_SK_REUSEPORT:
1254 /* dst_input() and dst_output() can't write for now */
1255 if (t == BPF_WRITE)
1256 return false;
1257 /* fallthrough */
1258 case BPF_PROG_TYPE_SCHED_CLS:
1259 case BPF_PROG_TYPE_SCHED_ACT:
1260 case BPF_PROG_TYPE_XDP:
1261 case BPF_PROG_TYPE_LWT_XMIT:
1262 case BPF_PROG_TYPE_SK_SKB:
1263 case BPF_PROG_TYPE_SK_MSG:
1264 if (meta)
1265 return meta->pkt_access;
1266
1267 env->seen_direct_write = true;
1268 return true;
1269 default:
1270 return false;
1271 }
1272 }
1273
__check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)1274 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno,
1275 int off, int size, bool zero_size_allowed)
1276 {
1277 struct bpf_reg_state *regs = cur_regs(env);
1278 struct bpf_reg_state *reg = ®s[regno];
1279
1280 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) ||
1281 (u64)off + size > reg->range) {
1282 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
1283 off, size, regno, reg->id, reg->off, reg->range);
1284 return -EACCES;
1285 }
1286 return 0;
1287 }
1288
check_packet_access(struct bpf_verifier_env * env,u32 regno,int off,int size,bool zero_size_allowed)1289 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
1290 int size, bool zero_size_allowed)
1291 {
1292 struct bpf_reg_state *regs = cur_regs(env);
1293 struct bpf_reg_state *reg = ®s[regno];
1294 int err;
1295
1296 /* We may have added a variable offset to the packet pointer; but any
1297 * reg->range we have comes after that. We are only checking the fixed
1298 * offset.
1299 */
1300
1301 /* We don't allow negative numbers, because we aren't tracking enough
1302 * detail to prove they're safe.
1303 */
1304 if (reg->smin_value < 0) {
1305 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
1306 regno);
1307 return -EACCES;
1308 }
1309 err = __check_packet_access(env, regno, off, size, zero_size_allowed);
1310 if (err) {
1311 verbose(env, "R%d offset is outside of the packet\n", regno);
1312 return err;
1313 }
1314 return err;
1315 }
1316
1317 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */
check_ctx_access(struct bpf_verifier_env * env,int insn_idx,int off,int size,enum bpf_access_type t,enum bpf_reg_type * reg_type)1318 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
1319 enum bpf_access_type t, enum bpf_reg_type *reg_type)
1320 {
1321 struct bpf_insn_access_aux info = {
1322 .reg_type = *reg_type,
1323 };
1324
1325 if (env->ops->is_valid_access &&
1326 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
1327 /* A non zero info.ctx_field_size indicates that this field is a
1328 * candidate for later verifier transformation to load the whole
1329 * field and then apply a mask when accessed with a narrower
1330 * access than actual ctx access size. A zero info.ctx_field_size
1331 * will only allow for whole field access and rejects any other
1332 * type of narrower access.
1333 */
1334 *reg_type = info.reg_type;
1335
1336 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
1337 /* remember the offset of last byte accessed in ctx */
1338 if (env->prog->aux->max_ctx_offset < off + size)
1339 env->prog->aux->max_ctx_offset = off + size;
1340 return 0;
1341 }
1342
1343 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
1344 return -EACCES;
1345 }
1346
__is_pointer_value(bool allow_ptr_leaks,const struct bpf_reg_state * reg)1347 static bool __is_pointer_value(bool allow_ptr_leaks,
1348 const struct bpf_reg_state *reg)
1349 {
1350 if (allow_ptr_leaks)
1351 return false;
1352
1353 return reg->type != SCALAR_VALUE;
1354 }
1355
is_pointer_value(struct bpf_verifier_env * env,int regno)1356 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
1357 {
1358 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno);
1359 }
1360
is_ctx_reg(struct bpf_verifier_env * env,int regno)1361 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
1362 {
1363 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1364
1365 return reg->type == PTR_TO_CTX;
1366 }
1367
is_pkt_reg(struct bpf_verifier_env * env,int regno)1368 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
1369 {
1370 const struct bpf_reg_state *reg = cur_regs(env) + regno;
1371
1372 return type_is_pkt_pointer(reg->type);
1373 }
1374
check_pkt_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict)1375 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
1376 const struct bpf_reg_state *reg,
1377 int off, int size, bool strict)
1378 {
1379 struct tnum reg_off;
1380 int ip_align;
1381
1382 /* Byte size accesses are always allowed. */
1383 if (!strict || size == 1)
1384 return 0;
1385
1386 /* For platforms that do not have a Kconfig enabling
1387 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
1388 * NET_IP_ALIGN is universally set to '2'. And on platforms
1389 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
1390 * to this code only in strict mode where we want to emulate
1391 * the NET_IP_ALIGN==2 checking. Therefore use an
1392 * unconditional IP align value of '2'.
1393 */
1394 ip_align = 2;
1395
1396 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
1397 if (!tnum_is_aligned(reg_off, size)) {
1398 char tn_buf[48];
1399
1400 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1401 verbose(env,
1402 "misaligned packet access off %d+%s+%d+%d size %d\n",
1403 ip_align, tn_buf, reg->off, off, size);
1404 return -EACCES;
1405 }
1406
1407 return 0;
1408 }
1409
check_generic_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,const char * pointer_desc,int off,int size,bool strict)1410 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
1411 const struct bpf_reg_state *reg,
1412 const char *pointer_desc,
1413 int off, int size, bool strict)
1414 {
1415 struct tnum reg_off;
1416
1417 /* Byte size accesses are always allowed. */
1418 if (!strict || size == 1)
1419 return 0;
1420
1421 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
1422 if (!tnum_is_aligned(reg_off, size)) {
1423 char tn_buf[48];
1424
1425 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1426 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
1427 pointer_desc, tn_buf, reg->off, off, size);
1428 return -EACCES;
1429 }
1430
1431 return 0;
1432 }
1433
check_ptr_alignment(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int off,int size,bool strict_alignment_once)1434 static int check_ptr_alignment(struct bpf_verifier_env *env,
1435 const struct bpf_reg_state *reg, int off,
1436 int size, bool strict_alignment_once)
1437 {
1438 bool strict = env->strict_alignment || strict_alignment_once;
1439 const char *pointer_desc = "";
1440
1441 switch (reg->type) {
1442 case PTR_TO_PACKET:
1443 case PTR_TO_PACKET_META:
1444 /* Special case, because of NET_IP_ALIGN. Given metadata sits
1445 * right in front, treat it the very same way.
1446 */
1447 return check_pkt_ptr_alignment(env, reg, off, size, strict);
1448 case PTR_TO_MAP_VALUE:
1449 pointer_desc = "value ";
1450 break;
1451 case PTR_TO_CTX:
1452 pointer_desc = "context ";
1453 break;
1454 case PTR_TO_STACK:
1455 pointer_desc = "stack ";
1456 /* The stack spill tracking logic in check_stack_write()
1457 * and check_stack_read() relies on stack accesses being
1458 * aligned.
1459 */
1460 strict = true;
1461 break;
1462 default:
1463 break;
1464 }
1465 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
1466 strict);
1467 }
1468
update_stack_depth(struct bpf_verifier_env * env,const struct bpf_func_state * func,int off)1469 static int update_stack_depth(struct bpf_verifier_env *env,
1470 const struct bpf_func_state *func,
1471 int off)
1472 {
1473 u16 stack = env->subprog_info[func->subprogno].stack_depth;
1474
1475 if (stack >= -off)
1476 return 0;
1477
1478 /* update known max for given subprogram */
1479 env->subprog_info[func->subprogno].stack_depth = -off;
1480 return 0;
1481 }
1482
1483 /* starting from main bpf function walk all instructions of the function
1484 * and recursively walk all callees that given function can call.
1485 * Ignore jump and exit insns.
1486 * Since recursion is prevented by check_cfg() this algorithm
1487 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
1488 */
check_max_stack_depth(struct bpf_verifier_env * env)1489 static int check_max_stack_depth(struct bpf_verifier_env *env)
1490 {
1491 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
1492 struct bpf_subprog_info *subprog = env->subprog_info;
1493 struct bpf_insn *insn = env->prog->insnsi;
1494 int ret_insn[MAX_CALL_FRAMES];
1495 int ret_prog[MAX_CALL_FRAMES];
1496
1497 process_func:
1498 /* round up to 32-bytes, since this is granularity
1499 * of interpreter stack size
1500 */
1501 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1502 if (depth > MAX_BPF_STACK) {
1503 verbose(env, "combined stack size of %d calls is %d. Too large\n",
1504 frame + 1, depth);
1505 return -EACCES;
1506 }
1507 continue_func:
1508 subprog_end = subprog[idx + 1].start;
1509 for (; i < subprog_end; i++) {
1510 if (insn[i].code != (BPF_JMP | BPF_CALL))
1511 continue;
1512 if (insn[i].src_reg != BPF_PSEUDO_CALL)
1513 continue;
1514 /* remember insn and function to return to */
1515 ret_insn[frame] = i + 1;
1516 ret_prog[frame] = idx;
1517
1518 /* find the callee */
1519 i = i + insn[i].imm + 1;
1520 idx = find_subprog(env, i);
1521 if (idx < 0) {
1522 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1523 i);
1524 return -EFAULT;
1525 }
1526 frame++;
1527 if (frame >= MAX_CALL_FRAMES) {
1528 WARN_ONCE(1, "verifier bug. Call stack is too deep\n");
1529 return -EFAULT;
1530 }
1531 goto process_func;
1532 }
1533 /* end of for() loop means the last insn of the 'subprog'
1534 * was reached. Doesn't matter whether it was JA or EXIT
1535 */
1536 if (frame == 0)
1537 return 0;
1538 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
1539 frame--;
1540 i = ret_insn[frame];
1541 idx = ret_prog[frame];
1542 goto continue_func;
1543 }
1544
1545 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
get_callee_stack_depth(struct bpf_verifier_env * env,const struct bpf_insn * insn,int idx)1546 static int get_callee_stack_depth(struct bpf_verifier_env *env,
1547 const struct bpf_insn *insn, int idx)
1548 {
1549 int start = idx + insn->imm + 1, subprog;
1550
1551 subprog = find_subprog(env, start);
1552 if (subprog < 0) {
1553 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
1554 start);
1555 return -EFAULT;
1556 }
1557 return env->subprog_info[subprog].stack_depth;
1558 }
1559 #endif
1560
check_ctx_reg(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,int regno)1561 static int check_ctx_reg(struct bpf_verifier_env *env,
1562 const struct bpf_reg_state *reg, int regno)
1563 {
1564 /* Access to ctx or passing it to a helper is only allowed in
1565 * its original, unmodified form.
1566 */
1567
1568 if (reg->off) {
1569 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
1570 regno, reg->off);
1571 return -EACCES;
1572 }
1573
1574 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
1575 char tn_buf[48];
1576
1577 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1578 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
1579 return -EACCES;
1580 }
1581
1582 return 0;
1583 }
1584
1585 /* truncate register to smaller size (in bytes)
1586 * must be called with size < BPF_REG_SIZE
1587 */
coerce_reg_to_size(struct bpf_reg_state * reg,int size)1588 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
1589 {
1590 u64 mask;
1591
1592 /* clear high bits in bit representation */
1593 reg->var_off = tnum_cast(reg->var_off, size);
1594
1595 /* fix arithmetic bounds */
1596 mask = ((u64)1 << (size * 8)) - 1;
1597 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
1598 reg->umin_value &= mask;
1599 reg->umax_value &= mask;
1600 } else {
1601 reg->umin_value = 0;
1602 reg->umax_value = mask;
1603 }
1604 reg->smin_value = reg->umin_value;
1605 reg->smax_value = reg->umax_value;
1606 }
1607
1608 /* check whether memory at (regno + off) is accessible for t = (read | write)
1609 * if t==write, value_regno is a register which value is stored into memory
1610 * if t==read, value_regno is a register which will receive the value from memory
1611 * if t==write && value_regno==-1, some unknown value is stored into memory
1612 * if t==read && value_regno==-1, don't care what we read from memory
1613 */
check_mem_access(struct bpf_verifier_env * env,int insn_idx,u32 regno,int off,int bpf_size,enum bpf_access_type t,int value_regno,bool strict_alignment_once)1614 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
1615 int off, int bpf_size, enum bpf_access_type t,
1616 int value_regno, bool strict_alignment_once)
1617 {
1618 struct bpf_reg_state *regs = cur_regs(env);
1619 struct bpf_reg_state *reg = regs + regno;
1620 struct bpf_func_state *state;
1621 int size, err = 0;
1622
1623 size = bpf_size_to_bytes(bpf_size);
1624 if (size < 0)
1625 return size;
1626
1627 /* alignment checks will add in reg->off themselves */
1628 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
1629 if (err)
1630 return err;
1631
1632 /* for access checks, reg->off is just part of off */
1633 off += reg->off;
1634
1635 if (reg->type == PTR_TO_MAP_VALUE) {
1636 if (t == BPF_WRITE && value_regno >= 0 &&
1637 is_pointer_value(env, value_regno)) {
1638 verbose(env, "R%d leaks addr into map\n", value_regno);
1639 return -EACCES;
1640 }
1641
1642 err = check_map_access(env, regno, off, size, false);
1643 if (!err && t == BPF_READ && value_regno >= 0)
1644 mark_reg_unknown(env, regs, value_regno);
1645
1646 } else if (reg->type == PTR_TO_CTX) {
1647 enum bpf_reg_type reg_type = SCALAR_VALUE;
1648
1649 if (t == BPF_WRITE && value_regno >= 0 &&
1650 is_pointer_value(env, value_regno)) {
1651 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1652 return -EACCES;
1653 }
1654
1655 err = check_ctx_reg(env, reg, regno);
1656 if (err < 0)
1657 return err;
1658
1659 err = check_ctx_access(env, insn_idx, off, size, t, ®_type);
1660 if (!err && t == BPF_READ && value_regno >= 0) {
1661 /* ctx access returns either a scalar, or a
1662 * PTR_TO_PACKET[_META,_END]. In the latter
1663 * case, we know the offset is zero.
1664 */
1665 if (reg_type == SCALAR_VALUE)
1666 mark_reg_unknown(env, regs, value_regno);
1667 else
1668 mark_reg_known_zero(env, regs,
1669 value_regno);
1670 regs[value_regno].type = reg_type;
1671 }
1672
1673 } else if (reg->type == PTR_TO_STACK) {
1674 off += reg->var_off.value;
1675 err = check_stack_access(env, reg, off, size);
1676 if (err)
1677 return err;
1678
1679 state = func(env, reg);
1680 err = update_stack_depth(env, state, off);
1681 if (err)
1682 return err;
1683
1684 if (t == BPF_WRITE)
1685 err = check_stack_write(env, state, off, size,
1686 value_regno, insn_idx);
1687 else
1688 err = check_stack_read(env, state, off, size,
1689 value_regno);
1690 } else if (reg_is_pkt_pointer(reg)) {
1691 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
1692 verbose(env, "cannot write into packet\n");
1693 return -EACCES;
1694 }
1695 if (t == BPF_WRITE && value_regno >= 0 &&
1696 is_pointer_value(env, value_regno)) {
1697 verbose(env, "R%d leaks addr into packet\n",
1698 value_regno);
1699 return -EACCES;
1700 }
1701 err = check_packet_access(env, regno, off, size, false);
1702 if (!err && t == BPF_READ && value_regno >= 0)
1703 mark_reg_unknown(env, regs, value_regno);
1704 } else {
1705 verbose(env, "R%d invalid mem access '%s'\n", regno,
1706 reg_type_str[reg->type]);
1707 return -EACCES;
1708 }
1709
1710 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
1711 regs[value_regno].type == SCALAR_VALUE) {
1712 /* b/h/w load zero-extends, mark upper bits as known 0 */
1713 coerce_reg_to_size(®s[value_regno], size);
1714 }
1715 return err;
1716 }
1717
check_xadd(struct bpf_verifier_env * env,int insn_idx,struct bpf_insn * insn)1718 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
1719 {
1720 int err;
1721
1722 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) ||
1723 insn->imm != 0) {
1724 verbose(env, "BPF_XADD uses reserved fields\n");
1725 return -EINVAL;
1726 }
1727
1728 /* check src1 operand */
1729 err = check_reg_arg(env, insn->src_reg, SRC_OP);
1730 if (err)
1731 return err;
1732
1733 /* check src2 operand */
1734 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
1735 if (err)
1736 return err;
1737
1738 if (is_pointer_value(env, insn->src_reg)) {
1739 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
1740 return -EACCES;
1741 }
1742
1743 if (is_ctx_reg(env, insn->dst_reg) ||
1744 is_pkt_reg(env, insn->dst_reg)) {
1745 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n",
1746 insn->dst_reg, is_ctx_reg(env, insn->dst_reg) ?
1747 "context" : "packet");
1748 return -EACCES;
1749 }
1750
1751 /* check whether atomic_add can read the memory */
1752 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1753 BPF_SIZE(insn->code), BPF_READ, -1, true);
1754 if (err)
1755 return err;
1756
1757 /* check whether atomic_add can write into the same memory */
1758 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
1759 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
1760 }
1761
1762 /* when register 'regno' is passed into function that will read 'access_size'
1763 * bytes from that pointer, make sure that it's within stack boundary
1764 * and all elements of stack are initialized.
1765 * Unlike most pointer bounds-checking functions, this one doesn't take an
1766 * 'off' argument, so it has to add in reg->off itself.
1767 */
check_stack_boundary(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)1768 static int check_stack_boundary(struct bpf_verifier_env *env, int regno,
1769 int access_size, bool zero_size_allowed,
1770 struct bpf_call_arg_meta *meta)
1771 {
1772 struct bpf_reg_state *reg = cur_regs(env) + regno;
1773 struct bpf_func_state *state = func(env, reg);
1774 int off, i, j, slot, spi;
1775
1776 if (reg->type != PTR_TO_STACK) {
1777 /* Allow zero-byte read from NULL, regardless of pointer type */
1778 if (zero_size_allowed && access_size == 0 &&
1779 register_is_null(reg))
1780 return 0;
1781
1782 verbose(env, "R%d type=%s expected=%s\n", regno,
1783 reg_type_str[reg->type],
1784 reg_type_str[PTR_TO_STACK]);
1785 return -EACCES;
1786 }
1787
1788 /* Only allow fixed-offset stack reads */
1789 if (!tnum_is_const(reg->var_off)) {
1790 char tn_buf[48];
1791
1792 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1793 verbose(env, "invalid variable stack read R%d var_off=%s\n",
1794 regno, tn_buf);
1795 return -EACCES;
1796 }
1797 off = reg->off + reg->var_off.value;
1798 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 ||
1799 access_size < 0 || (access_size == 0 && !zero_size_allowed)) {
1800 verbose(env, "invalid stack type R%d off=%d access_size=%d\n",
1801 regno, off, access_size);
1802 return -EACCES;
1803 }
1804
1805 if (meta && meta->raw_mode) {
1806 meta->access_size = access_size;
1807 meta->regno = regno;
1808 return 0;
1809 }
1810
1811 for (i = 0; i < access_size; i++) {
1812 u8 *stype;
1813
1814 slot = -(off + i) - 1;
1815 spi = slot / BPF_REG_SIZE;
1816 if (state->allocated_stack <= slot)
1817 goto err;
1818 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
1819 if (*stype == STACK_MISC)
1820 goto mark;
1821 if (*stype == STACK_ZERO) {
1822 /* helper can write anything into the stack */
1823 *stype = STACK_MISC;
1824 goto mark;
1825 }
1826
1827 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
1828 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) {
1829 __mark_reg_unknown(&state->stack[spi].spilled_ptr);
1830 for (j = 0; j < BPF_REG_SIZE; j++)
1831 state->stack[spi].slot_type[j] = STACK_MISC;
1832 goto mark;
1833 }
1834
1835
1836 err:
1837 verbose(env, "invalid indirect read from stack off %d+%d size %d\n",
1838 off, i, access_size);
1839 return -EACCES;
1840 mark:
1841 /* reading any byte out of 8-byte 'spill_slot' will cause
1842 * the whole slot to be marked as 'read'
1843 */
1844 mark_reg_read(env, &state->stack[spi].spilled_ptr,
1845 state->stack[spi].spilled_ptr.parent);
1846 }
1847 return update_stack_depth(env, state, off);
1848 }
1849
check_helper_mem_access(struct bpf_verifier_env * env,int regno,int access_size,bool zero_size_allowed,struct bpf_call_arg_meta * meta)1850 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
1851 int access_size, bool zero_size_allowed,
1852 struct bpf_call_arg_meta *meta)
1853 {
1854 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1855
1856 switch (reg->type) {
1857 case PTR_TO_PACKET:
1858 case PTR_TO_PACKET_META:
1859 return check_packet_access(env, regno, reg->off, access_size,
1860 zero_size_allowed);
1861 case PTR_TO_MAP_VALUE:
1862 return check_map_access(env, regno, reg->off, access_size,
1863 zero_size_allowed);
1864 default: /* scalar_value|ptr_to_stack or invalid ptr */
1865 return check_stack_boundary(env, regno, access_size,
1866 zero_size_allowed, meta);
1867 }
1868 }
1869
arg_type_is_mem_ptr(enum bpf_arg_type type)1870 static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
1871 {
1872 return type == ARG_PTR_TO_MEM ||
1873 type == ARG_PTR_TO_MEM_OR_NULL ||
1874 type == ARG_PTR_TO_UNINIT_MEM;
1875 }
1876
arg_type_is_mem_size(enum bpf_arg_type type)1877 static bool arg_type_is_mem_size(enum bpf_arg_type type)
1878 {
1879 return type == ARG_CONST_SIZE ||
1880 type == ARG_CONST_SIZE_OR_ZERO;
1881 }
1882
check_func_arg(struct bpf_verifier_env * env,u32 regno,enum bpf_arg_type arg_type,struct bpf_call_arg_meta * meta)1883 static int check_func_arg(struct bpf_verifier_env *env, u32 regno,
1884 enum bpf_arg_type arg_type,
1885 struct bpf_call_arg_meta *meta)
1886 {
1887 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno];
1888 enum bpf_reg_type expected_type, type = reg->type;
1889 int err = 0;
1890
1891 if (arg_type == ARG_DONTCARE)
1892 return 0;
1893
1894 err = check_reg_arg(env, regno, SRC_OP);
1895 if (err)
1896 return err;
1897
1898 if (arg_type == ARG_ANYTHING) {
1899 if (is_pointer_value(env, regno)) {
1900 verbose(env, "R%d leaks addr into helper function\n",
1901 regno);
1902 return -EACCES;
1903 }
1904 return 0;
1905 }
1906
1907 if (type_is_pkt_pointer(type) &&
1908 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
1909 verbose(env, "helper access to the packet is not allowed\n");
1910 return -EACCES;
1911 }
1912
1913 if (arg_type == ARG_PTR_TO_MAP_KEY ||
1914 arg_type == ARG_PTR_TO_MAP_VALUE) {
1915 expected_type = PTR_TO_STACK;
1916 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE &&
1917 type != expected_type)
1918 goto err_type;
1919 } else if (arg_type == ARG_CONST_SIZE ||
1920 arg_type == ARG_CONST_SIZE_OR_ZERO) {
1921 expected_type = SCALAR_VALUE;
1922 if (type != expected_type)
1923 goto err_type;
1924 } else if (arg_type == ARG_CONST_MAP_PTR) {
1925 expected_type = CONST_PTR_TO_MAP;
1926 if (type != expected_type)
1927 goto err_type;
1928 } else if (arg_type == ARG_PTR_TO_CTX) {
1929 expected_type = PTR_TO_CTX;
1930 if (type != expected_type)
1931 goto err_type;
1932 err = check_ctx_reg(env, reg, regno);
1933 if (err < 0)
1934 return err;
1935 } else if (arg_type_is_mem_ptr(arg_type)) {
1936 expected_type = PTR_TO_STACK;
1937 /* One exception here. In case function allows for NULL to be
1938 * passed in as argument, it's a SCALAR_VALUE type. Final test
1939 * happens during stack boundary checking.
1940 */
1941 if (register_is_null(reg) &&
1942 arg_type == ARG_PTR_TO_MEM_OR_NULL)
1943 /* final test in check_stack_boundary() */;
1944 else if (!type_is_pkt_pointer(type) &&
1945 type != PTR_TO_MAP_VALUE &&
1946 type != expected_type)
1947 goto err_type;
1948 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM;
1949 } else {
1950 verbose(env, "unsupported arg_type %d\n", arg_type);
1951 return -EFAULT;
1952 }
1953
1954 if (arg_type == ARG_CONST_MAP_PTR) {
1955 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
1956 meta->map_ptr = reg->map_ptr;
1957 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
1958 /* bpf_map_xxx(..., map_ptr, ..., key) call:
1959 * check that [key, key + map->key_size) are within
1960 * stack limits and initialized
1961 */
1962 if (!meta->map_ptr) {
1963 /* in function declaration map_ptr must come before
1964 * map_key, so that it's verified and known before
1965 * we have to check map_key here. Otherwise it means
1966 * that kernel subsystem misconfigured verifier
1967 */
1968 verbose(env, "invalid map_ptr to access map->key\n");
1969 return -EACCES;
1970 }
1971 err = check_helper_mem_access(env, regno,
1972 meta->map_ptr->key_size, false,
1973 NULL);
1974 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) {
1975 /* bpf_map_xxx(..., map_ptr, ..., value) call:
1976 * check [value, value + map->value_size) validity
1977 */
1978 if (!meta->map_ptr) {
1979 /* kernel subsystem misconfigured verifier */
1980 verbose(env, "invalid map_ptr to access map->value\n");
1981 return -EACCES;
1982 }
1983 err = check_helper_mem_access(env, regno,
1984 meta->map_ptr->value_size, false,
1985 NULL);
1986 } else if (arg_type_is_mem_size(arg_type)) {
1987 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
1988
1989 /* remember the mem_size which may be used later
1990 * to refine return values.
1991 */
1992 meta->msize_max_value = reg->umax_value;
1993
1994 /* The register is SCALAR_VALUE; the access check
1995 * happens using its boundaries.
1996 */
1997 if (!tnum_is_const(reg->var_off))
1998 /* For unprivileged variable accesses, disable raw
1999 * mode so that the program is required to
2000 * initialize all the memory that the helper could
2001 * just partially fill up.
2002 */
2003 meta = NULL;
2004
2005 if (reg->smin_value < 0) {
2006 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
2007 regno);
2008 return -EACCES;
2009 }
2010
2011 if (reg->umin_value == 0) {
2012 err = check_helper_mem_access(env, regno - 1, 0,
2013 zero_size_allowed,
2014 meta);
2015 if (err)
2016 return err;
2017 }
2018
2019 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
2020 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
2021 regno);
2022 return -EACCES;
2023 }
2024 err = check_helper_mem_access(env, regno - 1,
2025 reg->umax_value,
2026 zero_size_allowed, meta);
2027 }
2028
2029 return err;
2030 err_type:
2031 verbose(env, "R%d type=%s expected=%s\n", regno,
2032 reg_type_str[type], reg_type_str[expected_type]);
2033 return -EACCES;
2034 }
2035
check_map_func_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,int func_id)2036 static int check_map_func_compatibility(struct bpf_verifier_env *env,
2037 struct bpf_map *map, int func_id)
2038 {
2039 if (!map)
2040 return 0;
2041
2042 /* We need a two way check, first is from map perspective ... */
2043 switch (map->map_type) {
2044 case BPF_MAP_TYPE_PROG_ARRAY:
2045 if (func_id != BPF_FUNC_tail_call)
2046 goto error;
2047 break;
2048 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
2049 if (func_id != BPF_FUNC_perf_event_read &&
2050 func_id != BPF_FUNC_perf_event_output &&
2051 func_id != BPF_FUNC_perf_event_read_value)
2052 goto error;
2053 break;
2054 case BPF_MAP_TYPE_STACK_TRACE:
2055 if (func_id != BPF_FUNC_get_stackid)
2056 goto error;
2057 break;
2058 case BPF_MAP_TYPE_CGROUP_ARRAY:
2059 if (func_id != BPF_FUNC_skb_under_cgroup &&
2060 func_id != BPF_FUNC_current_task_under_cgroup)
2061 goto error;
2062 break;
2063 case BPF_MAP_TYPE_CGROUP_STORAGE:
2064 if (func_id != BPF_FUNC_get_local_storage)
2065 goto error;
2066 break;
2067 /* devmap returns a pointer to a live net_device ifindex that we cannot
2068 * allow to be modified from bpf side. So do not allow lookup elements
2069 * for now.
2070 */
2071 case BPF_MAP_TYPE_DEVMAP:
2072 if (func_id != BPF_FUNC_redirect_map)
2073 goto error;
2074 break;
2075 /* Restrict bpf side of cpumap and xskmap, open when use-cases
2076 * appear.
2077 */
2078 case BPF_MAP_TYPE_CPUMAP:
2079 case BPF_MAP_TYPE_XSKMAP:
2080 if (func_id != BPF_FUNC_redirect_map)
2081 goto error;
2082 break;
2083 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
2084 case BPF_MAP_TYPE_HASH_OF_MAPS:
2085 if (func_id != BPF_FUNC_map_lookup_elem)
2086 goto error;
2087 break;
2088 case BPF_MAP_TYPE_SOCKMAP:
2089 if (func_id != BPF_FUNC_sk_redirect_map &&
2090 func_id != BPF_FUNC_sock_map_update &&
2091 func_id != BPF_FUNC_map_delete_elem &&
2092 func_id != BPF_FUNC_msg_redirect_map)
2093 goto error;
2094 break;
2095 case BPF_MAP_TYPE_SOCKHASH:
2096 if (func_id != BPF_FUNC_sk_redirect_hash &&
2097 func_id != BPF_FUNC_sock_hash_update &&
2098 func_id != BPF_FUNC_map_delete_elem &&
2099 func_id != BPF_FUNC_msg_redirect_hash)
2100 goto error;
2101 break;
2102 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
2103 if (func_id != BPF_FUNC_sk_select_reuseport)
2104 goto error;
2105 break;
2106 default:
2107 break;
2108 }
2109
2110 /* ... and second from the function itself. */
2111 switch (func_id) {
2112 case BPF_FUNC_tail_call:
2113 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
2114 goto error;
2115 if (env->subprog_cnt > 1) {
2116 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n");
2117 return -EINVAL;
2118 }
2119 break;
2120 case BPF_FUNC_perf_event_read:
2121 case BPF_FUNC_perf_event_output:
2122 case BPF_FUNC_perf_event_read_value:
2123 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
2124 goto error;
2125 break;
2126 case BPF_FUNC_get_stackid:
2127 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
2128 goto error;
2129 break;
2130 case BPF_FUNC_current_task_under_cgroup:
2131 case BPF_FUNC_skb_under_cgroup:
2132 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
2133 goto error;
2134 break;
2135 case BPF_FUNC_redirect_map:
2136 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
2137 map->map_type != BPF_MAP_TYPE_CPUMAP &&
2138 map->map_type != BPF_MAP_TYPE_XSKMAP)
2139 goto error;
2140 break;
2141 case BPF_FUNC_sk_redirect_map:
2142 case BPF_FUNC_msg_redirect_map:
2143 case BPF_FUNC_sock_map_update:
2144 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
2145 goto error;
2146 break;
2147 case BPF_FUNC_sk_redirect_hash:
2148 case BPF_FUNC_msg_redirect_hash:
2149 case BPF_FUNC_sock_hash_update:
2150 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
2151 goto error;
2152 break;
2153 case BPF_FUNC_get_local_storage:
2154 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE)
2155 goto error;
2156 break;
2157 case BPF_FUNC_sk_select_reuseport:
2158 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY)
2159 goto error;
2160 break;
2161 default:
2162 break;
2163 }
2164
2165 return 0;
2166 error:
2167 verbose(env, "cannot pass map_type %d into func %s#%d\n",
2168 map->map_type, func_id_name(func_id), func_id);
2169 return -EINVAL;
2170 }
2171
check_raw_mode_ok(const struct bpf_func_proto * fn)2172 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
2173 {
2174 int count = 0;
2175
2176 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
2177 count++;
2178 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
2179 count++;
2180 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
2181 count++;
2182 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
2183 count++;
2184 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
2185 count++;
2186
2187 /* We only support one arg being in raw mode at the moment,
2188 * which is sufficient for the helper functions we have
2189 * right now.
2190 */
2191 return count <= 1;
2192 }
2193
check_args_pair_invalid(enum bpf_arg_type arg_curr,enum bpf_arg_type arg_next)2194 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
2195 enum bpf_arg_type arg_next)
2196 {
2197 return (arg_type_is_mem_ptr(arg_curr) &&
2198 !arg_type_is_mem_size(arg_next)) ||
2199 (!arg_type_is_mem_ptr(arg_curr) &&
2200 arg_type_is_mem_size(arg_next));
2201 }
2202
check_arg_pair_ok(const struct bpf_func_proto * fn)2203 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
2204 {
2205 /* bpf_xxx(..., buf, len) call will access 'len'
2206 * bytes from memory 'buf'. Both arg types need
2207 * to be paired, so make sure there's no buggy
2208 * helper function specification.
2209 */
2210 if (arg_type_is_mem_size(fn->arg1_type) ||
2211 arg_type_is_mem_ptr(fn->arg5_type) ||
2212 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
2213 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
2214 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
2215 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
2216 return false;
2217
2218 return true;
2219 }
2220
check_func_proto(const struct bpf_func_proto * fn)2221 static int check_func_proto(const struct bpf_func_proto *fn)
2222 {
2223 return check_raw_mode_ok(fn) &&
2224 check_arg_pair_ok(fn) ? 0 : -EINVAL;
2225 }
2226
2227 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
2228 * are now invalid, so turn them into unknown SCALAR_VALUE.
2229 */
__clear_all_pkt_pointers(struct bpf_verifier_env * env,struct bpf_func_state * state)2230 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
2231 struct bpf_func_state *state)
2232 {
2233 struct bpf_reg_state *regs = state->regs, *reg;
2234 int i;
2235
2236 for (i = 0; i < MAX_BPF_REG; i++)
2237 if (reg_is_pkt_pointer_any(®s[i]))
2238 mark_reg_unknown(env, regs, i);
2239
2240 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
2241 if (state->stack[i].slot_type[0] != STACK_SPILL)
2242 continue;
2243 reg = &state->stack[i].spilled_ptr;
2244 if (reg_is_pkt_pointer_any(reg))
2245 __mark_reg_unknown(reg);
2246 }
2247 }
2248
clear_all_pkt_pointers(struct bpf_verifier_env * env)2249 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
2250 {
2251 struct bpf_verifier_state *vstate = env->cur_state;
2252 int i;
2253
2254 for (i = 0; i <= vstate->curframe; i++)
2255 __clear_all_pkt_pointers(env, vstate->frame[i]);
2256 }
2257
check_func_call(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)2258 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
2259 int *insn_idx)
2260 {
2261 struct bpf_verifier_state *state = env->cur_state;
2262 struct bpf_func_state *caller, *callee;
2263 int i, subprog, target_insn;
2264
2265 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
2266 verbose(env, "the call stack of %d frames is too deep\n",
2267 state->curframe + 2);
2268 return -E2BIG;
2269 }
2270
2271 target_insn = *insn_idx + insn->imm;
2272 subprog = find_subprog(env, target_insn + 1);
2273 if (subprog < 0) {
2274 verbose(env, "verifier bug. No program starts at insn %d\n",
2275 target_insn + 1);
2276 return -EFAULT;
2277 }
2278
2279 caller = state->frame[state->curframe];
2280 if (state->frame[state->curframe + 1]) {
2281 verbose(env, "verifier bug. Frame %d already allocated\n",
2282 state->curframe + 1);
2283 return -EFAULT;
2284 }
2285
2286 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
2287 if (!callee)
2288 return -ENOMEM;
2289 state->frame[state->curframe + 1] = callee;
2290
2291 /* callee cannot access r0, r6 - r9 for reading and has to write
2292 * into its own stack before reading from it.
2293 * callee can read/write into caller's stack
2294 */
2295 init_func_state(env, callee,
2296 /* remember the callsite, it will be used by bpf_exit */
2297 *insn_idx /* callsite */,
2298 state->curframe + 1 /* frameno within this callchain */,
2299 subprog /* subprog number within this prog */);
2300
2301 /* copy r1 - r5 args that callee can access. The copy includes parent
2302 * pointers, which connects us up to the liveness chain
2303 */
2304 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
2305 callee->regs[i] = caller->regs[i];
2306
2307 /* after the call registers r0 - r5 were scratched */
2308 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2309 mark_reg_not_init(env, caller->regs, caller_saved[i]);
2310 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2311 }
2312
2313 /* only increment it after check_reg_arg() finished */
2314 state->curframe++;
2315
2316 /* and go analyze first insn of the callee */
2317 *insn_idx = target_insn;
2318
2319 if (env->log.level) {
2320 verbose(env, "caller:\n");
2321 print_verifier_state(env, caller);
2322 verbose(env, "callee:\n");
2323 print_verifier_state(env, callee);
2324 }
2325 return 0;
2326 }
2327
prepare_func_exit(struct bpf_verifier_env * env,int * insn_idx)2328 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
2329 {
2330 struct bpf_verifier_state *state = env->cur_state;
2331 struct bpf_func_state *caller, *callee;
2332 struct bpf_reg_state *r0;
2333
2334 callee = state->frame[state->curframe];
2335 r0 = &callee->regs[BPF_REG_0];
2336 if (r0->type == PTR_TO_STACK) {
2337 /* technically it's ok to return caller's stack pointer
2338 * (or caller's caller's pointer) back to the caller,
2339 * since these pointers are valid. Only current stack
2340 * pointer will be invalid as soon as function exits,
2341 * but let's be conservative
2342 */
2343 verbose(env, "cannot return stack pointer to the caller\n");
2344 return -EINVAL;
2345 }
2346
2347 state->curframe--;
2348 caller = state->frame[state->curframe];
2349 /* return to the caller whatever r0 had in the callee */
2350 caller->regs[BPF_REG_0] = *r0;
2351
2352 *insn_idx = callee->callsite + 1;
2353 if (env->log.level) {
2354 verbose(env, "returning from callee:\n");
2355 print_verifier_state(env, callee);
2356 verbose(env, "to caller at %d:\n", *insn_idx);
2357 print_verifier_state(env, caller);
2358 }
2359 /* clear everything in the callee */
2360 free_func_state(callee);
2361 state->frame[state->curframe + 1] = NULL;
2362 return 0;
2363 }
2364
do_refine_retval_range(struct bpf_verifier_env * env,struct bpf_reg_state * regs,int ret_type,int func_id,struct bpf_call_arg_meta * meta)2365 static int do_refine_retval_range(struct bpf_verifier_env *env,
2366 struct bpf_reg_state *regs, int ret_type,
2367 int func_id, struct bpf_call_arg_meta *meta)
2368 {
2369 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0];
2370 struct bpf_reg_state tmp_reg = *ret_reg;
2371 bool ret;
2372
2373 if (ret_type != RET_INTEGER ||
2374 (func_id != BPF_FUNC_get_stack &&
2375 func_id != BPF_FUNC_probe_read_str))
2376 return 0;
2377
2378 /* Error case where ret is in interval [S32MIN, -1]. */
2379 ret_reg->smin_value = S32_MIN;
2380 ret_reg->smax_value = -1;
2381
2382 __reg_deduce_bounds(ret_reg);
2383 __reg_bound_offset(ret_reg);
2384 __update_reg_bounds(ret_reg);
2385
2386 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, false);
2387 if (!ret)
2388 return -EFAULT;
2389
2390 *ret_reg = tmp_reg;
2391
2392 /* Success case where ret is in range [0, msize_max_value]. */
2393 ret_reg->smin_value = 0;
2394 ret_reg->smax_value = meta->msize_max_value;
2395 ret_reg->umin_value = ret_reg->smin_value;
2396 ret_reg->umax_value = ret_reg->smax_value;
2397
2398 __reg_deduce_bounds(ret_reg);
2399 __reg_bound_offset(ret_reg);
2400 __update_reg_bounds(ret_reg);
2401
2402 return 0;
2403 }
2404
2405 static int
record_func_map(struct bpf_verifier_env * env,struct bpf_call_arg_meta * meta,int func_id,int insn_idx)2406 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
2407 int func_id, int insn_idx)
2408 {
2409 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
2410
2411 if (func_id != BPF_FUNC_tail_call &&
2412 func_id != BPF_FUNC_map_lookup_elem &&
2413 func_id != BPF_FUNC_map_update_elem &&
2414 func_id != BPF_FUNC_map_delete_elem)
2415 return 0;
2416
2417 if (meta->map_ptr == NULL) {
2418 verbose(env, "kernel subsystem misconfigured verifier\n");
2419 return -EINVAL;
2420 }
2421
2422 if (!BPF_MAP_PTR(aux->map_state))
2423 bpf_map_ptr_store(aux, meta->map_ptr,
2424 meta->map_ptr->unpriv_array);
2425 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr)
2426 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2427 meta->map_ptr->unpriv_array);
2428 return 0;
2429 }
2430
check_helper_call(struct bpf_verifier_env * env,int func_id,int insn_idx)2431 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
2432 {
2433 const struct bpf_func_proto *fn = NULL;
2434 struct bpf_reg_state *regs;
2435 struct bpf_call_arg_meta meta;
2436 bool changes_data;
2437 int i, err;
2438
2439 /* find function prototype */
2440 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
2441 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
2442 func_id);
2443 return -EINVAL;
2444 }
2445
2446 if (env->ops->get_func_proto)
2447 fn = env->ops->get_func_proto(func_id, env->prog);
2448 if (!fn) {
2449 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
2450 func_id);
2451 return -EINVAL;
2452 }
2453
2454 /* eBPF programs must be GPL compatible to use GPL-ed functions */
2455 if (!env->prog->gpl_compatible && fn->gpl_only) {
2456 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
2457 return -EINVAL;
2458 }
2459
2460 /* With LD_ABS/IND some JITs save/restore skb from r1. */
2461 changes_data = bpf_helper_changes_pkt_data(fn->func);
2462 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
2463 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
2464 func_id_name(func_id), func_id);
2465 return -EINVAL;
2466 }
2467
2468 memset(&meta, 0, sizeof(meta));
2469 meta.pkt_access = fn->pkt_access;
2470
2471 err = check_func_proto(fn);
2472 if (err) {
2473 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
2474 func_id_name(func_id), func_id);
2475 return err;
2476 }
2477
2478 /* check args */
2479 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta);
2480 if (err)
2481 return err;
2482 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta);
2483 if (err)
2484 return err;
2485 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta);
2486 if (err)
2487 return err;
2488 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta);
2489 if (err)
2490 return err;
2491 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta);
2492 if (err)
2493 return err;
2494
2495 err = record_func_map(env, &meta, func_id, insn_idx);
2496 if (err)
2497 return err;
2498
2499 /* Mark slots with STACK_MISC in case of raw mode, stack offset
2500 * is inferred from register state.
2501 */
2502 for (i = 0; i < meta.access_size; i++) {
2503 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
2504 BPF_WRITE, -1, false);
2505 if (err)
2506 return err;
2507 }
2508
2509 regs = cur_regs(env);
2510
2511 /* check that flags argument in get_local_storage(map, flags) is 0,
2512 * this is required because get_local_storage() can't return an error.
2513 */
2514 if (func_id == BPF_FUNC_get_local_storage &&
2515 !register_is_null(®s[BPF_REG_2])) {
2516 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
2517 return -EINVAL;
2518 }
2519
2520 /* reset caller saved regs */
2521 for (i = 0; i < CALLER_SAVED_REGS; i++) {
2522 mark_reg_not_init(env, regs, caller_saved[i]);
2523 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
2524 }
2525
2526 /* update return register (already marked as written above) */
2527 if (fn->ret_type == RET_INTEGER) {
2528 /* sets type to SCALAR_VALUE */
2529 mark_reg_unknown(env, regs, BPF_REG_0);
2530 } else if (fn->ret_type == RET_VOID) {
2531 regs[BPF_REG_0].type = NOT_INIT;
2532 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
2533 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
2534 if (fn->ret_type == RET_PTR_TO_MAP_VALUE)
2535 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
2536 else
2537 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
2538 /* There is no offset yet applied, variable or fixed */
2539 mark_reg_known_zero(env, regs, BPF_REG_0);
2540 /* remember map_ptr, so that check_map_access()
2541 * can check 'value_size' boundary of memory access
2542 * to map element returned from bpf_map_lookup_elem()
2543 */
2544 if (meta.map_ptr == NULL) {
2545 verbose(env,
2546 "kernel subsystem misconfigured verifier\n");
2547 return -EINVAL;
2548 }
2549 regs[BPF_REG_0].map_ptr = meta.map_ptr;
2550 regs[BPF_REG_0].id = ++env->id_gen;
2551 } else {
2552 verbose(env, "unknown return type %d of func %s#%d\n",
2553 fn->ret_type, func_id_name(func_id), func_id);
2554 return -EINVAL;
2555 }
2556
2557 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta);
2558 if (err)
2559 return err;
2560
2561 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
2562 if (err)
2563 return err;
2564
2565 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) {
2566 const char *err_str;
2567
2568 #ifdef CONFIG_PERF_EVENTS
2569 err = get_callchain_buffers(sysctl_perf_event_max_stack);
2570 err_str = "cannot get callchain buffer for func %s#%d\n";
2571 #else
2572 err = -ENOTSUPP;
2573 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
2574 #endif
2575 if (err) {
2576 verbose(env, err_str, func_id_name(func_id), func_id);
2577 return err;
2578 }
2579
2580 env->prog->has_callchain_buf = true;
2581 }
2582
2583 if (changes_data)
2584 clear_all_pkt_pointers(env);
2585 return 0;
2586 }
2587
signed_add_overflows(s64 a,s64 b)2588 static bool signed_add_overflows(s64 a, s64 b)
2589 {
2590 /* Do the add in u64, where overflow is well-defined */
2591 s64 res = (s64)((u64)a + (u64)b);
2592
2593 if (b < 0)
2594 return res > a;
2595 return res < a;
2596 }
2597
signed_sub_overflows(s64 a,s64 b)2598 static bool signed_sub_overflows(s64 a, s64 b)
2599 {
2600 /* Do the sub in u64, where overflow is well-defined */
2601 s64 res = (s64)((u64)a - (u64)b);
2602
2603 if (b < 0)
2604 return res < a;
2605 return res > a;
2606 }
2607
check_reg_sane_offset(struct bpf_verifier_env * env,const struct bpf_reg_state * reg,enum bpf_reg_type type)2608 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
2609 const struct bpf_reg_state *reg,
2610 enum bpf_reg_type type)
2611 {
2612 bool known = tnum_is_const(reg->var_off);
2613 s64 val = reg->var_off.value;
2614 s64 smin = reg->smin_value;
2615
2616 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
2617 verbose(env, "math between %s pointer and %lld is not allowed\n",
2618 reg_type_str[type], val);
2619 return false;
2620 }
2621
2622 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
2623 verbose(env, "%s pointer offset %d is not allowed\n",
2624 reg_type_str[type], reg->off);
2625 return false;
2626 }
2627
2628 if (smin == S64_MIN) {
2629 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
2630 reg_type_str[type]);
2631 return false;
2632 }
2633
2634 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
2635 verbose(env, "value %lld makes %s pointer be out of bounds\n",
2636 smin, reg_type_str[type]);
2637 return false;
2638 }
2639
2640 return true;
2641 }
2642
cur_aux(struct bpf_verifier_env * env)2643 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
2644 {
2645 return &env->insn_aux_data[env->insn_idx];
2646 }
2647
2648 enum {
2649 REASON_BOUNDS = -1,
2650 REASON_TYPE = -2,
2651 REASON_PATHS = -3,
2652 REASON_LIMIT = -4,
2653 REASON_STACK = -5,
2654 };
2655
retrieve_ptr_limit(const struct bpf_reg_state * ptr_reg,u32 * alu_limit,bool mask_to_left)2656 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
2657 u32 *alu_limit, bool mask_to_left)
2658 {
2659 u32 max = 0, ptr_limit = 0;
2660
2661 switch (ptr_reg->type) {
2662 case PTR_TO_STACK:
2663 /* Offset 0 is out-of-bounds, but acceptable start for the
2664 * left direction, see BPF_REG_FP. Also, unknown scalar
2665 * offset where we would need to deal with min/max bounds is
2666 * currently prohibited for unprivileged.
2667 */
2668 max = MAX_BPF_STACK + mask_to_left;
2669 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
2670 break;
2671 case PTR_TO_MAP_VALUE:
2672 max = ptr_reg->map_ptr->value_size;
2673 ptr_limit = (mask_to_left ?
2674 ptr_reg->smin_value :
2675 ptr_reg->umax_value) + ptr_reg->off;
2676 break;
2677 default:
2678 return REASON_TYPE;
2679 }
2680
2681 if (ptr_limit >= max)
2682 return REASON_LIMIT;
2683 *alu_limit = ptr_limit;
2684 return 0;
2685 }
2686
can_skip_alu_sanitation(const struct bpf_verifier_env * env,const struct bpf_insn * insn)2687 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
2688 const struct bpf_insn *insn)
2689 {
2690 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K;
2691 }
2692
update_alu_sanitation_state(struct bpf_insn_aux_data * aux,u32 alu_state,u32 alu_limit)2693 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
2694 u32 alu_state, u32 alu_limit)
2695 {
2696 /* If we arrived here from different branches with different
2697 * state or limits to sanitize, then this won't work.
2698 */
2699 if (aux->alu_state &&
2700 (aux->alu_state != alu_state ||
2701 aux->alu_limit != alu_limit))
2702 return REASON_PATHS;
2703
2704 /* Corresponding fixup done in fixup_bpf_calls(). */
2705 aux->alu_state = alu_state;
2706 aux->alu_limit = alu_limit;
2707 return 0;
2708 }
2709
sanitize_val_alu(struct bpf_verifier_env * env,struct bpf_insn * insn)2710 static int sanitize_val_alu(struct bpf_verifier_env *env,
2711 struct bpf_insn *insn)
2712 {
2713 struct bpf_insn_aux_data *aux = cur_aux(env);
2714
2715 if (can_skip_alu_sanitation(env, insn))
2716 return 0;
2717
2718 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
2719 }
2720
sanitize_needed(u8 opcode)2721 static bool sanitize_needed(u8 opcode)
2722 {
2723 return opcode == BPF_ADD || opcode == BPF_SUB;
2724 }
2725
2726 struct bpf_sanitize_info {
2727 struct bpf_insn_aux_data aux;
2728 bool mask_to_left;
2729 };
2730
2731 static struct bpf_verifier_state *
sanitize_speculative_path(struct bpf_verifier_env * env,const struct bpf_insn * insn,u32 next_idx,u32 curr_idx)2732 sanitize_speculative_path(struct bpf_verifier_env *env,
2733 const struct bpf_insn *insn,
2734 u32 next_idx, u32 curr_idx)
2735 {
2736 struct bpf_verifier_state *branch;
2737 struct bpf_reg_state *regs;
2738
2739 branch = push_stack(env, next_idx, curr_idx, true);
2740 if (branch && insn) {
2741 regs = branch->frame[branch->curframe]->regs;
2742 if (BPF_SRC(insn->code) == BPF_K) {
2743 mark_reg_unknown(env, regs, insn->dst_reg);
2744 } else if (BPF_SRC(insn->code) == BPF_X) {
2745 mark_reg_unknown(env, regs, insn->dst_reg);
2746 mark_reg_unknown(env, regs, insn->src_reg);
2747 }
2748 }
2749 return branch;
2750 }
2751
sanitize_ptr_alu(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg,struct bpf_reg_state * dst_reg,struct bpf_sanitize_info * info,const bool commit_window)2752 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
2753 struct bpf_insn *insn,
2754 const struct bpf_reg_state *ptr_reg,
2755 const struct bpf_reg_state *off_reg,
2756 struct bpf_reg_state *dst_reg,
2757 struct bpf_sanitize_info *info,
2758 const bool commit_window)
2759 {
2760 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
2761 struct bpf_verifier_state *vstate = env->cur_state;
2762 bool off_is_imm = tnum_is_const(off_reg->var_off);
2763 bool off_is_neg = off_reg->smin_value < 0;
2764 bool ptr_is_dst_reg = ptr_reg == dst_reg;
2765 u8 opcode = BPF_OP(insn->code);
2766 u32 alu_state, alu_limit;
2767 struct bpf_reg_state tmp;
2768 bool ret;
2769 int err;
2770
2771 if (can_skip_alu_sanitation(env, insn))
2772 return 0;
2773
2774 /* We already marked aux for masking from non-speculative
2775 * paths, thus we got here in the first place. We only care
2776 * to explore bad access from here.
2777 */
2778 if (vstate->speculative)
2779 goto do_sim;
2780
2781 if (!commit_window) {
2782 if (!tnum_is_const(off_reg->var_off) &&
2783 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
2784 return REASON_BOUNDS;
2785
2786 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
2787 (opcode == BPF_SUB && !off_is_neg);
2788 }
2789
2790 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
2791 if (err < 0)
2792 return err;
2793
2794 if (commit_window) {
2795 /* In commit phase we narrow the masking window based on
2796 * the observed pointer move after the simulated operation.
2797 */
2798 alu_state = info->aux.alu_state;
2799 alu_limit = abs(info->aux.alu_limit - alu_limit);
2800 } else {
2801 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
2802 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
2803 alu_state |= ptr_is_dst_reg ?
2804 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
2805 }
2806
2807 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
2808 if (err < 0)
2809 return err;
2810 do_sim:
2811 /* If we're in commit phase, we're done here given we already
2812 * pushed the truncated dst_reg into the speculative verification
2813 * stack.
2814 *
2815 * Also, when register is a known constant, we rewrite register-based
2816 * operation to immediate-based, and thus do not need masking (and as
2817 * a consequence, do not need to simulate the zero-truncation either).
2818 */
2819 if (commit_window || off_is_imm)
2820 return 0;
2821
2822 /* Simulate and find potential out-of-bounds access under
2823 * speculative execution from truncation as a result of
2824 * masking when off was not within expected range. If off
2825 * sits in dst, then we temporarily need to move ptr there
2826 * to simulate dst (== 0) +/-= ptr. Needed, for example,
2827 * for cases where we use K-based arithmetic in one direction
2828 * and truncated reg-based in the other in order to explore
2829 * bad access.
2830 */
2831 if (!ptr_is_dst_reg) {
2832 tmp = *dst_reg;
2833 *dst_reg = *ptr_reg;
2834 }
2835 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
2836 env->insn_idx);
2837 if (!ptr_is_dst_reg && ret)
2838 *dst_reg = tmp;
2839 return !ret ? REASON_STACK : 0;
2840 }
2841
sanitize_mark_insn_seen(struct bpf_verifier_env * env)2842 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
2843 {
2844 struct bpf_verifier_state *vstate = env->cur_state;
2845
2846 /* If we simulate paths under speculation, we don't update the
2847 * insn as 'seen' such that when we verify unreachable paths in
2848 * the non-speculative domain, sanitize_dead_code() can still
2849 * rewrite/sanitize them.
2850 */
2851 if (!vstate->speculative)
2852 env->insn_aux_data[env->insn_idx].seen = true;
2853 }
2854
sanitize_err(struct bpf_verifier_env * env,const struct bpf_insn * insn,int reason,const struct bpf_reg_state * off_reg,const struct bpf_reg_state * dst_reg)2855 static int sanitize_err(struct bpf_verifier_env *env,
2856 const struct bpf_insn *insn, int reason,
2857 const struct bpf_reg_state *off_reg,
2858 const struct bpf_reg_state *dst_reg)
2859 {
2860 static const char *err = "pointer arithmetic with it prohibited for !root";
2861 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
2862 u32 dst = insn->dst_reg, src = insn->src_reg;
2863
2864 switch (reason) {
2865 case REASON_BOUNDS:
2866 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
2867 off_reg == dst_reg ? dst : src, err);
2868 break;
2869 case REASON_TYPE:
2870 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
2871 off_reg == dst_reg ? src : dst, err);
2872 break;
2873 case REASON_PATHS:
2874 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
2875 dst, op, err);
2876 break;
2877 case REASON_LIMIT:
2878 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
2879 dst, op, err);
2880 break;
2881 case REASON_STACK:
2882 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
2883 dst, err);
2884 break;
2885 default:
2886 verbose(env, "verifier internal error: unknown reason (%d)\n",
2887 reason);
2888 break;
2889 }
2890
2891 return -EACCES;
2892 }
2893
2894 /* check that stack access falls within stack limits and that 'reg' doesn't
2895 * have a variable offset.
2896 *
2897 * Variable offset is prohibited for unprivileged mode for simplicity since it
2898 * requires corresponding support in Spectre masking for stack ALU. See also
2899 * retrieve_ptr_limit().
2900 *
2901 *
2902 * 'off' includes 'reg->off'.
2903 */
check_stack_access_for_ptr_arithmetic(struct bpf_verifier_env * env,int regno,const struct bpf_reg_state * reg,int off)2904 static int check_stack_access_for_ptr_arithmetic(
2905 struct bpf_verifier_env *env,
2906 int regno,
2907 const struct bpf_reg_state *reg,
2908 int off)
2909 {
2910 if (!tnum_is_const(reg->var_off)) {
2911 char tn_buf[48];
2912
2913 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2914 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
2915 regno, tn_buf, off);
2916 return -EACCES;
2917 }
2918
2919 if (off >= 0 || off < -MAX_BPF_STACK) {
2920 verbose(env, "R%d stack pointer arithmetic goes out of range, "
2921 "prohibited for !root; off=%d\n", regno, off);
2922 return -EACCES;
2923 }
2924
2925 return 0;
2926 }
2927
sanitize_check_bounds(struct bpf_verifier_env * env,const struct bpf_insn * insn,const struct bpf_reg_state * dst_reg)2928 static int sanitize_check_bounds(struct bpf_verifier_env *env,
2929 const struct bpf_insn *insn,
2930 const struct bpf_reg_state *dst_reg)
2931 {
2932 u32 dst = insn->dst_reg;
2933
2934 /* For unprivileged we require that resulting offset must be in bounds
2935 * in order to be able to sanitize access later on.
2936 */
2937 if (env->allow_ptr_leaks)
2938 return 0;
2939
2940 switch (dst_reg->type) {
2941 case PTR_TO_STACK:
2942 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
2943 dst_reg->off + dst_reg->var_off.value))
2944 return -EACCES;
2945 break;
2946 case PTR_TO_MAP_VALUE:
2947 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
2948 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
2949 "prohibited for !root\n", dst);
2950 return -EACCES;
2951 }
2952 break;
2953 default:
2954 break;
2955 }
2956
2957 return 0;
2958 }
2959
2960 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
2961 * Caller should also handle BPF_MOV case separately.
2962 * If we return -EACCES, caller may want to try again treating pointer as a
2963 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
2964 */
adjust_ptr_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,const struct bpf_reg_state * ptr_reg,const struct bpf_reg_state * off_reg)2965 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
2966 struct bpf_insn *insn,
2967 const struct bpf_reg_state *ptr_reg,
2968 const struct bpf_reg_state *off_reg)
2969 {
2970 struct bpf_verifier_state *vstate = env->cur_state;
2971 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2972 struct bpf_reg_state *regs = state->regs, *dst_reg;
2973 bool known = tnum_is_const(off_reg->var_off);
2974 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
2975 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
2976 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
2977 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
2978 struct bpf_sanitize_info info = {};
2979 u8 opcode = BPF_OP(insn->code);
2980 u32 dst = insn->dst_reg;
2981 int ret;
2982
2983 dst_reg = ®s[dst];
2984
2985 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
2986 smin_val > smax_val || umin_val > umax_val) {
2987 /* Taint dst register if offset had invalid bounds derived from
2988 * e.g. dead branches.
2989 */
2990 __mark_reg_unknown(dst_reg);
2991 return 0;
2992 }
2993
2994 if (BPF_CLASS(insn->code) != BPF_ALU64) {
2995 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
2996 verbose(env,
2997 "R%d 32-bit pointer arithmetic prohibited\n",
2998 dst);
2999 return -EACCES;
3000 }
3001
3002 if (ptr_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
3003 verbose(env, "R%d pointer arithmetic on PTR_TO_MAP_VALUE_OR_NULL prohibited, null-check it first\n",
3004 dst);
3005 return -EACCES;
3006 }
3007 if (ptr_reg->type == CONST_PTR_TO_MAP) {
3008 verbose(env, "R%d pointer arithmetic on CONST_PTR_TO_MAP prohibited\n",
3009 dst);
3010 return -EACCES;
3011 }
3012 if (ptr_reg->type == PTR_TO_PACKET_END) {
3013 verbose(env, "R%d pointer arithmetic on PTR_TO_PACKET_END prohibited\n",
3014 dst);
3015 return -EACCES;
3016 }
3017
3018 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
3019 * The id may be overwritten later if we create a new variable offset.
3020 */
3021 dst_reg->type = ptr_reg->type;
3022 dst_reg->id = ptr_reg->id;
3023
3024 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
3025 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
3026 return -EINVAL;
3027
3028 if (sanitize_needed(opcode)) {
3029 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3030 &info, false);
3031 if (ret < 0)
3032 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3033 }
3034
3035 switch (opcode) {
3036 case BPF_ADD:
3037 /* We can take a fixed offset as long as it doesn't overflow
3038 * the s32 'off' field
3039 */
3040 if (known && (ptr_reg->off + smin_val ==
3041 (s64)(s32)(ptr_reg->off + smin_val))) {
3042 /* pointer += K. Accumulate it into fixed offset */
3043 dst_reg->smin_value = smin_ptr;
3044 dst_reg->smax_value = smax_ptr;
3045 dst_reg->umin_value = umin_ptr;
3046 dst_reg->umax_value = umax_ptr;
3047 dst_reg->var_off = ptr_reg->var_off;
3048 dst_reg->off = ptr_reg->off + smin_val;
3049 dst_reg->raw = ptr_reg->raw;
3050 break;
3051 }
3052 /* A new variable offset is created. Note that off_reg->off
3053 * == 0, since it's a scalar.
3054 * dst_reg gets the pointer type and since some positive
3055 * integer value was added to the pointer, give it a new 'id'
3056 * if it's a PTR_TO_PACKET.
3057 * this creates a new 'base' pointer, off_reg (variable) gets
3058 * added into the variable offset, and we copy the fixed offset
3059 * from ptr_reg.
3060 */
3061 if (signed_add_overflows(smin_ptr, smin_val) ||
3062 signed_add_overflows(smax_ptr, smax_val)) {
3063 dst_reg->smin_value = S64_MIN;
3064 dst_reg->smax_value = S64_MAX;
3065 } else {
3066 dst_reg->smin_value = smin_ptr + smin_val;
3067 dst_reg->smax_value = smax_ptr + smax_val;
3068 }
3069 if (umin_ptr + umin_val < umin_ptr ||
3070 umax_ptr + umax_val < umax_ptr) {
3071 dst_reg->umin_value = 0;
3072 dst_reg->umax_value = U64_MAX;
3073 } else {
3074 dst_reg->umin_value = umin_ptr + umin_val;
3075 dst_reg->umax_value = umax_ptr + umax_val;
3076 }
3077 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
3078 dst_reg->off = ptr_reg->off;
3079 dst_reg->raw = ptr_reg->raw;
3080 if (reg_is_pkt_pointer(ptr_reg)) {
3081 dst_reg->id = ++env->id_gen;
3082 /* something was added to pkt_ptr, set range to zero */
3083 dst_reg->raw = 0;
3084 }
3085 break;
3086 case BPF_SUB:
3087 if (dst_reg == off_reg) {
3088 /* scalar -= pointer. Creates an unknown scalar */
3089 verbose(env, "R%d tried to subtract pointer from scalar\n",
3090 dst);
3091 return -EACCES;
3092 }
3093 /* We don't allow subtraction from FP, because (according to
3094 * test_verifier.c test "invalid fp arithmetic", JITs might not
3095 * be able to deal with it.
3096 */
3097 if (ptr_reg->type == PTR_TO_STACK) {
3098 verbose(env, "R%d subtraction from stack pointer prohibited\n",
3099 dst);
3100 return -EACCES;
3101 }
3102 if (known && (ptr_reg->off - smin_val ==
3103 (s64)(s32)(ptr_reg->off - smin_val))) {
3104 /* pointer -= K. Subtract it from fixed offset */
3105 dst_reg->smin_value = smin_ptr;
3106 dst_reg->smax_value = smax_ptr;
3107 dst_reg->umin_value = umin_ptr;
3108 dst_reg->umax_value = umax_ptr;
3109 dst_reg->var_off = ptr_reg->var_off;
3110 dst_reg->id = ptr_reg->id;
3111 dst_reg->off = ptr_reg->off - smin_val;
3112 dst_reg->raw = ptr_reg->raw;
3113 break;
3114 }
3115 /* A new variable offset is created. If the subtrahend is known
3116 * nonnegative, then any reg->range we had before is still good.
3117 */
3118 if (signed_sub_overflows(smin_ptr, smax_val) ||
3119 signed_sub_overflows(smax_ptr, smin_val)) {
3120 /* Overflow possible, we know nothing */
3121 dst_reg->smin_value = S64_MIN;
3122 dst_reg->smax_value = S64_MAX;
3123 } else {
3124 dst_reg->smin_value = smin_ptr - smax_val;
3125 dst_reg->smax_value = smax_ptr - smin_val;
3126 }
3127 if (umin_ptr < umax_val) {
3128 /* Overflow possible, we know nothing */
3129 dst_reg->umin_value = 0;
3130 dst_reg->umax_value = U64_MAX;
3131 } else {
3132 /* Cannot overflow (as long as bounds are consistent) */
3133 dst_reg->umin_value = umin_ptr - umax_val;
3134 dst_reg->umax_value = umax_ptr - umin_val;
3135 }
3136 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
3137 dst_reg->off = ptr_reg->off;
3138 dst_reg->raw = ptr_reg->raw;
3139 if (reg_is_pkt_pointer(ptr_reg)) {
3140 dst_reg->id = ++env->id_gen;
3141 /* something was added to pkt_ptr, set range to zero */
3142 if (smin_val < 0)
3143 dst_reg->raw = 0;
3144 }
3145 break;
3146 case BPF_AND:
3147 case BPF_OR:
3148 case BPF_XOR:
3149 /* bitwise ops on pointers are troublesome, prohibit. */
3150 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
3151 dst, bpf_alu_string[opcode >> 4]);
3152 return -EACCES;
3153 default:
3154 /* other operators (e.g. MUL,LSH) produce non-pointer results */
3155 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
3156 dst, bpf_alu_string[opcode >> 4]);
3157 return -EACCES;
3158 }
3159
3160 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
3161 return -EINVAL;
3162
3163 __update_reg_bounds(dst_reg);
3164 __reg_deduce_bounds(dst_reg);
3165 __reg_bound_offset(dst_reg);
3166
3167
3168 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
3169 return -EACCES;
3170 if (sanitize_needed(opcode)) {
3171 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3172 &info, true);
3173 if (ret < 0)
3174 return sanitize_err(env, insn, ret, off_reg, dst_reg);
3175 }
3176
3177 return 0;
3178 }
3179
3180 /* WARNING: This function does calculations on 64-bit values, but the actual
3181 * execution may occur on 32-bit values. Therefore, things like bitshifts
3182 * need extra checks in the 32-bit case.
3183 */
adjust_scalar_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state src_reg)3184 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
3185 struct bpf_insn *insn,
3186 struct bpf_reg_state *dst_reg,
3187 struct bpf_reg_state src_reg)
3188 {
3189 struct bpf_reg_state *regs = cur_regs(env);
3190 u8 opcode = BPF_OP(insn->code);
3191 bool src_known, dst_known;
3192 s64 smin_val, smax_val;
3193 u64 umin_val, umax_val;
3194 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3195 int ret;
3196
3197 if (insn_bitness == 32) {
3198 /* Relevant for 32-bit RSH: Information can propagate towards
3199 * LSB, so it isn't sufficient to only truncate the output to
3200 * 32 bits.
3201 */
3202 coerce_reg_to_size(dst_reg, 4);
3203 coerce_reg_to_size(&src_reg, 4);
3204 }
3205
3206 smin_val = src_reg.smin_value;
3207 smax_val = src_reg.smax_value;
3208 umin_val = src_reg.umin_value;
3209 umax_val = src_reg.umax_value;
3210 src_known = tnum_is_const(src_reg.var_off);
3211 dst_known = tnum_is_const(dst_reg->var_off);
3212
3213 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) ||
3214 smin_val > smax_val || umin_val > umax_val) {
3215 /* Taint dst register if offset had invalid bounds derived from
3216 * e.g. dead branches.
3217 */
3218 __mark_reg_unknown(dst_reg);
3219 return 0;
3220 }
3221
3222 if (!src_known &&
3223 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
3224 __mark_reg_unknown(dst_reg);
3225 return 0;
3226 }
3227
3228 if (sanitize_needed(opcode)) {
3229 ret = sanitize_val_alu(env, insn);
3230 if (ret < 0)
3231 return sanitize_err(env, insn, ret, NULL, NULL);
3232 }
3233
3234 switch (opcode) {
3235 case BPF_ADD:
3236 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
3237 signed_add_overflows(dst_reg->smax_value, smax_val)) {
3238 dst_reg->smin_value = S64_MIN;
3239 dst_reg->smax_value = S64_MAX;
3240 } else {
3241 dst_reg->smin_value += smin_val;
3242 dst_reg->smax_value += smax_val;
3243 }
3244 if (dst_reg->umin_value + umin_val < umin_val ||
3245 dst_reg->umax_value + umax_val < umax_val) {
3246 dst_reg->umin_value = 0;
3247 dst_reg->umax_value = U64_MAX;
3248 } else {
3249 dst_reg->umin_value += umin_val;
3250 dst_reg->umax_value += umax_val;
3251 }
3252 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
3253 break;
3254 case BPF_SUB:
3255 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
3256 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
3257 /* Overflow possible, we know nothing */
3258 dst_reg->smin_value = S64_MIN;
3259 dst_reg->smax_value = S64_MAX;
3260 } else {
3261 dst_reg->smin_value -= smax_val;
3262 dst_reg->smax_value -= smin_val;
3263 }
3264 if (dst_reg->umin_value < umax_val) {
3265 /* Overflow possible, we know nothing */
3266 dst_reg->umin_value = 0;
3267 dst_reg->umax_value = U64_MAX;
3268 } else {
3269 /* Cannot overflow (as long as bounds are consistent) */
3270 dst_reg->umin_value -= umax_val;
3271 dst_reg->umax_value -= umin_val;
3272 }
3273 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
3274 break;
3275 case BPF_MUL:
3276 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
3277 if (smin_val < 0 || dst_reg->smin_value < 0) {
3278 /* Ain't nobody got time to multiply that sign */
3279 __mark_reg_unbounded(dst_reg);
3280 __update_reg_bounds(dst_reg);
3281 break;
3282 }
3283 /* Both values are positive, so we can work with unsigned and
3284 * copy the result to signed (unless it exceeds S64_MAX).
3285 */
3286 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
3287 /* Potential overflow, we know nothing */
3288 __mark_reg_unbounded(dst_reg);
3289 /* (except what we can learn from the var_off) */
3290 __update_reg_bounds(dst_reg);
3291 break;
3292 }
3293 dst_reg->umin_value *= umin_val;
3294 dst_reg->umax_value *= umax_val;
3295 if (dst_reg->umax_value > S64_MAX) {
3296 /* Overflow possible, we know nothing */
3297 dst_reg->smin_value = S64_MIN;
3298 dst_reg->smax_value = S64_MAX;
3299 } else {
3300 dst_reg->smin_value = dst_reg->umin_value;
3301 dst_reg->smax_value = dst_reg->umax_value;
3302 }
3303 break;
3304 case BPF_AND:
3305 if (src_known && dst_known) {
3306 __mark_reg_known(dst_reg, dst_reg->var_off.value &
3307 src_reg.var_off.value);
3308 break;
3309 }
3310 /* We get our minimum from the var_off, since that's inherently
3311 * bitwise. Our maximum is the minimum of the operands' maxima.
3312 */
3313 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
3314 dst_reg->umin_value = dst_reg->var_off.value;
3315 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
3316 if (dst_reg->smin_value < 0 || smin_val < 0) {
3317 /* Lose signed bounds when ANDing negative numbers,
3318 * ain't nobody got time for that.
3319 */
3320 dst_reg->smin_value = S64_MIN;
3321 dst_reg->smax_value = S64_MAX;
3322 } else {
3323 /* ANDing two positives gives a positive, so safe to
3324 * cast result into s64.
3325 */
3326 dst_reg->smin_value = dst_reg->umin_value;
3327 dst_reg->smax_value = dst_reg->umax_value;
3328 }
3329 /* We may learn something more from the var_off */
3330 __update_reg_bounds(dst_reg);
3331 break;
3332 case BPF_OR:
3333 if (src_known && dst_known) {
3334 __mark_reg_known(dst_reg, dst_reg->var_off.value |
3335 src_reg.var_off.value);
3336 break;
3337 }
3338 /* We get our maximum from the var_off, and our minimum is the
3339 * maximum of the operands' minima
3340 */
3341 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
3342 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
3343 dst_reg->umax_value = dst_reg->var_off.value |
3344 dst_reg->var_off.mask;
3345 if (dst_reg->smin_value < 0 || smin_val < 0) {
3346 /* Lose signed bounds when ORing negative numbers,
3347 * ain't nobody got time for that.
3348 */
3349 dst_reg->smin_value = S64_MIN;
3350 dst_reg->smax_value = S64_MAX;
3351 } else {
3352 /* ORing two positives gives a positive, so safe to
3353 * cast result into s64.
3354 */
3355 dst_reg->smin_value = dst_reg->umin_value;
3356 dst_reg->smax_value = dst_reg->umax_value;
3357 }
3358 /* We may learn something more from the var_off */
3359 __update_reg_bounds(dst_reg);
3360 break;
3361 case BPF_LSH:
3362 if (umax_val >= insn_bitness) {
3363 /* Shifts greater than 31 or 63 are undefined.
3364 * This includes shifts by a negative number.
3365 */
3366 mark_reg_unknown(env, regs, insn->dst_reg);
3367 break;
3368 }
3369 /* We lose all sign bit information (except what we can pick
3370 * up from var_off)
3371 */
3372 dst_reg->smin_value = S64_MIN;
3373 dst_reg->smax_value = S64_MAX;
3374 /* If we might shift our top bit out, then we know nothing */
3375 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
3376 dst_reg->umin_value = 0;
3377 dst_reg->umax_value = U64_MAX;
3378 } else {
3379 dst_reg->umin_value <<= umin_val;
3380 dst_reg->umax_value <<= umax_val;
3381 }
3382 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
3383 /* We may learn something more from the var_off */
3384 __update_reg_bounds(dst_reg);
3385 break;
3386 case BPF_RSH:
3387 if (umax_val >= insn_bitness) {
3388 /* Shifts greater than 31 or 63 are undefined.
3389 * This includes shifts by a negative number.
3390 */
3391 mark_reg_unknown(env, regs, insn->dst_reg);
3392 break;
3393 }
3394 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
3395 * be negative, then either:
3396 * 1) src_reg might be zero, so the sign bit of the result is
3397 * unknown, so we lose our signed bounds
3398 * 2) it's known negative, thus the unsigned bounds capture the
3399 * signed bounds
3400 * 3) the signed bounds cross zero, so they tell us nothing
3401 * about the result
3402 * If the value in dst_reg is known nonnegative, then again the
3403 * unsigned bounts capture the signed bounds.
3404 * Thus, in all cases it suffices to blow away our signed bounds
3405 * and rely on inferring new ones from the unsigned bounds and
3406 * var_off of the result.
3407 */
3408 dst_reg->smin_value = S64_MIN;
3409 dst_reg->smax_value = S64_MAX;
3410 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
3411 dst_reg->umin_value >>= umax_val;
3412 dst_reg->umax_value >>= umin_val;
3413 /* We may learn something more from the var_off */
3414 __update_reg_bounds(dst_reg);
3415 break;
3416 case BPF_ARSH:
3417 if (umax_val >= insn_bitness) {
3418 /* Shifts greater than 31 or 63 are undefined.
3419 * This includes shifts by a negative number.
3420 */
3421 mark_reg_unknown(env, regs, insn->dst_reg);
3422 break;
3423 }
3424
3425 /* Upon reaching here, src_known is true and
3426 * umax_val is equal to umin_val.
3427 */
3428 if (insn_bitness == 32) {
3429 dst_reg->smin_value = (u32)(((s32)dst_reg->smin_value) >> umin_val);
3430 dst_reg->smax_value = (u32)(((s32)dst_reg->smax_value) >> umin_val);
3431 } else {
3432 dst_reg->smin_value >>= umin_val;
3433 dst_reg->smax_value >>= umin_val;
3434 }
3435
3436 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val,
3437 insn_bitness);
3438
3439 /* blow away the dst_reg umin_value/umax_value and rely on
3440 * dst_reg var_off to refine the result.
3441 */
3442 dst_reg->umin_value = 0;
3443 dst_reg->umax_value = U64_MAX;
3444 __update_reg_bounds(dst_reg);
3445 break;
3446 default:
3447 mark_reg_unknown(env, regs, insn->dst_reg);
3448 break;
3449 }
3450
3451 if (BPF_CLASS(insn->code) != BPF_ALU64) {
3452 /* 32-bit ALU ops are (32,32)->32 */
3453 coerce_reg_to_size(dst_reg, 4);
3454 }
3455
3456 __reg_deduce_bounds(dst_reg);
3457 __reg_bound_offset(dst_reg);
3458 return 0;
3459 }
3460
3461 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
3462 * and var_off.
3463 */
adjust_reg_min_max_vals(struct bpf_verifier_env * env,struct bpf_insn * insn)3464 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
3465 struct bpf_insn *insn)
3466 {
3467 struct bpf_verifier_state *vstate = env->cur_state;
3468 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3469 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
3470 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
3471 u8 opcode = BPF_OP(insn->code);
3472
3473 dst_reg = ®s[insn->dst_reg];
3474 src_reg = NULL;
3475 if (dst_reg->type != SCALAR_VALUE)
3476 ptr_reg = dst_reg;
3477 if (BPF_SRC(insn->code) == BPF_X) {
3478 src_reg = ®s[insn->src_reg];
3479 if (src_reg->type != SCALAR_VALUE) {
3480 if (dst_reg->type != SCALAR_VALUE) {
3481 /* Combining two pointers by any ALU op yields
3482 * an arbitrary scalar. Disallow all math except
3483 * pointer subtraction
3484 */
3485 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
3486 mark_reg_unknown(env, regs, insn->dst_reg);
3487 return 0;
3488 }
3489 verbose(env, "R%d pointer %s pointer prohibited\n",
3490 insn->dst_reg,
3491 bpf_alu_string[opcode >> 4]);
3492 return -EACCES;
3493 } else {
3494 /* scalar += pointer
3495 * This is legal, but we have to reverse our
3496 * src/dest handling in computing the range
3497 */
3498 return adjust_ptr_min_max_vals(env, insn,
3499 src_reg, dst_reg);
3500 }
3501 } else if (ptr_reg) {
3502 /* pointer += scalar */
3503 return adjust_ptr_min_max_vals(env, insn,
3504 dst_reg, src_reg);
3505 }
3506 } else {
3507 /* Pretend the src is a reg with a known value, since we only
3508 * need to be able to read from this state.
3509 */
3510 off_reg.type = SCALAR_VALUE;
3511 __mark_reg_known(&off_reg, insn->imm);
3512 src_reg = &off_reg;
3513 if (ptr_reg) /* pointer += K */
3514 return adjust_ptr_min_max_vals(env, insn,
3515 ptr_reg, src_reg);
3516 }
3517
3518 /* Got here implies adding two SCALAR_VALUEs */
3519 if (WARN_ON_ONCE(ptr_reg)) {
3520 print_verifier_state(env, state);
3521 verbose(env, "verifier internal error: unexpected ptr_reg\n");
3522 return -EINVAL;
3523 }
3524 if (WARN_ON(!src_reg)) {
3525 print_verifier_state(env, state);
3526 verbose(env, "verifier internal error: no src_reg\n");
3527 return -EINVAL;
3528 }
3529 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
3530 }
3531
3532 /* check validity of 32-bit and 64-bit arithmetic operations */
check_alu_op(struct bpf_verifier_env * env,struct bpf_insn * insn)3533 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
3534 {
3535 struct bpf_reg_state *regs = cur_regs(env);
3536 u8 opcode = BPF_OP(insn->code);
3537 int err;
3538
3539 if (opcode == BPF_END || opcode == BPF_NEG) {
3540 if (opcode == BPF_NEG) {
3541 if (BPF_SRC(insn->code) != 0 ||
3542 insn->src_reg != BPF_REG_0 ||
3543 insn->off != 0 || insn->imm != 0) {
3544 verbose(env, "BPF_NEG uses reserved fields\n");
3545 return -EINVAL;
3546 }
3547 } else {
3548 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
3549 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
3550 BPF_CLASS(insn->code) == BPF_ALU64) {
3551 verbose(env, "BPF_END uses reserved fields\n");
3552 return -EINVAL;
3553 }
3554 }
3555
3556 /* check src operand */
3557 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3558 if (err)
3559 return err;
3560
3561 if (is_pointer_value(env, insn->dst_reg)) {
3562 verbose(env, "R%d pointer arithmetic prohibited\n",
3563 insn->dst_reg);
3564 return -EACCES;
3565 }
3566
3567 /* check dest operand */
3568 err = check_reg_arg(env, insn->dst_reg, DST_OP);
3569 if (err)
3570 return err;
3571
3572 } else if (opcode == BPF_MOV) {
3573
3574 if (BPF_SRC(insn->code) == BPF_X) {
3575 if (insn->imm != 0 || insn->off != 0) {
3576 verbose(env, "BPF_MOV uses reserved fields\n");
3577 return -EINVAL;
3578 }
3579
3580 /* check src operand */
3581 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3582 if (err)
3583 return err;
3584 } else {
3585 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3586 verbose(env, "BPF_MOV uses reserved fields\n");
3587 return -EINVAL;
3588 }
3589 }
3590
3591 /* check dest operand, mark as required later */
3592 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3593 if (err)
3594 return err;
3595
3596 if (BPF_SRC(insn->code) == BPF_X) {
3597 struct bpf_reg_state *src_reg = regs + insn->src_reg;
3598 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
3599
3600 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3601 /* case: R1 = R2
3602 * copy register state to dest reg
3603 */
3604 *dst_reg = *src_reg;
3605 dst_reg->live |= REG_LIVE_WRITTEN;
3606 } else {
3607 /* R1 = (u32) R2 */
3608 if (is_pointer_value(env, insn->src_reg)) {
3609 verbose(env,
3610 "R%d partial copy of pointer\n",
3611 insn->src_reg);
3612 return -EACCES;
3613 } else if (src_reg->type == SCALAR_VALUE) {
3614 *dst_reg = *src_reg;
3615 dst_reg->live |= REG_LIVE_WRITTEN;
3616 } else {
3617 mark_reg_unknown(env, regs,
3618 insn->dst_reg);
3619 }
3620 coerce_reg_to_size(dst_reg, 4);
3621 }
3622 } else {
3623 /* case: R = imm
3624 * remember the value we stored into this reg
3625 */
3626 /* clear any state __mark_reg_known doesn't set */
3627 mark_reg_unknown(env, regs, insn->dst_reg);
3628 regs[insn->dst_reg].type = SCALAR_VALUE;
3629 if (BPF_CLASS(insn->code) == BPF_ALU64) {
3630 __mark_reg_known(regs + insn->dst_reg,
3631 insn->imm);
3632 } else {
3633 __mark_reg_known(regs + insn->dst_reg,
3634 (u32)insn->imm);
3635 }
3636 }
3637
3638 } else if (opcode > BPF_END) {
3639 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
3640 return -EINVAL;
3641
3642 } else { /* all other ALU ops: and, sub, xor, add, ... */
3643
3644 if (BPF_SRC(insn->code) == BPF_X) {
3645 if (insn->imm != 0 || insn->off != 0) {
3646 verbose(env, "BPF_ALU uses reserved fields\n");
3647 return -EINVAL;
3648 }
3649 /* check src1 operand */
3650 err = check_reg_arg(env, insn->src_reg, SRC_OP);
3651 if (err)
3652 return err;
3653 } else {
3654 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
3655 verbose(env, "BPF_ALU uses reserved fields\n");
3656 return -EINVAL;
3657 }
3658 }
3659
3660 /* check src2 operand */
3661 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
3662 if (err)
3663 return err;
3664
3665 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
3666 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
3667 verbose(env, "div by zero\n");
3668 return -EINVAL;
3669 }
3670
3671 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) {
3672 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n");
3673 return -EINVAL;
3674 }
3675
3676 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
3677 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
3678 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
3679
3680 if (insn->imm < 0 || insn->imm >= size) {
3681 verbose(env, "invalid shift %d\n", insn->imm);
3682 return -EINVAL;
3683 }
3684 }
3685
3686 /* check dest operand */
3687 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
3688 if (err)
3689 return err;
3690
3691 return adjust_reg_min_max_vals(env, insn);
3692 }
3693
3694 return 0;
3695 }
3696
find_good_pkt_pointers(struct bpf_verifier_state * vstate,struct bpf_reg_state * dst_reg,enum bpf_reg_type type,bool range_right_open)3697 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
3698 struct bpf_reg_state *dst_reg,
3699 enum bpf_reg_type type,
3700 bool range_right_open)
3701 {
3702 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3703 struct bpf_reg_state *regs = state->regs, *reg;
3704 u16 new_range;
3705 int i, j;
3706
3707 if (dst_reg->off < 0 ||
3708 (dst_reg->off == 0 && range_right_open))
3709 /* This doesn't give us any range */
3710 return;
3711
3712 if (dst_reg->umax_value > MAX_PACKET_OFF ||
3713 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
3714 /* Risk of overflow. For instance, ptr + (1<<63) may be less
3715 * than pkt_end, but that's because it's also less than pkt.
3716 */
3717 return;
3718
3719 new_range = dst_reg->off;
3720 if (range_right_open)
3721 new_range--;
3722
3723 /* Examples for register markings:
3724 *
3725 * pkt_data in dst register:
3726 *
3727 * r2 = r3;
3728 * r2 += 8;
3729 * if (r2 > pkt_end) goto <handle exception>
3730 * <access okay>
3731 *
3732 * r2 = r3;
3733 * r2 += 8;
3734 * if (r2 < pkt_end) goto <access okay>
3735 * <handle exception>
3736 *
3737 * Where:
3738 * r2 == dst_reg, pkt_end == src_reg
3739 * r2=pkt(id=n,off=8,r=0)
3740 * r3=pkt(id=n,off=0,r=0)
3741 *
3742 * pkt_data in src register:
3743 *
3744 * r2 = r3;
3745 * r2 += 8;
3746 * if (pkt_end >= r2) goto <access okay>
3747 * <handle exception>
3748 *
3749 * r2 = r3;
3750 * r2 += 8;
3751 * if (pkt_end <= r2) goto <handle exception>
3752 * <access okay>
3753 *
3754 * Where:
3755 * pkt_end == dst_reg, r2 == src_reg
3756 * r2=pkt(id=n,off=8,r=0)
3757 * r3=pkt(id=n,off=0,r=0)
3758 *
3759 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
3760 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
3761 * and [r3, r3 + 8-1) respectively is safe to access depending on
3762 * the check.
3763 */
3764
3765 /* If our ids match, then we must have the same max_value. And we
3766 * don't care about the other reg's fixed offset, since if it's too big
3767 * the range won't allow anything.
3768 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
3769 */
3770 for (i = 0; i < MAX_BPF_REG; i++)
3771 if (regs[i].type == type && regs[i].id == dst_reg->id)
3772 /* keep the maximum range already checked */
3773 regs[i].range = max(regs[i].range, new_range);
3774
3775 for (j = 0; j <= vstate->curframe; j++) {
3776 state = vstate->frame[j];
3777 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
3778 if (state->stack[i].slot_type[0] != STACK_SPILL)
3779 continue;
3780 reg = &state->stack[i].spilled_ptr;
3781 if (reg->type == type && reg->id == dst_reg->id)
3782 reg->range = max(reg->range, new_range);
3783 }
3784 }
3785 }
3786
3787 /* compute branch direction of the expression "if (reg opcode val) goto target;"
3788 * and return:
3789 * 1 - branch will be taken and "goto target" will be executed
3790 * 0 - branch will not be taken and fall-through to next insn
3791 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10]
3792 */
is_branch_taken(struct bpf_reg_state * reg,u64 val,u8 opcode,bool is_jmp32)3793 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
3794 bool is_jmp32)
3795 {
3796 struct bpf_reg_state reg_lo;
3797 s64 sval;
3798
3799 if (__is_pointer_value(false, reg))
3800 return -1;
3801
3802 if (is_jmp32) {
3803 reg_lo = *reg;
3804 reg = ®_lo;
3805 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size
3806 * could truncate high bits and update umin/umax according to
3807 * information of low bits.
3808 */
3809 coerce_reg_to_size(reg, 4);
3810 /* smin/smax need special handling. For example, after coerce,
3811 * if smin_value is 0x00000000ffffffffLL, the value is -1 when
3812 * used as operand to JMP32. It is a negative number from s32's
3813 * point of view, while it is a positive number when seen as
3814 * s64. The smin/smax are kept as s64, therefore, when used with
3815 * JMP32, they need to be transformed into s32, then sign
3816 * extended back to s64.
3817 *
3818 * Also, smin/smax were copied from umin/umax. If umin/umax has
3819 * different sign bit, then min/max relationship doesn't
3820 * maintain after casting into s32, for this case, set smin/smax
3821 * to safest range.
3822 */
3823 if ((reg->umax_value ^ reg->umin_value) &
3824 (1ULL << 31)) {
3825 reg->smin_value = S32_MIN;
3826 reg->smax_value = S32_MAX;
3827 }
3828 reg->smin_value = (s64)(s32)reg->smin_value;
3829 reg->smax_value = (s64)(s32)reg->smax_value;
3830
3831 val = (u32)val;
3832 sval = (s64)(s32)val;
3833 } else {
3834 sval = (s64)val;
3835 }
3836
3837 switch (opcode) {
3838 case BPF_JEQ:
3839 if (tnum_is_const(reg->var_off))
3840 return !!tnum_equals_const(reg->var_off, val);
3841 break;
3842 case BPF_JNE:
3843 if (tnum_is_const(reg->var_off))
3844 return !tnum_equals_const(reg->var_off, val);
3845 break;
3846 case BPF_JGT:
3847 if (reg->umin_value > val)
3848 return 1;
3849 else if (reg->umax_value <= val)
3850 return 0;
3851 break;
3852 case BPF_JSGT:
3853 if (reg->smin_value > sval)
3854 return 1;
3855 else if (reg->smax_value < sval)
3856 return 0;
3857 break;
3858 case BPF_JLT:
3859 if (reg->umax_value < val)
3860 return 1;
3861 else if (reg->umin_value >= val)
3862 return 0;
3863 break;
3864 case BPF_JSLT:
3865 if (reg->smax_value < sval)
3866 return 1;
3867 else if (reg->smin_value >= sval)
3868 return 0;
3869 break;
3870 case BPF_JGE:
3871 if (reg->umin_value >= val)
3872 return 1;
3873 else if (reg->umax_value < val)
3874 return 0;
3875 break;
3876 case BPF_JSGE:
3877 if (reg->smin_value >= sval)
3878 return 1;
3879 else if (reg->smax_value < sval)
3880 return 0;
3881 break;
3882 case BPF_JLE:
3883 if (reg->umax_value <= val)
3884 return 1;
3885 else if (reg->umin_value > val)
3886 return 0;
3887 break;
3888 case BPF_JSLE:
3889 if (reg->smax_value <= sval)
3890 return 1;
3891 else if (reg->smin_value > sval)
3892 return 0;
3893 break;
3894 }
3895
3896 return -1;
3897 }
3898
3899 /* Generate min value of the high 32-bit from TNUM info. */
gen_hi_min(struct tnum var)3900 static u64 gen_hi_min(struct tnum var)
3901 {
3902 return var.value & ~0xffffffffULL;
3903 }
3904
3905 /* Generate max value of the high 32-bit from TNUM info. */
gen_hi_max(struct tnum var)3906 static u64 gen_hi_max(struct tnum var)
3907 {
3908 return (var.value | var.mask) & ~0xffffffffULL;
3909 }
3910
3911 /* Return true if VAL is compared with a s64 sign extended from s32, and they
3912 * are with the same signedness.
3913 */
cmp_val_with_extended_s64(s64 sval,struct bpf_reg_state * reg)3914 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg)
3915 {
3916 return ((s32)sval >= 0 &&
3917 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) ||
3918 ((s32)sval < 0 &&
3919 reg->smax_value <= 0 && reg->smin_value >= S32_MIN);
3920 }
3921
3922 /* Adjusts the register min/max values in the case that the dst_reg is the
3923 * variable register that we are working on, and src_reg is a constant or we're
3924 * simply doing a BPF_K check.
3925 * In JEQ/JNE cases we also adjust the var_off values.
3926 */
reg_set_min_max(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode,bool is_jmp32)3927 static void reg_set_min_max(struct bpf_reg_state *true_reg,
3928 struct bpf_reg_state *false_reg, u64 val,
3929 u8 opcode, bool is_jmp32)
3930 {
3931 s64 sval;
3932
3933 /* If the dst_reg is a pointer, we can't learn anything about its
3934 * variable offset from the compare (unless src_reg were a pointer into
3935 * the same object, but we don't bother with that.
3936 * Since false_reg and true_reg have the same type by construction, we
3937 * only need to check one of them for pointerness.
3938 */
3939 if (__is_pointer_value(false, false_reg))
3940 return;
3941 val = is_jmp32 ? (u32)val : val;
3942 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
3943
3944 switch (opcode) {
3945 case BPF_JEQ:
3946 case BPF_JNE:
3947 {
3948 struct bpf_reg_state *reg =
3949 opcode == BPF_JEQ ? true_reg : false_reg;
3950 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but
3951 * if it is true we know the value for sure. Likewise for
3952 * BPF_JNE.
3953 */
3954 if (is_jmp32) {
3955 u64 old_v = reg->var_off.value;
3956 u64 hi_mask = ~0xffffffffULL;
3957
3958 reg->var_off.value = (old_v & hi_mask) | val;
3959 reg->var_off.mask &= hi_mask;
3960 } else {
3961 __mark_reg_known(reg, val);
3962 }
3963 break;
3964 }
3965 case BPF_JGE:
3966 case BPF_JGT:
3967 {
3968 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
3969 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
3970
3971 if (is_jmp32) {
3972 false_umax += gen_hi_max(false_reg->var_off);
3973 true_umin += gen_hi_min(true_reg->var_off);
3974 }
3975 false_reg->umax_value = min(false_reg->umax_value, false_umax);
3976 true_reg->umin_value = max(true_reg->umin_value, true_umin);
3977 break;
3978 }
3979 case BPF_JSGE:
3980 case BPF_JSGT:
3981 {
3982 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
3983 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
3984
3985 /* If the full s64 was not sign-extended from s32 then don't
3986 * deduct further info.
3987 */
3988 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
3989 break;
3990 false_reg->smax_value = min(false_reg->smax_value, false_smax);
3991 true_reg->smin_value = max(true_reg->smin_value, true_smin);
3992 break;
3993 }
3994 case BPF_JLE:
3995 case BPF_JLT:
3996 {
3997 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
3998 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
3999
4000 if (is_jmp32) {
4001 false_umin += gen_hi_min(false_reg->var_off);
4002 true_umax += gen_hi_max(true_reg->var_off);
4003 }
4004 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4005 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4006
4007 break;
4008 }
4009 case BPF_JSLE:
4010 case BPF_JSLT:
4011 {
4012 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
4013 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
4014
4015 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4016 break;
4017 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4018 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4019 break;
4020 }
4021 default:
4022 break;
4023 }
4024
4025 __reg_deduce_bounds(false_reg);
4026 __reg_deduce_bounds(true_reg);
4027 /* We might have learned some bits from the bounds. */
4028 __reg_bound_offset(false_reg);
4029 __reg_bound_offset(true_reg);
4030 /* Intersecting with the old var_off might have improved our bounds
4031 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4032 * then new var_off is (0; 0x7f...fc) which improves our umax.
4033 */
4034 __update_reg_bounds(false_reg);
4035 __update_reg_bounds(true_reg);
4036 }
4037
4038 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
4039 * the variable reg.
4040 */
reg_set_min_max_inv(struct bpf_reg_state * true_reg,struct bpf_reg_state * false_reg,u64 val,u8 opcode,bool is_jmp32)4041 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
4042 struct bpf_reg_state *false_reg, u64 val,
4043 u8 opcode, bool is_jmp32)
4044 {
4045 s64 sval;
4046
4047 if (__is_pointer_value(false, false_reg))
4048 return;
4049
4050 val = is_jmp32 ? (u32)val : val;
4051 sval = is_jmp32 ? (s64)(s32)val : (s64)val;
4052
4053 switch (opcode) {
4054 case BPF_JEQ:
4055 case BPF_JNE:
4056 {
4057 struct bpf_reg_state *reg =
4058 opcode == BPF_JEQ ? true_reg : false_reg;
4059 if (is_jmp32) {
4060 u64 old_v = reg->var_off.value;
4061 u64 hi_mask = ~0xffffffffULL;
4062
4063 reg->var_off.value = (old_v & hi_mask) | val;
4064 reg->var_off.mask &= hi_mask;
4065 } else {
4066 __mark_reg_known(reg, val);
4067 }
4068 break;
4069 }
4070 case BPF_JGE:
4071 case BPF_JGT:
4072 {
4073 u64 false_umin = opcode == BPF_JGT ? val : val + 1;
4074 u64 true_umax = opcode == BPF_JGT ? val - 1 : val;
4075
4076 if (is_jmp32) {
4077 false_umin += gen_hi_min(false_reg->var_off);
4078 true_umax += gen_hi_max(true_reg->var_off);
4079 }
4080 false_reg->umin_value = max(false_reg->umin_value, false_umin);
4081 true_reg->umax_value = min(true_reg->umax_value, true_umax);
4082 break;
4083 }
4084 case BPF_JSGE:
4085 case BPF_JSGT:
4086 {
4087 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1;
4088 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval;
4089
4090 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4091 break;
4092 false_reg->smin_value = max(false_reg->smin_value, false_smin);
4093 true_reg->smax_value = min(true_reg->smax_value, true_smax);
4094 break;
4095 }
4096 case BPF_JLE:
4097 case BPF_JLT:
4098 {
4099 u64 false_umax = opcode == BPF_JLT ? val : val - 1;
4100 u64 true_umin = opcode == BPF_JLT ? val + 1 : val;
4101
4102 if (is_jmp32) {
4103 false_umax += gen_hi_max(false_reg->var_off);
4104 true_umin += gen_hi_min(true_reg->var_off);
4105 }
4106 false_reg->umax_value = min(false_reg->umax_value, false_umax);
4107 true_reg->umin_value = max(true_reg->umin_value, true_umin);
4108 break;
4109 }
4110 case BPF_JSLE:
4111 case BPF_JSLT:
4112 {
4113 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1;
4114 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval;
4115
4116 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg))
4117 break;
4118 false_reg->smax_value = min(false_reg->smax_value, false_smax);
4119 true_reg->smin_value = max(true_reg->smin_value, true_smin);
4120 break;
4121 }
4122 default:
4123 break;
4124 }
4125
4126 __reg_deduce_bounds(false_reg);
4127 __reg_deduce_bounds(true_reg);
4128 /* We might have learned some bits from the bounds. */
4129 __reg_bound_offset(false_reg);
4130 __reg_bound_offset(true_reg);
4131 /* Intersecting with the old var_off might have improved our bounds
4132 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4133 * then new var_off is (0; 0x7f...fc) which improves our umax.
4134 */
4135 __update_reg_bounds(false_reg);
4136 __update_reg_bounds(true_reg);
4137 }
4138
4139 /* Regs are known to be equal, so intersect their min/max/var_off */
__reg_combine_min_max(struct bpf_reg_state * src_reg,struct bpf_reg_state * dst_reg)4140 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
4141 struct bpf_reg_state *dst_reg)
4142 {
4143 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
4144 dst_reg->umin_value);
4145 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
4146 dst_reg->umax_value);
4147 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
4148 dst_reg->smin_value);
4149 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
4150 dst_reg->smax_value);
4151 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
4152 dst_reg->var_off);
4153 /* We might have learned new bounds from the var_off. */
4154 __update_reg_bounds(src_reg);
4155 __update_reg_bounds(dst_reg);
4156 /* We might have learned something about the sign bit. */
4157 __reg_deduce_bounds(src_reg);
4158 __reg_deduce_bounds(dst_reg);
4159 /* We might have learned some bits from the bounds. */
4160 __reg_bound_offset(src_reg);
4161 __reg_bound_offset(dst_reg);
4162 /* Intersecting with the old var_off might have improved our bounds
4163 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
4164 * then new var_off is (0; 0x7f...fc) which improves our umax.
4165 */
4166 __update_reg_bounds(src_reg);
4167 __update_reg_bounds(dst_reg);
4168 }
4169
reg_combine_min_max(struct bpf_reg_state * true_src,struct bpf_reg_state * true_dst,struct bpf_reg_state * false_src,struct bpf_reg_state * false_dst,u8 opcode)4170 static void reg_combine_min_max(struct bpf_reg_state *true_src,
4171 struct bpf_reg_state *true_dst,
4172 struct bpf_reg_state *false_src,
4173 struct bpf_reg_state *false_dst,
4174 u8 opcode)
4175 {
4176 switch (opcode) {
4177 case BPF_JEQ:
4178 __reg_combine_min_max(true_src, true_dst);
4179 break;
4180 case BPF_JNE:
4181 __reg_combine_min_max(false_src, false_dst);
4182 break;
4183 }
4184 }
4185
mark_map_reg(struct bpf_reg_state * regs,u32 regno,u32 id,bool is_null)4186 static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id,
4187 bool is_null)
4188 {
4189 struct bpf_reg_state *reg = ®s[regno];
4190
4191 if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) {
4192 /* Old offset (both fixed and variable parts) should
4193 * have been known-zero, because we don't allow pointer
4194 * arithmetic on pointers that might be NULL.
4195 */
4196 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
4197 !tnum_equals_const(reg->var_off, 0) ||
4198 reg->off)) {
4199 __mark_reg_known_zero(reg);
4200 reg->off = 0;
4201 }
4202 if (is_null) {
4203 reg->type = SCALAR_VALUE;
4204 } else if (reg->map_ptr->inner_map_meta) {
4205 reg->type = CONST_PTR_TO_MAP;
4206 reg->map_ptr = reg->map_ptr->inner_map_meta;
4207 } else {
4208 reg->type = PTR_TO_MAP_VALUE;
4209 }
4210 /* We don't need id from this point onwards anymore, thus we
4211 * should better reset it, so that state pruning has chances
4212 * to take effect.
4213 */
4214 reg->id = 0;
4215 }
4216 }
4217
4218 /* The logic is similar to find_good_pkt_pointers(), both could eventually
4219 * be folded together at some point.
4220 */
mark_map_regs(struct bpf_verifier_state * vstate,u32 regno,bool is_null)4221 static void mark_map_regs(struct bpf_verifier_state *vstate, u32 regno,
4222 bool is_null)
4223 {
4224 struct bpf_func_state *state = vstate->frame[vstate->curframe];
4225 struct bpf_reg_state *regs = state->regs;
4226 u32 id = regs[regno].id;
4227 int i, j;
4228
4229 for (i = 0; i < MAX_BPF_REG; i++)
4230 mark_map_reg(regs, i, id, is_null);
4231
4232 for (j = 0; j <= vstate->curframe; j++) {
4233 state = vstate->frame[j];
4234 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
4235 if (state->stack[i].slot_type[0] != STACK_SPILL)
4236 continue;
4237 mark_map_reg(&state->stack[i].spilled_ptr, 0, id, is_null);
4238 }
4239 }
4240 }
4241
try_match_pkt_pointers(const struct bpf_insn * insn,struct bpf_reg_state * dst_reg,struct bpf_reg_state * src_reg,struct bpf_verifier_state * this_branch,struct bpf_verifier_state * other_branch)4242 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
4243 struct bpf_reg_state *dst_reg,
4244 struct bpf_reg_state *src_reg,
4245 struct bpf_verifier_state *this_branch,
4246 struct bpf_verifier_state *other_branch)
4247 {
4248 if (BPF_SRC(insn->code) != BPF_X)
4249 return false;
4250
4251 /* Pointers are always 64-bit. */
4252 if (BPF_CLASS(insn->code) == BPF_JMP32)
4253 return false;
4254
4255 switch (BPF_OP(insn->code)) {
4256 case BPF_JGT:
4257 if ((dst_reg->type == PTR_TO_PACKET &&
4258 src_reg->type == PTR_TO_PACKET_END) ||
4259 (dst_reg->type == PTR_TO_PACKET_META &&
4260 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4261 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
4262 find_good_pkt_pointers(this_branch, dst_reg,
4263 dst_reg->type, false);
4264 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4265 src_reg->type == PTR_TO_PACKET) ||
4266 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4267 src_reg->type == PTR_TO_PACKET_META)) {
4268 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
4269 find_good_pkt_pointers(other_branch, src_reg,
4270 src_reg->type, true);
4271 } else {
4272 return false;
4273 }
4274 break;
4275 case BPF_JLT:
4276 if ((dst_reg->type == PTR_TO_PACKET &&
4277 src_reg->type == PTR_TO_PACKET_END) ||
4278 (dst_reg->type == PTR_TO_PACKET_META &&
4279 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4280 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
4281 find_good_pkt_pointers(other_branch, dst_reg,
4282 dst_reg->type, true);
4283 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4284 src_reg->type == PTR_TO_PACKET) ||
4285 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4286 src_reg->type == PTR_TO_PACKET_META)) {
4287 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
4288 find_good_pkt_pointers(this_branch, src_reg,
4289 src_reg->type, false);
4290 } else {
4291 return false;
4292 }
4293 break;
4294 case BPF_JGE:
4295 if ((dst_reg->type == PTR_TO_PACKET &&
4296 src_reg->type == PTR_TO_PACKET_END) ||
4297 (dst_reg->type == PTR_TO_PACKET_META &&
4298 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4299 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
4300 find_good_pkt_pointers(this_branch, dst_reg,
4301 dst_reg->type, true);
4302 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4303 src_reg->type == PTR_TO_PACKET) ||
4304 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4305 src_reg->type == PTR_TO_PACKET_META)) {
4306 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
4307 find_good_pkt_pointers(other_branch, src_reg,
4308 src_reg->type, false);
4309 } else {
4310 return false;
4311 }
4312 break;
4313 case BPF_JLE:
4314 if ((dst_reg->type == PTR_TO_PACKET &&
4315 src_reg->type == PTR_TO_PACKET_END) ||
4316 (dst_reg->type == PTR_TO_PACKET_META &&
4317 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
4318 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
4319 find_good_pkt_pointers(other_branch, dst_reg,
4320 dst_reg->type, false);
4321 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
4322 src_reg->type == PTR_TO_PACKET) ||
4323 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
4324 src_reg->type == PTR_TO_PACKET_META)) {
4325 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
4326 find_good_pkt_pointers(this_branch, src_reg,
4327 src_reg->type, true);
4328 } else {
4329 return false;
4330 }
4331 break;
4332 default:
4333 return false;
4334 }
4335
4336 return true;
4337 }
4338
check_cond_jmp_op(struct bpf_verifier_env * env,struct bpf_insn * insn,int * insn_idx)4339 static int check_cond_jmp_op(struct bpf_verifier_env *env,
4340 struct bpf_insn *insn, int *insn_idx)
4341 {
4342 struct bpf_verifier_state *this_branch = env->cur_state;
4343 struct bpf_verifier_state *other_branch;
4344 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
4345 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
4346 u8 opcode = BPF_OP(insn->code);
4347 bool is_jmp32;
4348 int pred = -1;
4349 int err;
4350
4351 /* Only conditional jumps are expected to reach here. */
4352 if (opcode == BPF_JA || opcode > BPF_JSLE) {
4353 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
4354 return -EINVAL;
4355 }
4356
4357 if (BPF_SRC(insn->code) == BPF_X) {
4358 if (insn->imm != 0) {
4359 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
4360 return -EINVAL;
4361 }
4362
4363 /* check src1 operand */
4364 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4365 if (err)
4366 return err;
4367
4368 if (is_pointer_value(env, insn->src_reg)) {
4369 verbose(env, "R%d pointer comparison prohibited\n",
4370 insn->src_reg);
4371 return -EACCES;
4372 }
4373 src_reg = ®s[insn->src_reg];
4374 } else {
4375 if (insn->src_reg != BPF_REG_0) {
4376 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
4377 return -EINVAL;
4378 }
4379 }
4380
4381 /* check src2 operand */
4382 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
4383 if (err)
4384 return err;
4385
4386 dst_reg = ®s[insn->dst_reg];
4387 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
4388
4389 if (BPF_SRC(insn->code) == BPF_K)
4390 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
4391 else if (src_reg->type == SCALAR_VALUE &&
4392 tnum_is_const(src_reg->var_off))
4393 pred = is_branch_taken(dst_reg, src_reg->var_off.value,
4394 opcode, is_jmp32);
4395
4396 if (pred == 1) {
4397 /* Only follow the goto, ignore fall-through. If needed, push
4398 * the fall-through branch for simulation under speculative
4399 * execution.
4400 */
4401 if (!env->allow_ptr_leaks &&
4402 !sanitize_speculative_path(env, insn, *insn_idx + 1,
4403 *insn_idx))
4404 return -EFAULT;
4405
4406 *insn_idx += insn->off;
4407 return 0;
4408 } else if (pred == 0) {
4409 /* Only follow the fall-through branch, since that's where the
4410 * program will go. If needed, push the goto branch for
4411 * simulation under speculative execution.
4412 */
4413 if (!env->allow_ptr_leaks &&
4414 !sanitize_speculative_path(env, insn,
4415 *insn_idx + insn->off + 1,
4416 *insn_idx))
4417 return -EFAULT;
4418
4419 return 0;
4420 }
4421
4422 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
4423 false);
4424 if (!other_branch)
4425 return -EFAULT;
4426 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
4427
4428 /* detect if we are comparing against a constant value so we can adjust
4429 * our min/max values for our dst register.
4430 * this is only legit if both are scalars (or pointers to the same
4431 * object, I suppose, but we don't support that right now), because
4432 * otherwise the different base pointers mean the offsets aren't
4433 * comparable.
4434 */
4435 if (BPF_SRC(insn->code) == BPF_X) {
4436 struct bpf_reg_state *src_reg = ®s[insn->src_reg];
4437 struct bpf_reg_state lo_reg0 = *dst_reg;
4438 struct bpf_reg_state lo_reg1 = *src_reg;
4439 struct bpf_reg_state *src_lo, *dst_lo;
4440
4441 dst_lo = &lo_reg0;
4442 src_lo = &lo_reg1;
4443 coerce_reg_to_size(dst_lo, 4);
4444 coerce_reg_to_size(src_lo, 4);
4445
4446 if (dst_reg->type == SCALAR_VALUE &&
4447 src_reg->type == SCALAR_VALUE) {
4448 if (tnum_is_const(src_reg->var_off) ||
4449 (is_jmp32 && tnum_is_const(src_lo->var_off)))
4450 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4451 dst_reg,
4452 is_jmp32
4453 ? src_lo->var_off.value
4454 : src_reg->var_off.value,
4455 opcode, is_jmp32);
4456 else if (tnum_is_const(dst_reg->var_off) ||
4457 (is_jmp32 && tnum_is_const(dst_lo->var_off)))
4458 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
4459 src_reg,
4460 is_jmp32
4461 ? dst_lo->var_off.value
4462 : dst_reg->var_off.value,
4463 opcode, is_jmp32);
4464 else if (!is_jmp32 &&
4465 (opcode == BPF_JEQ || opcode == BPF_JNE))
4466 /* Comparing for equality, we can combine knowledge */
4467 reg_combine_min_max(&other_branch_regs[insn->src_reg],
4468 &other_branch_regs[insn->dst_reg],
4469 src_reg, dst_reg, opcode);
4470 }
4471 } else if (dst_reg->type == SCALAR_VALUE) {
4472 reg_set_min_max(&other_branch_regs[insn->dst_reg],
4473 dst_reg, insn->imm, opcode, is_jmp32);
4474 }
4475
4476 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
4477 * NOTE: these optimizations below are related with pointer comparison
4478 * which will never be JMP32.
4479 */
4480 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
4481 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
4482 dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) {
4483 /* Mark all identical map registers in each branch as either
4484 * safe or unknown depending R == 0 or R != 0 conditional.
4485 */
4486 mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE);
4487 mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ);
4488 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg],
4489 this_branch, other_branch) &&
4490 is_pointer_value(env, insn->dst_reg)) {
4491 verbose(env, "R%d pointer comparison prohibited\n",
4492 insn->dst_reg);
4493 return -EACCES;
4494 }
4495 if (env->log.level)
4496 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
4497 return 0;
4498 }
4499
4500 /* return the map pointer stored inside BPF_LD_IMM64 instruction */
ld_imm64_to_map_ptr(struct bpf_insn * insn)4501 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn)
4502 {
4503 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32;
4504
4505 return (struct bpf_map *) (unsigned long) imm64;
4506 }
4507
4508 /* verify BPF_LD_IMM64 instruction */
check_ld_imm(struct bpf_verifier_env * env,struct bpf_insn * insn)4509 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
4510 {
4511 struct bpf_reg_state *regs = cur_regs(env);
4512 int err;
4513
4514 if (BPF_SIZE(insn->code) != BPF_DW) {
4515 verbose(env, "invalid BPF_LD_IMM insn\n");
4516 return -EINVAL;
4517 }
4518 if (insn->off != 0) {
4519 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
4520 return -EINVAL;
4521 }
4522
4523 err = check_reg_arg(env, insn->dst_reg, DST_OP);
4524 if (err)
4525 return err;
4526
4527 if (insn->src_reg == 0) {
4528 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
4529
4530 regs[insn->dst_reg].type = SCALAR_VALUE;
4531 __mark_reg_known(®s[insn->dst_reg], imm);
4532 return 0;
4533 }
4534
4535 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */
4536 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD);
4537
4538 regs[insn->dst_reg].type = CONST_PTR_TO_MAP;
4539 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn);
4540 return 0;
4541 }
4542
may_access_skb(enum bpf_prog_type type)4543 static bool may_access_skb(enum bpf_prog_type type)
4544 {
4545 switch (type) {
4546 case BPF_PROG_TYPE_SOCKET_FILTER:
4547 case BPF_PROG_TYPE_SCHED_CLS:
4548 case BPF_PROG_TYPE_SCHED_ACT:
4549 return true;
4550 default:
4551 return false;
4552 }
4553 }
4554
4555 /* verify safety of LD_ABS|LD_IND instructions:
4556 * - they can only appear in the programs where ctx == skb
4557 * - since they are wrappers of function calls, they scratch R1-R5 registers,
4558 * preserve R6-R9, and store return value into R0
4559 *
4560 * Implicit input:
4561 * ctx == skb == R6 == CTX
4562 *
4563 * Explicit input:
4564 * SRC == any register
4565 * IMM == 32-bit immediate
4566 *
4567 * Output:
4568 * R0 - 8/16/32-bit skb data converted to cpu endianness
4569 */
check_ld_abs(struct bpf_verifier_env * env,struct bpf_insn * insn)4570 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
4571 {
4572 struct bpf_reg_state *regs = cur_regs(env);
4573 static const int ctx_reg = BPF_REG_6;
4574 u8 mode = BPF_MODE(insn->code);
4575 int i, err;
4576
4577 if (!may_access_skb(env->prog->type)) {
4578 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
4579 return -EINVAL;
4580 }
4581
4582 if (!env->ops->gen_ld_abs) {
4583 verbose(env, "bpf verifier is misconfigured\n");
4584 return -EINVAL;
4585 }
4586
4587 if (env->subprog_cnt > 1) {
4588 /* when program has LD_ABS insn JITs and interpreter assume
4589 * that r1 == ctx == skb which is not the case for callees
4590 * that can have arbitrary arguments. It's problematic
4591 * for main prog as well since JITs would need to analyze
4592 * all functions in order to make proper register save/restore
4593 * decisions in the main prog. Hence disallow LD_ABS with calls
4594 */
4595 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n");
4596 return -EINVAL;
4597 }
4598
4599 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
4600 BPF_SIZE(insn->code) == BPF_DW ||
4601 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
4602 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
4603 return -EINVAL;
4604 }
4605
4606 /* check whether implicit source operand (register R6) is readable */
4607 err = check_reg_arg(env, ctx_reg, SRC_OP);
4608 if (err)
4609 return err;
4610
4611 if (regs[ctx_reg].type != PTR_TO_CTX) {
4612 verbose(env,
4613 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
4614 return -EINVAL;
4615 }
4616
4617 if (mode == BPF_IND) {
4618 /* check explicit source operand */
4619 err = check_reg_arg(env, insn->src_reg, SRC_OP);
4620 if (err)
4621 return err;
4622 }
4623
4624 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg);
4625 if (err < 0)
4626 return err;
4627
4628 /* reset caller saved regs to unreadable */
4629 for (i = 0; i < CALLER_SAVED_REGS; i++) {
4630 mark_reg_not_init(env, regs, caller_saved[i]);
4631 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
4632 }
4633
4634 /* mark destination R0 register as readable, since it contains
4635 * the value fetched from the packet.
4636 * Already marked as written above.
4637 */
4638 mark_reg_unknown(env, regs, BPF_REG_0);
4639 return 0;
4640 }
4641
check_return_code(struct bpf_verifier_env * env)4642 static int check_return_code(struct bpf_verifier_env *env)
4643 {
4644 struct bpf_reg_state *reg;
4645 struct tnum range = tnum_range(0, 1);
4646
4647 switch (env->prog->type) {
4648 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4649 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
4650 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)
4651 range = tnum_range(1, 1);
4652 case BPF_PROG_TYPE_CGROUP_SKB:
4653 case BPF_PROG_TYPE_CGROUP_SOCK:
4654 case BPF_PROG_TYPE_SOCK_OPS:
4655 case BPF_PROG_TYPE_CGROUP_DEVICE:
4656 break;
4657 default:
4658 return 0;
4659 }
4660
4661 reg = cur_regs(env) + BPF_REG_0;
4662 if (reg->type != SCALAR_VALUE) {
4663 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
4664 reg_type_str[reg->type]);
4665 return -EINVAL;
4666 }
4667
4668 if (!tnum_in(range, reg->var_off)) {
4669 char tn_buf[48];
4670
4671 verbose(env, "At program exit the register R0 ");
4672 if (!tnum_is_unknown(reg->var_off)) {
4673 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4674 verbose(env, "has value %s", tn_buf);
4675 } else {
4676 verbose(env, "has unknown scalar value");
4677 }
4678 tnum_strn(tn_buf, sizeof(tn_buf), range);
4679 verbose(env, " should have been in %s\n", tn_buf);
4680 return -EINVAL;
4681 }
4682 return 0;
4683 }
4684
4685 /* non-recursive DFS pseudo code
4686 * 1 procedure DFS-iterative(G,v):
4687 * 2 label v as discovered
4688 * 3 let S be a stack
4689 * 4 S.push(v)
4690 * 5 while S is not empty
4691 * 6 t <- S.pop()
4692 * 7 if t is what we're looking for:
4693 * 8 return t
4694 * 9 for all edges e in G.adjacentEdges(t) do
4695 * 10 if edge e is already labelled
4696 * 11 continue with the next edge
4697 * 12 w <- G.adjacentVertex(t,e)
4698 * 13 if vertex w is not discovered and not explored
4699 * 14 label e as tree-edge
4700 * 15 label w as discovered
4701 * 16 S.push(w)
4702 * 17 continue at 5
4703 * 18 else if vertex w is discovered
4704 * 19 label e as back-edge
4705 * 20 else
4706 * 21 // vertex w is explored
4707 * 22 label e as forward- or cross-edge
4708 * 23 label t as explored
4709 * 24 S.pop()
4710 *
4711 * convention:
4712 * 0x10 - discovered
4713 * 0x11 - discovered and fall-through edge labelled
4714 * 0x12 - discovered and fall-through and branch edges labelled
4715 * 0x20 - explored
4716 */
4717
4718 enum {
4719 DISCOVERED = 0x10,
4720 EXPLORED = 0x20,
4721 FALLTHROUGH = 1,
4722 BRANCH = 2,
4723 };
4724
4725 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L)
4726
4727 static int *insn_stack; /* stack of insns to process */
4728 static int cur_stack; /* current stack index */
4729 static int *insn_state;
4730
4731 /* t, w, e - match pseudo-code above:
4732 * t - index of current instruction
4733 * w - next instruction
4734 * e - edge
4735 */
push_insn(int t,int w,int e,struct bpf_verifier_env * env)4736 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
4737 {
4738 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
4739 return 0;
4740
4741 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
4742 return 0;
4743
4744 if (w < 0 || w >= env->prog->len) {
4745 verbose(env, "jump out of range from insn %d to %d\n", t, w);
4746 return -EINVAL;
4747 }
4748
4749 if (e == BRANCH)
4750 /* mark branch target for state pruning */
4751 env->explored_states[w] = STATE_LIST_MARK;
4752
4753 if (insn_state[w] == 0) {
4754 /* tree-edge */
4755 insn_state[t] = DISCOVERED | e;
4756 insn_state[w] = DISCOVERED;
4757 if (cur_stack >= env->prog->len)
4758 return -E2BIG;
4759 insn_stack[cur_stack++] = w;
4760 return 1;
4761 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
4762 verbose(env, "back-edge from insn %d to %d\n", t, w);
4763 return -EINVAL;
4764 } else if (insn_state[w] == EXPLORED) {
4765 /* forward- or cross-edge */
4766 insn_state[t] = DISCOVERED | e;
4767 } else {
4768 verbose(env, "insn state internal bug\n");
4769 return -EFAULT;
4770 }
4771 return 0;
4772 }
4773
4774 /* non-recursive depth-first-search to detect loops in BPF program
4775 * loop == back-edge in directed graph
4776 */
check_cfg(struct bpf_verifier_env * env)4777 static int check_cfg(struct bpf_verifier_env *env)
4778 {
4779 struct bpf_insn *insns = env->prog->insnsi;
4780 int insn_cnt = env->prog->len;
4781 int ret = 0;
4782 int i, t;
4783
4784 ret = check_subprogs(env);
4785 if (ret < 0)
4786 return ret;
4787
4788 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4789 if (!insn_state)
4790 return -ENOMEM;
4791
4792 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
4793 if (!insn_stack) {
4794 kfree(insn_state);
4795 return -ENOMEM;
4796 }
4797
4798 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
4799 insn_stack[0] = 0; /* 0 is the first instruction */
4800 cur_stack = 1;
4801
4802 peek_stack:
4803 if (cur_stack == 0)
4804 goto check_state;
4805 t = insn_stack[cur_stack - 1];
4806
4807 if (BPF_CLASS(insns[t].code) == BPF_JMP ||
4808 BPF_CLASS(insns[t].code) == BPF_JMP32) {
4809 u8 opcode = BPF_OP(insns[t].code);
4810
4811 if (opcode == BPF_EXIT) {
4812 goto mark_explored;
4813 } else if (opcode == BPF_CALL) {
4814 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4815 if (ret == 1)
4816 goto peek_stack;
4817 else if (ret < 0)
4818 goto err_free;
4819 if (t + 1 < insn_cnt)
4820 env->explored_states[t + 1] = STATE_LIST_MARK;
4821 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
4822 env->explored_states[t] = STATE_LIST_MARK;
4823 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
4824 if (ret == 1)
4825 goto peek_stack;
4826 else if (ret < 0)
4827 goto err_free;
4828 }
4829 } else if (opcode == BPF_JA) {
4830 if (BPF_SRC(insns[t].code) != BPF_K) {
4831 ret = -EINVAL;
4832 goto err_free;
4833 }
4834 /* unconditional jump with single edge */
4835 ret = push_insn(t, t + insns[t].off + 1,
4836 FALLTHROUGH, env);
4837 if (ret == 1)
4838 goto peek_stack;
4839 else if (ret < 0)
4840 goto err_free;
4841 /* tell verifier to check for equivalent states
4842 * after every call and jump
4843 */
4844 if (t + 1 < insn_cnt)
4845 env->explored_states[t + 1] = STATE_LIST_MARK;
4846 } else {
4847 /* conditional jump with two edges */
4848 env->explored_states[t] = STATE_LIST_MARK;
4849 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4850 if (ret == 1)
4851 goto peek_stack;
4852 else if (ret < 0)
4853 goto err_free;
4854
4855 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env);
4856 if (ret == 1)
4857 goto peek_stack;
4858 else if (ret < 0)
4859 goto err_free;
4860 }
4861 } else {
4862 /* all other non-branch instructions with single
4863 * fall-through edge
4864 */
4865 ret = push_insn(t, t + 1, FALLTHROUGH, env);
4866 if (ret == 1)
4867 goto peek_stack;
4868 else if (ret < 0)
4869 goto err_free;
4870 }
4871
4872 mark_explored:
4873 insn_state[t] = EXPLORED;
4874 if (cur_stack-- <= 0) {
4875 verbose(env, "pop stack internal bug\n");
4876 ret = -EFAULT;
4877 goto err_free;
4878 }
4879 goto peek_stack;
4880
4881 check_state:
4882 for (i = 0; i < insn_cnt; i++) {
4883 if (insn_state[i] != EXPLORED) {
4884 verbose(env, "unreachable insn %d\n", i);
4885 ret = -EINVAL;
4886 goto err_free;
4887 }
4888 }
4889 ret = 0; /* cfg looks good */
4890
4891 err_free:
4892 kfree(insn_state);
4893 kfree(insn_stack);
4894 return ret;
4895 }
4896
4897 /* check %cur's range satisfies %old's */
range_within(struct bpf_reg_state * old,struct bpf_reg_state * cur)4898 static bool range_within(struct bpf_reg_state *old,
4899 struct bpf_reg_state *cur)
4900 {
4901 return old->umin_value <= cur->umin_value &&
4902 old->umax_value >= cur->umax_value &&
4903 old->smin_value <= cur->smin_value &&
4904 old->smax_value >= cur->smax_value;
4905 }
4906
4907 /* Maximum number of register states that can exist at once */
4908 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
4909 struct idpair {
4910 u32 old;
4911 u32 cur;
4912 };
4913
4914 /* If in the old state two registers had the same id, then they need to have
4915 * the same id in the new state as well. But that id could be different from
4916 * the old state, so we need to track the mapping from old to new ids.
4917 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
4918 * regs with old id 5 must also have new id 9 for the new state to be safe. But
4919 * regs with a different old id could still have new id 9, we don't care about
4920 * that.
4921 * So we look through our idmap to see if this old id has been seen before. If
4922 * so, we require the new id to match; otherwise, we add the id pair to the map.
4923 */
check_ids(u32 old_id,u32 cur_id,struct idpair * idmap)4924 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
4925 {
4926 unsigned int i;
4927
4928 for (i = 0; i < ID_MAP_SIZE; i++) {
4929 if (!idmap[i].old) {
4930 /* Reached an empty slot; haven't seen this id before */
4931 idmap[i].old = old_id;
4932 idmap[i].cur = cur_id;
4933 return true;
4934 }
4935 if (idmap[i].old == old_id)
4936 return idmap[i].cur == cur_id;
4937 }
4938 /* We ran out of idmap slots, which should be impossible */
4939 WARN_ON_ONCE(1);
4940 return false;
4941 }
4942
4943 /* Returns true if (rold safe implies rcur safe) */
regsafe(struct bpf_reg_state * rold,struct bpf_reg_state * rcur,struct idpair * idmap)4944 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
4945 struct idpair *idmap)
4946 {
4947 bool equal;
4948
4949 if (!(rold->live & REG_LIVE_READ))
4950 /* explored state didn't use this */
4951 return true;
4952
4953 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
4954
4955 if (rold->type == PTR_TO_STACK)
4956 /* two stack pointers are equal only if they're pointing to
4957 * the same stack frame, since fp-8 in foo != fp-8 in bar
4958 */
4959 return equal && rold->frameno == rcur->frameno;
4960
4961 if (equal)
4962 return true;
4963
4964 if (rold->type == NOT_INIT)
4965 /* explored state can't have used this */
4966 return true;
4967 if (rcur->type == NOT_INIT)
4968 return false;
4969 switch (rold->type) {
4970 case SCALAR_VALUE:
4971 if (rcur->type == SCALAR_VALUE) {
4972 /* new val must satisfy old val knowledge */
4973 return range_within(rold, rcur) &&
4974 tnum_in(rold->var_off, rcur->var_off);
4975 } else {
4976 /* We're trying to use a pointer in place of a scalar.
4977 * Even if the scalar was unbounded, this could lead to
4978 * pointer leaks because scalars are allowed to leak
4979 * while pointers are not. We could make this safe in
4980 * special cases if root is calling us, but it's
4981 * probably not worth the hassle.
4982 */
4983 return false;
4984 }
4985 case PTR_TO_MAP_VALUE:
4986 /* If the new min/max/var_off satisfy the old ones and
4987 * everything else matches, we are OK.
4988 * We don't care about the 'id' value, because nothing
4989 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL)
4990 */
4991 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
4992 range_within(rold, rcur) &&
4993 tnum_in(rold->var_off, rcur->var_off);
4994 case PTR_TO_MAP_VALUE_OR_NULL:
4995 /* a PTR_TO_MAP_VALUE could be safe to use as a
4996 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
4997 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
4998 * checked, doing so could have affected others with the same
4999 * id, and we can't check for that because we lost the id when
5000 * we converted to a PTR_TO_MAP_VALUE.
5001 */
5002 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
5003 return false;
5004 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
5005 return false;
5006 /* Check our ids match any regs they're supposed to */
5007 return check_ids(rold->id, rcur->id, idmap);
5008 case PTR_TO_PACKET_META:
5009 case PTR_TO_PACKET:
5010 if (rcur->type != rold->type)
5011 return false;
5012 /* We must have at least as much range as the old ptr
5013 * did, so that any accesses which were safe before are
5014 * still safe. This is true even if old range < old off,
5015 * since someone could have accessed through (ptr - k), or
5016 * even done ptr -= k in a register, to get a safe access.
5017 */
5018 if (rold->range > rcur->range)
5019 return false;
5020 /* If the offsets don't match, we can't trust our alignment;
5021 * nor can we be sure that we won't fall out of range.
5022 */
5023 if (rold->off != rcur->off)
5024 return false;
5025 /* id relations must be preserved */
5026 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
5027 return false;
5028 /* new val must satisfy old val knowledge */
5029 return range_within(rold, rcur) &&
5030 tnum_in(rold->var_off, rcur->var_off);
5031 case PTR_TO_CTX:
5032 case CONST_PTR_TO_MAP:
5033 case PTR_TO_PACKET_END:
5034 /* Only valid matches are exact, which memcmp() above
5035 * would have accepted
5036 */
5037 default:
5038 /* Don't know what's going on, just say it's not safe */
5039 return false;
5040 }
5041
5042 /* Shouldn't get here; if we do, say it's not safe */
5043 WARN_ON_ONCE(1);
5044 return false;
5045 }
5046
stacksafe(struct bpf_func_state * old,struct bpf_func_state * cur,struct idpair * idmap)5047 static bool stacksafe(struct bpf_func_state *old,
5048 struct bpf_func_state *cur,
5049 struct idpair *idmap)
5050 {
5051 int i, spi;
5052
5053 /* if explored stack has more populated slots than current stack
5054 * such stacks are not equivalent
5055 */
5056 if (old->allocated_stack > cur->allocated_stack)
5057 return false;
5058
5059 /* walk slots of the explored stack and ignore any additional
5060 * slots in the current stack, since explored(safe) state
5061 * didn't use them
5062 */
5063 for (i = 0; i < old->allocated_stack; i++) {
5064 spi = i / BPF_REG_SIZE;
5065
5066 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ))
5067 /* explored state didn't use this */
5068 continue;
5069
5070 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
5071 continue;
5072 /* if old state was safe with misc data in the stack
5073 * it will be safe with zero-initialized stack.
5074 * The opposite is not true
5075 */
5076 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
5077 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
5078 continue;
5079 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
5080 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
5081 /* Ex: old explored (safe) state has STACK_SPILL in
5082 * this stack slot, but current has has STACK_MISC ->
5083 * this verifier states are not equivalent,
5084 * return false to continue verification of this path
5085 */
5086 return false;
5087 if (i % BPF_REG_SIZE)
5088 continue;
5089 if (old->stack[spi].slot_type[0] != STACK_SPILL)
5090 continue;
5091 if (!regsafe(&old->stack[spi].spilled_ptr,
5092 &cur->stack[spi].spilled_ptr,
5093 idmap))
5094 /* when explored and current stack slot are both storing
5095 * spilled registers, check that stored pointers types
5096 * are the same as well.
5097 * Ex: explored safe path could have stored
5098 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
5099 * but current path has stored:
5100 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
5101 * such verifier states are not equivalent.
5102 * return false to continue verification of this path
5103 */
5104 return false;
5105 }
5106 return true;
5107 }
5108
5109 /* compare two verifier states
5110 *
5111 * all states stored in state_list are known to be valid, since
5112 * verifier reached 'bpf_exit' instruction through them
5113 *
5114 * this function is called when verifier exploring different branches of
5115 * execution popped from the state stack. If it sees an old state that has
5116 * more strict register state and more strict stack state then this execution
5117 * branch doesn't need to be explored further, since verifier already
5118 * concluded that more strict state leads to valid finish.
5119 *
5120 * Therefore two states are equivalent if register state is more conservative
5121 * and explored stack state is more conservative than the current one.
5122 * Example:
5123 * explored current
5124 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
5125 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
5126 *
5127 * In other words if current stack state (one being explored) has more
5128 * valid slots than old one that already passed validation, it means
5129 * the verifier can stop exploring and conclude that current state is valid too
5130 *
5131 * Similarly with registers. If explored state has register type as invalid
5132 * whereas register type in current state is meaningful, it means that
5133 * the current state will reach 'bpf_exit' instruction safely
5134 */
func_states_equal(struct bpf_func_state * old,struct bpf_func_state * cur)5135 static bool func_states_equal(struct bpf_func_state *old,
5136 struct bpf_func_state *cur)
5137 {
5138 struct idpair *idmap;
5139 bool ret = false;
5140 int i;
5141
5142 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
5143 /* If we failed to allocate the idmap, just say it's not safe */
5144 if (!idmap)
5145 return false;
5146
5147 for (i = 0; i < MAX_BPF_REG; i++) {
5148 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
5149 goto out_free;
5150 }
5151
5152 if (!stacksafe(old, cur, idmap))
5153 goto out_free;
5154 ret = true;
5155 out_free:
5156 kfree(idmap);
5157 return ret;
5158 }
5159
states_equal(struct bpf_verifier_env * env,struct bpf_verifier_state * old,struct bpf_verifier_state * cur)5160 static bool states_equal(struct bpf_verifier_env *env,
5161 struct bpf_verifier_state *old,
5162 struct bpf_verifier_state *cur)
5163 {
5164 int i;
5165
5166 if (old->curframe != cur->curframe)
5167 return false;
5168
5169 /* Verification state from speculative execution simulation
5170 * must never prune a non-speculative execution one.
5171 */
5172 if (old->speculative && !cur->speculative)
5173 return false;
5174
5175 /* for states to be equal callsites have to be the same
5176 * and all frame states need to be equivalent
5177 */
5178 for (i = 0; i <= old->curframe; i++) {
5179 if (old->frame[i]->callsite != cur->frame[i]->callsite)
5180 return false;
5181 if (!func_states_equal(old->frame[i], cur->frame[i]))
5182 return false;
5183 }
5184 return true;
5185 }
5186
5187 /* A write screens off any subsequent reads; but write marks come from the
5188 * straight-line code between a state and its parent. When we arrive at an
5189 * equivalent state (jump target or such) we didn't arrive by the straight-line
5190 * code, so read marks in the state must propagate to the parent regardless
5191 * of the state's write marks. That's what 'parent == state->parent' comparison
5192 * in mark_reg_read() is for.
5193 */
propagate_liveness(struct bpf_verifier_env * env,const struct bpf_verifier_state * vstate,struct bpf_verifier_state * vparent)5194 static int propagate_liveness(struct bpf_verifier_env *env,
5195 const struct bpf_verifier_state *vstate,
5196 struct bpf_verifier_state *vparent)
5197 {
5198 int i, frame, err = 0;
5199 struct bpf_func_state *state, *parent;
5200
5201 if (vparent->curframe != vstate->curframe) {
5202 WARN(1, "propagate_live: parent frame %d current frame %d\n",
5203 vparent->curframe, vstate->curframe);
5204 return -EFAULT;
5205 }
5206 /* Propagate read liveness of registers... */
5207 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
5208 /* We don't need to worry about FP liveness because it's read-only */
5209 for (i = 0; i < BPF_REG_FP; i++) {
5210 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ)
5211 continue;
5212 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) {
5213 err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i],
5214 &vparent->frame[vstate->curframe]->regs[i]);
5215 if (err)
5216 return err;
5217 }
5218 }
5219
5220 /* ... and stack slots */
5221 for (frame = 0; frame <= vstate->curframe; frame++) {
5222 state = vstate->frame[frame];
5223 parent = vparent->frame[frame];
5224 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
5225 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
5226 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ)
5227 continue;
5228 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ)
5229 mark_reg_read(env, &state->stack[i].spilled_ptr,
5230 &parent->stack[i].spilled_ptr);
5231 }
5232 }
5233 return err;
5234 }
5235
is_state_visited(struct bpf_verifier_env * env,int insn_idx)5236 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
5237 {
5238 struct bpf_verifier_state_list *new_sl;
5239 struct bpf_verifier_state_list *sl;
5240 struct bpf_verifier_state *cur = env->cur_state, *new;
5241 int i, j, err, states_cnt = 0;
5242
5243 sl = env->explored_states[insn_idx];
5244 if (!sl)
5245 /* this 'insn_idx' instruction wasn't marked, so we will not
5246 * be doing state search here
5247 */
5248 return 0;
5249
5250 while (sl != STATE_LIST_MARK) {
5251 if (states_equal(env, &sl->state, cur)) {
5252 /* reached equivalent register/stack state,
5253 * prune the search.
5254 * Registers read by the continuation are read by us.
5255 * If we have any write marks in env->cur_state, they
5256 * will prevent corresponding reads in the continuation
5257 * from reaching our parent (an explored_state). Our
5258 * own state will get the read marks recorded, but
5259 * they'll be immediately forgotten as we're pruning
5260 * this state and will pop a new one.
5261 */
5262 err = propagate_liveness(env, &sl->state, cur);
5263 if (err)
5264 return err;
5265 return 1;
5266 }
5267 sl = sl->next;
5268 states_cnt++;
5269 }
5270
5271 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
5272 return 0;
5273
5274 /* there were no equivalent states, remember current one.
5275 * technically the current state is not proven to be safe yet,
5276 * but it will either reach outer most bpf_exit (which means it's safe)
5277 * or it will be rejected. Since there are no loops, we won't be
5278 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
5279 * again on the way to bpf_exit
5280 */
5281 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
5282 if (!new_sl)
5283 return -ENOMEM;
5284
5285 /* add new state to the head of linked list */
5286 new = &new_sl->state;
5287 err = copy_verifier_state(new, cur);
5288 if (err) {
5289 free_verifier_state(new, false);
5290 kfree(new_sl);
5291 return err;
5292 }
5293 new_sl->next = env->explored_states[insn_idx];
5294 env->explored_states[insn_idx] = new_sl;
5295 /* connect new state to parentage chain */
5296 for (i = 0; i < BPF_REG_FP; i++)
5297 cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i];
5298 /* clear write marks in current state: the writes we did are not writes
5299 * our child did, so they don't screen off its reads from us.
5300 * (There are no read marks in current state, because reads always mark
5301 * their parent and current state never has children yet. Only
5302 * explored_states can get read marks.)
5303 */
5304 for (i = 0; i < BPF_REG_FP; i++)
5305 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE;
5306
5307 /* all stack frames are accessible from callee, clear them all */
5308 for (j = 0; j <= cur->curframe; j++) {
5309 struct bpf_func_state *frame = cur->frame[j];
5310 struct bpf_func_state *newframe = new->frame[j];
5311
5312 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
5313 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
5314 frame->stack[i].spilled_ptr.parent =
5315 &newframe->stack[i].spilled_ptr;
5316 }
5317 }
5318 return 0;
5319 }
5320
do_check(struct bpf_verifier_env * env)5321 static int do_check(struct bpf_verifier_env *env)
5322 {
5323 struct bpf_verifier_state *state;
5324 struct bpf_insn *insns = env->prog->insnsi;
5325 struct bpf_reg_state *regs;
5326 int insn_cnt = env->prog->len, i;
5327 int insn_processed = 0;
5328 bool do_print_state = false;
5329
5330 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
5331 if (!state)
5332 return -ENOMEM;
5333 state->curframe = 0;
5334 state->speculative = false;
5335 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
5336 if (!state->frame[0]) {
5337 kfree(state);
5338 return -ENOMEM;
5339 }
5340 env->cur_state = state;
5341 init_func_state(env, state->frame[0],
5342 BPF_MAIN_FUNC /* callsite */,
5343 0 /* frameno */,
5344 0 /* subprogno, zero == main subprog */);
5345
5346 for (;;) {
5347 struct bpf_insn *insn;
5348 u8 class;
5349 int err;
5350
5351 if (env->insn_idx >= insn_cnt) {
5352 verbose(env, "invalid insn idx %d insn_cnt %d\n",
5353 env->insn_idx, insn_cnt);
5354 return -EFAULT;
5355 }
5356
5357 insn = &insns[env->insn_idx];
5358 class = BPF_CLASS(insn->code);
5359
5360 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
5361 verbose(env,
5362 "BPF program is too large. Processed %d insn\n",
5363 insn_processed);
5364 return -E2BIG;
5365 }
5366
5367 err = is_state_visited(env, env->insn_idx);
5368 if (err < 0)
5369 return err;
5370 if (err == 1) {
5371 /* found equivalent state, can prune the search */
5372 if (env->log.level) {
5373 if (do_print_state)
5374 verbose(env, "\nfrom %d to %d%s: safe\n",
5375 env->prev_insn_idx, env->insn_idx,
5376 env->cur_state->speculative ?
5377 " (speculative execution)" : "");
5378 else
5379 verbose(env, "%d: safe\n", env->insn_idx);
5380 }
5381 goto process_bpf_exit;
5382 }
5383
5384 if (signal_pending(current))
5385 return -EAGAIN;
5386
5387 if (need_resched())
5388 cond_resched();
5389
5390 if (env->log.level > 1 || (env->log.level && do_print_state)) {
5391 if (env->log.level > 1)
5392 verbose(env, "%d:", env->insn_idx);
5393 else
5394 verbose(env, "\nfrom %d to %d%s:",
5395 env->prev_insn_idx, env->insn_idx,
5396 env->cur_state->speculative ?
5397 " (speculative execution)" : "");
5398 print_verifier_state(env, state->frame[state->curframe]);
5399 do_print_state = false;
5400 }
5401
5402 if (env->log.level) {
5403 const struct bpf_insn_cbs cbs = {
5404 .cb_print = verbose,
5405 .private_data = env,
5406 };
5407
5408 verbose(env, "%d: ", env->insn_idx);
5409 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
5410 }
5411
5412 if (bpf_prog_is_dev_bound(env->prog->aux)) {
5413 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
5414 env->prev_insn_idx);
5415 if (err)
5416 return err;
5417 }
5418
5419 regs = cur_regs(env);
5420 sanitize_mark_insn_seen(env);
5421
5422 if (class == BPF_ALU || class == BPF_ALU64) {
5423 err = check_alu_op(env, insn);
5424 if (err)
5425 return err;
5426
5427 } else if (class == BPF_LDX) {
5428 enum bpf_reg_type *prev_src_type, src_reg_type;
5429
5430 /* check for reserved fields is already done */
5431
5432 /* check src operand */
5433 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5434 if (err)
5435 return err;
5436
5437 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
5438 if (err)
5439 return err;
5440
5441 src_reg_type = regs[insn->src_reg].type;
5442
5443 /* check that memory (src_reg + off) is readable,
5444 * the state of dst_reg will be updated by this func
5445 */
5446 err = check_mem_access(env, env->insn_idx, insn->src_reg,
5447 insn->off, BPF_SIZE(insn->code),
5448 BPF_READ, insn->dst_reg, false);
5449 if (err)
5450 return err;
5451
5452 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5453
5454 if (*prev_src_type == NOT_INIT) {
5455 /* saw a valid insn
5456 * dst_reg = *(u32 *)(src_reg + off)
5457 * save type to validate intersecting paths
5458 */
5459 *prev_src_type = src_reg_type;
5460
5461 } else if (src_reg_type != *prev_src_type &&
5462 (src_reg_type == PTR_TO_CTX ||
5463 *prev_src_type == PTR_TO_CTX)) {
5464 /* ABuser program is trying to use the same insn
5465 * dst_reg = *(u32*) (src_reg + off)
5466 * with different pointer types:
5467 * src_reg == ctx in one branch and
5468 * src_reg == stack|map in some other branch.
5469 * Reject it.
5470 */
5471 verbose(env, "same insn cannot be used with different pointers\n");
5472 return -EINVAL;
5473 }
5474
5475 } else if (class == BPF_STX) {
5476 enum bpf_reg_type *prev_dst_type, dst_reg_type;
5477
5478 if (BPF_MODE(insn->code) == BPF_XADD) {
5479 err = check_xadd(env, env->insn_idx, insn);
5480 if (err)
5481 return err;
5482 env->insn_idx++;
5483 continue;
5484 }
5485
5486 /* check src1 operand */
5487 err = check_reg_arg(env, insn->src_reg, SRC_OP);
5488 if (err)
5489 return err;
5490 /* check src2 operand */
5491 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5492 if (err)
5493 return err;
5494
5495 dst_reg_type = regs[insn->dst_reg].type;
5496
5497 /* check that memory (dst_reg + off) is writeable */
5498 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5499 insn->off, BPF_SIZE(insn->code),
5500 BPF_WRITE, insn->src_reg, false);
5501 if (err)
5502 return err;
5503
5504 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
5505
5506 if (*prev_dst_type == NOT_INIT) {
5507 *prev_dst_type = dst_reg_type;
5508 } else if (dst_reg_type != *prev_dst_type &&
5509 (dst_reg_type == PTR_TO_CTX ||
5510 *prev_dst_type == PTR_TO_CTX)) {
5511 verbose(env, "same insn cannot be used with different pointers\n");
5512 return -EINVAL;
5513 }
5514
5515 } else if (class == BPF_ST) {
5516 if (BPF_MODE(insn->code) != BPF_MEM ||
5517 insn->src_reg != BPF_REG_0) {
5518 verbose(env, "BPF_ST uses reserved fields\n");
5519 return -EINVAL;
5520 }
5521 /* check src operand */
5522 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
5523 if (err)
5524 return err;
5525
5526 if (is_ctx_reg(env, insn->dst_reg)) {
5527 verbose(env, "BPF_ST stores into R%d context is not allowed\n",
5528 insn->dst_reg);
5529 return -EACCES;
5530 }
5531
5532 /* check that memory (dst_reg + off) is writeable */
5533 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
5534 insn->off, BPF_SIZE(insn->code),
5535 BPF_WRITE, -1, false);
5536 if (err)
5537 return err;
5538
5539 } else if (class == BPF_JMP || class == BPF_JMP32) {
5540 u8 opcode = BPF_OP(insn->code);
5541
5542 if (opcode == BPF_CALL) {
5543 if (BPF_SRC(insn->code) != BPF_K ||
5544 insn->off != 0 ||
5545 (insn->src_reg != BPF_REG_0 &&
5546 insn->src_reg != BPF_PSEUDO_CALL) ||
5547 insn->dst_reg != BPF_REG_0 ||
5548 class == BPF_JMP32) {
5549 verbose(env, "BPF_CALL uses reserved fields\n");
5550 return -EINVAL;
5551 }
5552
5553 if (insn->src_reg == BPF_PSEUDO_CALL)
5554 err = check_func_call(env, insn, &env->insn_idx);
5555 else
5556 err = check_helper_call(env, insn->imm, env->insn_idx);
5557 if (err)
5558 return err;
5559
5560 } else if (opcode == BPF_JA) {
5561 if (BPF_SRC(insn->code) != BPF_K ||
5562 insn->imm != 0 ||
5563 insn->src_reg != BPF_REG_0 ||
5564 insn->dst_reg != BPF_REG_0 ||
5565 class == BPF_JMP32) {
5566 verbose(env, "BPF_JA uses reserved fields\n");
5567 return -EINVAL;
5568 }
5569
5570 env->insn_idx += insn->off + 1;
5571 continue;
5572
5573 } else if (opcode == BPF_EXIT) {
5574 if (BPF_SRC(insn->code) != BPF_K ||
5575 insn->imm != 0 ||
5576 insn->src_reg != BPF_REG_0 ||
5577 insn->dst_reg != BPF_REG_0 ||
5578 class == BPF_JMP32) {
5579 verbose(env, "BPF_EXIT uses reserved fields\n");
5580 return -EINVAL;
5581 }
5582
5583 if (state->curframe) {
5584 /* exit from nested function */
5585 env->prev_insn_idx = env->insn_idx;
5586 err = prepare_func_exit(env, &env->insn_idx);
5587 if (err)
5588 return err;
5589 do_print_state = true;
5590 continue;
5591 }
5592
5593 /* eBPF calling convetion is such that R0 is used
5594 * to return the value from eBPF program.
5595 * Make sure that it's readable at this time
5596 * of bpf_exit, which means that program wrote
5597 * something into it earlier
5598 */
5599 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
5600 if (err)
5601 return err;
5602
5603 if (is_pointer_value(env, BPF_REG_0)) {
5604 verbose(env, "R0 leaks addr as return value\n");
5605 return -EACCES;
5606 }
5607
5608 err = check_return_code(env);
5609 if (err)
5610 return err;
5611 process_bpf_exit:
5612 err = pop_stack(env, &env->prev_insn_idx,
5613 &env->insn_idx);
5614 if (err < 0) {
5615 if (err != -ENOENT)
5616 return err;
5617 break;
5618 } else {
5619 do_print_state = true;
5620 continue;
5621 }
5622 } else {
5623 err = check_cond_jmp_op(env, insn, &env->insn_idx);
5624 if (err)
5625 return err;
5626 }
5627 } else if (class == BPF_LD) {
5628 u8 mode = BPF_MODE(insn->code);
5629
5630 if (mode == BPF_ABS || mode == BPF_IND) {
5631 err = check_ld_abs(env, insn);
5632 if (err)
5633 return err;
5634
5635 } else if (mode == BPF_IMM) {
5636 err = check_ld_imm(env, insn);
5637 if (err)
5638 return err;
5639
5640 env->insn_idx++;
5641 sanitize_mark_insn_seen(env);
5642 } else {
5643 verbose(env, "invalid BPF_LD mode\n");
5644 return -EINVAL;
5645 }
5646 } else {
5647 verbose(env, "unknown insn class %d\n", class);
5648 return -EINVAL;
5649 }
5650
5651 env->insn_idx++;
5652 }
5653
5654 verbose(env, "processed %d insns (limit %d), stack depth ",
5655 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS);
5656 for (i = 0; i < env->subprog_cnt; i++) {
5657 u32 depth = env->subprog_info[i].stack_depth;
5658
5659 verbose(env, "%d", depth);
5660 if (i + 1 < env->subprog_cnt)
5661 verbose(env, "+");
5662 }
5663 verbose(env, "\n");
5664 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
5665 return 0;
5666 }
5667
check_map_prealloc(struct bpf_map * map)5668 static int check_map_prealloc(struct bpf_map *map)
5669 {
5670 return (map->map_type != BPF_MAP_TYPE_HASH &&
5671 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
5672 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
5673 !(map->map_flags & BPF_F_NO_PREALLOC);
5674 }
5675
check_map_prog_compatibility(struct bpf_verifier_env * env,struct bpf_map * map,struct bpf_prog * prog)5676 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
5677 struct bpf_map *map,
5678 struct bpf_prog *prog)
5679
5680 {
5681 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use
5682 * preallocated hash maps, since doing memory allocation
5683 * in overflow_handler can crash depending on where nmi got
5684 * triggered.
5685 */
5686 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) {
5687 if (!check_map_prealloc(map)) {
5688 verbose(env, "perf_event programs can only use preallocated hash map\n");
5689 return -EINVAL;
5690 }
5691 if (map->inner_map_meta &&
5692 !check_map_prealloc(map->inner_map_meta)) {
5693 verbose(env, "perf_event programs can only use preallocated inner hash map\n");
5694 return -EINVAL;
5695 }
5696 }
5697
5698 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
5699 !bpf_offload_prog_map_match(prog, map)) {
5700 verbose(env, "offload device mismatch between prog and map\n");
5701 return -EINVAL;
5702 }
5703
5704 return 0;
5705 }
5706
5707 /* look for pseudo eBPF instructions that access map FDs and
5708 * replace them with actual map pointers
5709 */
replace_map_fd_with_map_ptr(struct bpf_verifier_env * env)5710 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)
5711 {
5712 struct bpf_insn *insn = env->prog->insnsi;
5713 int insn_cnt = env->prog->len;
5714 int i, j, err;
5715
5716 err = bpf_prog_calc_tag(env->prog);
5717 if (err)
5718 return err;
5719
5720 for (i = 0; i < insn_cnt; i++, insn++) {
5721 if (BPF_CLASS(insn->code) == BPF_LDX &&
5722 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
5723 verbose(env, "BPF_LDX uses reserved fields\n");
5724 return -EINVAL;
5725 }
5726
5727 if (BPF_CLASS(insn->code) == BPF_STX &&
5728 ((BPF_MODE(insn->code) != BPF_MEM &&
5729 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {
5730 verbose(env, "BPF_STX uses reserved fields\n");
5731 return -EINVAL;
5732 }
5733
5734 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
5735 struct bpf_map *map;
5736 struct fd f;
5737
5738 if (i == insn_cnt - 1 || insn[1].code != 0 ||
5739 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
5740 insn[1].off != 0) {
5741 verbose(env, "invalid bpf_ld_imm64 insn\n");
5742 return -EINVAL;
5743 }
5744
5745 if (insn->src_reg == 0)
5746 /* valid generic load 64-bit imm */
5747 goto next_insn;
5748
5749 if (insn->src_reg != BPF_PSEUDO_MAP_FD) {
5750 verbose(env,
5751 "unrecognized bpf_ld_imm64 insn\n");
5752 return -EINVAL;
5753 }
5754
5755 f = fdget(insn->imm);
5756 map = __bpf_map_get(f);
5757 if (IS_ERR(map)) {
5758 verbose(env, "fd %d is not pointing to valid bpf_map\n",
5759 insn->imm);
5760 return PTR_ERR(map);
5761 }
5762
5763 err = check_map_prog_compatibility(env, map, env->prog);
5764 if (err) {
5765 fdput(f);
5766 return err;
5767 }
5768
5769 /* store map pointer inside BPF_LD_IMM64 instruction */
5770 insn[0].imm = (u32) (unsigned long) map;
5771 insn[1].imm = ((u64) (unsigned long) map) >> 32;
5772
5773 /* check whether we recorded this map already */
5774 for (j = 0; j < env->used_map_cnt; j++)
5775 if (env->used_maps[j] == map) {
5776 fdput(f);
5777 goto next_insn;
5778 }
5779
5780 if (env->used_map_cnt >= MAX_USED_MAPS) {
5781 fdput(f);
5782 return -E2BIG;
5783 }
5784
5785 /* hold the map. If the program is rejected by verifier,
5786 * the map will be released by release_maps() or it
5787 * will be used by the valid program until it's unloaded
5788 * and all maps are released in free_used_maps()
5789 */
5790 map = bpf_map_inc(map, false);
5791 if (IS_ERR(map)) {
5792 fdput(f);
5793 return PTR_ERR(map);
5794 }
5795 env->used_maps[env->used_map_cnt++] = map;
5796
5797 if (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE &&
5798 bpf_cgroup_storage_assign(env->prog, map)) {
5799 verbose(env,
5800 "only one cgroup storage is allowed\n");
5801 fdput(f);
5802 return -EBUSY;
5803 }
5804
5805 fdput(f);
5806 next_insn:
5807 insn++;
5808 i++;
5809 continue;
5810 }
5811
5812 /* Basic sanity check before we invest more work here. */
5813 if (!bpf_opcode_in_insntable(insn->code)) {
5814 verbose(env, "unknown opcode %02x\n", insn->code);
5815 return -EINVAL;
5816 }
5817 }
5818
5819 /* now all pseudo BPF_LD_IMM64 instructions load valid
5820 * 'struct bpf_map *' into a register instead of user map_fd.
5821 * These pointers will be used later by verifier to validate map access.
5822 */
5823 return 0;
5824 }
5825
5826 /* drop refcnt of maps used by the rejected program */
release_maps(struct bpf_verifier_env * env)5827 static void release_maps(struct bpf_verifier_env *env)
5828 {
5829 int i;
5830
5831 if (env->prog->aux->cgroup_storage)
5832 bpf_cgroup_storage_release(env->prog,
5833 env->prog->aux->cgroup_storage);
5834
5835 for (i = 0; i < env->used_map_cnt; i++)
5836 bpf_map_put(env->used_maps[i]);
5837 }
5838
5839 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
convert_pseudo_ld_imm64(struct bpf_verifier_env * env)5840 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
5841 {
5842 struct bpf_insn *insn = env->prog->insnsi;
5843 int insn_cnt = env->prog->len;
5844 int i;
5845
5846 for (i = 0; i < insn_cnt; i++, insn++)
5847 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
5848 insn->src_reg = 0;
5849 }
5850
5851 /* single env->prog->insni[off] instruction was replaced with the range
5852 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
5853 * [0, off) and [off, end) to new locations, so the patched range stays zero
5854 */
adjust_insn_aux_data(struct bpf_verifier_env * env,u32 prog_len,u32 off,u32 cnt)5855 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len,
5856 u32 off, u32 cnt)
5857 {
5858 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
5859 bool old_seen = old_data[off].seen;
5860 int i;
5861
5862 if (cnt == 1)
5863 return 0;
5864 new_data = vzalloc(array_size(prog_len,
5865 sizeof(struct bpf_insn_aux_data)));
5866 if (!new_data)
5867 return -ENOMEM;
5868 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
5869 memcpy(new_data + off + cnt - 1, old_data + off,
5870 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
5871 for (i = off; i < off + cnt - 1; i++) {
5872 /* Expand insni[off]'s seen count to the patched range. */
5873 new_data[i].seen = old_seen;
5874 }
5875 env->insn_aux_data = new_data;
5876 vfree(old_data);
5877 return 0;
5878 }
5879
adjust_subprog_starts(struct bpf_verifier_env * env,u32 off,u32 len)5880 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
5881 {
5882 int i;
5883
5884 if (len == 1)
5885 return;
5886 /* NOTE: fake 'exit' subprog should be updated as well. */
5887 for (i = 0; i <= env->subprog_cnt; i++) {
5888 if (env->subprog_info[i].start <= off)
5889 continue;
5890 env->subprog_info[i].start += len - 1;
5891 }
5892 }
5893
bpf_patch_insn_data(struct bpf_verifier_env * env,u32 off,const struct bpf_insn * patch,u32 len)5894 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
5895 const struct bpf_insn *patch, u32 len)
5896 {
5897 struct bpf_prog *new_prog;
5898
5899 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
5900 if (!new_prog)
5901 return NULL;
5902 if (adjust_insn_aux_data(env, new_prog->len, off, len))
5903 return NULL;
5904 adjust_subprog_starts(env, off, len);
5905 return new_prog;
5906 }
5907
5908 /* The verifier does more data flow analysis than llvm and will not
5909 * explore branches that are dead at run time. Malicious programs can
5910 * have dead code too. Therefore replace all dead at-run-time code
5911 * with 'ja -1'.
5912 *
5913 * Just nops are not optimal, e.g. if they would sit at the end of the
5914 * program and through another bug we would manage to jump there, then
5915 * we'd execute beyond program memory otherwise. Returning exception
5916 * code also wouldn't work since we can have subprogs where the dead
5917 * code could be located.
5918 */
sanitize_dead_code(struct bpf_verifier_env * env)5919 static void sanitize_dead_code(struct bpf_verifier_env *env)
5920 {
5921 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
5922 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
5923 struct bpf_insn *insn = env->prog->insnsi;
5924 const int insn_cnt = env->prog->len;
5925 int i;
5926
5927 for (i = 0; i < insn_cnt; i++) {
5928 if (aux_data[i].seen)
5929 continue;
5930 memcpy(insn + i, &trap, sizeof(trap));
5931 }
5932 }
5933
5934 /* convert load instructions that access fields of 'struct __sk_buff'
5935 * into sequence of instructions that access fields of 'struct sk_buff'
5936 */
convert_ctx_accesses(struct bpf_verifier_env * env)5937 static int convert_ctx_accesses(struct bpf_verifier_env *env)
5938 {
5939 const struct bpf_verifier_ops *ops = env->ops;
5940 int i, cnt, size, ctx_field_size, delta = 0;
5941 const int insn_cnt = env->prog->len;
5942 struct bpf_insn insn_buf[16], *insn;
5943 u32 target_size, size_default, off;
5944 struct bpf_prog *new_prog;
5945 enum bpf_access_type type;
5946 bool is_narrower_load;
5947
5948 if (ops->gen_prologue) {
5949 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
5950 env->prog);
5951 if (cnt >= ARRAY_SIZE(insn_buf)) {
5952 verbose(env, "bpf verifier is misconfigured\n");
5953 return -EINVAL;
5954 } else if (cnt) {
5955 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
5956 if (!new_prog)
5957 return -ENOMEM;
5958
5959 env->prog = new_prog;
5960 delta += cnt - 1;
5961 }
5962 }
5963
5964 if (!ops->convert_ctx_access || bpf_prog_is_dev_bound(env->prog->aux))
5965 return 0;
5966
5967 insn = env->prog->insnsi + delta;
5968
5969 for (i = 0; i < insn_cnt; i++, insn++) {
5970 bool ctx_access;
5971
5972 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
5973 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
5974 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
5975 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
5976 type = BPF_READ;
5977 ctx_access = true;
5978 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
5979 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
5980 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
5981 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
5982 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
5983 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
5984 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
5985 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
5986 type = BPF_WRITE;
5987 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
5988 } else {
5989 continue;
5990 }
5991
5992 if (type == BPF_WRITE &&
5993 env->insn_aux_data[i + delta].sanitize_stack_spill) {
5994 struct bpf_insn patch[] = {
5995 *insn,
5996 BPF_ST_NOSPEC(),
5997 };
5998
5999 cnt = ARRAY_SIZE(patch);
6000 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
6001 if (!new_prog)
6002 return -ENOMEM;
6003
6004 delta += cnt - 1;
6005 env->prog = new_prog;
6006 insn = new_prog->insnsi + i + delta;
6007 continue;
6008 }
6009
6010 if (!ctx_access)
6011 continue;
6012
6013 if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX)
6014 continue;
6015
6016 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
6017 size = BPF_LDST_BYTES(insn);
6018
6019 /* If the read access is a narrower load of the field,
6020 * convert to a 4/8-byte load, to minimum program type specific
6021 * convert_ctx_access changes. If conversion is successful,
6022 * we will apply proper mask to the result.
6023 */
6024 is_narrower_load = size < ctx_field_size;
6025 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
6026 off = insn->off;
6027 if (is_narrower_load) {
6028 u8 size_code;
6029
6030 if (type == BPF_WRITE) {
6031 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
6032 return -EINVAL;
6033 }
6034
6035 size_code = BPF_H;
6036 if (ctx_field_size == 4)
6037 size_code = BPF_W;
6038 else if (ctx_field_size == 8)
6039 size_code = BPF_DW;
6040
6041 insn->off = off & ~(size_default - 1);
6042 insn->code = BPF_LDX | BPF_MEM | size_code;
6043 }
6044
6045 target_size = 0;
6046 cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog,
6047 &target_size);
6048 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
6049 (ctx_field_size && !target_size)) {
6050 verbose(env, "bpf verifier is misconfigured\n");
6051 return -EINVAL;
6052 }
6053
6054 if (is_narrower_load && size < target_size) {
6055 u8 shift = (off & (size_default - 1)) * 8;
6056
6057 if (ctx_field_size <= 4) {
6058 if (shift)
6059 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
6060 insn->dst_reg,
6061 shift);
6062 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
6063 (1 << size * 8) - 1);
6064 } else {
6065 if (shift)
6066 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
6067 insn->dst_reg,
6068 shift);
6069 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
6070 (1ULL << size * 8) - 1);
6071 }
6072 }
6073
6074 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6075 if (!new_prog)
6076 return -ENOMEM;
6077
6078 delta += cnt - 1;
6079
6080 /* keep walking new program and skip insns we just inserted */
6081 env->prog = new_prog;
6082 insn = new_prog->insnsi + i + delta;
6083 }
6084
6085 return 0;
6086 }
6087
jit_subprogs(struct bpf_verifier_env * env)6088 static int jit_subprogs(struct bpf_verifier_env *env)
6089 {
6090 struct bpf_prog *prog = env->prog, **func, *tmp;
6091 int i, j, subprog_start, subprog_end = 0, len, subprog;
6092 struct bpf_insn *insn;
6093 void *old_bpf_func;
6094 int err = -ENOMEM;
6095
6096 if (env->subprog_cnt <= 1)
6097 return 0;
6098
6099 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6100 if (insn->code != (BPF_JMP | BPF_CALL) ||
6101 insn->src_reg != BPF_PSEUDO_CALL)
6102 continue;
6103 /* Upon error here we cannot fall back to interpreter but
6104 * need a hard reject of the program. Thus -EFAULT is
6105 * propagated in any case.
6106 */
6107 subprog = find_subprog(env, i + insn->imm + 1);
6108 if (subprog < 0) {
6109 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6110 i + insn->imm + 1);
6111 return -EFAULT;
6112 }
6113 /* temporarily remember subprog id inside insn instead of
6114 * aux_data, since next loop will split up all insns into funcs
6115 */
6116 insn->off = subprog;
6117 /* remember original imm in case JIT fails and fallback
6118 * to interpreter will be needed
6119 */
6120 env->insn_aux_data[i].call_imm = insn->imm;
6121 /* point imm to __bpf_call_base+1 from JITs point of view */
6122 insn->imm = 1;
6123 }
6124
6125 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
6126 if (!func)
6127 goto out_undo_insn;
6128
6129 for (i = 0; i < env->subprog_cnt; i++) {
6130 subprog_start = subprog_end;
6131 subprog_end = env->subprog_info[i + 1].start;
6132
6133 len = subprog_end - subprog_start;
6134 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);
6135 if (!func[i])
6136 goto out_free;
6137 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
6138 len * sizeof(struct bpf_insn));
6139 func[i]->type = prog->type;
6140 func[i]->len = len;
6141 if (bpf_prog_calc_tag(func[i]))
6142 goto out_free;
6143 func[i]->is_func = 1;
6144 /* Use bpf_prog_F_tag to indicate functions in stack traces.
6145 * Long term would need debug info to populate names
6146 */
6147 func[i]->aux->name[0] = 'F';
6148 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
6149 func[i]->jit_requested = 1;
6150 func[i] = bpf_int_jit_compile(func[i]);
6151 if (!func[i]->jited) {
6152 err = -ENOTSUPP;
6153 goto out_free;
6154 }
6155 cond_resched();
6156 }
6157 /* at this point all bpf functions were successfully JITed
6158 * now populate all bpf_calls with correct addresses and
6159 * run last pass of JIT
6160 */
6161 for (i = 0; i < env->subprog_cnt; i++) {
6162 insn = func[i]->insnsi;
6163 for (j = 0; j < func[i]->len; j++, insn++) {
6164 if (insn->code != (BPF_JMP | BPF_CALL) ||
6165 insn->src_reg != BPF_PSEUDO_CALL)
6166 continue;
6167 subprog = insn->off;
6168 insn->imm = (u64 (*)(u64, u64, u64, u64, u64))
6169 func[subprog]->bpf_func -
6170 __bpf_call_base;
6171 }
6172
6173 /* we use the aux data to keep a list of the start addresses
6174 * of the JITed images for each function in the program
6175 *
6176 * for some architectures, such as powerpc64, the imm field
6177 * might not be large enough to hold the offset of the start
6178 * address of the callee's JITed image from __bpf_call_base
6179 *
6180 * in such cases, we can lookup the start address of a callee
6181 * by using its subprog id, available from the off field of
6182 * the call instruction, as an index for this list
6183 */
6184 func[i]->aux->func = func;
6185 func[i]->aux->func_cnt = env->subprog_cnt;
6186 }
6187 for (i = 0; i < env->subprog_cnt; i++) {
6188 old_bpf_func = func[i]->bpf_func;
6189 tmp = bpf_int_jit_compile(func[i]);
6190 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
6191 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
6192 err = -ENOTSUPP;
6193 goto out_free;
6194 }
6195 cond_resched();
6196 }
6197
6198 /* finally lock prog and jit images for all functions and
6199 * populate kallsysm
6200 */
6201 for (i = 0; i < env->subprog_cnt; i++) {
6202 bpf_prog_lock_ro(func[i]);
6203 bpf_prog_kallsyms_add(func[i]);
6204 }
6205
6206 /* Last step: make now unused interpreter insns from main
6207 * prog consistent for later dump requests, so they can
6208 * later look the same as if they were interpreted only.
6209 */
6210 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6211 if (insn->code != (BPF_JMP | BPF_CALL) ||
6212 insn->src_reg != BPF_PSEUDO_CALL)
6213 continue;
6214 insn->off = env->insn_aux_data[i].call_imm;
6215 subprog = find_subprog(env, i + insn->off + 1);
6216 insn->imm = subprog;
6217 }
6218
6219 prog->jited = 1;
6220 prog->bpf_func = func[0]->bpf_func;
6221 prog->aux->func = func;
6222 prog->aux->func_cnt = env->subprog_cnt;
6223 return 0;
6224 out_free:
6225 for (i = 0; i < env->subprog_cnt; i++)
6226 if (func[i])
6227 bpf_jit_free(func[i]);
6228 kfree(func);
6229 out_undo_insn:
6230 /* cleanup main prog to be interpreted */
6231 prog->jit_requested = 0;
6232 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
6233 if (insn->code != (BPF_JMP | BPF_CALL) ||
6234 insn->src_reg != BPF_PSEUDO_CALL)
6235 continue;
6236 insn->off = 0;
6237 insn->imm = env->insn_aux_data[i].call_imm;
6238 }
6239 return err;
6240 }
6241
fixup_call_args(struct bpf_verifier_env * env)6242 static int fixup_call_args(struct bpf_verifier_env *env)
6243 {
6244 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6245 struct bpf_prog *prog = env->prog;
6246 struct bpf_insn *insn = prog->insnsi;
6247 int i, depth;
6248 #endif
6249 int err;
6250
6251 err = 0;
6252 if (env->prog->jit_requested) {
6253 err = jit_subprogs(env);
6254 if (err == 0)
6255 return 0;
6256 if (err == -EFAULT)
6257 return err;
6258 }
6259 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6260 for (i = 0; i < prog->len; i++, insn++) {
6261 if (insn->code != (BPF_JMP | BPF_CALL) ||
6262 insn->src_reg != BPF_PSEUDO_CALL)
6263 continue;
6264 depth = get_callee_stack_depth(env, insn, i);
6265 if (depth < 0)
6266 return depth;
6267 bpf_patch_call_args(insn, depth);
6268 }
6269 err = 0;
6270 #endif
6271 return err;
6272 }
6273
6274 /* fixup insn->imm field of bpf_call instructions
6275 * and inline eligible helpers as explicit sequence of BPF instructions
6276 *
6277 * this function is called after eBPF program passed verification
6278 */
fixup_bpf_calls(struct bpf_verifier_env * env)6279 static int fixup_bpf_calls(struct bpf_verifier_env *env)
6280 {
6281 struct bpf_prog *prog = env->prog;
6282 struct bpf_insn *insn = prog->insnsi;
6283 const struct bpf_func_proto *fn;
6284 const int insn_cnt = prog->len;
6285 const struct bpf_map_ops *ops;
6286 struct bpf_insn_aux_data *aux;
6287 struct bpf_insn insn_buf[16];
6288 struct bpf_prog *new_prog;
6289 struct bpf_map *map_ptr;
6290 int i, cnt, delta = 0;
6291
6292 for (i = 0; i < insn_cnt; i++, insn++) {
6293 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
6294 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
6295 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
6296 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
6297 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
6298 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
6299 struct bpf_insn *patchlet;
6300 struct bpf_insn chk_and_div[] = {
6301 /* [R,W]x div 0 -> 0 */
6302 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
6303 BPF_JNE | BPF_K, insn->src_reg,
6304 0, 2, 0),
6305 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
6306 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6307 *insn,
6308 };
6309 struct bpf_insn chk_and_mod[] = {
6310 /* [R,W]x mod 0 -> [R,W]x */
6311 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
6312 BPF_JEQ | BPF_K, insn->src_reg,
6313 0, 1 + (is64 ? 0 : 1), 0),
6314 *insn,
6315 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
6316 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
6317 };
6318
6319 patchlet = isdiv ? chk_and_div : chk_and_mod;
6320 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
6321 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
6322
6323 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
6324 if (!new_prog)
6325 return -ENOMEM;
6326
6327 delta += cnt - 1;
6328 env->prog = prog = new_prog;
6329 insn = new_prog->insnsi + i + delta;
6330 continue;
6331 }
6332
6333 if (BPF_CLASS(insn->code) == BPF_LD &&
6334 (BPF_MODE(insn->code) == BPF_ABS ||
6335 BPF_MODE(insn->code) == BPF_IND)) {
6336 cnt = env->ops->gen_ld_abs(insn, insn_buf);
6337 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6338 verbose(env, "bpf verifier is misconfigured\n");
6339 return -EINVAL;
6340 }
6341
6342 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6343 if (!new_prog)
6344 return -ENOMEM;
6345
6346 delta += cnt - 1;
6347 env->prog = prog = new_prog;
6348 insn = new_prog->insnsi + i + delta;
6349 continue;
6350 }
6351
6352 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
6353 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
6354 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
6355 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
6356 struct bpf_insn insn_buf[16];
6357 struct bpf_insn *patch = &insn_buf[0];
6358 bool issrc, isneg, isimm;
6359 u32 off_reg;
6360
6361 aux = &env->insn_aux_data[i + delta];
6362 if (!aux->alu_state ||
6363 aux->alu_state == BPF_ALU_NON_POINTER)
6364 continue;
6365
6366 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
6367 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
6368 BPF_ALU_SANITIZE_SRC;
6369 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
6370
6371 off_reg = issrc ? insn->src_reg : insn->dst_reg;
6372 if (isimm) {
6373 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6374 } else {
6375 if (isneg)
6376 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6377 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
6378 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
6379 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
6380 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
6381 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
6382 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
6383 }
6384 if (!issrc)
6385 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
6386 insn->src_reg = BPF_REG_AX;
6387 if (isneg)
6388 insn->code = insn->code == code_add ?
6389 code_sub : code_add;
6390 *patch++ = *insn;
6391 if (issrc && isneg && !isimm)
6392 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
6393 cnt = patch - insn_buf;
6394
6395 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6396 if (!new_prog)
6397 return -ENOMEM;
6398
6399 delta += cnt - 1;
6400 env->prog = prog = new_prog;
6401 insn = new_prog->insnsi + i + delta;
6402 continue;
6403 }
6404
6405 if (insn->code != (BPF_JMP | BPF_CALL))
6406 continue;
6407 if (insn->src_reg == BPF_PSEUDO_CALL)
6408 continue;
6409
6410 if (insn->imm == BPF_FUNC_get_route_realm)
6411 prog->dst_needed = 1;
6412 if (insn->imm == BPF_FUNC_get_prandom_u32)
6413 bpf_user_rnd_init_once();
6414 if (insn->imm == BPF_FUNC_override_return)
6415 prog->kprobe_override = 1;
6416 if (insn->imm == BPF_FUNC_tail_call) {
6417 /* If we tail call into other programs, we
6418 * cannot make any assumptions since they can
6419 * be replaced dynamically during runtime in
6420 * the program array.
6421 */
6422 prog->cb_access = 1;
6423 env->prog->aux->stack_depth = MAX_BPF_STACK;
6424
6425 /* mark bpf_tail_call as different opcode to avoid
6426 * conditional branch in the interpeter for every normal
6427 * call and to prevent accidental JITing by JIT compiler
6428 * that doesn't support bpf_tail_call yet
6429 */
6430 insn->imm = 0;
6431 insn->code = BPF_JMP | BPF_TAIL_CALL;
6432
6433 aux = &env->insn_aux_data[i + delta];
6434 if (!bpf_map_ptr_unpriv(aux))
6435 continue;
6436
6437 /* instead of changing every JIT dealing with tail_call
6438 * emit two extra insns:
6439 * if (index >= max_entries) goto out;
6440 * index &= array->index_mask;
6441 * to avoid out-of-bounds cpu speculation
6442 */
6443 if (bpf_map_ptr_poisoned(aux)) {
6444 verbose(env, "tail_call abusing map_ptr\n");
6445 return -EINVAL;
6446 }
6447
6448 map_ptr = BPF_MAP_PTR(aux->map_state);
6449 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
6450 map_ptr->max_entries, 2);
6451 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
6452 container_of(map_ptr,
6453 struct bpf_array,
6454 map)->index_mask);
6455 insn_buf[2] = *insn;
6456 cnt = 3;
6457 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
6458 if (!new_prog)
6459 return -ENOMEM;
6460
6461 delta += cnt - 1;
6462 env->prog = prog = new_prog;
6463 insn = new_prog->insnsi + i + delta;
6464 continue;
6465 }
6466
6467 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
6468 * and other inlining handlers are currently limited to 64 bit
6469 * only.
6470 */
6471 if (prog->jit_requested && BITS_PER_LONG == 64 &&
6472 (insn->imm == BPF_FUNC_map_lookup_elem ||
6473 insn->imm == BPF_FUNC_map_update_elem ||
6474 insn->imm == BPF_FUNC_map_delete_elem)) {
6475 aux = &env->insn_aux_data[i + delta];
6476 if (bpf_map_ptr_poisoned(aux))
6477 goto patch_call_imm;
6478
6479 map_ptr = BPF_MAP_PTR(aux->map_state);
6480 ops = map_ptr->ops;
6481 if (insn->imm == BPF_FUNC_map_lookup_elem &&
6482 ops->map_gen_lookup) {
6483 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
6484 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
6485 verbose(env, "bpf verifier is misconfigured\n");
6486 return -EINVAL;
6487 }
6488
6489 new_prog = bpf_patch_insn_data(env, i + delta,
6490 insn_buf, cnt);
6491 if (!new_prog)
6492 return -ENOMEM;
6493
6494 delta += cnt - 1;
6495 env->prog = prog = new_prog;
6496 insn = new_prog->insnsi + i + delta;
6497 continue;
6498 }
6499
6500 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
6501 (void *(*)(struct bpf_map *map, void *key))NULL));
6502 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
6503 (int (*)(struct bpf_map *map, void *key))NULL));
6504 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
6505 (int (*)(struct bpf_map *map, void *key, void *value,
6506 u64 flags))NULL));
6507 switch (insn->imm) {
6508 case BPF_FUNC_map_lookup_elem:
6509 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
6510 __bpf_call_base;
6511 continue;
6512 case BPF_FUNC_map_update_elem:
6513 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
6514 __bpf_call_base;
6515 continue;
6516 case BPF_FUNC_map_delete_elem:
6517 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
6518 __bpf_call_base;
6519 continue;
6520 }
6521
6522 goto patch_call_imm;
6523 }
6524
6525 patch_call_imm:
6526 fn = env->ops->get_func_proto(insn->imm, env->prog);
6527 /* all functions that have prototype and verifier allowed
6528 * programs to call them, must be real in-kernel functions
6529 */
6530 if (!fn->func) {
6531 verbose(env,
6532 "kernel subsystem misconfigured func %s#%d\n",
6533 func_id_name(insn->imm), insn->imm);
6534 return -EFAULT;
6535 }
6536 insn->imm = fn->func - __bpf_call_base;
6537 }
6538
6539 return 0;
6540 }
6541
free_states(struct bpf_verifier_env * env)6542 static void free_states(struct bpf_verifier_env *env)
6543 {
6544 struct bpf_verifier_state_list *sl, *sln;
6545 int i;
6546
6547 if (!env->explored_states)
6548 return;
6549
6550 for (i = 0; i < env->prog->len; i++) {
6551 sl = env->explored_states[i];
6552
6553 if (sl)
6554 while (sl != STATE_LIST_MARK) {
6555 sln = sl->next;
6556 free_verifier_state(&sl->state, false);
6557 kfree(sl);
6558 sl = sln;
6559 }
6560 }
6561
6562 kfree(env->explored_states);
6563 }
6564
bpf_check(struct bpf_prog ** prog,union bpf_attr * attr)6565 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr)
6566 {
6567 struct bpf_verifier_env *env;
6568 struct bpf_verifier_log *log;
6569 int ret = -EINVAL;
6570
6571 /* no program is valid */
6572 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
6573 return -EINVAL;
6574
6575 /* 'struct bpf_verifier_env' can be global, but since it's not small,
6576 * allocate/free it every time bpf_check() is called
6577 */
6578 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
6579 if (!env)
6580 return -ENOMEM;
6581 log = &env->log;
6582
6583 env->insn_aux_data =
6584 vzalloc(array_size(sizeof(struct bpf_insn_aux_data),
6585 (*prog)->len));
6586 ret = -ENOMEM;
6587 if (!env->insn_aux_data)
6588 goto err_free_env;
6589 env->prog = *prog;
6590 env->ops = bpf_verifier_ops[env->prog->type];
6591
6592 /* grab the mutex to protect few globals used by verifier */
6593 mutex_lock(&bpf_verifier_lock);
6594
6595 if (attr->log_level || attr->log_buf || attr->log_size) {
6596 /* user requested verbose verifier output
6597 * and supplied buffer to store the verification trace
6598 */
6599 log->level = attr->log_level;
6600 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
6601 log->len_total = attr->log_size;
6602
6603 ret = -EINVAL;
6604 /* log attributes have to be sane */
6605 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
6606 !log->level || !log->ubuf)
6607 goto err_unlock;
6608 }
6609
6610 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
6611 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
6612 env->strict_alignment = true;
6613
6614 ret = replace_map_fd_with_map_ptr(env);
6615 if (ret < 0)
6616 goto skip_full_check;
6617
6618 if (bpf_prog_is_dev_bound(env->prog->aux)) {
6619 ret = bpf_prog_offload_verifier_prep(env);
6620 if (ret)
6621 goto skip_full_check;
6622 }
6623
6624 env->explored_states = kcalloc(env->prog->len,
6625 sizeof(struct bpf_verifier_state_list *),
6626 GFP_USER);
6627 ret = -ENOMEM;
6628 if (!env->explored_states)
6629 goto skip_full_check;
6630
6631 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN);
6632
6633 ret = check_cfg(env);
6634 if (ret < 0)
6635 goto skip_full_check;
6636
6637 ret = do_check(env);
6638 if (env->cur_state) {
6639 free_verifier_state(env->cur_state, true);
6640 env->cur_state = NULL;
6641 }
6642
6643 skip_full_check:
6644 while (!pop_stack(env, NULL, NULL));
6645 free_states(env);
6646
6647 if (ret == 0)
6648 sanitize_dead_code(env);
6649
6650 if (ret == 0)
6651 ret = check_max_stack_depth(env);
6652
6653 if (ret == 0)
6654 /* program is valid, convert *(u32*)(ctx + off) accesses */
6655 ret = convert_ctx_accesses(env);
6656
6657 if (ret == 0)
6658 ret = fixup_bpf_calls(env);
6659
6660 if (ret == 0)
6661 ret = fixup_call_args(env);
6662
6663 if (log->level && bpf_verifier_log_full(log))
6664 ret = -ENOSPC;
6665 if (log->level && !log->ubuf) {
6666 ret = -EFAULT;
6667 goto err_release_maps;
6668 }
6669
6670 if (ret == 0 && env->used_map_cnt) {
6671 /* if program passed verifier, update used_maps in bpf_prog_info */
6672 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
6673 sizeof(env->used_maps[0]),
6674 GFP_KERNEL);
6675
6676 if (!env->prog->aux->used_maps) {
6677 ret = -ENOMEM;
6678 goto err_release_maps;
6679 }
6680
6681 memcpy(env->prog->aux->used_maps, env->used_maps,
6682 sizeof(env->used_maps[0]) * env->used_map_cnt);
6683 env->prog->aux->used_map_cnt = env->used_map_cnt;
6684
6685 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
6686 * bpf_ld_imm64 instructions
6687 */
6688 convert_pseudo_ld_imm64(env);
6689 }
6690
6691 err_release_maps:
6692 if (!env->prog->aux->used_maps)
6693 /* if we didn't copy map pointers into bpf_prog_info, release
6694 * them now. Otherwise free_used_maps() will release them.
6695 */
6696 release_maps(env);
6697 *prog = env->prog;
6698 err_unlock:
6699 mutex_unlock(&bpf_verifier_lock);
6700 vfree(env->insn_aux_data);
6701 err_free_env:
6702 kfree(env);
6703 return ret;
6704 }
6705