bpf: Introduce BPF nospec instruction for mitigating Spectre v4
[linux-block.git] / kernel / bpf / verifier.c
CommitLineData
5b497af4 1// SPDX-License-Identifier: GPL-2.0-only
51580e79 2/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
969bf05e 3 * Copyright (c) 2016 Facebook
fd978bf7 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
51580e79 5 */
838e9690 6#include <uapi/linux/btf.h>
51580e79
AS
7#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
838e9690 11#include <linux/btf.h>
58e2af8b 12#include <linux/bpf_verifier.h>
51580e79
AS
13#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
ebb676da 17#include <linux/stringify.h>
cc8b0b92
AS
18#include <linux/bsearch.h>
19#include <linux/sort.h>
c195651e 20#include <linux/perf_event.h>
d9762e84 21#include <linux/ctype.h>
6ba43b76 22#include <linux/error-injection.h>
9e4e01df 23#include <linux/bpf_lsm.h>
1e6c62a8 24#include <linux/btf_ids.h>
51580e79 25
f4ac7e0b
JK
26#include "disasm.h"
27
00176a34 28static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
91cc1a99 29#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
00176a34
JK
30 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
f2e10bff 32#define BPF_LINK_TYPE(_id, _name)
00176a34
JK
33#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
f2e10bff 36#undef BPF_LINK_TYPE
00176a34
JK
37};
38
51580e79
AS
39/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
8fb33b60 50 * Since it's analyzing all paths through the program, the length of the
eba38a96 51 * analysis is limited to 64k insn, which may be hit even if total number of
51580e79
AS
52 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
f1174f77 79 * Most of the time the registers have SCALAR_VALUE type, which
51580e79 80 * means the register has some value, but it's not a valid pointer.
f1174f77 81 * (like pointer plus pointer becomes SCALAR_VALUE type)
51580e79
AS
82 *
83 * When verifier sees load or store instructions the type of base register
c64b7983
JS
84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
51580e79
AS
86 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
8fb33b60 135 * returns either pointer to map value or NULL.
51580e79
AS
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
fd978bf7
JS
144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
6acc9b43
JS
156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
51580e79
AS
162 */
163
17a52670 164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
58e2af8b 165struct bpf_verifier_stack_elem {
17a52670
AS
166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
58e2af8b 170 struct bpf_verifier_state st;
17a52670
AS
171 int insn_idx;
172 int prev_insn_idx;
58e2af8b 173 struct bpf_verifier_stack_elem *next;
6f8a57cc
AN
174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
cbd35700
AS
176};
177
b285fcb7 178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
ceefbc96 179#define BPF_COMPLEXITY_LIMIT_STATES 64
07016151 180
d2e4c1e6
DB
181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
c93552c4
DB
184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
d2e4c1e6 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
c93552c4
DB
192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
d2e4c1e6 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
c93552c4
DB
197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
d2e4c1e6
DB
204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
c93552c4 229}
fad73a1a 230
23a2d70c
YS
231static bool bpf_pseudo_call(const struct bpf_insn *insn)
232{
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
235}
236
e6ac2450
MKL
237static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
238{
239 return insn->code == (BPF_JMP | BPF_CALL) &&
240 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
241}
242
69c087ba
YS
243static bool bpf_pseudo_func(const struct bpf_insn *insn)
244{
245 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
246 insn->src_reg == BPF_PSEUDO_FUNC;
247}
248
33ff9823
DB
249struct bpf_call_arg_meta {
250 struct bpf_map *map_ptr;
435faee1 251 bool raw_mode;
36bbef52 252 bool pkt_access;
435faee1
DB
253 int regno;
254 int access_size;
457f4436 255 int mem_size;
10060503 256 u64 msize_max_value;
1b986589 257 int ref_obj_id;
d83525ca 258 int func_id;
22dc4a0f 259 struct btf *btf;
eaa6bcb7 260 u32 btf_id;
22dc4a0f 261 struct btf *ret_btf;
eaa6bcb7 262 u32 ret_btf_id;
69c087ba 263 u32 subprogno;
33ff9823
DB
264};
265
8580ac94
AS
266struct btf *btf_vmlinux;
267
cbd35700
AS
268static DEFINE_MUTEX(bpf_verifier_lock);
269
d9762e84
MKL
270static const struct bpf_line_info *
271find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
272{
273 const struct bpf_line_info *linfo;
274 const struct bpf_prog *prog;
275 u32 i, nr_linfo;
276
277 prog = env->prog;
278 nr_linfo = prog->aux->nr_linfo;
279
280 if (!nr_linfo || insn_off >= prog->len)
281 return NULL;
282
283 linfo = prog->aux->linfo;
284 for (i = 1; i < nr_linfo; i++)
285 if (insn_off < linfo[i].insn_off)
286 break;
287
288 return &linfo[i - 1];
289}
290
77d2e05a
MKL
291void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
292 va_list args)
cbd35700 293{
a2a7d570 294 unsigned int n;
cbd35700 295
a2a7d570 296 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
a2a7d570
JK
297
298 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
299 "verifier log line truncated - local buffer too short\n");
300
301 n = min(log->len_total - log->len_used - 1, n);
302 log->kbuf[n] = '\0';
303
8580ac94
AS
304 if (log->level == BPF_LOG_KERNEL) {
305 pr_err("BPF:%s\n", log->kbuf);
306 return;
307 }
a2a7d570
JK
308 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
309 log->len_used += n;
310 else
311 log->ubuf = NULL;
cbd35700 312}
abe08840 313
6f8a57cc
AN
314static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
315{
316 char zero = 0;
317
318 if (!bpf_verifier_log_needed(log))
319 return;
320
321 log->len_used = new_pos;
322 if (put_user(zero, log->ubuf + new_pos))
323 log->ubuf = NULL;
324}
325
abe08840
JO
326/* log_level controls verbosity level of eBPF verifier.
327 * bpf_verifier_log_write() is used to dump the verification trace to the log,
328 * so the user can figure out what's wrong with the program
430e68d1 329 */
abe08840
JO
330__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331 const char *fmt, ...)
332{
333 va_list args;
334
77d2e05a
MKL
335 if (!bpf_verifier_log_needed(&env->log))
336 return;
337
abe08840 338 va_start(args, fmt);
77d2e05a 339 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
340 va_end(args);
341}
342EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
343
344__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
345{
77d2e05a 346 struct bpf_verifier_env *env = private_data;
abe08840
JO
347 va_list args;
348
77d2e05a
MKL
349 if (!bpf_verifier_log_needed(&env->log))
350 return;
351
abe08840 352 va_start(args, fmt);
77d2e05a 353 bpf_verifier_vlog(&env->log, fmt, args);
abe08840
JO
354 va_end(args);
355}
cbd35700 356
9e15db66
AS
357__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
358 const char *fmt, ...)
359{
360 va_list args;
361
362 if (!bpf_verifier_log_needed(log))
363 return;
364
365 va_start(args, fmt);
366 bpf_verifier_vlog(log, fmt, args);
367 va_end(args);
368}
369
d9762e84
MKL
370static const char *ltrim(const char *s)
371{
372 while (isspace(*s))
373 s++;
374
375 return s;
376}
377
378__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
379 u32 insn_off,
380 const char *prefix_fmt, ...)
381{
382 const struct bpf_line_info *linfo;
383
384 if (!bpf_verifier_log_needed(&env->log))
385 return;
386
387 linfo = find_linfo(env, insn_off);
388 if (!linfo || linfo == env->prev_linfo)
389 return;
390
391 if (prefix_fmt) {
392 va_list args;
393
394 va_start(args, prefix_fmt);
395 bpf_verifier_vlog(&env->log, prefix_fmt, args);
396 va_end(args);
397 }
398
399 verbose(env, "%s\n",
400 ltrim(btf_name_by_offset(env->prog->aux->btf,
401 linfo->line_off)));
402
403 env->prev_linfo = linfo;
404}
405
bc2591d6
YS
406static void verbose_invalid_scalar(struct bpf_verifier_env *env,
407 struct bpf_reg_state *reg,
408 struct tnum *range, const char *ctx,
409 const char *reg_name)
410{
411 char tn_buf[48];
412
413 verbose(env, "At %s the register %s ", ctx, reg_name);
414 if (!tnum_is_unknown(reg->var_off)) {
415 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
416 verbose(env, "has value %s", tn_buf);
417 } else {
418 verbose(env, "has unknown scalar value");
419 }
420 tnum_strn(tn_buf, sizeof(tn_buf), *range);
421 verbose(env, " should have been in %s\n", tn_buf);
422}
423
de8f3a83
DB
424static bool type_is_pkt_pointer(enum bpf_reg_type type)
425{
426 return type == PTR_TO_PACKET ||
427 type == PTR_TO_PACKET_META;
428}
429
46f8bc92
MKL
430static bool type_is_sk_pointer(enum bpf_reg_type type)
431{
432 return type == PTR_TO_SOCKET ||
655a51e5 433 type == PTR_TO_SOCK_COMMON ||
fada7fdc
JL
434 type == PTR_TO_TCP_SOCK ||
435 type == PTR_TO_XDP_SOCK;
46f8bc92
MKL
436}
437
cac616db
JF
438static bool reg_type_not_null(enum bpf_reg_type type)
439{
440 return type == PTR_TO_SOCKET ||
441 type == PTR_TO_TCP_SOCK ||
442 type == PTR_TO_MAP_VALUE ||
69c087ba 443 type == PTR_TO_MAP_KEY ||
01c66c48 444 type == PTR_TO_SOCK_COMMON;
cac616db
JF
445}
446
840b9615
JS
447static bool reg_type_may_be_null(enum bpf_reg_type type)
448{
fd978bf7 449 return type == PTR_TO_MAP_VALUE_OR_NULL ||
46f8bc92 450 type == PTR_TO_SOCKET_OR_NULL ||
655a51e5 451 type == PTR_TO_SOCK_COMMON_OR_NULL ||
b121b341 452 type == PTR_TO_TCP_SOCK_OR_NULL ||
457f4436 453 type == PTR_TO_BTF_ID_OR_NULL ||
afbf21dc
YS
454 type == PTR_TO_MEM_OR_NULL ||
455 type == PTR_TO_RDONLY_BUF_OR_NULL ||
456 type == PTR_TO_RDWR_BUF_OR_NULL;
fd978bf7
JS
457}
458
d83525ca
AS
459static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
460{
461 return reg->type == PTR_TO_MAP_VALUE &&
462 map_value_has_spin_lock(reg->map_ptr);
463}
464
cba368c1
MKL
465static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
466{
467 return type == PTR_TO_SOCKET ||
468 type == PTR_TO_SOCKET_OR_NULL ||
469 type == PTR_TO_TCP_SOCK ||
457f4436
AN
470 type == PTR_TO_TCP_SOCK_OR_NULL ||
471 type == PTR_TO_MEM ||
472 type == PTR_TO_MEM_OR_NULL;
cba368c1
MKL
473}
474
1b986589 475static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
fd978bf7 476{
1b986589 477 return type == ARG_PTR_TO_SOCK_COMMON;
fd978bf7
JS
478}
479
fd1b0d60
LB
480static bool arg_type_may_be_null(enum bpf_arg_type type)
481{
482 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
483 type == ARG_PTR_TO_MEM_OR_NULL ||
484 type == ARG_PTR_TO_CTX_OR_NULL ||
485 type == ARG_PTR_TO_SOCKET_OR_NULL ||
69c087ba
YS
486 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487 type == ARG_PTR_TO_STACK_OR_NULL;
fd1b0d60
LB
488}
489
fd978bf7
JS
490/* Determine whether the function releases some resources allocated by another
491 * function call. The first reference type argument will be assumed to be
492 * released by release_reference().
493 */
494static bool is_release_function(enum bpf_func_id func_id)
495{
457f4436
AN
496 return func_id == BPF_FUNC_sk_release ||
497 func_id == BPF_FUNC_ringbuf_submit ||
498 func_id == BPF_FUNC_ringbuf_discard;
840b9615
JS
499}
500
64d85290 501static bool may_be_acquire_function(enum bpf_func_id func_id)
46f8bc92
MKL
502{
503 return func_id == BPF_FUNC_sk_lookup_tcp ||
edbf8c01 504 func_id == BPF_FUNC_sk_lookup_udp ||
64d85290 505 func_id == BPF_FUNC_skc_lookup_tcp ||
457f4436
AN
506 func_id == BPF_FUNC_map_lookup_elem ||
507 func_id == BPF_FUNC_ringbuf_reserve;
64d85290
JS
508}
509
510static bool is_acquire_function(enum bpf_func_id func_id,
511 const struct bpf_map *map)
512{
513 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
514
515 if (func_id == BPF_FUNC_sk_lookup_tcp ||
516 func_id == BPF_FUNC_sk_lookup_udp ||
457f4436
AN
517 func_id == BPF_FUNC_skc_lookup_tcp ||
518 func_id == BPF_FUNC_ringbuf_reserve)
64d85290
JS
519 return true;
520
521 if (func_id == BPF_FUNC_map_lookup_elem &&
522 (map_type == BPF_MAP_TYPE_SOCKMAP ||
523 map_type == BPF_MAP_TYPE_SOCKHASH))
524 return true;
525
526 return false;
46f8bc92
MKL
527}
528
1b986589
MKL
529static bool is_ptr_cast_function(enum bpf_func_id func_id)
530{
531 return func_id == BPF_FUNC_tcp_sock ||
1df8f55a
MKL
532 func_id == BPF_FUNC_sk_fullsock ||
533 func_id == BPF_FUNC_skc_to_tcp_sock ||
534 func_id == BPF_FUNC_skc_to_tcp6_sock ||
535 func_id == BPF_FUNC_skc_to_udp6_sock ||
536 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537 func_id == BPF_FUNC_skc_to_tcp_request_sock;
1b986589
MKL
538}
539
39491867
BJ
540static bool is_cmpxchg_insn(const struct bpf_insn *insn)
541{
542 return BPF_CLASS(insn->code) == BPF_STX &&
543 BPF_MODE(insn->code) == BPF_ATOMIC &&
544 insn->imm == BPF_CMPXCHG;
545}
546
17a52670
AS
547/* string representation of 'enum bpf_reg_type' */
548static const char * const reg_type_str[] = {
549 [NOT_INIT] = "?",
f1174f77 550 [SCALAR_VALUE] = "inv",
17a52670
AS
551 [PTR_TO_CTX] = "ctx",
552 [CONST_PTR_TO_MAP] = "map_ptr",
553 [PTR_TO_MAP_VALUE] = "map_value",
554 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
17a52670 555 [PTR_TO_STACK] = "fp",
969bf05e 556 [PTR_TO_PACKET] = "pkt",
de8f3a83 557 [PTR_TO_PACKET_META] = "pkt_meta",
969bf05e 558 [PTR_TO_PACKET_END] = "pkt_end",
d58e468b 559 [PTR_TO_FLOW_KEYS] = "flow_keys",
c64b7983
JS
560 [PTR_TO_SOCKET] = "sock",
561 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
46f8bc92
MKL
562 [PTR_TO_SOCK_COMMON] = "sock_common",
563 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
655a51e5
MKL
564 [PTR_TO_TCP_SOCK] = "tcp_sock",
565 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
9df1c28b 566 [PTR_TO_TP_BUFFER] = "tp_buffer",
fada7fdc 567 [PTR_TO_XDP_SOCK] = "xdp_sock",
9e15db66 568 [PTR_TO_BTF_ID] = "ptr_",
b121b341 569 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
eaa6bcb7 570 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
457f4436
AN
571 [PTR_TO_MEM] = "mem",
572 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
afbf21dc
YS
573 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
574 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
575 [PTR_TO_RDWR_BUF] = "rdwr_buf",
576 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
69c087ba
YS
577 [PTR_TO_FUNC] = "func",
578 [PTR_TO_MAP_KEY] = "map_key",
17a52670
AS
579};
580
8efea21d
EC
581static char slot_type_char[] = {
582 [STACK_INVALID] = '?',
583 [STACK_SPILL] = 'r',
584 [STACK_MISC] = 'm',
585 [STACK_ZERO] = '0',
586};
587
4e92024a
AS
588static void print_liveness(struct bpf_verifier_env *env,
589 enum bpf_reg_liveness live)
590{
9242b5f5 591 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
4e92024a
AS
592 verbose(env, "_");
593 if (live & REG_LIVE_READ)
594 verbose(env, "r");
595 if (live & REG_LIVE_WRITTEN)
596 verbose(env, "w");
9242b5f5
AS
597 if (live & REG_LIVE_DONE)
598 verbose(env, "D");
4e92024a
AS
599}
600
f4d7e40a
AS
601static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 const struct bpf_reg_state *reg)
603{
604 struct bpf_verifier_state *cur = env->cur_state;
605
606 return cur->frame[reg->frameno];
607}
608
22dc4a0f 609static const char *kernel_type_name(const struct btf* btf, u32 id)
9e15db66 610{
22dc4a0f 611 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
9e15db66
AS
612}
613
61bd5218 614static void print_verifier_state(struct bpf_verifier_env *env,
f4d7e40a 615 const struct bpf_func_state *state)
17a52670 616{
f4d7e40a 617 const struct bpf_reg_state *reg;
17a52670
AS
618 enum bpf_reg_type t;
619 int i;
620
f4d7e40a
AS
621 if (state->frameno)
622 verbose(env, " frame%d:", state->frameno);
17a52670 623 for (i = 0; i < MAX_BPF_REG; i++) {
1a0dc1ac
AS
624 reg = &state->regs[i];
625 t = reg->type;
17a52670
AS
626 if (t == NOT_INIT)
627 continue;
4e92024a
AS
628 verbose(env, " R%d", i);
629 print_liveness(env, reg->live);
630 verbose(env, "=%s", reg_type_str[t]);
b5dc0163
AS
631 if (t == SCALAR_VALUE && reg->precise)
632 verbose(env, "P");
f1174f77
EC
633 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634 tnum_is_const(reg->var_off)) {
635 /* reg->off should be 0 for SCALAR_VALUE */
61bd5218 636 verbose(env, "%lld", reg->var_off.value + reg->off);
f1174f77 637 } else {
eaa6bcb7
HL
638 if (t == PTR_TO_BTF_ID ||
639 t == PTR_TO_BTF_ID_OR_NULL ||
640 t == PTR_TO_PERCPU_BTF_ID)
22dc4a0f 641 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
cba368c1
MKL
642 verbose(env, "(id=%d", reg->id);
643 if (reg_type_may_be_refcounted_or_null(t))
644 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
f1174f77 645 if (t != SCALAR_VALUE)
61bd5218 646 verbose(env, ",off=%d", reg->off);
de8f3a83 647 if (type_is_pkt_pointer(t))
61bd5218 648 verbose(env, ",r=%d", reg->range);
f1174f77 649 else if (t == CONST_PTR_TO_MAP ||
69c087ba 650 t == PTR_TO_MAP_KEY ||
f1174f77
EC
651 t == PTR_TO_MAP_VALUE ||
652 t == PTR_TO_MAP_VALUE_OR_NULL)
61bd5218 653 verbose(env, ",ks=%d,vs=%d",
f1174f77
EC
654 reg->map_ptr->key_size,
655 reg->map_ptr->value_size);
7d1238f2
EC
656 if (tnum_is_const(reg->var_off)) {
657 /* Typically an immediate SCALAR_VALUE, but
658 * could be a pointer whose offset is too big
659 * for reg->off
660 */
61bd5218 661 verbose(env, ",imm=%llx", reg->var_off.value);
7d1238f2
EC
662 } else {
663 if (reg->smin_value != reg->umin_value &&
664 reg->smin_value != S64_MIN)
61bd5218 665 verbose(env, ",smin_value=%lld",
7d1238f2
EC
666 (long long)reg->smin_value);
667 if (reg->smax_value != reg->umax_value &&
668 reg->smax_value != S64_MAX)
61bd5218 669 verbose(env, ",smax_value=%lld",
7d1238f2
EC
670 (long long)reg->smax_value);
671 if (reg->umin_value != 0)
61bd5218 672 verbose(env, ",umin_value=%llu",
7d1238f2
EC
673 (unsigned long long)reg->umin_value);
674 if (reg->umax_value != U64_MAX)
61bd5218 675 verbose(env, ",umax_value=%llu",
7d1238f2
EC
676 (unsigned long long)reg->umax_value);
677 if (!tnum_is_unknown(reg->var_off)) {
678 char tn_buf[48];
f1174f77 679
7d1238f2 680 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 681 verbose(env, ",var_off=%s", tn_buf);
7d1238f2 682 }
3f50f132
JF
683 if (reg->s32_min_value != reg->smin_value &&
684 reg->s32_min_value != S32_MIN)
685 verbose(env, ",s32_min_value=%d",
686 (int)(reg->s32_min_value));
687 if (reg->s32_max_value != reg->smax_value &&
688 reg->s32_max_value != S32_MAX)
689 verbose(env, ",s32_max_value=%d",
690 (int)(reg->s32_max_value));
691 if (reg->u32_min_value != reg->umin_value &&
692 reg->u32_min_value != U32_MIN)
693 verbose(env, ",u32_min_value=%d",
694 (int)(reg->u32_min_value));
695 if (reg->u32_max_value != reg->umax_value &&
696 reg->u32_max_value != U32_MAX)
697 verbose(env, ",u32_max_value=%d",
698 (int)(reg->u32_max_value));
f1174f77 699 }
61bd5218 700 verbose(env, ")");
f1174f77 701 }
17a52670 702 }
638f5b90 703 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
8efea21d
EC
704 char types_buf[BPF_REG_SIZE + 1];
705 bool valid = false;
706 int j;
707
708 for (j = 0; j < BPF_REG_SIZE; j++) {
709 if (state->stack[i].slot_type[j] != STACK_INVALID)
710 valid = true;
711 types_buf[j] = slot_type_char[
712 state->stack[i].slot_type[j]];
713 }
714 types_buf[BPF_REG_SIZE] = 0;
715 if (!valid)
716 continue;
717 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
718 print_liveness(env, state->stack[i].spilled_ptr.live);
b5dc0163
AS
719 if (state->stack[i].slot_type[0] == STACK_SPILL) {
720 reg = &state->stack[i].spilled_ptr;
721 t = reg->type;
722 verbose(env, "=%s", reg_type_str[t]);
723 if (t == SCALAR_VALUE && reg->precise)
724 verbose(env, "P");
725 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
726 verbose(env, "%lld", reg->var_off.value + reg->off);
727 } else {
8efea21d 728 verbose(env, "=%s", types_buf);
b5dc0163 729 }
17a52670 730 }
fd978bf7
JS
731 if (state->acquired_refs && state->refs[0].id) {
732 verbose(env, " refs=%d", state->refs[0].id);
733 for (i = 1; i < state->acquired_refs; i++)
734 if (state->refs[i].id)
735 verbose(env, ",%d", state->refs[i].id);
736 }
61bd5218 737 verbose(env, "\n");
17a52670
AS
738}
739
c69431aa
LB
740/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
741 * small to hold src. This is different from krealloc since we don't want to preserve
742 * the contents of dst.
743 *
744 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
745 * not be allocated.
638f5b90 746 */
c69431aa 747static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
638f5b90 748{
c69431aa
LB
749 size_t bytes;
750
751 if (ZERO_OR_NULL_PTR(src))
752 goto out;
753
754 if (unlikely(check_mul_overflow(n, size, &bytes)))
755 return NULL;
756
757 if (ksize(dst) < bytes) {
758 kfree(dst);
759 dst = kmalloc_track_caller(bytes, flags);
760 if (!dst)
761 return NULL;
762 }
763
764 memcpy(dst, src, bytes);
765out:
766 return dst ? dst : ZERO_SIZE_PTR;
767}
768
769/* resize an array from old_n items to new_n items. the array is reallocated if it's too
770 * small to hold new_n items. new items are zeroed out if the array grows.
771 *
772 * Contrary to krealloc_array, does not free arr if new_n is zero.
773 */
774static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
775{
776 if (!new_n || old_n == new_n)
777 goto out;
778
779 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
780 if (!arr)
781 return NULL;
782
783 if (new_n > old_n)
784 memset(arr + old_n * size, 0, (new_n - old_n) * size);
785
786out:
787 return arr ? arr : ZERO_SIZE_PTR;
788}
789
790static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
791{
792 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
793 sizeof(struct bpf_reference_state), GFP_KERNEL);
794 if (!dst->refs)
795 return -ENOMEM;
796
797 dst->acquired_refs = src->acquired_refs;
798 return 0;
799}
800
801static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
802{
803 size_t n = src->allocated_stack / BPF_REG_SIZE;
804
805 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
806 GFP_KERNEL);
807 if (!dst->stack)
808 return -ENOMEM;
809
810 dst->allocated_stack = src->allocated_stack;
811 return 0;
812}
813
814static int resize_reference_state(struct bpf_func_state *state, size_t n)
815{
816 state->refs = realloc_array(state->refs, state->acquired_refs, n,
817 sizeof(struct bpf_reference_state));
818 if (!state->refs)
819 return -ENOMEM;
820
821 state->acquired_refs = n;
822 return 0;
823}
824
825static int grow_stack_state(struct bpf_func_state *state, int size)
826{
827 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
828
829 if (old_n >= n)
830 return 0;
831
832 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
833 if (!state->stack)
834 return -ENOMEM;
835
836 state->allocated_stack = size;
837 return 0;
fd978bf7
JS
838}
839
840/* Acquire a pointer id from the env and update the state->refs to include
841 * this new pointer reference.
842 * On success, returns a valid pointer id to associate with the register
843 * On failure, returns a negative errno.
638f5b90 844 */
fd978bf7 845static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
638f5b90 846{
fd978bf7
JS
847 struct bpf_func_state *state = cur_func(env);
848 int new_ofs = state->acquired_refs;
849 int id, err;
850
c69431aa 851 err = resize_reference_state(state, state->acquired_refs + 1);
fd978bf7
JS
852 if (err)
853 return err;
854 id = ++env->id_gen;
855 state->refs[new_ofs].id = id;
856 state->refs[new_ofs].insn_idx = insn_idx;
638f5b90 857
fd978bf7
JS
858 return id;
859}
860
861/* release function corresponding to acquire_reference_state(). Idempotent. */
46f8bc92 862static int release_reference_state(struct bpf_func_state *state, int ptr_id)
fd978bf7
JS
863{
864 int i, last_idx;
865
fd978bf7
JS
866 last_idx = state->acquired_refs - 1;
867 for (i = 0; i < state->acquired_refs; i++) {
868 if (state->refs[i].id == ptr_id) {
869 if (last_idx && i != last_idx)
870 memcpy(&state->refs[i], &state->refs[last_idx],
871 sizeof(*state->refs));
872 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
873 state->acquired_refs--;
638f5b90 874 return 0;
638f5b90 875 }
638f5b90 876 }
46f8bc92 877 return -EINVAL;
fd978bf7
JS
878}
879
f4d7e40a
AS
880static void free_func_state(struct bpf_func_state *state)
881{
5896351e
AS
882 if (!state)
883 return;
fd978bf7 884 kfree(state->refs);
f4d7e40a
AS
885 kfree(state->stack);
886 kfree(state);
887}
888
b5dc0163
AS
889static void clear_jmp_history(struct bpf_verifier_state *state)
890{
891 kfree(state->jmp_history);
892 state->jmp_history = NULL;
893 state->jmp_history_cnt = 0;
894}
895
1969db47
AS
896static void free_verifier_state(struct bpf_verifier_state *state,
897 bool free_self)
638f5b90 898{
f4d7e40a
AS
899 int i;
900
901 for (i = 0; i <= state->curframe; i++) {
902 free_func_state(state->frame[i]);
903 state->frame[i] = NULL;
904 }
b5dc0163 905 clear_jmp_history(state);
1969db47
AS
906 if (free_self)
907 kfree(state);
638f5b90
AS
908}
909
910/* copy verifier state from src to dst growing dst stack space
911 * when necessary to accommodate larger src stack
912 */
f4d7e40a
AS
913static int copy_func_state(struct bpf_func_state *dst,
914 const struct bpf_func_state *src)
638f5b90
AS
915{
916 int err;
917
fd978bf7
JS
918 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
919 err = copy_reference_state(dst, src);
638f5b90
AS
920 if (err)
921 return err;
638f5b90
AS
922 return copy_stack_state(dst, src);
923}
924
f4d7e40a
AS
925static int copy_verifier_state(struct bpf_verifier_state *dst_state,
926 const struct bpf_verifier_state *src)
927{
928 struct bpf_func_state *dst;
929 int i, err;
930
06ab6a50
LB
931 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
932 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
933 GFP_USER);
934 if (!dst_state->jmp_history)
935 return -ENOMEM;
b5dc0163
AS
936 dst_state->jmp_history_cnt = src->jmp_history_cnt;
937
f4d7e40a
AS
938 /* if dst has more stack frames then src frame, free them */
939 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
940 free_func_state(dst_state->frame[i]);
941 dst_state->frame[i] = NULL;
942 }
979d63d5 943 dst_state->speculative = src->speculative;
f4d7e40a 944 dst_state->curframe = src->curframe;
d83525ca 945 dst_state->active_spin_lock = src->active_spin_lock;
2589726d
AS
946 dst_state->branches = src->branches;
947 dst_state->parent = src->parent;
b5dc0163
AS
948 dst_state->first_insn_idx = src->first_insn_idx;
949 dst_state->last_insn_idx = src->last_insn_idx;
f4d7e40a
AS
950 for (i = 0; i <= src->curframe; i++) {
951 dst = dst_state->frame[i];
952 if (!dst) {
953 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
954 if (!dst)
955 return -ENOMEM;
956 dst_state->frame[i] = dst;
957 }
958 err = copy_func_state(dst, src->frame[i]);
959 if (err)
960 return err;
961 }
962 return 0;
963}
964
2589726d
AS
965static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
966{
967 while (st) {
968 u32 br = --st->branches;
969
970 /* WARN_ON(br > 1) technically makes sense here,
971 * but see comment in push_stack(), hence:
972 */
973 WARN_ONCE((int)br < 0,
974 "BUG update_branch_counts:branches_to_explore=%d\n",
975 br);
976 if (br)
977 break;
978 st = st->parent;
979 }
980}
981
638f5b90 982static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
6f8a57cc 983 int *insn_idx, bool pop_log)
638f5b90
AS
984{
985 struct bpf_verifier_state *cur = env->cur_state;
986 struct bpf_verifier_stack_elem *elem, *head = env->head;
987 int err;
17a52670
AS
988
989 if (env->head == NULL)
638f5b90 990 return -ENOENT;
17a52670 991
638f5b90
AS
992 if (cur) {
993 err = copy_verifier_state(cur, &head->st);
994 if (err)
995 return err;
996 }
6f8a57cc
AN
997 if (pop_log)
998 bpf_vlog_reset(&env->log, head->log_pos);
638f5b90
AS
999 if (insn_idx)
1000 *insn_idx = head->insn_idx;
17a52670 1001 if (prev_insn_idx)
638f5b90
AS
1002 *prev_insn_idx = head->prev_insn_idx;
1003 elem = head->next;
1969db47 1004 free_verifier_state(&head->st, false);
638f5b90 1005 kfree(head);
17a52670
AS
1006 env->head = elem;
1007 env->stack_size--;
638f5b90 1008 return 0;
17a52670
AS
1009}
1010
58e2af8b 1011static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
979d63d5
DB
1012 int insn_idx, int prev_insn_idx,
1013 bool speculative)
17a52670 1014{
638f5b90 1015 struct bpf_verifier_state *cur = env->cur_state;
58e2af8b 1016 struct bpf_verifier_stack_elem *elem;
638f5b90 1017 int err;
17a52670 1018
638f5b90 1019 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
17a52670
AS
1020 if (!elem)
1021 goto err;
1022
17a52670
AS
1023 elem->insn_idx = insn_idx;
1024 elem->prev_insn_idx = prev_insn_idx;
1025 elem->next = env->head;
6f8a57cc 1026 elem->log_pos = env->log.len_used;
17a52670
AS
1027 env->head = elem;
1028 env->stack_size++;
1969db47
AS
1029 err = copy_verifier_state(&elem->st, cur);
1030 if (err)
1031 goto err;
979d63d5 1032 elem->st.speculative |= speculative;
b285fcb7
AS
1033 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1034 verbose(env, "The sequence of %d jumps is too complex.\n",
1035 env->stack_size);
17a52670
AS
1036 goto err;
1037 }
2589726d
AS
1038 if (elem->st.parent) {
1039 ++elem->st.parent->branches;
1040 /* WARN_ON(branches > 2) technically makes sense here,
1041 * but
1042 * 1. speculative states will bump 'branches' for non-branch
1043 * instructions
1044 * 2. is_state_visited() heuristics may decide not to create
1045 * a new state for a sequence of branches and all such current
1046 * and cloned states will be pointing to a single parent state
1047 * which might have large 'branches' count.
1048 */
1049 }
17a52670
AS
1050 return &elem->st;
1051err:
5896351e
AS
1052 free_verifier_state(env->cur_state, true);
1053 env->cur_state = NULL;
17a52670 1054 /* pop all elements and return */
6f8a57cc 1055 while (!pop_stack(env, NULL, NULL, false));
17a52670
AS
1056 return NULL;
1057}
1058
1059#define CALLER_SAVED_REGS 6
1060static const int caller_saved[CALLER_SAVED_REGS] = {
1061 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1062};
1063
f54c7898
DB
1064static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1065 struct bpf_reg_state *reg);
f1174f77 1066
e688c3db
AS
1067/* This helper doesn't clear reg->id */
1068static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
b03c9f9f 1069{
b03c9f9f
EC
1070 reg->var_off = tnum_const(imm);
1071 reg->smin_value = (s64)imm;
1072 reg->smax_value = (s64)imm;
1073 reg->umin_value = imm;
1074 reg->umax_value = imm;
3f50f132
JF
1075
1076 reg->s32_min_value = (s32)imm;
1077 reg->s32_max_value = (s32)imm;
1078 reg->u32_min_value = (u32)imm;
1079 reg->u32_max_value = (u32)imm;
1080}
1081
e688c3db
AS
1082/* Mark the unknown part of a register (variable offset or scalar value) as
1083 * known to have the value @imm.
1084 */
1085static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1086{
1087 /* Clear id, off, and union(map_ptr, range) */
1088 memset(((u8 *)reg) + sizeof(reg->type), 0,
1089 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1090 ___mark_reg_known(reg, imm);
1091}
1092
3f50f132
JF
1093static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1094{
1095 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1096 reg->s32_min_value = (s32)imm;
1097 reg->s32_max_value = (s32)imm;
1098 reg->u32_min_value = (u32)imm;
1099 reg->u32_max_value = (u32)imm;
b03c9f9f
EC
1100}
1101
f1174f77
EC
1102/* Mark the 'variable offset' part of a register as zero. This should be
1103 * used only on registers holding a pointer type.
1104 */
1105static void __mark_reg_known_zero(struct bpf_reg_state *reg)
a9789ef9 1106{
b03c9f9f 1107 __mark_reg_known(reg, 0);
f1174f77 1108}
a9789ef9 1109
cc2b14d5
AS
1110static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1111{
1112 __mark_reg_known(reg, 0);
cc2b14d5
AS
1113 reg->type = SCALAR_VALUE;
1114}
1115
61bd5218
JK
1116static void mark_reg_known_zero(struct bpf_verifier_env *env,
1117 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1118{
1119 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1120 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
f1174f77
EC
1121 /* Something bad happened, let's kill all regs */
1122 for (regno = 0; regno < MAX_BPF_REG; regno++)
f54c7898 1123 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1124 return;
1125 }
1126 __mark_reg_known_zero(regs + regno);
1127}
1128
4ddb7416
DB
1129static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1130{
1131 switch (reg->type) {
1132 case PTR_TO_MAP_VALUE_OR_NULL: {
1133 const struct bpf_map *map = reg->map_ptr;
1134
1135 if (map->inner_map_meta) {
1136 reg->type = CONST_PTR_TO_MAP;
1137 reg->map_ptr = map->inner_map_meta;
1138 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1139 reg->type = PTR_TO_XDP_SOCK;
1140 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1141 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1142 reg->type = PTR_TO_SOCKET;
1143 } else {
1144 reg->type = PTR_TO_MAP_VALUE;
1145 }
1146 break;
1147 }
1148 case PTR_TO_SOCKET_OR_NULL:
1149 reg->type = PTR_TO_SOCKET;
1150 break;
1151 case PTR_TO_SOCK_COMMON_OR_NULL:
1152 reg->type = PTR_TO_SOCK_COMMON;
1153 break;
1154 case PTR_TO_TCP_SOCK_OR_NULL:
1155 reg->type = PTR_TO_TCP_SOCK;
1156 break;
1157 case PTR_TO_BTF_ID_OR_NULL:
1158 reg->type = PTR_TO_BTF_ID;
1159 break;
1160 case PTR_TO_MEM_OR_NULL:
1161 reg->type = PTR_TO_MEM;
1162 break;
1163 case PTR_TO_RDONLY_BUF_OR_NULL:
1164 reg->type = PTR_TO_RDONLY_BUF;
1165 break;
1166 case PTR_TO_RDWR_BUF_OR_NULL:
1167 reg->type = PTR_TO_RDWR_BUF;
1168 break;
1169 default:
33ccec5f 1170 WARN_ONCE(1, "unknown nullable register type");
4ddb7416
DB
1171 }
1172}
1173
de8f3a83
DB
1174static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1175{
1176 return type_is_pkt_pointer(reg->type);
1177}
1178
1179static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1180{
1181 return reg_is_pkt_pointer(reg) ||
1182 reg->type == PTR_TO_PACKET_END;
1183}
1184
1185/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1186static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1187 enum bpf_reg_type which)
1188{
1189 /* The register can already have a range from prior markings.
1190 * This is fine as long as it hasn't been advanced from its
1191 * origin.
1192 */
1193 return reg->type == which &&
1194 reg->id == 0 &&
1195 reg->off == 0 &&
1196 tnum_equals_const(reg->var_off, 0);
1197}
1198
3f50f132
JF
1199/* Reset the min/max bounds of a register */
1200static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1201{
1202 reg->smin_value = S64_MIN;
1203 reg->smax_value = S64_MAX;
1204 reg->umin_value = 0;
1205 reg->umax_value = U64_MAX;
1206
1207 reg->s32_min_value = S32_MIN;
1208 reg->s32_max_value = S32_MAX;
1209 reg->u32_min_value = 0;
1210 reg->u32_max_value = U32_MAX;
1211}
1212
1213static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1214{
1215 reg->smin_value = S64_MIN;
1216 reg->smax_value = S64_MAX;
1217 reg->umin_value = 0;
1218 reg->umax_value = U64_MAX;
1219}
1220
1221static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1222{
1223 reg->s32_min_value = S32_MIN;
1224 reg->s32_max_value = S32_MAX;
1225 reg->u32_min_value = 0;
1226 reg->u32_max_value = U32_MAX;
1227}
1228
1229static void __update_reg32_bounds(struct bpf_reg_state *reg)
1230{
1231 struct tnum var32_off = tnum_subreg(reg->var_off);
1232
1233 /* min signed is max(sign bit) | min(other bits) */
1234 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1235 var32_off.value | (var32_off.mask & S32_MIN));
1236 /* max signed is min(sign bit) | max(other bits) */
1237 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1238 var32_off.value | (var32_off.mask & S32_MAX));
1239 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1240 reg->u32_max_value = min(reg->u32_max_value,
1241 (u32)(var32_off.value | var32_off.mask));
1242}
1243
1244static void __update_reg64_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1245{
1246 /* min signed is max(sign bit) | min(other bits) */
1247 reg->smin_value = max_t(s64, reg->smin_value,
1248 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1249 /* max signed is min(sign bit) | max(other bits) */
1250 reg->smax_value = min_t(s64, reg->smax_value,
1251 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1252 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1253 reg->umax_value = min(reg->umax_value,
1254 reg->var_off.value | reg->var_off.mask);
1255}
1256
3f50f132
JF
1257static void __update_reg_bounds(struct bpf_reg_state *reg)
1258{
1259 __update_reg32_bounds(reg);
1260 __update_reg64_bounds(reg);
1261}
1262
b03c9f9f 1263/* Uses signed min/max values to inform unsigned, and vice-versa */
3f50f132
JF
1264static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1265{
1266 /* Learn sign from signed bounds.
1267 * If we cannot cross the sign boundary, then signed and unsigned bounds
1268 * are the same, so combine. This works even in the negative case, e.g.
1269 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1270 */
1271 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1272 reg->s32_min_value = reg->u32_min_value =
1273 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1274 reg->s32_max_value = reg->u32_max_value =
1275 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1276 return;
1277 }
1278 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1279 * boundary, so we must be careful.
1280 */
1281 if ((s32)reg->u32_max_value >= 0) {
1282 /* Positive. We can't learn anything from the smin, but smax
1283 * is positive, hence safe.
1284 */
1285 reg->s32_min_value = reg->u32_min_value;
1286 reg->s32_max_value = reg->u32_max_value =
1287 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1288 } else if ((s32)reg->u32_min_value < 0) {
1289 /* Negative. We can't learn anything from the smax, but smin
1290 * is negative, hence safe.
1291 */
1292 reg->s32_min_value = reg->u32_min_value =
1293 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1294 reg->s32_max_value = reg->u32_max_value;
1295 }
1296}
1297
1298static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
b03c9f9f
EC
1299{
1300 /* Learn sign from signed bounds.
1301 * If we cannot cross the sign boundary, then signed and unsigned bounds
1302 * are the same, so combine. This works even in the negative case, e.g.
1303 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1304 */
1305 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1306 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1307 reg->umin_value);
1308 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1309 reg->umax_value);
1310 return;
1311 }
1312 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1313 * boundary, so we must be careful.
1314 */
1315 if ((s64)reg->umax_value >= 0) {
1316 /* Positive. We can't learn anything from the smin, but smax
1317 * is positive, hence safe.
1318 */
1319 reg->smin_value = reg->umin_value;
1320 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1321 reg->umax_value);
1322 } else if ((s64)reg->umin_value < 0) {
1323 /* Negative. We can't learn anything from the smax, but smin
1324 * is negative, hence safe.
1325 */
1326 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1327 reg->umin_value);
1328 reg->smax_value = reg->umax_value;
1329 }
1330}
1331
3f50f132
JF
1332static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1333{
1334 __reg32_deduce_bounds(reg);
1335 __reg64_deduce_bounds(reg);
1336}
1337
b03c9f9f
EC
1338/* Attempts to improve var_off based on unsigned min/max information */
1339static void __reg_bound_offset(struct bpf_reg_state *reg)
1340{
3f50f132
JF
1341 struct tnum var64_off = tnum_intersect(reg->var_off,
1342 tnum_range(reg->umin_value,
1343 reg->umax_value));
1344 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1345 tnum_range(reg->u32_min_value,
1346 reg->u32_max_value));
1347
1348 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
b03c9f9f
EC
1349}
1350
3f50f132 1351static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
b03c9f9f 1352{
3f50f132
JF
1353 reg->umin_value = reg->u32_min_value;
1354 reg->umax_value = reg->u32_max_value;
1355 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1356 * but must be positive otherwise set to worse case bounds
1357 * and refine later from tnum.
1358 */
3a71dc36 1359 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
3f50f132
JF
1360 reg->smax_value = reg->s32_max_value;
1361 else
1362 reg->smax_value = U32_MAX;
3a71dc36
JF
1363 if (reg->s32_min_value >= 0)
1364 reg->smin_value = reg->s32_min_value;
1365 else
1366 reg->smin_value = 0;
3f50f132
JF
1367}
1368
1369static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1370{
1371 /* special case when 64-bit register has upper 32-bit register
1372 * zeroed. Typically happens after zext or <<32, >>32 sequence
1373 * allowing us to use 32-bit bounds directly,
1374 */
1375 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1376 __reg_assign_32_into_64(reg);
1377 } else {
1378 /* Otherwise the best we can do is push lower 32bit known and
1379 * unknown bits into register (var_off set from jmp logic)
1380 * then learn as much as possible from the 64-bit tnum
1381 * known and unknown bits. The previous smin/smax bounds are
1382 * invalid here because of jmp32 compare so mark them unknown
1383 * so they do not impact tnum bounds calculation.
1384 */
1385 __mark_reg64_unbounded(reg);
1386 __update_reg_bounds(reg);
1387 }
1388
1389 /* Intersecting with the old var_off might have improved our bounds
1390 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1391 * then new var_off is (0; 0x7f...fc) which improves our umax.
1392 */
1393 __reg_deduce_bounds(reg);
1394 __reg_bound_offset(reg);
1395 __update_reg_bounds(reg);
1396}
1397
1398static bool __reg64_bound_s32(s64 a)
1399{
b0270958 1400 return a > S32_MIN && a < S32_MAX;
3f50f132
JF
1401}
1402
1403static bool __reg64_bound_u32(u64 a)
1404{
10bf4e83 1405 return a > U32_MIN && a < U32_MAX;
3f50f132
JF
1406}
1407
1408static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1409{
1410 __mark_reg32_unbounded(reg);
1411
b0270958 1412 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
3f50f132 1413 reg->s32_min_value = (s32)reg->smin_value;
3f50f132 1414 reg->s32_max_value = (s32)reg->smax_value;
b0270958 1415 }
10bf4e83 1416 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
3f50f132 1417 reg->u32_min_value = (u32)reg->umin_value;
3f50f132 1418 reg->u32_max_value = (u32)reg->umax_value;
10bf4e83 1419 }
3f50f132
JF
1420
1421 /* Intersecting with the old var_off might have improved our bounds
1422 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1423 * then new var_off is (0; 0x7f...fc) which improves our umax.
1424 */
1425 __reg_deduce_bounds(reg);
1426 __reg_bound_offset(reg);
1427 __update_reg_bounds(reg);
b03c9f9f
EC
1428}
1429
f1174f77 1430/* Mark a register as having a completely unknown (scalar) value. */
f54c7898
DB
1431static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1432 struct bpf_reg_state *reg)
f1174f77 1433{
a9c676bc
AS
1434 /*
1435 * Clear type, id, off, and union(map_ptr, range) and
1436 * padding between 'type' and union
1437 */
1438 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
f1174f77 1439 reg->type = SCALAR_VALUE;
f1174f77 1440 reg->var_off = tnum_unknown;
f4d7e40a 1441 reg->frameno = 0;
2c78ee89 1442 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
b03c9f9f 1443 __mark_reg_unbounded(reg);
f1174f77
EC
1444}
1445
61bd5218
JK
1446static void mark_reg_unknown(struct bpf_verifier_env *env,
1447 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1448{
1449 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1450 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
19ceb417
AS
1451 /* Something bad happened, let's kill all regs except FP */
1452 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1453 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1454 return;
1455 }
f54c7898 1456 __mark_reg_unknown(env, regs + regno);
f1174f77
EC
1457}
1458
f54c7898
DB
1459static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1460 struct bpf_reg_state *reg)
f1174f77 1461{
f54c7898 1462 __mark_reg_unknown(env, reg);
f1174f77
EC
1463 reg->type = NOT_INIT;
1464}
1465
61bd5218
JK
1466static void mark_reg_not_init(struct bpf_verifier_env *env,
1467 struct bpf_reg_state *regs, u32 regno)
f1174f77
EC
1468{
1469 if (WARN_ON(regno >= MAX_BPF_REG)) {
61bd5218 1470 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
19ceb417
AS
1471 /* Something bad happened, let's kill all regs except FP */
1472 for (regno = 0; regno < BPF_REG_FP; regno++)
f54c7898 1473 __mark_reg_not_init(env, regs + regno);
f1174f77
EC
1474 return;
1475 }
f54c7898 1476 __mark_reg_not_init(env, regs + regno);
a9789ef9
DB
1477}
1478
41c48f3a
AI
1479static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1480 struct bpf_reg_state *regs, u32 regno,
22dc4a0f
AN
1481 enum bpf_reg_type reg_type,
1482 struct btf *btf, u32 btf_id)
41c48f3a
AI
1483{
1484 if (reg_type == SCALAR_VALUE) {
1485 mark_reg_unknown(env, regs, regno);
1486 return;
1487 }
1488 mark_reg_known_zero(env, regs, regno);
1489 regs[regno].type = PTR_TO_BTF_ID;
22dc4a0f 1490 regs[regno].btf = btf;
41c48f3a
AI
1491 regs[regno].btf_id = btf_id;
1492}
1493
5327ed3d 1494#define DEF_NOT_SUBREG (0)
61bd5218 1495static void init_reg_state(struct bpf_verifier_env *env,
f4d7e40a 1496 struct bpf_func_state *state)
17a52670 1497{
f4d7e40a 1498 struct bpf_reg_state *regs = state->regs;
17a52670
AS
1499 int i;
1500
dc503a8a 1501 for (i = 0; i < MAX_BPF_REG; i++) {
61bd5218 1502 mark_reg_not_init(env, regs, i);
dc503a8a 1503 regs[i].live = REG_LIVE_NONE;
679c782d 1504 regs[i].parent = NULL;
5327ed3d 1505 regs[i].subreg_def = DEF_NOT_SUBREG;
dc503a8a 1506 }
17a52670
AS
1507
1508 /* frame pointer */
f1174f77 1509 regs[BPF_REG_FP].type = PTR_TO_STACK;
61bd5218 1510 mark_reg_known_zero(env, regs, BPF_REG_FP);
f4d7e40a 1511 regs[BPF_REG_FP].frameno = state->frameno;
6760bf2d
DB
1512}
1513
f4d7e40a
AS
1514#define BPF_MAIN_FUNC (-1)
1515static void init_func_state(struct bpf_verifier_env *env,
1516 struct bpf_func_state *state,
1517 int callsite, int frameno, int subprogno)
1518{
1519 state->callsite = callsite;
1520 state->frameno = frameno;
1521 state->subprogno = subprogno;
1522 init_reg_state(env, state);
1523}
1524
17a52670
AS
1525enum reg_arg_type {
1526 SRC_OP, /* register is used as source operand */
1527 DST_OP, /* register is used as destination operand */
1528 DST_OP_NO_MARK /* same as above, check only, don't mark */
1529};
1530
cc8b0b92
AS
1531static int cmp_subprogs(const void *a, const void *b)
1532{
9c8105bd
JW
1533 return ((struct bpf_subprog_info *)a)->start -
1534 ((struct bpf_subprog_info *)b)->start;
cc8b0b92
AS
1535}
1536
1537static int find_subprog(struct bpf_verifier_env *env, int off)
1538{
9c8105bd 1539 struct bpf_subprog_info *p;
cc8b0b92 1540
9c8105bd
JW
1541 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1542 sizeof(env->subprog_info[0]), cmp_subprogs);
cc8b0b92
AS
1543 if (!p)
1544 return -ENOENT;
9c8105bd 1545 return p - env->subprog_info;
cc8b0b92
AS
1546
1547}
1548
1549static int add_subprog(struct bpf_verifier_env *env, int off)
1550{
1551 int insn_cnt = env->prog->len;
1552 int ret;
1553
1554 if (off >= insn_cnt || off < 0) {
1555 verbose(env, "call to invalid destination\n");
1556 return -EINVAL;
1557 }
1558 ret = find_subprog(env, off);
1559 if (ret >= 0)
282a0f46 1560 return ret;
4cb3d99c 1561 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
cc8b0b92
AS
1562 verbose(env, "too many subprograms\n");
1563 return -E2BIG;
1564 }
e6ac2450 1565 /* determine subprog starts. The end is one before the next starts */
9c8105bd
JW
1566 env->subprog_info[env->subprog_cnt++].start = off;
1567 sort(env->subprog_info, env->subprog_cnt,
1568 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
282a0f46 1569 return env->subprog_cnt - 1;
cc8b0b92
AS
1570}
1571
e6ac2450
MKL
1572struct bpf_kfunc_desc {
1573 struct btf_func_model func_model;
1574 u32 func_id;
1575 s32 imm;
1576};
1577
1578#define MAX_KFUNC_DESCS 256
1579struct bpf_kfunc_desc_tab {
1580 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1581 u32 nr_descs;
1582};
1583
1584static int kfunc_desc_cmp_by_id(const void *a, const void *b)
1585{
1586 const struct bpf_kfunc_desc *d0 = a;
1587 const struct bpf_kfunc_desc *d1 = b;
1588
1589 /* func_id is not greater than BTF_MAX_TYPE */
1590 return d0->func_id - d1->func_id;
1591}
1592
1593static const struct bpf_kfunc_desc *
1594find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1595{
1596 struct bpf_kfunc_desc desc = {
1597 .func_id = func_id,
1598 };
1599 struct bpf_kfunc_desc_tab *tab;
1600
1601 tab = prog->aux->kfunc_tab;
1602 return bsearch(&desc, tab->descs, tab->nr_descs,
1603 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1604}
1605
1606static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1607{
1608 const struct btf_type *func, *func_proto;
1609 struct bpf_kfunc_desc_tab *tab;
1610 struct bpf_prog_aux *prog_aux;
1611 struct bpf_kfunc_desc *desc;
1612 const char *func_name;
1613 unsigned long addr;
1614 int err;
1615
1616 prog_aux = env->prog->aux;
1617 tab = prog_aux->kfunc_tab;
1618 if (!tab) {
1619 if (!btf_vmlinux) {
1620 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1621 return -ENOTSUPP;
1622 }
1623
1624 if (!env->prog->jit_requested) {
1625 verbose(env, "JIT is required for calling kernel function\n");
1626 return -ENOTSUPP;
1627 }
1628
1629 if (!bpf_jit_supports_kfunc_call()) {
1630 verbose(env, "JIT does not support calling kernel function\n");
1631 return -ENOTSUPP;
1632 }
1633
1634 if (!env->prog->gpl_compatible) {
1635 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1636 return -EINVAL;
1637 }
1638
1639 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1640 if (!tab)
1641 return -ENOMEM;
1642 prog_aux->kfunc_tab = tab;
1643 }
1644
1645 if (find_kfunc_desc(env->prog, func_id))
1646 return 0;
1647
1648 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1649 verbose(env, "too many different kernel function calls\n");
1650 return -E2BIG;
1651 }
1652
1653 func = btf_type_by_id(btf_vmlinux, func_id);
1654 if (!func || !btf_type_is_func(func)) {
1655 verbose(env, "kernel btf_id %u is not a function\n",
1656 func_id);
1657 return -EINVAL;
1658 }
1659 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1660 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1661 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1662 func_id);
1663 return -EINVAL;
1664 }
1665
1666 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1667 addr = kallsyms_lookup_name(func_name);
1668 if (!addr) {
1669 verbose(env, "cannot find address for kernel function %s\n",
1670 func_name);
1671 return -EINVAL;
1672 }
1673
1674 desc = &tab->descs[tab->nr_descs++];
1675 desc->func_id = func_id;
1676 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1677 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1678 func_proto, func_name,
1679 &desc->func_model);
1680 if (!err)
1681 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1682 kfunc_desc_cmp_by_id, NULL);
1683 return err;
1684}
1685
1686static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1687{
1688 const struct bpf_kfunc_desc *d0 = a;
1689 const struct bpf_kfunc_desc *d1 = b;
1690
1691 if (d0->imm > d1->imm)
1692 return 1;
1693 else if (d0->imm < d1->imm)
1694 return -1;
1695 return 0;
1696}
1697
1698static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1699{
1700 struct bpf_kfunc_desc_tab *tab;
1701
1702 tab = prog->aux->kfunc_tab;
1703 if (!tab)
1704 return;
1705
1706 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1707 kfunc_desc_cmp_by_imm, NULL);
1708}
1709
1710bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1711{
1712 return !!prog->aux->kfunc_tab;
1713}
1714
1715const struct btf_func_model *
1716bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1717 const struct bpf_insn *insn)
1718{
1719 const struct bpf_kfunc_desc desc = {
1720 .imm = insn->imm,
1721 };
1722 const struct bpf_kfunc_desc *res;
1723 struct bpf_kfunc_desc_tab *tab;
1724
1725 tab = prog->aux->kfunc_tab;
1726 res = bsearch(&desc, tab->descs, tab->nr_descs,
1727 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1728
1729 return res ? &res->func_model : NULL;
1730}
1731
1732static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
cc8b0b92 1733{
9c8105bd 1734 struct bpf_subprog_info *subprog = env->subprog_info;
cc8b0b92 1735 struct bpf_insn *insn = env->prog->insnsi;
e6ac2450 1736 int i, ret, insn_cnt = env->prog->len;
cc8b0b92 1737
f910cefa
JW
1738 /* Add entry function. */
1739 ret = add_subprog(env, 0);
e6ac2450 1740 if (ret)
f910cefa
JW
1741 return ret;
1742
e6ac2450
MKL
1743 for (i = 0; i < insn_cnt; i++, insn++) {
1744 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1745 !bpf_pseudo_kfunc_call(insn))
cc8b0b92 1746 continue;
e6ac2450 1747
2c78ee89 1748 if (!env->bpf_capable) {
e6ac2450 1749 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
cc8b0b92
AS
1750 return -EPERM;
1751 }
e6ac2450
MKL
1752
1753 if (bpf_pseudo_func(insn)) {
1754 ret = add_subprog(env, i + insn->imm + 1);
1755 if (ret >= 0)
1756 /* remember subprog */
1757 insn[1].imm = ret;
1758 } else if (bpf_pseudo_call(insn)) {
1759 ret = add_subprog(env, i + insn->imm + 1);
1760 } else {
1761 ret = add_kfunc_call(env, insn->imm);
1762 }
1763
cc8b0b92
AS
1764 if (ret < 0)
1765 return ret;
1766 }
1767
4cb3d99c
JW
1768 /* Add a fake 'exit' subprog which could simplify subprog iteration
1769 * logic. 'subprog_cnt' should not be increased.
1770 */
1771 subprog[env->subprog_cnt].start = insn_cnt;
1772
06ee7115 1773 if (env->log.level & BPF_LOG_LEVEL2)
cc8b0b92 1774 for (i = 0; i < env->subprog_cnt; i++)
9c8105bd 1775 verbose(env, "func#%d @%d\n", i, subprog[i].start);
cc8b0b92 1776
e6ac2450
MKL
1777 return 0;
1778}
1779
1780static int check_subprogs(struct bpf_verifier_env *env)
1781{
1782 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1783 struct bpf_subprog_info *subprog = env->subprog_info;
1784 struct bpf_insn *insn = env->prog->insnsi;
1785 int insn_cnt = env->prog->len;
1786
cc8b0b92 1787 /* now check that all jumps are within the same subprog */
4cb3d99c
JW
1788 subprog_start = subprog[cur_subprog].start;
1789 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1790 for (i = 0; i < insn_cnt; i++) {
1791 u8 code = insn[i].code;
1792
7f6e4312
MF
1793 if (code == (BPF_JMP | BPF_CALL) &&
1794 insn[i].imm == BPF_FUNC_tail_call &&
1795 insn[i].src_reg != BPF_PSEUDO_CALL)
1796 subprog[cur_subprog].has_tail_call = true;
09b28d76
AS
1797 if (BPF_CLASS(code) == BPF_LD &&
1798 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1799 subprog[cur_subprog].has_ld_abs = true;
092ed096 1800 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
cc8b0b92
AS
1801 goto next;
1802 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1803 goto next;
1804 off = i + insn[i].off + 1;
1805 if (off < subprog_start || off >= subprog_end) {
1806 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1807 return -EINVAL;
1808 }
1809next:
1810 if (i == subprog_end - 1) {
1811 /* to avoid fall-through from one subprog into another
1812 * the last insn of the subprog should be either exit
1813 * or unconditional jump back
1814 */
1815 if (code != (BPF_JMP | BPF_EXIT) &&
1816 code != (BPF_JMP | BPF_JA)) {
1817 verbose(env, "last insn is not an exit or jmp\n");
1818 return -EINVAL;
1819 }
1820 subprog_start = subprog_end;
4cb3d99c
JW
1821 cur_subprog++;
1822 if (cur_subprog < env->subprog_cnt)
9c8105bd 1823 subprog_end = subprog[cur_subprog + 1].start;
cc8b0b92
AS
1824 }
1825 }
1826 return 0;
1827}
1828
679c782d
EC
1829/* Parentage chain of this register (or stack slot) should take care of all
1830 * issues like callee-saved registers, stack slot allocation time, etc.
1831 */
f4d7e40a 1832static int mark_reg_read(struct bpf_verifier_env *env,
679c782d 1833 const struct bpf_reg_state *state,
5327ed3d 1834 struct bpf_reg_state *parent, u8 flag)
f4d7e40a
AS
1835{
1836 bool writes = parent == state->parent; /* Observe write marks */
06ee7115 1837 int cnt = 0;
dc503a8a
EC
1838
1839 while (parent) {
1840 /* if read wasn't screened by an earlier write ... */
679c782d 1841 if (writes && state->live & REG_LIVE_WRITTEN)
dc503a8a 1842 break;
9242b5f5
AS
1843 if (parent->live & REG_LIVE_DONE) {
1844 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1845 reg_type_str[parent->type],
1846 parent->var_off.value, parent->off);
1847 return -EFAULT;
1848 }
5327ed3d
JW
1849 /* The first condition is more likely to be true than the
1850 * second, checked it first.
1851 */
1852 if ((parent->live & REG_LIVE_READ) == flag ||
1853 parent->live & REG_LIVE_READ64)
25af32da
AS
1854 /* The parentage chain never changes and
1855 * this parent was already marked as LIVE_READ.
1856 * There is no need to keep walking the chain again and
1857 * keep re-marking all parents as LIVE_READ.
1858 * This case happens when the same register is read
1859 * multiple times without writes into it in-between.
5327ed3d
JW
1860 * Also, if parent has the stronger REG_LIVE_READ64 set,
1861 * then no need to set the weak REG_LIVE_READ32.
25af32da
AS
1862 */
1863 break;
dc503a8a 1864 /* ... then we depend on parent's value */
5327ed3d
JW
1865 parent->live |= flag;
1866 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1867 if (flag == REG_LIVE_READ64)
1868 parent->live &= ~REG_LIVE_READ32;
dc503a8a
EC
1869 state = parent;
1870 parent = state->parent;
f4d7e40a 1871 writes = true;
06ee7115 1872 cnt++;
dc503a8a 1873 }
06ee7115
AS
1874
1875 if (env->longest_mark_read_walk < cnt)
1876 env->longest_mark_read_walk = cnt;
f4d7e40a 1877 return 0;
dc503a8a
EC
1878}
1879
5327ed3d
JW
1880/* This function is supposed to be used by the following 32-bit optimization
1881 * code only. It returns TRUE if the source or destination register operates
1882 * on 64-bit, otherwise return FALSE.
1883 */
1884static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1885 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1886{
1887 u8 code, class, op;
1888
1889 code = insn->code;
1890 class = BPF_CLASS(code);
1891 op = BPF_OP(code);
1892 if (class == BPF_JMP) {
1893 /* BPF_EXIT for "main" will reach here. Return TRUE
1894 * conservatively.
1895 */
1896 if (op == BPF_EXIT)
1897 return true;
1898 if (op == BPF_CALL) {
1899 /* BPF to BPF call will reach here because of marking
1900 * caller saved clobber with DST_OP_NO_MARK for which we
1901 * don't care the register def because they are anyway
1902 * marked as NOT_INIT already.
1903 */
1904 if (insn->src_reg == BPF_PSEUDO_CALL)
1905 return false;
1906 /* Helper call will reach here because of arg type
1907 * check, conservatively return TRUE.
1908 */
1909 if (t == SRC_OP)
1910 return true;
1911
1912 return false;
1913 }
1914 }
1915
1916 if (class == BPF_ALU64 || class == BPF_JMP ||
1917 /* BPF_END always use BPF_ALU class. */
1918 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1919 return true;
1920
1921 if (class == BPF_ALU || class == BPF_JMP32)
1922 return false;
1923
1924 if (class == BPF_LDX) {
1925 if (t != SRC_OP)
1926 return BPF_SIZE(code) == BPF_DW;
1927 /* LDX source must be ptr. */
1928 return true;
1929 }
1930
1931 if (class == BPF_STX) {
83a28819
IL
1932 /* BPF_STX (including atomic variants) has multiple source
1933 * operands, one of which is a ptr. Check whether the caller is
1934 * asking about it.
1935 */
1936 if (t == SRC_OP && reg->type != SCALAR_VALUE)
5327ed3d
JW
1937 return true;
1938 return BPF_SIZE(code) == BPF_DW;
1939 }
1940
1941 if (class == BPF_LD) {
1942 u8 mode = BPF_MODE(code);
1943
1944 /* LD_IMM64 */
1945 if (mode == BPF_IMM)
1946 return true;
1947
1948 /* Both LD_IND and LD_ABS return 32-bit data. */
1949 if (t != SRC_OP)
1950 return false;
1951
1952 /* Implicit ctx ptr. */
1953 if (regno == BPF_REG_6)
1954 return true;
1955
1956 /* Explicit source could be any width. */
1957 return true;
1958 }
1959
1960 if (class == BPF_ST)
1961 /* The only source register for BPF_ST is a ptr. */
1962 return true;
1963
1964 /* Conservatively return true at default. */
1965 return true;
1966}
1967
83a28819
IL
1968/* Return the regno defined by the insn, or -1. */
1969static int insn_def_regno(const struct bpf_insn *insn)
b325fbca 1970{
83a28819
IL
1971 switch (BPF_CLASS(insn->code)) {
1972 case BPF_JMP:
1973 case BPF_JMP32:
1974 case BPF_ST:
1975 return -1;
1976 case BPF_STX:
1977 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1978 (insn->imm & BPF_FETCH)) {
1979 if (insn->imm == BPF_CMPXCHG)
1980 return BPF_REG_0;
1981 else
1982 return insn->src_reg;
1983 } else {
1984 return -1;
1985 }
1986 default:
1987 return insn->dst_reg;
1988 }
b325fbca
JW
1989}
1990
1991/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1992static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1993{
83a28819
IL
1994 int dst_reg = insn_def_regno(insn);
1995
1996 if (dst_reg == -1)
b325fbca
JW
1997 return false;
1998
83a28819 1999 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
b325fbca
JW
2000}
2001
5327ed3d
JW
2002static void mark_insn_zext(struct bpf_verifier_env *env,
2003 struct bpf_reg_state *reg)
2004{
2005 s32 def_idx = reg->subreg_def;
2006
2007 if (def_idx == DEF_NOT_SUBREG)
2008 return;
2009
2010 env->insn_aux_data[def_idx - 1].zext_dst = true;
2011 /* The dst will be zero extended, so won't be sub-register anymore. */
2012 reg->subreg_def = DEF_NOT_SUBREG;
2013}
2014
dc503a8a 2015static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
17a52670
AS
2016 enum reg_arg_type t)
2017{
f4d7e40a
AS
2018 struct bpf_verifier_state *vstate = env->cur_state;
2019 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5327ed3d 2020 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
c342dc10 2021 struct bpf_reg_state *reg, *regs = state->regs;
5327ed3d 2022 bool rw64;
dc503a8a 2023
17a52670 2024 if (regno >= MAX_BPF_REG) {
61bd5218 2025 verbose(env, "R%d is invalid\n", regno);
17a52670
AS
2026 return -EINVAL;
2027 }
2028
c342dc10 2029 reg = &regs[regno];
5327ed3d 2030 rw64 = is_reg64(env, insn, regno, reg, t);
17a52670
AS
2031 if (t == SRC_OP) {
2032 /* check whether register used as source operand can be read */
c342dc10 2033 if (reg->type == NOT_INIT) {
61bd5218 2034 verbose(env, "R%d !read_ok\n", regno);
17a52670
AS
2035 return -EACCES;
2036 }
679c782d 2037 /* We don't need to worry about FP liveness because it's read-only */
c342dc10
JW
2038 if (regno == BPF_REG_FP)
2039 return 0;
2040
5327ed3d
JW
2041 if (rw64)
2042 mark_insn_zext(env, reg);
2043
2044 return mark_reg_read(env, reg, reg->parent,
2045 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
17a52670
AS
2046 } else {
2047 /* check whether register used as dest operand can be written to */
2048 if (regno == BPF_REG_FP) {
61bd5218 2049 verbose(env, "frame pointer is read only\n");
17a52670
AS
2050 return -EACCES;
2051 }
c342dc10 2052 reg->live |= REG_LIVE_WRITTEN;
5327ed3d 2053 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
17a52670 2054 if (t == DST_OP)
61bd5218 2055 mark_reg_unknown(env, regs, regno);
17a52670
AS
2056 }
2057 return 0;
2058}
2059
b5dc0163
AS
2060/* for any branch, call, exit record the history of jmps in the given state */
2061static int push_jmp_history(struct bpf_verifier_env *env,
2062 struct bpf_verifier_state *cur)
2063{
2064 u32 cnt = cur->jmp_history_cnt;
2065 struct bpf_idx_pair *p;
2066
2067 cnt++;
2068 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2069 if (!p)
2070 return -ENOMEM;
2071 p[cnt - 1].idx = env->insn_idx;
2072 p[cnt - 1].prev_idx = env->prev_insn_idx;
2073 cur->jmp_history = p;
2074 cur->jmp_history_cnt = cnt;
2075 return 0;
2076}
2077
2078/* Backtrack one insn at a time. If idx is not at the top of recorded
2079 * history then previous instruction came from straight line execution.
2080 */
2081static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2082 u32 *history)
2083{
2084 u32 cnt = *history;
2085
2086 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2087 i = st->jmp_history[cnt - 1].prev_idx;
2088 (*history)--;
2089 } else {
2090 i--;
2091 }
2092 return i;
2093}
2094
e6ac2450
MKL
2095static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2096{
2097 const struct btf_type *func;
2098
2099 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2100 return NULL;
2101
2102 func = btf_type_by_id(btf_vmlinux, insn->imm);
2103 return btf_name_by_offset(btf_vmlinux, func->name_off);
2104}
2105
b5dc0163
AS
2106/* For given verifier state backtrack_insn() is called from the last insn to
2107 * the first insn. Its purpose is to compute a bitmask of registers and
2108 * stack slots that needs precision in the parent verifier state.
2109 */
2110static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2111 u32 *reg_mask, u64 *stack_mask)
2112{
2113 const struct bpf_insn_cbs cbs = {
e6ac2450 2114 .cb_call = disasm_kfunc_name,
b5dc0163
AS
2115 .cb_print = verbose,
2116 .private_data = env,
2117 };
2118 struct bpf_insn *insn = env->prog->insnsi + idx;
2119 u8 class = BPF_CLASS(insn->code);
2120 u8 opcode = BPF_OP(insn->code);
2121 u8 mode = BPF_MODE(insn->code);
2122 u32 dreg = 1u << insn->dst_reg;
2123 u32 sreg = 1u << insn->src_reg;
2124 u32 spi;
2125
2126 if (insn->code == 0)
2127 return 0;
2128 if (env->log.level & BPF_LOG_LEVEL) {
2129 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2130 verbose(env, "%d: ", idx);
2131 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2132 }
2133
2134 if (class == BPF_ALU || class == BPF_ALU64) {
2135 if (!(*reg_mask & dreg))
2136 return 0;
2137 if (opcode == BPF_MOV) {
2138 if (BPF_SRC(insn->code) == BPF_X) {
2139 /* dreg = sreg
2140 * dreg needs precision after this insn
2141 * sreg needs precision before this insn
2142 */
2143 *reg_mask &= ~dreg;
2144 *reg_mask |= sreg;
2145 } else {
2146 /* dreg = K
2147 * dreg needs precision after this insn.
2148 * Corresponding register is already marked
2149 * as precise=true in this verifier state.
2150 * No further markings in parent are necessary
2151 */
2152 *reg_mask &= ~dreg;
2153 }
2154 } else {
2155 if (BPF_SRC(insn->code) == BPF_X) {
2156 /* dreg += sreg
2157 * both dreg and sreg need precision
2158 * before this insn
2159 */
2160 *reg_mask |= sreg;
2161 } /* else dreg += K
2162 * dreg still needs precision before this insn
2163 */
2164 }
2165 } else if (class == BPF_LDX) {
2166 if (!(*reg_mask & dreg))
2167 return 0;
2168 *reg_mask &= ~dreg;
2169
2170 /* scalars can only be spilled into stack w/o losing precision.
2171 * Load from any other memory can be zero extended.
2172 * The desire to keep that precision is already indicated
2173 * by 'precise' mark in corresponding register of this state.
2174 * No further tracking necessary.
2175 */
2176 if (insn->src_reg != BPF_REG_FP)
2177 return 0;
2178 if (BPF_SIZE(insn->code) != BPF_DW)
2179 return 0;
2180
2181 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2182 * that [fp - off] slot contains scalar that needs to be
2183 * tracked with precision
2184 */
2185 spi = (-insn->off - 1) / BPF_REG_SIZE;
2186 if (spi >= 64) {
2187 verbose(env, "BUG spi %d\n", spi);
2188 WARN_ONCE(1, "verifier backtracking bug");
2189 return -EFAULT;
2190 }
2191 *stack_mask |= 1ull << spi;
b3b50f05 2192 } else if (class == BPF_STX || class == BPF_ST) {
b5dc0163 2193 if (*reg_mask & dreg)
b3b50f05 2194 /* stx & st shouldn't be using _scalar_ dst_reg
b5dc0163
AS
2195 * to access memory. It means backtracking
2196 * encountered a case of pointer subtraction.
2197 */
2198 return -ENOTSUPP;
2199 /* scalars can only be spilled into stack */
2200 if (insn->dst_reg != BPF_REG_FP)
2201 return 0;
2202 if (BPF_SIZE(insn->code) != BPF_DW)
2203 return 0;
2204 spi = (-insn->off - 1) / BPF_REG_SIZE;
2205 if (spi >= 64) {
2206 verbose(env, "BUG spi %d\n", spi);
2207 WARN_ONCE(1, "verifier backtracking bug");
2208 return -EFAULT;
2209 }
2210 if (!(*stack_mask & (1ull << spi)))
2211 return 0;
2212 *stack_mask &= ~(1ull << spi);
b3b50f05
AN
2213 if (class == BPF_STX)
2214 *reg_mask |= sreg;
b5dc0163
AS
2215 } else if (class == BPF_JMP || class == BPF_JMP32) {
2216 if (opcode == BPF_CALL) {
2217 if (insn->src_reg == BPF_PSEUDO_CALL)
2218 return -ENOTSUPP;
2219 /* regular helper call sets R0 */
2220 *reg_mask &= ~1;
2221 if (*reg_mask & 0x3f) {
2222 /* if backtracing was looking for registers R1-R5
2223 * they should have been found already.
2224 */
2225 verbose(env, "BUG regs %x\n", *reg_mask);
2226 WARN_ONCE(1, "verifier backtracking bug");
2227 return -EFAULT;
2228 }
2229 } else if (opcode == BPF_EXIT) {
2230 return -ENOTSUPP;
2231 }
2232 } else if (class == BPF_LD) {
2233 if (!(*reg_mask & dreg))
2234 return 0;
2235 *reg_mask &= ~dreg;
2236 /* It's ld_imm64 or ld_abs or ld_ind.
2237 * For ld_imm64 no further tracking of precision
2238 * into parent is necessary
2239 */
2240 if (mode == BPF_IND || mode == BPF_ABS)
2241 /* to be analyzed */
2242 return -ENOTSUPP;
b5dc0163
AS
2243 }
2244 return 0;
2245}
2246
2247/* the scalar precision tracking algorithm:
2248 * . at the start all registers have precise=false.
2249 * . scalar ranges are tracked as normal through alu and jmp insns.
2250 * . once precise value of the scalar register is used in:
2251 * . ptr + scalar alu
2252 * . if (scalar cond K|scalar)
2253 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2254 * backtrack through the verifier states and mark all registers and
2255 * stack slots with spilled constants that these scalar regisers
2256 * should be precise.
2257 * . during state pruning two registers (or spilled stack slots)
2258 * are equivalent if both are not precise.
2259 *
2260 * Note the verifier cannot simply walk register parentage chain,
2261 * since many different registers and stack slots could have been
2262 * used to compute single precise scalar.
2263 *
2264 * The approach of starting with precise=true for all registers and then
2265 * backtrack to mark a register as not precise when the verifier detects
2266 * that program doesn't care about specific value (e.g., when helper
2267 * takes register as ARG_ANYTHING parameter) is not safe.
2268 *
2269 * It's ok to walk single parentage chain of the verifier states.
2270 * It's possible that this backtracking will go all the way till 1st insn.
2271 * All other branches will be explored for needing precision later.
2272 *
2273 * The backtracking needs to deal with cases like:
2274 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
2275 * r9 -= r8
2276 * r5 = r9
2277 * if r5 > 0x79f goto pc+7
2278 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2279 * r5 += 1
2280 * ...
2281 * call bpf_perf_event_output#25
2282 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2283 *
2284 * and this case:
2285 * r6 = 1
2286 * call foo // uses callee's r6 inside to compute r0
2287 * r0 += r6
2288 * if r0 == 0 goto
2289 *
2290 * to track above reg_mask/stack_mask needs to be independent for each frame.
2291 *
2292 * Also if parent's curframe > frame where backtracking started,
2293 * the verifier need to mark registers in both frames, otherwise callees
2294 * may incorrectly prune callers. This is similar to
2295 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2296 *
2297 * For now backtracking falls back into conservative marking.
2298 */
2299static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2300 struct bpf_verifier_state *st)
2301{
2302 struct bpf_func_state *func;
2303 struct bpf_reg_state *reg;
2304 int i, j;
2305
2306 /* big hammer: mark all scalars precise in this path.
2307 * pop_stack may still get !precise scalars.
2308 */
2309 for (; st; st = st->parent)
2310 for (i = 0; i <= st->curframe; i++) {
2311 func = st->frame[i];
2312 for (j = 0; j < BPF_REG_FP; j++) {
2313 reg = &func->regs[j];
2314 if (reg->type != SCALAR_VALUE)
2315 continue;
2316 reg->precise = true;
2317 }
2318 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2319 if (func->stack[j].slot_type[0] != STACK_SPILL)
2320 continue;
2321 reg = &func->stack[j].spilled_ptr;
2322 if (reg->type != SCALAR_VALUE)
2323 continue;
2324 reg->precise = true;
2325 }
2326 }
2327}
2328
a3ce685d
AS
2329static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2330 int spi)
b5dc0163
AS
2331{
2332 struct bpf_verifier_state *st = env->cur_state;
2333 int first_idx = st->first_insn_idx;
2334 int last_idx = env->insn_idx;
2335 struct bpf_func_state *func;
2336 struct bpf_reg_state *reg;
a3ce685d
AS
2337 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2338 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
b5dc0163 2339 bool skip_first = true;
a3ce685d 2340 bool new_marks = false;
b5dc0163
AS
2341 int i, err;
2342
2c78ee89 2343 if (!env->bpf_capable)
b5dc0163
AS
2344 return 0;
2345
2346 func = st->frame[st->curframe];
a3ce685d
AS
2347 if (regno >= 0) {
2348 reg = &func->regs[regno];
2349 if (reg->type != SCALAR_VALUE) {
2350 WARN_ONCE(1, "backtracing misuse");
2351 return -EFAULT;
2352 }
2353 if (!reg->precise)
2354 new_marks = true;
2355 else
2356 reg_mask = 0;
2357 reg->precise = true;
b5dc0163 2358 }
b5dc0163 2359
a3ce685d
AS
2360 while (spi >= 0) {
2361 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2362 stack_mask = 0;
2363 break;
2364 }
2365 reg = &func->stack[spi].spilled_ptr;
2366 if (reg->type != SCALAR_VALUE) {
2367 stack_mask = 0;
2368 break;
2369 }
2370 if (!reg->precise)
2371 new_marks = true;
2372 else
2373 stack_mask = 0;
2374 reg->precise = true;
2375 break;
2376 }
2377
2378 if (!new_marks)
2379 return 0;
2380 if (!reg_mask && !stack_mask)
2381 return 0;
b5dc0163
AS
2382 for (;;) {
2383 DECLARE_BITMAP(mask, 64);
b5dc0163
AS
2384 u32 history = st->jmp_history_cnt;
2385
2386 if (env->log.level & BPF_LOG_LEVEL)
2387 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2388 for (i = last_idx;;) {
2389 if (skip_first) {
2390 err = 0;
2391 skip_first = false;
2392 } else {
2393 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2394 }
2395 if (err == -ENOTSUPP) {
2396 mark_all_scalars_precise(env, st);
2397 return 0;
2398 } else if (err) {
2399 return err;
2400 }
2401 if (!reg_mask && !stack_mask)
2402 /* Found assignment(s) into tracked register in this state.
2403 * Since this state is already marked, just return.
2404 * Nothing to be tracked further in the parent state.
2405 */
2406 return 0;
2407 if (i == first_idx)
2408 break;
2409 i = get_prev_insn_idx(st, i, &history);
2410 if (i >= env->prog->len) {
2411 /* This can happen if backtracking reached insn 0
2412 * and there are still reg_mask or stack_mask
2413 * to backtrack.
2414 * It means the backtracking missed the spot where
2415 * particular register was initialized with a constant.
2416 */
2417 verbose(env, "BUG backtracking idx %d\n", i);
2418 WARN_ONCE(1, "verifier backtracking bug");
2419 return -EFAULT;
2420 }
2421 }
2422 st = st->parent;
2423 if (!st)
2424 break;
2425
a3ce685d 2426 new_marks = false;
b5dc0163
AS
2427 func = st->frame[st->curframe];
2428 bitmap_from_u64(mask, reg_mask);
2429 for_each_set_bit(i, mask, 32) {
2430 reg = &func->regs[i];
a3ce685d
AS
2431 if (reg->type != SCALAR_VALUE) {
2432 reg_mask &= ~(1u << i);
b5dc0163 2433 continue;
a3ce685d 2434 }
b5dc0163
AS
2435 if (!reg->precise)
2436 new_marks = true;
2437 reg->precise = true;
2438 }
2439
2440 bitmap_from_u64(mask, stack_mask);
2441 for_each_set_bit(i, mask, 64) {
2442 if (i >= func->allocated_stack / BPF_REG_SIZE) {
2339cd6c
AS
2443 /* the sequence of instructions:
2444 * 2: (bf) r3 = r10
2445 * 3: (7b) *(u64 *)(r3 -8) = r0
2446 * 4: (79) r4 = *(u64 *)(r10 -8)
2447 * doesn't contain jmps. It's backtracked
2448 * as a single block.
2449 * During backtracking insn 3 is not recognized as
2450 * stack access, so at the end of backtracking
2451 * stack slot fp-8 is still marked in stack_mask.
2452 * However the parent state may not have accessed
2453 * fp-8 and it's "unallocated" stack space.
2454 * In such case fallback to conservative.
b5dc0163 2455 */
2339cd6c
AS
2456 mark_all_scalars_precise(env, st);
2457 return 0;
b5dc0163
AS
2458 }
2459
a3ce685d
AS
2460 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2461 stack_mask &= ~(1ull << i);
b5dc0163 2462 continue;
a3ce685d 2463 }
b5dc0163 2464 reg = &func->stack[i].spilled_ptr;
a3ce685d
AS
2465 if (reg->type != SCALAR_VALUE) {
2466 stack_mask &= ~(1ull << i);
b5dc0163 2467 continue;
a3ce685d 2468 }
b5dc0163
AS
2469 if (!reg->precise)
2470 new_marks = true;
2471 reg->precise = true;
2472 }
2473 if (env->log.level & BPF_LOG_LEVEL) {
2474 print_verifier_state(env, func);
2475 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2476 new_marks ? "didn't have" : "already had",
2477 reg_mask, stack_mask);
2478 }
2479
a3ce685d
AS
2480 if (!reg_mask && !stack_mask)
2481 break;
b5dc0163
AS
2482 if (!new_marks)
2483 break;
2484
2485 last_idx = st->last_insn_idx;
2486 first_idx = st->first_insn_idx;
2487 }
2488 return 0;
2489}
2490
a3ce685d
AS
2491static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2492{
2493 return __mark_chain_precision(env, regno, -1);
2494}
2495
2496static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2497{
2498 return __mark_chain_precision(env, -1, spi);
2499}
b5dc0163 2500
1be7f75d
AS
2501static bool is_spillable_regtype(enum bpf_reg_type type)
2502{
2503 switch (type) {
2504 case PTR_TO_MAP_VALUE:
2505 case PTR_TO_MAP_VALUE_OR_NULL:
2506 case PTR_TO_STACK:
2507 case PTR_TO_CTX:
969bf05e 2508 case PTR_TO_PACKET:
de8f3a83 2509 case PTR_TO_PACKET_META:
969bf05e 2510 case PTR_TO_PACKET_END:
d58e468b 2511 case PTR_TO_FLOW_KEYS:
1be7f75d 2512 case CONST_PTR_TO_MAP:
c64b7983
JS
2513 case PTR_TO_SOCKET:
2514 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
2515 case PTR_TO_SOCK_COMMON:
2516 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
2517 case PTR_TO_TCP_SOCK:
2518 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 2519 case PTR_TO_XDP_SOCK:
65726b5b 2520 case PTR_TO_BTF_ID:
b121b341 2521 case PTR_TO_BTF_ID_OR_NULL:
afbf21dc
YS
2522 case PTR_TO_RDONLY_BUF:
2523 case PTR_TO_RDONLY_BUF_OR_NULL:
2524 case PTR_TO_RDWR_BUF:
2525 case PTR_TO_RDWR_BUF_OR_NULL:
eaa6bcb7 2526 case PTR_TO_PERCPU_BTF_ID:
744ea4e3
GR
2527 case PTR_TO_MEM:
2528 case PTR_TO_MEM_OR_NULL:
69c087ba
YS
2529 case PTR_TO_FUNC:
2530 case PTR_TO_MAP_KEY:
1be7f75d
AS
2531 return true;
2532 default:
2533 return false;
2534 }
2535}
2536
cc2b14d5
AS
2537/* Does this register contain a constant zero? */
2538static bool register_is_null(struct bpf_reg_state *reg)
2539{
2540 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2541}
2542
f7cf25b2
AS
2543static bool register_is_const(struct bpf_reg_state *reg)
2544{
2545 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2546}
2547
5689d49b
YS
2548static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2549{
2550 return tnum_is_unknown(reg->var_off) &&
2551 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2552 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2553 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2554 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2555}
2556
2557static bool register_is_bounded(struct bpf_reg_state *reg)
2558{
2559 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2560}
2561
6e7e63cb
JH
2562static bool __is_pointer_value(bool allow_ptr_leaks,
2563 const struct bpf_reg_state *reg)
2564{
2565 if (allow_ptr_leaks)
2566 return false;
2567
2568 return reg->type != SCALAR_VALUE;
2569}
2570
f7cf25b2
AS
2571static void save_register_state(struct bpf_func_state *state,
2572 int spi, struct bpf_reg_state *reg)
2573{
2574 int i;
2575
2576 state->stack[spi].spilled_ptr = *reg;
2577 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2578
2579 for (i = 0; i < BPF_REG_SIZE; i++)
2580 state->stack[spi].slot_type[i] = STACK_SPILL;
2581}
2582
01f810ac 2583/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
17a52670
AS
2584 * stack boundary and alignment are checked in check_mem_access()
2585 */
01f810ac
AM
2586static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2587 /* stack frame we're writing to */
2588 struct bpf_func_state *state,
2589 int off, int size, int value_regno,
2590 int insn_idx)
17a52670 2591{
f4d7e40a 2592 struct bpf_func_state *cur; /* state of the current function */
638f5b90 2593 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
b5dc0163 2594 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
f7cf25b2 2595 struct bpf_reg_state *reg = NULL;
638f5b90 2596
c69431aa 2597 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
638f5b90
AS
2598 if (err)
2599 return err;
9c399760
AS
2600 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2601 * so it's aligned access and [off, off + size) are within stack limits
2602 */
638f5b90
AS
2603 if (!env->allow_ptr_leaks &&
2604 state->stack[spi].slot_type[0] == STACK_SPILL &&
2605 size != BPF_REG_SIZE) {
2606 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2607 return -EACCES;
2608 }
17a52670 2609
f4d7e40a 2610 cur = env->cur_state->frame[env->cur_state->curframe];
f7cf25b2
AS
2611 if (value_regno >= 0)
2612 reg = &cur->regs[value_regno];
17a52670 2613
5689d49b 2614 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
2c78ee89 2615 !register_is_null(reg) && env->bpf_capable) {
b5dc0163
AS
2616 if (dst_reg != BPF_REG_FP) {
2617 /* The backtracking logic can only recognize explicit
2618 * stack slot address like [fp - 8]. Other spill of
8fb33b60 2619 * scalar via different register has to be conservative.
b5dc0163
AS
2620 * Backtrack from here and mark all registers as precise
2621 * that contributed into 'reg' being a constant.
2622 */
2623 err = mark_chain_precision(env, value_regno);
2624 if (err)
2625 return err;
2626 }
f7cf25b2
AS
2627 save_register_state(state, spi, reg);
2628 } else if (reg && is_spillable_regtype(reg->type)) {
17a52670 2629 /* register containing pointer is being spilled into stack */
9c399760 2630 if (size != BPF_REG_SIZE) {
f7cf25b2 2631 verbose_linfo(env, insn_idx, "; ");
61bd5218 2632 verbose(env, "invalid size of register spill\n");
17a52670
AS
2633 return -EACCES;
2634 }
2635
f7cf25b2 2636 if (state != cur && reg->type == PTR_TO_STACK) {
f4d7e40a
AS
2637 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2638 return -EINVAL;
2639 }
2640
2c78ee89 2641 if (!env->bypass_spec_v4) {
f7cf25b2 2642 bool sanitize = false;
17a52670 2643
f7cf25b2
AS
2644 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2645 register_is_const(&state->stack[spi].spilled_ptr))
2646 sanitize = true;
2647 for (i = 0; i < BPF_REG_SIZE; i++)
2648 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2649 sanitize = true;
2650 break;
2651 }
2652 if (sanitize) {
af86ca4e
AS
2653 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2654 int soff = (-spi - 1) * BPF_REG_SIZE;
2655
2656 /* detected reuse of integer stack slot with a pointer
2657 * which means either llvm is reusing stack slot or
2658 * an attacker is trying to exploit CVE-2018-3639
2659 * (speculative store bypass)
2660 * Have to sanitize that slot with preemptive
2661 * store of zero.
2662 */
2663 if (*poff && *poff != soff) {
2664 /* disallow programs where single insn stores
2665 * into two different stack slots, since verifier
2666 * cannot sanitize them
2667 */
2668 verbose(env,
2669 "insn %d cannot access two stack slots fp%d and fp%d",
2670 insn_idx, *poff, soff);
2671 return -EINVAL;
2672 }
2673 *poff = soff;
2674 }
af86ca4e 2675 }
f7cf25b2 2676 save_register_state(state, spi, reg);
9c399760 2677 } else {
cc2b14d5
AS
2678 u8 type = STACK_MISC;
2679
679c782d
EC
2680 /* regular write of data into stack destroys any spilled ptr */
2681 state->stack[spi].spilled_ptr.type = NOT_INIT;
0bae2d4d
JW
2682 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2683 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2684 for (i = 0; i < BPF_REG_SIZE; i++)
2685 state->stack[spi].slot_type[i] = STACK_MISC;
9c399760 2686
cc2b14d5
AS
2687 /* only mark the slot as written if all 8 bytes were written
2688 * otherwise read propagation may incorrectly stop too soon
2689 * when stack slots are partially written.
2690 * This heuristic means that read propagation will be
2691 * conservative, since it will add reg_live_read marks
2692 * to stack slots all the way to first state when programs
2693 * writes+reads less than 8 bytes
2694 */
2695 if (size == BPF_REG_SIZE)
2696 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2697
2698 /* when we zero initialize stack slots mark them as such */
b5dc0163
AS
2699 if (reg && register_is_null(reg)) {
2700 /* backtracking doesn't work for STACK_ZERO yet. */
2701 err = mark_chain_precision(env, value_regno);
2702 if (err)
2703 return err;
cc2b14d5 2704 type = STACK_ZERO;
b5dc0163 2705 }
cc2b14d5 2706
0bae2d4d 2707 /* Mark slots affected by this stack write. */
9c399760 2708 for (i = 0; i < size; i++)
638f5b90 2709 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
cc2b14d5 2710 type;
17a52670
AS
2711 }
2712 return 0;
2713}
2714
01f810ac
AM
2715/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2716 * known to contain a variable offset.
2717 * This function checks whether the write is permitted and conservatively
2718 * tracks the effects of the write, considering that each stack slot in the
2719 * dynamic range is potentially written to.
2720 *
2721 * 'off' includes 'regno->off'.
2722 * 'value_regno' can be -1, meaning that an unknown value is being written to
2723 * the stack.
2724 *
2725 * Spilled pointers in range are not marked as written because we don't know
2726 * what's going to be actually written. This means that read propagation for
2727 * future reads cannot be terminated by this write.
2728 *
2729 * For privileged programs, uninitialized stack slots are considered
2730 * initialized by this write (even though we don't know exactly what offsets
2731 * are going to be written to). The idea is that we don't want the verifier to
2732 * reject future reads that access slots written to through variable offsets.
2733 */
2734static int check_stack_write_var_off(struct bpf_verifier_env *env,
2735 /* func where register points to */
2736 struct bpf_func_state *state,
2737 int ptr_regno, int off, int size,
2738 int value_regno, int insn_idx)
2739{
2740 struct bpf_func_state *cur; /* state of the current function */
2741 int min_off, max_off;
2742 int i, err;
2743 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2744 bool writing_zero = false;
2745 /* set if the fact that we're writing a zero is used to let any
2746 * stack slots remain STACK_ZERO
2747 */
2748 bool zero_used = false;
2749
2750 cur = env->cur_state->frame[env->cur_state->curframe];
2751 ptr_reg = &cur->regs[ptr_regno];
2752 min_off = ptr_reg->smin_value + off;
2753 max_off = ptr_reg->smax_value + off + size;
2754 if (value_regno >= 0)
2755 value_reg = &cur->regs[value_regno];
2756 if (value_reg && register_is_null(value_reg))
2757 writing_zero = true;
2758
c69431aa 2759 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
01f810ac
AM
2760 if (err)
2761 return err;
2762
2763
2764 /* Variable offset writes destroy any spilled pointers in range. */
2765 for (i = min_off; i < max_off; i++) {
2766 u8 new_type, *stype;
2767 int slot, spi;
2768
2769 slot = -i - 1;
2770 spi = slot / BPF_REG_SIZE;
2771 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2772
2773 if (!env->allow_ptr_leaks
2774 && *stype != NOT_INIT
2775 && *stype != SCALAR_VALUE) {
2776 /* Reject the write if there's are spilled pointers in
2777 * range. If we didn't reject here, the ptr status
2778 * would be erased below (even though not all slots are
2779 * actually overwritten), possibly opening the door to
2780 * leaks.
2781 */
2782 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2783 insn_idx, i);
2784 return -EINVAL;
2785 }
2786
2787 /* Erase all spilled pointers. */
2788 state->stack[spi].spilled_ptr.type = NOT_INIT;
2789
2790 /* Update the slot type. */
2791 new_type = STACK_MISC;
2792 if (writing_zero && *stype == STACK_ZERO) {
2793 new_type = STACK_ZERO;
2794 zero_used = true;
2795 }
2796 /* If the slot is STACK_INVALID, we check whether it's OK to
2797 * pretend that it will be initialized by this write. The slot
2798 * might not actually be written to, and so if we mark it as
2799 * initialized future reads might leak uninitialized memory.
2800 * For privileged programs, we will accept such reads to slots
2801 * that may or may not be written because, if we're reject
2802 * them, the error would be too confusing.
2803 */
2804 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2805 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2806 insn_idx, i);
2807 return -EINVAL;
2808 }
2809 *stype = new_type;
2810 }
2811 if (zero_used) {
2812 /* backtracking doesn't work for STACK_ZERO yet. */
2813 err = mark_chain_precision(env, value_regno);
2814 if (err)
2815 return err;
2816 }
2817 return 0;
2818}
2819
2820/* When register 'dst_regno' is assigned some values from stack[min_off,
2821 * max_off), we set the register's type according to the types of the
2822 * respective stack slots. If all the stack values are known to be zeros, then
2823 * so is the destination reg. Otherwise, the register is considered to be
2824 * SCALAR. This function does not deal with register filling; the caller must
2825 * ensure that all spilled registers in the stack range have been marked as
2826 * read.
2827 */
2828static void mark_reg_stack_read(struct bpf_verifier_env *env,
2829 /* func where src register points to */
2830 struct bpf_func_state *ptr_state,
2831 int min_off, int max_off, int dst_regno)
2832{
2833 struct bpf_verifier_state *vstate = env->cur_state;
2834 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2835 int i, slot, spi;
2836 u8 *stype;
2837 int zeros = 0;
2838
2839 for (i = min_off; i < max_off; i++) {
2840 slot = -i - 1;
2841 spi = slot / BPF_REG_SIZE;
2842 stype = ptr_state->stack[spi].slot_type;
2843 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2844 break;
2845 zeros++;
2846 }
2847 if (zeros == max_off - min_off) {
2848 /* any access_size read into register is zero extended,
2849 * so the whole register == const_zero
2850 */
2851 __mark_reg_const_zero(&state->regs[dst_regno]);
2852 /* backtracking doesn't support STACK_ZERO yet,
2853 * so mark it precise here, so that later
2854 * backtracking can stop here.
2855 * Backtracking may not need this if this register
2856 * doesn't participate in pointer adjustment.
2857 * Forward propagation of precise flag is not
2858 * necessary either. This mark is only to stop
2859 * backtracking. Any register that contributed
2860 * to const 0 was marked precise before spill.
2861 */
2862 state->regs[dst_regno].precise = true;
2863 } else {
2864 /* have read misc data from the stack */
2865 mark_reg_unknown(env, state->regs, dst_regno);
2866 }
2867 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2868}
2869
2870/* Read the stack at 'off' and put the results into the register indicated by
2871 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2872 * spilled reg.
2873 *
2874 * 'dst_regno' can be -1, meaning that the read value is not going to a
2875 * register.
2876 *
2877 * The access is assumed to be within the current stack bounds.
2878 */
2879static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2880 /* func where src register points to */
2881 struct bpf_func_state *reg_state,
2882 int off, int size, int dst_regno)
17a52670 2883{
f4d7e40a
AS
2884 struct bpf_verifier_state *vstate = env->cur_state;
2885 struct bpf_func_state *state = vstate->frame[vstate->curframe];
638f5b90 2886 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
f7cf25b2 2887 struct bpf_reg_state *reg;
638f5b90 2888 u8 *stype;
17a52670 2889
f4d7e40a 2890 stype = reg_state->stack[spi].slot_type;
f7cf25b2 2891 reg = &reg_state->stack[spi].spilled_ptr;
17a52670 2892
638f5b90 2893 if (stype[0] == STACK_SPILL) {
9c399760 2894 if (size != BPF_REG_SIZE) {
f7cf25b2
AS
2895 if (reg->type != SCALAR_VALUE) {
2896 verbose_linfo(env, env->insn_idx, "; ");
2897 verbose(env, "invalid size of register fill\n");
2898 return -EACCES;
2899 }
01f810ac
AM
2900 if (dst_regno >= 0) {
2901 mark_reg_unknown(env, state->regs, dst_regno);
2902 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
f7cf25b2
AS
2903 }
2904 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2905 return 0;
17a52670 2906 }
9c399760 2907 for (i = 1; i < BPF_REG_SIZE; i++) {
638f5b90 2908 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
61bd5218 2909 verbose(env, "corrupted spill memory\n");
17a52670
AS
2910 return -EACCES;
2911 }
2912 }
2913
01f810ac 2914 if (dst_regno >= 0) {
17a52670 2915 /* restore register state from stack */
01f810ac 2916 state->regs[dst_regno] = *reg;
2f18f62e
AS
2917 /* mark reg as written since spilled pointer state likely
2918 * has its liveness marks cleared by is_state_visited()
2919 * which resets stack/reg liveness for state transitions
2920 */
01f810ac 2921 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
6e7e63cb 2922 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
01f810ac 2923 /* If dst_regno==-1, the caller is asking us whether
6e7e63cb
JH
2924 * it is acceptable to use this value as a SCALAR_VALUE
2925 * (e.g. for XADD).
2926 * We must not allow unprivileged callers to do that
2927 * with spilled pointers.
2928 */
2929 verbose(env, "leaking pointer from stack off %d\n",
2930 off);
2931 return -EACCES;
dc503a8a 2932 }
f7cf25b2 2933 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
17a52670 2934 } else {
01f810ac 2935 u8 type;
cc2b14d5 2936
17a52670 2937 for (i = 0; i < size; i++) {
01f810ac
AM
2938 type = stype[(slot - i) % BPF_REG_SIZE];
2939 if (type == STACK_MISC)
cc2b14d5 2940 continue;
01f810ac 2941 if (type == STACK_ZERO)
cc2b14d5 2942 continue;
cc2b14d5
AS
2943 verbose(env, "invalid read from stack off %d+%d size %d\n",
2944 off, i, size);
2945 return -EACCES;
2946 }
f7cf25b2 2947 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
01f810ac
AM
2948 if (dst_regno >= 0)
2949 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
17a52670 2950 }
f7cf25b2 2951 return 0;
17a52670
AS
2952}
2953
01f810ac
AM
2954enum stack_access_src {
2955 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2956 ACCESS_HELPER = 2, /* the access is performed by a helper */
2957};
2958
2959static int check_stack_range_initialized(struct bpf_verifier_env *env,
2960 int regno, int off, int access_size,
2961 bool zero_size_allowed,
2962 enum stack_access_src type,
2963 struct bpf_call_arg_meta *meta);
2964
2965static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
2966{
2967 return cur_regs(env) + regno;
2968}
2969
2970/* Read the stack at 'ptr_regno + off' and put the result into the register
2971 * 'dst_regno'.
2972 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2973 * but not its variable offset.
2974 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2975 *
2976 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2977 * filling registers (i.e. reads of spilled register cannot be detected when
2978 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2979 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2980 * offset; for a fixed offset check_stack_read_fixed_off should be used
2981 * instead.
2982 */
2983static int check_stack_read_var_off(struct bpf_verifier_env *env,
2984 int ptr_regno, int off, int size, int dst_regno)
e4298d25 2985{
01f810ac
AM
2986 /* The state of the source register. */
2987 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2988 struct bpf_func_state *ptr_state = func(env, reg);
2989 int err;
2990 int min_off, max_off;
2991
2992 /* Note that we pass a NULL meta, so raw access will not be permitted.
e4298d25 2993 */
01f810ac
AM
2994 err = check_stack_range_initialized(env, ptr_regno, off, size,
2995 false, ACCESS_DIRECT, NULL);
2996 if (err)
2997 return err;
2998
2999 min_off = reg->smin_value + off;
3000 max_off = reg->smax_value + off;
3001 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3002 return 0;
3003}
3004
3005/* check_stack_read dispatches to check_stack_read_fixed_off or
3006 * check_stack_read_var_off.
3007 *
3008 * The caller must ensure that the offset falls within the allocated stack
3009 * bounds.
3010 *
3011 * 'dst_regno' is a register which will receive the value from the stack. It
3012 * can be -1, meaning that the read value is not going to a register.
3013 */
3014static int check_stack_read(struct bpf_verifier_env *env,
3015 int ptr_regno, int off, int size,
3016 int dst_regno)
3017{
3018 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3019 struct bpf_func_state *state = func(env, reg);
3020 int err;
3021 /* Some accesses are only permitted with a static offset. */
3022 bool var_off = !tnum_is_const(reg->var_off);
3023
3024 /* The offset is required to be static when reads don't go to a
3025 * register, in order to not leak pointers (see
3026 * check_stack_read_fixed_off).
3027 */
3028 if (dst_regno < 0 && var_off) {
e4298d25
DB
3029 char tn_buf[48];
3030
3031 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac 3032 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
e4298d25
DB
3033 tn_buf, off, size);
3034 return -EACCES;
3035 }
01f810ac
AM
3036 /* Variable offset is prohibited for unprivileged mode for simplicity
3037 * since it requires corresponding support in Spectre masking for stack
3038 * ALU. See also retrieve_ptr_limit().
3039 */
3040 if (!env->bypass_spec_v1 && var_off) {
3041 char tn_buf[48];
e4298d25 3042
01f810ac
AM
3043 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3044 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3045 ptr_regno, tn_buf);
e4298d25
DB
3046 return -EACCES;
3047 }
3048
01f810ac
AM
3049 if (!var_off) {
3050 off += reg->var_off.value;
3051 err = check_stack_read_fixed_off(env, state, off, size,
3052 dst_regno);
3053 } else {
3054 /* Variable offset stack reads need more conservative handling
3055 * than fixed offset ones. Note that dst_regno >= 0 on this
3056 * branch.
3057 */
3058 err = check_stack_read_var_off(env, ptr_regno, off, size,
3059 dst_regno);
3060 }
3061 return err;
3062}
3063
3064
3065/* check_stack_write dispatches to check_stack_write_fixed_off or
3066 * check_stack_write_var_off.
3067 *
3068 * 'ptr_regno' is the register used as a pointer into the stack.
3069 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3070 * 'value_regno' is the register whose value we're writing to the stack. It can
3071 * be -1, meaning that we're not writing from a register.
3072 *
3073 * The caller must ensure that the offset falls within the maximum stack size.
3074 */
3075static int check_stack_write(struct bpf_verifier_env *env,
3076 int ptr_regno, int off, int size,
3077 int value_regno, int insn_idx)
3078{
3079 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3080 struct bpf_func_state *state = func(env, reg);
3081 int err;
3082
3083 if (tnum_is_const(reg->var_off)) {
3084 off += reg->var_off.value;
3085 err = check_stack_write_fixed_off(env, state, off, size,
3086 value_regno, insn_idx);
3087 } else {
3088 /* Variable offset stack reads need more conservative handling
3089 * than fixed offset ones.
3090 */
3091 err = check_stack_write_var_off(env, state,
3092 ptr_regno, off, size,
3093 value_regno, insn_idx);
3094 }
3095 return err;
e4298d25
DB
3096}
3097
591fe988
DB
3098static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3099 int off, int size, enum bpf_access_type type)
3100{
3101 struct bpf_reg_state *regs = cur_regs(env);
3102 struct bpf_map *map = regs[regno].map_ptr;
3103 u32 cap = bpf_map_flags_to_cap(map);
3104
3105 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3106 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3107 map->value_size, off, size);
3108 return -EACCES;
3109 }
3110
3111 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3112 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3113 map->value_size, off, size);
3114 return -EACCES;
3115 }
3116
3117 return 0;
3118}
3119
457f4436
AN
3120/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3121static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3122 int off, int size, u32 mem_size,
3123 bool zero_size_allowed)
17a52670 3124{
457f4436
AN
3125 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3126 struct bpf_reg_state *reg;
3127
3128 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3129 return 0;
17a52670 3130
457f4436
AN
3131 reg = &cur_regs(env)[regno];
3132 switch (reg->type) {
69c087ba
YS
3133 case PTR_TO_MAP_KEY:
3134 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3135 mem_size, off, size);
3136 break;
457f4436 3137 case PTR_TO_MAP_VALUE:
61bd5218 3138 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
457f4436
AN
3139 mem_size, off, size);
3140 break;
3141 case PTR_TO_PACKET:
3142 case PTR_TO_PACKET_META:
3143 case PTR_TO_PACKET_END:
3144 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3145 off, size, regno, reg->id, off, mem_size);
3146 break;
3147 case PTR_TO_MEM:
3148 default:
3149 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3150 mem_size, off, size);
17a52670 3151 }
457f4436
AN
3152
3153 return -EACCES;
17a52670
AS
3154}
3155
457f4436
AN
3156/* check read/write into a memory region with possible variable offset */
3157static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3158 int off, int size, u32 mem_size,
3159 bool zero_size_allowed)
dbcfe5f7 3160{
f4d7e40a
AS
3161 struct bpf_verifier_state *vstate = env->cur_state;
3162 struct bpf_func_state *state = vstate->frame[vstate->curframe];
dbcfe5f7
GB
3163 struct bpf_reg_state *reg = &state->regs[regno];
3164 int err;
3165
457f4436 3166 /* We may have adjusted the register pointing to memory region, so we
f1174f77
EC
3167 * need to try adding each of min_value and max_value to off
3168 * to make sure our theoretical access will be safe.
dbcfe5f7 3169 */
06ee7115 3170 if (env->log.level & BPF_LOG_LEVEL)
61bd5218 3171 print_verifier_state(env, state);
b7137c4e 3172
dbcfe5f7
GB
3173 /* The minimum value is only important with signed
3174 * comparisons where we can't assume the floor of a
3175 * value is 0. If we are using signed variables for our
3176 * index'es we need to make sure that whatever we use
3177 * will have a set floor within our range.
3178 */
b7137c4e
DB
3179 if (reg->smin_value < 0 &&
3180 (reg->smin_value == S64_MIN ||
3181 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3182 reg->smin_value + off < 0)) {
61bd5218 3183 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
dbcfe5f7
GB
3184 regno);
3185 return -EACCES;
3186 }
457f4436
AN
3187 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3188 mem_size, zero_size_allowed);
dbcfe5f7 3189 if (err) {
457f4436 3190 verbose(env, "R%d min value is outside of the allowed memory range\n",
61bd5218 3191 regno);
dbcfe5f7
GB
3192 return err;
3193 }
3194
b03c9f9f
EC
3195 /* If we haven't set a max value then we need to bail since we can't be
3196 * sure we won't do bad things.
3197 * If reg->umax_value + off could overflow, treat that as unbounded too.
dbcfe5f7 3198 */
b03c9f9f 3199 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
457f4436 3200 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
dbcfe5f7
GB
3201 regno);
3202 return -EACCES;
3203 }
457f4436
AN
3204 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3205 mem_size, zero_size_allowed);
3206 if (err) {
3207 verbose(env, "R%d max value is outside of the allowed memory range\n",
61bd5218 3208 regno);
457f4436
AN
3209 return err;
3210 }
3211
3212 return 0;
3213}
d83525ca 3214
457f4436
AN
3215/* check read/write into a map element with possible variable offset */
3216static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3217 int off, int size, bool zero_size_allowed)
3218{
3219 struct bpf_verifier_state *vstate = env->cur_state;
3220 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3221 struct bpf_reg_state *reg = &state->regs[regno];
3222 struct bpf_map *map = reg->map_ptr;
3223 int err;
3224
3225 err = check_mem_region_access(env, regno, off, size, map->value_size,
3226 zero_size_allowed);
3227 if (err)
3228 return err;
3229
3230 if (map_value_has_spin_lock(map)) {
3231 u32 lock = map->spin_lock_off;
d83525ca
AS
3232
3233 /* if any part of struct bpf_spin_lock can be touched by
3234 * load/store reject this program.
3235 * To check that [x1, x2) overlaps with [y1, y2)
3236 * it is sufficient to check x1 < y2 && y1 < x2.
3237 */
3238 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3239 lock < reg->umax_value + off + size) {
3240 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3241 return -EACCES;
3242 }
3243 }
f1174f77 3244 return err;
dbcfe5f7
GB
3245}
3246
969bf05e
AS
3247#define MAX_PACKET_OFF 0xffff
3248
7e40781c
UP
3249static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3250{
3aac1ead 3251 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
7e40781c
UP
3252}
3253
58e2af8b 3254static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
3a0af8fd
TG
3255 const struct bpf_call_arg_meta *meta,
3256 enum bpf_access_type t)
4acf6c0b 3257{
7e40781c
UP
3258 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3259
3260 switch (prog_type) {
5d66fa7d 3261 /* Program types only with direct read access go here! */
3a0af8fd
TG
3262 case BPF_PROG_TYPE_LWT_IN:
3263 case BPF_PROG_TYPE_LWT_OUT:
004d4b27 3264 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2dbb9b9e 3265 case BPF_PROG_TYPE_SK_REUSEPORT:
5d66fa7d 3266 case BPF_PROG_TYPE_FLOW_DISSECTOR:
d5563d36 3267 case BPF_PROG_TYPE_CGROUP_SKB:
3a0af8fd
TG
3268 if (t == BPF_WRITE)
3269 return false;
8731745e 3270 fallthrough;
5d66fa7d
DB
3271
3272 /* Program types with direct read + write access go here! */
36bbef52
DB
3273 case BPF_PROG_TYPE_SCHED_CLS:
3274 case BPF_PROG_TYPE_SCHED_ACT:
4acf6c0b 3275 case BPF_PROG_TYPE_XDP:
3a0af8fd 3276 case BPF_PROG_TYPE_LWT_XMIT:
8a31db56 3277 case BPF_PROG_TYPE_SK_SKB:
4f738adb 3278 case BPF_PROG_TYPE_SK_MSG:
36bbef52
DB
3279 if (meta)
3280 return meta->pkt_access;
3281
3282 env->seen_direct_write = true;
4acf6c0b 3283 return true;
0d01da6a
SF
3284
3285 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3286 if (t == BPF_WRITE)
3287 env->seen_direct_write = true;
3288
3289 return true;
3290
4acf6c0b
BB
3291 default:
3292 return false;
3293 }
3294}
3295
f1174f77 3296static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
9fd29c08 3297 int size, bool zero_size_allowed)
f1174f77 3298{
638f5b90 3299 struct bpf_reg_state *regs = cur_regs(env);
f1174f77
EC
3300 struct bpf_reg_state *reg = &regs[regno];
3301 int err;
3302
3303 /* We may have added a variable offset to the packet pointer; but any
3304 * reg->range we have comes after that. We are only checking the fixed
3305 * offset.
3306 */
3307
3308 /* We don't allow negative numbers, because we aren't tracking enough
3309 * detail to prove they're safe.
3310 */
b03c9f9f 3311 if (reg->smin_value < 0) {
61bd5218 3312 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
f1174f77
EC
3313 regno);
3314 return -EACCES;
3315 }
6d94e741
AS
3316
3317 err = reg->range < 0 ? -EINVAL :
3318 __check_mem_access(env, regno, off, size, reg->range,
457f4436 3319 zero_size_allowed);
f1174f77 3320 if (err) {
61bd5218 3321 verbose(env, "R%d offset is outside of the packet\n", regno);
f1174f77
EC
3322 return err;
3323 }
e647815a 3324
457f4436 3325 /* __check_mem_access has made sure "off + size - 1" is within u16.
e647815a
JW
3326 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3327 * otherwise find_good_pkt_pointers would have refused to set range info
457f4436 3328 * that __check_mem_access would have rejected this pkt access.
e647815a
JW
3329 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3330 */
3331 env->prog->aux->max_pkt_offset =
3332 max_t(u32, env->prog->aux->max_pkt_offset,
3333 off + reg->umax_value + size - 1);
3334
f1174f77
EC
3335 return err;
3336}
3337
3338/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
31fd8581 3339static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
9e15db66 3340 enum bpf_access_type t, enum bpf_reg_type *reg_type,
22dc4a0f 3341 struct btf **btf, u32 *btf_id)
17a52670 3342{
f96da094
DB
3343 struct bpf_insn_access_aux info = {
3344 .reg_type = *reg_type,
9e15db66 3345 .log = &env->log,
f96da094 3346 };
31fd8581 3347
4f9218aa 3348 if (env->ops->is_valid_access &&
5e43f899 3349 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
f96da094
DB
3350 /* A non zero info.ctx_field_size indicates that this field is a
3351 * candidate for later verifier transformation to load the whole
3352 * field and then apply a mask when accessed with a narrower
3353 * access than actual ctx access size. A zero info.ctx_field_size
3354 * will only allow for whole field access and rejects any other
3355 * type of narrower access.
31fd8581 3356 */
23994631 3357 *reg_type = info.reg_type;
31fd8581 3358
22dc4a0f
AN
3359 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3360 *btf = info.btf;
9e15db66 3361 *btf_id = info.btf_id;
22dc4a0f 3362 } else {
9e15db66 3363 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
22dc4a0f 3364 }
32bbe007
AS
3365 /* remember the offset of last byte accessed in ctx */
3366 if (env->prog->aux->max_ctx_offset < off + size)
3367 env->prog->aux->max_ctx_offset = off + size;
17a52670 3368 return 0;
32bbe007 3369 }
17a52670 3370
61bd5218 3371 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
17a52670
AS
3372 return -EACCES;
3373}
3374
d58e468b
PP
3375static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3376 int size)
3377{
3378 if (size < 0 || off < 0 ||
3379 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3380 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3381 off, size);
3382 return -EACCES;
3383 }
3384 return 0;
3385}
3386
5f456649
MKL
3387static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3388 u32 regno, int off, int size,
3389 enum bpf_access_type t)
c64b7983
JS
3390{
3391 struct bpf_reg_state *regs = cur_regs(env);
3392 struct bpf_reg_state *reg = &regs[regno];
5f456649 3393 struct bpf_insn_access_aux info = {};
46f8bc92 3394 bool valid;
c64b7983
JS
3395
3396 if (reg->smin_value < 0) {
3397 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3398 regno);
3399 return -EACCES;
3400 }
3401
46f8bc92
MKL
3402 switch (reg->type) {
3403 case PTR_TO_SOCK_COMMON:
3404 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3405 break;
3406 case PTR_TO_SOCKET:
3407 valid = bpf_sock_is_valid_access(off, size, t, &info);
3408 break;
655a51e5
MKL
3409 case PTR_TO_TCP_SOCK:
3410 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3411 break;
fada7fdc
JL
3412 case PTR_TO_XDP_SOCK:
3413 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3414 break;
46f8bc92
MKL
3415 default:
3416 valid = false;
c64b7983
JS
3417 }
3418
5f456649 3419
46f8bc92
MKL
3420 if (valid) {
3421 env->insn_aux_data[insn_idx].ctx_field_size =
3422 info.ctx_field_size;
3423 return 0;
3424 }
3425
3426 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3427 regno, reg_type_str[reg->type], off, size);
3428
3429 return -EACCES;
c64b7983
JS
3430}
3431
4cabc5b1
DB
3432static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3433{
2a159c6f 3434 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
4cabc5b1
DB
3435}
3436
f37a8cb8
DB
3437static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3438{
2a159c6f 3439 const struct bpf_reg_state *reg = reg_state(env, regno);
f37a8cb8 3440
46f8bc92
MKL
3441 return reg->type == PTR_TO_CTX;
3442}
3443
3444static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3445{
3446 const struct bpf_reg_state *reg = reg_state(env, regno);
3447
3448 return type_is_sk_pointer(reg->type);
f37a8cb8
DB
3449}
3450
ca369602
DB
3451static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3452{
2a159c6f 3453 const struct bpf_reg_state *reg = reg_state(env, regno);
ca369602
DB
3454
3455 return type_is_pkt_pointer(reg->type);
3456}
3457
4b5defde
DB
3458static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3459{
3460 const struct bpf_reg_state *reg = reg_state(env, regno);
3461
3462 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3463 return reg->type == PTR_TO_FLOW_KEYS;
3464}
3465
61bd5218
JK
3466static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3467 const struct bpf_reg_state *reg,
d1174416 3468 int off, int size, bool strict)
969bf05e 3469{
f1174f77 3470 struct tnum reg_off;
e07b98d9 3471 int ip_align;
d1174416
DM
3472
3473 /* Byte size accesses are always allowed. */
3474 if (!strict || size == 1)
3475 return 0;
3476
e4eda884
DM
3477 /* For platforms that do not have a Kconfig enabling
3478 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3479 * NET_IP_ALIGN is universally set to '2'. And on platforms
3480 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3481 * to this code only in strict mode where we want to emulate
3482 * the NET_IP_ALIGN==2 checking. Therefore use an
3483 * unconditional IP align value of '2'.
e07b98d9 3484 */
e4eda884 3485 ip_align = 2;
f1174f77
EC
3486
3487 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3488 if (!tnum_is_aligned(reg_off, size)) {
3489 char tn_buf[48];
3490
3491 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218
JK
3492 verbose(env,
3493 "misaligned packet access off %d+%s+%d+%d size %d\n",
f1174f77 3494 ip_align, tn_buf, reg->off, off, size);
969bf05e
AS
3495 return -EACCES;
3496 }
79adffcd 3497
969bf05e
AS
3498 return 0;
3499}
3500
61bd5218
JK
3501static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3502 const struct bpf_reg_state *reg,
f1174f77
EC
3503 const char *pointer_desc,
3504 int off, int size, bool strict)
79adffcd 3505{
f1174f77
EC
3506 struct tnum reg_off;
3507
3508 /* Byte size accesses are always allowed. */
3509 if (!strict || size == 1)
3510 return 0;
3511
3512 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3513 if (!tnum_is_aligned(reg_off, size)) {
3514 char tn_buf[48];
3515
3516 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
61bd5218 3517 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
f1174f77 3518 pointer_desc, tn_buf, reg->off, off, size);
79adffcd
DB
3519 return -EACCES;
3520 }
3521
969bf05e
AS
3522 return 0;
3523}
3524
e07b98d9 3525static int check_ptr_alignment(struct bpf_verifier_env *env,
ca369602
DB
3526 const struct bpf_reg_state *reg, int off,
3527 int size, bool strict_alignment_once)
79adffcd 3528{
ca369602 3529 bool strict = env->strict_alignment || strict_alignment_once;
f1174f77 3530 const char *pointer_desc = "";
d1174416 3531
79adffcd
DB
3532 switch (reg->type) {
3533 case PTR_TO_PACKET:
de8f3a83
DB
3534 case PTR_TO_PACKET_META:
3535 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3536 * right in front, treat it the very same way.
3537 */
61bd5218 3538 return check_pkt_ptr_alignment(env, reg, off, size, strict);
d58e468b
PP
3539 case PTR_TO_FLOW_KEYS:
3540 pointer_desc = "flow keys ";
3541 break;
69c087ba
YS
3542 case PTR_TO_MAP_KEY:
3543 pointer_desc = "key ";
3544 break;
f1174f77
EC
3545 case PTR_TO_MAP_VALUE:
3546 pointer_desc = "value ";
3547 break;
3548 case PTR_TO_CTX:
3549 pointer_desc = "context ";
3550 break;
3551 case PTR_TO_STACK:
3552 pointer_desc = "stack ";
01f810ac
AM
3553 /* The stack spill tracking logic in check_stack_write_fixed_off()
3554 * and check_stack_read_fixed_off() relies on stack accesses being
a5ec6ae1
JH
3555 * aligned.
3556 */
3557 strict = true;
f1174f77 3558 break;
c64b7983
JS
3559 case PTR_TO_SOCKET:
3560 pointer_desc = "sock ";
3561 break;
46f8bc92
MKL
3562 case PTR_TO_SOCK_COMMON:
3563 pointer_desc = "sock_common ";
3564 break;
655a51e5
MKL
3565 case PTR_TO_TCP_SOCK:
3566 pointer_desc = "tcp_sock ";
3567 break;
fada7fdc
JL
3568 case PTR_TO_XDP_SOCK:
3569 pointer_desc = "xdp_sock ";
3570 break;
79adffcd 3571 default:
f1174f77 3572 break;
79adffcd 3573 }
61bd5218
JK
3574 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3575 strict);
79adffcd
DB
3576}
3577
f4d7e40a
AS
3578static int update_stack_depth(struct bpf_verifier_env *env,
3579 const struct bpf_func_state *func,
3580 int off)
3581{
9c8105bd 3582 u16 stack = env->subprog_info[func->subprogno].stack_depth;
f4d7e40a
AS
3583
3584 if (stack >= -off)
3585 return 0;
3586
3587 /* update known max for given subprogram */
9c8105bd 3588 env->subprog_info[func->subprogno].stack_depth = -off;
70a87ffe
AS
3589 return 0;
3590}
f4d7e40a 3591
70a87ffe
AS
3592/* starting from main bpf function walk all instructions of the function
3593 * and recursively walk all callees that given function can call.
3594 * Ignore jump and exit insns.
3595 * Since recursion is prevented by check_cfg() this algorithm
3596 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3597 */
3598static int check_max_stack_depth(struct bpf_verifier_env *env)
3599{
9c8105bd
JW
3600 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3601 struct bpf_subprog_info *subprog = env->subprog_info;
70a87ffe 3602 struct bpf_insn *insn = env->prog->insnsi;
ebf7d1f5 3603 bool tail_call_reachable = false;
70a87ffe
AS
3604 int ret_insn[MAX_CALL_FRAMES];
3605 int ret_prog[MAX_CALL_FRAMES];
ebf7d1f5 3606 int j;
f4d7e40a 3607
70a87ffe 3608process_func:
7f6e4312
MF
3609 /* protect against potential stack overflow that might happen when
3610 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3611 * depth for such case down to 256 so that the worst case scenario
3612 * would result in 8k stack size (32 which is tailcall limit * 256 =
3613 * 8k).
3614 *
3615 * To get the idea what might happen, see an example:
3616 * func1 -> sub rsp, 128
3617 * subfunc1 -> sub rsp, 256
3618 * tailcall1 -> add rsp, 256
3619 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3620 * subfunc2 -> sub rsp, 64
3621 * subfunc22 -> sub rsp, 128
3622 * tailcall2 -> add rsp, 128
3623 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3624 *
3625 * tailcall will unwind the current stack frame but it will not get rid
3626 * of caller's stack as shown on the example above.
3627 */
3628 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3629 verbose(env,
3630 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3631 depth);
3632 return -EACCES;
3633 }
70a87ffe
AS
3634 /* round up to 32-bytes, since this is granularity
3635 * of interpreter stack size
3636 */
9c8105bd 3637 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe 3638 if (depth > MAX_BPF_STACK) {
f4d7e40a 3639 verbose(env, "combined stack size of %d calls is %d. Too large\n",
70a87ffe 3640 frame + 1, depth);
f4d7e40a
AS
3641 return -EACCES;
3642 }
70a87ffe 3643continue_func:
4cb3d99c 3644 subprog_end = subprog[idx + 1].start;
70a87ffe 3645 for (; i < subprog_end; i++) {
69c087ba 3646 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
70a87ffe
AS
3647 continue;
3648 /* remember insn and function to return to */
3649 ret_insn[frame] = i + 1;
9c8105bd 3650 ret_prog[frame] = idx;
70a87ffe
AS
3651
3652 /* find the callee */
3653 i = i + insn[i].imm + 1;
9c8105bd
JW
3654 idx = find_subprog(env, i);
3655 if (idx < 0) {
70a87ffe
AS
3656 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3657 i);
3658 return -EFAULT;
3659 }
ebf7d1f5
MF
3660
3661 if (subprog[idx].has_tail_call)
3662 tail_call_reachable = true;
3663
70a87ffe
AS
3664 frame++;
3665 if (frame >= MAX_CALL_FRAMES) {
927cb781
PC
3666 verbose(env, "the call stack of %d frames is too deep !\n",
3667 frame);
3668 return -E2BIG;
70a87ffe
AS
3669 }
3670 goto process_func;
3671 }
ebf7d1f5
MF
3672 /* if tail call got detected across bpf2bpf calls then mark each of the
3673 * currently present subprog frames as tail call reachable subprogs;
3674 * this info will be utilized by JIT so that we will be preserving the
3675 * tail call counter throughout bpf2bpf calls combined with tailcalls
3676 */
3677 if (tail_call_reachable)
3678 for (j = 0; j < frame; j++)
3679 subprog[ret_prog[j]].tail_call_reachable = true;
5dd0a6b8
DB
3680 if (subprog[0].tail_call_reachable)
3681 env->prog->aux->tail_call_reachable = true;
ebf7d1f5 3682
70a87ffe
AS
3683 /* end of for() loop means the last insn of the 'subprog'
3684 * was reached. Doesn't matter whether it was JA or EXIT
3685 */
3686 if (frame == 0)
3687 return 0;
9c8105bd 3688 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
70a87ffe
AS
3689 frame--;
3690 i = ret_insn[frame];
9c8105bd 3691 idx = ret_prog[frame];
70a87ffe 3692 goto continue_func;
f4d7e40a
AS
3693}
3694
19d28fbd 3695#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
3696static int get_callee_stack_depth(struct bpf_verifier_env *env,
3697 const struct bpf_insn *insn, int idx)
3698{
3699 int start = idx + insn->imm + 1, subprog;
3700
3701 subprog = find_subprog(env, start);
3702 if (subprog < 0) {
3703 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3704 start);
3705 return -EFAULT;
3706 }
9c8105bd 3707 return env->subprog_info[subprog].stack_depth;
1ea47e01 3708}
19d28fbd 3709#endif
1ea47e01 3710
51c39bb1
AS
3711int check_ctx_reg(struct bpf_verifier_env *env,
3712 const struct bpf_reg_state *reg, int regno)
58990d1f
DB
3713{
3714 /* Access to ctx or passing it to a helper is only allowed in
3715 * its original, unmodified form.
3716 */
3717
3718 if (reg->off) {
3719 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3720 regno, reg->off);
3721 return -EACCES;
3722 }
3723
3724 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3725 char tn_buf[48];
3726
3727 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3728 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3729 return -EACCES;
3730 }
3731
3732 return 0;
3733}
3734
afbf21dc
YS
3735static int __check_buffer_access(struct bpf_verifier_env *env,
3736 const char *buf_info,
3737 const struct bpf_reg_state *reg,
3738 int regno, int off, int size)
9df1c28b
MM
3739{
3740 if (off < 0) {
3741 verbose(env,
4fc00b79 3742 "R%d invalid %s buffer access: off=%d, size=%d\n",
afbf21dc 3743 regno, buf_info, off, size);
9df1c28b
MM
3744 return -EACCES;
3745 }
3746 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3747 char tn_buf[48];
3748
3749 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3750 verbose(env,
4fc00b79 3751 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
9df1c28b
MM
3752 regno, off, tn_buf);
3753 return -EACCES;
3754 }
afbf21dc
YS
3755
3756 return 0;
3757}
3758
3759static int check_tp_buffer_access(struct bpf_verifier_env *env,
3760 const struct bpf_reg_state *reg,
3761 int regno, int off, int size)
3762{
3763 int err;
3764
3765 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3766 if (err)
3767 return err;
3768
9df1c28b
MM
3769 if (off + size > env->prog->aux->max_tp_access)
3770 env->prog->aux->max_tp_access = off + size;
3771
3772 return 0;
3773}
3774
afbf21dc
YS
3775static int check_buffer_access(struct bpf_verifier_env *env,
3776 const struct bpf_reg_state *reg,
3777 int regno, int off, int size,
3778 bool zero_size_allowed,
3779 const char *buf_info,
3780 u32 *max_access)
3781{
3782 int err;
3783
3784 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3785 if (err)
3786 return err;
3787
3788 if (off + size > *max_access)
3789 *max_access = off + size;
3790
3791 return 0;
3792}
3793
3f50f132
JF
3794/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3795static void zext_32_to_64(struct bpf_reg_state *reg)
3796{
3797 reg->var_off = tnum_subreg(reg->var_off);
3798 __reg_assign_32_into_64(reg);
3799}
9df1c28b 3800
0c17d1d2
JH
3801/* truncate register to smaller size (in bytes)
3802 * must be called with size < BPF_REG_SIZE
3803 */
3804static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3805{
3806 u64 mask;
3807
3808 /* clear high bits in bit representation */
3809 reg->var_off = tnum_cast(reg->var_off, size);
3810
3811 /* fix arithmetic bounds */
3812 mask = ((u64)1 << (size * 8)) - 1;
3813 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3814 reg->umin_value &= mask;
3815 reg->umax_value &= mask;
3816 } else {
3817 reg->umin_value = 0;
3818 reg->umax_value = mask;
3819 }
3820 reg->smin_value = reg->umin_value;
3821 reg->smax_value = reg->umax_value;
3f50f132
JF
3822
3823 /* If size is smaller than 32bit register the 32bit register
3824 * values are also truncated so we push 64-bit bounds into
3825 * 32-bit bounds. Above were truncated < 32-bits already.
3826 */
3827 if (size >= 4)
3828 return;
3829 __reg_combine_64_into_32(reg);
0c17d1d2
JH
3830}
3831
a23740ec
AN
3832static bool bpf_map_is_rdonly(const struct bpf_map *map)
3833{
3834 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3835}
3836
3837static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3838{
3839 void *ptr;
3840 u64 addr;
3841 int err;
3842
3843 err = map->ops->map_direct_value_addr(map, &addr, off);
3844 if (err)
3845 return err;
2dedd7d2 3846 ptr = (void *)(long)addr + off;
a23740ec
AN
3847
3848 switch (size) {
3849 case sizeof(u8):
3850 *val = (u64)*(u8 *)ptr;
3851 break;
3852 case sizeof(u16):
3853 *val = (u64)*(u16 *)ptr;
3854 break;
3855 case sizeof(u32):
3856 *val = (u64)*(u32 *)ptr;
3857 break;
3858 case sizeof(u64):
3859 *val = *(u64 *)ptr;
3860 break;
3861 default:
3862 return -EINVAL;
3863 }
3864 return 0;
3865}
3866
9e15db66
AS
3867static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3868 struct bpf_reg_state *regs,
3869 int regno, int off, int size,
3870 enum bpf_access_type atype,
3871 int value_regno)
3872{
3873 struct bpf_reg_state *reg = regs + regno;
22dc4a0f
AN
3874 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3875 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
9e15db66
AS
3876 u32 btf_id;
3877 int ret;
3878
9e15db66
AS
3879 if (off < 0) {
3880 verbose(env,
3881 "R%d is ptr_%s invalid negative access: off=%d\n",
3882 regno, tname, off);
3883 return -EACCES;
3884 }
3885 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3886 char tn_buf[48];
3887
3888 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3889 verbose(env,
3890 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3891 regno, tname, off, tn_buf);
3892 return -EACCES;
3893 }
3894
27ae7997 3895 if (env->ops->btf_struct_access) {
22dc4a0f
AN
3896 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3897 off, size, atype, &btf_id);
27ae7997
MKL
3898 } else {
3899 if (atype != BPF_READ) {
3900 verbose(env, "only read is supported\n");
3901 return -EACCES;
3902 }
3903
22dc4a0f
AN
3904 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3905 atype, &btf_id);
27ae7997
MKL
3906 }
3907
9e15db66
AS
3908 if (ret < 0)
3909 return ret;
3910
41c48f3a 3911 if (atype == BPF_READ && value_regno >= 0)
22dc4a0f 3912 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
41c48f3a
AI
3913
3914 return 0;
3915}
3916
3917static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3918 struct bpf_reg_state *regs,
3919 int regno, int off, int size,
3920 enum bpf_access_type atype,
3921 int value_regno)
3922{
3923 struct bpf_reg_state *reg = regs + regno;
3924 struct bpf_map *map = reg->map_ptr;
3925 const struct btf_type *t;
3926 const char *tname;
3927 u32 btf_id;
3928 int ret;
3929
3930 if (!btf_vmlinux) {
3931 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3932 return -ENOTSUPP;
3933 }
3934
3935 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3936 verbose(env, "map_ptr access not supported for map type %d\n",
3937 map->map_type);
3938 return -ENOTSUPP;
3939 }
3940
3941 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3942 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3943
3944 if (!env->allow_ptr_to_map_access) {
3945 verbose(env,
3946 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3947 tname);
3948 return -EPERM;
9e15db66 3949 }
27ae7997 3950
41c48f3a
AI
3951 if (off < 0) {
3952 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3953 regno, tname, off);
3954 return -EACCES;
3955 }
3956
3957 if (atype != BPF_READ) {
3958 verbose(env, "only read from %s is supported\n", tname);
3959 return -EACCES;
3960 }
3961
22dc4a0f 3962 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
41c48f3a
AI
3963 if (ret < 0)
3964 return ret;
3965
3966 if (value_regno >= 0)
22dc4a0f 3967 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
41c48f3a 3968
9e15db66
AS
3969 return 0;
3970}
3971
01f810ac
AM
3972/* Check that the stack access at the given offset is within bounds. The
3973 * maximum valid offset is -1.
3974 *
3975 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3976 * -state->allocated_stack for reads.
3977 */
3978static int check_stack_slot_within_bounds(int off,
3979 struct bpf_func_state *state,
3980 enum bpf_access_type t)
3981{
3982 int min_valid_off;
3983
3984 if (t == BPF_WRITE)
3985 min_valid_off = -MAX_BPF_STACK;
3986 else
3987 min_valid_off = -state->allocated_stack;
3988
3989 if (off < min_valid_off || off > -1)
3990 return -EACCES;
3991 return 0;
3992}
3993
3994/* Check that the stack access at 'regno + off' falls within the maximum stack
3995 * bounds.
3996 *
3997 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3998 */
3999static int check_stack_access_within_bounds(
4000 struct bpf_verifier_env *env,
4001 int regno, int off, int access_size,
4002 enum stack_access_src src, enum bpf_access_type type)
4003{
4004 struct bpf_reg_state *regs = cur_regs(env);
4005 struct bpf_reg_state *reg = regs + regno;
4006 struct bpf_func_state *state = func(env, reg);
4007 int min_off, max_off;
4008 int err;
4009 char *err_extra;
4010
4011 if (src == ACCESS_HELPER)
4012 /* We don't know if helpers are reading or writing (or both). */
4013 err_extra = " indirect access to";
4014 else if (type == BPF_READ)
4015 err_extra = " read from";
4016 else
4017 err_extra = " write to";
4018
4019 if (tnum_is_const(reg->var_off)) {
4020 min_off = reg->var_off.value + off;
4021 if (access_size > 0)
4022 max_off = min_off + access_size - 1;
4023 else
4024 max_off = min_off;
4025 } else {
4026 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4027 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4028 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4029 err_extra, regno);
4030 return -EACCES;
4031 }
4032 min_off = reg->smin_value + off;
4033 if (access_size > 0)
4034 max_off = reg->smax_value + off + access_size - 1;
4035 else
4036 max_off = min_off;
4037 }
4038
4039 err = check_stack_slot_within_bounds(min_off, state, type);
4040 if (!err)
4041 err = check_stack_slot_within_bounds(max_off, state, type);
4042
4043 if (err) {
4044 if (tnum_is_const(reg->var_off)) {
4045 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4046 err_extra, regno, off, access_size);
4047 } else {
4048 char tn_buf[48];
4049
4050 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4051 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4052 err_extra, regno, tn_buf, access_size);
4053 }
4054 }
4055 return err;
4056}
41c48f3a 4057
17a52670
AS
4058/* check whether memory at (regno + off) is accessible for t = (read | write)
4059 * if t==write, value_regno is a register which value is stored into memory
4060 * if t==read, value_regno is a register which will receive the value from memory
4061 * if t==write && value_regno==-1, some unknown value is stored into memory
4062 * if t==read && value_regno==-1, don't care what we read from memory
4063 */
ca369602
DB
4064static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4065 int off, int bpf_size, enum bpf_access_type t,
4066 int value_regno, bool strict_alignment_once)
17a52670 4067{
638f5b90
AS
4068 struct bpf_reg_state *regs = cur_regs(env);
4069 struct bpf_reg_state *reg = regs + regno;
f4d7e40a 4070 struct bpf_func_state *state;
17a52670
AS
4071 int size, err = 0;
4072
4073 size = bpf_size_to_bytes(bpf_size);
4074 if (size < 0)
4075 return size;
4076
f1174f77 4077 /* alignment checks will add in reg->off themselves */
ca369602 4078 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
969bf05e
AS
4079 if (err)
4080 return err;
17a52670 4081
f1174f77
EC
4082 /* for access checks, reg->off is just part of off */
4083 off += reg->off;
4084
69c087ba
YS
4085 if (reg->type == PTR_TO_MAP_KEY) {
4086 if (t == BPF_WRITE) {
4087 verbose(env, "write to change key R%d not allowed\n", regno);
4088 return -EACCES;
4089 }
4090
4091 err = check_mem_region_access(env, regno, off, size,
4092 reg->map_ptr->key_size, false);
4093 if (err)
4094 return err;
4095 if (value_regno >= 0)
4096 mark_reg_unknown(env, regs, value_regno);
4097 } else if (reg->type == PTR_TO_MAP_VALUE) {
1be7f75d
AS
4098 if (t == BPF_WRITE && value_regno >= 0 &&
4099 is_pointer_value(env, value_regno)) {
61bd5218 4100 verbose(env, "R%d leaks addr into map\n", value_regno);
1be7f75d
AS
4101 return -EACCES;
4102 }
591fe988
DB
4103 err = check_map_access_type(env, regno, off, size, t);
4104 if (err)
4105 return err;
9fd29c08 4106 err = check_map_access(env, regno, off, size, false);
a23740ec
AN
4107 if (!err && t == BPF_READ && value_regno >= 0) {
4108 struct bpf_map *map = reg->map_ptr;
4109
4110 /* if map is read-only, track its contents as scalars */
4111 if (tnum_is_const(reg->var_off) &&
4112 bpf_map_is_rdonly(map) &&
4113 map->ops->map_direct_value_addr) {
4114 int map_off = off + reg->var_off.value;
4115 u64 val = 0;
4116
4117 err = bpf_map_direct_read(map, map_off, size,
4118 &val);
4119 if (err)
4120 return err;
4121
4122 regs[value_regno].type = SCALAR_VALUE;
4123 __mark_reg_known(&regs[value_regno], val);
4124 } else {
4125 mark_reg_unknown(env, regs, value_regno);
4126 }
4127 }
457f4436
AN
4128 } else if (reg->type == PTR_TO_MEM) {
4129 if (t == BPF_WRITE && value_regno >= 0 &&
4130 is_pointer_value(env, value_regno)) {
4131 verbose(env, "R%d leaks addr into mem\n", value_regno);
4132 return -EACCES;
4133 }
4134 err = check_mem_region_access(env, regno, off, size,
4135 reg->mem_size, false);
4136 if (!err && t == BPF_READ && value_regno >= 0)
4137 mark_reg_unknown(env, regs, value_regno);
1a0dc1ac 4138 } else if (reg->type == PTR_TO_CTX) {
f1174f77 4139 enum bpf_reg_type reg_type = SCALAR_VALUE;
22dc4a0f 4140 struct btf *btf = NULL;
9e15db66 4141 u32 btf_id = 0;
19de99f7 4142
1be7f75d
AS
4143 if (t == BPF_WRITE && value_regno >= 0 &&
4144 is_pointer_value(env, value_regno)) {
61bd5218 4145 verbose(env, "R%d leaks addr into ctx\n", value_regno);
1be7f75d
AS
4146 return -EACCES;
4147 }
f1174f77 4148
58990d1f
DB
4149 err = check_ctx_reg(env, reg, regno);
4150 if (err < 0)
4151 return err;
4152
22dc4a0f 4153 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
9e15db66
AS
4154 if (err)
4155 verbose_linfo(env, insn_idx, "; ");
969bf05e 4156 if (!err && t == BPF_READ && value_regno >= 0) {
f1174f77 4157 /* ctx access returns either a scalar, or a
de8f3a83
DB
4158 * PTR_TO_PACKET[_META,_END]. In the latter
4159 * case, we know the offset is zero.
f1174f77 4160 */
46f8bc92 4161 if (reg_type == SCALAR_VALUE) {
638f5b90 4162 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4163 } else {
638f5b90 4164 mark_reg_known_zero(env, regs,
61bd5218 4165 value_regno);
46f8bc92
MKL
4166 if (reg_type_may_be_null(reg_type))
4167 regs[value_regno].id = ++env->id_gen;
5327ed3d
JW
4168 /* A load of ctx field could have different
4169 * actual load size with the one encoded in the
4170 * insn. When the dst is PTR, it is for sure not
4171 * a sub-register.
4172 */
4173 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
b121b341 4174 if (reg_type == PTR_TO_BTF_ID ||
22dc4a0f
AN
4175 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4176 regs[value_regno].btf = btf;
9e15db66 4177 regs[value_regno].btf_id = btf_id;
22dc4a0f 4178 }
46f8bc92 4179 }
638f5b90 4180 regs[value_regno].type = reg_type;
969bf05e 4181 }
17a52670 4182
f1174f77 4183 } else if (reg->type == PTR_TO_STACK) {
01f810ac
AM
4184 /* Basic bounds checks. */
4185 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
e4298d25
DB
4186 if (err)
4187 return err;
8726679a 4188
f4d7e40a
AS
4189 state = func(env, reg);
4190 err = update_stack_depth(env, state, off);
4191 if (err)
4192 return err;
8726679a 4193
01f810ac
AM
4194 if (t == BPF_READ)
4195 err = check_stack_read(env, regno, off, size,
61bd5218 4196 value_regno);
01f810ac
AM
4197 else
4198 err = check_stack_write(env, regno, off, size,
4199 value_regno, insn_idx);
de8f3a83 4200 } else if (reg_is_pkt_pointer(reg)) {
3a0af8fd 4201 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
61bd5218 4202 verbose(env, "cannot write into packet\n");
969bf05e
AS
4203 return -EACCES;
4204 }
4acf6c0b
BB
4205 if (t == BPF_WRITE && value_regno >= 0 &&
4206 is_pointer_value(env, value_regno)) {
61bd5218
JK
4207 verbose(env, "R%d leaks addr into packet\n",
4208 value_regno);
4acf6c0b
BB
4209 return -EACCES;
4210 }
9fd29c08 4211 err = check_packet_access(env, regno, off, size, false);
969bf05e 4212 if (!err && t == BPF_READ && value_regno >= 0)
638f5b90 4213 mark_reg_unknown(env, regs, value_regno);
d58e468b
PP
4214 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4215 if (t == BPF_WRITE && value_regno >= 0 &&
4216 is_pointer_value(env, value_regno)) {
4217 verbose(env, "R%d leaks addr into flow keys\n",
4218 value_regno);
4219 return -EACCES;
4220 }
4221
4222 err = check_flow_keys_access(env, off, size);
4223 if (!err && t == BPF_READ && value_regno >= 0)
4224 mark_reg_unknown(env, regs, value_regno);
46f8bc92 4225 } else if (type_is_sk_pointer(reg->type)) {
c64b7983 4226 if (t == BPF_WRITE) {
46f8bc92
MKL
4227 verbose(env, "R%d cannot write into %s\n",
4228 regno, reg_type_str[reg->type]);
c64b7983
JS
4229 return -EACCES;
4230 }
5f456649 4231 err = check_sock_access(env, insn_idx, regno, off, size, t);
c64b7983
JS
4232 if (!err && value_regno >= 0)
4233 mark_reg_unknown(env, regs, value_regno);
9df1c28b
MM
4234 } else if (reg->type == PTR_TO_TP_BUFFER) {
4235 err = check_tp_buffer_access(env, reg, regno, off, size);
4236 if (!err && t == BPF_READ && value_regno >= 0)
4237 mark_reg_unknown(env, regs, value_regno);
9e15db66
AS
4238 } else if (reg->type == PTR_TO_BTF_ID) {
4239 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4240 value_regno);
41c48f3a
AI
4241 } else if (reg->type == CONST_PTR_TO_MAP) {
4242 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4243 value_regno);
afbf21dc
YS
4244 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4245 if (t == BPF_WRITE) {
4246 verbose(env, "R%d cannot write into %s\n",
4247 regno, reg_type_str[reg->type]);
4248 return -EACCES;
4249 }
f6dfbe31
CIK
4250 err = check_buffer_access(env, reg, regno, off, size, false,
4251 "rdonly",
afbf21dc
YS
4252 &env->prog->aux->max_rdonly_access);
4253 if (!err && value_regno >= 0)
4254 mark_reg_unknown(env, regs, value_regno);
4255 } else if (reg->type == PTR_TO_RDWR_BUF) {
f6dfbe31
CIK
4256 err = check_buffer_access(env, reg, regno, off, size, false,
4257 "rdwr",
afbf21dc
YS
4258 &env->prog->aux->max_rdwr_access);
4259 if (!err && t == BPF_READ && value_regno >= 0)
4260 mark_reg_unknown(env, regs, value_regno);
17a52670 4261 } else {
61bd5218
JK
4262 verbose(env, "R%d invalid mem access '%s'\n", regno,
4263 reg_type_str[reg->type]);
17a52670
AS
4264 return -EACCES;
4265 }
969bf05e 4266
f1174f77 4267 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
638f5b90 4268 regs[value_regno].type == SCALAR_VALUE) {
f1174f77 4269 /* b/h/w load zero-extends, mark upper bits as known 0 */
0c17d1d2 4270 coerce_reg_to_size(&regs[value_regno], size);
969bf05e 4271 }
17a52670
AS
4272 return err;
4273}
4274
91c960b0 4275static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
17a52670 4276{
5ffa2550 4277 int load_reg;
17a52670
AS
4278 int err;
4279
5ca419f2
BJ
4280 switch (insn->imm) {
4281 case BPF_ADD:
4282 case BPF_ADD | BPF_FETCH:
981f94c3
BJ
4283 case BPF_AND:
4284 case BPF_AND | BPF_FETCH:
4285 case BPF_OR:
4286 case BPF_OR | BPF_FETCH:
4287 case BPF_XOR:
4288 case BPF_XOR | BPF_FETCH:
5ffa2550
BJ
4289 case BPF_XCHG:
4290 case BPF_CMPXCHG:
5ca419f2
BJ
4291 break;
4292 default:
91c960b0
BJ
4293 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4294 return -EINVAL;
4295 }
4296
4297 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4298 verbose(env, "invalid atomic operand size\n");
17a52670
AS
4299 return -EINVAL;
4300 }
4301
4302 /* check src1 operand */
dc503a8a 4303 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
4304 if (err)
4305 return err;
4306
4307 /* check src2 operand */
dc503a8a 4308 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
4309 if (err)
4310 return err;
4311
5ffa2550
BJ
4312 if (insn->imm == BPF_CMPXCHG) {
4313 /* Check comparison of R0 with memory location */
4314 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4315 if (err)
4316 return err;
4317 }
4318
6bdf6abc 4319 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 4320 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6bdf6abc
DB
4321 return -EACCES;
4322 }
4323
ca369602 4324 if (is_ctx_reg(env, insn->dst_reg) ||
4b5defde 4325 is_pkt_reg(env, insn->dst_reg) ||
46f8bc92
MKL
4326 is_flow_key_reg(env, insn->dst_reg) ||
4327 is_sk_reg(env, insn->dst_reg)) {
91c960b0 4328 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
2a159c6f
DB
4329 insn->dst_reg,
4330 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
4331 return -EACCES;
4332 }
4333
37086bfd
BJ
4334 if (insn->imm & BPF_FETCH) {
4335 if (insn->imm == BPF_CMPXCHG)
4336 load_reg = BPF_REG_0;
4337 else
4338 load_reg = insn->src_reg;
4339
4340 /* check and record load of old value */
4341 err = check_reg_arg(env, load_reg, DST_OP);
4342 if (err)
4343 return err;
4344 } else {
4345 /* This instruction accesses a memory location but doesn't
4346 * actually load it into a register.
4347 */
4348 load_reg = -1;
4349 }
4350
91c960b0 4351 /* check whether we can read the memory */
31fd8581 4352 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
37086bfd 4353 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
17a52670
AS
4354 if (err)
4355 return err;
4356
91c960b0 4357 /* check whether we can write into the same memory */
5ca419f2
BJ
4358 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4359 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4360 if (err)
4361 return err;
4362
5ca419f2 4363 return 0;
17a52670
AS
4364}
4365
01f810ac
AM
4366/* When register 'regno' is used to read the stack (either directly or through
4367 * a helper function) make sure that it's within stack boundary and, depending
4368 * on the access type, that all elements of the stack are initialized.
4369 *
4370 * 'off' includes 'regno->off', but not its dynamic part (if any).
4371 *
4372 * All registers that have been spilled on the stack in the slots within the
4373 * read offsets are marked as read.
4374 */
4375static int check_stack_range_initialized(
4376 struct bpf_verifier_env *env, int regno, int off,
4377 int access_size, bool zero_size_allowed,
4378 enum stack_access_src type, struct bpf_call_arg_meta *meta)
2011fccf
AI
4379{
4380 struct bpf_reg_state *reg = reg_state(env, regno);
01f810ac
AM
4381 struct bpf_func_state *state = func(env, reg);
4382 int err, min_off, max_off, i, j, slot, spi;
4383 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4384 enum bpf_access_type bounds_check_type;
4385 /* Some accesses can write anything into the stack, others are
4386 * read-only.
4387 */
4388 bool clobber = false;
2011fccf 4389
01f810ac
AM
4390 if (access_size == 0 && !zero_size_allowed) {
4391 verbose(env, "invalid zero-sized read\n");
2011fccf
AI
4392 return -EACCES;
4393 }
2011fccf 4394
01f810ac
AM
4395 if (type == ACCESS_HELPER) {
4396 /* The bounds checks for writes are more permissive than for
4397 * reads. However, if raw_mode is not set, we'll do extra
4398 * checks below.
4399 */
4400 bounds_check_type = BPF_WRITE;
4401 clobber = true;
4402 } else {
4403 bounds_check_type = BPF_READ;
4404 }
4405 err = check_stack_access_within_bounds(env, regno, off, access_size,
4406 type, bounds_check_type);
4407 if (err)
4408 return err;
4409
17a52670 4410
2011fccf 4411 if (tnum_is_const(reg->var_off)) {
01f810ac 4412 min_off = max_off = reg->var_off.value + off;
2011fccf 4413 } else {
088ec26d
AI
4414 /* Variable offset is prohibited for unprivileged mode for
4415 * simplicity since it requires corresponding support in
4416 * Spectre masking for stack ALU.
4417 * See also retrieve_ptr_limit().
4418 */
2c78ee89 4419 if (!env->bypass_spec_v1) {
088ec26d 4420 char tn_buf[48];
f1174f77 4421
088ec26d 4422 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4423 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4424 regno, err_extra, tn_buf);
088ec26d
AI
4425 return -EACCES;
4426 }
f2bcd05e
AI
4427 /* Only initialized buffer on stack is allowed to be accessed
4428 * with variable offset. With uninitialized buffer it's hard to
4429 * guarantee that whole memory is marked as initialized on
4430 * helper return since specific bounds are unknown what may
4431 * cause uninitialized stack leaking.
4432 */
4433 if (meta && meta->raw_mode)
4434 meta = NULL;
4435
01f810ac
AM
4436 min_off = reg->smin_value + off;
4437 max_off = reg->smax_value + off;
17a52670
AS
4438 }
4439
435faee1
DB
4440 if (meta && meta->raw_mode) {
4441 meta->access_size = access_size;
4442 meta->regno = regno;
4443 return 0;
4444 }
4445
2011fccf 4446 for (i = min_off; i < max_off + access_size; i++) {
cc2b14d5
AS
4447 u8 *stype;
4448
2011fccf 4449 slot = -i - 1;
638f5b90 4450 spi = slot / BPF_REG_SIZE;
cc2b14d5
AS
4451 if (state->allocated_stack <= slot)
4452 goto err;
4453 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4454 if (*stype == STACK_MISC)
4455 goto mark;
4456 if (*stype == STACK_ZERO) {
01f810ac
AM
4457 if (clobber) {
4458 /* helper can write anything into the stack */
4459 *stype = STACK_MISC;
4460 }
cc2b14d5 4461 goto mark;
17a52670 4462 }
1d68f22b
YS
4463
4464 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4465 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4466 goto mark;
4467
f7cf25b2 4468 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
cd17d38f
YS
4469 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4470 env->allow_ptr_leaks)) {
01f810ac
AM
4471 if (clobber) {
4472 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4473 for (j = 0; j < BPF_REG_SIZE; j++)
4474 state->stack[spi].slot_type[j] = STACK_MISC;
4475 }
f7cf25b2
AS
4476 goto mark;
4477 }
4478
cc2b14d5 4479err:
2011fccf 4480 if (tnum_is_const(reg->var_off)) {
01f810ac
AM
4481 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4482 err_extra, regno, min_off, i - min_off, access_size);
2011fccf
AI
4483 } else {
4484 char tn_buf[48];
4485
4486 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
01f810ac
AM
4487 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4488 err_extra, regno, tn_buf, i - min_off, access_size);
2011fccf 4489 }
cc2b14d5
AS
4490 return -EACCES;
4491mark:
4492 /* reading any byte out of 8-byte 'spill_slot' will cause
4493 * the whole slot to be marked as 'read'
4494 */
679c782d 4495 mark_reg_read(env, &state->stack[spi].spilled_ptr,
5327ed3d
JW
4496 state->stack[spi].spilled_ptr.parent,
4497 REG_LIVE_READ64);
17a52670 4498 }
2011fccf 4499 return update_stack_depth(env, state, min_off);
17a52670
AS
4500}
4501
06c1c049
GB
4502static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4503 int access_size, bool zero_size_allowed,
4504 struct bpf_call_arg_meta *meta)
4505{
638f5b90 4506 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
06c1c049 4507
f1174f77 4508 switch (reg->type) {
06c1c049 4509 case PTR_TO_PACKET:
de8f3a83 4510 case PTR_TO_PACKET_META:
9fd29c08
YS
4511 return check_packet_access(env, regno, reg->off, access_size,
4512 zero_size_allowed);
69c087ba
YS
4513 case PTR_TO_MAP_KEY:
4514 return check_mem_region_access(env, regno, reg->off, access_size,
4515 reg->map_ptr->key_size, false);
06c1c049 4516 case PTR_TO_MAP_VALUE:
591fe988
DB
4517 if (check_map_access_type(env, regno, reg->off, access_size,
4518 meta && meta->raw_mode ? BPF_WRITE :
4519 BPF_READ))
4520 return -EACCES;
9fd29c08
YS
4521 return check_map_access(env, regno, reg->off, access_size,
4522 zero_size_allowed);
457f4436
AN
4523 case PTR_TO_MEM:
4524 return check_mem_region_access(env, regno, reg->off,
4525 access_size, reg->mem_size,
4526 zero_size_allowed);
afbf21dc
YS
4527 case PTR_TO_RDONLY_BUF:
4528 if (meta && meta->raw_mode)
4529 return -EACCES;
4530 return check_buffer_access(env, reg, regno, reg->off,
4531 access_size, zero_size_allowed,
4532 "rdonly",
4533 &env->prog->aux->max_rdonly_access);
4534 case PTR_TO_RDWR_BUF:
4535 return check_buffer_access(env, reg, regno, reg->off,
4536 access_size, zero_size_allowed,
4537 "rdwr",
4538 &env->prog->aux->max_rdwr_access);
0d004c02 4539 case PTR_TO_STACK:
01f810ac
AM
4540 return check_stack_range_initialized(
4541 env,
4542 regno, reg->off, access_size,
4543 zero_size_allowed, ACCESS_HELPER, meta);
0d004c02
LB
4544 default: /* scalar_value or invalid ptr */
4545 /* Allow zero-byte read from NULL, regardless of pointer type */
4546 if (zero_size_allowed && access_size == 0 &&
4547 register_is_null(reg))
4548 return 0;
4549
4550 verbose(env, "R%d type=%s expected=%s\n", regno,
4551 reg_type_str[reg->type],
4552 reg_type_str[PTR_TO_STACK]);
4553 return -EACCES;
06c1c049
GB
4554 }
4555}
4556
e5069b9c
DB
4557int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4558 u32 regno, u32 mem_size)
4559{
4560 if (register_is_null(reg))
4561 return 0;
4562
4563 if (reg_type_may_be_null(reg->type)) {
4564 /* Assuming that the register contains a value check if the memory
4565 * access is safe. Temporarily save and restore the register's state as
4566 * the conversion shouldn't be visible to a caller.
4567 */
4568 const struct bpf_reg_state saved_reg = *reg;
4569 int rv;
4570
4571 mark_ptr_not_null_reg(reg);
4572 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4573 *reg = saved_reg;
4574 return rv;
4575 }
4576
4577 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4578}
4579
d83525ca
AS
4580/* Implementation details:
4581 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4582 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4583 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4584 * value_or_null->value transition, since the verifier only cares about
4585 * the range of access to valid map value pointer and doesn't care about actual
4586 * address of the map element.
4587 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4588 * reg->id > 0 after value_or_null->value transition. By doing so
4589 * two bpf_map_lookups will be considered two different pointers that
4590 * point to different bpf_spin_locks.
4591 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4592 * dead-locks.
4593 * Since only one bpf_spin_lock is allowed the checks are simpler than
4594 * reg_is_refcounted() logic. The verifier needs to remember only
4595 * one spin_lock instead of array of acquired_refs.
4596 * cur_state->active_spin_lock remembers which map value element got locked
4597 * and clears it after bpf_spin_unlock.
4598 */
4599static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4600 bool is_lock)
4601{
4602 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4603 struct bpf_verifier_state *cur = env->cur_state;
4604 bool is_const = tnum_is_const(reg->var_off);
4605 struct bpf_map *map = reg->map_ptr;
4606 u64 val = reg->var_off.value;
4607
d83525ca
AS
4608 if (!is_const) {
4609 verbose(env,
4610 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4611 regno);
4612 return -EINVAL;
4613 }
4614 if (!map->btf) {
4615 verbose(env,
4616 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4617 map->name);
4618 return -EINVAL;
4619 }
4620 if (!map_value_has_spin_lock(map)) {
4621 if (map->spin_lock_off == -E2BIG)
4622 verbose(env,
4623 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4624 map->name);
4625 else if (map->spin_lock_off == -ENOENT)
4626 verbose(env,
4627 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4628 map->name);
4629 else
4630 verbose(env,
4631 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4632 map->name);
4633 return -EINVAL;
4634 }
4635 if (map->spin_lock_off != val + reg->off) {
4636 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4637 val + reg->off);
4638 return -EINVAL;
4639 }
4640 if (is_lock) {
4641 if (cur->active_spin_lock) {
4642 verbose(env,
4643 "Locking two bpf_spin_locks are not allowed\n");
4644 return -EINVAL;
4645 }
4646 cur->active_spin_lock = reg->id;
4647 } else {
4648 if (!cur->active_spin_lock) {
4649 verbose(env, "bpf_spin_unlock without taking a lock\n");
4650 return -EINVAL;
4651 }
4652 if (cur->active_spin_lock != reg->id) {
4653 verbose(env, "bpf_spin_unlock of different lock\n");
4654 return -EINVAL;
4655 }
4656 cur->active_spin_lock = 0;
4657 }
4658 return 0;
4659}
4660
90133415
DB
4661static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4662{
4663 return type == ARG_PTR_TO_MEM ||
4664 type == ARG_PTR_TO_MEM_OR_NULL ||
4665 type == ARG_PTR_TO_UNINIT_MEM;
4666}
4667
4668static bool arg_type_is_mem_size(enum bpf_arg_type type)
4669{
4670 return type == ARG_CONST_SIZE ||
4671 type == ARG_CONST_SIZE_OR_ZERO;
4672}
4673
457f4436
AN
4674static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4675{
4676 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4677}
4678
57c3bb72
AI
4679static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4680{
4681 return type == ARG_PTR_TO_INT ||
4682 type == ARG_PTR_TO_LONG;
4683}
4684
4685static int int_ptr_type_to_size(enum bpf_arg_type type)
4686{
4687 if (type == ARG_PTR_TO_INT)
4688 return sizeof(u32);
4689 else if (type == ARG_PTR_TO_LONG)
4690 return sizeof(u64);
4691
4692 return -EINVAL;
4693}
4694
912f442c
LB
4695static int resolve_map_arg_type(struct bpf_verifier_env *env,
4696 const struct bpf_call_arg_meta *meta,
4697 enum bpf_arg_type *arg_type)
4698{
4699 if (!meta->map_ptr) {
4700 /* kernel subsystem misconfigured verifier */
4701 verbose(env, "invalid map_ptr to access map->type\n");
4702 return -EACCES;
4703 }
4704
4705 switch (meta->map_ptr->map_type) {
4706 case BPF_MAP_TYPE_SOCKMAP:
4707 case BPF_MAP_TYPE_SOCKHASH:
4708 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
6550f2dd 4709 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
912f442c
LB
4710 } else {
4711 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4712 return -EINVAL;
4713 }
4714 break;
4715
4716 default:
4717 break;
4718 }
4719 return 0;
4720}
4721
f79e7ea5
LB
4722struct bpf_reg_types {
4723 const enum bpf_reg_type types[10];
1df8f55a 4724 u32 *btf_id;
f79e7ea5
LB
4725};
4726
4727static const struct bpf_reg_types map_key_value_types = {
4728 .types = {
4729 PTR_TO_STACK,
4730 PTR_TO_PACKET,
4731 PTR_TO_PACKET_META,
69c087ba 4732 PTR_TO_MAP_KEY,
f79e7ea5
LB
4733 PTR_TO_MAP_VALUE,
4734 },
4735};
4736
4737static const struct bpf_reg_types sock_types = {
4738 .types = {
4739 PTR_TO_SOCK_COMMON,
4740 PTR_TO_SOCKET,
4741 PTR_TO_TCP_SOCK,
4742 PTR_TO_XDP_SOCK,
4743 },
4744};
4745
49a2a4d4 4746#ifdef CONFIG_NET
1df8f55a
MKL
4747static const struct bpf_reg_types btf_id_sock_common_types = {
4748 .types = {
4749 PTR_TO_SOCK_COMMON,
4750 PTR_TO_SOCKET,
4751 PTR_TO_TCP_SOCK,
4752 PTR_TO_XDP_SOCK,
4753 PTR_TO_BTF_ID,
4754 },
4755 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4756};
49a2a4d4 4757#endif
1df8f55a 4758
f79e7ea5
LB
4759static const struct bpf_reg_types mem_types = {
4760 .types = {
4761 PTR_TO_STACK,
4762 PTR_TO_PACKET,
4763 PTR_TO_PACKET_META,
69c087ba 4764 PTR_TO_MAP_KEY,
f79e7ea5
LB
4765 PTR_TO_MAP_VALUE,
4766 PTR_TO_MEM,
4767 PTR_TO_RDONLY_BUF,
4768 PTR_TO_RDWR_BUF,
4769 },
4770};
4771
4772static const struct bpf_reg_types int_ptr_types = {
4773 .types = {
4774 PTR_TO_STACK,
4775 PTR_TO_PACKET,
4776 PTR_TO_PACKET_META,
69c087ba 4777 PTR_TO_MAP_KEY,
f79e7ea5
LB
4778 PTR_TO_MAP_VALUE,
4779 },
4780};
4781
4782static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4783static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4784static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4785static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4786static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4787static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4788static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
eaa6bcb7 4789static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
69c087ba
YS
4790static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4791static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
fff13c4b 4792static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
f79e7ea5 4793
0789e13b 4794static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
f79e7ea5
LB
4795 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4796 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4797 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4798 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4799 [ARG_CONST_SIZE] = &scalar_types,
4800 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4801 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4802 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4803 [ARG_PTR_TO_CTX] = &context_types,
4804 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4805 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
49a2a4d4 4806#ifdef CONFIG_NET
1df8f55a 4807 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
49a2a4d4 4808#endif
f79e7ea5
LB
4809 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4810 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4811 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4812 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4813 [ARG_PTR_TO_MEM] = &mem_types,
4814 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4815 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4816 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4817 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4818 [ARG_PTR_TO_INT] = &int_ptr_types,
4819 [ARG_PTR_TO_LONG] = &int_ptr_types,
eaa6bcb7 4820 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
69c087ba
YS
4821 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4822 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
fff13c4b 4823 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
f79e7ea5
LB
4824};
4825
4826static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
a968d5e2
MKL
4827 enum bpf_arg_type arg_type,
4828 const u32 *arg_btf_id)
f79e7ea5
LB
4829{
4830 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4831 enum bpf_reg_type expected, type = reg->type;
a968d5e2 4832 const struct bpf_reg_types *compatible;
f79e7ea5
LB
4833 int i, j;
4834
a968d5e2
MKL
4835 compatible = compatible_reg_types[arg_type];
4836 if (!compatible) {
4837 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4838 return -EFAULT;
4839 }
4840
f79e7ea5
LB
4841 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4842 expected = compatible->types[i];
4843 if (expected == NOT_INIT)
4844 break;
4845
4846 if (type == expected)
a968d5e2 4847 goto found;
f79e7ea5
LB
4848 }
4849
4850 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4851 for (j = 0; j + 1 < i; j++)
4852 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4853 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4854 return -EACCES;
a968d5e2
MKL
4855
4856found:
4857 if (type == PTR_TO_BTF_ID) {
1df8f55a
MKL
4858 if (!arg_btf_id) {
4859 if (!compatible->btf_id) {
4860 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4861 return -EFAULT;
4862 }
4863 arg_btf_id = compatible->btf_id;
4864 }
4865
22dc4a0f
AN
4866 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4867 btf_vmlinux, *arg_btf_id)) {
a968d5e2 4868 verbose(env, "R%d is of type %s but %s is expected\n",
22dc4a0f
AN
4869 regno, kernel_type_name(reg->btf, reg->btf_id),
4870 kernel_type_name(btf_vmlinux, *arg_btf_id));
a968d5e2
MKL
4871 return -EACCES;
4872 }
4873
4874 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4875 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4876 regno);
4877 return -EACCES;
4878 }
4879 }
4880
4881 return 0;
f79e7ea5
LB
4882}
4883
af7ec138
YS
4884static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4885 struct bpf_call_arg_meta *meta,
4886 const struct bpf_func_proto *fn)
17a52670 4887{
af7ec138 4888 u32 regno = BPF_REG_1 + arg;
638f5b90 4889 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
af7ec138 4890 enum bpf_arg_type arg_type = fn->arg_type[arg];
f79e7ea5 4891 enum bpf_reg_type type = reg->type;
17a52670
AS
4892 int err = 0;
4893
80f1d68c 4894 if (arg_type == ARG_DONTCARE)
17a52670
AS
4895 return 0;
4896
dc503a8a
EC
4897 err = check_reg_arg(env, regno, SRC_OP);
4898 if (err)
4899 return err;
17a52670 4900
1be7f75d
AS
4901 if (arg_type == ARG_ANYTHING) {
4902 if (is_pointer_value(env, regno)) {
61bd5218
JK
4903 verbose(env, "R%d leaks addr into helper function\n",
4904 regno);
1be7f75d
AS
4905 return -EACCES;
4906 }
80f1d68c 4907 return 0;
1be7f75d 4908 }
80f1d68c 4909
de8f3a83 4910 if (type_is_pkt_pointer(type) &&
3a0af8fd 4911 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
61bd5218 4912 verbose(env, "helper access to the packet is not allowed\n");
6841de8b
AS
4913 return -EACCES;
4914 }
4915
912f442c
LB
4916 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4917 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4918 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4919 err = resolve_map_arg_type(env, meta, &arg_type);
4920 if (err)
4921 return err;
4922 }
4923
fd1b0d60
LB
4924 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4925 /* A NULL register has a SCALAR_VALUE type, so skip
4926 * type checking.
4927 */
4928 goto skip_type_check;
4929
a968d5e2 4930 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
f79e7ea5
LB
4931 if (err)
4932 return err;
4933
a968d5e2 4934 if (type == PTR_TO_CTX) {
feec7040
LB
4935 err = check_ctx_reg(env, reg, regno);
4936 if (err < 0)
4937 return err;
d7b9454a
LB
4938 }
4939
fd1b0d60 4940skip_type_check:
02f7c958 4941 if (reg->ref_obj_id) {
457f4436
AN
4942 if (meta->ref_obj_id) {
4943 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4944 regno, reg->ref_obj_id,
4945 meta->ref_obj_id);
4946 return -EFAULT;
4947 }
4948 meta->ref_obj_id = reg->ref_obj_id;
17a52670
AS
4949 }
4950
17a52670
AS
4951 if (arg_type == ARG_CONST_MAP_PTR) {
4952 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
33ff9823 4953 meta->map_ptr = reg->map_ptr;
17a52670
AS
4954 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4955 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4956 * check that [key, key + map->key_size) are within
4957 * stack limits and initialized
4958 */
33ff9823 4959 if (!meta->map_ptr) {
17a52670
AS
4960 /* in function declaration map_ptr must come before
4961 * map_key, so that it's verified and known before
4962 * we have to check map_key here. Otherwise it means
4963 * that kernel subsystem misconfigured verifier
4964 */
61bd5218 4965 verbose(env, "invalid map_ptr to access map->key\n");
17a52670
AS
4966 return -EACCES;
4967 }
d71962f3
PC
4968 err = check_helper_mem_access(env, regno,
4969 meta->map_ptr->key_size, false,
4970 NULL);
2ea864c5 4971 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
6ac99e8f
MKL
4972 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4973 !register_is_null(reg)) ||
2ea864c5 4974 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
17a52670
AS
4975 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4976 * check [value, value + map->value_size) validity
4977 */
33ff9823 4978 if (!meta->map_ptr) {
17a52670 4979 /* kernel subsystem misconfigured verifier */
61bd5218 4980 verbose(env, "invalid map_ptr to access map->value\n");
17a52670
AS
4981 return -EACCES;
4982 }
2ea864c5 4983 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
d71962f3
PC
4984 err = check_helper_mem_access(env, regno,
4985 meta->map_ptr->value_size, false,
2ea864c5 4986 meta);
eaa6bcb7
HL
4987 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4988 if (!reg->btf_id) {
4989 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4990 return -EACCES;
4991 }
22dc4a0f 4992 meta->ret_btf = reg->btf;
eaa6bcb7 4993 meta->ret_btf_id = reg->btf_id;
c18f0b6a
LB
4994 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4995 if (meta->func_id == BPF_FUNC_spin_lock) {
4996 if (process_spin_lock(env, regno, true))
4997 return -EACCES;
4998 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4999 if (process_spin_lock(env, regno, false))
5000 return -EACCES;
5001 } else {
5002 verbose(env, "verifier internal error\n");
5003 return -EFAULT;
5004 }
69c087ba
YS
5005 } else if (arg_type == ARG_PTR_TO_FUNC) {
5006 meta->subprogno = reg->subprogno;
a2bbe7cc
LB
5007 } else if (arg_type_is_mem_ptr(arg_type)) {
5008 /* The access to this pointer is only checked when we hit the
5009 * next is_mem_size argument below.
5010 */
5011 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
90133415 5012 } else if (arg_type_is_mem_size(arg_type)) {
39f19ebb 5013 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
17a52670 5014
10060503
JF
5015 /* This is used to refine r0 return value bounds for helpers
5016 * that enforce this value as an upper bound on return values.
5017 * See do_refine_retval_range() for helpers that can refine
5018 * the return value. C type of helper is u32 so we pull register
5019 * bound from umax_value however, if negative verifier errors
5020 * out. Only upper bounds can be learned because retval is an
5021 * int type and negative retvals are allowed.
849fa506 5022 */
10060503 5023 meta->msize_max_value = reg->umax_value;
849fa506 5024
f1174f77
EC
5025 /* The register is SCALAR_VALUE; the access check
5026 * happens using its boundaries.
06c1c049 5027 */
f1174f77 5028 if (!tnum_is_const(reg->var_off))
06c1c049
GB
5029 /* For unprivileged variable accesses, disable raw
5030 * mode so that the program is required to
5031 * initialize all the memory that the helper could
5032 * just partially fill up.
5033 */
5034 meta = NULL;
5035
b03c9f9f 5036 if (reg->smin_value < 0) {
61bd5218 5037 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
f1174f77
EC
5038 regno);
5039 return -EACCES;
5040 }
06c1c049 5041
b03c9f9f 5042 if (reg->umin_value == 0) {
f1174f77
EC
5043 err = check_helper_mem_access(env, regno - 1, 0,
5044 zero_size_allowed,
5045 meta);
06c1c049
GB
5046 if (err)
5047 return err;
06c1c049 5048 }
f1174f77 5049
b03c9f9f 5050 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
61bd5218 5051 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
f1174f77
EC
5052 regno);
5053 return -EACCES;
5054 }
5055 err = check_helper_mem_access(env, regno - 1,
b03c9f9f 5056 reg->umax_value,
f1174f77 5057 zero_size_allowed, meta);
b5dc0163
AS
5058 if (!err)
5059 err = mark_chain_precision(env, regno);
457f4436
AN
5060 } else if (arg_type_is_alloc_size(arg_type)) {
5061 if (!tnum_is_const(reg->var_off)) {
28a8add6 5062 verbose(env, "R%d is not a known constant'\n",
457f4436
AN
5063 regno);
5064 return -EACCES;
5065 }
5066 meta->mem_size = reg->var_off.value;
57c3bb72
AI
5067 } else if (arg_type_is_int_ptr(arg_type)) {
5068 int size = int_ptr_type_to_size(arg_type);
5069
5070 err = check_helper_mem_access(env, regno, size, false, meta);
5071 if (err)
5072 return err;
5073 err = check_ptr_alignment(env, reg, 0, size, true);
fff13c4b
FR
5074 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5075 struct bpf_map *map = reg->map_ptr;
5076 int map_off;
5077 u64 map_addr;
5078 char *str_ptr;
5079
a8fad73e 5080 if (!bpf_map_is_rdonly(map)) {
fff13c4b
FR
5081 verbose(env, "R%d does not point to a readonly map'\n", regno);
5082 return -EACCES;
5083 }
5084
5085 if (!tnum_is_const(reg->var_off)) {
5086 verbose(env, "R%d is not a constant address'\n", regno);
5087 return -EACCES;
5088 }
5089
5090 if (!map->ops->map_direct_value_addr) {
5091 verbose(env, "no direct value access support for this map type\n");
5092 return -EACCES;
5093 }
5094
5095 err = check_map_access(env, regno, reg->off,
5096 map->value_size - reg->off, false);
5097 if (err)
5098 return err;
5099
5100 map_off = reg->off + reg->var_off.value;
5101 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5102 if (err) {
5103 verbose(env, "direct value access on string failed\n");
5104 return err;
5105 }
5106
5107 str_ptr = (char *)(long)(map_addr);
5108 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5109 verbose(env, "string is not zero-terminated\n");
5110 return -EINVAL;
5111 }
17a52670
AS
5112 }
5113
5114 return err;
5115}
5116
0126240f
LB
5117static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5118{
5119 enum bpf_attach_type eatype = env->prog->expected_attach_type;
7e40781c 5120 enum bpf_prog_type type = resolve_prog_type(env->prog);
0126240f
LB
5121
5122 if (func_id != BPF_FUNC_map_update_elem)
5123 return false;
5124
5125 /* It's not possible to get access to a locked struct sock in these
5126 * contexts, so updating is safe.
5127 */
5128 switch (type) {
5129 case BPF_PROG_TYPE_TRACING:
5130 if (eatype == BPF_TRACE_ITER)
5131 return true;
5132 break;
5133 case BPF_PROG_TYPE_SOCKET_FILTER:
5134 case BPF_PROG_TYPE_SCHED_CLS:
5135 case BPF_PROG_TYPE_SCHED_ACT:
5136 case BPF_PROG_TYPE_XDP:
5137 case BPF_PROG_TYPE_SK_REUSEPORT:
5138 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5139 case BPF_PROG_TYPE_SK_LOOKUP:
5140 return true;
5141 default:
5142 break;
5143 }
5144
5145 verbose(env, "cannot update sockmap in this context\n");
5146 return false;
5147}
5148
e411901c
MF
5149static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5150{
5151 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5152}
5153
61bd5218
JK
5154static int check_map_func_compatibility(struct bpf_verifier_env *env,
5155 struct bpf_map *map, int func_id)
35578d79 5156{
35578d79
KX
5157 if (!map)
5158 return 0;
5159
6aff67c8
AS
5160 /* We need a two way check, first is from map perspective ... */
5161 switch (map->map_type) {
5162 case BPF_MAP_TYPE_PROG_ARRAY:
5163 if (func_id != BPF_FUNC_tail_call)
5164 goto error;
5165 break;
5166 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5167 if (func_id != BPF_FUNC_perf_event_read &&
908432ca 5168 func_id != BPF_FUNC_perf_event_output &&
a7658e1a 5169 func_id != BPF_FUNC_skb_output &&
d831ee84
EC
5170 func_id != BPF_FUNC_perf_event_read_value &&
5171 func_id != BPF_FUNC_xdp_output)
6aff67c8
AS
5172 goto error;
5173 break;
457f4436
AN
5174 case BPF_MAP_TYPE_RINGBUF:
5175 if (func_id != BPF_FUNC_ringbuf_output &&
5176 func_id != BPF_FUNC_ringbuf_reserve &&
5177 func_id != BPF_FUNC_ringbuf_submit &&
5178 func_id != BPF_FUNC_ringbuf_discard &&
5179 func_id != BPF_FUNC_ringbuf_query)
5180 goto error;
5181 break;
6aff67c8
AS
5182 case BPF_MAP_TYPE_STACK_TRACE:
5183 if (func_id != BPF_FUNC_get_stackid)
5184 goto error;
5185 break;
4ed8ec52 5186 case BPF_MAP_TYPE_CGROUP_ARRAY:
60747ef4 5187 if (func_id != BPF_FUNC_skb_under_cgroup &&
60d20f91 5188 func_id != BPF_FUNC_current_task_under_cgroup)
4a482f34
MKL
5189 goto error;
5190 break;
cd339431 5191 case BPF_MAP_TYPE_CGROUP_STORAGE:
b741f163 5192 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
cd339431
RG
5193 if (func_id != BPF_FUNC_get_local_storage)
5194 goto error;
5195 break;
546ac1ff 5196 case BPF_MAP_TYPE_DEVMAP:
6f9d451a 5197 case BPF_MAP_TYPE_DEVMAP_HASH:
0cdbb4b0
THJ
5198 if (func_id != BPF_FUNC_redirect_map &&
5199 func_id != BPF_FUNC_map_lookup_elem)
546ac1ff
JF
5200 goto error;
5201 break;
fbfc504a
BT
5202 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5203 * appear.
5204 */
6710e112
JDB
5205 case BPF_MAP_TYPE_CPUMAP:
5206 if (func_id != BPF_FUNC_redirect_map)
5207 goto error;
5208 break;
fada7fdc
JL
5209 case BPF_MAP_TYPE_XSKMAP:
5210 if (func_id != BPF_FUNC_redirect_map &&
5211 func_id != BPF_FUNC_map_lookup_elem)
5212 goto error;
5213 break;
56f668df 5214 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
bcc6b1b7 5215 case BPF_MAP_TYPE_HASH_OF_MAPS:
56f668df
MKL
5216 if (func_id != BPF_FUNC_map_lookup_elem)
5217 goto error;
16a43625 5218 break;
174a79ff
JF
5219 case BPF_MAP_TYPE_SOCKMAP:
5220 if (func_id != BPF_FUNC_sk_redirect_map &&
5221 func_id != BPF_FUNC_sock_map_update &&
4f738adb 5222 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5223 func_id != BPF_FUNC_msg_redirect_map &&
64d85290 5224 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5225 func_id != BPF_FUNC_map_lookup_elem &&
5226 !may_update_sockmap(env, func_id))
174a79ff
JF
5227 goto error;
5228 break;
81110384
JF
5229 case BPF_MAP_TYPE_SOCKHASH:
5230 if (func_id != BPF_FUNC_sk_redirect_hash &&
5231 func_id != BPF_FUNC_sock_hash_update &&
5232 func_id != BPF_FUNC_map_delete_elem &&
9fed9000 5233 func_id != BPF_FUNC_msg_redirect_hash &&
64d85290 5234 func_id != BPF_FUNC_sk_select_reuseport &&
0126240f
LB
5235 func_id != BPF_FUNC_map_lookup_elem &&
5236 !may_update_sockmap(env, func_id))
81110384
JF
5237 goto error;
5238 break;
2dbb9b9e
MKL
5239 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5240 if (func_id != BPF_FUNC_sk_select_reuseport)
5241 goto error;
5242 break;
f1a2e44a
MV
5243 case BPF_MAP_TYPE_QUEUE:
5244 case BPF_MAP_TYPE_STACK:
5245 if (func_id != BPF_FUNC_map_peek_elem &&
5246 func_id != BPF_FUNC_map_pop_elem &&
5247 func_id != BPF_FUNC_map_push_elem)
5248 goto error;
5249 break;
6ac99e8f
MKL
5250 case BPF_MAP_TYPE_SK_STORAGE:
5251 if (func_id != BPF_FUNC_sk_storage_get &&
5252 func_id != BPF_FUNC_sk_storage_delete)
5253 goto error;
5254 break;
8ea63684
KS
5255 case BPF_MAP_TYPE_INODE_STORAGE:
5256 if (func_id != BPF_FUNC_inode_storage_get &&
5257 func_id != BPF_FUNC_inode_storage_delete)
5258 goto error;
5259 break;
4cf1bc1f
KS
5260 case BPF_MAP_TYPE_TASK_STORAGE:
5261 if (func_id != BPF_FUNC_task_storage_get &&
5262 func_id != BPF_FUNC_task_storage_delete)
5263 goto error;
5264 break;
6aff67c8
AS
5265 default:
5266 break;
5267 }
5268
5269 /* ... and second from the function itself. */
5270 switch (func_id) {
5271 case BPF_FUNC_tail_call:
5272 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5273 goto error;
e411901c
MF
5274 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5275 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
f4d7e40a
AS
5276 return -EINVAL;
5277 }
6aff67c8
AS
5278 break;
5279 case BPF_FUNC_perf_event_read:
5280 case BPF_FUNC_perf_event_output:
908432ca 5281 case BPF_FUNC_perf_event_read_value:
a7658e1a 5282 case BPF_FUNC_skb_output:
d831ee84 5283 case BPF_FUNC_xdp_output:
6aff67c8
AS
5284 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5285 goto error;
5286 break;
5287 case BPF_FUNC_get_stackid:
5288 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5289 goto error;
5290 break;
60d20f91 5291 case BPF_FUNC_current_task_under_cgroup:
747ea55e 5292 case BPF_FUNC_skb_under_cgroup:
4a482f34
MKL
5293 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5294 goto error;
5295 break;
97f91a7c 5296 case BPF_FUNC_redirect_map:
9c270af3 5297 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
6f9d451a 5298 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
fbfc504a
BT
5299 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5300 map->map_type != BPF_MAP_TYPE_XSKMAP)
97f91a7c
JF
5301 goto error;
5302 break;
174a79ff 5303 case BPF_FUNC_sk_redirect_map:
4f738adb 5304 case BPF_FUNC_msg_redirect_map:
81110384 5305 case BPF_FUNC_sock_map_update:
174a79ff
JF
5306 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5307 goto error;
5308 break;
81110384
JF
5309 case BPF_FUNC_sk_redirect_hash:
5310 case BPF_FUNC_msg_redirect_hash:
5311 case BPF_FUNC_sock_hash_update:
5312 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
174a79ff
JF
5313 goto error;
5314 break;
cd339431 5315 case BPF_FUNC_get_local_storage:
b741f163
RG
5316 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5317 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
cd339431
RG
5318 goto error;
5319 break;
2dbb9b9e 5320 case BPF_FUNC_sk_select_reuseport:
9fed9000
JS
5321 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5322 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5323 map->map_type != BPF_MAP_TYPE_SOCKHASH)
2dbb9b9e
MKL
5324 goto error;
5325 break;
f1a2e44a
MV
5326 case BPF_FUNC_map_peek_elem:
5327 case BPF_FUNC_map_pop_elem:
5328 case BPF_FUNC_map_push_elem:
5329 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5330 map->map_type != BPF_MAP_TYPE_STACK)
5331 goto error;
5332 break;
6ac99e8f
MKL
5333 case BPF_FUNC_sk_storage_get:
5334 case BPF_FUNC_sk_storage_delete:
5335 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5336 goto error;
5337 break;
8ea63684
KS
5338 case BPF_FUNC_inode_storage_get:
5339 case BPF_FUNC_inode_storage_delete:
5340 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5341 goto error;
5342 break;
4cf1bc1f
KS
5343 case BPF_FUNC_task_storage_get:
5344 case BPF_FUNC_task_storage_delete:
5345 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5346 goto error;
5347 break;
6aff67c8
AS
5348 default:
5349 break;
35578d79
KX
5350 }
5351
5352 return 0;
6aff67c8 5353error:
61bd5218 5354 verbose(env, "cannot pass map_type %d into func %s#%d\n",
ebb676da 5355 map->map_type, func_id_name(func_id), func_id);
6aff67c8 5356 return -EINVAL;
35578d79
KX
5357}
5358
90133415 5359static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
435faee1
DB
5360{
5361 int count = 0;
5362
39f19ebb 5363 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5364 count++;
39f19ebb 5365 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5366 count++;
39f19ebb 5367 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5368 count++;
39f19ebb 5369 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
435faee1 5370 count++;
39f19ebb 5371 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
435faee1
DB
5372 count++;
5373
90133415
DB
5374 /* We only support one arg being in raw mode at the moment,
5375 * which is sufficient for the helper functions we have
5376 * right now.
5377 */
5378 return count <= 1;
5379}
5380
5381static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5382 enum bpf_arg_type arg_next)
5383{
5384 return (arg_type_is_mem_ptr(arg_curr) &&
5385 !arg_type_is_mem_size(arg_next)) ||
5386 (!arg_type_is_mem_ptr(arg_curr) &&
5387 arg_type_is_mem_size(arg_next));
5388}
5389
5390static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5391{
5392 /* bpf_xxx(..., buf, len) call will access 'len'
5393 * bytes from memory 'buf'. Both arg types need
5394 * to be paired, so make sure there's no buggy
5395 * helper function specification.
5396 */
5397 if (arg_type_is_mem_size(fn->arg1_type) ||
5398 arg_type_is_mem_ptr(fn->arg5_type) ||
5399 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5400 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5401 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5402 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5403 return false;
5404
5405 return true;
5406}
5407
1b986589 5408static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
fd978bf7
JS
5409{
5410 int count = 0;
5411
1b986589 5412 if (arg_type_may_be_refcounted(fn->arg1_type))
fd978bf7 5413 count++;
1b986589 5414 if (arg_type_may_be_refcounted(fn->arg2_type))
fd978bf7 5415 count++;
1b986589 5416 if (arg_type_may_be_refcounted(fn->arg3_type))
fd978bf7 5417 count++;
1b986589 5418 if (arg_type_may_be_refcounted(fn->arg4_type))
fd978bf7 5419 count++;
1b986589 5420 if (arg_type_may_be_refcounted(fn->arg5_type))
fd978bf7
JS
5421 count++;
5422
1b986589
MKL
5423 /* A reference acquiring function cannot acquire
5424 * another refcounted ptr.
5425 */
64d85290 5426 if (may_be_acquire_function(func_id) && count)
1b986589
MKL
5427 return false;
5428
fd978bf7
JS
5429 /* We only support one arg being unreferenced at the moment,
5430 * which is sufficient for the helper functions we have right now.
5431 */
5432 return count <= 1;
5433}
5434
9436ef6e
LB
5435static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5436{
5437 int i;
5438
1df8f55a 5439 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9436ef6e
LB
5440 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5441 return false;
5442
1df8f55a
MKL
5443 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5444 return false;
5445 }
5446
9436ef6e
LB
5447 return true;
5448}
5449
1b986589 5450static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
90133415
DB
5451{
5452 return check_raw_mode_ok(fn) &&
fd978bf7 5453 check_arg_pair_ok(fn) &&
9436ef6e 5454 check_btf_id_ok(fn) &&
1b986589 5455 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
435faee1
DB
5456}
5457
de8f3a83
DB
5458/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5459 * are now invalid, so turn them into unknown SCALAR_VALUE.
f1174f77 5460 */
f4d7e40a
AS
5461static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5462 struct bpf_func_state *state)
969bf05e 5463{
58e2af8b 5464 struct bpf_reg_state *regs = state->regs, *reg;
969bf05e
AS
5465 int i;
5466
5467 for (i = 0; i < MAX_BPF_REG; i++)
de8f3a83 5468 if (reg_is_pkt_pointer_any(&regs[i]))
61bd5218 5469 mark_reg_unknown(env, regs, i);
969bf05e 5470
f3709f69
JS
5471 bpf_for_each_spilled_reg(i, state, reg) {
5472 if (!reg)
969bf05e 5473 continue;
de8f3a83 5474 if (reg_is_pkt_pointer_any(reg))
f54c7898 5475 __mark_reg_unknown(env, reg);
969bf05e
AS
5476 }
5477}
5478
f4d7e40a
AS
5479static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5480{
5481 struct bpf_verifier_state *vstate = env->cur_state;
5482 int i;
5483
5484 for (i = 0; i <= vstate->curframe; i++)
5485 __clear_all_pkt_pointers(env, vstate->frame[i]);
5486}
5487
6d94e741
AS
5488enum {
5489 AT_PKT_END = -1,
5490 BEYOND_PKT_END = -2,
5491};
5492
5493static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5494{
5495 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5496 struct bpf_reg_state *reg = &state->regs[regn];
5497
5498 if (reg->type != PTR_TO_PACKET)
5499 /* PTR_TO_PACKET_META is not supported yet */
5500 return;
5501
5502 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5503 * How far beyond pkt_end it goes is unknown.
5504 * if (!range_open) it's the case of pkt >= pkt_end
5505 * if (range_open) it's the case of pkt > pkt_end
5506 * hence this pointer is at least 1 byte bigger than pkt_end
5507 */
5508 if (range_open)
5509 reg->range = BEYOND_PKT_END;
5510 else
5511 reg->range = AT_PKT_END;
5512}
5513
fd978bf7 5514static void release_reg_references(struct bpf_verifier_env *env,
1b986589
MKL
5515 struct bpf_func_state *state,
5516 int ref_obj_id)
fd978bf7
JS
5517{
5518 struct bpf_reg_state *regs = state->regs, *reg;
5519 int i;
5520
5521 for (i = 0; i < MAX_BPF_REG; i++)
1b986589 5522 if (regs[i].ref_obj_id == ref_obj_id)
fd978bf7
JS
5523 mark_reg_unknown(env, regs, i);
5524
5525 bpf_for_each_spilled_reg(i, state, reg) {
5526 if (!reg)
5527 continue;
1b986589 5528 if (reg->ref_obj_id == ref_obj_id)
f54c7898 5529 __mark_reg_unknown(env, reg);
fd978bf7
JS
5530 }
5531}
5532
5533/* The pointer with the specified id has released its reference to kernel
5534 * resources. Identify all copies of the same pointer and clear the reference.
5535 */
5536static int release_reference(struct bpf_verifier_env *env,
1b986589 5537 int ref_obj_id)
fd978bf7
JS
5538{
5539 struct bpf_verifier_state *vstate = env->cur_state;
1b986589 5540 int err;
fd978bf7
JS
5541 int i;
5542
1b986589
MKL
5543 err = release_reference_state(cur_func(env), ref_obj_id);
5544 if (err)
5545 return err;
5546
fd978bf7 5547 for (i = 0; i <= vstate->curframe; i++)
1b986589 5548 release_reg_references(env, vstate->frame[i], ref_obj_id);
fd978bf7 5549
1b986589 5550 return 0;
fd978bf7
JS
5551}
5552
51c39bb1
AS
5553static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5554 struct bpf_reg_state *regs)
5555{
5556 int i;
5557
5558 /* after the call registers r0 - r5 were scratched */
5559 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5560 mark_reg_not_init(env, regs, caller_saved[i]);
5561 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5562 }
5563}
5564
14351375
YS
5565typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5566 struct bpf_func_state *caller,
5567 struct bpf_func_state *callee,
5568 int insn_idx);
5569
5570static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5571 int *insn_idx, int subprog,
5572 set_callee_state_fn set_callee_state_cb)
f4d7e40a
AS
5573{
5574 struct bpf_verifier_state *state = env->cur_state;
51c39bb1 5575 struct bpf_func_info_aux *func_info_aux;
f4d7e40a 5576 struct bpf_func_state *caller, *callee;
14351375 5577 int err;
51c39bb1 5578 bool is_global = false;
f4d7e40a 5579
aada9ce6 5580 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
f4d7e40a 5581 verbose(env, "the call stack of %d frames is too deep\n",
aada9ce6 5582 state->curframe + 2);
f4d7e40a
AS
5583 return -E2BIG;
5584 }
5585
f4d7e40a
AS
5586 caller = state->frame[state->curframe];
5587 if (state->frame[state->curframe + 1]) {
5588 verbose(env, "verifier bug. Frame %d already allocated\n",
5589 state->curframe + 1);
5590 return -EFAULT;
5591 }
5592
51c39bb1
AS
5593 func_info_aux = env->prog->aux->func_info_aux;
5594 if (func_info_aux)
5595 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
34747c41 5596 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
51c39bb1
AS
5597 if (err == -EFAULT)
5598 return err;
5599 if (is_global) {
5600 if (err) {
5601 verbose(env, "Caller passes invalid args into func#%d\n",
5602 subprog);
5603 return err;
5604 } else {
5605 if (env->log.level & BPF_LOG_LEVEL)
5606 verbose(env,
5607 "Func#%d is global and valid. Skipping.\n",
5608 subprog);
5609 clear_caller_saved_regs(env, caller->regs);
5610
45159b27 5611 /* All global functions return a 64-bit SCALAR_VALUE */
51c39bb1 5612 mark_reg_unknown(env, caller->regs, BPF_REG_0);
45159b27 5613 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
51c39bb1
AS
5614
5615 /* continue with next insn after call */
5616 return 0;
5617 }
5618 }
5619
f4d7e40a
AS
5620 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5621 if (!callee)
5622 return -ENOMEM;
5623 state->frame[state->curframe + 1] = callee;
5624
5625 /* callee cannot access r0, r6 - r9 for reading and has to write
5626 * into its own stack before reading from it.
5627 * callee can read/write into caller's stack
5628 */
5629 init_func_state(env, callee,
5630 /* remember the callsite, it will be used by bpf_exit */
5631 *insn_idx /* callsite */,
5632 state->curframe + 1 /* frameno within this callchain */,
f910cefa 5633 subprog /* subprog number within this prog */);
f4d7e40a 5634
fd978bf7 5635 /* Transfer references to the callee */
c69431aa 5636 err = copy_reference_state(callee, caller);
fd978bf7
JS
5637 if (err)
5638 return err;
5639
14351375
YS
5640 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5641 if (err)
5642 return err;
f4d7e40a 5643
51c39bb1 5644 clear_caller_saved_regs(env, caller->regs);
f4d7e40a
AS
5645
5646 /* only increment it after check_reg_arg() finished */
5647 state->curframe++;
5648
5649 /* and go analyze first insn of the callee */
14351375 5650 *insn_idx = env->subprog_info[subprog].start - 1;
f4d7e40a 5651
06ee7115 5652 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5653 verbose(env, "caller:\n");
5654 print_verifier_state(env, caller);
5655 verbose(env, "callee:\n");
5656 print_verifier_state(env, callee);
5657 }
5658 return 0;
5659}
5660
314ee05e
YS
5661int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5662 struct bpf_func_state *caller,
5663 struct bpf_func_state *callee)
5664{
5665 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5666 * void *callback_ctx, u64 flags);
5667 * callback_fn(struct bpf_map *map, void *key, void *value,
5668 * void *callback_ctx);
5669 */
5670 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5671
5672 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5673 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5674 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5675
5676 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5677 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5678 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5679
5680 /* pointer to stack or null */
5681 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5682
5683 /* unused */
5684 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5685 return 0;
5686}
5687
14351375
YS
5688static int set_callee_state(struct bpf_verifier_env *env,
5689 struct bpf_func_state *caller,
5690 struct bpf_func_state *callee, int insn_idx)
5691{
5692 int i;
5693
5694 /* copy r1 - r5 args that callee can access. The copy includes parent
5695 * pointers, which connects us up to the liveness chain
5696 */
5697 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5698 callee->regs[i] = caller->regs[i];
5699 return 0;
5700}
5701
5702static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5703 int *insn_idx)
5704{
5705 int subprog, target_insn;
5706
5707 target_insn = *insn_idx + insn->imm + 1;
5708 subprog = find_subprog(env, target_insn);
5709 if (subprog < 0) {
5710 verbose(env, "verifier bug. No program starts at insn %d\n",
5711 target_insn);
5712 return -EFAULT;
5713 }
5714
5715 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5716}
5717
69c087ba
YS
5718static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5719 struct bpf_func_state *caller,
5720 struct bpf_func_state *callee,
5721 int insn_idx)
5722{
5723 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5724 struct bpf_map *map;
5725 int err;
5726
5727 if (bpf_map_ptr_poisoned(insn_aux)) {
5728 verbose(env, "tail_call abusing map_ptr\n");
5729 return -EINVAL;
5730 }
5731
5732 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5733 if (!map->ops->map_set_for_each_callback_args ||
5734 !map->ops->map_for_each_callback) {
5735 verbose(env, "callback function not allowed for map\n");
5736 return -ENOTSUPP;
5737 }
5738
5739 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5740 if (err)
5741 return err;
5742
5743 callee->in_callback_fn = true;
5744 return 0;
5745}
5746
f4d7e40a
AS
5747static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5748{
5749 struct bpf_verifier_state *state = env->cur_state;
5750 struct bpf_func_state *caller, *callee;
5751 struct bpf_reg_state *r0;
fd978bf7 5752 int err;
f4d7e40a
AS
5753
5754 callee = state->frame[state->curframe];
5755 r0 = &callee->regs[BPF_REG_0];
5756 if (r0->type == PTR_TO_STACK) {
5757 /* technically it's ok to return caller's stack pointer
5758 * (or caller's caller's pointer) back to the caller,
5759 * since these pointers are valid. Only current stack
5760 * pointer will be invalid as soon as function exits,
5761 * but let's be conservative
5762 */
5763 verbose(env, "cannot return stack pointer to the caller\n");
5764 return -EINVAL;
5765 }
5766
5767 state->curframe--;
5768 caller = state->frame[state->curframe];
69c087ba
YS
5769 if (callee->in_callback_fn) {
5770 /* enforce R0 return value range [0, 1]. */
5771 struct tnum range = tnum_range(0, 1);
5772
5773 if (r0->type != SCALAR_VALUE) {
5774 verbose(env, "R0 not a scalar value\n");
5775 return -EACCES;
5776 }
5777 if (!tnum_in(range, r0->var_off)) {
5778 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5779 return -EINVAL;
5780 }
5781 } else {
5782 /* return to the caller whatever r0 had in the callee */
5783 caller->regs[BPF_REG_0] = *r0;
5784 }
f4d7e40a 5785
fd978bf7 5786 /* Transfer references to the caller */
c69431aa 5787 err = copy_reference_state(caller, callee);
fd978bf7
JS
5788 if (err)
5789 return err;
5790
f4d7e40a 5791 *insn_idx = callee->callsite + 1;
06ee7115 5792 if (env->log.level & BPF_LOG_LEVEL) {
f4d7e40a
AS
5793 verbose(env, "returning from callee:\n");
5794 print_verifier_state(env, callee);
5795 verbose(env, "to caller at %d:\n", *insn_idx);
5796 print_verifier_state(env, caller);
5797 }
5798 /* clear everything in the callee */
5799 free_func_state(callee);
5800 state->frame[state->curframe + 1] = NULL;
5801 return 0;
5802}
5803
849fa506
YS
5804static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5805 int func_id,
5806 struct bpf_call_arg_meta *meta)
5807{
5808 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5809
5810 if (ret_type != RET_INTEGER ||
5811 (func_id != BPF_FUNC_get_stack &&
fd0b88f7 5812 func_id != BPF_FUNC_get_task_stack &&
47cc0ed5
DB
5813 func_id != BPF_FUNC_probe_read_str &&
5814 func_id != BPF_FUNC_probe_read_kernel_str &&
5815 func_id != BPF_FUNC_probe_read_user_str))
849fa506
YS
5816 return;
5817
10060503 5818 ret_reg->smax_value = meta->msize_max_value;
fa123ac0 5819 ret_reg->s32_max_value = meta->msize_max_value;
b0270958
AS
5820 ret_reg->smin_value = -MAX_ERRNO;
5821 ret_reg->s32_min_value = -MAX_ERRNO;
849fa506
YS
5822 __reg_deduce_bounds(ret_reg);
5823 __reg_bound_offset(ret_reg);
10060503 5824 __update_reg_bounds(ret_reg);
849fa506
YS
5825}
5826
c93552c4
DB
5827static int
5828record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5829 int func_id, int insn_idx)
5830{
5831 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
591fe988 5832 struct bpf_map *map = meta->map_ptr;
c93552c4
DB
5833
5834 if (func_id != BPF_FUNC_tail_call &&
09772d92
DB
5835 func_id != BPF_FUNC_map_lookup_elem &&
5836 func_id != BPF_FUNC_map_update_elem &&
f1a2e44a
MV
5837 func_id != BPF_FUNC_map_delete_elem &&
5838 func_id != BPF_FUNC_map_push_elem &&
5839 func_id != BPF_FUNC_map_pop_elem &&
69c087ba 5840 func_id != BPF_FUNC_map_peek_elem &&
e6a4750f
BT
5841 func_id != BPF_FUNC_for_each_map_elem &&
5842 func_id != BPF_FUNC_redirect_map)
c93552c4 5843 return 0;
09772d92 5844
591fe988 5845 if (map == NULL) {
c93552c4
DB
5846 verbose(env, "kernel subsystem misconfigured verifier\n");
5847 return -EINVAL;
5848 }
5849
591fe988
DB
5850 /* In case of read-only, some additional restrictions
5851 * need to be applied in order to prevent altering the
5852 * state of the map from program side.
5853 */
5854 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5855 (func_id == BPF_FUNC_map_delete_elem ||
5856 func_id == BPF_FUNC_map_update_elem ||
5857 func_id == BPF_FUNC_map_push_elem ||
5858 func_id == BPF_FUNC_map_pop_elem)) {
5859 verbose(env, "write into map forbidden\n");
5860 return -EACCES;
5861 }
5862
d2e4c1e6 5863 if (!BPF_MAP_PTR(aux->map_ptr_state))
c93552c4 5864 bpf_map_ptr_store(aux, meta->map_ptr,
2c78ee89 5865 !meta->map_ptr->bypass_spec_v1);
d2e4c1e6 5866 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
c93552c4 5867 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
2c78ee89 5868 !meta->map_ptr->bypass_spec_v1);
c93552c4
DB
5869 return 0;
5870}
5871
d2e4c1e6
DB
5872static int
5873record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5874 int func_id, int insn_idx)
5875{
5876 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5877 struct bpf_reg_state *regs = cur_regs(env), *reg;
5878 struct bpf_map *map = meta->map_ptr;
5879 struct tnum range;
5880 u64 val;
cc52d914 5881 int err;
d2e4c1e6
DB
5882
5883 if (func_id != BPF_FUNC_tail_call)
5884 return 0;
5885 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5886 verbose(env, "kernel subsystem misconfigured verifier\n");
5887 return -EINVAL;
5888 }
5889
5890 range = tnum_range(0, map->max_entries - 1);
5891 reg = &regs[BPF_REG_3];
5892
5893 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5894 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5895 return 0;
5896 }
5897
cc52d914
DB
5898 err = mark_chain_precision(env, BPF_REG_3);
5899 if (err)
5900 return err;
5901
d2e4c1e6
DB
5902 val = reg->var_off.value;
5903 if (bpf_map_key_unseen(aux))
5904 bpf_map_key_store(aux, val);
5905 else if (!bpf_map_key_poisoned(aux) &&
5906 bpf_map_key_immediate(aux) != val)
5907 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5908 return 0;
5909}
5910
fd978bf7
JS
5911static int check_reference_leak(struct bpf_verifier_env *env)
5912{
5913 struct bpf_func_state *state = cur_func(env);
5914 int i;
5915
5916 for (i = 0; i < state->acquired_refs; i++) {
5917 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5918 state->refs[i].id, state->refs[i].insn_idx);
5919 }
5920 return state->acquired_refs ? -EINVAL : 0;
5921}
5922
7b15523a
FR
5923static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5924 struct bpf_reg_state *regs)
5925{
5926 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5927 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5928 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5929 int err, fmt_map_off, num_args;
5930 u64 fmt_addr;
5931 char *fmt;
5932
5933 /* data must be an array of u64 */
5934 if (data_len_reg->var_off.value % 8)
5935 return -EINVAL;
5936 num_args = data_len_reg->var_off.value / 8;
5937
5938 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5939 * and map_direct_value_addr is set.
5940 */
5941 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5942 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5943 fmt_map_off);
8e8ee109
FR
5944 if (err) {
5945 verbose(env, "verifier bug\n");
5946 return -EFAULT;
5947 }
7b15523a
FR
5948 fmt = (char *)(long)fmt_addr + fmt_map_off;
5949
5950 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5951 * can focus on validating the format specifiers.
5952 */
48cac3f4 5953 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
7b15523a
FR
5954 if (err < 0)
5955 verbose(env, "Invalid format string\n");
5956
5957 return err;
5958}
5959
69c087ba
YS
5960static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5961 int *insn_idx_p)
17a52670 5962{
17a52670 5963 const struct bpf_func_proto *fn = NULL;
638f5b90 5964 struct bpf_reg_state *regs;
33ff9823 5965 struct bpf_call_arg_meta meta;
69c087ba 5966 int insn_idx = *insn_idx_p;
969bf05e 5967 bool changes_data;
69c087ba 5968 int i, err, func_id;
17a52670
AS
5969
5970 /* find function prototype */
69c087ba 5971 func_id = insn->imm;
17a52670 5972 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
61bd5218
JK
5973 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5974 func_id);
17a52670
AS
5975 return -EINVAL;
5976 }
5977
00176a34 5978 if (env->ops->get_func_proto)
5e43f899 5979 fn = env->ops->get_func_proto(func_id, env->prog);
17a52670 5980 if (!fn) {
61bd5218
JK
5981 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5982 func_id);
17a52670
AS
5983 return -EINVAL;
5984 }
5985
5986 /* eBPF programs must be GPL compatible to use GPL-ed functions */
24701ece 5987 if (!env->prog->gpl_compatible && fn->gpl_only) {
3fe2867c 5988 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
17a52670
AS
5989 return -EINVAL;
5990 }
5991
eae2e83e
JO
5992 if (fn->allowed && !fn->allowed(env->prog)) {
5993 verbose(env, "helper call is not allowed in probe\n");
5994 return -EINVAL;
5995 }
5996
04514d13 5997 /* With LD_ABS/IND some JITs save/restore skb from r1. */
17bedab2 5998 changes_data = bpf_helper_changes_pkt_data(fn->func);
04514d13
DB
5999 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6000 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6001 func_id_name(func_id), func_id);
6002 return -EINVAL;
6003 }
969bf05e 6004
33ff9823 6005 memset(&meta, 0, sizeof(meta));
36bbef52 6006 meta.pkt_access = fn->pkt_access;
33ff9823 6007
1b986589 6008 err = check_func_proto(fn, func_id);
435faee1 6009 if (err) {
61bd5218 6010 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
ebb676da 6011 func_id_name(func_id), func_id);
435faee1
DB
6012 return err;
6013 }
6014
d83525ca 6015 meta.func_id = func_id;
17a52670 6016 /* check args */
523a4cf4 6017 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
af7ec138 6018 err = check_func_arg(env, i, &meta, fn);
a7658e1a
AS
6019 if (err)
6020 return err;
6021 }
17a52670 6022
c93552c4
DB
6023 err = record_func_map(env, &meta, func_id, insn_idx);
6024 if (err)
6025 return err;
6026
d2e4c1e6
DB
6027 err = record_func_key(env, &meta, func_id, insn_idx);
6028 if (err)
6029 return err;
6030
435faee1
DB
6031 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6032 * is inferred from register state.
6033 */
6034 for (i = 0; i < meta.access_size; i++) {
ca369602
DB
6035 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6036 BPF_WRITE, -1, false);
435faee1
DB
6037 if (err)
6038 return err;
6039 }
6040
fd978bf7
JS
6041 if (func_id == BPF_FUNC_tail_call) {
6042 err = check_reference_leak(env);
6043 if (err) {
6044 verbose(env, "tail_call would lead to reference leak\n");
6045 return err;
6046 }
6047 } else if (is_release_function(func_id)) {
1b986589 6048 err = release_reference(env, meta.ref_obj_id);
46f8bc92
MKL
6049 if (err) {
6050 verbose(env, "func %s#%d reference has not been acquired before\n",
6051 func_id_name(func_id), func_id);
fd978bf7 6052 return err;
46f8bc92 6053 }
fd978bf7
JS
6054 }
6055
638f5b90 6056 regs = cur_regs(env);
cd339431
RG
6057
6058 /* check that flags argument in get_local_storage(map, flags) is 0,
6059 * this is required because get_local_storage() can't return an error.
6060 */
6061 if (func_id == BPF_FUNC_get_local_storage &&
6062 !register_is_null(&regs[BPF_REG_2])) {
6063 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6064 return -EINVAL;
6065 }
6066
69c087ba
YS
6067 if (func_id == BPF_FUNC_for_each_map_elem) {
6068 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6069 set_map_elem_callback_state);
6070 if (err < 0)
6071 return -EINVAL;
6072 }
6073
7b15523a
FR
6074 if (func_id == BPF_FUNC_snprintf) {
6075 err = check_bpf_snprintf_call(env, regs);
6076 if (err < 0)
6077 return err;
6078 }
6079
17a52670 6080 /* reset caller saved regs */
dc503a8a 6081 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 6082 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
6083 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6084 }
17a52670 6085
5327ed3d
JW
6086 /* helper call returns 64-bit value. */
6087 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6088
dc503a8a 6089 /* update return register (already marked as written above) */
17a52670 6090 if (fn->ret_type == RET_INTEGER) {
f1174f77 6091 /* sets type to SCALAR_VALUE */
61bd5218 6092 mark_reg_unknown(env, regs, BPF_REG_0);
17a52670
AS
6093 } else if (fn->ret_type == RET_VOID) {
6094 regs[BPF_REG_0].type = NOT_INIT;
3e6a4b3e
RG
6095 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6096 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
f1174f77 6097 /* There is no offset yet applied, variable or fixed */
61bd5218 6098 mark_reg_known_zero(env, regs, BPF_REG_0);
17a52670
AS
6099 /* remember map_ptr, so that check_map_access()
6100 * can check 'value_size' boundary of memory access
6101 * to map element returned from bpf_map_lookup_elem()
6102 */
33ff9823 6103 if (meta.map_ptr == NULL) {
61bd5218
JK
6104 verbose(env,
6105 "kernel subsystem misconfigured verifier\n");
17a52670
AS
6106 return -EINVAL;
6107 }
33ff9823 6108 regs[BPF_REG_0].map_ptr = meta.map_ptr;
4d31f301
DB
6109 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6110 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
e16d2f1a
AS
6111 if (map_value_has_spin_lock(meta.map_ptr))
6112 regs[BPF_REG_0].id = ++env->id_gen;
4d31f301
DB
6113 } else {
6114 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
4d31f301 6115 }
c64b7983
JS
6116 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6117 mark_reg_known_zero(env, regs, BPF_REG_0);
6118 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
85a51f8c
LB
6119 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6120 mark_reg_known_zero(env, regs, BPF_REG_0);
6121 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
655a51e5
MKL
6122 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6123 mark_reg_known_zero(env, regs, BPF_REG_0);
6124 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
457f4436
AN
6125 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6126 mark_reg_known_zero(env, regs, BPF_REG_0);
6127 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
457f4436 6128 regs[BPF_REG_0].mem_size = meta.mem_size;
63d9b80d
HL
6129 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6130 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
eaa6bcb7
HL
6131 const struct btf_type *t;
6132
6133 mark_reg_known_zero(env, regs, BPF_REG_0);
22dc4a0f 6134 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
eaa6bcb7
HL
6135 if (!btf_type_is_struct(t)) {
6136 u32 tsize;
6137 const struct btf_type *ret;
6138 const char *tname;
6139
6140 /* resolve the type size of ksym. */
22dc4a0f 6141 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
eaa6bcb7 6142 if (IS_ERR(ret)) {
22dc4a0f 6143 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
eaa6bcb7
HL
6144 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6145 tname, PTR_ERR(ret));
6146 return -EINVAL;
6147 }
63d9b80d
HL
6148 regs[BPF_REG_0].type =
6149 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6150 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
eaa6bcb7
HL
6151 regs[BPF_REG_0].mem_size = tsize;
6152 } else {
63d9b80d
HL
6153 regs[BPF_REG_0].type =
6154 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6155 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
22dc4a0f 6156 regs[BPF_REG_0].btf = meta.ret_btf;
eaa6bcb7
HL
6157 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6158 }
3ca1032a
KS
6159 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6160 fn->ret_type == RET_PTR_TO_BTF_ID) {
af7ec138
YS
6161 int ret_btf_id;
6162
6163 mark_reg_known_zero(env, regs, BPF_REG_0);
3ca1032a
KS
6164 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6165 PTR_TO_BTF_ID :
6166 PTR_TO_BTF_ID_OR_NULL;
af7ec138
YS
6167 ret_btf_id = *fn->ret_btf_id;
6168 if (ret_btf_id == 0) {
6169 verbose(env, "invalid return type %d of func %s#%d\n",
6170 fn->ret_type, func_id_name(func_id), func_id);
6171 return -EINVAL;
6172 }
22dc4a0f
AN
6173 /* current BPF helper definitions are only coming from
6174 * built-in code with type IDs from vmlinux BTF
6175 */
6176 regs[BPF_REG_0].btf = btf_vmlinux;
af7ec138 6177 regs[BPF_REG_0].btf_id = ret_btf_id;
17a52670 6178 } else {
61bd5218 6179 verbose(env, "unknown return type %d of func %s#%d\n",
ebb676da 6180 fn->ret_type, func_id_name(func_id), func_id);
17a52670
AS
6181 return -EINVAL;
6182 }
04fd61ab 6183
93c230e3
MKL
6184 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6185 regs[BPF_REG_0].id = ++env->id_gen;
6186
0f3adc28 6187 if (is_ptr_cast_function(func_id)) {
1b986589
MKL
6188 /* For release_reference() */
6189 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
64d85290 6190 } else if (is_acquire_function(func_id, meta.map_ptr)) {
0f3adc28
LB
6191 int id = acquire_reference_state(env, insn_idx);
6192
6193 if (id < 0)
6194 return id;
6195 /* For mark_ptr_or_null_reg() */
6196 regs[BPF_REG_0].id = id;
6197 /* For release_reference() */
6198 regs[BPF_REG_0].ref_obj_id = id;
6199 }
1b986589 6200
849fa506
YS
6201 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6202
61bd5218 6203 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
35578d79
KX
6204 if (err)
6205 return err;
04fd61ab 6206
fa28dcb8
SL
6207 if ((func_id == BPF_FUNC_get_stack ||
6208 func_id == BPF_FUNC_get_task_stack) &&
6209 !env->prog->has_callchain_buf) {
c195651e
YS
6210 const char *err_str;
6211
6212#ifdef CONFIG_PERF_EVENTS
6213 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6214 err_str = "cannot get callchain buffer for func %s#%d\n";
6215#else
6216 err = -ENOTSUPP;
6217 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6218#endif
6219 if (err) {
6220 verbose(env, err_str, func_id_name(func_id), func_id);
6221 return err;
6222 }
6223
6224 env->prog->has_callchain_buf = true;
6225 }
6226
5d99cb2c
SL
6227 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6228 env->prog->call_get_stack = true;
6229
969bf05e
AS
6230 if (changes_data)
6231 clear_all_pkt_pointers(env);
6232 return 0;
6233}
6234
e6ac2450
MKL
6235/* mark_btf_func_reg_size() is used when the reg size is determined by
6236 * the BTF func_proto's return value size and argument.
6237 */
6238static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6239 size_t reg_size)
6240{
6241 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6242
6243 if (regno == BPF_REG_0) {
6244 /* Function return value */
6245 reg->live |= REG_LIVE_WRITTEN;
6246 reg->subreg_def = reg_size == sizeof(u64) ?
6247 DEF_NOT_SUBREG : env->insn_idx + 1;
6248 } else {
6249 /* Function argument */
6250 if (reg_size == sizeof(u64)) {
6251 mark_insn_zext(env, reg);
6252 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6253 } else {
6254 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6255 }
6256 }
6257}
6258
6259static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6260{
6261 const struct btf_type *t, *func, *func_proto, *ptr_type;
6262 struct bpf_reg_state *regs = cur_regs(env);
6263 const char *func_name, *ptr_type_name;
6264 u32 i, nargs, func_id, ptr_type_id;
6265 const struct btf_param *args;
6266 int err;
6267
6268 func_id = insn->imm;
6269 func = btf_type_by_id(btf_vmlinux, func_id);
6270 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6271 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6272
6273 if (!env->ops->check_kfunc_call ||
6274 !env->ops->check_kfunc_call(func_id)) {
6275 verbose(env, "calling kernel function %s is not allowed\n",
6276 func_name);
6277 return -EACCES;
6278 }
6279
6280 /* Check the arguments */
6281 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6282 if (err)
6283 return err;
6284
6285 for (i = 0; i < CALLER_SAVED_REGS; i++)
6286 mark_reg_not_init(env, regs, caller_saved[i]);
6287
6288 /* Check return type */
6289 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6290 if (btf_type_is_scalar(t)) {
6291 mark_reg_unknown(env, regs, BPF_REG_0);
6292 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6293 } else if (btf_type_is_ptr(t)) {
6294 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6295 &ptr_type_id);
6296 if (!btf_type_is_struct(ptr_type)) {
6297 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6298 ptr_type->name_off);
6299 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6300 func_name, btf_type_str(ptr_type),
6301 ptr_type_name);
6302 return -EINVAL;
6303 }
6304 mark_reg_known_zero(env, regs, BPF_REG_0);
6305 regs[BPF_REG_0].btf = btf_vmlinux;
6306 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6307 regs[BPF_REG_0].btf_id = ptr_type_id;
6308 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6309 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6310
6311 nargs = btf_type_vlen(func_proto);
6312 args = (const struct btf_param *)(func_proto + 1);
6313 for (i = 0; i < nargs; i++) {
6314 u32 regno = i + 1;
6315
6316 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6317 if (btf_type_is_ptr(t))
6318 mark_btf_func_reg_size(env, regno, sizeof(void *));
6319 else
6320 /* scalar. ensured by btf_check_kfunc_arg_match() */
6321 mark_btf_func_reg_size(env, regno, t->size);
6322 }
6323
6324 return 0;
6325}
6326
b03c9f9f
EC
6327static bool signed_add_overflows(s64 a, s64 b)
6328{
6329 /* Do the add in u64, where overflow is well-defined */
6330 s64 res = (s64)((u64)a + (u64)b);
6331
6332 if (b < 0)
6333 return res > a;
6334 return res < a;
6335}
6336
bc895e8b 6337static bool signed_add32_overflows(s32 a, s32 b)
3f50f132
JF
6338{
6339 /* Do the add in u32, where overflow is well-defined */
6340 s32 res = (s32)((u32)a + (u32)b);
6341
6342 if (b < 0)
6343 return res > a;
6344 return res < a;
6345}
6346
bc895e8b 6347static bool signed_sub_overflows(s64 a, s64 b)
b03c9f9f
EC
6348{
6349 /* Do the sub in u64, where overflow is well-defined */
6350 s64 res = (s64)((u64)a - (u64)b);
6351
6352 if (b < 0)
6353 return res < a;
6354 return res > a;
969bf05e
AS
6355}
6356
3f50f132
JF
6357static bool signed_sub32_overflows(s32 a, s32 b)
6358{
bc895e8b 6359 /* Do the sub in u32, where overflow is well-defined */
3f50f132
JF
6360 s32 res = (s32)((u32)a - (u32)b);
6361
6362 if (b < 0)
6363 return res < a;
6364 return res > a;
6365}
6366
bb7f0f98
AS
6367static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6368 const struct bpf_reg_state *reg,
6369 enum bpf_reg_type type)
6370{
6371 bool known = tnum_is_const(reg->var_off);
6372 s64 val = reg->var_off.value;
6373 s64 smin = reg->smin_value;
6374
6375 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6376 verbose(env, "math between %s pointer and %lld is not allowed\n",
6377 reg_type_str[type], val);
6378 return false;
6379 }
6380
6381 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6382 verbose(env, "%s pointer offset %d is not allowed\n",
6383 reg_type_str[type], reg->off);
6384 return false;
6385 }
6386
6387 if (smin == S64_MIN) {
6388 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6389 reg_type_str[type]);
6390 return false;
6391 }
6392
6393 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6394 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6395 smin, reg_type_str[type]);
6396 return false;
6397 }
6398
6399 return true;
6400}
6401
979d63d5
DB
6402static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6403{
6404 return &env->insn_aux_data[env->insn_idx];
6405}
6406
a6aaece0
DB
6407enum {
6408 REASON_BOUNDS = -1,
6409 REASON_TYPE = -2,
6410 REASON_PATHS = -3,
6411 REASON_LIMIT = -4,
6412 REASON_STACK = -5,
6413};
6414
979d63d5 6415static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
bb01a1bb 6416 u32 *alu_limit, bool mask_to_left)
979d63d5 6417{
7fedb63a 6418 u32 max = 0, ptr_limit = 0;
979d63d5
DB
6419
6420 switch (ptr_reg->type) {
6421 case PTR_TO_STACK:
1b1597e6 6422 /* Offset 0 is out-of-bounds, but acceptable start for the
7fedb63a
DB
6423 * left direction, see BPF_REG_FP. Also, unknown scalar
6424 * offset where we would need to deal with min/max bounds is
6425 * currently prohibited for unprivileged.
1b1597e6
PK
6426 */
6427 max = MAX_BPF_STACK + mask_to_left;
7fedb63a 6428 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
b658bbb8 6429 break;
979d63d5 6430 case PTR_TO_MAP_VALUE:
1b1597e6 6431 max = ptr_reg->map_ptr->value_size;
7fedb63a
DB
6432 ptr_limit = (mask_to_left ?
6433 ptr_reg->smin_value :
6434 ptr_reg->umax_value) + ptr_reg->off;
b658bbb8 6435 break;
979d63d5 6436 default:
a6aaece0 6437 return REASON_TYPE;
979d63d5 6438 }
b658bbb8
DB
6439
6440 if (ptr_limit >= max)
a6aaece0 6441 return REASON_LIMIT;
b658bbb8
DB
6442 *alu_limit = ptr_limit;
6443 return 0;
979d63d5
DB
6444}
6445
d3bd7413
DB
6446static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6447 const struct bpf_insn *insn)
6448{
2c78ee89 6449 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
d3bd7413
DB
6450}
6451
6452static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6453 u32 alu_state, u32 alu_limit)
6454{
6455 /* If we arrived here from different branches with different
6456 * state or limits to sanitize, then this won't work.
6457 */
6458 if (aux->alu_state &&
6459 (aux->alu_state != alu_state ||
6460 aux->alu_limit != alu_limit))
a6aaece0 6461 return REASON_PATHS;
d3bd7413 6462
e6ac5933 6463 /* Corresponding fixup done in do_misc_fixups(). */
d3bd7413
DB
6464 aux->alu_state = alu_state;
6465 aux->alu_limit = alu_limit;
6466 return 0;
6467}
6468
6469static int sanitize_val_alu(struct bpf_verifier_env *env,
6470 struct bpf_insn *insn)
6471{
6472 struct bpf_insn_aux_data *aux = cur_aux(env);
6473
6474 if (can_skip_alu_sanitation(env, insn))
6475 return 0;
6476
6477 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6478}
6479
f5288193
DB
6480static bool sanitize_needed(u8 opcode)
6481{
6482 return opcode == BPF_ADD || opcode == BPF_SUB;
6483}
6484
3d0220f6
DB
6485struct bpf_sanitize_info {
6486 struct bpf_insn_aux_data aux;
bb01a1bb 6487 bool mask_to_left;
3d0220f6
DB
6488};
6489
9183671a
DB
6490static struct bpf_verifier_state *
6491sanitize_speculative_path(struct bpf_verifier_env *env,
6492 const struct bpf_insn *insn,
6493 u32 next_idx, u32 curr_idx)
6494{
6495 struct bpf_verifier_state *branch;
6496 struct bpf_reg_state *regs;
6497
6498 branch = push_stack(env, next_idx, curr_idx, true);
6499 if (branch && insn) {
6500 regs = branch->frame[branch->curframe]->regs;
6501 if (BPF_SRC(insn->code) == BPF_K) {
6502 mark_reg_unknown(env, regs, insn->dst_reg);
6503 } else if (BPF_SRC(insn->code) == BPF_X) {
6504 mark_reg_unknown(env, regs, insn->dst_reg);
6505 mark_reg_unknown(env, regs, insn->src_reg);
6506 }
6507 }
6508 return branch;
6509}
6510
979d63d5
DB
6511static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6512 struct bpf_insn *insn,
6513 const struct bpf_reg_state *ptr_reg,
6f55b2f2 6514 const struct bpf_reg_state *off_reg,
979d63d5 6515 struct bpf_reg_state *dst_reg,
3d0220f6 6516 struct bpf_sanitize_info *info,
7fedb63a 6517 const bool commit_window)
979d63d5 6518{
3d0220f6 6519 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
979d63d5 6520 struct bpf_verifier_state *vstate = env->cur_state;
801c6058 6521 bool off_is_imm = tnum_is_const(off_reg->var_off);
6f55b2f2 6522 bool off_is_neg = off_reg->smin_value < 0;
979d63d5
DB
6523 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6524 u8 opcode = BPF_OP(insn->code);
6525 u32 alu_state, alu_limit;
6526 struct bpf_reg_state tmp;
6527 bool ret;
f232326f 6528 int err;
979d63d5 6529
d3bd7413 6530 if (can_skip_alu_sanitation(env, insn))
979d63d5
DB
6531 return 0;
6532
6533 /* We already marked aux for masking from non-speculative
6534 * paths, thus we got here in the first place. We only care
6535 * to explore bad access from here.
6536 */
6537 if (vstate->speculative)
6538 goto do_sim;
6539
bb01a1bb
DB
6540 if (!commit_window) {
6541 if (!tnum_is_const(off_reg->var_off) &&
6542 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6543 return REASON_BOUNDS;
6544
6545 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6546 (opcode == BPF_SUB && !off_is_neg);
6547 }
6548
6549 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
f232326f
PK
6550 if (err < 0)
6551 return err;
6552
7fedb63a
DB
6553 if (commit_window) {
6554 /* In commit phase we narrow the masking window based on
6555 * the observed pointer move after the simulated operation.
6556 */
3d0220f6
DB
6557 alu_state = info->aux.alu_state;
6558 alu_limit = abs(info->aux.alu_limit - alu_limit);
7fedb63a
DB
6559 } else {
6560 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
801c6058 6561 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
7fedb63a
DB
6562 alu_state |= ptr_is_dst_reg ?
6563 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
e042aa53
DB
6564
6565 /* Limit pruning on unknown scalars to enable deep search for
6566 * potential masking differences from other program paths.
6567 */
6568 if (!off_is_imm)
6569 env->explore_alu_limits = true;
7fedb63a
DB
6570 }
6571
f232326f
PK
6572 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6573 if (err < 0)
6574 return err;
979d63d5 6575do_sim:
7fedb63a
DB
6576 /* If we're in commit phase, we're done here given we already
6577 * pushed the truncated dst_reg into the speculative verification
6578 * stack.
a7036191
DB
6579 *
6580 * Also, when register is a known constant, we rewrite register-based
6581 * operation to immediate-based, and thus do not need masking (and as
6582 * a consequence, do not need to simulate the zero-truncation either).
7fedb63a 6583 */
a7036191 6584 if (commit_window || off_is_imm)
7fedb63a
DB
6585 return 0;
6586
979d63d5
DB
6587 /* Simulate and find potential out-of-bounds access under
6588 * speculative execution from truncation as a result of
6589 * masking when off was not within expected range. If off
6590 * sits in dst, then we temporarily need to move ptr there
6591 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6592 * for cases where we use K-based arithmetic in one direction
6593 * and truncated reg-based in the other in order to explore
6594 * bad access.
6595 */
6596 if (!ptr_is_dst_reg) {
6597 tmp = *dst_reg;
6598 *dst_reg = *ptr_reg;
6599 }
9183671a
DB
6600 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6601 env->insn_idx);
0803278b 6602 if (!ptr_is_dst_reg && ret)
979d63d5 6603 *dst_reg = tmp;
a6aaece0
DB
6604 return !ret ? REASON_STACK : 0;
6605}
6606
fe9a5ca7
DB
6607static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6608{
6609 struct bpf_verifier_state *vstate = env->cur_state;
6610
6611 /* If we simulate paths under speculation, we don't update the
6612 * insn as 'seen' such that when we verify unreachable paths in
6613 * the non-speculative domain, sanitize_dead_code() can still
6614 * rewrite/sanitize them.
6615 */
6616 if (!vstate->speculative)
6617 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6618}
6619
a6aaece0
DB
6620static int sanitize_err(struct bpf_verifier_env *env,
6621 const struct bpf_insn *insn, int reason,
6622 const struct bpf_reg_state *off_reg,
6623 const struct bpf_reg_state *dst_reg)
6624{
6625 static const char *err = "pointer arithmetic with it prohibited for !root";
6626 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6627 u32 dst = insn->dst_reg, src = insn->src_reg;
6628
6629 switch (reason) {
6630 case REASON_BOUNDS:
6631 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6632 off_reg == dst_reg ? dst : src, err);
6633 break;
6634 case REASON_TYPE:
6635 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6636 off_reg == dst_reg ? src : dst, err);
6637 break;
6638 case REASON_PATHS:
6639 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6640 dst, op, err);
6641 break;
6642 case REASON_LIMIT:
6643 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6644 dst, op, err);
6645 break;
6646 case REASON_STACK:
6647 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6648 dst, err);
6649 break;
6650 default:
6651 verbose(env, "verifier internal error: unknown reason (%d)\n",
6652 reason);
6653 break;
6654 }
6655
6656 return -EACCES;
979d63d5
DB
6657}
6658
01f810ac
AM
6659/* check that stack access falls within stack limits and that 'reg' doesn't
6660 * have a variable offset.
6661 *
6662 * Variable offset is prohibited for unprivileged mode for simplicity since it
6663 * requires corresponding support in Spectre masking for stack ALU. See also
6664 * retrieve_ptr_limit().
6665 *
6666 *
6667 * 'off' includes 'reg->off'.
6668 */
6669static int check_stack_access_for_ptr_arithmetic(
6670 struct bpf_verifier_env *env,
6671 int regno,
6672 const struct bpf_reg_state *reg,
6673 int off)
6674{
6675 if (!tnum_is_const(reg->var_off)) {
6676 char tn_buf[48];
6677
6678 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6679 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6680 regno, tn_buf, off);
6681 return -EACCES;
6682 }
6683
6684 if (off >= 0 || off < -MAX_BPF_STACK) {
6685 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6686 "prohibited for !root; off=%d\n", regno, off);
6687 return -EACCES;
6688 }
6689
6690 return 0;
6691}
6692
073815b7
DB
6693static int sanitize_check_bounds(struct bpf_verifier_env *env,
6694 const struct bpf_insn *insn,
6695 const struct bpf_reg_state *dst_reg)
6696{
6697 u32 dst = insn->dst_reg;
6698
6699 /* For unprivileged we require that resulting offset must be in bounds
6700 * in order to be able to sanitize access later on.
6701 */
6702 if (env->bypass_spec_v1)
6703 return 0;
6704
6705 switch (dst_reg->type) {
6706 case PTR_TO_STACK:
6707 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6708 dst_reg->off + dst_reg->var_off.value))
6709 return -EACCES;
6710 break;
6711 case PTR_TO_MAP_VALUE:
6712 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6713 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6714 "prohibited for !root\n", dst);
6715 return -EACCES;
6716 }
6717 break;
6718 default:
6719 break;
6720 }
6721
6722 return 0;
6723}
01f810ac 6724
f1174f77 6725/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
f1174f77
EC
6726 * Caller should also handle BPF_MOV case separately.
6727 * If we return -EACCES, caller may want to try again treating pointer as a
6728 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6729 */
6730static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6731 struct bpf_insn *insn,
6732 const struct bpf_reg_state *ptr_reg,
6733 const struct bpf_reg_state *off_reg)
969bf05e 6734{
f4d7e40a
AS
6735 struct bpf_verifier_state *vstate = env->cur_state;
6736 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6737 struct bpf_reg_state *regs = state->regs, *dst_reg;
f1174f77 6738 bool known = tnum_is_const(off_reg->var_off);
b03c9f9f
EC
6739 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6740 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6741 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6742 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
3d0220f6 6743 struct bpf_sanitize_info info = {};
969bf05e 6744 u8 opcode = BPF_OP(insn->code);
24c109bb 6745 u32 dst = insn->dst_reg;
979d63d5 6746 int ret;
969bf05e 6747
f1174f77 6748 dst_reg = &regs[dst];
969bf05e 6749
6f16101e
DB
6750 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6751 smin_val > smax_val || umin_val > umax_val) {
6752 /* Taint dst register if offset had invalid bounds derived from
6753 * e.g. dead branches.
6754 */
f54c7898 6755 __mark_reg_unknown(env, dst_reg);
6f16101e 6756 return 0;
f1174f77
EC
6757 }
6758
6759 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6760 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
6c693541
YS
6761 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6762 __mark_reg_unknown(env, dst_reg);
6763 return 0;
6764 }
6765
82abbf8d
AS
6766 verbose(env,
6767 "R%d 32-bit pointer arithmetic prohibited\n",
6768 dst);
f1174f77 6769 return -EACCES;
969bf05e
AS
6770 }
6771
aad2eeaf
JS
6772 switch (ptr_reg->type) {
6773 case PTR_TO_MAP_VALUE_OR_NULL:
6774 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6775 dst, reg_type_str[ptr_reg->type]);
f1174f77 6776 return -EACCES;
aad2eeaf 6777 case CONST_PTR_TO_MAP:
7c696732
YS
6778 /* smin_val represents the known value */
6779 if (known && smin_val == 0 && opcode == BPF_ADD)
6780 break;
8731745e 6781 fallthrough;
aad2eeaf 6782 case PTR_TO_PACKET_END:
c64b7983
JS
6783 case PTR_TO_SOCKET:
6784 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
6785 case PTR_TO_SOCK_COMMON:
6786 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
6787 case PTR_TO_TCP_SOCK:
6788 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 6789 case PTR_TO_XDP_SOCK:
aad2eeaf
JS
6790 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6791 dst, reg_type_str[ptr_reg->type]);
f1174f77 6792 return -EACCES;
aad2eeaf
JS
6793 default:
6794 break;
f1174f77
EC
6795 }
6796
6797 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6798 * The id may be overwritten later if we create a new variable offset.
969bf05e 6799 */
f1174f77
EC
6800 dst_reg->type = ptr_reg->type;
6801 dst_reg->id = ptr_reg->id;
969bf05e 6802
bb7f0f98
AS
6803 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6804 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6805 return -EINVAL;
6806
3f50f132
JF
6807 /* pointer types do not carry 32-bit bounds at the moment. */
6808 __mark_reg32_unbounded(dst_reg);
6809
7fedb63a
DB
6810 if (sanitize_needed(opcode)) {
6811 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
3d0220f6 6812 &info, false);
a6aaece0
DB
6813 if (ret < 0)
6814 return sanitize_err(env, insn, ret, off_reg, dst_reg);
7fedb63a 6815 }
a6aaece0 6816
f1174f77
EC
6817 switch (opcode) {
6818 case BPF_ADD:
6819 /* We can take a fixed offset as long as it doesn't overflow
6820 * the s32 'off' field
969bf05e 6821 */
b03c9f9f
EC
6822 if (known && (ptr_reg->off + smin_val ==
6823 (s64)(s32)(ptr_reg->off + smin_val))) {
f1174f77 6824 /* pointer += K. Accumulate it into fixed offset */
b03c9f9f
EC
6825 dst_reg->smin_value = smin_ptr;
6826 dst_reg->smax_value = smax_ptr;
6827 dst_reg->umin_value = umin_ptr;
6828 dst_reg->umax_value = umax_ptr;
f1174f77 6829 dst_reg->var_off = ptr_reg->var_off;
b03c9f9f 6830 dst_reg->off = ptr_reg->off + smin_val;
0962590e 6831 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6832 break;
6833 }
f1174f77
EC
6834 /* A new variable offset is created. Note that off_reg->off
6835 * == 0, since it's a scalar.
6836 * dst_reg gets the pointer type and since some positive
6837 * integer value was added to the pointer, give it a new 'id'
6838 * if it's a PTR_TO_PACKET.
6839 * this creates a new 'base' pointer, off_reg (variable) gets
6840 * added into the variable offset, and we copy the fixed offset
6841 * from ptr_reg.
969bf05e 6842 */
b03c9f9f
EC
6843 if (signed_add_overflows(smin_ptr, smin_val) ||
6844 signed_add_overflows(smax_ptr, smax_val)) {
6845 dst_reg->smin_value = S64_MIN;
6846 dst_reg->smax_value = S64_MAX;
6847 } else {
6848 dst_reg->smin_value = smin_ptr + smin_val;
6849 dst_reg->smax_value = smax_ptr + smax_val;
6850 }
6851 if (umin_ptr + umin_val < umin_ptr ||
6852 umax_ptr + umax_val < umax_ptr) {
6853 dst_reg->umin_value = 0;
6854 dst_reg->umax_value = U64_MAX;
6855 } else {
6856 dst_reg->umin_value = umin_ptr + umin_val;
6857 dst_reg->umax_value = umax_ptr + umax_val;
6858 }
f1174f77
EC
6859 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6860 dst_reg->off = ptr_reg->off;
0962590e 6861 dst_reg->raw = ptr_reg->raw;
de8f3a83 6862 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6863 dst_reg->id = ++env->id_gen;
6864 /* something was added to pkt_ptr, set range to zero */
22dc4a0f 6865 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
f1174f77
EC
6866 }
6867 break;
6868 case BPF_SUB:
6869 if (dst_reg == off_reg) {
6870 /* scalar -= pointer. Creates an unknown scalar */
82abbf8d
AS
6871 verbose(env, "R%d tried to subtract pointer from scalar\n",
6872 dst);
f1174f77
EC
6873 return -EACCES;
6874 }
6875 /* We don't allow subtraction from FP, because (according to
6876 * test_verifier.c test "invalid fp arithmetic", JITs might not
6877 * be able to deal with it.
969bf05e 6878 */
f1174f77 6879 if (ptr_reg->type == PTR_TO_STACK) {
82abbf8d
AS
6880 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6881 dst);
f1174f77
EC
6882 return -EACCES;
6883 }
b03c9f9f
EC
6884 if (known && (ptr_reg->off - smin_val ==
6885 (s64)(s32)(ptr_reg->off - smin_val))) {
f1174f77 6886 /* pointer -= K. Subtract it from fixed offset */
b03c9f9f
EC
6887 dst_reg->smin_value = smin_ptr;
6888 dst_reg->smax_value = smax_ptr;
6889 dst_reg->umin_value = umin_ptr;
6890 dst_reg->umax_value = umax_ptr;
f1174f77
EC
6891 dst_reg->var_off = ptr_reg->var_off;
6892 dst_reg->id = ptr_reg->id;
b03c9f9f 6893 dst_reg->off = ptr_reg->off - smin_val;
0962590e 6894 dst_reg->raw = ptr_reg->raw;
f1174f77
EC
6895 break;
6896 }
f1174f77
EC
6897 /* A new variable offset is created. If the subtrahend is known
6898 * nonnegative, then any reg->range we had before is still good.
969bf05e 6899 */
b03c9f9f
EC
6900 if (signed_sub_overflows(smin_ptr, smax_val) ||
6901 signed_sub_overflows(smax_ptr, smin_val)) {
6902 /* Overflow possible, we know nothing */
6903 dst_reg->smin_value = S64_MIN;
6904 dst_reg->smax_value = S64_MAX;
6905 } else {
6906 dst_reg->smin_value = smin_ptr - smax_val;
6907 dst_reg->smax_value = smax_ptr - smin_val;
6908 }
6909 if (umin_ptr < umax_val) {
6910 /* Overflow possible, we know nothing */
6911 dst_reg->umin_value = 0;
6912 dst_reg->umax_value = U64_MAX;
6913 } else {
6914 /* Cannot overflow (as long as bounds are consistent) */
6915 dst_reg->umin_value = umin_ptr - umax_val;
6916 dst_reg->umax_value = umax_ptr - umin_val;
6917 }
f1174f77
EC
6918 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6919 dst_reg->off = ptr_reg->off;
0962590e 6920 dst_reg->raw = ptr_reg->raw;
de8f3a83 6921 if (reg_is_pkt_pointer(ptr_reg)) {
f1174f77
EC
6922 dst_reg->id = ++env->id_gen;
6923 /* something was added to pkt_ptr, set range to zero */
b03c9f9f 6924 if (smin_val < 0)
22dc4a0f 6925 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
43188702 6926 }
f1174f77
EC
6927 break;
6928 case BPF_AND:
6929 case BPF_OR:
6930 case BPF_XOR:
82abbf8d
AS
6931 /* bitwise ops on pointers are troublesome, prohibit. */
6932 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6933 dst, bpf_alu_string[opcode >> 4]);
f1174f77
EC
6934 return -EACCES;
6935 default:
6936 /* other operators (e.g. MUL,LSH) produce non-pointer results */
82abbf8d
AS
6937 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6938 dst, bpf_alu_string[opcode >> 4]);
f1174f77 6939 return -EACCES;
43188702
JF
6940 }
6941
bb7f0f98
AS
6942 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6943 return -EINVAL;
6944
b03c9f9f
EC
6945 __update_reg_bounds(dst_reg);
6946 __reg_deduce_bounds(dst_reg);
6947 __reg_bound_offset(dst_reg);
0d6303db 6948
073815b7
DB
6949 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6950 return -EACCES;
7fedb63a
DB
6951 if (sanitize_needed(opcode)) {
6952 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
3d0220f6 6953 &info, true);
7fedb63a
DB
6954 if (ret < 0)
6955 return sanitize_err(env, insn, ret, off_reg, dst_reg);
0d6303db
DB
6956 }
6957
43188702
JF
6958 return 0;
6959}
6960
3f50f132
JF
6961static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6962 struct bpf_reg_state *src_reg)
6963{
6964 s32 smin_val = src_reg->s32_min_value;
6965 s32 smax_val = src_reg->s32_max_value;
6966 u32 umin_val = src_reg->u32_min_value;
6967 u32 umax_val = src_reg->u32_max_value;
6968
6969 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6970 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6971 dst_reg->s32_min_value = S32_MIN;
6972 dst_reg->s32_max_value = S32_MAX;
6973 } else {
6974 dst_reg->s32_min_value += smin_val;
6975 dst_reg->s32_max_value += smax_val;
6976 }
6977 if (dst_reg->u32_min_value + umin_val < umin_val ||
6978 dst_reg->u32_max_value + umax_val < umax_val) {
6979 dst_reg->u32_min_value = 0;
6980 dst_reg->u32_max_value = U32_MAX;
6981 } else {
6982 dst_reg->u32_min_value += umin_val;
6983 dst_reg->u32_max_value += umax_val;
6984 }
6985}
6986
07cd2631
JF
6987static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6988 struct bpf_reg_state *src_reg)
6989{
6990 s64 smin_val = src_reg->smin_value;
6991 s64 smax_val = src_reg->smax_value;
6992 u64 umin_val = src_reg->umin_value;
6993 u64 umax_val = src_reg->umax_value;
6994
6995 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6996 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6997 dst_reg->smin_value = S64_MIN;
6998 dst_reg->smax_value = S64_MAX;
6999 } else {
7000 dst_reg->smin_value += smin_val;
7001 dst_reg->smax_value += smax_val;
7002 }
7003 if (dst_reg->umin_value + umin_val < umin_val ||
7004 dst_reg->umax_value + umax_val < umax_val) {
7005 dst_reg->umin_value = 0;
7006 dst_reg->umax_value = U64_MAX;
7007 } else {
7008 dst_reg->umin_value += umin_val;
7009 dst_reg->umax_value += umax_val;
7010 }
3f50f132
JF
7011}
7012
7013static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7014 struct bpf_reg_state *src_reg)
7015{
7016 s32 smin_val = src_reg->s32_min_value;
7017 s32 smax_val = src_reg->s32_max_value;
7018 u32 umin_val = src_reg->u32_min_value;
7019 u32 umax_val = src_reg->u32_max_value;
7020
7021 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7022 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7023 /* Overflow possible, we know nothing */
7024 dst_reg->s32_min_value = S32_MIN;
7025 dst_reg->s32_max_value = S32_MAX;
7026 } else {
7027 dst_reg->s32_min_value -= smax_val;
7028 dst_reg->s32_max_value -= smin_val;
7029 }
7030 if (dst_reg->u32_min_value < umax_val) {
7031 /* Overflow possible, we know nothing */
7032 dst_reg->u32_min_value = 0;
7033 dst_reg->u32_max_value = U32_MAX;
7034 } else {
7035 /* Cannot overflow (as long as bounds are consistent) */
7036 dst_reg->u32_min_value -= umax_val;
7037 dst_reg->u32_max_value -= umin_val;
7038 }
07cd2631
JF
7039}
7040
7041static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7042 struct bpf_reg_state *src_reg)
7043{
7044 s64 smin_val = src_reg->smin_value;
7045 s64 smax_val = src_reg->smax_value;
7046 u64 umin_val = src_reg->umin_value;
7047 u64 umax_val = src_reg->umax_value;
7048
7049 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7050 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7051 /* Overflow possible, we know nothing */
7052 dst_reg->smin_value = S64_MIN;
7053 dst_reg->smax_value = S64_MAX;
7054 } else {
7055 dst_reg->smin_value -= smax_val;
7056 dst_reg->smax_value -= smin_val;
7057 }
7058 if (dst_reg->umin_value < umax_val) {
7059 /* Overflow possible, we know nothing */
7060 dst_reg->umin_value = 0;
7061 dst_reg->umax_value = U64_MAX;
7062 } else {
7063 /* Cannot overflow (as long as bounds are consistent) */
7064 dst_reg->umin_value -= umax_val;
7065 dst_reg->umax_value -= umin_val;
7066 }
3f50f132
JF
7067}
7068
7069static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7070 struct bpf_reg_state *src_reg)
7071{
7072 s32 smin_val = src_reg->s32_min_value;
7073 u32 umin_val = src_reg->u32_min_value;
7074 u32 umax_val = src_reg->u32_max_value;
7075
7076 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7077 /* Ain't nobody got time to multiply that sign */
7078 __mark_reg32_unbounded(dst_reg);
7079 return;
7080 }
7081 /* Both values are positive, so we can work with unsigned and
7082 * copy the result to signed (unless it exceeds S32_MAX).
7083 */
7084 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7085 /* Potential overflow, we know nothing */
7086 __mark_reg32_unbounded(dst_reg);
7087 return;
7088 }
7089 dst_reg->u32_min_value *= umin_val;
7090 dst_reg->u32_max_value *= umax_val;
7091 if (dst_reg->u32_max_value > S32_MAX) {
7092 /* Overflow possible, we know nothing */
7093 dst_reg->s32_min_value = S32_MIN;
7094 dst_reg->s32_max_value = S32_MAX;
7095 } else {
7096 dst_reg->s32_min_value = dst_reg->u32_min_value;
7097 dst_reg->s32_max_value = dst_reg->u32_max_value;
7098 }
07cd2631
JF
7099}
7100
7101static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7102 struct bpf_reg_state *src_reg)
7103{
7104 s64 smin_val = src_reg->smin_value;
7105 u64 umin_val = src_reg->umin_value;
7106 u64 umax_val = src_reg->umax_value;
7107
07cd2631
JF
7108 if (smin_val < 0 || dst_reg->smin_value < 0) {
7109 /* Ain't nobody got time to multiply that sign */
3f50f132 7110 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7111 return;
7112 }
7113 /* Both values are positive, so we can work with unsigned and
7114 * copy the result to signed (unless it exceeds S64_MAX).
7115 */
7116 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7117 /* Potential overflow, we know nothing */
3f50f132 7118 __mark_reg64_unbounded(dst_reg);
07cd2631
JF
7119 return;
7120 }
7121 dst_reg->umin_value *= umin_val;
7122 dst_reg->umax_value *= umax_val;
7123 if (dst_reg->umax_value > S64_MAX) {
7124 /* Overflow possible, we know nothing */
7125 dst_reg->smin_value = S64_MIN;
7126 dst_reg->smax_value = S64_MAX;
7127 } else {
7128 dst_reg->smin_value = dst_reg->umin_value;
7129 dst_reg->smax_value = dst_reg->umax_value;
7130 }
7131}
7132
3f50f132
JF
7133static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7134 struct bpf_reg_state *src_reg)
7135{
7136 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7137 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7138 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7139 s32 smin_val = src_reg->s32_min_value;
7140 u32 umax_val = src_reg->u32_max_value;
7141
049c4e13
DB
7142 if (src_known && dst_known) {
7143 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7144 return;
049c4e13 7145 }
3f50f132
JF
7146
7147 /* We get our minimum from the var_off, since that's inherently
7148 * bitwise. Our maximum is the minimum of the operands' maxima.
7149 */
7150 dst_reg->u32_min_value = var32_off.value;
7151 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7152 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7153 /* Lose signed bounds when ANDing negative numbers,
7154 * ain't nobody got time for that.
7155 */
7156 dst_reg->s32_min_value = S32_MIN;
7157 dst_reg->s32_max_value = S32_MAX;
7158 } else {
7159 /* ANDing two positives gives a positive, so safe to
7160 * cast result into s64.
7161 */
7162 dst_reg->s32_min_value = dst_reg->u32_min_value;
7163 dst_reg->s32_max_value = dst_reg->u32_max_value;
7164 }
3f50f132
JF
7165}
7166
07cd2631
JF
7167static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7168 struct bpf_reg_state *src_reg)
7169{
3f50f132
JF
7170 bool src_known = tnum_is_const(src_reg->var_off);
7171 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7172 s64 smin_val = src_reg->smin_value;
7173 u64 umax_val = src_reg->umax_value;
7174
3f50f132 7175 if (src_known && dst_known) {
4fbb38a3 7176 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7177 return;
7178 }
7179
07cd2631
JF
7180 /* We get our minimum from the var_off, since that's inherently
7181 * bitwise. Our maximum is the minimum of the operands' maxima.
7182 */
07cd2631
JF
7183 dst_reg->umin_value = dst_reg->var_off.value;
7184 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7185 if (dst_reg->smin_value < 0 || smin_val < 0) {
7186 /* Lose signed bounds when ANDing negative numbers,
7187 * ain't nobody got time for that.
7188 */
7189 dst_reg->smin_value = S64_MIN;
7190 dst_reg->smax_value = S64_MAX;
7191 } else {
7192 /* ANDing two positives gives a positive, so safe to
7193 * cast result into s64.
7194 */
7195 dst_reg->smin_value = dst_reg->umin_value;
7196 dst_reg->smax_value = dst_reg->umax_value;
7197 }
7198 /* We may learn something more from the var_off */
7199 __update_reg_bounds(dst_reg);
7200}
7201
3f50f132
JF
7202static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7203 struct bpf_reg_state *src_reg)
7204{
7205 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7206 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7207 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
5b9fbeb7
DB
7208 s32 smin_val = src_reg->s32_min_value;
7209 u32 umin_val = src_reg->u32_min_value;
3f50f132 7210
049c4e13
DB
7211 if (src_known && dst_known) {
7212 __mark_reg32_known(dst_reg, var32_off.value);
3f50f132 7213 return;
049c4e13 7214 }
3f50f132
JF
7215
7216 /* We get our maximum from the var_off, and our minimum is the
7217 * maximum of the operands' minima
7218 */
7219 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7220 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7221 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7222 /* Lose signed bounds when ORing negative numbers,
7223 * ain't nobody got time for that.
7224 */
7225 dst_reg->s32_min_value = S32_MIN;
7226 dst_reg->s32_max_value = S32_MAX;
7227 } else {
7228 /* ORing two positives gives a positive, so safe to
7229 * cast result into s64.
7230 */
5b9fbeb7
DB
7231 dst_reg->s32_min_value = dst_reg->u32_min_value;
7232 dst_reg->s32_max_value = dst_reg->u32_max_value;
3f50f132
JF
7233 }
7234}
7235
07cd2631
JF
7236static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7237 struct bpf_reg_state *src_reg)
7238{
3f50f132
JF
7239 bool src_known = tnum_is_const(src_reg->var_off);
7240 bool dst_known = tnum_is_const(dst_reg->var_off);
07cd2631
JF
7241 s64 smin_val = src_reg->smin_value;
7242 u64 umin_val = src_reg->umin_value;
7243
3f50f132 7244 if (src_known && dst_known) {
4fbb38a3 7245 __mark_reg_known(dst_reg, dst_reg->var_off.value);
3f50f132
JF
7246 return;
7247 }
7248
07cd2631
JF
7249 /* We get our maximum from the var_off, and our minimum is the
7250 * maximum of the operands' minima
7251 */
07cd2631
JF
7252 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7253 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7254 if (dst_reg->smin_value < 0 || smin_val < 0) {
7255 /* Lose signed bounds when ORing negative numbers,
7256 * ain't nobody got time for that.
7257 */
7258 dst_reg->smin_value = S64_MIN;
7259 dst_reg->smax_value = S64_MAX;
7260 } else {
7261 /* ORing two positives gives a positive, so safe to
7262 * cast result into s64.
7263 */
7264 dst_reg->smin_value = dst_reg->umin_value;
7265 dst_reg->smax_value = dst_reg->umax_value;
7266 }
7267 /* We may learn something more from the var_off */
7268 __update_reg_bounds(dst_reg);
7269}
7270
2921c90d
YS
7271static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7272 struct bpf_reg_state *src_reg)
7273{
7274 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7275 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7276 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7277 s32 smin_val = src_reg->s32_min_value;
7278
049c4e13
DB
7279 if (src_known && dst_known) {
7280 __mark_reg32_known(dst_reg, var32_off.value);
2921c90d 7281 return;
049c4e13 7282 }
2921c90d
YS
7283
7284 /* We get both minimum and maximum from the var32_off. */
7285 dst_reg->u32_min_value = var32_off.value;
7286 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7287
7288 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7289 /* XORing two positive sign numbers gives a positive,
7290 * so safe to cast u32 result into s32.
7291 */
7292 dst_reg->s32_min_value = dst_reg->u32_min_value;
7293 dst_reg->s32_max_value = dst_reg->u32_max_value;
7294 } else {
7295 dst_reg->s32_min_value = S32_MIN;
7296 dst_reg->s32_max_value = S32_MAX;
7297 }
7298}
7299
7300static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7301 struct bpf_reg_state *src_reg)
7302{
7303 bool src_known = tnum_is_const(src_reg->var_off);
7304 bool dst_known = tnum_is_const(dst_reg->var_off);
7305 s64 smin_val = src_reg->smin_value;
7306
7307 if (src_known && dst_known) {
7308 /* dst_reg->var_off.value has been updated earlier */
7309 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7310 return;
7311 }
7312
7313 /* We get both minimum and maximum from the var_off. */
7314 dst_reg->umin_value = dst_reg->var_off.value;
7315 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7316
7317 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7318 /* XORing two positive sign numbers gives a positive,
7319 * so safe to cast u64 result into s64.
7320 */
7321 dst_reg->smin_value = dst_reg->umin_value;
7322 dst_reg->smax_value = dst_reg->umax_value;
7323 } else {
7324 dst_reg->smin_value = S64_MIN;
7325 dst_reg->smax_value = S64_MAX;
7326 }
7327
7328 __update_reg_bounds(dst_reg);
7329}
7330
3f50f132
JF
7331static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7332 u64 umin_val, u64 umax_val)
07cd2631 7333{
07cd2631
JF
7334 /* We lose all sign bit information (except what we can pick
7335 * up from var_off)
7336 */
3f50f132
JF
7337 dst_reg->s32_min_value = S32_MIN;
7338 dst_reg->s32_max_value = S32_MAX;
7339 /* If we might shift our top bit out, then we know nothing */
7340 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7341 dst_reg->u32_min_value = 0;
7342 dst_reg->u32_max_value = U32_MAX;
7343 } else {
7344 dst_reg->u32_min_value <<= umin_val;
7345 dst_reg->u32_max_value <<= umax_val;
7346 }
7347}
7348
7349static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7350 struct bpf_reg_state *src_reg)
7351{
7352 u32 umax_val = src_reg->u32_max_value;
7353 u32 umin_val = src_reg->u32_min_value;
7354 /* u32 alu operation will zext upper bits */
7355 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7356
7357 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7358 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7359 /* Not required but being careful mark reg64 bounds as unknown so
7360 * that we are forced to pick them up from tnum and zext later and
7361 * if some path skips this step we are still safe.
7362 */
7363 __mark_reg64_unbounded(dst_reg);
7364 __update_reg32_bounds(dst_reg);
7365}
7366
7367static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7368 u64 umin_val, u64 umax_val)
7369{
7370 /* Special case <<32 because it is a common compiler pattern to sign
7371 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7372 * positive we know this shift will also be positive so we can track
7373 * bounds correctly. Otherwise we lose all sign bit information except
7374 * what we can pick up from var_off. Perhaps we can generalize this
7375 * later to shifts of any length.
7376 */
7377 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7378 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7379 else
7380 dst_reg->smax_value = S64_MAX;
7381
7382 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7383 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7384 else
7385 dst_reg->smin_value = S64_MIN;
7386
07cd2631
JF
7387 /* If we might shift our top bit out, then we know nothing */
7388 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7389 dst_reg->umin_value = 0;
7390 dst_reg->umax_value = U64_MAX;
7391 } else {
7392 dst_reg->umin_value <<= umin_val;
7393 dst_reg->umax_value <<= umax_val;
7394 }
3f50f132
JF
7395}
7396
7397static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7398 struct bpf_reg_state *src_reg)
7399{
7400 u64 umax_val = src_reg->umax_value;
7401 u64 umin_val = src_reg->umin_value;
7402
7403 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7404 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7405 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7406
07cd2631
JF
7407 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7408 /* We may learn something more from the var_off */
7409 __update_reg_bounds(dst_reg);
7410}
7411
3f50f132
JF
7412static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7413 struct bpf_reg_state *src_reg)
7414{
7415 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7416 u32 umax_val = src_reg->u32_max_value;
7417 u32 umin_val = src_reg->u32_min_value;
7418
7419 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7420 * be negative, then either:
7421 * 1) src_reg might be zero, so the sign bit of the result is
7422 * unknown, so we lose our signed bounds
7423 * 2) it's known negative, thus the unsigned bounds capture the
7424 * signed bounds
7425 * 3) the signed bounds cross zero, so they tell us nothing
7426 * about the result
7427 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7428 * unsigned bounds capture the signed bounds.
3f50f132
JF
7429 * Thus, in all cases it suffices to blow away our signed bounds
7430 * and rely on inferring new ones from the unsigned bounds and
7431 * var_off of the result.
7432 */
7433 dst_reg->s32_min_value = S32_MIN;
7434 dst_reg->s32_max_value = S32_MAX;
7435
7436 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7437 dst_reg->u32_min_value >>= umax_val;
7438 dst_reg->u32_max_value >>= umin_val;
7439
7440 __mark_reg64_unbounded(dst_reg);
7441 __update_reg32_bounds(dst_reg);
7442}
7443
07cd2631
JF
7444static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7445 struct bpf_reg_state *src_reg)
7446{
7447 u64 umax_val = src_reg->umax_value;
7448 u64 umin_val = src_reg->umin_value;
7449
7450 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7451 * be negative, then either:
7452 * 1) src_reg might be zero, so the sign bit of the result is
7453 * unknown, so we lose our signed bounds
7454 * 2) it's known negative, thus the unsigned bounds capture the
7455 * signed bounds
7456 * 3) the signed bounds cross zero, so they tell us nothing
7457 * about the result
7458 * If the value in dst_reg is known nonnegative, then again the
18b24d78 7459 * unsigned bounds capture the signed bounds.
07cd2631
JF
7460 * Thus, in all cases it suffices to blow away our signed bounds
7461 * and rely on inferring new ones from the unsigned bounds and
7462 * var_off of the result.
7463 */
7464 dst_reg->smin_value = S64_MIN;
7465 dst_reg->smax_value = S64_MAX;
7466 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7467 dst_reg->umin_value >>= umax_val;
7468 dst_reg->umax_value >>= umin_val;
3f50f132
JF
7469
7470 /* Its not easy to operate on alu32 bounds here because it depends
7471 * on bits being shifted in. Take easy way out and mark unbounded
7472 * so we can recalculate later from tnum.
7473 */
7474 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7475 __update_reg_bounds(dst_reg);
7476}
7477
3f50f132
JF
7478static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7479 struct bpf_reg_state *src_reg)
07cd2631 7480{
3f50f132 7481 u64 umin_val = src_reg->u32_min_value;
07cd2631
JF
7482
7483 /* Upon reaching here, src_known is true and
7484 * umax_val is equal to umin_val.
7485 */
3f50f132
JF
7486 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7487 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
07cd2631 7488
3f50f132
JF
7489 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7490
7491 /* blow away the dst_reg umin_value/umax_value and rely on
7492 * dst_reg var_off to refine the result.
7493 */
7494 dst_reg->u32_min_value = 0;
7495 dst_reg->u32_max_value = U32_MAX;
7496
7497 __mark_reg64_unbounded(dst_reg);
7498 __update_reg32_bounds(dst_reg);
7499}
7500
7501static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7502 struct bpf_reg_state *src_reg)
7503{
7504 u64 umin_val = src_reg->umin_value;
7505
7506 /* Upon reaching here, src_known is true and umax_val is equal
7507 * to umin_val.
7508 */
7509 dst_reg->smin_value >>= umin_val;
7510 dst_reg->smax_value >>= umin_val;
7511
7512 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
07cd2631
JF
7513
7514 /* blow away the dst_reg umin_value/umax_value and rely on
7515 * dst_reg var_off to refine the result.
7516 */
7517 dst_reg->umin_value = 0;
7518 dst_reg->umax_value = U64_MAX;
3f50f132
JF
7519
7520 /* Its not easy to operate on alu32 bounds here because it depends
7521 * on bits being shifted in from upper 32-bits. Take easy way out
7522 * and mark unbounded so we can recalculate later from tnum.
7523 */
7524 __mark_reg32_unbounded(dst_reg);
07cd2631
JF
7525 __update_reg_bounds(dst_reg);
7526}
7527
468f6eaf
JH
7528/* WARNING: This function does calculations on 64-bit values, but the actual
7529 * execution may occur on 32-bit values. Therefore, things like bitshifts
7530 * need extra checks in the 32-bit case.
7531 */
f1174f77
EC
7532static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7533 struct bpf_insn *insn,
7534 struct bpf_reg_state *dst_reg,
7535 struct bpf_reg_state src_reg)
969bf05e 7536{
638f5b90 7537 struct bpf_reg_state *regs = cur_regs(env);
48461135 7538 u8 opcode = BPF_OP(insn->code);
b0b3fb67 7539 bool src_known;
b03c9f9f
EC
7540 s64 smin_val, smax_val;
7541 u64 umin_val, umax_val;
3f50f132
JF
7542 s32 s32_min_val, s32_max_val;
7543 u32 u32_min_val, u32_max_val;
468f6eaf 7544 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
3f50f132 7545 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
a6aaece0 7546 int ret;
b799207e 7547
b03c9f9f
EC
7548 smin_val = src_reg.smin_value;
7549 smax_val = src_reg.smax_value;
7550 umin_val = src_reg.umin_value;
7551 umax_val = src_reg.umax_value;
f23cc643 7552
3f50f132
JF
7553 s32_min_val = src_reg.s32_min_value;
7554 s32_max_val = src_reg.s32_max_value;
7555 u32_min_val = src_reg.u32_min_value;
7556 u32_max_val = src_reg.u32_max_value;
7557
7558 if (alu32) {
7559 src_known = tnum_subreg_is_const(src_reg.var_off);
3f50f132
JF
7560 if ((src_known &&
7561 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7562 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7563 /* Taint dst register if offset had invalid bounds
7564 * derived from e.g. dead branches.
7565 */
7566 __mark_reg_unknown(env, dst_reg);
7567 return 0;
7568 }
7569 } else {
7570 src_known = tnum_is_const(src_reg.var_off);
3f50f132
JF
7571 if ((src_known &&
7572 (smin_val != smax_val || umin_val != umax_val)) ||
7573 smin_val > smax_val || umin_val > umax_val) {
7574 /* Taint dst register if offset had invalid bounds
7575 * derived from e.g. dead branches.
7576 */
7577 __mark_reg_unknown(env, dst_reg);
7578 return 0;
7579 }
6f16101e
DB
7580 }
7581
bb7f0f98
AS
7582 if (!src_known &&
7583 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
f54c7898 7584 __mark_reg_unknown(env, dst_reg);
bb7f0f98
AS
7585 return 0;
7586 }
7587
f5288193
DB
7588 if (sanitize_needed(opcode)) {
7589 ret = sanitize_val_alu(env, insn);
7590 if (ret < 0)
7591 return sanitize_err(env, insn, ret, NULL, NULL);
7592 }
7593
3f50f132
JF
7594 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7595 * There are two classes of instructions: The first class we track both
7596 * alu32 and alu64 sign/unsigned bounds independently this provides the
7597 * greatest amount of precision when alu operations are mixed with jmp32
7598 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7599 * and BPF_OR. This is possible because these ops have fairly easy to
7600 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7601 * See alu32 verifier tests for examples. The second class of
7602 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7603 * with regards to tracking sign/unsigned bounds because the bits may
7604 * cross subreg boundaries in the alu64 case. When this happens we mark
7605 * the reg unbounded in the subreg bound space and use the resulting
7606 * tnum to calculate an approximation of the sign/unsigned bounds.
7607 */
48461135
JB
7608 switch (opcode) {
7609 case BPF_ADD:
3f50f132 7610 scalar32_min_max_add(dst_reg, &src_reg);
07cd2631 7611 scalar_min_max_add(dst_reg, &src_reg);
3f50f132 7612 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
48461135
JB
7613 break;
7614 case BPF_SUB:
3f50f132 7615 scalar32_min_max_sub(dst_reg, &src_reg);
07cd2631 7616 scalar_min_max_sub(dst_reg, &src_reg);
3f50f132 7617 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
48461135
JB
7618 break;
7619 case BPF_MUL:
3f50f132
JF
7620 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7621 scalar32_min_max_mul(dst_reg, &src_reg);
07cd2631 7622 scalar_min_max_mul(dst_reg, &src_reg);
48461135
JB
7623 break;
7624 case BPF_AND:
3f50f132
JF
7625 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7626 scalar32_min_max_and(dst_reg, &src_reg);
07cd2631 7627 scalar_min_max_and(dst_reg, &src_reg);
f1174f77
EC
7628 break;
7629 case BPF_OR:
3f50f132
JF
7630 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7631 scalar32_min_max_or(dst_reg, &src_reg);
07cd2631 7632 scalar_min_max_or(dst_reg, &src_reg);
48461135 7633 break;
2921c90d
YS
7634 case BPF_XOR:
7635 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7636 scalar32_min_max_xor(dst_reg, &src_reg);
7637 scalar_min_max_xor(dst_reg, &src_reg);
7638 break;
48461135 7639 case BPF_LSH:
468f6eaf
JH
7640 if (umax_val >= insn_bitness) {
7641 /* Shifts greater than 31 or 63 are undefined.
7642 * This includes shifts by a negative number.
b03c9f9f 7643 */
61bd5218 7644 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7645 break;
7646 }
3f50f132
JF
7647 if (alu32)
7648 scalar32_min_max_lsh(dst_reg, &src_reg);
7649 else
7650 scalar_min_max_lsh(dst_reg, &src_reg);
48461135
JB
7651 break;
7652 case BPF_RSH:
468f6eaf
JH
7653 if (umax_val >= insn_bitness) {
7654 /* Shifts greater than 31 or 63 are undefined.
7655 * This includes shifts by a negative number.
b03c9f9f 7656 */
61bd5218 7657 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77
EC
7658 break;
7659 }
3f50f132
JF
7660 if (alu32)
7661 scalar32_min_max_rsh(dst_reg, &src_reg);
7662 else
7663 scalar_min_max_rsh(dst_reg, &src_reg);
48461135 7664 break;
9cbe1f5a
YS
7665 case BPF_ARSH:
7666 if (umax_val >= insn_bitness) {
7667 /* Shifts greater than 31 or 63 are undefined.
7668 * This includes shifts by a negative number.
7669 */
7670 mark_reg_unknown(env, regs, insn->dst_reg);
7671 break;
7672 }
3f50f132
JF
7673 if (alu32)
7674 scalar32_min_max_arsh(dst_reg, &src_reg);
7675 else
7676 scalar_min_max_arsh(dst_reg, &src_reg);
9cbe1f5a 7677 break;
48461135 7678 default:
61bd5218 7679 mark_reg_unknown(env, regs, insn->dst_reg);
48461135
JB
7680 break;
7681 }
7682
3f50f132
JF
7683 /* ALU32 ops are zero extended into 64bit register */
7684 if (alu32)
7685 zext_32_to_64(dst_reg);
468f6eaf 7686
294f2fc6 7687 __update_reg_bounds(dst_reg);
b03c9f9f
EC
7688 __reg_deduce_bounds(dst_reg);
7689 __reg_bound_offset(dst_reg);
f1174f77
EC
7690 return 0;
7691}
7692
7693/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7694 * and var_off.
7695 */
7696static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7697 struct bpf_insn *insn)
7698{
f4d7e40a
AS
7699 struct bpf_verifier_state *vstate = env->cur_state;
7700 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7701 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
f1174f77
EC
7702 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7703 u8 opcode = BPF_OP(insn->code);
b5dc0163 7704 int err;
f1174f77
EC
7705
7706 dst_reg = &regs[insn->dst_reg];
f1174f77
EC
7707 src_reg = NULL;
7708 if (dst_reg->type != SCALAR_VALUE)
7709 ptr_reg = dst_reg;
75748837
AS
7710 else
7711 /* Make sure ID is cleared otherwise dst_reg min/max could be
7712 * incorrectly propagated into other registers by find_equal_scalars()
7713 */
7714 dst_reg->id = 0;
f1174f77
EC
7715 if (BPF_SRC(insn->code) == BPF_X) {
7716 src_reg = &regs[insn->src_reg];
f1174f77
EC
7717 if (src_reg->type != SCALAR_VALUE) {
7718 if (dst_reg->type != SCALAR_VALUE) {
7719 /* Combining two pointers by any ALU op yields
82abbf8d
AS
7720 * an arbitrary scalar. Disallow all math except
7721 * pointer subtraction
f1174f77 7722 */
dd066823 7723 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
82abbf8d
AS
7724 mark_reg_unknown(env, regs, insn->dst_reg);
7725 return 0;
f1174f77 7726 }
82abbf8d
AS
7727 verbose(env, "R%d pointer %s pointer prohibited\n",
7728 insn->dst_reg,
7729 bpf_alu_string[opcode >> 4]);
7730 return -EACCES;
f1174f77
EC
7731 } else {
7732 /* scalar += pointer
7733 * This is legal, but we have to reverse our
7734 * src/dest handling in computing the range
7735 */
b5dc0163
AS
7736 err = mark_chain_precision(env, insn->dst_reg);
7737 if (err)
7738 return err;
82abbf8d
AS
7739 return adjust_ptr_min_max_vals(env, insn,
7740 src_reg, dst_reg);
f1174f77
EC
7741 }
7742 } else if (ptr_reg) {
7743 /* pointer += scalar */
b5dc0163
AS
7744 err = mark_chain_precision(env, insn->src_reg);
7745 if (err)
7746 return err;
82abbf8d
AS
7747 return adjust_ptr_min_max_vals(env, insn,
7748 dst_reg, src_reg);
f1174f77
EC
7749 }
7750 } else {
7751 /* Pretend the src is a reg with a known value, since we only
7752 * need to be able to read from this state.
7753 */
7754 off_reg.type = SCALAR_VALUE;
b03c9f9f 7755 __mark_reg_known(&off_reg, insn->imm);
f1174f77 7756 src_reg = &off_reg;
82abbf8d
AS
7757 if (ptr_reg) /* pointer += K */
7758 return adjust_ptr_min_max_vals(env, insn,
7759 ptr_reg, src_reg);
f1174f77
EC
7760 }
7761
7762 /* Got here implies adding two SCALAR_VALUEs */
7763 if (WARN_ON_ONCE(ptr_reg)) {
f4d7e40a 7764 print_verifier_state(env, state);
61bd5218 7765 verbose(env, "verifier internal error: unexpected ptr_reg\n");
f1174f77
EC
7766 return -EINVAL;
7767 }
7768 if (WARN_ON(!src_reg)) {
f4d7e40a 7769 print_verifier_state(env, state);
61bd5218 7770 verbose(env, "verifier internal error: no src_reg\n");
f1174f77
EC
7771 return -EINVAL;
7772 }
7773 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
48461135
JB
7774}
7775
17a52670 7776/* check validity of 32-bit and 64-bit arithmetic operations */
58e2af8b 7777static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 7778{
638f5b90 7779 struct bpf_reg_state *regs = cur_regs(env);
17a52670
AS
7780 u8 opcode = BPF_OP(insn->code);
7781 int err;
7782
7783 if (opcode == BPF_END || opcode == BPF_NEG) {
7784 if (opcode == BPF_NEG) {
7785 if (BPF_SRC(insn->code) != 0 ||
7786 insn->src_reg != BPF_REG_0 ||
7787 insn->off != 0 || insn->imm != 0) {
61bd5218 7788 verbose(env, "BPF_NEG uses reserved fields\n");
17a52670
AS
7789 return -EINVAL;
7790 }
7791 } else {
7792 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
e67b8a68
EC
7793 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7794 BPF_CLASS(insn->code) == BPF_ALU64) {
61bd5218 7795 verbose(env, "BPF_END uses reserved fields\n");
17a52670
AS
7796 return -EINVAL;
7797 }
7798 }
7799
7800 /* check src operand */
dc503a8a 7801 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7802 if (err)
7803 return err;
7804
1be7f75d 7805 if (is_pointer_value(env, insn->dst_reg)) {
61bd5218 7806 verbose(env, "R%d pointer arithmetic prohibited\n",
1be7f75d
AS
7807 insn->dst_reg);
7808 return -EACCES;
7809 }
7810
17a52670 7811 /* check dest operand */
dc503a8a 7812 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
7813 if (err)
7814 return err;
7815
7816 } else if (opcode == BPF_MOV) {
7817
7818 if (BPF_SRC(insn->code) == BPF_X) {
7819 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7820 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7821 return -EINVAL;
7822 }
7823
7824 /* check src operand */
dc503a8a 7825 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7826 if (err)
7827 return err;
7828 } else {
7829 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7830 verbose(env, "BPF_MOV uses reserved fields\n");
17a52670
AS
7831 return -EINVAL;
7832 }
7833 }
7834
fbeb1603
AF
7835 /* check dest operand, mark as required later */
7836 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
7837 if (err)
7838 return err;
7839
7840 if (BPF_SRC(insn->code) == BPF_X) {
e434b8cd
JW
7841 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7842 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7843
17a52670
AS
7844 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7845 /* case: R1 = R2
7846 * copy register state to dest reg
7847 */
75748837
AS
7848 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7849 /* Assign src and dst registers the same ID
7850 * that will be used by find_equal_scalars()
7851 * to propagate min/max range.
7852 */
7853 src_reg->id = ++env->id_gen;
e434b8cd
JW
7854 *dst_reg = *src_reg;
7855 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7856 dst_reg->subreg_def = DEF_NOT_SUBREG;
17a52670 7857 } else {
f1174f77 7858 /* R1 = (u32) R2 */
1be7f75d 7859 if (is_pointer_value(env, insn->src_reg)) {
61bd5218
JK
7860 verbose(env,
7861 "R%d partial copy of pointer\n",
1be7f75d
AS
7862 insn->src_reg);
7863 return -EACCES;
e434b8cd
JW
7864 } else if (src_reg->type == SCALAR_VALUE) {
7865 *dst_reg = *src_reg;
75748837
AS
7866 /* Make sure ID is cleared otherwise
7867 * dst_reg min/max could be incorrectly
7868 * propagated into src_reg by find_equal_scalars()
7869 */
7870 dst_reg->id = 0;
e434b8cd 7871 dst_reg->live |= REG_LIVE_WRITTEN;
5327ed3d 7872 dst_reg->subreg_def = env->insn_idx + 1;
e434b8cd
JW
7873 } else {
7874 mark_reg_unknown(env, regs,
7875 insn->dst_reg);
1be7f75d 7876 }
3f50f132 7877 zext_32_to_64(dst_reg);
17a52670
AS
7878 }
7879 } else {
7880 /* case: R = imm
7881 * remember the value we stored into this reg
7882 */
fbeb1603
AF
7883 /* clear any state __mark_reg_known doesn't set */
7884 mark_reg_unknown(env, regs, insn->dst_reg);
f1174f77 7885 regs[insn->dst_reg].type = SCALAR_VALUE;
95a762e2
JH
7886 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7887 __mark_reg_known(regs + insn->dst_reg,
7888 insn->imm);
7889 } else {
7890 __mark_reg_known(regs + insn->dst_reg,
7891 (u32)insn->imm);
7892 }
17a52670
AS
7893 }
7894
7895 } else if (opcode > BPF_END) {
61bd5218 7896 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
17a52670
AS
7897 return -EINVAL;
7898
7899 } else { /* all other ALU ops: and, sub, xor, add, ... */
7900
17a52670
AS
7901 if (BPF_SRC(insn->code) == BPF_X) {
7902 if (insn->imm != 0 || insn->off != 0) {
61bd5218 7903 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7904 return -EINVAL;
7905 }
7906 /* check src1 operand */
dc503a8a 7907 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
7908 if (err)
7909 return err;
7910 } else {
7911 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
61bd5218 7912 verbose(env, "BPF_ALU uses reserved fields\n");
17a52670
AS
7913 return -EINVAL;
7914 }
7915 }
7916
7917 /* check src2 operand */
dc503a8a 7918 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
7919 if (err)
7920 return err;
7921
7922 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7923 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
61bd5218 7924 verbose(env, "div by zero\n");
17a52670
AS
7925 return -EINVAL;
7926 }
7927
229394e8
RV
7928 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7929 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7930 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7931
7932 if (insn->imm < 0 || insn->imm >= size) {
61bd5218 7933 verbose(env, "invalid shift %d\n", insn->imm);
229394e8
RV
7934 return -EINVAL;
7935 }
7936 }
7937
1a0dc1ac 7938 /* check dest operand */
dc503a8a 7939 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
1a0dc1ac
AS
7940 if (err)
7941 return err;
7942
f1174f77 7943 return adjust_reg_min_max_vals(env, insn);
17a52670
AS
7944 }
7945
7946 return 0;
7947}
7948
c6a9efa1
PC
7949static void __find_good_pkt_pointers(struct bpf_func_state *state,
7950 struct bpf_reg_state *dst_reg,
6d94e741 7951 enum bpf_reg_type type, int new_range)
c6a9efa1
PC
7952{
7953 struct bpf_reg_state *reg;
7954 int i;
7955
7956 for (i = 0; i < MAX_BPF_REG; i++) {
7957 reg = &state->regs[i];
7958 if (reg->type == type && reg->id == dst_reg->id)
7959 /* keep the maximum range already checked */
7960 reg->range = max(reg->range, new_range);
7961 }
7962
7963 bpf_for_each_spilled_reg(i, state, reg) {
7964 if (!reg)
7965 continue;
7966 if (reg->type == type && reg->id == dst_reg->id)
7967 reg->range = max(reg->range, new_range);
7968 }
7969}
7970
f4d7e40a 7971static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
de8f3a83 7972 struct bpf_reg_state *dst_reg,
f8ddadc4 7973 enum bpf_reg_type type,
fb2a311a 7974 bool range_right_open)
969bf05e 7975{
6d94e741 7976 int new_range, i;
2d2be8ca 7977
fb2a311a
DB
7978 if (dst_reg->off < 0 ||
7979 (dst_reg->off == 0 && range_right_open))
f1174f77
EC
7980 /* This doesn't give us any range */
7981 return;
7982
b03c9f9f
EC
7983 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7984 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
f1174f77
EC
7985 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7986 * than pkt_end, but that's because it's also less than pkt.
7987 */
7988 return;
7989
fb2a311a
DB
7990 new_range = dst_reg->off;
7991 if (range_right_open)
7992 new_range--;
7993
7994 /* Examples for register markings:
2d2be8ca 7995 *
fb2a311a 7996 * pkt_data in dst register:
2d2be8ca
DB
7997 *
7998 * r2 = r3;
7999 * r2 += 8;
8000 * if (r2 > pkt_end) goto <handle exception>
8001 * <access okay>
8002 *
b4e432f1
DB
8003 * r2 = r3;
8004 * r2 += 8;
8005 * if (r2 < pkt_end) goto <access okay>
8006 * <handle exception>
8007 *
2d2be8ca
DB
8008 * Where:
8009 * r2 == dst_reg, pkt_end == src_reg
8010 * r2=pkt(id=n,off=8,r=0)
8011 * r3=pkt(id=n,off=0,r=0)
8012 *
fb2a311a 8013 * pkt_data in src register:
2d2be8ca
DB
8014 *
8015 * r2 = r3;
8016 * r2 += 8;
8017 * if (pkt_end >= r2) goto <access okay>
8018 * <handle exception>
8019 *
b4e432f1
DB
8020 * r2 = r3;
8021 * r2 += 8;
8022 * if (pkt_end <= r2) goto <handle exception>
8023 * <access okay>
8024 *
2d2be8ca
DB
8025 * Where:
8026 * pkt_end == dst_reg, r2 == src_reg
8027 * r2=pkt(id=n,off=8,r=0)
8028 * r3=pkt(id=n,off=0,r=0)
8029 *
8030 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
fb2a311a
DB
8031 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8032 * and [r3, r3 + 8-1) respectively is safe to access depending on
8033 * the check.
969bf05e 8034 */
2d2be8ca 8035
f1174f77
EC
8036 /* If our ids match, then we must have the same max_value. And we
8037 * don't care about the other reg's fixed offset, since if it's too big
8038 * the range won't allow anything.
8039 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8040 */
c6a9efa1
PC
8041 for (i = 0; i <= vstate->curframe; i++)
8042 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8043 new_range);
969bf05e
AS
8044}
8045
3f50f132 8046static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
4f7b3e82 8047{
3f50f132
JF
8048 struct tnum subreg = tnum_subreg(reg->var_off);
8049 s32 sval = (s32)val;
a72dafaf 8050
3f50f132
JF
8051 switch (opcode) {
8052 case BPF_JEQ:
8053 if (tnum_is_const(subreg))
8054 return !!tnum_equals_const(subreg, val);
8055 break;
8056 case BPF_JNE:
8057 if (tnum_is_const(subreg))
8058 return !tnum_equals_const(subreg, val);
8059 break;
8060 case BPF_JSET:
8061 if ((~subreg.mask & subreg.value) & val)
8062 return 1;
8063 if (!((subreg.mask | subreg.value) & val))
8064 return 0;
8065 break;
8066 case BPF_JGT:
8067 if (reg->u32_min_value > val)
8068 return 1;
8069 else if (reg->u32_max_value <= val)
8070 return 0;
8071 break;
8072 case BPF_JSGT:
8073 if (reg->s32_min_value > sval)
8074 return 1;
ee114dd6 8075 else if (reg->s32_max_value <= sval)
3f50f132
JF
8076 return 0;
8077 break;
8078 case BPF_JLT:
8079 if (reg->u32_max_value < val)
8080 return 1;
8081 else if (reg->u32_min_value >= val)
8082 return 0;
8083 break;
8084 case BPF_JSLT:
8085 if (reg->s32_max_value < sval)
8086 return 1;
8087 else if (reg->s32_min_value >= sval)
8088 return 0;
8089 break;
8090 case BPF_JGE:
8091 if (reg->u32_min_value >= val)
8092 return 1;
8093 else if (reg->u32_max_value < val)
8094 return 0;
8095 break;
8096 case BPF_JSGE:
8097 if (reg->s32_min_value >= sval)
8098 return 1;
8099 else if (reg->s32_max_value < sval)
8100 return 0;
8101 break;
8102 case BPF_JLE:
8103 if (reg->u32_max_value <= val)
8104 return 1;
8105 else if (reg->u32_min_value > val)
8106 return 0;
8107 break;
8108 case BPF_JSLE:
8109 if (reg->s32_max_value <= sval)
8110 return 1;
8111 else if (reg->s32_min_value > sval)
8112 return 0;
8113 break;
8114 }
4f7b3e82 8115
3f50f132
JF
8116 return -1;
8117}
092ed096 8118
3f50f132
JF
8119
8120static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8121{
8122 s64 sval = (s64)val;
a72dafaf 8123
4f7b3e82
AS
8124 switch (opcode) {
8125 case BPF_JEQ:
8126 if (tnum_is_const(reg->var_off))
8127 return !!tnum_equals_const(reg->var_off, val);
8128 break;
8129 case BPF_JNE:
8130 if (tnum_is_const(reg->var_off))
8131 return !tnum_equals_const(reg->var_off, val);
8132 break;
960ea056
JK
8133 case BPF_JSET:
8134 if ((~reg->var_off.mask & reg->var_off.value) & val)
8135 return 1;
8136 if (!((reg->var_off.mask | reg->var_off.value) & val))
8137 return 0;
8138 break;
4f7b3e82
AS
8139 case BPF_JGT:
8140 if (reg->umin_value > val)
8141 return 1;
8142 else if (reg->umax_value <= val)
8143 return 0;
8144 break;
8145 case BPF_JSGT:
a72dafaf 8146 if (reg->smin_value > sval)
4f7b3e82 8147 return 1;
ee114dd6 8148 else if (reg->smax_value <= sval)
4f7b3e82
AS
8149 return 0;
8150 break;
8151 case BPF_JLT:
8152 if (reg->umax_value < val)
8153 return 1;
8154 else if (reg->umin_value >= val)
8155 return 0;
8156 break;
8157 case BPF_JSLT:
a72dafaf 8158 if (reg->smax_value < sval)
4f7b3e82 8159 return 1;
a72dafaf 8160 else if (reg->smin_value >= sval)
4f7b3e82
AS
8161 return 0;
8162 break;
8163 case BPF_JGE:
8164 if (reg->umin_value >= val)
8165 return 1;
8166 else if (reg->umax_value < val)
8167 return 0;
8168 break;
8169 case BPF_JSGE:
a72dafaf 8170 if (reg->smin_value >= sval)
4f7b3e82 8171 return 1;
a72dafaf 8172 else if (reg->smax_value < sval)
4f7b3e82
AS
8173 return 0;
8174 break;
8175 case BPF_JLE:
8176 if (reg->umax_value <= val)
8177 return 1;
8178 else if (reg->umin_value > val)
8179 return 0;
8180 break;
8181 case BPF_JSLE:
a72dafaf 8182 if (reg->smax_value <= sval)
4f7b3e82 8183 return 1;
a72dafaf 8184 else if (reg->smin_value > sval)
4f7b3e82
AS
8185 return 0;
8186 break;
8187 }
8188
8189 return -1;
8190}
8191
3f50f132
JF
8192/* compute branch direction of the expression "if (reg opcode val) goto target;"
8193 * and return:
8194 * 1 - branch will be taken and "goto target" will be executed
8195 * 0 - branch will not be taken and fall-through to next insn
8196 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8197 * range [0,10]
604dca5e 8198 */
3f50f132
JF
8199static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8200 bool is_jmp32)
604dca5e 8201{
cac616db
JF
8202 if (__is_pointer_value(false, reg)) {
8203 if (!reg_type_not_null(reg->type))
8204 return -1;
8205
8206 /* If pointer is valid tests against zero will fail so we can
8207 * use this to direct branch taken.
8208 */
8209 if (val != 0)
8210 return -1;
8211
8212 switch (opcode) {
8213 case BPF_JEQ:
8214 return 0;
8215 case BPF_JNE:
8216 return 1;
8217 default:
8218 return -1;
8219 }
8220 }
604dca5e 8221
3f50f132
JF
8222 if (is_jmp32)
8223 return is_branch32_taken(reg, val, opcode);
8224 return is_branch64_taken(reg, val, opcode);
604dca5e
JH
8225}
8226
6d94e741
AS
8227static int flip_opcode(u32 opcode)
8228{
8229 /* How can we transform "a <op> b" into "b <op> a"? */
8230 static const u8 opcode_flip[16] = {
8231 /* these stay the same */
8232 [BPF_JEQ >> 4] = BPF_JEQ,
8233 [BPF_JNE >> 4] = BPF_JNE,
8234 [BPF_JSET >> 4] = BPF_JSET,
8235 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8236 [BPF_JGE >> 4] = BPF_JLE,
8237 [BPF_JGT >> 4] = BPF_JLT,
8238 [BPF_JLE >> 4] = BPF_JGE,
8239 [BPF_JLT >> 4] = BPF_JGT,
8240 [BPF_JSGE >> 4] = BPF_JSLE,
8241 [BPF_JSGT >> 4] = BPF_JSLT,
8242 [BPF_JSLE >> 4] = BPF_JSGE,
8243 [BPF_JSLT >> 4] = BPF_JSGT
8244 };
8245 return opcode_flip[opcode >> 4];
8246}
8247
8248static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8249 struct bpf_reg_state *src_reg,
8250 u8 opcode)
8251{
8252 struct bpf_reg_state *pkt;
8253
8254 if (src_reg->type == PTR_TO_PACKET_END) {
8255 pkt = dst_reg;
8256 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8257 pkt = src_reg;
8258 opcode = flip_opcode(opcode);
8259 } else {
8260 return -1;
8261 }
8262
8263 if (pkt->range >= 0)
8264 return -1;
8265
8266 switch (opcode) {
8267 case BPF_JLE:
8268 /* pkt <= pkt_end */
8269 fallthrough;
8270 case BPF_JGT:
8271 /* pkt > pkt_end */
8272 if (pkt->range == BEYOND_PKT_END)
8273 /* pkt has at last one extra byte beyond pkt_end */
8274 return opcode == BPF_JGT;
8275 break;
8276 case BPF_JLT:
8277 /* pkt < pkt_end */
8278 fallthrough;
8279 case BPF_JGE:
8280 /* pkt >= pkt_end */
8281 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8282 return opcode == BPF_JGE;
8283 break;
8284 }
8285 return -1;
8286}
8287
48461135
JB
8288/* Adjusts the register min/max values in the case that the dst_reg is the
8289 * variable register that we are working on, and src_reg is a constant or we're
8290 * simply doing a BPF_K check.
f1174f77 8291 * In JEQ/JNE cases we also adjust the var_off values.
48461135
JB
8292 */
8293static void reg_set_min_max(struct bpf_reg_state *true_reg,
3f50f132
JF
8294 struct bpf_reg_state *false_reg,
8295 u64 val, u32 val32,
092ed096 8296 u8 opcode, bool is_jmp32)
48461135 8297{
3f50f132
JF
8298 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8299 struct tnum false_64off = false_reg->var_off;
8300 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8301 struct tnum true_64off = true_reg->var_off;
8302 s64 sval = (s64)val;
8303 s32 sval32 = (s32)val32;
a72dafaf 8304
f1174f77
EC
8305 /* If the dst_reg is a pointer, we can't learn anything about its
8306 * variable offset from the compare (unless src_reg were a pointer into
8307 * the same object, but we don't bother with that.
8308 * Since false_reg and true_reg have the same type by construction, we
8309 * only need to check one of them for pointerness.
8310 */
8311 if (__is_pointer_value(false, false_reg))
8312 return;
4cabc5b1 8313
48461135
JB
8314 switch (opcode) {
8315 case BPF_JEQ:
48461135 8316 case BPF_JNE:
a72dafaf
JW
8317 {
8318 struct bpf_reg_state *reg =
8319 opcode == BPF_JEQ ? true_reg : false_reg;
8320
e688c3db
AS
8321 /* JEQ/JNE comparison doesn't change the register equivalence.
8322 * r1 = r2;
8323 * if (r1 == 42) goto label;
8324 * ...
8325 * label: // here both r1 and r2 are known to be 42.
8326 *
8327 * Hence when marking register as known preserve it's ID.
48461135 8328 */
3f50f132
JF
8329 if (is_jmp32)
8330 __mark_reg32_known(reg, val32);
8331 else
e688c3db 8332 ___mark_reg_known(reg, val);
48461135 8333 break;
a72dafaf 8334 }
960ea056 8335 case BPF_JSET:
3f50f132
JF
8336 if (is_jmp32) {
8337 false_32off = tnum_and(false_32off, tnum_const(~val32));
8338 if (is_power_of_2(val32))
8339 true_32off = tnum_or(true_32off,
8340 tnum_const(val32));
8341 } else {
8342 false_64off = tnum_and(false_64off, tnum_const(~val));
8343 if (is_power_of_2(val))
8344 true_64off = tnum_or(true_64off,
8345 tnum_const(val));
8346 }
960ea056 8347 break;
48461135 8348 case BPF_JGE:
a72dafaf
JW
8349 case BPF_JGT:
8350 {
3f50f132
JF
8351 if (is_jmp32) {
8352 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8353 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8354
8355 false_reg->u32_max_value = min(false_reg->u32_max_value,
8356 false_umax);
8357 true_reg->u32_min_value = max(true_reg->u32_min_value,
8358 true_umin);
8359 } else {
8360 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8361 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8362
8363 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8364 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8365 }
b03c9f9f 8366 break;
a72dafaf 8367 }
48461135 8368 case BPF_JSGE:
a72dafaf
JW
8369 case BPF_JSGT:
8370 {
3f50f132
JF
8371 if (is_jmp32) {
8372 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8373 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
a72dafaf 8374
3f50f132
JF
8375 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8376 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8377 } else {
8378 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8379 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8380
8381 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8382 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8383 }
48461135 8384 break;
a72dafaf 8385 }
b4e432f1 8386 case BPF_JLE:
a72dafaf
JW
8387 case BPF_JLT:
8388 {
3f50f132
JF
8389 if (is_jmp32) {
8390 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8391 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8392
8393 false_reg->u32_min_value = max(false_reg->u32_min_value,
8394 false_umin);
8395 true_reg->u32_max_value = min(true_reg->u32_max_value,
8396 true_umax);
8397 } else {
8398 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8399 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8400
8401 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8402 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8403 }
b4e432f1 8404 break;
a72dafaf 8405 }
b4e432f1 8406 case BPF_JSLE:
a72dafaf
JW
8407 case BPF_JSLT:
8408 {
3f50f132
JF
8409 if (is_jmp32) {
8410 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8411 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
a72dafaf 8412
3f50f132
JF
8413 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8414 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8415 } else {
8416 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8417 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8418
8419 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8420 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8421 }
b4e432f1 8422 break;
a72dafaf 8423 }
48461135 8424 default:
0fc31b10 8425 return;
48461135
JB
8426 }
8427
3f50f132
JF
8428 if (is_jmp32) {
8429 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8430 tnum_subreg(false_32off));
8431 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8432 tnum_subreg(true_32off));
8433 __reg_combine_32_into_64(false_reg);
8434 __reg_combine_32_into_64(true_reg);
8435 } else {
8436 false_reg->var_off = false_64off;
8437 true_reg->var_off = true_64off;
8438 __reg_combine_64_into_32(false_reg);
8439 __reg_combine_64_into_32(true_reg);
8440 }
48461135
JB
8441}
8442
f1174f77
EC
8443/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8444 * the variable reg.
48461135
JB
8445 */
8446static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
3f50f132
JF
8447 struct bpf_reg_state *false_reg,
8448 u64 val, u32 val32,
092ed096 8449 u8 opcode, bool is_jmp32)
48461135 8450{
6d94e741 8451 opcode = flip_opcode(opcode);
0fc31b10
JH
8452 /* This uses zero as "not present in table"; luckily the zero opcode,
8453 * BPF_JA, can't get here.
b03c9f9f 8454 */
0fc31b10 8455 if (opcode)
3f50f132 8456 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
f1174f77
EC
8457}
8458
8459/* Regs are known to be equal, so intersect their min/max/var_off */
8460static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8461 struct bpf_reg_state *dst_reg)
8462{
b03c9f9f
EC
8463 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8464 dst_reg->umin_value);
8465 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8466 dst_reg->umax_value);
8467 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8468 dst_reg->smin_value);
8469 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8470 dst_reg->smax_value);
f1174f77
EC
8471 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8472 dst_reg->var_off);
b03c9f9f
EC
8473 /* We might have learned new bounds from the var_off. */
8474 __update_reg_bounds(src_reg);
8475 __update_reg_bounds(dst_reg);
8476 /* We might have learned something about the sign bit. */
8477 __reg_deduce_bounds(src_reg);
8478 __reg_deduce_bounds(dst_reg);
8479 /* We might have learned some bits from the bounds. */
8480 __reg_bound_offset(src_reg);
8481 __reg_bound_offset(dst_reg);
8482 /* Intersecting with the old var_off might have improved our bounds
8483 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8484 * then new var_off is (0; 0x7f...fc) which improves our umax.
8485 */
8486 __update_reg_bounds(src_reg);
8487 __update_reg_bounds(dst_reg);
f1174f77
EC
8488}
8489
8490static void reg_combine_min_max(struct bpf_reg_state *true_src,
8491 struct bpf_reg_state *true_dst,
8492 struct bpf_reg_state *false_src,
8493 struct bpf_reg_state *false_dst,
8494 u8 opcode)
8495{
8496 switch (opcode) {
8497 case BPF_JEQ:
8498 __reg_combine_min_max(true_src, true_dst);
8499 break;
8500 case BPF_JNE:
8501 __reg_combine_min_max(false_src, false_dst);
b03c9f9f 8502 break;
4cabc5b1 8503 }
48461135
JB
8504}
8505
fd978bf7
JS
8506static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8507 struct bpf_reg_state *reg, u32 id,
840b9615 8508 bool is_null)
57a09bf0 8509{
93c230e3
MKL
8510 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8511 !WARN_ON_ONCE(!reg->id)) {
f1174f77
EC
8512 /* Old offset (both fixed and variable parts) should
8513 * have been known-zero, because we don't allow pointer
8514 * arithmetic on pointers that might be NULL.
8515 */
b03c9f9f
EC
8516 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8517 !tnum_equals_const(reg->var_off, 0) ||
f1174f77 8518 reg->off)) {
b03c9f9f
EC
8519 __mark_reg_known_zero(reg);
8520 reg->off = 0;
f1174f77
EC
8521 }
8522 if (is_null) {
8523 reg->type = SCALAR_VALUE;
1b986589
MKL
8524 /* We don't need id and ref_obj_id from this point
8525 * onwards anymore, thus we should better reset it,
8526 * so that state pruning has chances to take effect.
8527 */
8528 reg->id = 0;
8529 reg->ref_obj_id = 0;
4ddb7416
DB
8530
8531 return;
8532 }
8533
8534 mark_ptr_not_null_reg(reg);
8535
8536 if (!reg_may_point_to_spin_lock(reg)) {
1b986589
MKL
8537 /* For not-NULL ptr, reg->ref_obj_id will be reset
8538 * in release_reg_references().
8539 *
8540 * reg->id is still used by spin_lock ptr. Other
8541 * than spin_lock ptr type, reg->id can be reset.
fd978bf7
JS
8542 */
8543 reg->id = 0;
56f668df 8544 }
57a09bf0
TG
8545 }
8546}
8547
c6a9efa1
PC
8548static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8549 bool is_null)
8550{
8551 struct bpf_reg_state *reg;
8552 int i;
8553
8554 for (i = 0; i < MAX_BPF_REG; i++)
8555 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8556
8557 bpf_for_each_spilled_reg(i, state, reg) {
8558 if (!reg)
8559 continue;
8560 mark_ptr_or_null_reg(state, reg, id, is_null);
8561 }
8562}
8563
57a09bf0
TG
8564/* The logic is similar to find_good_pkt_pointers(), both could eventually
8565 * be folded together at some point.
8566 */
840b9615
JS
8567static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8568 bool is_null)
57a09bf0 8569{
f4d7e40a 8570 struct bpf_func_state *state = vstate->frame[vstate->curframe];
c6a9efa1 8571 struct bpf_reg_state *regs = state->regs;
1b986589 8572 u32 ref_obj_id = regs[regno].ref_obj_id;
a08dd0da 8573 u32 id = regs[regno].id;
c6a9efa1 8574 int i;
57a09bf0 8575
1b986589
MKL
8576 if (ref_obj_id && ref_obj_id == id && is_null)
8577 /* regs[regno] is in the " == NULL" branch.
8578 * No one could have freed the reference state before
8579 * doing the NULL check.
8580 */
8581 WARN_ON_ONCE(release_reference_state(state, id));
fd978bf7 8582
c6a9efa1
PC
8583 for (i = 0; i <= vstate->curframe; i++)
8584 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
57a09bf0
TG
8585}
8586
5beca081
DB
8587static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8588 struct bpf_reg_state *dst_reg,
8589 struct bpf_reg_state *src_reg,
8590 struct bpf_verifier_state *this_branch,
8591 struct bpf_verifier_state *other_branch)
8592{
8593 if (BPF_SRC(insn->code) != BPF_X)
8594 return false;
8595
092ed096
JW
8596 /* Pointers are always 64-bit. */
8597 if (BPF_CLASS(insn->code) == BPF_JMP32)
8598 return false;
8599
5beca081
DB
8600 switch (BPF_OP(insn->code)) {
8601 case BPF_JGT:
8602 if ((dst_reg->type == PTR_TO_PACKET &&
8603 src_reg->type == PTR_TO_PACKET_END) ||
8604 (dst_reg->type == PTR_TO_PACKET_META &&
8605 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8606 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8607 find_good_pkt_pointers(this_branch, dst_reg,
8608 dst_reg->type, false);
6d94e741 8609 mark_pkt_end(other_branch, insn->dst_reg, true);
5beca081
DB
8610 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8611 src_reg->type == PTR_TO_PACKET) ||
8612 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8613 src_reg->type == PTR_TO_PACKET_META)) {
8614 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8615 find_good_pkt_pointers(other_branch, src_reg,
8616 src_reg->type, true);
6d94e741 8617 mark_pkt_end(this_branch, insn->src_reg, false);
5beca081
DB
8618 } else {
8619 return false;
8620 }
8621 break;
8622 case BPF_JLT:
8623 if ((dst_reg->type == PTR_TO_PACKET &&
8624 src_reg->type == PTR_TO_PACKET_END) ||
8625 (dst_reg->type == PTR_TO_PACKET_META &&
8626 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8627 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8628 find_good_pkt_pointers(other_branch, dst_reg,
8629 dst_reg->type, true);
6d94e741 8630 mark_pkt_end(this_branch, insn->dst_reg, false);
5beca081
DB
8631 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8632 src_reg->type == PTR_TO_PACKET) ||
8633 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8634 src_reg->type == PTR_TO_PACKET_META)) {
8635 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8636 find_good_pkt_pointers(this_branch, src_reg,
8637 src_reg->type, false);
6d94e741 8638 mark_pkt_end(other_branch, insn->src_reg, true);
5beca081
DB
8639 } else {
8640 return false;
8641 }
8642 break;
8643 case BPF_JGE:
8644 if ((dst_reg->type == PTR_TO_PACKET &&
8645 src_reg->type == PTR_TO_PACKET_END) ||
8646 (dst_reg->type == PTR_TO_PACKET_META &&
8647 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8648 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8649 find_good_pkt_pointers(this_branch, dst_reg,
8650 dst_reg->type, true);
6d94e741 8651 mark_pkt_end(other_branch, insn->dst_reg, false);
5beca081
DB
8652 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8653 src_reg->type == PTR_TO_PACKET) ||
8654 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8655 src_reg->type == PTR_TO_PACKET_META)) {
8656 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8657 find_good_pkt_pointers(other_branch, src_reg,
8658 src_reg->type, false);
6d94e741 8659 mark_pkt_end(this_branch, insn->src_reg, true);
5beca081
DB
8660 } else {
8661 return false;
8662 }
8663 break;
8664 case BPF_JLE:
8665 if ((dst_reg->type == PTR_TO_PACKET &&
8666 src_reg->type == PTR_TO_PACKET_END) ||
8667 (dst_reg->type == PTR_TO_PACKET_META &&
8668 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8669 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8670 find_good_pkt_pointers(other_branch, dst_reg,
8671 dst_reg->type, false);
6d94e741 8672 mark_pkt_end(this_branch, insn->dst_reg, true);
5beca081
DB
8673 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8674 src_reg->type == PTR_TO_PACKET) ||
8675 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8676 src_reg->type == PTR_TO_PACKET_META)) {
8677 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8678 find_good_pkt_pointers(this_branch, src_reg,
8679 src_reg->type, true);
6d94e741 8680 mark_pkt_end(other_branch, insn->src_reg, false);
5beca081
DB
8681 } else {
8682 return false;
8683 }
8684 break;
8685 default:
8686 return false;
8687 }
8688
8689 return true;
8690}
8691
75748837
AS
8692static void find_equal_scalars(struct bpf_verifier_state *vstate,
8693 struct bpf_reg_state *known_reg)
8694{
8695 struct bpf_func_state *state;
8696 struct bpf_reg_state *reg;
8697 int i, j;
8698
8699 for (i = 0; i <= vstate->curframe; i++) {
8700 state = vstate->frame[i];
8701 for (j = 0; j < MAX_BPF_REG; j++) {
8702 reg = &state->regs[j];
8703 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8704 *reg = *known_reg;
8705 }
8706
8707 bpf_for_each_spilled_reg(j, state, reg) {
8708 if (!reg)
8709 continue;
8710 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8711 *reg = *known_reg;
8712 }
8713 }
8714}
8715
58e2af8b 8716static int check_cond_jmp_op(struct bpf_verifier_env *env,
17a52670
AS
8717 struct bpf_insn *insn, int *insn_idx)
8718{
f4d7e40a
AS
8719 struct bpf_verifier_state *this_branch = env->cur_state;
8720 struct bpf_verifier_state *other_branch;
8721 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
fb8d251e 8722 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
17a52670 8723 u8 opcode = BPF_OP(insn->code);
092ed096 8724 bool is_jmp32;
fb8d251e 8725 int pred = -1;
17a52670
AS
8726 int err;
8727
092ed096
JW
8728 /* Only conditional jumps are expected to reach here. */
8729 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8730 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
17a52670
AS
8731 return -EINVAL;
8732 }
8733
8734 if (BPF_SRC(insn->code) == BPF_X) {
8735 if (insn->imm != 0) {
092ed096 8736 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8737 return -EINVAL;
8738 }
8739
8740 /* check src1 operand */
dc503a8a 8741 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
8742 if (err)
8743 return err;
1be7f75d
AS
8744
8745 if (is_pointer_value(env, insn->src_reg)) {
61bd5218 8746 verbose(env, "R%d pointer comparison prohibited\n",
1be7f75d
AS
8747 insn->src_reg);
8748 return -EACCES;
8749 }
fb8d251e 8750 src_reg = &regs[insn->src_reg];
17a52670
AS
8751 } else {
8752 if (insn->src_reg != BPF_REG_0) {
092ed096 8753 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
17a52670
AS
8754 return -EINVAL;
8755 }
8756 }
8757
8758 /* check src2 operand */
dc503a8a 8759 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
8760 if (err)
8761 return err;
8762
1a0dc1ac 8763 dst_reg = &regs[insn->dst_reg];
092ed096 8764 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
1a0dc1ac 8765
3f50f132
JF
8766 if (BPF_SRC(insn->code) == BPF_K) {
8767 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8768 } else if (src_reg->type == SCALAR_VALUE &&
8769 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8770 pred = is_branch_taken(dst_reg,
8771 tnum_subreg(src_reg->var_off).value,
8772 opcode,
8773 is_jmp32);
8774 } else if (src_reg->type == SCALAR_VALUE &&
8775 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8776 pred = is_branch_taken(dst_reg,
8777 src_reg->var_off.value,
8778 opcode,
8779 is_jmp32);
6d94e741
AS
8780 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8781 reg_is_pkt_pointer_any(src_reg) &&
8782 !is_jmp32) {
8783 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
3f50f132
JF
8784 }
8785
b5dc0163 8786 if (pred >= 0) {
cac616db
JF
8787 /* If we get here with a dst_reg pointer type it is because
8788 * above is_branch_taken() special cased the 0 comparison.
8789 */
8790 if (!__is_pointer_value(false, dst_reg))
8791 err = mark_chain_precision(env, insn->dst_reg);
6d94e741
AS
8792 if (BPF_SRC(insn->code) == BPF_X && !err &&
8793 !__is_pointer_value(false, src_reg))
b5dc0163
AS
8794 err = mark_chain_precision(env, insn->src_reg);
8795 if (err)
8796 return err;
8797 }
9183671a 8798
fb8d251e 8799 if (pred == 1) {
9183671a
DB
8800 /* Only follow the goto, ignore fall-through. If needed, push
8801 * the fall-through branch for simulation under speculative
8802 * execution.
8803 */
8804 if (!env->bypass_spec_v1 &&
8805 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8806 *insn_idx))
8807 return -EFAULT;
fb8d251e
AS
8808 *insn_idx += insn->off;
8809 return 0;
8810 } else if (pred == 0) {
9183671a
DB
8811 /* Only follow the fall-through branch, since that's where the
8812 * program will go. If needed, push the goto branch for
8813 * simulation under speculative execution.
fb8d251e 8814 */
9183671a
DB
8815 if (!env->bypass_spec_v1 &&
8816 !sanitize_speculative_path(env, insn,
8817 *insn_idx + insn->off + 1,
8818 *insn_idx))
8819 return -EFAULT;
fb8d251e 8820 return 0;
17a52670
AS
8821 }
8822
979d63d5
DB
8823 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8824 false);
17a52670
AS
8825 if (!other_branch)
8826 return -EFAULT;
f4d7e40a 8827 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
17a52670 8828
48461135
JB
8829 /* detect if we are comparing against a constant value so we can adjust
8830 * our min/max values for our dst register.
f1174f77
EC
8831 * this is only legit if both are scalars (or pointers to the same
8832 * object, I suppose, but we don't support that right now), because
8833 * otherwise the different base pointers mean the offsets aren't
8834 * comparable.
48461135
JB
8835 */
8836 if (BPF_SRC(insn->code) == BPF_X) {
092ed096 8837 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
092ed096 8838
f1174f77 8839 if (dst_reg->type == SCALAR_VALUE &&
092ed096
JW
8840 src_reg->type == SCALAR_VALUE) {
8841 if (tnum_is_const(src_reg->var_off) ||
3f50f132
JF
8842 (is_jmp32 &&
8843 tnum_is_const(tnum_subreg(src_reg->var_off))))
f4d7e40a 8844 reg_set_min_max(&other_branch_regs[insn->dst_reg],
092ed096 8845 dst_reg,
3f50f132
JF
8846 src_reg->var_off.value,
8847 tnum_subreg(src_reg->var_off).value,
092ed096
JW
8848 opcode, is_jmp32);
8849 else if (tnum_is_const(dst_reg->var_off) ||
3f50f132
JF
8850 (is_jmp32 &&
8851 tnum_is_const(tnum_subreg(dst_reg->var_off))))
f4d7e40a 8852 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
092ed096 8853 src_reg,
3f50f132
JF
8854 dst_reg->var_off.value,
8855 tnum_subreg(dst_reg->var_off).value,
092ed096
JW
8856 opcode, is_jmp32);
8857 else if (!is_jmp32 &&
8858 (opcode == BPF_JEQ || opcode == BPF_JNE))
f1174f77 8859 /* Comparing for equality, we can combine knowledge */
f4d7e40a
AS
8860 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8861 &other_branch_regs[insn->dst_reg],
092ed096 8862 src_reg, dst_reg, opcode);
e688c3db
AS
8863 if (src_reg->id &&
8864 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
75748837
AS
8865 find_equal_scalars(this_branch, src_reg);
8866 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8867 }
8868
f1174f77
EC
8869 }
8870 } else if (dst_reg->type == SCALAR_VALUE) {
f4d7e40a 8871 reg_set_min_max(&other_branch_regs[insn->dst_reg],
3f50f132
JF
8872 dst_reg, insn->imm, (u32)insn->imm,
8873 opcode, is_jmp32);
48461135
JB
8874 }
8875
e688c3db
AS
8876 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8877 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
75748837
AS
8878 find_equal_scalars(this_branch, dst_reg);
8879 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8880 }
8881
092ed096
JW
8882 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8883 * NOTE: these optimizations below are related with pointer comparison
8884 * which will never be JMP32.
8885 */
8886 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
1a0dc1ac 8887 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
840b9615
JS
8888 reg_type_may_be_null(dst_reg->type)) {
8889 /* Mark all identical registers in each branch as either
57a09bf0
TG
8890 * safe or unknown depending R == 0 or R != 0 conditional.
8891 */
840b9615
JS
8892 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8893 opcode == BPF_JNE);
8894 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8895 opcode == BPF_JEQ);
5beca081
DB
8896 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8897 this_branch, other_branch) &&
8898 is_pointer_value(env, insn->dst_reg)) {
61bd5218
JK
8899 verbose(env, "R%d pointer comparison prohibited\n",
8900 insn->dst_reg);
1be7f75d 8901 return -EACCES;
17a52670 8902 }
06ee7115 8903 if (env->log.level & BPF_LOG_LEVEL)
f4d7e40a 8904 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
17a52670
AS
8905 return 0;
8906}
8907
17a52670 8908/* verify BPF_LD_IMM64 instruction */
58e2af8b 8909static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
17a52670 8910{
d8eca5bb 8911 struct bpf_insn_aux_data *aux = cur_aux(env);
638f5b90 8912 struct bpf_reg_state *regs = cur_regs(env);
4976b718 8913 struct bpf_reg_state *dst_reg;
d8eca5bb 8914 struct bpf_map *map;
17a52670
AS
8915 int err;
8916
8917 if (BPF_SIZE(insn->code) != BPF_DW) {
61bd5218 8918 verbose(env, "invalid BPF_LD_IMM insn\n");
17a52670
AS
8919 return -EINVAL;
8920 }
8921 if (insn->off != 0) {
61bd5218 8922 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
17a52670
AS
8923 return -EINVAL;
8924 }
8925
dc503a8a 8926 err = check_reg_arg(env, insn->dst_reg, DST_OP);
17a52670
AS
8927 if (err)
8928 return err;
8929
4976b718 8930 dst_reg = &regs[insn->dst_reg];
6b173873 8931 if (insn->src_reg == 0) {
6b173873
JK
8932 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8933
4976b718 8934 dst_reg->type = SCALAR_VALUE;
b03c9f9f 8935 __mark_reg_known(&regs[insn->dst_reg], imm);
17a52670 8936 return 0;
6b173873 8937 }
17a52670 8938
4976b718
HL
8939 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8940 mark_reg_known_zero(env, regs, insn->dst_reg);
8941
8942 dst_reg->type = aux->btf_var.reg_type;
8943 switch (dst_reg->type) {
8944 case PTR_TO_MEM:
8945 dst_reg->mem_size = aux->btf_var.mem_size;
8946 break;
8947 case PTR_TO_BTF_ID:
eaa6bcb7 8948 case PTR_TO_PERCPU_BTF_ID:
22dc4a0f 8949 dst_reg->btf = aux->btf_var.btf;
4976b718
HL
8950 dst_reg->btf_id = aux->btf_var.btf_id;
8951 break;
8952 default:
8953 verbose(env, "bpf verifier is misconfigured\n");
8954 return -EFAULT;
8955 }
8956 return 0;
8957 }
8958
69c087ba
YS
8959 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8960 struct bpf_prog_aux *aux = env->prog->aux;
8961 u32 subprogno = insn[1].imm;
8962
8963 if (!aux->func_info) {
8964 verbose(env, "missing btf func_info\n");
8965 return -EINVAL;
8966 }
8967 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8968 verbose(env, "callback function not static\n");
8969 return -EINVAL;
8970 }
8971
8972 dst_reg->type = PTR_TO_FUNC;
8973 dst_reg->subprogno = subprogno;
8974 return 0;
8975 }
8976
d8eca5bb
DB
8977 map = env->used_maps[aux->map_index];
8978 mark_reg_known_zero(env, regs, insn->dst_reg);
4976b718 8979 dst_reg->map_ptr = map;
d8eca5bb 8980
387544bf
AS
8981 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
8982 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
4976b718
HL
8983 dst_reg->type = PTR_TO_MAP_VALUE;
8984 dst_reg->off = aux->map_off;
d8eca5bb 8985 if (map_value_has_spin_lock(map))
4976b718 8986 dst_reg->id = ++env->id_gen;
387544bf
AS
8987 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
8988 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
4976b718 8989 dst_reg->type = CONST_PTR_TO_MAP;
d8eca5bb
DB
8990 } else {
8991 verbose(env, "bpf verifier is misconfigured\n");
8992 return -EINVAL;
8993 }
17a52670 8994
17a52670
AS
8995 return 0;
8996}
8997
96be4325
DB
8998static bool may_access_skb(enum bpf_prog_type type)
8999{
9000 switch (type) {
9001 case BPF_PROG_TYPE_SOCKET_FILTER:
9002 case BPF_PROG_TYPE_SCHED_CLS:
94caee8c 9003 case BPF_PROG_TYPE_SCHED_ACT:
96be4325
DB
9004 return true;
9005 default:
9006 return false;
9007 }
9008}
9009
ddd872bc
AS
9010/* verify safety of LD_ABS|LD_IND instructions:
9011 * - they can only appear in the programs where ctx == skb
9012 * - since they are wrappers of function calls, they scratch R1-R5 registers,
9013 * preserve R6-R9, and store return value into R0
9014 *
9015 * Implicit input:
9016 * ctx == skb == R6 == CTX
9017 *
9018 * Explicit input:
9019 * SRC == any register
9020 * IMM == 32-bit immediate
9021 *
9022 * Output:
9023 * R0 - 8/16/32-bit skb data converted to cpu endianness
9024 */
58e2af8b 9025static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
ddd872bc 9026{
638f5b90 9027 struct bpf_reg_state *regs = cur_regs(env);
6d4f151a 9028 static const int ctx_reg = BPF_REG_6;
ddd872bc 9029 u8 mode = BPF_MODE(insn->code);
ddd872bc
AS
9030 int i, err;
9031
7e40781c 9032 if (!may_access_skb(resolve_prog_type(env->prog))) {
61bd5218 9033 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
ddd872bc
AS
9034 return -EINVAL;
9035 }
9036
e0cea7ce
DB
9037 if (!env->ops->gen_ld_abs) {
9038 verbose(env, "bpf verifier is misconfigured\n");
9039 return -EINVAL;
9040 }
9041
ddd872bc 9042 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
d82bccc6 9043 BPF_SIZE(insn->code) == BPF_DW ||
ddd872bc 9044 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
61bd5218 9045 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
ddd872bc
AS
9046 return -EINVAL;
9047 }
9048
9049 /* check whether implicit source operand (register R6) is readable */
6d4f151a 9050 err = check_reg_arg(env, ctx_reg, SRC_OP);
ddd872bc
AS
9051 if (err)
9052 return err;
9053
fd978bf7
JS
9054 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9055 * gen_ld_abs() may terminate the program at runtime, leading to
9056 * reference leak.
9057 */
9058 err = check_reference_leak(env);
9059 if (err) {
9060 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9061 return err;
9062 }
9063
d83525ca
AS
9064 if (env->cur_state->active_spin_lock) {
9065 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9066 return -EINVAL;
9067 }
9068
6d4f151a 9069 if (regs[ctx_reg].type != PTR_TO_CTX) {
61bd5218
JK
9070 verbose(env,
9071 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
ddd872bc
AS
9072 return -EINVAL;
9073 }
9074
9075 if (mode == BPF_IND) {
9076 /* check explicit source operand */
dc503a8a 9077 err = check_reg_arg(env, insn->src_reg, SRC_OP);
ddd872bc
AS
9078 if (err)
9079 return err;
9080 }
9081
6d4f151a
DB
9082 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9083 if (err < 0)
9084 return err;
9085
ddd872bc 9086 /* reset caller saved regs to unreadable */
dc503a8a 9087 for (i = 0; i < CALLER_SAVED_REGS; i++) {
61bd5218 9088 mark_reg_not_init(env, regs, caller_saved[i]);
dc503a8a
EC
9089 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9090 }
ddd872bc
AS
9091
9092 /* mark destination R0 register as readable, since it contains
dc503a8a
EC
9093 * the value fetched from the packet.
9094 * Already marked as written above.
ddd872bc 9095 */
61bd5218 9096 mark_reg_unknown(env, regs, BPF_REG_0);
5327ed3d
JW
9097 /* ld_abs load up to 32-bit skb data. */
9098 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
ddd872bc
AS
9099 return 0;
9100}
9101
390ee7e2
AS
9102static int check_return_code(struct bpf_verifier_env *env)
9103{
5cf1e914 9104 struct tnum enforce_attach_type_range = tnum_unknown;
27ae7997 9105 const struct bpf_prog *prog = env->prog;
390ee7e2
AS
9106 struct bpf_reg_state *reg;
9107 struct tnum range = tnum_range(0, 1);
7e40781c 9108 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
27ae7997 9109 int err;
f782e2c3 9110 const bool is_subprog = env->cur_state->frame[0]->subprogno;
27ae7997 9111
9e4e01df 9112 /* LSM and struct_ops func-ptr's return type could be "void" */
f782e2c3
DB
9113 if (!is_subprog &&
9114 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
7e40781c 9115 prog_type == BPF_PROG_TYPE_LSM) &&
27ae7997
MKL
9116 !prog->aux->attach_func_proto->type)
9117 return 0;
9118
8fb33b60 9119 /* eBPF calling convention is such that R0 is used
27ae7997
MKL
9120 * to return the value from eBPF program.
9121 * Make sure that it's readable at this time
9122 * of bpf_exit, which means that program wrote
9123 * something into it earlier
9124 */
9125 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9126 if (err)
9127 return err;
9128
9129 if (is_pointer_value(env, BPF_REG_0)) {
9130 verbose(env, "R0 leaks addr as return value\n");
9131 return -EACCES;
9132 }
390ee7e2 9133
f782e2c3
DB
9134 reg = cur_regs(env) + BPF_REG_0;
9135 if (is_subprog) {
9136 if (reg->type != SCALAR_VALUE) {
9137 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9138 reg_type_str[reg->type]);
9139 return -EINVAL;
9140 }
9141 return 0;
9142 }
9143
7e40781c 9144 switch (prog_type) {
983695fa
DB
9145 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9146 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
1b66d253
DB
9147 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9148 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9149 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9150 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9151 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
983695fa 9152 range = tnum_range(1, 1);
77241217
SF
9153 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9154 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9155 range = tnum_range(0, 3);
ed4ed404 9156 break;
390ee7e2 9157 case BPF_PROG_TYPE_CGROUP_SKB:
5cf1e914 9158 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9159 range = tnum_range(0, 3);
9160 enforce_attach_type_range = tnum_range(2, 3);
9161 }
ed4ed404 9162 break;
390ee7e2
AS
9163 case BPF_PROG_TYPE_CGROUP_SOCK:
9164 case BPF_PROG_TYPE_SOCK_OPS:
ebc614f6 9165 case BPF_PROG_TYPE_CGROUP_DEVICE:
7b146ceb 9166 case BPF_PROG_TYPE_CGROUP_SYSCTL:
0d01da6a 9167 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
390ee7e2 9168 break;
15ab09bd
AS
9169 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9170 if (!env->prog->aux->attach_btf_id)
9171 return 0;
9172 range = tnum_const(0);
9173 break;
15d83c4d 9174 case BPF_PROG_TYPE_TRACING:
e92888c7
YS
9175 switch (env->prog->expected_attach_type) {
9176 case BPF_TRACE_FENTRY:
9177 case BPF_TRACE_FEXIT:
9178 range = tnum_const(0);
9179 break;
9180 case BPF_TRACE_RAW_TP:
9181 case BPF_MODIFY_RETURN:
15d83c4d 9182 return 0;
2ec0616e
DB
9183 case BPF_TRACE_ITER:
9184 break;
e92888c7
YS
9185 default:
9186 return -ENOTSUPP;
9187 }
15d83c4d 9188 break;
e9ddbb77
JS
9189 case BPF_PROG_TYPE_SK_LOOKUP:
9190 range = tnum_range(SK_DROP, SK_PASS);
9191 break;
e92888c7
YS
9192 case BPF_PROG_TYPE_EXT:
9193 /* freplace program can return anything as its return value
9194 * depends on the to-be-replaced kernel func or bpf program.
9195 */
390ee7e2
AS
9196 default:
9197 return 0;
9198 }
9199
390ee7e2 9200 if (reg->type != SCALAR_VALUE) {
61bd5218 9201 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
390ee7e2
AS
9202 reg_type_str[reg->type]);
9203 return -EINVAL;
9204 }
9205
9206 if (!tnum_in(range, reg->var_off)) {
bc2591d6 9207 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
390ee7e2
AS
9208 return -EINVAL;
9209 }
5cf1e914 9210
9211 if (!tnum_is_unknown(enforce_attach_type_range) &&
9212 tnum_in(enforce_attach_type_range, reg->var_off))
9213 env->prog->enforce_expected_attach_type = 1;
390ee7e2
AS
9214 return 0;
9215}
9216
475fb78f
AS
9217/* non-recursive DFS pseudo code
9218 * 1 procedure DFS-iterative(G,v):
9219 * 2 label v as discovered
9220 * 3 let S be a stack
9221 * 4 S.push(v)
9222 * 5 while S is not empty
9223 * 6 t <- S.pop()
9224 * 7 if t is what we're looking for:
9225 * 8 return t
9226 * 9 for all edges e in G.adjacentEdges(t) do
9227 * 10 if edge e is already labelled
9228 * 11 continue with the next edge
9229 * 12 w <- G.adjacentVertex(t,e)
9230 * 13 if vertex w is not discovered and not explored
9231 * 14 label e as tree-edge
9232 * 15 label w as discovered
9233 * 16 S.push(w)
9234 * 17 continue at 5
9235 * 18 else if vertex w is discovered
9236 * 19 label e as back-edge
9237 * 20 else
9238 * 21 // vertex w is explored
9239 * 22 label e as forward- or cross-edge
9240 * 23 label t as explored
9241 * 24 S.pop()
9242 *
9243 * convention:
9244 * 0x10 - discovered
9245 * 0x11 - discovered and fall-through edge labelled
9246 * 0x12 - discovered and fall-through and branch edges labelled
9247 * 0x20 - explored
9248 */
9249
9250enum {
9251 DISCOVERED = 0x10,
9252 EXPLORED = 0x20,
9253 FALLTHROUGH = 1,
9254 BRANCH = 2,
9255};
9256
dc2a4ebc
AS
9257static u32 state_htab_size(struct bpf_verifier_env *env)
9258{
9259 return env->prog->len;
9260}
9261
5d839021
AS
9262static struct bpf_verifier_state_list **explored_state(
9263 struct bpf_verifier_env *env,
9264 int idx)
9265{
dc2a4ebc
AS
9266 struct bpf_verifier_state *cur = env->cur_state;
9267 struct bpf_func_state *state = cur->frame[cur->curframe];
9268
9269 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
5d839021
AS
9270}
9271
9272static void init_explored_state(struct bpf_verifier_env *env, int idx)
9273{
a8f500af 9274 env->insn_aux_data[idx].prune_point = true;
5d839021 9275}
f1bca824 9276
59e2e27d
WAF
9277enum {
9278 DONE_EXPLORING = 0,
9279 KEEP_EXPLORING = 1,
9280};
9281
475fb78f
AS
9282/* t, w, e - match pseudo-code above:
9283 * t - index of current instruction
9284 * w - next instruction
9285 * e - edge
9286 */
2589726d
AS
9287static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9288 bool loop_ok)
475fb78f 9289{
7df737e9
AS
9290 int *insn_stack = env->cfg.insn_stack;
9291 int *insn_state = env->cfg.insn_state;
9292
475fb78f 9293 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
59e2e27d 9294 return DONE_EXPLORING;
475fb78f
AS
9295
9296 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
59e2e27d 9297 return DONE_EXPLORING;
475fb78f
AS
9298
9299 if (w < 0 || w >= env->prog->len) {
d9762e84 9300 verbose_linfo(env, t, "%d: ", t);
61bd5218 9301 verbose(env, "jump out of range from insn %d to %d\n", t, w);
475fb78f
AS
9302 return -EINVAL;
9303 }
9304
f1bca824
AS
9305 if (e == BRANCH)
9306 /* mark branch target for state pruning */
5d839021 9307 init_explored_state(env, w);
f1bca824 9308
475fb78f
AS
9309 if (insn_state[w] == 0) {
9310 /* tree-edge */
9311 insn_state[t] = DISCOVERED | e;
9312 insn_state[w] = DISCOVERED;
7df737e9 9313 if (env->cfg.cur_stack >= env->prog->len)
475fb78f 9314 return -E2BIG;
7df737e9 9315 insn_stack[env->cfg.cur_stack++] = w;
59e2e27d 9316 return KEEP_EXPLORING;
475fb78f 9317 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
2c78ee89 9318 if (loop_ok && env->bpf_capable)
59e2e27d 9319 return DONE_EXPLORING;
d9762e84
MKL
9320 verbose_linfo(env, t, "%d: ", t);
9321 verbose_linfo(env, w, "%d: ", w);
61bd5218 9322 verbose(env, "back-edge from insn %d to %d\n", t, w);
475fb78f
AS
9323 return -EINVAL;
9324 } else if (insn_state[w] == EXPLORED) {
9325 /* forward- or cross-edge */
9326 insn_state[t] = DISCOVERED | e;
9327 } else {
61bd5218 9328 verbose(env, "insn state internal bug\n");
475fb78f
AS
9329 return -EFAULT;
9330 }
59e2e27d
WAF
9331 return DONE_EXPLORING;
9332}
9333
efdb22de
YS
9334static int visit_func_call_insn(int t, int insn_cnt,
9335 struct bpf_insn *insns,
9336 struct bpf_verifier_env *env,
9337 bool visit_callee)
9338{
9339 int ret;
9340
9341 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9342 if (ret)
9343 return ret;
9344
9345 if (t + 1 < insn_cnt)
9346 init_explored_state(env, t + 1);
9347 if (visit_callee) {
9348 init_explored_state(env, t);
9349 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9350 env, false);
9351 }
9352 return ret;
9353}
9354
59e2e27d
WAF
9355/* Visits the instruction at index t and returns one of the following:
9356 * < 0 - an error occurred
9357 * DONE_EXPLORING - the instruction was fully explored
9358 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9359 */
9360static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9361{
9362 struct bpf_insn *insns = env->prog->insnsi;
9363 int ret;
9364
69c087ba
YS
9365 if (bpf_pseudo_func(insns + t))
9366 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9367
59e2e27d
WAF
9368 /* All non-branch instructions have a single fall-through edge. */
9369 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9370 BPF_CLASS(insns[t].code) != BPF_JMP32)
9371 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9372
9373 switch (BPF_OP(insns[t].code)) {
9374 case BPF_EXIT:
9375 return DONE_EXPLORING;
9376
9377 case BPF_CALL:
efdb22de
YS
9378 return visit_func_call_insn(t, insn_cnt, insns, env,
9379 insns[t].src_reg == BPF_PSEUDO_CALL);
59e2e27d
WAF
9380
9381 case BPF_JA:
9382 if (BPF_SRC(insns[t].code) != BPF_K)
9383 return -EINVAL;
9384
9385 /* unconditional jump with single edge */
9386 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9387 true);
9388 if (ret)
9389 return ret;
9390
9391 /* unconditional jmp is not a good pruning point,
9392 * but it's marked, since backtracking needs
9393 * to record jmp history in is_state_visited().
9394 */
9395 init_explored_state(env, t + insns[t].off + 1);
9396 /* tell verifier to check for equivalent states
9397 * after every call and jump
9398 */
9399 if (t + 1 < insn_cnt)
9400 init_explored_state(env, t + 1);
9401
9402 return ret;
9403
9404 default:
9405 /* conditional jump with two edges */
9406 init_explored_state(env, t);
9407 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9408 if (ret)
9409 return ret;
9410
9411 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9412 }
475fb78f
AS
9413}
9414
9415/* non-recursive depth-first-search to detect loops in BPF program
9416 * loop == back-edge in directed graph
9417 */
58e2af8b 9418static int check_cfg(struct bpf_verifier_env *env)
475fb78f 9419{
475fb78f 9420 int insn_cnt = env->prog->len;
7df737e9 9421 int *insn_stack, *insn_state;
475fb78f 9422 int ret = 0;
59e2e27d 9423 int i;
475fb78f 9424
7df737e9 9425 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f
AS
9426 if (!insn_state)
9427 return -ENOMEM;
9428
7df737e9 9429 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
475fb78f 9430 if (!insn_stack) {
71dde681 9431 kvfree(insn_state);
475fb78f
AS
9432 return -ENOMEM;
9433 }
9434
9435 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9436 insn_stack[0] = 0; /* 0 is the first instruction */
7df737e9 9437 env->cfg.cur_stack = 1;
475fb78f 9438
59e2e27d
WAF
9439 while (env->cfg.cur_stack > 0) {
9440 int t = insn_stack[env->cfg.cur_stack - 1];
475fb78f 9441
59e2e27d
WAF
9442 ret = visit_insn(t, insn_cnt, env);
9443 switch (ret) {
9444 case DONE_EXPLORING:
9445 insn_state[t] = EXPLORED;
9446 env->cfg.cur_stack--;
9447 break;
9448 case KEEP_EXPLORING:
9449 break;
9450 default:
9451 if (ret > 0) {
9452 verbose(env, "visit_insn internal bug\n");
9453 ret = -EFAULT;
475fb78f 9454 }
475fb78f 9455 goto err_free;
59e2e27d 9456 }
475fb78f
AS
9457 }
9458
59e2e27d 9459 if (env->cfg.cur_stack < 0) {
61bd5218 9460 verbose(env, "pop stack internal bug\n");
475fb78f
AS
9461 ret = -EFAULT;
9462 goto err_free;
9463 }
475fb78f 9464
475fb78f
AS
9465 for (i = 0; i < insn_cnt; i++) {
9466 if (insn_state[i] != EXPLORED) {
61bd5218 9467 verbose(env, "unreachable insn %d\n", i);
475fb78f
AS
9468 ret = -EINVAL;
9469 goto err_free;
9470 }
9471 }
9472 ret = 0; /* cfg looks good */
9473
9474err_free:
71dde681
AS
9475 kvfree(insn_state);
9476 kvfree(insn_stack);
7df737e9 9477 env->cfg.insn_state = env->cfg.insn_stack = NULL;
475fb78f
AS
9478 return ret;
9479}
9480
09b28d76
AS
9481static int check_abnormal_return(struct bpf_verifier_env *env)
9482{
9483 int i;
9484
9485 for (i = 1; i < env->subprog_cnt; i++) {
9486 if (env->subprog_info[i].has_ld_abs) {
9487 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9488 return -EINVAL;
9489 }
9490 if (env->subprog_info[i].has_tail_call) {
9491 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9492 return -EINVAL;
9493 }
9494 }
9495 return 0;
9496}
9497
838e9690
YS
9498/* The minimum supported BTF func info size */
9499#define MIN_BPF_FUNCINFO_SIZE 8
9500#define MAX_FUNCINFO_REC_SIZE 252
9501
c454a46b
MKL
9502static int check_btf_func(struct bpf_verifier_env *env,
9503 const union bpf_attr *attr,
af2ac3e1 9504 bpfptr_t uattr)
838e9690 9505{
09b28d76 9506 const struct btf_type *type, *func_proto, *ret_type;
d0b2818e 9507 u32 i, nfuncs, urec_size, min_size;
838e9690 9508 u32 krec_size = sizeof(struct bpf_func_info);
c454a46b 9509 struct bpf_func_info *krecord;
8c1b6e69 9510 struct bpf_func_info_aux *info_aux = NULL;
c454a46b
MKL
9511 struct bpf_prog *prog;
9512 const struct btf *btf;
af2ac3e1 9513 bpfptr_t urecord;
d0b2818e 9514 u32 prev_offset = 0;
09b28d76 9515 bool scalar_return;
e7ed83d6 9516 int ret = -ENOMEM;
838e9690
YS
9517
9518 nfuncs = attr->func_info_cnt;
09b28d76
AS
9519 if (!nfuncs) {
9520 if (check_abnormal_return(env))
9521 return -EINVAL;
838e9690 9522 return 0;
09b28d76 9523 }
838e9690
YS
9524
9525 if (nfuncs != env->subprog_cnt) {
9526 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9527 return -EINVAL;
9528 }
9529
9530 urec_size = attr->func_info_rec_size;
9531 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9532 urec_size > MAX_FUNCINFO_REC_SIZE ||
9533 urec_size % sizeof(u32)) {
9534 verbose(env, "invalid func info rec size %u\n", urec_size);
9535 return -EINVAL;
9536 }
9537
c454a46b
MKL
9538 prog = env->prog;
9539 btf = prog->aux->btf;
838e9690 9540
af2ac3e1 9541 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
838e9690
YS
9542 min_size = min_t(u32, krec_size, urec_size);
9543
ba64e7d8 9544 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
c454a46b
MKL
9545 if (!krecord)
9546 return -ENOMEM;
8c1b6e69
AS
9547 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9548 if (!info_aux)
9549 goto err_free;
ba64e7d8 9550
838e9690
YS
9551 for (i = 0; i < nfuncs; i++) {
9552 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9553 if (ret) {
9554 if (ret == -E2BIG) {
9555 verbose(env, "nonzero tailing record in func info");
9556 /* set the size kernel expects so loader can zero
9557 * out the rest of the record.
9558 */
af2ac3e1
AS
9559 if (copy_to_bpfptr_offset(uattr,
9560 offsetof(union bpf_attr, func_info_rec_size),
9561 &min_size, sizeof(min_size)))
838e9690
YS
9562 ret = -EFAULT;
9563 }
c454a46b 9564 goto err_free;
838e9690
YS
9565 }
9566
af2ac3e1 9567 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
838e9690 9568 ret = -EFAULT;
c454a46b 9569 goto err_free;
838e9690
YS
9570 }
9571
d30d42e0 9572 /* check insn_off */
09b28d76 9573 ret = -EINVAL;
838e9690 9574 if (i == 0) {
d30d42e0 9575 if (krecord[i].insn_off) {
838e9690 9576 verbose(env,
d30d42e0
MKL
9577 "nonzero insn_off %u for the first func info record",
9578 krecord[i].insn_off);
c454a46b 9579 goto err_free;
838e9690 9580 }
d30d42e0 9581 } else if (krecord[i].insn_off <= prev_offset) {
838e9690
YS
9582 verbose(env,
9583 "same or smaller insn offset (%u) than previous func info record (%u)",
d30d42e0 9584 krecord[i].insn_off, prev_offset);
c454a46b 9585 goto err_free;
838e9690
YS
9586 }
9587
d30d42e0 9588 if (env->subprog_info[i].start != krecord[i].insn_off) {
838e9690 9589 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
c454a46b 9590 goto err_free;
838e9690
YS
9591 }
9592
9593 /* check type_id */
ba64e7d8 9594 type = btf_type_by_id(btf, krecord[i].type_id);
51c39bb1 9595 if (!type || !btf_type_is_func(type)) {
838e9690 9596 verbose(env, "invalid type id %d in func info",
ba64e7d8 9597 krecord[i].type_id);
c454a46b 9598 goto err_free;
838e9690 9599 }
51c39bb1 9600 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
09b28d76
AS
9601
9602 func_proto = btf_type_by_id(btf, type->type);
9603 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9604 /* btf_func_check() already verified it during BTF load */
9605 goto err_free;
9606 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9607 scalar_return =
9608 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9609 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9610 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9611 goto err_free;
9612 }
9613 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9614 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9615 goto err_free;
9616 }
9617
d30d42e0 9618 prev_offset = krecord[i].insn_off;
af2ac3e1 9619 bpfptr_add(&urecord, urec_size);
838e9690
YS
9620 }
9621
ba64e7d8
YS
9622 prog->aux->func_info = krecord;
9623 prog->aux->func_info_cnt = nfuncs;
8c1b6e69 9624 prog->aux->func_info_aux = info_aux;
838e9690
YS
9625 return 0;
9626
c454a46b 9627err_free:
ba64e7d8 9628 kvfree(krecord);
8c1b6e69 9629 kfree(info_aux);
838e9690
YS
9630 return ret;
9631}
9632
ba64e7d8
YS
9633static void adjust_btf_func(struct bpf_verifier_env *env)
9634{
8c1b6e69 9635 struct bpf_prog_aux *aux = env->prog->aux;
ba64e7d8
YS
9636 int i;
9637
8c1b6e69 9638 if (!aux->func_info)
ba64e7d8
YS
9639 return;
9640
9641 for (i = 0; i < env->subprog_cnt; i++)
8c1b6e69 9642 aux->func_info[i].insn_off = env->subprog_info[i].start;
ba64e7d8
YS
9643}
9644
c454a46b
MKL
9645#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9646 sizeof(((struct bpf_line_info *)(0))->line_col))
9647#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9648
9649static int check_btf_line(struct bpf_verifier_env *env,
9650 const union bpf_attr *attr,
af2ac3e1 9651 bpfptr_t uattr)
c454a46b
MKL
9652{
9653 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9654 struct bpf_subprog_info *sub;
9655 struct bpf_line_info *linfo;
9656 struct bpf_prog *prog;
9657 const struct btf *btf;
af2ac3e1 9658 bpfptr_t ulinfo;
c454a46b
MKL
9659 int err;
9660
9661 nr_linfo = attr->line_info_cnt;
9662 if (!nr_linfo)
9663 return 0;
9664
9665 rec_size = attr->line_info_rec_size;
9666 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9667 rec_size > MAX_LINEINFO_REC_SIZE ||
9668 rec_size & (sizeof(u32) - 1))
9669 return -EINVAL;
9670
9671 /* Need to zero it in case the userspace may
9672 * pass in a smaller bpf_line_info object.
9673 */
9674 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9675 GFP_KERNEL | __GFP_NOWARN);
9676 if (!linfo)
9677 return -ENOMEM;
9678
9679 prog = env->prog;
9680 btf = prog->aux->btf;
9681
9682 s = 0;
9683 sub = env->subprog_info;
af2ac3e1 9684 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
c454a46b
MKL
9685 expected_size = sizeof(struct bpf_line_info);
9686 ncopy = min_t(u32, expected_size, rec_size);
9687 for (i = 0; i < nr_linfo; i++) {
9688 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9689 if (err) {
9690 if (err == -E2BIG) {
9691 verbose(env, "nonzero tailing record in line_info");
af2ac3e1
AS
9692 if (copy_to_bpfptr_offset(uattr,
9693 offsetof(union bpf_attr, line_info_rec_size),
9694 &expected_size, sizeof(expected_size)))
c454a46b
MKL
9695 err = -EFAULT;
9696 }
9697 goto err_free;
9698 }
9699
af2ac3e1 9700 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
c454a46b
MKL
9701 err = -EFAULT;
9702 goto err_free;
9703 }
9704
9705 /*
9706 * Check insn_off to ensure
9707 * 1) strictly increasing AND
9708 * 2) bounded by prog->len
9709 *
9710 * The linfo[0].insn_off == 0 check logically falls into
9711 * the later "missing bpf_line_info for func..." case
9712 * because the first linfo[0].insn_off must be the
9713 * first sub also and the first sub must have
9714 * subprog_info[0].start == 0.
9715 */
9716 if ((i && linfo[i].insn_off <= prev_offset) ||
9717 linfo[i].insn_off >= prog->len) {
9718 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9719 i, linfo[i].insn_off, prev_offset,
9720 prog->len);
9721 err = -EINVAL;
9722 goto err_free;
9723 }
9724
fdbaa0be
MKL
9725 if (!prog->insnsi[linfo[i].insn_off].code) {
9726 verbose(env,
9727 "Invalid insn code at line_info[%u].insn_off\n",
9728 i);
9729 err = -EINVAL;
9730 goto err_free;
9731 }
9732
23127b33
MKL
9733 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9734 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
c454a46b
MKL
9735 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9736 err = -EINVAL;
9737 goto err_free;
9738 }
9739
9740 if (s != env->subprog_cnt) {
9741 if (linfo[i].insn_off == sub[s].start) {
9742 sub[s].linfo_idx = i;
9743 s++;
9744 } else if (sub[s].start < linfo[i].insn_off) {
9745 verbose(env, "missing bpf_line_info for func#%u\n", s);
9746 err = -EINVAL;
9747 goto err_free;
9748 }
9749 }
9750
9751 prev_offset = linfo[i].insn_off;
af2ac3e1 9752 bpfptr_add(&ulinfo, rec_size);
c454a46b
MKL
9753 }
9754
9755 if (s != env->subprog_cnt) {
9756 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9757 env->subprog_cnt - s, s);
9758 err = -EINVAL;
9759 goto err_free;
9760 }
9761
9762 prog->aux->linfo = linfo;
9763 prog->aux->nr_linfo = nr_linfo;
9764
9765 return 0;
9766
9767err_free:
9768 kvfree(linfo);
9769 return err;
9770}
9771
9772static int check_btf_info(struct bpf_verifier_env *env,
9773 const union bpf_attr *attr,
af2ac3e1 9774 bpfptr_t uattr)
c454a46b
MKL
9775{
9776 struct btf *btf;
9777 int err;
9778
09b28d76
AS
9779 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9780 if (check_abnormal_return(env))
9781 return -EINVAL;
c454a46b 9782 return 0;
09b28d76 9783 }
c454a46b
MKL
9784
9785 btf = btf_get_by_fd(attr->prog_btf_fd);
9786 if (IS_ERR(btf))
9787 return PTR_ERR(btf);
350a5c4d
AS
9788 if (btf_is_kernel(btf)) {
9789 btf_put(btf);
9790 return -EACCES;
9791 }
c454a46b
MKL
9792 env->prog->aux->btf = btf;
9793
9794 err = check_btf_func(env, attr, uattr);
9795 if (err)
9796 return err;
9797
9798 err = check_btf_line(env, attr, uattr);
9799 if (err)
9800 return err;
9801
9802 return 0;
ba64e7d8
YS
9803}
9804
f1174f77
EC
9805/* check %cur's range satisfies %old's */
9806static bool range_within(struct bpf_reg_state *old,
9807 struct bpf_reg_state *cur)
9808{
b03c9f9f
EC
9809 return old->umin_value <= cur->umin_value &&
9810 old->umax_value >= cur->umax_value &&
9811 old->smin_value <= cur->smin_value &&
fd675184
DB
9812 old->smax_value >= cur->smax_value &&
9813 old->u32_min_value <= cur->u32_min_value &&
9814 old->u32_max_value >= cur->u32_max_value &&
9815 old->s32_min_value <= cur->s32_min_value &&
9816 old->s32_max_value >= cur->s32_max_value;
f1174f77
EC
9817}
9818
f1174f77
EC
9819/* If in the old state two registers had the same id, then they need to have
9820 * the same id in the new state as well. But that id could be different from
9821 * the old state, so we need to track the mapping from old to new ids.
9822 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9823 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9824 * regs with a different old id could still have new id 9, we don't care about
9825 * that.
9826 * So we look through our idmap to see if this old id has been seen before. If
9827 * so, we require the new id to match; otherwise, we add the id pair to the map.
969bf05e 9828 */
c9e73e3d 9829static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
969bf05e 9830{
f1174f77 9831 unsigned int i;
969bf05e 9832
c9e73e3d 9833 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
f1174f77
EC
9834 if (!idmap[i].old) {
9835 /* Reached an empty slot; haven't seen this id before */
9836 idmap[i].old = old_id;
9837 idmap[i].cur = cur_id;
9838 return true;
9839 }
9840 if (idmap[i].old == old_id)
9841 return idmap[i].cur == cur_id;
9842 }
9843 /* We ran out of idmap slots, which should be impossible */
9844 WARN_ON_ONCE(1);
9845 return false;
9846}
9847
9242b5f5
AS
9848static void clean_func_state(struct bpf_verifier_env *env,
9849 struct bpf_func_state *st)
9850{
9851 enum bpf_reg_liveness live;
9852 int i, j;
9853
9854 for (i = 0; i < BPF_REG_FP; i++) {
9855 live = st->regs[i].live;
9856 /* liveness must not touch this register anymore */
9857 st->regs[i].live |= REG_LIVE_DONE;
9858 if (!(live & REG_LIVE_READ))
9859 /* since the register is unused, clear its state
9860 * to make further comparison simpler
9861 */
f54c7898 9862 __mark_reg_not_init(env, &st->regs[i]);
9242b5f5
AS
9863 }
9864
9865 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9866 live = st->stack[i].spilled_ptr.live;
9867 /* liveness must not touch this stack slot anymore */
9868 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9869 if (!(live & REG_LIVE_READ)) {
f54c7898 9870 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
9242b5f5
AS
9871 for (j = 0; j < BPF_REG_SIZE; j++)
9872 st->stack[i].slot_type[j] = STACK_INVALID;
9873 }
9874 }
9875}
9876
9877static void clean_verifier_state(struct bpf_verifier_env *env,
9878 struct bpf_verifier_state *st)
9879{
9880 int i;
9881
9882 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9883 /* all regs in this state in all frames were already marked */
9884 return;
9885
9886 for (i = 0; i <= st->curframe; i++)
9887 clean_func_state(env, st->frame[i]);
9888}
9889
9890/* the parentage chains form a tree.
9891 * the verifier states are added to state lists at given insn and
9892 * pushed into state stack for future exploration.
9893 * when the verifier reaches bpf_exit insn some of the verifer states
9894 * stored in the state lists have their final liveness state already,
9895 * but a lot of states will get revised from liveness point of view when
9896 * the verifier explores other branches.
9897 * Example:
9898 * 1: r0 = 1
9899 * 2: if r1 == 100 goto pc+1
9900 * 3: r0 = 2
9901 * 4: exit
9902 * when the verifier reaches exit insn the register r0 in the state list of
9903 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9904 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9905 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9906 *
9907 * Since the verifier pushes the branch states as it sees them while exploring
9908 * the program the condition of walking the branch instruction for the second
9909 * time means that all states below this branch were already explored and
8fb33b60 9910 * their final liveness marks are already propagated.
9242b5f5
AS
9911 * Hence when the verifier completes the search of state list in is_state_visited()
9912 * we can call this clean_live_states() function to mark all liveness states
9913 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9914 * will not be used.
9915 * This function also clears the registers and stack for states that !READ
9916 * to simplify state merging.
9917 *
9918 * Important note here that walking the same branch instruction in the callee
9919 * doesn't meant that the states are DONE. The verifier has to compare
9920 * the callsites
9921 */
9922static void clean_live_states(struct bpf_verifier_env *env, int insn,
9923 struct bpf_verifier_state *cur)
9924{
9925 struct bpf_verifier_state_list *sl;
9926 int i;
9927
5d839021 9928 sl = *explored_state(env, insn);
a8f500af 9929 while (sl) {
2589726d
AS
9930 if (sl->state.branches)
9931 goto next;
dc2a4ebc
AS
9932 if (sl->state.insn_idx != insn ||
9933 sl->state.curframe != cur->curframe)
9242b5f5
AS
9934 goto next;
9935 for (i = 0; i <= cur->curframe; i++)
9936 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9937 goto next;
9938 clean_verifier_state(env, &sl->state);
9939next:
9940 sl = sl->next;
9941 }
9942}
9943
f1174f77 9944/* Returns true if (rold safe implies rcur safe) */
e042aa53
DB
9945static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9946 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
f1174f77 9947{
f4d7e40a
AS
9948 bool equal;
9949
dc503a8a
EC
9950 if (!(rold->live & REG_LIVE_READ))
9951 /* explored state didn't use this */
9952 return true;
9953
679c782d 9954 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
f4d7e40a
AS
9955
9956 if (rold->type == PTR_TO_STACK)
9957 /* two stack pointers are equal only if they're pointing to
9958 * the same stack frame, since fp-8 in foo != fp-8 in bar
9959 */
9960 return equal && rold->frameno == rcur->frameno;
9961
9962 if (equal)
969bf05e
AS
9963 return true;
9964
f1174f77
EC
9965 if (rold->type == NOT_INIT)
9966 /* explored state can't have used this */
969bf05e 9967 return true;
f1174f77
EC
9968 if (rcur->type == NOT_INIT)
9969 return false;
9970 switch (rold->type) {
9971 case SCALAR_VALUE:
e042aa53
DB
9972 if (env->explore_alu_limits)
9973 return false;
f1174f77 9974 if (rcur->type == SCALAR_VALUE) {
b5dc0163
AS
9975 if (!rold->precise && !rcur->precise)
9976 return true;
f1174f77
EC
9977 /* new val must satisfy old val knowledge */
9978 return range_within(rold, rcur) &&
9979 tnum_in(rold->var_off, rcur->var_off);
9980 } else {
179d1c56
JH
9981 /* We're trying to use a pointer in place of a scalar.
9982 * Even if the scalar was unbounded, this could lead to
9983 * pointer leaks because scalars are allowed to leak
9984 * while pointers are not. We could make this safe in
9985 * special cases if root is calling us, but it's
9986 * probably not worth the hassle.
f1174f77 9987 */
179d1c56 9988 return false;
f1174f77 9989 }
69c087ba 9990 case PTR_TO_MAP_KEY:
f1174f77 9991 case PTR_TO_MAP_VALUE:
1b688a19
EC
9992 /* If the new min/max/var_off satisfy the old ones and
9993 * everything else matches, we are OK.
d83525ca
AS
9994 * 'id' is not compared, since it's only used for maps with
9995 * bpf_spin_lock inside map element and in such cases if
9996 * the rest of the prog is valid for one map element then
9997 * it's valid for all map elements regardless of the key
9998 * used in bpf_map_lookup()
1b688a19
EC
9999 */
10000 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10001 range_within(rold, rcur) &&
10002 tnum_in(rold->var_off, rcur->var_off);
f1174f77
EC
10003 case PTR_TO_MAP_VALUE_OR_NULL:
10004 /* a PTR_TO_MAP_VALUE could be safe to use as a
10005 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10006 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10007 * checked, doing so could have affected others with the same
10008 * id, and we can't check for that because we lost the id when
10009 * we converted to a PTR_TO_MAP_VALUE.
10010 */
10011 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10012 return false;
10013 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10014 return false;
10015 /* Check our ids match any regs they're supposed to */
10016 return check_ids(rold->id, rcur->id, idmap);
de8f3a83 10017 case PTR_TO_PACKET_META:
f1174f77 10018 case PTR_TO_PACKET:
de8f3a83 10019 if (rcur->type != rold->type)
f1174f77
EC
10020 return false;
10021 /* We must have at least as much range as the old ptr
10022 * did, so that any accesses which were safe before are
10023 * still safe. This is true even if old range < old off,
10024 * since someone could have accessed through (ptr - k), or
10025 * even done ptr -= k in a register, to get a safe access.
10026 */
10027 if (rold->range > rcur->range)
10028 return false;
10029 /* If the offsets don't match, we can't trust our alignment;
10030 * nor can we be sure that we won't fall out of range.
10031 */
10032 if (rold->off != rcur->off)
10033 return false;
10034 /* id relations must be preserved */
10035 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10036 return false;
10037 /* new val must satisfy old val knowledge */
10038 return range_within(rold, rcur) &&
10039 tnum_in(rold->var_off, rcur->var_off);
10040 case PTR_TO_CTX:
10041 case CONST_PTR_TO_MAP:
f1174f77 10042 case PTR_TO_PACKET_END:
d58e468b 10043 case PTR_TO_FLOW_KEYS:
c64b7983
JS
10044 case PTR_TO_SOCKET:
10045 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10046 case PTR_TO_SOCK_COMMON:
10047 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10048 case PTR_TO_TCP_SOCK:
10049 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10050 case PTR_TO_XDP_SOCK:
f1174f77
EC
10051 /* Only valid matches are exact, which memcmp() above
10052 * would have accepted
10053 */
10054 default:
10055 /* Don't know what's going on, just say it's not safe */
10056 return false;
10057 }
969bf05e 10058
f1174f77
EC
10059 /* Shouldn't get here; if we do, say it's not safe */
10060 WARN_ON_ONCE(1);
969bf05e
AS
10061 return false;
10062}
10063
e042aa53
DB
10064static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10065 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
638f5b90
AS
10066{
10067 int i, spi;
10068
638f5b90
AS
10069 /* walk slots of the explored stack and ignore any additional
10070 * slots in the current stack, since explored(safe) state
10071 * didn't use them
10072 */
10073 for (i = 0; i < old->allocated_stack; i++) {
10074 spi = i / BPF_REG_SIZE;
10075
b233920c
AS
10076 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10077 i += BPF_REG_SIZE - 1;
cc2b14d5 10078 /* explored state didn't use this */
fd05e57b 10079 continue;
b233920c 10080 }
cc2b14d5 10081
638f5b90
AS
10082 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10083 continue;
19e2dbb7
AS
10084
10085 /* explored stack has more populated slots than current stack
10086 * and these slots were used
10087 */
10088 if (i >= cur->allocated_stack)
10089 return false;
10090
cc2b14d5
AS
10091 /* if old state was safe with misc data in the stack
10092 * it will be safe with zero-initialized stack.
10093 * The opposite is not true
10094 */
10095 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10096 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10097 continue;
638f5b90
AS
10098 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10099 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10100 /* Ex: old explored (safe) state has STACK_SPILL in
b8c1a309 10101 * this stack slot, but current has STACK_MISC ->
638f5b90
AS
10102 * this verifier states are not equivalent,
10103 * return false to continue verification of this path
10104 */
10105 return false;
10106 if (i % BPF_REG_SIZE)
10107 continue;
10108 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10109 continue;
e042aa53
DB
10110 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10111 &cur->stack[spi].spilled_ptr, idmap))
638f5b90
AS
10112 /* when explored and current stack slot are both storing
10113 * spilled registers, check that stored pointers types
10114 * are the same as well.
10115 * Ex: explored safe path could have stored
10116 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10117 * but current path has stored:
10118 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10119 * such verifier states are not equivalent.
10120 * return false to continue verification of this path
10121 */
10122 return false;
10123 }
10124 return true;
10125}
10126
fd978bf7
JS
10127static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10128{
10129 if (old->acquired_refs != cur->acquired_refs)
10130 return false;
10131 return !memcmp(old->refs, cur->refs,
10132 sizeof(*old->refs) * old->acquired_refs);
10133}
10134
f1bca824
AS
10135/* compare two verifier states
10136 *
10137 * all states stored in state_list are known to be valid, since
10138 * verifier reached 'bpf_exit' instruction through them
10139 *
10140 * this function is called when verifier exploring different branches of
10141 * execution popped from the state stack. If it sees an old state that has
10142 * more strict register state and more strict stack state then this execution
10143 * branch doesn't need to be explored further, since verifier already
10144 * concluded that more strict state leads to valid finish.
10145 *
10146 * Therefore two states are equivalent if register state is more conservative
10147 * and explored stack state is more conservative than the current one.
10148 * Example:
10149 * explored current
10150 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10151 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10152 *
10153 * In other words if current stack state (one being explored) has more
10154 * valid slots than old one that already passed validation, it means
10155 * the verifier can stop exploring and conclude that current state is valid too
10156 *
10157 * Similarly with registers. If explored state has register type as invalid
10158 * whereas register type in current state is meaningful, it means that
10159 * the current state will reach 'bpf_exit' instruction safely
10160 */
c9e73e3d 10161static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
f4d7e40a 10162 struct bpf_func_state *cur)
f1bca824
AS
10163{
10164 int i;
10165
c9e73e3d
LB
10166 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10167 for (i = 0; i < MAX_BPF_REG; i++)
e042aa53
DB
10168 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10169 env->idmap_scratch))
c9e73e3d 10170 return false;
f1bca824 10171
e042aa53 10172 if (!stacksafe(env, old, cur, env->idmap_scratch))
c9e73e3d 10173 return false;
fd978bf7
JS
10174
10175 if (!refsafe(old, cur))
c9e73e3d
LB
10176 return false;
10177
10178 return true;
f1bca824
AS
10179}
10180
f4d7e40a
AS
10181static bool states_equal(struct bpf_verifier_env *env,
10182 struct bpf_verifier_state *old,
10183 struct bpf_verifier_state *cur)
10184{
10185 int i;
10186
10187 if (old->curframe != cur->curframe)
10188 return false;
10189
979d63d5
DB
10190 /* Verification state from speculative execution simulation
10191 * must never prune a non-speculative execution one.
10192 */
10193 if (old->speculative && !cur->speculative)
10194 return false;
10195
d83525ca
AS
10196 if (old->active_spin_lock != cur->active_spin_lock)
10197 return false;
10198
f4d7e40a
AS
10199 /* for states to be equal callsites have to be the same
10200 * and all frame states need to be equivalent
10201 */
10202 for (i = 0; i <= old->curframe; i++) {
10203 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10204 return false;
c9e73e3d 10205 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
f4d7e40a
AS
10206 return false;
10207 }
10208 return true;
10209}
10210
5327ed3d
JW
10211/* Return 0 if no propagation happened. Return negative error code if error
10212 * happened. Otherwise, return the propagated bit.
10213 */
55e7f3b5
JW
10214static int propagate_liveness_reg(struct bpf_verifier_env *env,
10215 struct bpf_reg_state *reg,
10216 struct bpf_reg_state *parent_reg)
10217{
5327ed3d
JW
10218 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10219 u8 flag = reg->live & REG_LIVE_READ;
55e7f3b5
JW
10220 int err;
10221
5327ed3d
JW
10222 /* When comes here, read flags of PARENT_REG or REG could be any of
10223 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10224 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10225 */
10226 if (parent_flag == REG_LIVE_READ64 ||
10227 /* Or if there is no read flag from REG. */
10228 !flag ||
10229 /* Or if the read flag from REG is the same as PARENT_REG. */
10230 parent_flag == flag)
55e7f3b5
JW
10231 return 0;
10232
5327ed3d 10233 err = mark_reg_read(env, reg, parent_reg, flag);
55e7f3b5
JW
10234 if (err)
10235 return err;
10236
5327ed3d 10237 return flag;
55e7f3b5
JW
10238}
10239
8e9cd9ce 10240/* A write screens off any subsequent reads; but write marks come from the
f4d7e40a
AS
10241 * straight-line code between a state and its parent. When we arrive at an
10242 * equivalent state (jump target or such) we didn't arrive by the straight-line
10243 * code, so read marks in the state must propagate to the parent regardless
10244 * of the state's write marks. That's what 'parent == state->parent' comparison
679c782d 10245 * in mark_reg_read() is for.
8e9cd9ce 10246 */
f4d7e40a
AS
10247static int propagate_liveness(struct bpf_verifier_env *env,
10248 const struct bpf_verifier_state *vstate,
10249 struct bpf_verifier_state *vparent)
dc503a8a 10250{
3f8cafa4 10251 struct bpf_reg_state *state_reg, *parent_reg;
f4d7e40a 10252 struct bpf_func_state *state, *parent;
3f8cafa4 10253 int i, frame, err = 0;
dc503a8a 10254
f4d7e40a
AS
10255 if (vparent->curframe != vstate->curframe) {
10256 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10257 vparent->curframe, vstate->curframe);
10258 return -EFAULT;
10259 }
dc503a8a
EC
10260 /* Propagate read liveness of registers... */
10261 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
83d16312 10262 for (frame = 0; frame <= vstate->curframe; frame++) {
3f8cafa4
JW
10263 parent = vparent->frame[frame];
10264 state = vstate->frame[frame];
10265 parent_reg = parent->regs;
10266 state_reg = state->regs;
83d16312
JK
10267 /* We don't need to worry about FP liveness, it's read-only */
10268 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
55e7f3b5
JW
10269 err = propagate_liveness_reg(env, &state_reg[i],
10270 &parent_reg[i]);
5327ed3d 10271 if (err < 0)
3f8cafa4 10272 return err;
5327ed3d
JW
10273 if (err == REG_LIVE_READ64)
10274 mark_insn_zext(env, &parent_reg[i]);
dc503a8a 10275 }
f4d7e40a 10276
1b04aee7 10277 /* Propagate stack slots. */
f4d7e40a
AS
10278 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10279 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
3f8cafa4
JW
10280 parent_reg = &parent->stack[i].spilled_ptr;
10281 state_reg = &state->stack[i].spilled_ptr;
55e7f3b5
JW
10282 err = propagate_liveness_reg(env, state_reg,
10283 parent_reg);
5327ed3d 10284 if (err < 0)
3f8cafa4 10285 return err;
dc503a8a
EC
10286 }
10287 }
5327ed3d 10288 return 0;
dc503a8a
EC
10289}
10290
a3ce685d
AS
10291/* find precise scalars in the previous equivalent state and
10292 * propagate them into the current state
10293 */
10294static int propagate_precision(struct bpf_verifier_env *env,
10295 const struct bpf_verifier_state *old)
10296{
10297 struct bpf_reg_state *state_reg;
10298 struct bpf_func_state *state;
10299 int i, err = 0;
10300
10301 state = old->frame[old->curframe];
10302 state_reg = state->regs;
10303 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10304 if (state_reg->type != SCALAR_VALUE ||
10305 !state_reg->precise)
10306 continue;
10307 if (env->log.level & BPF_LOG_LEVEL2)
10308 verbose(env, "propagating r%d\n", i);
10309 err = mark_chain_precision(env, i);
10310 if (err < 0)
10311 return err;
10312 }
10313
10314 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10315 if (state->stack[i].slot_type[0] != STACK_SPILL)
10316 continue;
10317 state_reg = &state->stack[i].spilled_ptr;
10318 if (state_reg->type != SCALAR_VALUE ||
10319 !state_reg->precise)
10320 continue;
10321 if (env->log.level & BPF_LOG_LEVEL2)
10322 verbose(env, "propagating fp%d\n",
10323 (-i - 1) * BPF_REG_SIZE);
10324 err = mark_chain_precision_stack(env, i);
10325 if (err < 0)
10326 return err;
10327 }
10328 return 0;
10329}
10330
2589726d
AS
10331static bool states_maybe_looping(struct bpf_verifier_state *old,
10332 struct bpf_verifier_state *cur)
10333{
10334 struct bpf_func_state *fold, *fcur;
10335 int i, fr = cur->curframe;
10336
10337 if (old->curframe != fr)
10338 return false;
10339
10340 fold = old->frame[fr];
10341 fcur = cur->frame[fr];
10342 for (i = 0; i < MAX_BPF_REG; i++)
10343 if (memcmp(&fold->regs[i], &fcur->regs[i],
10344 offsetof(struct bpf_reg_state, parent)))
10345 return false;
10346 return true;
10347}
10348
10349
58e2af8b 10350static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
f1bca824 10351{
58e2af8b 10352 struct bpf_verifier_state_list *new_sl;
9f4686c4 10353 struct bpf_verifier_state_list *sl, **pprev;
679c782d 10354 struct bpf_verifier_state *cur = env->cur_state, *new;
ceefbc96 10355 int i, j, err, states_cnt = 0;
10d274e8 10356 bool add_new_state = env->test_state_freq ? true : false;
f1bca824 10357
b5dc0163 10358 cur->last_insn_idx = env->prev_insn_idx;
a8f500af 10359 if (!env->insn_aux_data[insn_idx].prune_point)
f1bca824
AS
10360 /* this 'insn_idx' instruction wasn't marked, so we will not
10361 * be doing state search here
10362 */
10363 return 0;
10364
2589726d
AS
10365 /* bpf progs typically have pruning point every 4 instructions
10366 * http://vger.kernel.org/bpfconf2019.html#session-1
10367 * Do not add new state for future pruning if the verifier hasn't seen
10368 * at least 2 jumps and at least 8 instructions.
10369 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10370 * In tests that amounts to up to 50% reduction into total verifier
10371 * memory consumption and 20% verifier time speedup.
10372 */
10373 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10374 env->insn_processed - env->prev_insn_processed >= 8)
10375 add_new_state = true;
10376
a8f500af
AS
10377 pprev = explored_state(env, insn_idx);
10378 sl = *pprev;
10379
9242b5f5
AS
10380 clean_live_states(env, insn_idx, cur);
10381
a8f500af 10382 while (sl) {
dc2a4ebc
AS
10383 states_cnt++;
10384 if (sl->state.insn_idx != insn_idx)
10385 goto next;
2589726d
AS
10386 if (sl->state.branches) {
10387 if (states_maybe_looping(&sl->state, cur) &&
10388 states_equal(env, &sl->state, cur)) {
10389 verbose_linfo(env, insn_idx, "; ");
10390 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10391 return -EINVAL;
10392 }
10393 /* if the verifier is processing a loop, avoid adding new state
10394 * too often, since different loop iterations have distinct
10395 * states and may not help future pruning.
10396 * This threshold shouldn't be too low to make sure that
10397 * a loop with large bound will be rejected quickly.
10398 * The most abusive loop will be:
10399 * r1 += 1
10400 * if r1 < 1000000 goto pc-2
10401 * 1M insn_procssed limit / 100 == 10k peak states.
10402 * This threshold shouldn't be too high either, since states
10403 * at the end of the loop are likely to be useful in pruning.
10404 */
10405 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10406 env->insn_processed - env->prev_insn_processed < 100)
10407 add_new_state = false;
10408 goto miss;
10409 }
638f5b90 10410 if (states_equal(env, &sl->state, cur)) {
9f4686c4 10411 sl->hit_cnt++;
f1bca824 10412 /* reached equivalent register/stack state,
dc503a8a
EC
10413 * prune the search.
10414 * Registers read by the continuation are read by us.
8e9cd9ce
EC
10415 * If we have any write marks in env->cur_state, they
10416 * will prevent corresponding reads in the continuation
10417 * from reaching our parent (an explored_state). Our
10418 * own state will get the read marks recorded, but
10419 * they'll be immediately forgotten as we're pruning
10420 * this state and will pop a new one.
f1bca824 10421 */
f4d7e40a 10422 err = propagate_liveness(env, &sl->state, cur);
a3ce685d
AS
10423
10424 /* if previous state reached the exit with precision and
10425 * current state is equivalent to it (except precsion marks)
10426 * the precision needs to be propagated back in
10427 * the current state.
10428 */
10429 err = err ? : push_jmp_history(env, cur);
10430 err = err ? : propagate_precision(env, &sl->state);
f4d7e40a
AS
10431 if (err)
10432 return err;
f1bca824 10433 return 1;
dc503a8a 10434 }
2589726d
AS
10435miss:
10436 /* when new state is not going to be added do not increase miss count.
10437 * Otherwise several loop iterations will remove the state
10438 * recorded earlier. The goal of these heuristics is to have
10439 * states from some iterations of the loop (some in the beginning
10440 * and some at the end) to help pruning.
10441 */
10442 if (add_new_state)
10443 sl->miss_cnt++;
9f4686c4
AS
10444 /* heuristic to determine whether this state is beneficial
10445 * to keep checking from state equivalence point of view.
10446 * Higher numbers increase max_states_per_insn and verification time,
10447 * but do not meaningfully decrease insn_processed.
10448 */
10449 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10450 /* the state is unlikely to be useful. Remove it to
10451 * speed up verification
10452 */
10453 *pprev = sl->next;
10454 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
2589726d
AS
10455 u32 br = sl->state.branches;
10456
10457 WARN_ONCE(br,
10458 "BUG live_done but branches_to_explore %d\n",
10459 br);
9f4686c4
AS
10460 free_verifier_state(&sl->state, false);
10461 kfree(sl);
10462 env->peak_states--;
10463 } else {
10464 /* cannot free this state, since parentage chain may
10465 * walk it later. Add it for free_list instead to
10466 * be freed at the end of verification
10467 */
10468 sl->next = env->free_list;
10469 env->free_list = sl;
10470 }
10471 sl = *pprev;
10472 continue;
10473 }
dc2a4ebc 10474next:
9f4686c4
AS
10475 pprev = &sl->next;
10476 sl = *pprev;
f1bca824
AS
10477 }
10478
06ee7115
AS
10479 if (env->max_states_per_insn < states_cnt)
10480 env->max_states_per_insn = states_cnt;
10481
2c78ee89 10482 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
b5dc0163 10483 return push_jmp_history(env, cur);
ceefbc96 10484
2589726d 10485 if (!add_new_state)
b5dc0163 10486 return push_jmp_history(env, cur);
ceefbc96 10487
2589726d
AS
10488 /* There were no equivalent states, remember the current one.
10489 * Technically the current state is not proven to be safe yet,
f4d7e40a 10490 * but it will either reach outer most bpf_exit (which means it's safe)
2589726d 10491 * or it will be rejected. When there are no loops the verifier won't be
f4d7e40a 10492 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
2589726d
AS
10493 * again on the way to bpf_exit.
10494 * When looping the sl->state.branches will be > 0 and this state
10495 * will not be considered for equivalence until branches == 0.
f1bca824 10496 */
638f5b90 10497 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
f1bca824
AS
10498 if (!new_sl)
10499 return -ENOMEM;
06ee7115
AS
10500 env->total_states++;
10501 env->peak_states++;
2589726d
AS
10502 env->prev_jmps_processed = env->jmps_processed;
10503 env->prev_insn_processed = env->insn_processed;
f1bca824
AS
10504
10505 /* add new state to the head of linked list */
679c782d
EC
10506 new = &new_sl->state;
10507 err = copy_verifier_state(new, cur);
1969db47 10508 if (err) {
679c782d 10509 free_verifier_state(new, false);
1969db47
AS
10510 kfree(new_sl);
10511 return err;
10512 }
dc2a4ebc 10513 new->insn_idx = insn_idx;
2589726d
AS
10514 WARN_ONCE(new->branches != 1,
10515 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
b5dc0163 10516
2589726d 10517 cur->parent = new;
b5dc0163
AS
10518 cur->first_insn_idx = insn_idx;
10519 clear_jmp_history(cur);
5d839021
AS
10520 new_sl->next = *explored_state(env, insn_idx);
10521 *explored_state(env, insn_idx) = new_sl;
7640ead9
JK
10522 /* connect new state to parentage chain. Current frame needs all
10523 * registers connected. Only r6 - r9 of the callers are alive (pushed
10524 * to the stack implicitly by JITs) so in callers' frames connect just
10525 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10526 * the state of the call instruction (with WRITTEN set), and r0 comes
10527 * from callee with its full parentage chain, anyway.
10528 */
8e9cd9ce
EC
10529 /* clear write marks in current state: the writes we did are not writes
10530 * our child did, so they don't screen off its reads from us.
10531 * (There are no read marks in current state, because reads always mark
10532 * their parent and current state never has children yet. Only
10533 * explored_states can get read marks.)
10534 */
eea1c227
AS
10535 for (j = 0; j <= cur->curframe; j++) {
10536 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10537 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10538 for (i = 0; i < BPF_REG_FP; i++)
10539 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10540 }
f4d7e40a
AS
10541
10542 /* all stack frames are accessible from callee, clear them all */
10543 for (j = 0; j <= cur->curframe; j++) {
10544 struct bpf_func_state *frame = cur->frame[j];
679c782d 10545 struct bpf_func_state *newframe = new->frame[j];
f4d7e40a 10546
679c782d 10547 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
cc2b14d5 10548 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
679c782d
EC
10549 frame->stack[i].spilled_ptr.parent =
10550 &newframe->stack[i].spilled_ptr;
10551 }
f4d7e40a 10552 }
f1bca824
AS
10553 return 0;
10554}
10555
c64b7983
JS
10556/* Return true if it's OK to have the same insn return a different type. */
10557static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10558{
10559 switch (type) {
10560 case PTR_TO_CTX:
10561 case PTR_TO_SOCKET:
10562 case PTR_TO_SOCKET_OR_NULL:
46f8bc92
MKL
10563 case PTR_TO_SOCK_COMMON:
10564 case PTR_TO_SOCK_COMMON_OR_NULL:
655a51e5
MKL
10565 case PTR_TO_TCP_SOCK:
10566 case PTR_TO_TCP_SOCK_OR_NULL:
fada7fdc 10567 case PTR_TO_XDP_SOCK:
2a02759e 10568 case PTR_TO_BTF_ID:
b121b341 10569 case PTR_TO_BTF_ID_OR_NULL:
c64b7983
JS
10570 return false;
10571 default:
10572 return true;
10573 }
10574}
10575
10576/* If an instruction was previously used with particular pointer types, then we
10577 * need to be careful to avoid cases such as the below, where it may be ok
10578 * for one branch accessing the pointer, but not ok for the other branch:
10579 *
10580 * R1 = sock_ptr
10581 * goto X;
10582 * ...
10583 * R1 = some_other_valid_ptr;
10584 * goto X;
10585 * ...
10586 * R2 = *(u32 *)(R1 + 0);
10587 */
10588static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10589{
10590 return src != prev && (!reg_type_mismatch_ok(src) ||
10591 !reg_type_mismatch_ok(prev));
10592}
10593
58e2af8b 10594static int do_check(struct bpf_verifier_env *env)
17a52670 10595{
6f8a57cc 10596 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1 10597 struct bpf_verifier_state *state = env->cur_state;
17a52670 10598 struct bpf_insn *insns = env->prog->insnsi;
638f5b90 10599 struct bpf_reg_state *regs;
06ee7115 10600 int insn_cnt = env->prog->len;
17a52670 10601 bool do_print_state = false;
b5dc0163 10602 int prev_insn_idx = -1;
17a52670 10603
17a52670
AS
10604 for (;;) {
10605 struct bpf_insn *insn;
10606 u8 class;
10607 int err;
10608
b5dc0163 10609 env->prev_insn_idx = prev_insn_idx;
c08435ec 10610 if (env->insn_idx >= insn_cnt) {
61bd5218 10611 verbose(env, "invalid insn idx %d insn_cnt %d\n",
c08435ec 10612 env->insn_idx, insn_cnt);
17a52670
AS
10613 return -EFAULT;
10614 }
10615
c08435ec 10616 insn = &insns[env->insn_idx];
17a52670
AS
10617 class = BPF_CLASS(insn->code);
10618
06ee7115 10619 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
61bd5218
JK
10620 verbose(env,
10621 "BPF program is too large. Processed %d insn\n",
06ee7115 10622 env->insn_processed);
17a52670
AS
10623 return -E2BIG;
10624 }
10625
c08435ec 10626 err = is_state_visited(env, env->insn_idx);
f1bca824
AS
10627 if (err < 0)
10628 return err;
10629 if (err == 1) {
10630 /* found equivalent state, can prune the search */
06ee7115 10631 if (env->log.level & BPF_LOG_LEVEL) {
f1bca824 10632 if (do_print_state)
979d63d5
DB
10633 verbose(env, "\nfrom %d to %d%s: safe\n",
10634 env->prev_insn_idx, env->insn_idx,
10635 env->cur_state->speculative ?
10636 " (speculative execution)" : "");
f1bca824 10637 else
c08435ec 10638 verbose(env, "%d: safe\n", env->insn_idx);
f1bca824
AS
10639 }
10640 goto process_bpf_exit;
10641 }
10642
c3494801
AS
10643 if (signal_pending(current))
10644 return -EAGAIN;
10645
3c2ce60b
DB
10646 if (need_resched())
10647 cond_resched();
10648
06ee7115
AS
10649 if (env->log.level & BPF_LOG_LEVEL2 ||
10650 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10651 if (env->log.level & BPF_LOG_LEVEL2)
c08435ec 10652 verbose(env, "%d:", env->insn_idx);
c5fc9692 10653 else
979d63d5
DB
10654 verbose(env, "\nfrom %d to %d%s:",
10655 env->prev_insn_idx, env->insn_idx,
10656 env->cur_state->speculative ?
10657 " (speculative execution)" : "");
f4d7e40a 10658 print_verifier_state(env, state->frame[state->curframe]);
17a52670
AS
10659 do_print_state = false;
10660 }
10661
06ee7115 10662 if (env->log.level & BPF_LOG_LEVEL) {
7105e828 10663 const struct bpf_insn_cbs cbs = {
e6ac2450 10664 .cb_call = disasm_kfunc_name,
7105e828 10665 .cb_print = verbose,
abe08840 10666 .private_data = env,
7105e828
DB
10667 };
10668
c08435ec
DB
10669 verbose_linfo(env, env->insn_idx, "; ");
10670 verbose(env, "%d: ", env->insn_idx);
abe08840 10671 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17a52670
AS
10672 }
10673
cae1927c 10674 if (bpf_prog_is_dev_bound(env->prog->aux)) {
c08435ec
DB
10675 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10676 env->prev_insn_idx);
cae1927c
JK
10677 if (err)
10678 return err;
10679 }
13a27dfc 10680
638f5b90 10681 regs = cur_regs(env);
fe9a5ca7 10682 sanitize_mark_insn_seen(env);
b5dc0163 10683 prev_insn_idx = env->insn_idx;
fd978bf7 10684
17a52670 10685 if (class == BPF_ALU || class == BPF_ALU64) {
1be7f75d 10686 err = check_alu_op(env, insn);
17a52670
AS
10687 if (err)
10688 return err;
10689
10690 } else if (class == BPF_LDX) {
3df126f3 10691 enum bpf_reg_type *prev_src_type, src_reg_type;
9bac3d6d
AS
10692
10693 /* check for reserved fields is already done */
10694
17a52670 10695 /* check src operand */
dc503a8a 10696 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10697 if (err)
10698 return err;
10699
dc503a8a 10700 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17a52670
AS
10701 if (err)
10702 return err;
10703
725f9dcd
AS
10704 src_reg_type = regs[insn->src_reg].type;
10705
17a52670
AS
10706 /* check that memory (src_reg + off) is readable,
10707 * the state of dst_reg will be updated by this func
10708 */
c08435ec
DB
10709 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10710 insn->off, BPF_SIZE(insn->code),
10711 BPF_READ, insn->dst_reg, false);
17a52670
AS
10712 if (err)
10713 return err;
10714
c08435ec 10715 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10716
10717 if (*prev_src_type == NOT_INIT) {
9bac3d6d
AS
10718 /* saw a valid insn
10719 * dst_reg = *(u32 *)(src_reg + off)
3df126f3 10720 * save type to validate intersecting paths
9bac3d6d 10721 */
3df126f3 10722 *prev_src_type = src_reg_type;
9bac3d6d 10723
c64b7983 10724 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
9bac3d6d
AS
10725 /* ABuser program is trying to use the same insn
10726 * dst_reg = *(u32*) (src_reg + off)
10727 * with different pointer types:
10728 * src_reg == ctx in one branch and
10729 * src_reg == stack|map in some other branch.
10730 * Reject it.
10731 */
61bd5218 10732 verbose(env, "same insn cannot be used with different pointers\n");
9bac3d6d
AS
10733 return -EINVAL;
10734 }
10735
17a52670 10736 } else if (class == BPF_STX) {
3df126f3 10737 enum bpf_reg_type *prev_dst_type, dst_reg_type;
d691f9e8 10738
91c960b0
BJ
10739 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10740 err = check_atomic(env, env->insn_idx, insn);
17a52670
AS
10741 if (err)
10742 return err;
c08435ec 10743 env->insn_idx++;
17a52670
AS
10744 continue;
10745 }
10746
5ca419f2
BJ
10747 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10748 verbose(env, "BPF_STX uses reserved fields\n");
10749 return -EINVAL;
10750 }
10751
17a52670 10752 /* check src1 operand */
dc503a8a 10753 err = check_reg_arg(env, insn->src_reg, SRC_OP);
17a52670
AS
10754 if (err)
10755 return err;
10756 /* check src2 operand */
dc503a8a 10757 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10758 if (err)
10759 return err;
10760
d691f9e8
AS
10761 dst_reg_type = regs[insn->dst_reg].type;
10762
17a52670 10763 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10764 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10765 insn->off, BPF_SIZE(insn->code),
10766 BPF_WRITE, insn->src_reg, false);
17a52670
AS
10767 if (err)
10768 return err;
10769
c08435ec 10770 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
3df126f3
JK
10771
10772 if (*prev_dst_type == NOT_INIT) {
10773 *prev_dst_type = dst_reg_type;
c64b7983 10774 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
61bd5218 10775 verbose(env, "same insn cannot be used with different pointers\n");
d691f9e8
AS
10776 return -EINVAL;
10777 }
10778
17a52670
AS
10779 } else if (class == BPF_ST) {
10780 if (BPF_MODE(insn->code) != BPF_MEM ||
10781 insn->src_reg != BPF_REG_0) {
61bd5218 10782 verbose(env, "BPF_ST uses reserved fields\n");
17a52670
AS
10783 return -EINVAL;
10784 }
10785 /* check src operand */
dc503a8a 10786 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17a52670
AS
10787 if (err)
10788 return err;
10789
f37a8cb8 10790 if (is_ctx_reg(env, insn->dst_reg)) {
9d2be44a 10791 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
2a159c6f
DB
10792 insn->dst_reg,
10793 reg_type_str[reg_state(env, insn->dst_reg)->type]);
f37a8cb8
DB
10794 return -EACCES;
10795 }
10796
17a52670 10797 /* check that memory (dst_reg + off) is writeable */
c08435ec
DB
10798 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10799 insn->off, BPF_SIZE(insn->code),
10800 BPF_WRITE, -1, false);
17a52670
AS
10801 if (err)
10802 return err;
10803
092ed096 10804 } else if (class == BPF_JMP || class == BPF_JMP32) {
17a52670
AS
10805 u8 opcode = BPF_OP(insn->code);
10806
2589726d 10807 env->jmps_processed++;
17a52670
AS
10808 if (opcode == BPF_CALL) {
10809 if (BPF_SRC(insn->code) != BPF_K ||
10810 insn->off != 0 ||
f4d7e40a 10811 (insn->src_reg != BPF_REG_0 &&
e6ac2450
MKL
10812 insn->src_reg != BPF_PSEUDO_CALL &&
10813 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
092ed096
JW
10814 insn->dst_reg != BPF_REG_0 ||
10815 class == BPF_JMP32) {
61bd5218 10816 verbose(env, "BPF_CALL uses reserved fields\n");
17a52670
AS
10817 return -EINVAL;
10818 }
10819
d83525ca
AS
10820 if (env->cur_state->active_spin_lock &&
10821 (insn->src_reg == BPF_PSEUDO_CALL ||
10822 insn->imm != BPF_FUNC_spin_unlock)) {
10823 verbose(env, "function calls are not allowed while holding a lock\n");
10824 return -EINVAL;
10825 }
f4d7e40a 10826 if (insn->src_reg == BPF_PSEUDO_CALL)
c08435ec 10827 err = check_func_call(env, insn, &env->insn_idx);
e6ac2450
MKL
10828 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10829 err = check_kfunc_call(env, insn);
f4d7e40a 10830 else
69c087ba 10831 err = check_helper_call(env, insn, &env->insn_idx);
17a52670
AS
10832 if (err)
10833 return err;
17a52670
AS
10834 } else if (opcode == BPF_JA) {
10835 if (BPF_SRC(insn->code) != BPF_K ||
10836 insn->imm != 0 ||
10837 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10838 insn->dst_reg != BPF_REG_0 ||
10839 class == BPF_JMP32) {
61bd5218 10840 verbose(env, "BPF_JA uses reserved fields\n");
17a52670
AS
10841 return -EINVAL;
10842 }
10843
c08435ec 10844 env->insn_idx += insn->off + 1;
17a52670
AS
10845 continue;
10846
10847 } else if (opcode == BPF_EXIT) {
10848 if (BPF_SRC(insn->code) != BPF_K ||
10849 insn->imm != 0 ||
10850 insn->src_reg != BPF_REG_0 ||
092ed096
JW
10851 insn->dst_reg != BPF_REG_0 ||
10852 class == BPF_JMP32) {
61bd5218 10853 verbose(env, "BPF_EXIT uses reserved fields\n");
17a52670
AS
10854 return -EINVAL;
10855 }
10856
d83525ca
AS
10857 if (env->cur_state->active_spin_lock) {
10858 verbose(env, "bpf_spin_unlock is missing\n");
10859 return -EINVAL;
10860 }
10861
f4d7e40a
AS
10862 if (state->curframe) {
10863 /* exit from nested function */
c08435ec 10864 err = prepare_func_exit(env, &env->insn_idx);
f4d7e40a
AS
10865 if (err)
10866 return err;
10867 do_print_state = true;
10868 continue;
10869 }
10870
fd978bf7
JS
10871 err = check_reference_leak(env);
10872 if (err)
10873 return err;
10874
390ee7e2
AS
10875 err = check_return_code(env);
10876 if (err)
10877 return err;
f1bca824 10878process_bpf_exit:
2589726d 10879 update_branch_counts(env, env->cur_state);
b5dc0163 10880 err = pop_stack(env, &prev_insn_idx,
6f8a57cc 10881 &env->insn_idx, pop_log);
638f5b90
AS
10882 if (err < 0) {
10883 if (err != -ENOENT)
10884 return err;
17a52670
AS
10885 break;
10886 } else {
10887 do_print_state = true;
10888 continue;
10889 }
10890 } else {
c08435ec 10891 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17a52670
AS
10892 if (err)
10893 return err;
10894 }
10895 } else if (class == BPF_LD) {
10896 u8 mode = BPF_MODE(insn->code);
10897
10898 if (mode == BPF_ABS || mode == BPF_IND) {
ddd872bc
AS
10899 err = check_ld_abs(env, insn);
10900 if (err)
10901 return err;
10902
17a52670
AS
10903 } else if (mode == BPF_IMM) {
10904 err = check_ld_imm(env, insn);
10905 if (err)
10906 return err;
10907
c08435ec 10908 env->insn_idx++;
fe9a5ca7 10909 sanitize_mark_insn_seen(env);
17a52670 10910 } else {
61bd5218 10911 verbose(env, "invalid BPF_LD mode\n");
17a52670
AS
10912 return -EINVAL;
10913 }
10914 } else {
61bd5218 10915 verbose(env, "unknown insn class %d\n", class);
17a52670
AS
10916 return -EINVAL;
10917 }
10918
c08435ec 10919 env->insn_idx++;
17a52670
AS
10920 }
10921
10922 return 0;
10923}
10924
541c3bad
AN
10925static int find_btf_percpu_datasec(struct btf *btf)
10926{
10927 const struct btf_type *t;
10928 const char *tname;
10929 int i, n;
10930
10931 /*
10932 * Both vmlinux and module each have their own ".data..percpu"
10933 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10934 * types to look at only module's own BTF types.
10935 */
10936 n = btf_nr_types(btf);
10937 if (btf_is_module(btf))
10938 i = btf_nr_types(btf_vmlinux);
10939 else
10940 i = 1;
10941
10942 for(; i < n; i++) {
10943 t = btf_type_by_id(btf, i);
10944 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10945 continue;
10946
10947 tname = btf_name_by_offset(btf, t->name_off);
10948 if (!strcmp(tname, ".data..percpu"))
10949 return i;
10950 }
10951
10952 return -ENOENT;
10953}
10954
4976b718
HL
10955/* replace pseudo btf_id with kernel symbol address */
10956static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10957 struct bpf_insn *insn,
10958 struct bpf_insn_aux_data *aux)
10959{
eaa6bcb7
HL
10960 const struct btf_var_secinfo *vsi;
10961 const struct btf_type *datasec;
541c3bad 10962 struct btf_mod_pair *btf_mod;
4976b718
HL
10963 const struct btf_type *t;
10964 const char *sym_name;
eaa6bcb7 10965 bool percpu = false;
f16e6313 10966 u32 type, id = insn->imm;
541c3bad 10967 struct btf *btf;
f16e6313 10968 s32 datasec_id;
4976b718 10969 u64 addr;
541c3bad 10970 int i, btf_fd, err;
4976b718 10971
541c3bad
AN
10972 btf_fd = insn[1].imm;
10973 if (btf_fd) {
10974 btf = btf_get_by_fd(btf_fd);
10975 if (IS_ERR(btf)) {
10976 verbose(env, "invalid module BTF object FD specified.\n");
10977 return -EINVAL;
10978 }
10979 } else {
10980 if (!btf_vmlinux) {
10981 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10982 return -EINVAL;
10983 }
10984 btf = btf_vmlinux;
10985 btf_get(btf);
4976b718
HL
10986 }
10987
541c3bad 10988 t = btf_type_by_id(btf, id);
4976b718
HL
10989 if (!t) {
10990 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
541c3bad
AN
10991 err = -ENOENT;
10992 goto err_put;
4976b718
HL
10993 }
10994
10995 if (!btf_type_is_var(t)) {
541c3bad
AN
10996 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10997 err = -EINVAL;
10998 goto err_put;
4976b718
HL
10999 }
11000
541c3bad 11001 sym_name = btf_name_by_offset(btf, t->name_off);
4976b718
HL
11002 addr = kallsyms_lookup_name(sym_name);
11003 if (!addr) {
11004 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11005 sym_name);
541c3bad
AN
11006 err = -ENOENT;
11007 goto err_put;
4976b718
HL
11008 }
11009
541c3bad 11010 datasec_id = find_btf_percpu_datasec(btf);
eaa6bcb7 11011 if (datasec_id > 0) {
541c3bad 11012 datasec = btf_type_by_id(btf, datasec_id);
eaa6bcb7
HL
11013 for_each_vsi(i, datasec, vsi) {
11014 if (vsi->type == id) {
11015 percpu = true;
11016 break;
11017 }
11018 }
11019 }
11020
4976b718
HL
11021 insn[0].imm = (u32)addr;
11022 insn[1].imm = addr >> 32;
11023
11024 type = t->type;
541c3bad 11025 t = btf_type_skip_modifiers(btf, type, NULL);
eaa6bcb7
HL
11026 if (percpu) {
11027 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
541c3bad 11028 aux->btf_var.btf = btf;
eaa6bcb7
HL
11029 aux->btf_var.btf_id = type;
11030 } else if (!btf_type_is_struct(t)) {
4976b718
HL
11031 const struct btf_type *ret;
11032 const char *tname;
11033 u32 tsize;
11034
11035 /* resolve the type size of ksym. */
541c3bad 11036 ret = btf_resolve_size(btf, t, &tsize);
4976b718 11037 if (IS_ERR(ret)) {
541c3bad 11038 tname = btf_name_by_offset(btf, t->name_off);
4976b718
HL
11039 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11040 tname, PTR_ERR(ret));
541c3bad
AN
11041 err = -EINVAL;
11042 goto err_put;
4976b718
HL
11043 }
11044 aux->btf_var.reg_type = PTR_TO_MEM;
11045 aux->btf_var.mem_size = tsize;
11046 } else {
11047 aux->btf_var.reg_type = PTR_TO_BTF_ID;
541c3bad 11048 aux->btf_var.btf = btf;
4976b718
HL
11049 aux->btf_var.btf_id = type;
11050 }
541c3bad
AN
11051
11052 /* check whether we recorded this BTF (and maybe module) already */
11053 for (i = 0; i < env->used_btf_cnt; i++) {
11054 if (env->used_btfs[i].btf == btf) {
11055 btf_put(btf);
11056 return 0;
11057 }
11058 }
11059
11060 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11061 err = -E2BIG;
11062 goto err_put;
11063 }
11064
11065 btf_mod = &env->used_btfs[env->used_btf_cnt];
11066 btf_mod->btf = btf;
11067 btf_mod->module = NULL;
11068
11069 /* if we reference variables from kernel module, bump its refcount */
11070 if (btf_is_module(btf)) {
11071 btf_mod->module = btf_try_get_module(btf);
11072 if (!btf_mod->module) {
11073 err = -ENXIO;
11074 goto err_put;
11075 }
11076 }
11077
11078 env->used_btf_cnt++;
11079
4976b718 11080 return 0;
541c3bad
AN
11081err_put:
11082 btf_put(btf);
11083 return err;
4976b718
HL
11084}
11085
56f668df
MKL
11086static int check_map_prealloc(struct bpf_map *map)
11087{
11088 return (map->map_type != BPF_MAP_TYPE_HASH &&
bcc6b1b7
MKL
11089 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11090 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
56f668df
MKL
11091 !(map->map_flags & BPF_F_NO_PREALLOC);
11092}
11093
d83525ca
AS
11094static bool is_tracing_prog_type(enum bpf_prog_type type)
11095{
11096 switch (type) {
11097 case BPF_PROG_TYPE_KPROBE:
11098 case BPF_PROG_TYPE_TRACEPOINT:
11099 case BPF_PROG_TYPE_PERF_EVENT:
11100 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11101 return true;
11102 default:
11103 return false;
11104 }
11105}
11106
94dacdbd
TG
11107static bool is_preallocated_map(struct bpf_map *map)
11108{
11109 if (!check_map_prealloc(map))
11110 return false;
11111 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11112 return false;
11113 return true;
11114}
11115
61bd5218
JK
11116static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11117 struct bpf_map *map,
fdc15d38
AS
11118 struct bpf_prog *prog)
11119
11120{
7e40781c 11121 enum bpf_prog_type prog_type = resolve_prog_type(prog);
94dacdbd
TG
11122 /*
11123 * Validate that trace type programs use preallocated hash maps.
11124 *
11125 * For programs attached to PERF events this is mandatory as the
11126 * perf NMI can hit any arbitrary code sequence.
11127 *
11128 * All other trace types using preallocated hash maps are unsafe as
11129 * well because tracepoint or kprobes can be inside locked regions
11130 * of the memory allocator or at a place where a recursion into the
11131 * memory allocator would see inconsistent state.
11132 *
2ed905c5
TG
11133 * On RT enabled kernels run-time allocation of all trace type
11134 * programs is strictly prohibited due to lock type constraints. On
11135 * !RT kernels it is allowed for backwards compatibility reasons for
11136 * now, but warnings are emitted so developers are made aware of
11137 * the unsafety and can fix their programs before this is enforced.
56f668df 11138 */
7e40781c
UP
11139 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11140 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
61bd5218 11141 verbose(env, "perf_event programs can only use preallocated hash map\n");
56f668df
MKL
11142 return -EINVAL;
11143 }
2ed905c5
TG
11144 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11145 verbose(env, "trace type programs can only use preallocated hash map\n");
11146 return -EINVAL;
11147 }
94dacdbd
TG
11148 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11149 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
fdc15d38 11150 }
a3884572 11151
9e7a4d98
KS
11152 if (map_value_has_spin_lock(map)) {
11153 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11154 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11155 return -EINVAL;
11156 }
11157
11158 if (is_tracing_prog_type(prog_type)) {
11159 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11160 return -EINVAL;
11161 }
11162
11163 if (prog->aux->sleepable) {
11164 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11165 return -EINVAL;
11166 }
d83525ca
AS
11167 }
11168
a3884572 11169 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
09728266 11170 !bpf_offload_prog_map_match(prog, map)) {
a3884572
JK
11171 verbose(env, "offload device mismatch between prog and map\n");
11172 return -EINVAL;
11173 }
11174
85d33df3
MKL
11175 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11176 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11177 return -EINVAL;
11178 }
11179
1e6c62a8
AS
11180 if (prog->aux->sleepable)
11181 switch (map->map_type) {
11182 case BPF_MAP_TYPE_HASH:
11183 case BPF_MAP_TYPE_LRU_HASH:
11184 case BPF_MAP_TYPE_ARRAY:
638e4b82
AS
11185 case BPF_MAP_TYPE_PERCPU_HASH:
11186 case BPF_MAP_TYPE_PERCPU_ARRAY:
11187 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11188 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11189 case BPF_MAP_TYPE_HASH_OF_MAPS:
1e6c62a8
AS
11190 if (!is_preallocated_map(map)) {
11191 verbose(env,
638e4b82 11192 "Sleepable programs can only use preallocated maps\n");
1e6c62a8
AS
11193 return -EINVAL;
11194 }
11195 break;
ba90c2cc
KS
11196 case BPF_MAP_TYPE_RINGBUF:
11197 break;
1e6c62a8
AS
11198 default:
11199 verbose(env,
ba90c2cc 11200 "Sleepable programs can only use array, hash, and ringbuf maps\n");
1e6c62a8
AS
11201 return -EINVAL;
11202 }
11203
fdc15d38
AS
11204 return 0;
11205}
11206
b741f163
RG
11207static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11208{
11209 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11210 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11211}
11212
4976b718
HL
11213/* find and rewrite pseudo imm in ld_imm64 instructions:
11214 *
11215 * 1. if it accesses map FD, replace it with actual map pointer.
11216 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11217 *
11218 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
0246e64d 11219 */
4976b718 11220static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
0246e64d
AS
11221{
11222 struct bpf_insn *insn = env->prog->insnsi;
11223 int insn_cnt = env->prog->len;
fdc15d38 11224 int i, j, err;
0246e64d 11225
f1f7714e 11226 err = bpf_prog_calc_tag(env->prog);
aafe6ae9
DB
11227 if (err)
11228 return err;
11229
0246e64d 11230 for (i = 0; i < insn_cnt; i++, insn++) {
9bac3d6d 11231 if (BPF_CLASS(insn->code) == BPF_LDX &&
d691f9e8 11232 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
61bd5218 11233 verbose(env, "BPF_LDX uses reserved fields\n");
d691f9e8
AS
11234 return -EINVAL;
11235 }
11236
0246e64d 11237 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
d8eca5bb 11238 struct bpf_insn_aux_data *aux;
0246e64d
AS
11239 struct bpf_map *map;
11240 struct fd f;
d8eca5bb 11241 u64 addr;
387544bf 11242 u32 fd;
0246e64d
AS
11243
11244 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11245 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11246 insn[1].off != 0) {
61bd5218 11247 verbose(env, "invalid bpf_ld_imm64 insn\n");
0246e64d
AS
11248 return -EINVAL;
11249 }
11250
d8eca5bb 11251 if (insn[0].src_reg == 0)
0246e64d
AS
11252 /* valid generic load 64-bit imm */
11253 goto next_insn;
11254
4976b718
HL
11255 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11256 aux = &env->insn_aux_data[i];
11257 err = check_pseudo_btf_id(env, insn, aux);
11258 if (err)
11259 return err;
11260 goto next_insn;
11261 }
11262
69c087ba
YS
11263 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11264 aux = &env->insn_aux_data[i];
11265 aux->ptr_type = PTR_TO_FUNC;
11266 goto next_insn;
11267 }
11268
d8eca5bb
DB
11269 /* In final convert_pseudo_ld_imm64() step, this is
11270 * converted into regular 64-bit imm load insn.
11271 */
387544bf
AS
11272 switch (insn[0].src_reg) {
11273 case BPF_PSEUDO_MAP_VALUE:
11274 case BPF_PSEUDO_MAP_IDX_VALUE:
11275 break;
11276 case BPF_PSEUDO_MAP_FD:
11277 case BPF_PSEUDO_MAP_IDX:
11278 if (insn[1].imm == 0)
11279 break;
11280 fallthrough;
11281 default:
11282 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
0246e64d
AS
11283 return -EINVAL;
11284 }
11285
387544bf
AS
11286 switch (insn[0].src_reg) {
11287 case BPF_PSEUDO_MAP_IDX_VALUE:
11288 case BPF_PSEUDO_MAP_IDX:
11289 if (bpfptr_is_null(env->fd_array)) {
11290 verbose(env, "fd_idx without fd_array is invalid\n");
11291 return -EPROTO;
11292 }
11293 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11294 insn[0].imm * sizeof(fd),
11295 sizeof(fd)))
11296 return -EFAULT;
11297 break;
11298 default:
11299 fd = insn[0].imm;
11300 break;
11301 }
11302
11303 f = fdget(fd);
c2101297 11304 map = __bpf_map_get(f);
0246e64d 11305 if (IS_ERR(map)) {
61bd5218 11306 verbose(env, "fd %d is not pointing to valid bpf_map\n",
20182390 11307 insn[0].imm);
0246e64d
AS
11308 return PTR_ERR(map);
11309 }
11310
61bd5218 11311 err = check_map_prog_compatibility(env, map, env->prog);
fdc15d38
AS
11312 if (err) {
11313 fdput(f);
11314 return err;
11315 }
11316
d8eca5bb 11317 aux = &env->insn_aux_data[i];
387544bf
AS
11318 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11319 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
d8eca5bb
DB
11320 addr = (unsigned long)map;
11321 } else {
11322 u32 off = insn[1].imm;
11323
11324 if (off >= BPF_MAX_VAR_OFF) {
11325 verbose(env, "direct value offset of %u is not allowed\n", off);
11326 fdput(f);
11327 return -EINVAL;
11328 }
11329
11330 if (!map->ops->map_direct_value_addr) {
11331 verbose(env, "no direct value access support for this map type\n");
11332 fdput(f);
11333 return -EINVAL;
11334 }
11335
11336 err = map->ops->map_direct_value_addr(map, &addr, off);
11337 if (err) {
11338 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11339 map->value_size, off);
11340 fdput(f);
11341 return err;
11342 }
11343
11344 aux->map_off = off;
11345 addr += off;
11346 }
11347
11348 insn[0].imm = (u32)addr;
11349 insn[1].imm = addr >> 32;
0246e64d
AS
11350
11351 /* check whether we recorded this map already */
d8eca5bb 11352 for (j = 0; j < env->used_map_cnt; j++) {
0246e64d 11353 if (env->used_maps[j] == map) {
d8eca5bb 11354 aux->map_index = j;
0246e64d
AS
11355 fdput(f);
11356 goto next_insn;
11357 }
d8eca5bb 11358 }
0246e64d
AS
11359
11360 if (env->used_map_cnt >= MAX_USED_MAPS) {
11361 fdput(f);
11362 return -E2BIG;
11363 }
11364
0246e64d
AS
11365 /* hold the map. If the program is rejected by verifier,
11366 * the map will be released by release_maps() or it
11367 * will be used by the valid program until it's unloaded
ab7f5bf0 11368 * and all maps are released in free_used_maps()
0246e64d 11369 */
1e0bd5a0 11370 bpf_map_inc(map);
d8eca5bb
DB
11371
11372 aux->map_index = env->used_map_cnt;
92117d84
AS
11373 env->used_maps[env->used_map_cnt++] = map;
11374
b741f163 11375 if (bpf_map_is_cgroup_storage(map) &&
e4730423 11376 bpf_cgroup_storage_assign(env->prog->aux, map)) {
b741f163 11377 verbose(env, "only one cgroup storage of each type is allowed\n");
de9cbbaa
RG
11378 fdput(f);
11379 return -EBUSY;
11380 }
11381
0246e64d
AS
11382 fdput(f);
11383next_insn:
11384 insn++;
11385 i++;
5e581dad
DB
11386 continue;
11387 }
11388
11389 /* Basic sanity check before we invest more work here. */
11390 if (!bpf_opcode_in_insntable(insn->code)) {
11391 verbose(env, "unknown opcode %02x\n", insn->code);
11392 return -EINVAL;
0246e64d
AS
11393 }
11394 }
11395
11396 /* now all pseudo BPF_LD_IMM64 instructions load valid
11397 * 'struct bpf_map *' into a register instead of user map_fd.
11398 * These pointers will be used later by verifier to validate map access.
11399 */
11400 return 0;
11401}
11402
11403/* drop refcnt of maps used by the rejected program */
58e2af8b 11404static void release_maps(struct bpf_verifier_env *env)
0246e64d 11405{
a2ea0746
DB
11406 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11407 env->used_map_cnt);
0246e64d
AS
11408}
11409
541c3bad
AN
11410/* drop refcnt of maps used by the rejected program */
11411static void release_btfs(struct bpf_verifier_env *env)
11412{
11413 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11414 env->used_btf_cnt);
11415}
11416
0246e64d 11417/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
58e2af8b 11418static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
0246e64d
AS
11419{
11420 struct bpf_insn *insn = env->prog->insnsi;
11421 int insn_cnt = env->prog->len;
11422 int i;
11423
69c087ba
YS
11424 for (i = 0; i < insn_cnt; i++, insn++) {
11425 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11426 continue;
11427 if (insn->src_reg == BPF_PSEUDO_FUNC)
11428 continue;
11429 insn->src_reg = 0;
11430 }
0246e64d
AS
11431}
11432
8041902d
AS
11433/* single env->prog->insni[off] instruction was replaced with the range
11434 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11435 * [0, off) and [off, end) to new locations, so the patched range stays zero
11436 */
b325fbca
JW
11437static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11438 struct bpf_prog *new_prog, u32 off, u32 cnt)
8041902d
AS
11439{
11440 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
b325fbca 11441 struct bpf_insn *insn = new_prog->insnsi;
d203b0fd 11442 u32 old_seen = old_data[off].seen;
b325fbca 11443 u32 prog_len;
c131187d 11444 int i;
8041902d 11445
b325fbca
JW
11446 /* aux info at OFF always needs adjustment, no matter fast path
11447 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11448 * original insn at old prog.
11449 */
11450 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11451
8041902d
AS
11452 if (cnt == 1)
11453 return 0;
b325fbca 11454 prog_len = new_prog->len;
fad953ce
KC
11455 new_data = vzalloc(array_size(prog_len,
11456 sizeof(struct bpf_insn_aux_data)));
8041902d
AS
11457 if (!new_data)
11458 return -ENOMEM;
11459 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11460 memcpy(new_data + off + cnt - 1, old_data + off,
11461 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
b325fbca 11462 for (i = off; i < off + cnt - 1; i++) {
d203b0fd
DB
11463 /* Expand insni[off]'s seen count to the patched range. */
11464 new_data[i].seen = old_seen;
b325fbca
JW
11465 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11466 }
8041902d
AS
11467 env->insn_aux_data = new_data;
11468 vfree(old_data);
11469 return 0;
11470}
11471
cc8b0b92
AS
11472static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11473{
11474 int i;
11475
11476 if (len == 1)
11477 return;
4cb3d99c
JW
11478 /* NOTE: fake 'exit' subprog should be updated as well. */
11479 for (i = 0; i <= env->subprog_cnt; i++) {
afd59424 11480 if (env->subprog_info[i].start <= off)
cc8b0b92 11481 continue;
9c8105bd 11482 env->subprog_info[i].start += len - 1;
cc8b0b92
AS
11483 }
11484}
11485
7506d211 11486static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
a748c697
MF
11487{
11488 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11489 int i, sz = prog->aux->size_poke_tab;
11490 struct bpf_jit_poke_descriptor *desc;
11491
11492 for (i = 0; i < sz; i++) {
11493 desc = &tab[i];
7506d211
JF
11494 if (desc->insn_idx <= off)
11495 continue;
a748c697
MF
11496 desc->insn_idx += len - 1;
11497 }
11498}
11499
8041902d
AS
11500static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11501 const struct bpf_insn *patch, u32 len)
11502{
11503 struct bpf_prog *new_prog;
11504
11505 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
4f73379e
AS
11506 if (IS_ERR(new_prog)) {
11507 if (PTR_ERR(new_prog) == -ERANGE)
11508 verbose(env,
11509 "insn %d cannot be patched due to 16-bit range\n",
11510 env->insn_aux_data[off].orig_idx);
8041902d 11511 return NULL;
4f73379e 11512 }
b325fbca 11513 if (adjust_insn_aux_data(env, new_prog, off, len))
8041902d 11514 return NULL;
cc8b0b92 11515 adjust_subprog_starts(env, off, len);
7506d211 11516 adjust_poke_descs(new_prog, off, len);
8041902d
AS
11517 return new_prog;
11518}
11519
52875a04
JK
11520static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11521 u32 off, u32 cnt)
11522{
11523 int i, j;
11524
11525 /* find first prog starting at or after off (first to remove) */
11526 for (i = 0; i < env->subprog_cnt; i++)
11527 if (env->subprog_info[i].start >= off)
11528 break;
11529 /* find first prog starting at or after off + cnt (first to stay) */
11530 for (j = i; j < env->subprog_cnt; j++)
11531 if (env->subprog_info[j].start >= off + cnt)
11532 break;
11533 /* if j doesn't start exactly at off + cnt, we are just removing
11534 * the front of previous prog
11535 */
11536 if (env->subprog_info[j].start != off + cnt)
11537 j--;
11538
11539 if (j > i) {
11540 struct bpf_prog_aux *aux = env->prog->aux;
11541 int move;
11542
11543 /* move fake 'exit' subprog as well */
11544 move = env->subprog_cnt + 1 - j;
11545
11546 memmove(env->subprog_info + i,
11547 env->subprog_info + j,
11548 sizeof(*env->subprog_info) * move);
11549 env->subprog_cnt -= j - i;
11550
11551 /* remove func_info */
11552 if (aux->func_info) {
11553 move = aux->func_info_cnt - j;
11554
11555 memmove(aux->func_info + i,
11556 aux->func_info + j,
11557 sizeof(*aux->func_info) * move);
11558 aux->func_info_cnt -= j - i;
11559 /* func_info->insn_off is set after all code rewrites,
11560 * in adjust_btf_func() - no need to adjust
11561 */
11562 }
11563 } else {
11564 /* convert i from "first prog to remove" to "first to adjust" */
11565 if (env->subprog_info[i].start == off)
11566 i++;
11567 }
11568
11569 /* update fake 'exit' subprog as well */
11570 for (; i <= env->subprog_cnt; i++)
11571 env->subprog_info[i].start -= cnt;
11572
11573 return 0;
11574}
11575
11576static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11577 u32 cnt)
11578{
11579 struct bpf_prog *prog = env->prog;
11580 u32 i, l_off, l_cnt, nr_linfo;
11581 struct bpf_line_info *linfo;
11582
11583 nr_linfo = prog->aux->nr_linfo;
11584 if (!nr_linfo)
11585 return 0;
11586
11587 linfo = prog->aux->linfo;
11588
11589 /* find first line info to remove, count lines to be removed */
11590 for (i = 0; i < nr_linfo; i++)
11591 if (linfo[i].insn_off >= off)
11592 break;
11593
11594 l_off = i;
11595 l_cnt = 0;
11596 for (; i < nr_linfo; i++)
11597 if (linfo[i].insn_off < off + cnt)
11598 l_cnt++;
11599 else
11600 break;
11601
11602 /* First live insn doesn't match first live linfo, it needs to "inherit"
11603 * last removed linfo. prog is already modified, so prog->len == off
11604 * means no live instructions after (tail of the program was removed).
11605 */
11606 if (prog->len != off && l_cnt &&
11607 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11608 l_cnt--;
11609 linfo[--i].insn_off = off + cnt;
11610 }
11611
11612 /* remove the line info which refer to the removed instructions */
11613 if (l_cnt) {
11614 memmove(linfo + l_off, linfo + i,
11615 sizeof(*linfo) * (nr_linfo - i));
11616
11617 prog->aux->nr_linfo -= l_cnt;
11618 nr_linfo = prog->aux->nr_linfo;
11619 }
11620
11621 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11622 for (i = l_off; i < nr_linfo; i++)
11623 linfo[i].insn_off -= cnt;
11624
11625 /* fix up all subprogs (incl. 'exit') which start >= off */
11626 for (i = 0; i <= env->subprog_cnt; i++)
11627 if (env->subprog_info[i].linfo_idx > l_off) {
11628 /* program may have started in the removed region but
11629 * may not be fully removed
11630 */
11631 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11632 env->subprog_info[i].linfo_idx -= l_cnt;
11633 else
11634 env->subprog_info[i].linfo_idx = l_off;
11635 }
11636
11637 return 0;
11638}
11639
11640static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11641{
11642 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11643 unsigned int orig_prog_len = env->prog->len;
11644 int err;
11645
08ca90af
JK
11646 if (bpf_prog_is_dev_bound(env->prog->aux))
11647 bpf_prog_offload_remove_insns(env, off, cnt);
11648
52875a04
JK
11649 err = bpf_remove_insns(env->prog, off, cnt);
11650 if (err)
11651 return err;
11652
11653 err = adjust_subprog_starts_after_remove(env, off, cnt);
11654 if (err)
11655 return err;
11656
11657 err = bpf_adj_linfo_after_remove(env, off, cnt);
11658 if (err)
11659 return err;
11660
11661 memmove(aux_data + off, aux_data + off + cnt,
11662 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11663
11664 return 0;
11665}
11666
2a5418a1
DB
11667/* The verifier does more data flow analysis than llvm and will not
11668 * explore branches that are dead at run time. Malicious programs can
11669 * have dead code too. Therefore replace all dead at-run-time code
11670 * with 'ja -1'.
11671 *
11672 * Just nops are not optimal, e.g. if they would sit at the end of the
11673 * program and through another bug we would manage to jump there, then
11674 * we'd execute beyond program memory otherwise. Returning exception
11675 * code also wouldn't work since we can have subprogs where the dead
11676 * code could be located.
c131187d
AS
11677 */
11678static void sanitize_dead_code(struct bpf_verifier_env *env)
11679{
11680 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
2a5418a1 11681 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
c131187d
AS
11682 struct bpf_insn *insn = env->prog->insnsi;
11683 const int insn_cnt = env->prog->len;
11684 int i;
11685
11686 for (i = 0; i < insn_cnt; i++) {
11687 if (aux_data[i].seen)
11688 continue;
2a5418a1 11689 memcpy(insn + i, &trap, sizeof(trap));
c131187d
AS
11690 }
11691}
11692
e2ae4ca2
JK
11693static bool insn_is_cond_jump(u8 code)
11694{
11695 u8 op;
11696
092ed096
JW
11697 if (BPF_CLASS(code) == BPF_JMP32)
11698 return true;
11699
e2ae4ca2
JK
11700 if (BPF_CLASS(code) != BPF_JMP)
11701 return false;
11702
11703 op = BPF_OP(code);
11704 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11705}
11706
11707static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11708{
11709 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11710 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11711 struct bpf_insn *insn = env->prog->insnsi;
11712 const int insn_cnt = env->prog->len;
11713 int i;
11714
11715 for (i = 0; i < insn_cnt; i++, insn++) {
11716 if (!insn_is_cond_jump(insn->code))
11717 continue;
11718
11719 if (!aux_data[i + 1].seen)
11720 ja.off = insn->off;
11721 else if (!aux_data[i + 1 + insn->off].seen)
11722 ja.off = 0;
11723 else
11724 continue;
11725
08ca90af
JK
11726 if (bpf_prog_is_dev_bound(env->prog->aux))
11727 bpf_prog_offload_replace_insn(env, i, &ja);
11728
e2ae4ca2
JK
11729 memcpy(insn, &ja, sizeof(ja));
11730 }
11731}
11732
52875a04
JK
11733static int opt_remove_dead_code(struct bpf_verifier_env *env)
11734{
11735 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11736 int insn_cnt = env->prog->len;
11737 int i, err;
11738
11739 for (i = 0; i < insn_cnt; i++) {
11740 int j;
11741
11742 j = 0;
11743 while (i + j < insn_cnt && !aux_data[i + j].seen)
11744 j++;
11745 if (!j)
11746 continue;
11747
11748 err = verifier_remove_insns(env, i, j);
11749 if (err)
11750 return err;
11751 insn_cnt = env->prog->len;
11752 }
11753
11754 return 0;
11755}
11756
a1b14abc
JK
11757static int opt_remove_nops(struct bpf_verifier_env *env)
11758{
11759 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11760 struct bpf_insn *insn = env->prog->insnsi;
11761 int insn_cnt = env->prog->len;
11762 int i, err;
11763
11764 for (i = 0; i < insn_cnt; i++) {
11765 if (memcmp(&insn[i], &ja, sizeof(ja)))
11766 continue;
11767
11768 err = verifier_remove_insns(env, i, 1);
11769 if (err)
11770 return err;
11771 insn_cnt--;
11772 i--;
11773 }
11774
11775 return 0;
11776}
11777
d6c2308c
JW
11778static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11779 const union bpf_attr *attr)
a4b1d3c1 11780{
d6c2308c 11781 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
a4b1d3c1 11782 struct bpf_insn_aux_data *aux = env->insn_aux_data;
d6c2308c 11783 int i, patch_len, delta = 0, len = env->prog->len;
a4b1d3c1 11784 struct bpf_insn *insns = env->prog->insnsi;
a4b1d3c1 11785 struct bpf_prog *new_prog;
d6c2308c 11786 bool rnd_hi32;
a4b1d3c1 11787
d6c2308c 11788 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
a4b1d3c1 11789 zext_patch[1] = BPF_ZEXT_REG(0);
d6c2308c
JW
11790 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11791 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11792 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
a4b1d3c1
JW
11793 for (i = 0; i < len; i++) {
11794 int adj_idx = i + delta;
11795 struct bpf_insn insn;
83a28819 11796 int load_reg;
a4b1d3c1 11797
d6c2308c 11798 insn = insns[adj_idx];
83a28819 11799 load_reg = insn_def_regno(&insn);
d6c2308c
JW
11800 if (!aux[adj_idx].zext_dst) {
11801 u8 code, class;
11802 u32 imm_rnd;
11803
11804 if (!rnd_hi32)
11805 continue;
11806
11807 code = insn.code;
11808 class = BPF_CLASS(code);
83a28819 11809 if (load_reg == -1)
d6c2308c
JW
11810 continue;
11811
11812 /* NOTE: arg "reg" (the fourth one) is only used for
83a28819
IL
11813 * BPF_STX + SRC_OP, so it is safe to pass NULL
11814 * here.
d6c2308c 11815 */
83a28819 11816 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
d6c2308c
JW
11817 if (class == BPF_LD &&
11818 BPF_MODE(code) == BPF_IMM)
11819 i++;
11820 continue;
11821 }
11822
11823 /* ctx load could be transformed into wider load. */
11824 if (class == BPF_LDX &&
11825 aux[adj_idx].ptr_type == PTR_TO_CTX)
11826 continue;
11827
11828 imm_rnd = get_random_int();
11829 rnd_hi32_patch[0] = insn;
11830 rnd_hi32_patch[1].imm = imm_rnd;
83a28819 11831 rnd_hi32_patch[3].dst_reg = load_reg;
d6c2308c
JW
11832 patch = rnd_hi32_patch;
11833 patch_len = 4;
11834 goto apply_patch_buffer;
11835 }
11836
39491867
BJ
11837 /* Add in an zero-extend instruction if a) the JIT has requested
11838 * it or b) it's a CMPXCHG.
11839 *
11840 * The latter is because: BPF_CMPXCHG always loads a value into
11841 * R0, therefore always zero-extends. However some archs'
11842 * equivalent instruction only does this load when the
11843 * comparison is successful. This detail of CMPXCHG is
11844 * orthogonal to the general zero-extension behaviour of the
11845 * CPU, so it's treated independently of bpf_jit_needs_zext.
11846 */
11847 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
a4b1d3c1
JW
11848 continue;
11849
83a28819
IL
11850 if (WARN_ON(load_reg == -1)) {
11851 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11852 return -EFAULT;
b2e37a71
IL
11853 }
11854
a4b1d3c1 11855 zext_patch[0] = insn;
b2e37a71
IL
11856 zext_patch[1].dst_reg = load_reg;
11857 zext_patch[1].src_reg = load_reg;
d6c2308c
JW
11858 patch = zext_patch;
11859 patch_len = 2;
11860apply_patch_buffer:
11861 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
a4b1d3c1
JW
11862 if (!new_prog)
11863 return -ENOMEM;
11864 env->prog = new_prog;
11865 insns = new_prog->insnsi;
11866 aux = env->insn_aux_data;
d6c2308c 11867 delta += patch_len - 1;
a4b1d3c1
JW
11868 }
11869
11870 return 0;
11871}
11872
c64b7983
JS
11873/* convert load instructions that access fields of a context type into a
11874 * sequence of instructions that access fields of the underlying structure:
11875 * struct __sk_buff -> struct sk_buff
11876 * struct bpf_sock_ops -> struct sock
9bac3d6d 11877 */
58e2af8b 11878static int convert_ctx_accesses(struct bpf_verifier_env *env)
9bac3d6d 11879{
00176a34 11880 const struct bpf_verifier_ops *ops = env->ops;
f96da094 11881 int i, cnt, size, ctx_field_size, delta = 0;
3df126f3 11882 const int insn_cnt = env->prog->len;
36bbef52 11883 struct bpf_insn insn_buf[16], *insn;
46f53a65 11884 u32 target_size, size_default, off;
9bac3d6d 11885 struct bpf_prog *new_prog;
d691f9e8 11886 enum bpf_access_type type;
f96da094 11887 bool is_narrower_load;
9bac3d6d 11888
b09928b9
DB
11889 if (ops->gen_prologue || env->seen_direct_write) {
11890 if (!ops->gen_prologue) {
11891 verbose(env, "bpf verifier is misconfigured\n");
11892 return -EINVAL;
11893 }
36bbef52
DB
11894 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11895 env->prog);
11896 if (cnt >= ARRAY_SIZE(insn_buf)) {
61bd5218 11897 verbose(env, "bpf verifier is misconfigured\n");
36bbef52
DB
11898 return -EINVAL;
11899 } else if (cnt) {
8041902d 11900 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
36bbef52
DB
11901 if (!new_prog)
11902 return -ENOMEM;
8041902d 11903
36bbef52 11904 env->prog = new_prog;
3df126f3 11905 delta += cnt - 1;
36bbef52
DB
11906 }
11907 }
11908
c64b7983 11909 if (bpf_prog_is_dev_bound(env->prog->aux))
9bac3d6d
AS
11910 return 0;
11911
3df126f3 11912 insn = env->prog->insnsi + delta;
36bbef52 11913
9bac3d6d 11914 for (i = 0; i < insn_cnt; i++, insn++) {
c64b7983
JS
11915 bpf_convert_ctx_access_t convert_ctx_access;
11916
62c7989b
DB
11917 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11918 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11919 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
ea2e7ce5 11920 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
d691f9e8 11921 type = BPF_READ;
62c7989b
DB
11922 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11923 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11924 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
ea2e7ce5 11925 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
d691f9e8
AS
11926 type = BPF_WRITE;
11927 else
9bac3d6d
AS
11928 continue;
11929
af86ca4e
AS
11930 if (type == BPF_WRITE &&
11931 env->insn_aux_data[i + delta].sanitize_stack_off) {
11932 struct bpf_insn patch[] = {
11933 /* Sanitize suspicious stack slot with zero.
11934 * There are no memory dependencies for this store,
11935 * since it's only using frame pointer and immediate
11936 * constant of zero
11937 */
11938 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11939 env->insn_aux_data[i + delta].sanitize_stack_off,
11940 0),
11941 /* the original STX instruction will immediately
11942 * overwrite the same stack slot with appropriate value
11943 */
11944 *insn,
11945 };
11946
11947 cnt = ARRAY_SIZE(patch);
11948 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11949 if (!new_prog)
11950 return -ENOMEM;
11951
11952 delta += cnt - 1;
11953 env->prog = new_prog;
11954 insn = new_prog->insnsi + i + delta;
11955 continue;
11956 }
11957
c64b7983
JS
11958 switch (env->insn_aux_data[i + delta].ptr_type) {
11959 case PTR_TO_CTX:
11960 if (!ops->convert_ctx_access)
11961 continue;
11962 convert_ctx_access = ops->convert_ctx_access;
11963 break;
11964 case PTR_TO_SOCKET:
46f8bc92 11965 case PTR_TO_SOCK_COMMON:
c64b7983
JS
11966 convert_ctx_access = bpf_sock_convert_ctx_access;
11967 break;
655a51e5
MKL
11968 case PTR_TO_TCP_SOCK:
11969 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11970 break;
fada7fdc
JL
11971 case PTR_TO_XDP_SOCK:
11972 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11973 break;
2a02759e 11974 case PTR_TO_BTF_ID:
27ae7997
MKL
11975 if (type == BPF_READ) {
11976 insn->code = BPF_LDX | BPF_PROBE_MEM |
11977 BPF_SIZE((insn)->code);
11978 env->prog->aux->num_exentries++;
7e40781c 11979 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
2a02759e
AS
11980 verbose(env, "Writes through BTF pointers are not allowed\n");
11981 return -EINVAL;
11982 }
2a02759e 11983 continue;
c64b7983 11984 default:
9bac3d6d 11985 continue;
c64b7983 11986 }
9bac3d6d 11987
31fd8581 11988 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
f96da094 11989 size = BPF_LDST_BYTES(insn);
31fd8581
YS
11990
11991 /* If the read access is a narrower load of the field,
11992 * convert to a 4/8-byte load, to minimum program type specific
11993 * convert_ctx_access changes. If conversion is successful,
11994 * we will apply proper mask to the result.
11995 */
f96da094 11996 is_narrower_load = size < ctx_field_size;
46f53a65
AI
11997 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11998 off = insn->off;
31fd8581 11999 if (is_narrower_load) {
f96da094
DB
12000 u8 size_code;
12001
12002 if (type == BPF_WRITE) {
61bd5218 12003 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
f96da094
DB
12004 return -EINVAL;
12005 }
31fd8581 12006
f96da094 12007 size_code = BPF_H;
31fd8581
YS
12008 if (ctx_field_size == 4)
12009 size_code = BPF_W;
12010 else if (ctx_field_size == 8)
12011 size_code = BPF_DW;
f96da094 12012
bc23105c 12013 insn->off = off & ~(size_default - 1);
31fd8581
YS
12014 insn->code = BPF_LDX | BPF_MEM | size_code;
12015 }
f96da094
DB
12016
12017 target_size = 0;
c64b7983
JS
12018 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12019 &target_size);
f96da094
DB
12020 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12021 (ctx_field_size && !target_size)) {
61bd5218 12022 verbose(env, "bpf verifier is misconfigured\n");
9bac3d6d
AS
12023 return -EINVAL;
12024 }
f96da094
DB
12025
12026 if (is_narrower_load && size < target_size) {
d895a0f1
IL
12027 u8 shift = bpf_ctx_narrow_access_offset(
12028 off, size, size_default) * 8;
46f53a65
AI
12029 if (ctx_field_size <= 4) {
12030 if (shift)
12031 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12032 insn->dst_reg,
12033 shift);
31fd8581 12034 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
f96da094 12035 (1 << size * 8) - 1);
46f53a65
AI
12036 } else {
12037 if (shift)
12038 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12039 insn->dst_reg,
12040 shift);
31fd8581 12041 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
e2f7fc0a 12042 (1ULL << size * 8) - 1);
46f53a65 12043 }
31fd8581 12044 }
9bac3d6d 12045
8041902d 12046 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
9bac3d6d
AS
12047 if (!new_prog)
12048 return -ENOMEM;
12049
3df126f3 12050 delta += cnt - 1;
9bac3d6d
AS
12051
12052 /* keep walking new program and skip insns we just inserted */
12053 env->prog = new_prog;
3df126f3 12054 insn = new_prog->insnsi + i + delta;
9bac3d6d
AS
12055 }
12056
12057 return 0;
12058}
12059
1c2a088a
AS
12060static int jit_subprogs(struct bpf_verifier_env *env)
12061{
12062 struct bpf_prog *prog = env->prog, **func, *tmp;
12063 int i, j, subprog_start, subprog_end = 0, len, subprog;
a748c697 12064 struct bpf_map *map_ptr;
7105e828 12065 struct bpf_insn *insn;
1c2a088a 12066 void *old_bpf_func;
c4c0bdc0 12067 int err, num_exentries;
1c2a088a 12068
f910cefa 12069 if (env->subprog_cnt <= 1)
1c2a088a
AS
12070 return 0;
12071
7105e828 12072 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
12073 if (bpf_pseudo_func(insn)) {
12074 env->insn_aux_data[i].call_imm = insn->imm;
12075 /* subprog is encoded in insn[1].imm */
12076 continue;
12077 }
12078
23a2d70c 12079 if (!bpf_pseudo_call(insn))
1c2a088a 12080 continue;
c7a89784
DB
12081 /* Upon error here we cannot fall back to interpreter but
12082 * need a hard reject of the program. Thus -EFAULT is
12083 * propagated in any case.
12084 */
1c2a088a
AS
12085 subprog = find_subprog(env, i + insn->imm + 1);
12086 if (subprog < 0) {
12087 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12088 i + insn->imm + 1);
12089 return -EFAULT;
12090 }
12091 /* temporarily remember subprog id inside insn instead of
12092 * aux_data, since next loop will split up all insns into funcs
12093 */
f910cefa 12094 insn->off = subprog;
1c2a088a
AS
12095 /* remember original imm in case JIT fails and fallback
12096 * to interpreter will be needed
12097 */
12098 env->insn_aux_data[i].call_imm = insn->imm;
12099 /* point imm to __bpf_call_base+1 from JITs point of view */
12100 insn->imm = 1;
12101 }
12102
c454a46b
MKL
12103 err = bpf_prog_alloc_jited_linfo(prog);
12104 if (err)
12105 goto out_undo_insn;
12106
12107 err = -ENOMEM;
6396bb22 12108 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
1c2a088a 12109 if (!func)
c7a89784 12110 goto out_undo_insn;
1c2a088a 12111
f910cefa 12112 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a 12113 subprog_start = subprog_end;
4cb3d99c 12114 subprog_end = env->subprog_info[i + 1].start;
1c2a088a
AS
12115
12116 len = subprog_end - subprog_start;
492ecee8
AS
12117 /* BPF_PROG_RUN doesn't call subprogs directly,
12118 * hence main prog stats include the runtime of subprogs.
12119 * subprogs don't have IDs and not reachable via prog_get_next_id
700d4796 12120 * func[i]->stats will never be accessed and stays NULL
492ecee8
AS
12121 */
12122 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1c2a088a
AS
12123 if (!func[i])
12124 goto out_free;
12125 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12126 len * sizeof(struct bpf_insn));
4f74d809 12127 func[i]->type = prog->type;
1c2a088a 12128 func[i]->len = len;
4f74d809
DB
12129 if (bpf_prog_calc_tag(func[i]))
12130 goto out_free;
1c2a088a 12131 func[i]->is_func = 1;
ba64e7d8 12132 func[i]->aux->func_idx = i;
f263a814 12133 /* Below members will be freed only at prog->aux */
ba64e7d8
YS
12134 func[i]->aux->btf = prog->aux->btf;
12135 func[i]->aux->func_info = prog->aux->func_info;
f263a814
JF
12136 func[i]->aux->poke_tab = prog->aux->poke_tab;
12137 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
ba64e7d8 12138
a748c697 12139 for (j = 0; j < prog->aux->size_poke_tab; j++) {
f263a814 12140 struct bpf_jit_poke_descriptor *poke;
a748c697 12141
f263a814
JF
12142 poke = &prog->aux->poke_tab[j];
12143 if (poke->insn_idx < subprog_end &&
12144 poke->insn_idx >= subprog_start)
12145 poke->aux = func[i]->aux;
a748c697
MF
12146 }
12147
1c2a088a
AS
12148 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12149 * Long term would need debug info to populate names
12150 */
12151 func[i]->aux->name[0] = 'F';
9c8105bd 12152 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1c2a088a 12153 func[i]->jit_requested = 1;
e6ac2450 12154 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
c454a46b
MKL
12155 func[i]->aux->linfo = prog->aux->linfo;
12156 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12157 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12158 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
c4c0bdc0
YS
12159 num_exentries = 0;
12160 insn = func[i]->insnsi;
12161 for (j = 0; j < func[i]->len; j++, insn++) {
12162 if (BPF_CLASS(insn->code) == BPF_LDX &&
12163 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12164 num_exentries++;
12165 }
12166 func[i]->aux->num_exentries = num_exentries;
ebf7d1f5 12167 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1c2a088a
AS
12168 func[i] = bpf_int_jit_compile(func[i]);
12169 if (!func[i]->jited) {
12170 err = -ENOTSUPP;
12171 goto out_free;
12172 }
12173 cond_resched();
12174 }
a748c697 12175
1c2a088a
AS
12176 /* at this point all bpf functions were successfully JITed
12177 * now populate all bpf_calls with correct addresses and
12178 * run last pass of JIT
12179 */
f910cefa 12180 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12181 insn = func[i]->insnsi;
12182 for (j = 0; j < func[i]->len; j++, insn++) {
69c087ba
YS
12183 if (bpf_pseudo_func(insn)) {
12184 subprog = insn[1].imm;
12185 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12186 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12187 continue;
12188 }
23a2d70c 12189 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12190 continue;
12191 subprog = insn->off;
0d306c31
PB
12192 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12193 __bpf_call_base;
1c2a088a 12194 }
2162fed4
SD
12195
12196 /* we use the aux data to keep a list of the start addresses
12197 * of the JITed images for each function in the program
12198 *
12199 * for some architectures, such as powerpc64, the imm field
12200 * might not be large enough to hold the offset of the start
12201 * address of the callee's JITed image from __bpf_call_base
12202 *
12203 * in such cases, we can lookup the start address of a callee
12204 * by using its subprog id, available from the off field of
12205 * the call instruction, as an index for this list
12206 */
12207 func[i]->aux->func = func;
12208 func[i]->aux->func_cnt = env->subprog_cnt;
1c2a088a 12209 }
f910cefa 12210 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12211 old_bpf_func = func[i]->bpf_func;
12212 tmp = bpf_int_jit_compile(func[i]);
12213 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12214 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
c7a89784 12215 err = -ENOTSUPP;
1c2a088a
AS
12216 goto out_free;
12217 }
12218 cond_resched();
12219 }
12220
12221 /* finally lock prog and jit images for all functions and
12222 * populate kallsysm
12223 */
f910cefa 12224 for (i = 0; i < env->subprog_cnt; i++) {
1c2a088a
AS
12225 bpf_prog_lock_ro(func[i]);
12226 bpf_prog_kallsyms_add(func[i]);
12227 }
7105e828
DB
12228
12229 /* Last step: make now unused interpreter insns from main
12230 * prog consistent for later dump requests, so they can
12231 * later look the same as if they were interpreted only.
12232 */
12233 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
69c087ba
YS
12234 if (bpf_pseudo_func(insn)) {
12235 insn[0].imm = env->insn_aux_data[i].call_imm;
12236 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12237 continue;
12238 }
23a2d70c 12239 if (!bpf_pseudo_call(insn))
7105e828
DB
12240 continue;
12241 insn->off = env->insn_aux_data[i].call_imm;
12242 subprog = find_subprog(env, i + insn->off + 1);
dbecd738 12243 insn->imm = subprog;
7105e828
DB
12244 }
12245
1c2a088a
AS
12246 prog->jited = 1;
12247 prog->bpf_func = func[0]->bpf_func;
12248 prog->aux->func = func;
f910cefa 12249 prog->aux->func_cnt = env->subprog_cnt;
e16301fb 12250 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12251 return 0;
12252out_free:
f263a814
JF
12253 /* We failed JIT'ing, so at this point we need to unregister poke
12254 * descriptors from subprogs, so that kernel is not attempting to
12255 * patch it anymore as we're freeing the subprog JIT memory.
12256 */
12257 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12258 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12259 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12260 }
12261 /* At this point we're guaranteed that poke descriptors are not
12262 * live anymore. We can just unlink its descriptor table as it's
12263 * released with the main prog.
12264 */
a748c697
MF
12265 for (i = 0; i < env->subprog_cnt; i++) {
12266 if (!func[i])
12267 continue;
f263a814 12268 func[i]->aux->poke_tab = NULL;
a748c697
MF
12269 bpf_jit_free(func[i]);
12270 }
1c2a088a 12271 kfree(func);
c7a89784 12272out_undo_insn:
1c2a088a
AS
12273 /* cleanup main prog to be interpreted */
12274 prog->jit_requested = 0;
12275 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
23a2d70c 12276 if (!bpf_pseudo_call(insn))
1c2a088a
AS
12277 continue;
12278 insn->off = 0;
12279 insn->imm = env->insn_aux_data[i].call_imm;
12280 }
e16301fb 12281 bpf_prog_jit_attempt_done(prog);
1c2a088a
AS
12282 return err;
12283}
12284
1ea47e01
AS
12285static int fixup_call_args(struct bpf_verifier_env *env)
12286{
19d28fbd 12287#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1ea47e01
AS
12288 struct bpf_prog *prog = env->prog;
12289 struct bpf_insn *insn = prog->insnsi;
e6ac2450 12290 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
1ea47e01 12291 int i, depth;
19d28fbd 12292#endif
e4052d06 12293 int err = 0;
1ea47e01 12294
e4052d06
QM
12295 if (env->prog->jit_requested &&
12296 !bpf_prog_is_dev_bound(env->prog->aux)) {
19d28fbd
DM
12297 err = jit_subprogs(env);
12298 if (err == 0)
1c2a088a 12299 return 0;
c7a89784
DB
12300 if (err == -EFAULT)
12301 return err;
19d28fbd
DM
12302 }
12303#ifndef CONFIG_BPF_JIT_ALWAYS_ON
e6ac2450
MKL
12304 if (has_kfunc_call) {
12305 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12306 return -EINVAL;
12307 }
e411901c
MF
12308 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12309 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12310 * have to be rejected, since interpreter doesn't support them yet.
12311 */
12312 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12313 return -EINVAL;
12314 }
1ea47e01 12315 for (i = 0; i < prog->len; i++, insn++) {
69c087ba
YS
12316 if (bpf_pseudo_func(insn)) {
12317 /* When JIT fails the progs with callback calls
12318 * have to be rejected, since interpreter doesn't support them yet.
12319 */
12320 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12321 return -EINVAL;
12322 }
12323
23a2d70c 12324 if (!bpf_pseudo_call(insn))
1ea47e01
AS
12325 continue;
12326 depth = get_callee_stack_depth(env, insn, i);
12327 if (depth < 0)
12328 return depth;
12329 bpf_patch_call_args(insn, depth);
12330 }
19d28fbd
DM
12331 err = 0;
12332#endif
12333 return err;
1ea47e01
AS
12334}
12335
e6ac2450
MKL
12336static int fixup_kfunc_call(struct bpf_verifier_env *env,
12337 struct bpf_insn *insn)
12338{
12339 const struct bpf_kfunc_desc *desc;
12340
12341 /* insn->imm has the btf func_id. Replace it with
12342 * an address (relative to __bpf_base_call).
12343 */
12344 desc = find_kfunc_desc(env->prog, insn->imm);
12345 if (!desc) {
12346 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12347 insn->imm);
12348 return -EFAULT;
12349 }
12350
12351 insn->imm = desc->imm;
12352
12353 return 0;
12354}
12355
e6ac5933
BJ
12356/* Do various post-verification rewrites in a single program pass.
12357 * These rewrites simplify JIT and interpreter implementations.
e245c5c6 12358 */
e6ac5933 12359static int do_misc_fixups(struct bpf_verifier_env *env)
e245c5c6 12360{
79741b3b 12361 struct bpf_prog *prog = env->prog;
d2e4c1e6 12362 bool expect_blinding = bpf_jit_blinding_enabled(prog);
79741b3b 12363 struct bpf_insn *insn = prog->insnsi;
e245c5c6 12364 const struct bpf_func_proto *fn;
79741b3b 12365 const int insn_cnt = prog->len;
09772d92 12366 const struct bpf_map_ops *ops;
c93552c4 12367 struct bpf_insn_aux_data *aux;
81ed18ab
AS
12368 struct bpf_insn insn_buf[16];
12369 struct bpf_prog *new_prog;
12370 struct bpf_map *map_ptr;
d2e4c1e6 12371 int i, ret, cnt, delta = 0;
e245c5c6 12372
79741b3b 12373 for (i = 0; i < insn_cnt; i++, insn++) {
e6ac5933 12374 /* Make divide-by-zero exceptions impossible. */
f6b1b3bf
DB
12375 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12376 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12377 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
68fda450 12378 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
f6b1b3bf 12379 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
e88b2c6e
DB
12380 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12381 struct bpf_insn *patchlet;
12382 struct bpf_insn chk_and_div[] = {
9b00f1b7 12383 /* [R,W]x div 0 -> 0 */
e88b2c6e
DB
12384 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12385 BPF_JNE | BPF_K, insn->src_reg,
12386 0, 2, 0),
f6b1b3bf
DB
12387 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12388 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12389 *insn,
12390 };
e88b2c6e 12391 struct bpf_insn chk_and_mod[] = {
9b00f1b7 12392 /* [R,W]x mod 0 -> [R,W]x */
e88b2c6e
DB
12393 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12394 BPF_JEQ | BPF_K, insn->src_reg,
9b00f1b7 12395 0, 1 + (is64 ? 0 : 1), 0),
f6b1b3bf 12396 *insn,
9b00f1b7
DB
12397 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12398 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
f6b1b3bf 12399 };
f6b1b3bf 12400
e88b2c6e
DB
12401 patchlet = isdiv ? chk_and_div : chk_and_mod;
12402 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
9b00f1b7 12403 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
f6b1b3bf
DB
12404
12405 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
68fda450
AS
12406 if (!new_prog)
12407 return -ENOMEM;
12408
12409 delta += cnt - 1;
12410 env->prog = prog = new_prog;
12411 insn = new_prog->insnsi + i + delta;
12412 continue;
12413 }
12414
e6ac5933 12415 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
e0cea7ce
DB
12416 if (BPF_CLASS(insn->code) == BPF_LD &&
12417 (BPF_MODE(insn->code) == BPF_ABS ||
12418 BPF_MODE(insn->code) == BPF_IND)) {
12419 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12420 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12421 verbose(env, "bpf verifier is misconfigured\n");
12422 return -EINVAL;
12423 }
12424
12425 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12426 if (!new_prog)
12427 return -ENOMEM;
12428
12429 delta += cnt - 1;
12430 env->prog = prog = new_prog;
12431 insn = new_prog->insnsi + i + delta;
12432 continue;
12433 }
12434
e6ac5933 12435 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
979d63d5
DB
12436 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12437 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12438 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12439 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
979d63d5 12440 struct bpf_insn *patch = &insn_buf[0];
801c6058 12441 bool issrc, isneg, isimm;
979d63d5
DB
12442 u32 off_reg;
12443
12444 aux = &env->insn_aux_data[i + delta];
3612af78
DB
12445 if (!aux->alu_state ||
12446 aux->alu_state == BPF_ALU_NON_POINTER)
979d63d5
DB
12447 continue;
12448
12449 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12450 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12451 BPF_ALU_SANITIZE_SRC;
801c6058 12452 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
979d63d5
DB
12453
12454 off_reg = issrc ? insn->src_reg : insn->dst_reg;
801c6058
DB
12455 if (isimm) {
12456 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12457 } else {
12458 if (isneg)
12459 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12460 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12461 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12462 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12463 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12464 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12465 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12466 }
b9b34ddb
DB
12467 if (!issrc)
12468 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12469 insn->src_reg = BPF_REG_AX;
979d63d5
DB
12470 if (isneg)
12471 insn->code = insn->code == code_add ?
12472 code_sub : code_add;
12473 *patch++ = *insn;
801c6058 12474 if (issrc && isneg && !isimm)
979d63d5
DB
12475 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12476 cnt = patch - insn_buf;
12477
12478 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12479 if (!new_prog)
12480 return -ENOMEM;
12481
12482 delta += cnt - 1;
12483 env->prog = prog = new_prog;
12484 insn = new_prog->insnsi + i + delta;
12485 continue;
12486 }
12487
79741b3b
AS
12488 if (insn->code != (BPF_JMP | BPF_CALL))
12489 continue;
cc8b0b92
AS
12490 if (insn->src_reg == BPF_PSEUDO_CALL)
12491 continue;
e6ac2450
MKL
12492 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12493 ret = fixup_kfunc_call(env, insn);
12494 if (ret)
12495 return ret;
12496 continue;
12497 }
e245c5c6 12498
79741b3b
AS
12499 if (insn->imm == BPF_FUNC_get_route_realm)
12500 prog->dst_needed = 1;
12501 if (insn->imm == BPF_FUNC_get_prandom_u32)
12502 bpf_user_rnd_init_once();
9802d865
JB
12503 if (insn->imm == BPF_FUNC_override_return)
12504 prog->kprobe_override = 1;
79741b3b 12505 if (insn->imm == BPF_FUNC_tail_call) {
7b9f6da1
DM
12506 /* If we tail call into other programs, we
12507 * cannot make any assumptions since they can
12508 * be replaced dynamically during runtime in
12509 * the program array.
12510 */
12511 prog->cb_access = 1;
e411901c
MF
12512 if (!allow_tail_call_in_subprogs(env))
12513 prog->aux->stack_depth = MAX_BPF_STACK;
12514 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
7b9f6da1 12515
79741b3b 12516 /* mark bpf_tail_call as different opcode to avoid
8fb33b60 12517 * conditional branch in the interpreter for every normal
79741b3b
AS
12518 * call and to prevent accidental JITing by JIT compiler
12519 * that doesn't support bpf_tail_call yet
e245c5c6 12520 */
79741b3b 12521 insn->imm = 0;
71189fa9 12522 insn->code = BPF_JMP | BPF_TAIL_CALL;
b2157399 12523
c93552c4 12524 aux = &env->insn_aux_data[i + delta];
2c78ee89 12525 if (env->bpf_capable && !expect_blinding &&
cc52d914 12526 prog->jit_requested &&
d2e4c1e6
DB
12527 !bpf_map_key_poisoned(aux) &&
12528 !bpf_map_ptr_poisoned(aux) &&
12529 !bpf_map_ptr_unpriv(aux)) {
12530 struct bpf_jit_poke_descriptor desc = {
12531 .reason = BPF_POKE_REASON_TAIL_CALL,
12532 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12533 .tail_call.key = bpf_map_key_immediate(aux),
a748c697 12534 .insn_idx = i + delta,
d2e4c1e6
DB
12535 };
12536
12537 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12538 if (ret < 0) {
12539 verbose(env, "adding tail call poke descriptor failed\n");
12540 return ret;
12541 }
12542
12543 insn->imm = ret + 1;
12544 continue;
12545 }
12546
c93552c4
DB
12547 if (!bpf_map_ptr_unpriv(aux))
12548 continue;
12549
b2157399
AS
12550 /* instead of changing every JIT dealing with tail_call
12551 * emit two extra insns:
12552 * if (index >= max_entries) goto out;
12553 * index &= array->index_mask;
12554 * to avoid out-of-bounds cpu speculation
12555 */
c93552c4 12556 if (bpf_map_ptr_poisoned(aux)) {
40950343 12557 verbose(env, "tail_call abusing map_ptr\n");
b2157399
AS
12558 return -EINVAL;
12559 }
c93552c4 12560
d2e4c1e6 12561 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
b2157399
AS
12562 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12563 map_ptr->max_entries, 2);
12564 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12565 container_of(map_ptr,
12566 struct bpf_array,
12567 map)->index_mask);
12568 insn_buf[2] = *insn;
12569 cnt = 3;
12570 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12571 if (!new_prog)
12572 return -ENOMEM;
12573
12574 delta += cnt - 1;
12575 env->prog = prog = new_prog;
12576 insn = new_prog->insnsi + i + delta;
79741b3b
AS
12577 continue;
12578 }
e245c5c6 12579
89c63074 12580 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
09772d92
DB
12581 * and other inlining handlers are currently limited to 64 bit
12582 * only.
89c63074 12583 */
60b58afc 12584 if (prog->jit_requested && BITS_PER_LONG == 64 &&
09772d92
DB
12585 (insn->imm == BPF_FUNC_map_lookup_elem ||
12586 insn->imm == BPF_FUNC_map_update_elem ||
84430d42
DB
12587 insn->imm == BPF_FUNC_map_delete_elem ||
12588 insn->imm == BPF_FUNC_map_push_elem ||
12589 insn->imm == BPF_FUNC_map_pop_elem ||
e6a4750f
BT
12590 insn->imm == BPF_FUNC_map_peek_elem ||
12591 insn->imm == BPF_FUNC_redirect_map)) {
c93552c4
DB
12592 aux = &env->insn_aux_data[i + delta];
12593 if (bpf_map_ptr_poisoned(aux))
12594 goto patch_call_imm;
12595
d2e4c1e6 12596 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
09772d92
DB
12597 ops = map_ptr->ops;
12598 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12599 ops->map_gen_lookup) {
12600 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
4a8f87e6
DB
12601 if (cnt == -EOPNOTSUPP)
12602 goto patch_map_ops_generic;
12603 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
09772d92
DB
12604 verbose(env, "bpf verifier is misconfigured\n");
12605 return -EINVAL;
12606 }
81ed18ab 12607
09772d92
DB
12608 new_prog = bpf_patch_insn_data(env, i + delta,
12609 insn_buf, cnt);
12610 if (!new_prog)
12611 return -ENOMEM;
81ed18ab 12612
09772d92
DB
12613 delta += cnt - 1;
12614 env->prog = prog = new_prog;
12615 insn = new_prog->insnsi + i + delta;
12616 continue;
12617 }
81ed18ab 12618
09772d92
DB
12619 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12620 (void *(*)(struct bpf_map *map, void *key))NULL));
12621 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12622 (int (*)(struct bpf_map *map, void *key))NULL));
12623 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12624 (int (*)(struct bpf_map *map, void *key, void *value,
12625 u64 flags))NULL));
84430d42
DB
12626 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12627 (int (*)(struct bpf_map *map, void *value,
12628 u64 flags))NULL));
12629 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12630 (int (*)(struct bpf_map *map, void *value))NULL));
12631 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12632 (int (*)(struct bpf_map *map, void *value))NULL));
e6a4750f
BT
12633 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12634 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12635
4a8f87e6 12636patch_map_ops_generic:
09772d92
DB
12637 switch (insn->imm) {
12638 case BPF_FUNC_map_lookup_elem:
12639 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12640 __bpf_call_base;
12641 continue;
12642 case BPF_FUNC_map_update_elem:
12643 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12644 __bpf_call_base;
12645 continue;
12646 case BPF_FUNC_map_delete_elem:
12647 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12648 __bpf_call_base;
12649 continue;
84430d42
DB
12650 case BPF_FUNC_map_push_elem:
12651 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12652 __bpf_call_base;
12653 continue;
12654 case BPF_FUNC_map_pop_elem:
12655 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12656 __bpf_call_base;
12657 continue;
12658 case BPF_FUNC_map_peek_elem:
12659 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12660 __bpf_call_base;
12661 continue;
e6a4750f
BT
12662 case BPF_FUNC_redirect_map:
12663 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12664 __bpf_call_base;
12665 continue;
09772d92 12666 }
81ed18ab 12667
09772d92 12668 goto patch_call_imm;
81ed18ab
AS
12669 }
12670
e6ac5933 12671 /* Implement bpf_jiffies64 inline. */
5576b991
MKL
12672 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12673 insn->imm == BPF_FUNC_jiffies64) {
12674 struct bpf_insn ld_jiffies_addr[2] = {
12675 BPF_LD_IMM64(BPF_REG_0,
12676 (unsigned long)&jiffies),
12677 };
12678
12679 insn_buf[0] = ld_jiffies_addr[0];
12680 insn_buf[1] = ld_jiffies_addr[1];
12681 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12682 BPF_REG_0, 0);
12683 cnt = 3;
12684
12685 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12686 cnt);
12687 if (!new_prog)
12688 return -ENOMEM;
12689
12690 delta += cnt - 1;
12691 env->prog = prog = new_prog;
12692 insn = new_prog->insnsi + i + delta;
12693 continue;
12694 }
12695
81ed18ab 12696patch_call_imm:
5e43f899 12697 fn = env->ops->get_func_proto(insn->imm, env->prog);
79741b3b
AS
12698 /* all functions that have prototype and verifier allowed
12699 * programs to call them, must be real in-kernel functions
12700 */
12701 if (!fn->func) {
61bd5218
JK
12702 verbose(env,
12703 "kernel subsystem misconfigured func %s#%d\n",
79741b3b
AS
12704 func_id_name(insn->imm), insn->imm);
12705 return -EFAULT;
e245c5c6 12706 }
79741b3b 12707 insn->imm = fn->func - __bpf_call_base;
e245c5c6 12708 }
e245c5c6 12709
d2e4c1e6
DB
12710 /* Since poke tab is now finalized, publish aux to tracker. */
12711 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12712 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12713 if (!map_ptr->ops->map_poke_track ||
12714 !map_ptr->ops->map_poke_untrack ||
12715 !map_ptr->ops->map_poke_run) {
12716 verbose(env, "bpf verifier is misconfigured\n");
12717 return -EINVAL;
12718 }
12719
12720 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12721 if (ret < 0) {
12722 verbose(env, "tracking tail call prog failed\n");
12723 return ret;
12724 }
12725 }
12726
e6ac2450
MKL
12727 sort_kfunc_descs_by_imm(env->prog);
12728
79741b3b
AS
12729 return 0;
12730}
e245c5c6 12731
58e2af8b 12732static void free_states(struct bpf_verifier_env *env)
f1bca824 12733{
58e2af8b 12734 struct bpf_verifier_state_list *sl, *sln;
f1bca824
AS
12735 int i;
12736
9f4686c4
AS
12737 sl = env->free_list;
12738 while (sl) {
12739 sln = sl->next;
12740 free_verifier_state(&sl->state, false);
12741 kfree(sl);
12742 sl = sln;
12743 }
51c39bb1 12744 env->free_list = NULL;
9f4686c4 12745
f1bca824
AS
12746 if (!env->explored_states)
12747 return;
12748
dc2a4ebc 12749 for (i = 0; i < state_htab_size(env); i++) {
f1bca824
AS
12750 sl = env->explored_states[i];
12751
a8f500af
AS
12752 while (sl) {
12753 sln = sl->next;
12754 free_verifier_state(&sl->state, false);
12755 kfree(sl);
12756 sl = sln;
12757 }
51c39bb1 12758 env->explored_states[i] = NULL;
f1bca824 12759 }
51c39bb1 12760}
f1bca824 12761
51c39bb1
AS
12762static int do_check_common(struct bpf_verifier_env *env, int subprog)
12763{
6f8a57cc 12764 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
51c39bb1
AS
12765 struct bpf_verifier_state *state;
12766 struct bpf_reg_state *regs;
12767 int ret, i;
12768
12769 env->prev_linfo = NULL;
12770 env->pass_cnt++;
12771
12772 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12773 if (!state)
12774 return -ENOMEM;
12775 state->curframe = 0;
12776 state->speculative = false;
12777 state->branches = 1;
12778 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12779 if (!state->frame[0]) {
12780 kfree(state);
12781 return -ENOMEM;
12782 }
12783 env->cur_state = state;
12784 init_func_state(env, state->frame[0],
12785 BPF_MAIN_FUNC /* callsite */,
12786 0 /* frameno */,
12787 subprog);
12788
12789 regs = state->frame[state->curframe]->regs;
be8704ff 12790 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
51c39bb1
AS
12791 ret = btf_prepare_func_args(env, subprog, regs);
12792 if (ret)
12793 goto out;
12794 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12795 if (regs[i].type == PTR_TO_CTX)
12796 mark_reg_known_zero(env, regs, i);
12797 else if (regs[i].type == SCALAR_VALUE)
12798 mark_reg_unknown(env, regs, i);
e5069b9c
DB
12799 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12800 const u32 mem_size = regs[i].mem_size;
12801
12802 mark_reg_known_zero(env, regs, i);
12803 regs[i].mem_size = mem_size;
12804 regs[i].id = ++env->id_gen;
12805 }
51c39bb1
AS
12806 }
12807 } else {
12808 /* 1st arg to a function */
12809 regs[BPF_REG_1].type = PTR_TO_CTX;
12810 mark_reg_known_zero(env, regs, BPF_REG_1);
34747c41 12811 ret = btf_check_subprog_arg_match(env, subprog, regs);
51c39bb1
AS
12812 if (ret == -EFAULT)
12813 /* unlikely verifier bug. abort.
12814 * ret == 0 and ret < 0 are sadly acceptable for
12815 * main() function due to backward compatibility.
12816 * Like socket filter program may be written as:
12817 * int bpf_prog(struct pt_regs *ctx)
12818 * and never dereference that ctx in the program.
12819 * 'struct pt_regs' is a type mismatch for socket
12820 * filter that should be using 'struct __sk_buff'.
12821 */
12822 goto out;
12823 }
12824
12825 ret = do_check(env);
12826out:
f59bbfc2
AS
12827 /* check for NULL is necessary, since cur_state can be freed inside
12828 * do_check() under memory pressure.
12829 */
12830 if (env->cur_state) {
12831 free_verifier_state(env->cur_state, true);
12832 env->cur_state = NULL;
12833 }
6f8a57cc
AN
12834 while (!pop_stack(env, NULL, NULL, false));
12835 if (!ret && pop_log)
12836 bpf_vlog_reset(&env->log, 0);
51c39bb1 12837 free_states(env);
51c39bb1
AS
12838 return ret;
12839}
12840
12841/* Verify all global functions in a BPF program one by one based on their BTF.
12842 * All global functions must pass verification. Otherwise the whole program is rejected.
12843 * Consider:
12844 * int bar(int);
12845 * int foo(int f)
12846 * {
12847 * return bar(f);
12848 * }
12849 * int bar(int b)
12850 * {
12851 * ...
12852 * }
12853 * foo() will be verified first for R1=any_scalar_value. During verification it
12854 * will be assumed that bar() already verified successfully and call to bar()
12855 * from foo() will be checked for type match only. Later bar() will be verified
12856 * independently to check that it's safe for R1=any_scalar_value.
12857 */
12858static int do_check_subprogs(struct bpf_verifier_env *env)
12859{
12860 struct bpf_prog_aux *aux = env->prog->aux;
12861 int i, ret;
12862
12863 if (!aux->func_info)
12864 return 0;
12865
12866 for (i = 1; i < env->subprog_cnt; i++) {
12867 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12868 continue;
12869 env->insn_idx = env->subprog_info[i].start;
12870 WARN_ON_ONCE(env->insn_idx == 0);
12871 ret = do_check_common(env, i);
12872 if (ret) {
12873 return ret;
12874 } else if (env->log.level & BPF_LOG_LEVEL) {
12875 verbose(env,
12876 "Func#%d is safe for any args that match its prototype\n",
12877 i);
12878 }
12879 }
12880 return 0;
12881}
12882
12883static int do_check_main(struct bpf_verifier_env *env)
12884{
12885 int ret;
12886
12887 env->insn_idx = 0;
12888 ret = do_check_common(env, 0);
12889 if (!ret)
12890 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12891 return ret;
12892}
12893
12894
06ee7115
AS
12895static void print_verification_stats(struct bpf_verifier_env *env)
12896{
12897 int i;
12898
12899 if (env->log.level & BPF_LOG_STATS) {
12900 verbose(env, "verification time %lld usec\n",
12901 div_u64(env->verification_time, 1000));
12902 verbose(env, "stack depth ");
12903 for (i = 0; i < env->subprog_cnt; i++) {
12904 u32 depth = env->subprog_info[i].stack_depth;
12905
12906 verbose(env, "%d", depth);
12907 if (i + 1 < env->subprog_cnt)
12908 verbose(env, "+");
12909 }
12910 verbose(env, "\n");
12911 }
12912 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12913 "total_states %d peak_states %d mark_read %d\n",
12914 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12915 env->max_states_per_insn, env->total_states,
12916 env->peak_states, env->longest_mark_read_walk);
f1bca824
AS
12917}
12918
27ae7997
MKL
12919static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12920{
12921 const struct btf_type *t, *func_proto;
12922 const struct bpf_struct_ops *st_ops;
12923 const struct btf_member *member;
12924 struct bpf_prog *prog = env->prog;
12925 u32 btf_id, member_idx;
12926 const char *mname;
12927
12aa8a94
THJ
12928 if (!prog->gpl_compatible) {
12929 verbose(env, "struct ops programs must have a GPL compatible license\n");
12930 return -EINVAL;
12931 }
12932
27ae7997
MKL
12933 btf_id = prog->aux->attach_btf_id;
12934 st_ops = bpf_struct_ops_find(btf_id);
12935 if (!st_ops) {
12936 verbose(env, "attach_btf_id %u is not a supported struct\n",
12937 btf_id);
12938 return -ENOTSUPP;
12939 }
12940
12941 t = st_ops->type;
12942 member_idx = prog->expected_attach_type;
12943 if (member_idx >= btf_type_vlen(t)) {
12944 verbose(env, "attach to invalid member idx %u of struct %s\n",
12945 member_idx, st_ops->name);
12946 return -EINVAL;
12947 }
12948
12949 member = &btf_type_member(t)[member_idx];
12950 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12951 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12952 NULL);
12953 if (!func_proto) {
12954 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12955 mname, member_idx, st_ops->name);
12956 return -EINVAL;
12957 }
12958
12959 if (st_ops->check_member) {
12960 int err = st_ops->check_member(t, member);
12961
12962 if (err) {
12963 verbose(env, "attach to unsupported member %s of struct %s\n",
12964 mname, st_ops->name);
12965 return err;
12966 }
12967 }
12968
12969 prog->aux->attach_func_proto = func_proto;
12970 prog->aux->attach_func_name = mname;
12971 env->ops = st_ops->verifier_ops;
12972
12973 return 0;
12974}
6ba43b76
KS
12975#define SECURITY_PREFIX "security_"
12976
f7b12b6f 12977static int check_attach_modify_return(unsigned long addr, const char *func_name)
6ba43b76 12978{
69191754 12979 if (within_error_injection_list(addr) ||
f7b12b6f 12980 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
6ba43b76 12981 return 0;
6ba43b76 12982
6ba43b76
KS
12983 return -EINVAL;
12984}
27ae7997 12985
1e6c62a8
AS
12986/* list of non-sleepable functions that are otherwise on
12987 * ALLOW_ERROR_INJECTION list
12988 */
12989BTF_SET_START(btf_non_sleepable_error_inject)
12990/* Three functions below can be called from sleepable and non-sleepable context.
12991 * Assume non-sleepable from bpf safety point of view.
12992 */
12993BTF_ID(func, __add_to_page_cache_locked)
12994BTF_ID(func, should_fail_alloc_page)
12995BTF_ID(func, should_failslab)
12996BTF_SET_END(btf_non_sleepable_error_inject)
12997
12998static int check_non_sleepable_error_inject(u32 btf_id)
12999{
13000 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13001}
13002
f7b12b6f
THJ
13003int bpf_check_attach_target(struct bpf_verifier_log *log,
13004 const struct bpf_prog *prog,
13005 const struct bpf_prog *tgt_prog,
13006 u32 btf_id,
13007 struct bpf_attach_target_info *tgt_info)
38207291 13008{
be8704ff 13009 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
f1b9509c 13010 const char prefix[] = "btf_trace_";
5b92a28a 13011 int ret = 0, subprog = -1, i;
38207291 13012 const struct btf_type *t;
5b92a28a 13013 bool conservative = true;
38207291 13014 const char *tname;
5b92a28a 13015 struct btf *btf;
f7b12b6f 13016 long addr = 0;
38207291 13017
f1b9509c 13018 if (!btf_id) {
efc68158 13019 bpf_log(log, "Tracing programs must provide btf_id\n");
f1b9509c
AS
13020 return -EINVAL;
13021 }
22dc4a0f 13022 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
5b92a28a 13023 if (!btf) {
efc68158 13024 bpf_log(log,
5b92a28a
AS
13025 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13026 return -EINVAL;
13027 }
13028 t = btf_type_by_id(btf, btf_id);
f1b9509c 13029 if (!t) {
efc68158 13030 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
f1b9509c
AS
13031 return -EINVAL;
13032 }
5b92a28a 13033 tname = btf_name_by_offset(btf, t->name_off);
f1b9509c 13034 if (!tname) {
efc68158 13035 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
f1b9509c
AS
13036 return -EINVAL;
13037 }
5b92a28a
AS
13038 if (tgt_prog) {
13039 struct bpf_prog_aux *aux = tgt_prog->aux;
13040
13041 for (i = 0; i < aux->func_info_cnt; i++)
13042 if (aux->func_info[i].type_id == btf_id) {
13043 subprog = i;
13044 break;
13045 }
13046 if (subprog == -1) {
efc68158 13047 bpf_log(log, "Subprog %s doesn't exist\n", tname);
5b92a28a
AS
13048 return -EINVAL;
13049 }
13050 conservative = aux->func_info_aux[subprog].unreliable;
be8704ff
AS
13051 if (prog_extension) {
13052 if (conservative) {
efc68158 13053 bpf_log(log,
be8704ff
AS
13054 "Cannot replace static functions\n");
13055 return -EINVAL;
13056 }
13057 if (!prog->jit_requested) {
efc68158 13058 bpf_log(log,
be8704ff
AS
13059 "Extension programs should be JITed\n");
13060 return -EINVAL;
13061 }
be8704ff
AS
13062 }
13063 if (!tgt_prog->jited) {
efc68158 13064 bpf_log(log, "Can attach to only JITed progs\n");
be8704ff
AS
13065 return -EINVAL;
13066 }
13067 if (tgt_prog->type == prog->type) {
13068 /* Cannot fentry/fexit another fentry/fexit program.
13069 * Cannot attach program extension to another extension.
13070 * It's ok to attach fentry/fexit to extension program.
13071 */
efc68158 13072 bpf_log(log, "Cannot recursively attach\n");
be8704ff
AS
13073 return -EINVAL;
13074 }
13075 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13076 prog_extension &&
13077 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13078 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13079 /* Program extensions can extend all program types
13080 * except fentry/fexit. The reason is the following.
13081 * The fentry/fexit programs are used for performance
13082 * analysis, stats and can be attached to any program
13083 * type except themselves. When extension program is
13084 * replacing XDP function it is necessary to allow
13085 * performance analysis of all functions. Both original
13086 * XDP program and its program extension. Hence
13087 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13088 * allowed. If extending of fentry/fexit was allowed it
13089 * would be possible to create long call chain
13090 * fentry->extension->fentry->extension beyond
13091 * reasonable stack size. Hence extending fentry is not
13092 * allowed.
13093 */
efc68158 13094 bpf_log(log, "Cannot extend fentry/fexit\n");
be8704ff
AS
13095 return -EINVAL;
13096 }
5b92a28a 13097 } else {
be8704ff 13098 if (prog_extension) {
efc68158 13099 bpf_log(log, "Cannot replace kernel functions\n");
be8704ff
AS
13100 return -EINVAL;
13101 }
5b92a28a 13102 }
f1b9509c
AS
13103
13104 switch (prog->expected_attach_type) {
13105 case BPF_TRACE_RAW_TP:
5b92a28a 13106 if (tgt_prog) {
efc68158 13107 bpf_log(log,
5b92a28a
AS
13108 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13109 return -EINVAL;
13110 }
38207291 13111 if (!btf_type_is_typedef(t)) {
efc68158 13112 bpf_log(log, "attach_btf_id %u is not a typedef\n",
38207291
MKL
13113 btf_id);
13114 return -EINVAL;
13115 }
f1b9509c 13116 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
efc68158 13117 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
38207291
MKL
13118 btf_id, tname);
13119 return -EINVAL;
13120 }
13121 tname += sizeof(prefix) - 1;
5b92a28a 13122 t = btf_type_by_id(btf, t->type);
38207291
MKL
13123 if (!btf_type_is_ptr(t))
13124 /* should never happen in valid vmlinux build */
13125 return -EINVAL;
5b92a28a 13126 t = btf_type_by_id(btf, t->type);
38207291
MKL
13127 if (!btf_type_is_func_proto(t))
13128 /* should never happen in valid vmlinux build */
13129 return -EINVAL;
13130
f7b12b6f 13131 break;
15d83c4d
YS
13132 case BPF_TRACE_ITER:
13133 if (!btf_type_is_func(t)) {
efc68158 13134 bpf_log(log, "attach_btf_id %u is not a function\n",
15d83c4d
YS
13135 btf_id);
13136 return -EINVAL;
13137 }
13138 t = btf_type_by_id(btf, t->type);
13139 if (!btf_type_is_func_proto(t))
13140 return -EINVAL;
f7b12b6f
THJ
13141 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13142 if (ret)
13143 return ret;
13144 break;
be8704ff
AS
13145 default:
13146 if (!prog_extension)
13147 return -EINVAL;
df561f66 13148 fallthrough;
ae240823 13149 case BPF_MODIFY_RETURN:
9e4e01df 13150 case BPF_LSM_MAC:
fec56f58
AS
13151 case BPF_TRACE_FENTRY:
13152 case BPF_TRACE_FEXIT:
13153 if (!btf_type_is_func(t)) {
efc68158 13154 bpf_log(log, "attach_btf_id %u is not a function\n",
fec56f58
AS
13155 btf_id);
13156 return -EINVAL;
13157 }
be8704ff 13158 if (prog_extension &&
efc68158 13159 btf_check_type_match(log, prog, btf, t))
be8704ff 13160 return -EINVAL;
5b92a28a 13161 t = btf_type_by_id(btf, t->type);
fec56f58
AS
13162 if (!btf_type_is_func_proto(t))
13163 return -EINVAL;
f7b12b6f 13164
4a1e7c0c
THJ
13165 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13166 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13167 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13168 return -EINVAL;
13169
f7b12b6f 13170 if (tgt_prog && conservative)
5b92a28a 13171 t = NULL;
f7b12b6f
THJ
13172
13173 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
fec56f58 13174 if (ret < 0)
f7b12b6f
THJ
13175 return ret;
13176
5b92a28a 13177 if (tgt_prog) {
e9eeec58
YS
13178 if (subprog == 0)
13179 addr = (long) tgt_prog->bpf_func;
13180 else
13181 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
5b92a28a
AS
13182 } else {
13183 addr = kallsyms_lookup_name(tname);
13184 if (!addr) {
efc68158 13185 bpf_log(log,
5b92a28a
AS
13186 "The address of function %s cannot be found\n",
13187 tname);
f7b12b6f 13188 return -ENOENT;
5b92a28a 13189 }
fec56f58 13190 }
18644cec 13191
1e6c62a8
AS
13192 if (prog->aux->sleepable) {
13193 ret = -EINVAL;
13194 switch (prog->type) {
13195 case BPF_PROG_TYPE_TRACING:
13196 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13197 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13198 */
13199 if (!check_non_sleepable_error_inject(btf_id) &&
13200 within_error_injection_list(addr))
13201 ret = 0;
13202 break;
13203 case BPF_PROG_TYPE_LSM:
13204 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13205 * Only some of them are sleepable.
13206 */
423f1610 13207 if (bpf_lsm_is_sleepable_hook(btf_id))
1e6c62a8
AS
13208 ret = 0;
13209 break;
13210 default:
13211 break;
13212 }
f7b12b6f
THJ
13213 if (ret) {
13214 bpf_log(log, "%s is not sleepable\n", tname);
13215 return ret;
13216 }
1e6c62a8 13217 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
1af9270e 13218 if (tgt_prog) {
efc68158 13219 bpf_log(log, "can't modify return codes of BPF programs\n");
f7b12b6f
THJ
13220 return -EINVAL;
13221 }
13222 ret = check_attach_modify_return(addr, tname);
13223 if (ret) {
13224 bpf_log(log, "%s() is not modifiable\n", tname);
13225 return ret;
1af9270e 13226 }
18644cec 13227 }
f7b12b6f
THJ
13228
13229 break;
13230 }
13231 tgt_info->tgt_addr = addr;
13232 tgt_info->tgt_name = tname;
13233 tgt_info->tgt_type = t;
13234 return 0;
13235}
13236
35e3815f
JO
13237BTF_SET_START(btf_id_deny)
13238BTF_ID_UNUSED
13239#ifdef CONFIG_SMP
13240BTF_ID(func, migrate_disable)
13241BTF_ID(func, migrate_enable)
13242#endif
13243#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13244BTF_ID(func, rcu_read_unlock_strict)
13245#endif
13246BTF_SET_END(btf_id_deny)
13247
f7b12b6f
THJ
13248static int check_attach_btf_id(struct bpf_verifier_env *env)
13249{
13250 struct bpf_prog *prog = env->prog;
3aac1ead 13251 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
f7b12b6f
THJ
13252 struct bpf_attach_target_info tgt_info = {};
13253 u32 btf_id = prog->aux->attach_btf_id;
13254 struct bpf_trampoline *tr;
13255 int ret;
13256 u64 key;
13257
79a7f8bd
AS
13258 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13259 if (prog->aux->sleepable)
13260 /* attach_btf_id checked to be zero already */
13261 return 0;
13262 verbose(env, "Syscall programs can only be sleepable\n");
13263 return -EINVAL;
13264 }
13265
f7b12b6f
THJ
13266 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13267 prog->type != BPF_PROG_TYPE_LSM) {
13268 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13269 return -EINVAL;
13270 }
13271
13272 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13273 return check_struct_ops_btf_id(env);
13274
13275 if (prog->type != BPF_PROG_TYPE_TRACING &&
13276 prog->type != BPF_PROG_TYPE_LSM &&
13277 prog->type != BPF_PROG_TYPE_EXT)
13278 return 0;
13279
13280 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13281 if (ret)
fec56f58 13282 return ret;
f7b12b6f
THJ
13283
13284 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
3aac1ead
THJ
13285 /* to make freplace equivalent to their targets, they need to
13286 * inherit env->ops and expected_attach_type for the rest of the
13287 * verification
13288 */
f7b12b6f
THJ
13289 env->ops = bpf_verifier_ops[tgt_prog->type];
13290 prog->expected_attach_type = tgt_prog->expected_attach_type;
13291 }
13292
13293 /* store info about the attachment target that will be used later */
13294 prog->aux->attach_func_proto = tgt_info.tgt_type;
13295 prog->aux->attach_func_name = tgt_info.tgt_name;
13296
4a1e7c0c
THJ
13297 if (tgt_prog) {
13298 prog->aux->saved_dst_prog_type = tgt_prog->type;
13299 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13300 }
13301
f7b12b6f
THJ
13302 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13303 prog->aux->attach_btf_trace = true;
13304 return 0;
13305 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13306 if (!bpf_iter_prog_supported(prog))
13307 return -EINVAL;
13308 return 0;
13309 }
13310
13311 if (prog->type == BPF_PROG_TYPE_LSM) {
13312 ret = bpf_lsm_verify_prog(&env->log, prog);
13313 if (ret < 0)
13314 return ret;
35e3815f
JO
13315 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13316 btf_id_set_contains(&btf_id_deny, btf_id)) {
13317 return -EINVAL;
38207291 13318 }
f7b12b6f 13319
22dc4a0f 13320 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
f7b12b6f
THJ
13321 tr = bpf_trampoline_get(key, &tgt_info);
13322 if (!tr)
13323 return -ENOMEM;
13324
3aac1ead 13325 prog->aux->dst_trampoline = tr;
f7b12b6f 13326 return 0;
38207291
MKL
13327}
13328
76654e67
AM
13329struct btf *bpf_get_btf_vmlinux(void)
13330{
13331 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13332 mutex_lock(&bpf_verifier_lock);
13333 if (!btf_vmlinux)
13334 btf_vmlinux = btf_parse_vmlinux();
13335 mutex_unlock(&bpf_verifier_lock);
13336 }
13337 return btf_vmlinux;
13338}
13339
af2ac3e1 13340int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
51580e79 13341{
06ee7115 13342 u64 start_time = ktime_get_ns();
58e2af8b 13343 struct bpf_verifier_env *env;
b9193c1b 13344 struct bpf_verifier_log *log;
9e4c24e7 13345 int i, len, ret = -EINVAL;
e2ae4ca2 13346 bool is_priv;
51580e79 13347
eba0c929
AB
13348 /* no program is valid */
13349 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13350 return -EINVAL;
13351
58e2af8b 13352 /* 'struct bpf_verifier_env' can be global, but since it's not small,
cbd35700
AS
13353 * allocate/free it every time bpf_check() is called
13354 */
58e2af8b 13355 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
cbd35700
AS
13356 if (!env)
13357 return -ENOMEM;
61bd5218 13358 log = &env->log;
cbd35700 13359
9e4c24e7 13360 len = (*prog)->len;
fad953ce 13361 env->insn_aux_data =
9e4c24e7 13362 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
3df126f3
JK
13363 ret = -ENOMEM;
13364 if (!env->insn_aux_data)
13365 goto err_free_env;
9e4c24e7
JK
13366 for (i = 0; i < len; i++)
13367 env->insn_aux_data[i].orig_idx = i;
9bac3d6d 13368 env->prog = *prog;
00176a34 13369 env->ops = bpf_verifier_ops[env->prog->type];
387544bf 13370 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
2c78ee89 13371 is_priv = bpf_capable();
0246e64d 13372
76654e67 13373 bpf_get_btf_vmlinux();
8580ac94 13374
cbd35700 13375 /* grab the mutex to protect few globals used by verifier */
45a73c17
AS
13376 if (!is_priv)
13377 mutex_lock(&bpf_verifier_lock);
cbd35700
AS
13378
13379 if (attr->log_level || attr->log_buf || attr->log_size) {
13380 /* user requested verbose verifier output
13381 * and supplied buffer to store the verification trace
13382 */
e7bf8249
JK
13383 log->level = attr->log_level;
13384 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13385 log->len_total = attr->log_size;
cbd35700
AS
13386
13387 ret = -EINVAL;
e7bf8249 13388 /* log attributes have to be sane */
7a9f5c65 13389 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
06ee7115 13390 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
3df126f3 13391 goto err_unlock;
cbd35700 13392 }
1ad2f583 13393
8580ac94
AS
13394 if (IS_ERR(btf_vmlinux)) {
13395 /* Either gcc or pahole or kernel are broken. */
13396 verbose(env, "in-kernel BTF is malformed\n");
13397 ret = PTR_ERR(btf_vmlinux);
38207291 13398 goto skip_full_check;
8580ac94
AS
13399 }
13400
1ad2f583
DB
13401 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13402 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
e07b98d9 13403 env->strict_alignment = true;
e9ee9efc
DM
13404 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13405 env->strict_alignment = false;
cbd35700 13406
2c78ee89 13407 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
01f810ac 13408 env->allow_uninit_stack = bpf_allow_uninit_stack();
41c48f3a 13409 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
2c78ee89
AS
13410 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13411 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13412 env->bpf_capable = bpf_capable();
e2ae4ca2 13413
10d274e8
AS
13414 if (is_priv)
13415 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13416
dc2a4ebc 13417 env->explored_states = kvcalloc(state_htab_size(env),
58e2af8b 13418 sizeof(struct bpf_verifier_state_list *),
f1bca824
AS
13419 GFP_USER);
13420 ret = -ENOMEM;
13421 if (!env->explored_states)
13422 goto skip_full_check;
13423
e6ac2450
MKL
13424 ret = add_subprog_and_kfunc(env);
13425 if (ret < 0)
13426 goto skip_full_check;
13427
d9762e84 13428 ret = check_subprogs(env);
475fb78f
AS
13429 if (ret < 0)
13430 goto skip_full_check;
13431
c454a46b 13432 ret = check_btf_info(env, attr, uattr);
838e9690
YS
13433 if (ret < 0)
13434 goto skip_full_check;
13435
be8704ff
AS
13436 ret = check_attach_btf_id(env);
13437 if (ret)
13438 goto skip_full_check;
13439
4976b718
HL
13440 ret = resolve_pseudo_ldimm64(env);
13441 if (ret < 0)
13442 goto skip_full_check;
13443
ceb11679
YZ
13444 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13445 ret = bpf_prog_offload_verifier_prep(env->prog);
13446 if (ret)
13447 goto skip_full_check;
13448 }
13449
d9762e84
MKL
13450 ret = check_cfg(env);
13451 if (ret < 0)
13452 goto skip_full_check;
13453
51c39bb1
AS
13454 ret = do_check_subprogs(env);
13455 ret = ret ?: do_check_main(env);
cbd35700 13456
c941ce9c
QM
13457 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13458 ret = bpf_prog_offload_finalize(env);
13459
0246e64d 13460skip_full_check:
51c39bb1 13461 kvfree(env->explored_states);
0246e64d 13462
c131187d 13463 if (ret == 0)
9b38c405 13464 ret = check_max_stack_depth(env);
c131187d 13465
9b38c405 13466 /* instruction rewrites happen after this point */
e2ae4ca2
JK
13467 if (is_priv) {
13468 if (ret == 0)
13469 opt_hard_wire_dead_code_branches(env);
52875a04
JK
13470 if (ret == 0)
13471 ret = opt_remove_dead_code(env);
a1b14abc
JK
13472 if (ret == 0)
13473 ret = opt_remove_nops(env);
52875a04
JK
13474 } else {
13475 if (ret == 0)
13476 sanitize_dead_code(env);
e2ae4ca2
JK
13477 }
13478
9bac3d6d
AS
13479 if (ret == 0)
13480 /* program is valid, convert *(u32*)(ctx + off) accesses */
13481 ret = convert_ctx_accesses(env);
13482
e245c5c6 13483 if (ret == 0)
e6ac5933 13484 ret = do_misc_fixups(env);
e245c5c6 13485
a4b1d3c1
JW
13486 /* do 32-bit optimization after insn patching has done so those patched
13487 * insns could be handled correctly.
13488 */
d6c2308c
JW
13489 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13490 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13491 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13492 : false;
a4b1d3c1
JW
13493 }
13494
1ea47e01
AS
13495 if (ret == 0)
13496 ret = fixup_call_args(env);
13497
06ee7115
AS
13498 env->verification_time = ktime_get_ns() - start_time;
13499 print_verification_stats(env);
13500
a2a7d570 13501 if (log->level && bpf_verifier_log_full(log))
cbd35700 13502 ret = -ENOSPC;
a2a7d570 13503 if (log->level && !log->ubuf) {
cbd35700 13504 ret = -EFAULT;
a2a7d570 13505 goto err_release_maps;
cbd35700
AS
13506 }
13507
541c3bad
AN
13508 if (ret)
13509 goto err_release_maps;
13510
13511 if (env->used_map_cnt) {
0246e64d 13512 /* if program passed verifier, update used_maps in bpf_prog_info */
9bac3d6d
AS
13513 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13514 sizeof(env->used_maps[0]),
13515 GFP_KERNEL);
0246e64d 13516
9bac3d6d 13517 if (!env->prog->aux->used_maps) {
0246e64d 13518 ret = -ENOMEM;
a2a7d570 13519 goto err_release_maps;
0246e64d
AS
13520 }
13521
9bac3d6d 13522 memcpy(env->prog->aux->used_maps, env->used_maps,
0246e64d 13523 sizeof(env->used_maps[0]) * env->used_map_cnt);
9bac3d6d 13524 env->prog->aux->used_map_cnt = env->used_map_cnt;
541c3bad
AN
13525 }
13526 if (env->used_btf_cnt) {
13527 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13528 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13529 sizeof(env->used_btfs[0]),
13530 GFP_KERNEL);
13531 if (!env->prog->aux->used_btfs) {
13532 ret = -ENOMEM;
13533 goto err_release_maps;
13534 }
0246e64d 13535
541c3bad
AN
13536 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13537 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13538 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13539 }
13540 if (env->used_map_cnt || env->used_btf_cnt) {
0246e64d
AS
13541 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13542 * bpf_ld_imm64 instructions
13543 */
13544 convert_pseudo_ld_imm64(env);
13545 }
cbd35700 13546
541c3bad 13547 adjust_btf_func(env);
ba64e7d8 13548
a2a7d570 13549err_release_maps:
9bac3d6d 13550 if (!env->prog->aux->used_maps)
0246e64d 13551 /* if we didn't copy map pointers into bpf_prog_info, release
ab7f5bf0 13552 * them now. Otherwise free_used_maps() will release them.
0246e64d
AS
13553 */
13554 release_maps(env);
541c3bad
AN
13555 if (!env->prog->aux->used_btfs)
13556 release_btfs(env);
03f87c0b
THJ
13557
13558 /* extension progs temporarily inherit the attach_type of their targets
13559 for verification purposes, so set it back to zero before returning
13560 */
13561 if (env->prog->type == BPF_PROG_TYPE_EXT)
13562 env->prog->expected_attach_type = 0;
13563
9bac3d6d 13564 *prog = env->prog;
3df126f3 13565err_unlock:
45a73c17
AS
13566 if (!is_priv)
13567 mutex_unlock(&bpf_verifier_lock);
3df126f3
JK
13568 vfree(env->insn_aux_data);
13569err_free_env:
13570 kfree(env);
51580e79
AS
13571 return ret;
13572}