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