blob: 8574cb60915ad18e4c3984b79a1f8a77f6d27a2a [file] [log] [blame]
Thomas Gleixner5b497af2019-05-29 07:18:09 -07001// SPDX-License-Identifier: GPL-2.0-only
Alexei Starovoitov51580e72014-09-26 00:17:02 -07002/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003 * Copyright (c) 2016 Facebook
Joe Stringerfd978bf72018-10-02 13:35:35 -07004 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
Alexei Starovoitov51580e72014-09-26 00:17:02 -07005 */
Yonghong Song838e9692018-11-19 15:29:11 -08006#include <uapi/linux/btf.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -07007#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
Yonghong Song838e9692018-11-19 15:29:11 -080011#include <linux/btf.h>
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012#include <linux/bpf_verifier.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
Thomas Grafebb676d2016-10-27 11:23:51 +020017#include <linux/stringify.h>
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080018#include <linux/bsearch.h>
19#include <linux/sort.h>
Yonghong Songc195651e2018-04-28 22:28:08 -070020#include <linux/perf_event.h>
Martin KaFai Laud9762e82018-12-13 10:41:48 -080021#include <linux/ctype.h>
KP Singh6ba43b72020-03-04 20:18:50 +010022#include <linux/error-injection.h>
KP Singh9e4e01d2020-03-29 01:43:52 +010023#include <linux/bpf_lsm.h>
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070024#include <linux/btf_ids.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070025
Jakub Kicinskif4ac7e02017-10-09 10:30:12 -070026#include "disasm.h"
27
Jakub Kicinski00176a32017-10-16 16:40:54 -070028static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
Alexei Starovoitov91cc1a92019-11-14 10:57:15 -080029#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
Jakub Kicinski00176a32017-10-16 16:40:54 -070030 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070032#define BPF_LINK_TYPE(_id, _name)
Jakub Kicinski00176a32017-10-16 16:40:54 -070033#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070036#undef BPF_LINK_TYPE
Jakub Kicinski00176a32017-10-16 16:40:54 -070037};
38
Alexei Starovoitov51580e72014-09-26 00:17:02 -070039/* 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.
50 * Since it's analyzing all pathes through the program, the length of the
Gary Lineba38a92017-03-01 16:25:51 +080051 * analysis is limited to 64k insn, which may be hit even if total number of
Alexei Starovoitov51580e72014-09-26 00:17:02 -070052 * 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 *
Edward Creef1174f72017-08-07 15:26:19 +010079 * Most of the time the registers have SCALAR_VALUE type, which
Alexei Starovoitov51580e72014-09-26 00:17:02 -070080 * means the register has some value, but it's not a valid pointer.
Edward Creef1174f72017-08-07 15:26:19 +010081 * (like pointer plus pointer becomes SCALAR_VALUE type)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070082 *
83 * When verifier sees load or store instructions the type of base register
Joe Stringerc64b7982018-10-02 13:35:33 -070084 * 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.
Alexei Starovoitov51580e72014-09-26 00:17:02 -070086 *
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
135 * returns ether pointer to map value or NULL.
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.
Joe Stringerfd978bf72018-10-02 13:35:35 -0700144 *
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.
Joe Stringer6acc9b42018-10-02 13:35:36 -0700156 *
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.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700162 */
163
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100165struct bpf_verifier_stack_elem {
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100170 struct bpf_verifier_state st;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700171 int insn_idx;
172 int prev_insn_idx;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100173 struct bpf_verifier_stack_elem *next;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700176};
177
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
Alexei Starovoitovceefbc92018-12-03 22:46:06 -0800179#define BPF_COMPLEXITY_LIMIT_STATES 64
Daniel Borkmann07016152016-04-05 22:33:17 +0200180
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200184#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{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200197}
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);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100204 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);
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200229}
Martin KaFai Laufad73a12017-03-22 10:00:32 -0700230
Yonghong Song23a2d702021-02-04 15:48:27 -0800231static 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
Martin KaFai Laue6ac2452021-03-24 18:51:42 -0700237static 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
Yonghong Song69c087b2021-02-26 12:49:25 -0800243static 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
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200249struct bpf_call_arg_meta {
250 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200251 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200252 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200253 int regno;
254 int access_size;
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700255 int mem_size;
John Fastabend10060502020-03-30 14:36:19 -0700256 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700257 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800258 int func_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800259 struct btf *btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700260 u32 btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800261 struct btf *ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700262 u32 ret_btf_id;
Yonghong Song69c087b2021-02-26 12:49:25 -0800263 u32 subprogno;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200264};
265
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700266struct btf *btf_vmlinux;
267
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700268static DEFINE_MUTEX(bpf_verifier_lock);
269
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800270static 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
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700291void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
292 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700293{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700294 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700295
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700296 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700297
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
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700304 if (log->level == BPF_LOG_KERNEL) {
305 pr_err("BPF:%s\n", log->kbuf);
306 return;
307 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700308 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
309 log->len_used += n;
310 else
311 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700312}
Jiri Olsaabe08842018-03-23 11:41:28 +0100313
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700314static 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
Jiri Olsaabe08842018-03-23 11:41:28 +0100326/* 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
Quentin Monnet430e68d2018-01-10 12:26:06 +0000329 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100330__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
331 const char *fmt, ...)
332{
333 va_list args;
334
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700335 if (!bpf_verifier_log_needed(&env->log))
336 return;
337
Jiri Olsaabe08842018-03-23 11:41:28 +0100338 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700339 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100340 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{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700346 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100347 va_list args;
348
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700349 if (!bpf_verifier_log_needed(&env->log))
350 return;
351
Jiri Olsaabe08842018-03-23 11:41:28 +0100352 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700353 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100354 va_end(args);
355}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700356
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700357__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
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800370static 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
Yonghong Songbc2591d2021-02-26 12:49:22 -0800406static 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
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200424static 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
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800430static bool type_is_sk_pointer(enum bpf_reg_type type)
431{
432 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800433 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700434 type == PTR_TO_TCP_SOCK ||
435 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800436}
437
John Fastabendcac616d2020-05-21 13:07:26 -0700438static 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 ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800443 type == PTR_TO_MAP_KEY ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700444 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700445}
446
Joe Stringer840b9612018-10-02 13:35:32 -0700447static bool reg_type_may_be_null(enum bpf_reg_type type)
448{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700449 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800450 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800451 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700452 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700453 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700454 type == PTR_TO_MEM_OR_NULL ||
455 type == PTR_TO_RDONLY_BUF_OR_NULL ||
456 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700457}
458
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800459static 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
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700465static 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 ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700470 type == PTR_TO_TCP_SOCK_OR_NULL ||
471 type == PTR_TO_MEM ||
472 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700473}
474
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700475static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700476{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700477 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700478}
479
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100480static 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 ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800486 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
487 type == ARG_PTR_TO_STACK_OR_NULL;
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100488}
489
Joe Stringerfd978bf72018-10-02 13:35:35 -0700490/* 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{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700496 return func_id == BPF_FUNC_sk_release ||
497 func_id == BPF_FUNC_ringbuf_submit ||
498 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700499}
500
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200501static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800502{
503 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800504 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200505 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700506 func_id == BPF_FUNC_map_lookup_elem ||
507 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200508}
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 ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700517 func_id == BPF_FUNC_skc_lookup_tcp ||
518 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200519 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;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800527}
528
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700529static bool is_ptr_cast_function(enum bpf_func_id func_id)
530{
531 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700532 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;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700538}
539
Brendan Jackman39491862021-03-04 18:56:46 -0800540static 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
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700547/* string representation of 'enum bpf_reg_type' */
548static const char * const reg_type_str[] = {
549 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100550 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700551 [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",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700555 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700556 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200557 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700558 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700559 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700560 [PTR_TO_SOCKET] = "sock",
561 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800562 [PTR_TO_SOCK_COMMON] = "sock_common",
563 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800564 [PTR_TO_TCP_SOCK] = "tcp_sock",
565 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700566 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700567 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700568 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700569 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700570 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700571 [PTR_TO_MEM] = "mem",
572 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700573 [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",
Yonghong Song69c087b2021-02-26 12:49:25 -0800577 [PTR_TO_FUNC] = "func",
578 [PTR_TO_MAP_KEY] = "map_key",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700579};
580
Edward Cree8efea212018-08-22 20:02:44 +0100581static char slot_type_char[] = {
582 [STACK_INVALID] = '?',
583 [STACK_SPILL] = 'r',
584 [STACK_MISC] = 'm',
585 [STACK_ZERO] = '0',
586};
587
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800588static void print_liveness(struct bpf_verifier_env *env,
589 enum bpf_reg_liveness live)
590{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800591 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800592 verbose(env, "_");
593 if (live & REG_LIVE_READ)
594 verbose(env, "r");
595 if (live & REG_LIVE_WRITTEN)
596 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800597 if (live & REG_LIVE_DONE)
598 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800599}
600
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800601static struct bpf_func_state *func(struct bpf_verifier_env *env,
602 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700603{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800604 struct bpf_verifier_state *cur = env->cur_state;
605
606 return cur->frame[reg->frameno];
607}
608
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800609static const char *kernel_type_name(const struct btf* btf, u32 id)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700610{
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800611 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700612}
613
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800614static void print_verifier_state(struct bpf_verifier_env *env,
615 const struct bpf_func_state *state)
616{
617 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700618 enum bpf_reg_type t;
619 int i;
620
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800621 if (state->frameno)
622 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700623 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700624 reg = &state->regs[i];
625 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700626 if (t == NOT_INIT)
627 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800628 verbose(env, " R%d", i);
629 print_liveness(env, reg->live);
630 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700631 if (t == SCALAR_VALUE && reg->precise)
632 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100633 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
634 tnum_is_const(reg->var_off)) {
635 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700636 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100637 } else {
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700638 if (t == PTR_TO_BTF_ID ||
639 t == PTR_TO_BTF_ID_OR_NULL ||
640 t == PTR_TO_PERCPU_BTF_ID)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800641 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700642 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);
Edward Creef1174f72017-08-07 15:26:19 +0100645 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700646 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200647 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700648 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100649 else if (t == CONST_PTR_TO_MAP ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800650 t == PTR_TO_MAP_KEY ||
Edward Creef1174f72017-08-07 15:26:19 +0100651 t == PTR_TO_MAP_VALUE ||
652 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700653 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100654 reg->map_ptr->key_size,
655 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100656 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 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700661 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100662 } else {
663 if (reg->smin_value != reg->umin_value &&
664 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700665 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100666 (long long)reg->smin_value);
667 if (reg->smax_value != reg->umax_value &&
668 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700669 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100670 (long long)reg->smax_value);
671 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700672 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100673 (unsigned long long)reg->umin_value);
674 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700675 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100676 (unsigned long long)reg->umax_value);
677 if (!tnum_is_unknown(reg->var_off)) {
678 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100679
Edward Cree7d1238f2017-08-07 15:26:56 +0100680 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700681 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100682 }
John Fastabend3f50f132020-03-30 14:36:39 -0700683 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));
Edward Creef1174f72017-08-07 15:26:19 +0100699 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700700 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100701 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700702 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700703 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100704 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);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700719 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 {
Edward Cree8efea212018-08-22 20:02:44 +0100728 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700729 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700730 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700731 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 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700737 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700738}
739
Joe Stringer84dbf352018-10-02 13:35:34 -0700740#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
741static int copy_##NAME##_state(struct bpf_func_state *dst, \
742 const struct bpf_func_state *src) \
743{ \
744 if (!src->FIELD) \
745 return 0; \
746 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
747 /* internal bug, make state invalid to reject the program */ \
748 memset(dst, 0, sizeof(*dst)); \
749 return -EFAULT; \
750 } \
751 memcpy(dst->FIELD, src->FIELD, \
752 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
753 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700754}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700755/* copy_reference_state() */
756COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700757/* copy_stack_state() */
758COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
759#undef COPY_STATE_FN
760
761#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
762static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
763 bool copy_old) \
764{ \
765 u32 old_size = state->COUNT; \
766 struct bpf_##NAME##_state *new_##FIELD; \
767 int slot = size / SIZE; \
768 \
769 if (size <= old_size || !size) { \
770 if (copy_old) \
771 return 0; \
772 state->COUNT = slot * SIZE; \
773 if (!size && old_size) { \
774 kfree(state->FIELD); \
775 state->FIELD = NULL; \
776 } \
777 return 0; \
778 } \
779 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
780 GFP_KERNEL); \
781 if (!new_##FIELD) \
782 return -ENOMEM; \
783 if (copy_old) { \
784 if (state->FIELD) \
785 memcpy(new_##FIELD, state->FIELD, \
786 sizeof(*new_##FIELD) * (old_size / SIZE)); \
787 memset(new_##FIELD + old_size / SIZE, 0, \
788 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
789 } \
790 state->COUNT = slot * SIZE; \
791 kfree(state->FIELD); \
792 state->FIELD = new_##FIELD; \
793 return 0; \
794}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700795/* realloc_reference_state() */
796REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700797/* realloc_stack_state() */
798REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
799#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700800
801/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
802 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800803 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700804 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
805 * which realloc_stack_state() copies over. It points to previous
806 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700807 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700808static int realloc_func_state(struct bpf_func_state *state, int stack_size,
809 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700810{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700811 int err = realloc_reference_state(state, refs_size, copy_old);
812 if (err)
813 return err;
814 return realloc_stack_state(state, stack_size, copy_old);
815}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700816
Joe Stringerfd978bf72018-10-02 13:35:35 -0700817/* Acquire a pointer id from the env and update the state->refs to include
818 * this new pointer reference.
819 * On success, returns a valid pointer id to associate with the register
820 * On failure, returns a negative errno.
821 */
822static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
823{
824 struct bpf_func_state *state = cur_func(env);
825 int new_ofs = state->acquired_refs;
826 int id, err;
827
828 err = realloc_reference_state(state, state->acquired_refs + 1, true);
829 if (err)
830 return err;
831 id = ++env->id_gen;
832 state->refs[new_ofs].id = id;
833 state->refs[new_ofs].insn_idx = insn_idx;
834
835 return id;
836}
837
838/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800839static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700840{
841 int i, last_idx;
842
Joe Stringerfd978bf72018-10-02 13:35:35 -0700843 last_idx = state->acquired_refs - 1;
844 for (i = 0; i < state->acquired_refs; i++) {
845 if (state->refs[i].id == ptr_id) {
846 if (last_idx && i != last_idx)
847 memcpy(&state->refs[i], &state->refs[last_idx],
848 sizeof(*state->refs));
849 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
850 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700851 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700852 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700853 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800854 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700855}
856
857static int transfer_reference_state(struct bpf_func_state *dst,
858 struct bpf_func_state *src)
859{
860 int err = realloc_reference_state(dst, src->acquired_refs, false);
861 if (err)
862 return err;
863 err = copy_reference_state(dst, src);
864 if (err)
865 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700866 return 0;
867}
868
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800869static void free_func_state(struct bpf_func_state *state)
870{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800871 if (!state)
872 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700873 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800874 kfree(state->stack);
875 kfree(state);
876}
877
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700878static void clear_jmp_history(struct bpf_verifier_state *state)
879{
880 kfree(state->jmp_history);
881 state->jmp_history = NULL;
882 state->jmp_history_cnt = 0;
883}
884
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700885static void free_verifier_state(struct bpf_verifier_state *state,
886 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700887{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800888 int i;
889
890 for (i = 0; i <= state->curframe; i++) {
891 free_func_state(state->frame[i]);
892 state->frame[i] = NULL;
893 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700894 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700895 if (free_self)
896 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700897}
898
899/* copy verifier state from src to dst growing dst stack space
900 * when necessary to accommodate larger src stack
901 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800902static int copy_func_state(struct bpf_func_state *dst,
903 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700904{
905 int err;
906
Joe Stringerfd978bf72018-10-02 13:35:35 -0700907 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
908 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700909 if (err)
910 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700911 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
912 err = copy_reference_state(dst, src);
913 if (err)
914 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700915 return copy_stack_state(dst, src);
916}
917
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800918static int copy_verifier_state(struct bpf_verifier_state *dst_state,
919 const struct bpf_verifier_state *src)
920{
921 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700922 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800923 int i, err;
924
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700925 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
926 kfree(dst_state->jmp_history);
927 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
928 if (!dst_state->jmp_history)
929 return -ENOMEM;
930 }
931 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
932 dst_state->jmp_history_cnt = src->jmp_history_cnt;
933
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800934 /* if dst has more stack frames then src frame, free them */
935 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
936 free_func_state(dst_state->frame[i]);
937 dst_state->frame[i] = NULL;
938 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100939 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800940 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800941 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700942 dst_state->branches = src->branches;
943 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700944 dst_state->first_insn_idx = src->first_insn_idx;
945 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800946 for (i = 0; i <= src->curframe; i++) {
947 dst = dst_state->frame[i];
948 if (!dst) {
949 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
950 if (!dst)
951 return -ENOMEM;
952 dst_state->frame[i] = dst;
953 }
954 err = copy_func_state(dst, src->frame[i]);
955 if (err)
956 return err;
957 }
958 return 0;
959}
960
Alexei Starovoitov25897262019-06-15 12:12:20 -0700961static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
962{
963 while (st) {
964 u32 br = --st->branches;
965
966 /* WARN_ON(br > 1) technically makes sense here,
967 * but see comment in push_stack(), hence:
968 */
969 WARN_ONCE((int)br < 0,
970 "BUG update_branch_counts:branches_to_explore=%d\n",
971 br);
972 if (br)
973 break;
974 st = st->parent;
975 }
976}
977
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700978static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700979 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700980{
981 struct bpf_verifier_state *cur = env->cur_state;
982 struct bpf_verifier_stack_elem *elem, *head = env->head;
983 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700984
985 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700986 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700987
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700988 if (cur) {
989 err = copy_verifier_state(cur, &head->st);
990 if (err)
991 return err;
992 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700993 if (pop_log)
994 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700995 if (insn_idx)
996 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700997 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700998 *prev_insn_idx = head->prev_insn_idx;
999 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001000 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001001 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001002 env->head = elem;
1003 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001004 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001005}
1006
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001007static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001008 int insn_idx, int prev_insn_idx,
1009 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001010{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001011 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001012 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001013 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001014
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001015 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001016 if (!elem)
1017 goto err;
1018
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001019 elem->insn_idx = insn_idx;
1020 elem->prev_insn_idx = prev_insn_idx;
1021 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001022 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001023 env->head = elem;
1024 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001025 err = copy_verifier_state(&elem->st, cur);
1026 if (err)
1027 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001028 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -07001029 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1030 verbose(env, "The sequence of %d jumps is too complex.\n",
1031 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001032 goto err;
1033 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07001034 if (elem->st.parent) {
1035 ++elem->st.parent->branches;
1036 /* WARN_ON(branches > 2) technically makes sense here,
1037 * but
1038 * 1. speculative states will bump 'branches' for non-branch
1039 * instructions
1040 * 2. is_state_visited() heuristics may decide not to create
1041 * a new state for a sequence of branches and all such current
1042 * and cloned states will be pointing to a single parent state
1043 * which might have large 'branches' count.
1044 */
1045 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001046 return &elem->st;
1047err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001048 free_verifier_state(env->cur_state, true);
1049 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001050 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001051 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001052 return NULL;
1053}
1054
1055#define CALLER_SAVED_REGS 6
1056static const int caller_saved[CALLER_SAVED_REGS] = {
1057 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1058};
1059
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001060static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1061 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001062
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001063/* This helper doesn't clear reg->id */
1064static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001065{
Edward Creeb03c9f92017-08-07 15:26:36 +01001066 reg->var_off = tnum_const(imm);
1067 reg->smin_value = (s64)imm;
1068 reg->smax_value = (s64)imm;
1069 reg->umin_value = imm;
1070 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001071
1072 reg->s32_min_value = (s32)imm;
1073 reg->s32_max_value = (s32)imm;
1074 reg->u32_min_value = (u32)imm;
1075 reg->u32_max_value = (u32)imm;
1076}
1077
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001078/* Mark the unknown part of a register (variable offset or scalar value) as
1079 * known to have the value @imm.
1080 */
1081static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1082{
1083 /* Clear id, off, and union(map_ptr, range) */
1084 memset(((u8 *)reg) + sizeof(reg->type), 0,
1085 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1086 ___mark_reg_known(reg, imm);
1087}
1088
John Fastabend3f50f132020-03-30 14:36:39 -07001089static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1090{
1091 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1092 reg->s32_min_value = (s32)imm;
1093 reg->s32_max_value = (s32)imm;
1094 reg->u32_min_value = (u32)imm;
1095 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001096}
1097
Edward Creef1174f72017-08-07 15:26:19 +01001098/* Mark the 'variable offset' part of a register as zero. This should be
1099 * used only on registers holding a pointer type.
1100 */
1101static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1102{
Edward Creeb03c9f92017-08-07 15:26:36 +01001103 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001104}
1105
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001106static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1107{
1108 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001109 reg->type = SCALAR_VALUE;
1110}
1111
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001112static void mark_reg_known_zero(struct bpf_verifier_env *env,
1113 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001114{
1115 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001116 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001117 /* Something bad happened, let's kill all regs */
1118 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001119 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001120 return;
1121 }
1122 __mark_reg_known_zero(regs + regno);
1123}
1124
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001125static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1126{
1127 switch (reg->type) {
1128 case PTR_TO_MAP_VALUE_OR_NULL: {
1129 const struct bpf_map *map = reg->map_ptr;
1130
1131 if (map->inner_map_meta) {
1132 reg->type = CONST_PTR_TO_MAP;
1133 reg->map_ptr = map->inner_map_meta;
1134 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1135 reg->type = PTR_TO_XDP_SOCK;
1136 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1137 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1138 reg->type = PTR_TO_SOCKET;
1139 } else {
1140 reg->type = PTR_TO_MAP_VALUE;
1141 }
1142 break;
1143 }
1144 case PTR_TO_SOCKET_OR_NULL:
1145 reg->type = PTR_TO_SOCKET;
1146 break;
1147 case PTR_TO_SOCK_COMMON_OR_NULL:
1148 reg->type = PTR_TO_SOCK_COMMON;
1149 break;
1150 case PTR_TO_TCP_SOCK_OR_NULL:
1151 reg->type = PTR_TO_TCP_SOCK;
1152 break;
1153 case PTR_TO_BTF_ID_OR_NULL:
1154 reg->type = PTR_TO_BTF_ID;
1155 break;
1156 case PTR_TO_MEM_OR_NULL:
1157 reg->type = PTR_TO_MEM;
1158 break;
1159 case PTR_TO_RDONLY_BUF_OR_NULL:
1160 reg->type = PTR_TO_RDONLY_BUF;
1161 break;
1162 case PTR_TO_RDWR_BUF_OR_NULL:
1163 reg->type = PTR_TO_RDWR_BUF;
1164 break;
1165 default:
Dan Carpenter33ccec52021-02-17 10:45:25 +03001166 WARN_ONCE(1, "unknown nullable register type");
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001167 }
1168}
1169
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001170static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1171{
1172 return type_is_pkt_pointer(reg->type);
1173}
1174
1175static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1176{
1177 return reg_is_pkt_pointer(reg) ||
1178 reg->type == PTR_TO_PACKET_END;
1179}
1180
1181/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1182static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1183 enum bpf_reg_type which)
1184{
1185 /* The register can already have a range from prior markings.
1186 * This is fine as long as it hasn't been advanced from its
1187 * origin.
1188 */
1189 return reg->type == which &&
1190 reg->id == 0 &&
1191 reg->off == 0 &&
1192 tnum_equals_const(reg->var_off, 0);
1193}
1194
John Fastabend3f50f132020-03-30 14:36:39 -07001195/* Reset the min/max bounds of a register */
1196static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1197{
1198 reg->smin_value = S64_MIN;
1199 reg->smax_value = S64_MAX;
1200 reg->umin_value = 0;
1201 reg->umax_value = U64_MAX;
1202
1203 reg->s32_min_value = S32_MIN;
1204 reg->s32_max_value = S32_MAX;
1205 reg->u32_min_value = 0;
1206 reg->u32_max_value = U32_MAX;
1207}
1208
1209static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1210{
1211 reg->smin_value = S64_MIN;
1212 reg->smax_value = S64_MAX;
1213 reg->umin_value = 0;
1214 reg->umax_value = U64_MAX;
1215}
1216
1217static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1218{
1219 reg->s32_min_value = S32_MIN;
1220 reg->s32_max_value = S32_MAX;
1221 reg->u32_min_value = 0;
1222 reg->u32_max_value = U32_MAX;
1223}
1224
1225static void __update_reg32_bounds(struct bpf_reg_state *reg)
1226{
1227 struct tnum var32_off = tnum_subreg(reg->var_off);
1228
1229 /* min signed is max(sign bit) | min(other bits) */
1230 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1231 var32_off.value | (var32_off.mask & S32_MIN));
1232 /* max signed is min(sign bit) | max(other bits) */
1233 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1234 var32_off.value | (var32_off.mask & S32_MAX));
1235 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1236 reg->u32_max_value = min(reg->u32_max_value,
1237 (u32)(var32_off.value | var32_off.mask));
1238}
1239
1240static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001241{
1242 /* min signed is max(sign bit) | min(other bits) */
1243 reg->smin_value = max_t(s64, reg->smin_value,
1244 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1245 /* max signed is min(sign bit) | max(other bits) */
1246 reg->smax_value = min_t(s64, reg->smax_value,
1247 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1248 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1249 reg->umax_value = min(reg->umax_value,
1250 reg->var_off.value | reg->var_off.mask);
1251}
1252
John Fastabend3f50f132020-03-30 14:36:39 -07001253static void __update_reg_bounds(struct bpf_reg_state *reg)
1254{
1255 __update_reg32_bounds(reg);
1256 __update_reg64_bounds(reg);
1257}
1258
Edward Creeb03c9f92017-08-07 15:26:36 +01001259/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001260static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1261{
1262 /* Learn sign from signed bounds.
1263 * If we cannot cross the sign boundary, then signed and unsigned bounds
1264 * are the same, so combine. This works even in the negative case, e.g.
1265 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1266 */
1267 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1268 reg->s32_min_value = reg->u32_min_value =
1269 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1270 reg->s32_max_value = reg->u32_max_value =
1271 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1272 return;
1273 }
1274 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1275 * boundary, so we must be careful.
1276 */
1277 if ((s32)reg->u32_max_value >= 0) {
1278 /* Positive. We can't learn anything from the smin, but smax
1279 * is positive, hence safe.
1280 */
1281 reg->s32_min_value = reg->u32_min_value;
1282 reg->s32_max_value = reg->u32_max_value =
1283 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1284 } else if ((s32)reg->u32_min_value < 0) {
1285 /* Negative. We can't learn anything from the smax, but smin
1286 * is negative, hence safe.
1287 */
1288 reg->s32_min_value = reg->u32_min_value =
1289 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1290 reg->s32_max_value = reg->u32_max_value;
1291 }
1292}
1293
1294static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001295{
1296 /* Learn sign from signed bounds.
1297 * If we cannot cross the sign boundary, then signed and unsigned bounds
1298 * are the same, so combine. This works even in the negative case, e.g.
1299 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1300 */
1301 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1302 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1303 reg->umin_value);
1304 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1305 reg->umax_value);
1306 return;
1307 }
1308 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1309 * boundary, so we must be careful.
1310 */
1311 if ((s64)reg->umax_value >= 0) {
1312 /* Positive. We can't learn anything from the smin, but smax
1313 * is positive, hence safe.
1314 */
1315 reg->smin_value = reg->umin_value;
1316 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1317 reg->umax_value);
1318 } else if ((s64)reg->umin_value < 0) {
1319 /* Negative. We can't learn anything from the smax, but smin
1320 * is negative, hence safe.
1321 */
1322 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1323 reg->umin_value);
1324 reg->smax_value = reg->umax_value;
1325 }
1326}
1327
John Fastabend3f50f132020-03-30 14:36:39 -07001328static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1329{
1330 __reg32_deduce_bounds(reg);
1331 __reg64_deduce_bounds(reg);
1332}
1333
Edward Creeb03c9f92017-08-07 15:26:36 +01001334/* Attempts to improve var_off based on unsigned min/max information */
1335static void __reg_bound_offset(struct bpf_reg_state *reg)
1336{
John Fastabend3f50f132020-03-30 14:36:39 -07001337 struct tnum var64_off = tnum_intersect(reg->var_off,
1338 tnum_range(reg->umin_value,
1339 reg->umax_value));
1340 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1341 tnum_range(reg->u32_min_value,
1342 reg->u32_max_value));
1343
1344 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001345}
1346
John Fastabend3f50f132020-03-30 14:36:39 -07001347static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001348{
John Fastabend3f50f132020-03-30 14:36:39 -07001349 reg->umin_value = reg->u32_min_value;
1350 reg->umax_value = reg->u32_max_value;
1351 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1352 * but must be positive otherwise set to worse case bounds
1353 * and refine later from tnum.
1354 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001355 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001356 reg->smax_value = reg->s32_max_value;
1357 else
1358 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001359 if (reg->s32_min_value >= 0)
1360 reg->smin_value = reg->s32_min_value;
1361 else
1362 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001363}
1364
1365static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1366{
1367 /* special case when 64-bit register has upper 32-bit register
1368 * zeroed. Typically happens after zext or <<32, >>32 sequence
1369 * allowing us to use 32-bit bounds directly,
1370 */
1371 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1372 __reg_assign_32_into_64(reg);
1373 } else {
1374 /* Otherwise the best we can do is push lower 32bit known and
1375 * unknown bits into register (var_off set from jmp logic)
1376 * then learn as much as possible from the 64-bit tnum
1377 * known and unknown bits. The previous smin/smax bounds are
1378 * invalid here because of jmp32 compare so mark them unknown
1379 * so they do not impact tnum bounds calculation.
1380 */
1381 __mark_reg64_unbounded(reg);
1382 __update_reg_bounds(reg);
1383 }
1384
1385 /* Intersecting with the old var_off might have improved our bounds
1386 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1387 * then new var_off is (0; 0x7f...fc) which improves our umax.
1388 */
1389 __reg_deduce_bounds(reg);
1390 __reg_bound_offset(reg);
1391 __update_reg_bounds(reg);
1392}
1393
1394static bool __reg64_bound_s32(s64 a)
1395{
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001396 return a > S32_MIN && a < S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001397}
1398
1399static bool __reg64_bound_u32(u64 a)
1400{
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001401 return a > U32_MIN && a < U32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001402}
1403
1404static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1405{
1406 __mark_reg32_unbounded(reg);
1407
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001408 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001409 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001410 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001411 }
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001412 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001413 reg->u32_min_value = (u32)reg->umin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001414 reg->u32_max_value = (u32)reg->umax_value;
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001415 }
John Fastabend3f50f132020-03-30 14:36:39 -07001416
1417 /* Intersecting with the old var_off might have improved our bounds
1418 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1419 * then new var_off is (0; 0x7f...fc) which improves our umax.
1420 */
1421 __reg_deduce_bounds(reg);
1422 __reg_bound_offset(reg);
1423 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001424}
1425
Edward Creef1174f72017-08-07 15:26:19 +01001426/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001427static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1428 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001429{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001430 /*
1431 * Clear type, id, off, and union(map_ptr, range) and
1432 * padding between 'type' and union
1433 */
1434 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001435 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001436 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001437 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001438 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001439 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001440}
1441
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001442static void mark_reg_unknown(struct bpf_verifier_env *env,
1443 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001444{
1445 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001446 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001447 /* Something bad happened, let's kill all regs except FP */
1448 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001449 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001450 return;
1451 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001452 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001453}
1454
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001455static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1456 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001457{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001458 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001459 reg->type = NOT_INIT;
1460}
1461
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001462static void mark_reg_not_init(struct bpf_verifier_env *env,
1463 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001464{
Edward Creef1174f72017-08-07 15:26:19 +01001465 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001466 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001467 /* Something bad happened, let's kill all regs except FP */
1468 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001469 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001470 return;
1471 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001472 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001473}
1474
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001475static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1476 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001477 enum bpf_reg_type reg_type,
1478 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001479{
1480 if (reg_type == SCALAR_VALUE) {
1481 mark_reg_unknown(env, regs, regno);
1482 return;
1483 }
1484 mark_reg_known_zero(env, regs, regno);
1485 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001486 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001487 regs[regno].btf_id = btf_id;
1488}
1489
Jiong Wang5327ed32019-05-24 23:25:12 +01001490#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001491static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001492 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001493{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001494 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001495 int i;
1496
Edward Creedc503a82017-08-15 20:34:35 +01001497 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001498 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001499 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001500 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001501 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001502 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001503
1504 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001505 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001506 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001507 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001508}
1509
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001510#define BPF_MAIN_FUNC (-1)
1511static void init_func_state(struct bpf_verifier_env *env,
1512 struct bpf_func_state *state,
1513 int callsite, int frameno, int subprogno)
1514{
1515 state->callsite = callsite;
1516 state->frameno = frameno;
1517 state->subprogno = subprogno;
1518 init_reg_state(env, state);
1519}
1520
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001521enum reg_arg_type {
1522 SRC_OP, /* register is used as source operand */
1523 DST_OP, /* register is used as destination operand */
1524 DST_OP_NO_MARK /* same as above, check only, don't mark */
1525};
1526
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001527static int cmp_subprogs(const void *a, const void *b)
1528{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001529 return ((struct bpf_subprog_info *)a)->start -
1530 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001531}
1532
1533static int find_subprog(struct bpf_verifier_env *env, int off)
1534{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001535 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001536
Jiong Wang9c8105b2018-05-02 16:17:18 -04001537 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1538 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001539 if (!p)
1540 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001541 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001542
1543}
1544
1545static int add_subprog(struct bpf_verifier_env *env, int off)
1546{
1547 int insn_cnt = env->prog->len;
1548 int ret;
1549
1550 if (off >= insn_cnt || off < 0) {
1551 verbose(env, "call to invalid destination\n");
1552 return -EINVAL;
1553 }
1554 ret = find_subprog(env, off);
1555 if (ret >= 0)
Yonghong Song282a0f42021-02-26 12:49:24 -08001556 return ret;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001557 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001558 verbose(env, "too many subprograms\n");
1559 return -E2BIG;
1560 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001561 /* determine subprog starts. The end is one before the next starts */
Jiong Wang9c8105b2018-05-02 16:17:18 -04001562 env->subprog_info[env->subprog_cnt++].start = off;
1563 sort(env->subprog_info, env->subprog_cnt,
1564 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Yonghong Song282a0f42021-02-26 12:49:24 -08001565 return env->subprog_cnt - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001566}
1567
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001568struct bpf_kfunc_desc {
1569 struct btf_func_model func_model;
1570 u32 func_id;
1571 s32 imm;
1572};
1573
1574#define MAX_KFUNC_DESCS 256
1575struct bpf_kfunc_desc_tab {
1576 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1577 u32 nr_descs;
1578};
1579
1580static int kfunc_desc_cmp_by_id(const void *a, const void *b)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001581{
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001582 const struct bpf_kfunc_desc *d0 = a;
1583 const struct bpf_kfunc_desc *d1 = b;
1584
1585 /* func_id is not greater than BTF_MAX_TYPE */
1586 return d0->func_id - d1->func_id;
1587}
1588
1589static const struct bpf_kfunc_desc *
1590find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1591{
1592 struct bpf_kfunc_desc desc = {
1593 .func_id = func_id,
1594 };
1595 struct bpf_kfunc_desc_tab *tab;
1596
1597 tab = prog->aux->kfunc_tab;
1598 return bsearch(&desc, tab->descs, tab->nr_descs,
1599 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1600}
1601
1602static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1603{
1604 const struct btf_type *func, *func_proto;
1605 struct bpf_kfunc_desc_tab *tab;
1606 struct bpf_prog_aux *prog_aux;
1607 struct bpf_kfunc_desc *desc;
1608 const char *func_name;
1609 unsigned long addr;
1610 int err;
1611
1612 prog_aux = env->prog->aux;
1613 tab = prog_aux->kfunc_tab;
1614 if (!tab) {
1615 if (!btf_vmlinux) {
1616 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1617 return -ENOTSUPP;
1618 }
1619
1620 if (!env->prog->jit_requested) {
1621 verbose(env, "JIT is required for calling kernel function\n");
1622 return -ENOTSUPP;
1623 }
1624
1625 if (!bpf_jit_supports_kfunc_call()) {
1626 verbose(env, "JIT does not support calling kernel function\n");
1627 return -ENOTSUPP;
1628 }
1629
1630 if (!env->prog->gpl_compatible) {
1631 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1632 return -EINVAL;
1633 }
1634
1635 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1636 if (!tab)
1637 return -ENOMEM;
1638 prog_aux->kfunc_tab = tab;
1639 }
1640
1641 if (find_kfunc_desc(env->prog, func_id))
1642 return 0;
1643
1644 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1645 verbose(env, "too many different kernel function calls\n");
1646 return -E2BIG;
1647 }
1648
1649 func = btf_type_by_id(btf_vmlinux, func_id);
1650 if (!func || !btf_type_is_func(func)) {
1651 verbose(env, "kernel btf_id %u is not a function\n",
1652 func_id);
1653 return -EINVAL;
1654 }
1655 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1656 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1657 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1658 func_id);
1659 return -EINVAL;
1660 }
1661
1662 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1663 addr = kallsyms_lookup_name(func_name);
1664 if (!addr) {
1665 verbose(env, "cannot find address for kernel function %s\n",
1666 func_name);
1667 return -EINVAL;
1668 }
1669
1670 desc = &tab->descs[tab->nr_descs++];
1671 desc->func_id = func_id;
1672 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1673 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1674 func_proto, func_name,
1675 &desc->func_model);
1676 if (!err)
1677 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1678 kfunc_desc_cmp_by_id, NULL);
1679 return err;
1680}
1681
1682static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1683{
1684 const struct bpf_kfunc_desc *d0 = a;
1685 const struct bpf_kfunc_desc *d1 = b;
1686
1687 if (d0->imm > d1->imm)
1688 return 1;
1689 else if (d0->imm < d1->imm)
1690 return -1;
1691 return 0;
1692}
1693
1694static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1695{
1696 struct bpf_kfunc_desc_tab *tab;
1697
1698 tab = prog->aux->kfunc_tab;
1699 if (!tab)
1700 return;
1701
1702 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1703 kfunc_desc_cmp_by_imm, NULL);
1704}
1705
1706bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1707{
1708 return !!prog->aux->kfunc_tab;
1709}
1710
1711const struct btf_func_model *
1712bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1713 const struct bpf_insn *insn)
1714{
1715 const struct bpf_kfunc_desc desc = {
1716 .imm = insn->imm,
1717 };
1718 const struct bpf_kfunc_desc *res;
1719 struct bpf_kfunc_desc_tab *tab;
1720
1721 tab = prog->aux->kfunc_tab;
1722 res = bsearch(&desc, tab->descs, tab->nr_descs,
1723 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1724
1725 return res ? &res->func_model : NULL;
1726}
1727
1728static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1729{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001730 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001731 struct bpf_insn *insn = env->prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001732 int i, ret, insn_cnt = env->prog->len;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001733
Jiong Wangf910cef2018-05-02 16:17:17 -04001734 /* Add entry function. */
1735 ret = add_subprog(env, 0);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001736 if (ret)
Jiong Wangf910cef2018-05-02 16:17:17 -04001737 return ret;
1738
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001739 for (i = 0; i < insn_cnt; i++, insn++) {
1740 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1741 !bpf_pseudo_kfunc_call(insn))
Yonghong Song69c087b2021-02-26 12:49:25 -08001742 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001743
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001744 if (!env->bpf_capable) {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001745 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001746 return -EPERM;
1747 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001748
1749 if (bpf_pseudo_func(insn)) {
1750 ret = add_subprog(env, i + insn->imm + 1);
1751 if (ret >= 0)
1752 /* remember subprog */
1753 insn[1].imm = ret;
1754 } else if (bpf_pseudo_call(insn)) {
1755 ret = add_subprog(env, i + insn->imm + 1);
1756 } else {
1757 ret = add_kfunc_call(env, insn->imm);
1758 }
1759
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001760 if (ret < 0)
1761 return ret;
1762 }
1763
Jiong Wang4cb3d992018-05-02 16:17:19 -04001764 /* Add a fake 'exit' subprog which could simplify subprog iteration
1765 * logic. 'subprog_cnt' should not be increased.
1766 */
1767 subprog[env->subprog_cnt].start = insn_cnt;
1768
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001769 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001770 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001771 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001772
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001773 return 0;
1774}
1775
1776static int check_subprogs(struct bpf_verifier_env *env)
1777{
1778 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1779 struct bpf_subprog_info *subprog = env->subprog_info;
1780 struct bpf_insn *insn = env->prog->insnsi;
1781 int insn_cnt = env->prog->len;
1782
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001783 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001784 subprog_start = subprog[cur_subprog].start;
1785 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001786 for (i = 0; i < insn_cnt; i++) {
1787 u8 code = insn[i].code;
1788
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001789 if (code == (BPF_JMP | BPF_CALL) &&
1790 insn[i].imm == BPF_FUNC_tail_call &&
1791 insn[i].src_reg != BPF_PSEUDO_CALL)
1792 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001793 if (BPF_CLASS(code) == BPF_LD &&
1794 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1795 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001796 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001797 goto next;
1798 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1799 goto next;
1800 off = i + insn[i].off + 1;
1801 if (off < subprog_start || off >= subprog_end) {
1802 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1803 return -EINVAL;
1804 }
1805next:
1806 if (i == subprog_end - 1) {
1807 /* to avoid fall-through from one subprog into another
1808 * the last insn of the subprog should be either exit
1809 * or unconditional jump back
1810 */
1811 if (code != (BPF_JMP | BPF_EXIT) &&
1812 code != (BPF_JMP | BPF_JA)) {
1813 verbose(env, "last insn is not an exit or jmp\n");
1814 return -EINVAL;
1815 }
1816 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001817 cur_subprog++;
1818 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001819 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001820 }
1821 }
1822 return 0;
1823}
1824
Edward Cree679c7822018-08-22 20:02:19 +01001825/* Parentage chain of this register (or stack slot) should take care of all
1826 * issues like callee-saved registers, stack slot allocation time, etc.
1827 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001828static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001829 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001830 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001831{
1832 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001833 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001834
1835 while (parent) {
1836 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001837 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001838 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001839 if (parent->live & REG_LIVE_DONE) {
1840 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1841 reg_type_str[parent->type],
1842 parent->var_off.value, parent->off);
1843 return -EFAULT;
1844 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001845 /* The first condition is more likely to be true than the
1846 * second, checked it first.
1847 */
1848 if ((parent->live & REG_LIVE_READ) == flag ||
1849 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001850 /* The parentage chain never changes and
1851 * this parent was already marked as LIVE_READ.
1852 * There is no need to keep walking the chain again and
1853 * keep re-marking all parents as LIVE_READ.
1854 * This case happens when the same register is read
1855 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001856 * Also, if parent has the stronger REG_LIVE_READ64 set,
1857 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001858 */
1859 break;
Edward Creedc503a82017-08-15 20:34:35 +01001860 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001861 parent->live |= flag;
1862 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1863 if (flag == REG_LIVE_READ64)
1864 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001865 state = parent;
1866 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001867 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001868 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001869 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001870
1871 if (env->longest_mark_read_walk < cnt)
1872 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001873 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001874}
1875
Jiong Wang5327ed32019-05-24 23:25:12 +01001876/* This function is supposed to be used by the following 32-bit optimization
1877 * code only. It returns TRUE if the source or destination register operates
1878 * on 64-bit, otherwise return FALSE.
1879 */
1880static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1881 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1882{
1883 u8 code, class, op;
1884
1885 code = insn->code;
1886 class = BPF_CLASS(code);
1887 op = BPF_OP(code);
1888 if (class == BPF_JMP) {
1889 /* BPF_EXIT for "main" will reach here. Return TRUE
1890 * conservatively.
1891 */
1892 if (op == BPF_EXIT)
1893 return true;
1894 if (op == BPF_CALL) {
1895 /* BPF to BPF call will reach here because of marking
1896 * caller saved clobber with DST_OP_NO_MARK for which we
1897 * don't care the register def because they are anyway
1898 * marked as NOT_INIT already.
1899 */
1900 if (insn->src_reg == BPF_PSEUDO_CALL)
1901 return false;
1902 /* Helper call will reach here because of arg type
1903 * check, conservatively return TRUE.
1904 */
1905 if (t == SRC_OP)
1906 return true;
1907
1908 return false;
1909 }
1910 }
1911
1912 if (class == BPF_ALU64 || class == BPF_JMP ||
1913 /* BPF_END always use BPF_ALU class. */
1914 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1915 return true;
1916
1917 if (class == BPF_ALU || class == BPF_JMP32)
1918 return false;
1919
1920 if (class == BPF_LDX) {
1921 if (t != SRC_OP)
1922 return BPF_SIZE(code) == BPF_DW;
1923 /* LDX source must be ptr. */
1924 return true;
1925 }
1926
1927 if (class == BPF_STX) {
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001928 /* BPF_STX (including atomic variants) has multiple source
1929 * operands, one of which is a ptr. Check whether the caller is
1930 * asking about it.
1931 */
1932 if (t == SRC_OP && reg->type != SCALAR_VALUE)
Jiong Wang5327ed32019-05-24 23:25:12 +01001933 return true;
1934 return BPF_SIZE(code) == BPF_DW;
1935 }
1936
1937 if (class == BPF_LD) {
1938 u8 mode = BPF_MODE(code);
1939
1940 /* LD_IMM64 */
1941 if (mode == BPF_IMM)
1942 return true;
1943
1944 /* Both LD_IND and LD_ABS return 32-bit data. */
1945 if (t != SRC_OP)
1946 return false;
1947
1948 /* Implicit ctx ptr. */
1949 if (regno == BPF_REG_6)
1950 return true;
1951
1952 /* Explicit source could be any width. */
1953 return true;
1954 }
1955
1956 if (class == BPF_ST)
1957 /* The only source register for BPF_ST is a ptr. */
1958 return true;
1959
1960 /* Conservatively return true at default. */
1961 return true;
1962}
1963
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001964/* Return the regno defined by the insn, or -1. */
1965static int insn_def_regno(const struct bpf_insn *insn)
Jiong Wangb325fbc2019-05-24 23:25:13 +01001966{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001967 switch (BPF_CLASS(insn->code)) {
1968 case BPF_JMP:
1969 case BPF_JMP32:
1970 case BPF_ST:
1971 return -1;
1972 case BPF_STX:
1973 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1974 (insn->imm & BPF_FETCH)) {
1975 if (insn->imm == BPF_CMPXCHG)
1976 return BPF_REG_0;
1977 else
1978 return insn->src_reg;
1979 } else {
1980 return -1;
1981 }
1982 default:
1983 return insn->dst_reg;
1984 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01001985}
1986
1987/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1988static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1989{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001990 int dst_reg = insn_def_regno(insn);
1991
1992 if (dst_reg == -1)
Jiong Wangb325fbc2019-05-24 23:25:13 +01001993 return false;
1994
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001995 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
Jiong Wangb325fbc2019-05-24 23:25:13 +01001996}
1997
Jiong Wang5327ed32019-05-24 23:25:12 +01001998static void mark_insn_zext(struct bpf_verifier_env *env,
1999 struct bpf_reg_state *reg)
2000{
2001 s32 def_idx = reg->subreg_def;
2002
2003 if (def_idx == DEF_NOT_SUBREG)
2004 return;
2005
2006 env->insn_aux_data[def_idx - 1].zext_dst = true;
2007 /* The dst will be zero extended, so won't be sub-register anymore. */
2008 reg->subreg_def = DEF_NOT_SUBREG;
2009}
2010
Edward Creedc503a82017-08-15 20:34:35 +01002011static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002012 enum reg_arg_type t)
2013{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002014 struct bpf_verifier_state *vstate = env->cur_state;
2015 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01002016 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01002017 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01002018 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01002019
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002020 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002021 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002022 return -EINVAL;
2023 }
2024
Jiong Wangc342dc12019-04-12 22:59:37 +01002025 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01002026 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002027 if (t == SRC_OP) {
2028 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01002029 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002030 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002031 return -EACCES;
2032 }
Edward Cree679c7822018-08-22 20:02:19 +01002033 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01002034 if (regno == BPF_REG_FP)
2035 return 0;
2036
Jiong Wang5327ed32019-05-24 23:25:12 +01002037 if (rw64)
2038 mark_insn_zext(env, reg);
2039
2040 return mark_reg_read(env, reg, reg->parent,
2041 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002042 } else {
2043 /* check whether register used as dest operand can be written to */
2044 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002045 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002046 return -EACCES;
2047 }
Jiong Wangc342dc12019-04-12 22:59:37 +01002048 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01002049 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002050 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002051 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002052 }
2053 return 0;
2054}
2055
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002056/* for any branch, call, exit record the history of jmps in the given state */
2057static int push_jmp_history(struct bpf_verifier_env *env,
2058 struct bpf_verifier_state *cur)
2059{
2060 u32 cnt = cur->jmp_history_cnt;
2061 struct bpf_idx_pair *p;
2062
2063 cnt++;
2064 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2065 if (!p)
2066 return -ENOMEM;
2067 p[cnt - 1].idx = env->insn_idx;
2068 p[cnt - 1].prev_idx = env->prev_insn_idx;
2069 cur->jmp_history = p;
2070 cur->jmp_history_cnt = cnt;
2071 return 0;
2072}
2073
2074/* Backtrack one insn at a time. If idx is not at the top of recorded
2075 * history then previous instruction came from straight line execution.
2076 */
2077static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2078 u32 *history)
2079{
2080 u32 cnt = *history;
2081
2082 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2083 i = st->jmp_history[cnt - 1].prev_idx;
2084 (*history)--;
2085 } else {
2086 i--;
2087 }
2088 return i;
2089}
2090
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002091static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2092{
2093 const struct btf_type *func;
2094
2095 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2096 return NULL;
2097
2098 func = btf_type_by_id(btf_vmlinux, insn->imm);
2099 return btf_name_by_offset(btf_vmlinux, func->name_off);
2100}
2101
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002102/* For given verifier state backtrack_insn() is called from the last insn to
2103 * the first insn. Its purpose is to compute a bitmask of registers and
2104 * stack slots that needs precision in the parent verifier state.
2105 */
2106static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2107 u32 *reg_mask, u64 *stack_mask)
2108{
2109 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002110 .cb_call = disasm_kfunc_name,
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002111 .cb_print = verbose,
2112 .private_data = env,
2113 };
2114 struct bpf_insn *insn = env->prog->insnsi + idx;
2115 u8 class = BPF_CLASS(insn->code);
2116 u8 opcode = BPF_OP(insn->code);
2117 u8 mode = BPF_MODE(insn->code);
2118 u32 dreg = 1u << insn->dst_reg;
2119 u32 sreg = 1u << insn->src_reg;
2120 u32 spi;
2121
2122 if (insn->code == 0)
2123 return 0;
2124 if (env->log.level & BPF_LOG_LEVEL) {
2125 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2126 verbose(env, "%d: ", idx);
2127 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2128 }
2129
2130 if (class == BPF_ALU || class == BPF_ALU64) {
2131 if (!(*reg_mask & dreg))
2132 return 0;
2133 if (opcode == BPF_MOV) {
2134 if (BPF_SRC(insn->code) == BPF_X) {
2135 /* dreg = sreg
2136 * dreg needs precision after this insn
2137 * sreg needs precision before this insn
2138 */
2139 *reg_mask &= ~dreg;
2140 *reg_mask |= sreg;
2141 } else {
2142 /* dreg = K
2143 * dreg needs precision after this insn.
2144 * Corresponding register is already marked
2145 * as precise=true in this verifier state.
2146 * No further markings in parent are necessary
2147 */
2148 *reg_mask &= ~dreg;
2149 }
2150 } else {
2151 if (BPF_SRC(insn->code) == BPF_X) {
2152 /* dreg += sreg
2153 * both dreg and sreg need precision
2154 * before this insn
2155 */
2156 *reg_mask |= sreg;
2157 } /* else dreg += K
2158 * dreg still needs precision before this insn
2159 */
2160 }
2161 } else if (class == BPF_LDX) {
2162 if (!(*reg_mask & dreg))
2163 return 0;
2164 *reg_mask &= ~dreg;
2165
2166 /* scalars can only be spilled into stack w/o losing precision.
2167 * Load from any other memory can be zero extended.
2168 * The desire to keep that precision is already indicated
2169 * by 'precise' mark in corresponding register of this state.
2170 * No further tracking necessary.
2171 */
2172 if (insn->src_reg != BPF_REG_FP)
2173 return 0;
2174 if (BPF_SIZE(insn->code) != BPF_DW)
2175 return 0;
2176
2177 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2178 * that [fp - off] slot contains scalar that needs to be
2179 * tracked with precision
2180 */
2181 spi = (-insn->off - 1) / BPF_REG_SIZE;
2182 if (spi >= 64) {
2183 verbose(env, "BUG spi %d\n", spi);
2184 WARN_ONCE(1, "verifier backtracking bug");
2185 return -EFAULT;
2186 }
2187 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002188 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002189 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002190 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002191 * to access memory. It means backtracking
2192 * encountered a case of pointer subtraction.
2193 */
2194 return -ENOTSUPP;
2195 /* scalars can only be spilled into stack */
2196 if (insn->dst_reg != BPF_REG_FP)
2197 return 0;
2198 if (BPF_SIZE(insn->code) != BPF_DW)
2199 return 0;
2200 spi = (-insn->off - 1) / BPF_REG_SIZE;
2201 if (spi >= 64) {
2202 verbose(env, "BUG spi %d\n", spi);
2203 WARN_ONCE(1, "verifier backtracking bug");
2204 return -EFAULT;
2205 }
2206 if (!(*stack_mask & (1ull << spi)))
2207 return 0;
2208 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002209 if (class == BPF_STX)
2210 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002211 } else if (class == BPF_JMP || class == BPF_JMP32) {
2212 if (opcode == BPF_CALL) {
2213 if (insn->src_reg == BPF_PSEUDO_CALL)
2214 return -ENOTSUPP;
2215 /* regular helper call sets R0 */
2216 *reg_mask &= ~1;
2217 if (*reg_mask & 0x3f) {
2218 /* if backtracing was looking for registers R1-R5
2219 * they should have been found already.
2220 */
2221 verbose(env, "BUG regs %x\n", *reg_mask);
2222 WARN_ONCE(1, "verifier backtracking bug");
2223 return -EFAULT;
2224 }
2225 } else if (opcode == BPF_EXIT) {
2226 return -ENOTSUPP;
2227 }
2228 } else if (class == BPF_LD) {
2229 if (!(*reg_mask & dreg))
2230 return 0;
2231 *reg_mask &= ~dreg;
2232 /* It's ld_imm64 or ld_abs or ld_ind.
2233 * For ld_imm64 no further tracking of precision
2234 * into parent is necessary
2235 */
2236 if (mode == BPF_IND || mode == BPF_ABS)
2237 /* to be analyzed */
2238 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002239 }
2240 return 0;
2241}
2242
2243/* the scalar precision tracking algorithm:
2244 * . at the start all registers have precise=false.
2245 * . scalar ranges are tracked as normal through alu and jmp insns.
2246 * . once precise value of the scalar register is used in:
2247 * . ptr + scalar alu
2248 * . if (scalar cond K|scalar)
2249 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2250 * backtrack through the verifier states and mark all registers and
2251 * stack slots with spilled constants that these scalar regisers
2252 * should be precise.
2253 * . during state pruning two registers (or spilled stack slots)
2254 * are equivalent if both are not precise.
2255 *
2256 * Note the verifier cannot simply walk register parentage chain,
2257 * since many different registers and stack slots could have been
2258 * used to compute single precise scalar.
2259 *
2260 * The approach of starting with precise=true for all registers and then
2261 * backtrack to mark a register as not precise when the verifier detects
2262 * that program doesn't care about specific value (e.g., when helper
2263 * takes register as ARG_ANYTHING parameter) is not safe.
2264 *
2265 * It's ok to walk single parentage chain of the verifier states.
2266 * It's possible that this backtracking will go all the way till 1st insn.
2267 * All other branches will be explored for needing precision later.
2268 *
2269 * The backtracking needs to deal with cases like:
2270 * 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)
2271 * r9 -= r8
2272 * r5 = r9
2273 * if r5 > 0x79f goto pc+7
2274 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2275 * r5 += 1
2276 * ...
2277 * call bpf_perf_event_output#25
2278 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2279 *
2280 * and this case:
2281 * r6 = 1
2282 * call foo // uses callee's r6 inside to compute r0
2283 * r0 += r6
2284 * if r0 == 0 goto
2285 *
2286 * to track above reg_mask/stack_mask needs to be independent for each frame.
2287 *
2288 * Also if parent's curframe > frame where backtracking started,
2289 * the verifier need to mark registers in both frames, otherwise callees
2290 * may incorrectly prune callers. This is similar to
2291 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2292 *
2293 * For now backtracking falls back into conservative marking.
2294 */
2295static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2296 struct bpf_verifier_state *st)
2297{
2298 struct bpf_func_state *func;
2299 struct bpf_reg_state *reg;
2300 int i, j;
2301
2302 /* big hammer: mark all scalars precise in this path.
2303 * pop_stack may still get !precise scalars.
2304 */
2305 for (; st; st = st->parent)
2306 for (i = 0; i <= st->curframe; i++) {
2307 func = st->frame[i];
2308 for (j = 0; j < BPF_REG_FP; j++) {
2309 reg = &func->regs[j];
2310 if (reg->type != SCALAR_VALUE)
2311 continue;
2312 reg->precise = true;
2313 }
2314 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2315 if (func->stack[j].slot_type[0] != STACK_SPILL)
2316 continue;
2317 reg = &func->stack[j].spilled_ptr;
2318 if (reg->type != SCALAR_VALUE)
2319 continue;
2320 reg->precise = true;
2321 }
2322 }
2323}
2324
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002325static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2326 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002327{
2328 struct bpf_verifier_state *st = env->cur_state;
2329 int first_idx = st->first_insn_idx;
2330 int last_idx = env->insn_idx;
2331 struct bpf_func_state *func;
2332 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002333 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2334 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002335 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002336 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002337 int i, err;
2338
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002339 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002340 return 0;
2341
2342 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002343 if (regno >= 0) {
2344 reg = &func->regs[regno];
2345 if (reg->type != SCALAR_VALUE) {
2346 WARN_ONCE(1, "backtracing misuse");
2347 return -EFAULT;
2348 }
2349 if (!reg->precise)
2350 new_marks = true;
2351 else
2352 reg_mask = 0;
2353 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002354 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002355
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002356 while (spi >= 0) {
2357 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2358 stack_mask = 0;
2359 break;
2360 }
2361 reg = &func->stack[spi].spilled_ptr;
2362 if (reg->type != SCALAR_VALUE) {
2363 stack_mask = 0;
2364 break;
2365 }
2366 if (!reg->precise)
2367 new_marks = true;
2368 else
2369 stack_mask = 0;
2370 reg->precise = true;
2371 break;
2372 }
2373
2374 if (!new_marks)
2375 return 0;
2376 if (!reg_mask && !stack_mask)
2377 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002378 for (;;) {
2379 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002380 u32 history = st->jmp_history_cnt;
2381
2382 if (env->log.level & BPF_LOG_LEVEL)
2383 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2384 for (i = last_idx;;) {
2385 if (skip_first) {
2386 err = 0;
2387 skip_first = false;
2388 } else {
2389 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2390 }
2391 if (err == -ENOTSUPP) {
2392 mark_all_scalars_precise(env, st);
2393 return 0;
2394 } else if (err) {
2395 return err;
2396 }
2397 if (!reg_mask && !stack_mask)
2398 /* Found assignment(s) into tracked register in this state.
2399 * Since this state is already marked, just return.
2400 * Nothing to be tracked further in the parent state.
2401 */
2402 return 0;
2403 if (i == first_idx)
2404 break;
2405 i = get_prev_insn_idx(st, i, &history);
2406 if (i >= env->prog->len) {
2407 /* This can happen if backtracking reached insn 0
2408 * and there are still reg_mask or stack_mask
2409 * to backtrack.
2410 * It means the backtracking missed the spot where
2411 * particular register was initialized with a constant.
2412 */
2413 verbose(env, "BUG backtracking idx %d\n", i);
2414 WARN_ONCE(1, "verifier backtracking bug");
2415 return -EFAULT;
2416 }
2417 }
2418 st = st->parent;
2419 if (!st)
2420 break;
2421
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002422 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002423 func = st->frame[st->curframe];
2424 bitmap_from_u64(mask, reg_mask);
2425 for_each_set_bit(i, mask, 32) {
2426 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002427 if (reg->type != SCALAR_VALUE) {
2428 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002429 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002430 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002431 if (!reg->precise)
2432 new_marks = true;
2433 reg->precise = true;
2434 }
2435
2436 bitmap_from_u64(mask, stack_mask);
2437 for_each_set_bit(i, mask, 64) {
2438 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002439 /* the sequence of instructions:
2440 * 2: (bf) r3 = r10
2441 * 3: (7b) *(u64 *)(r3 -8) = r0
2442 * 4: (79) r4 = *(u64 *)(r10 -8)
2443 * doesn't contain jmps. It's backtracked
2444 * as a single block.
2445 * During backtracking insn 3 is not recognized as
2446 * stack access, so at the end of backtracking
2447 * stack slot fp-8 is still marked in stack_mask.
2448 * However the parent state may not have accessed
2449 * fp-8 and it's "unallocated" stack space.
2450 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002451 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002452 mark_all_scalars_precise(env, st);
2453 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002454 }
2455
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002456 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2457 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002458 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002459 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002460 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002461 if (reg->type != SCALAR_VALUE) {
2462 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002463 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002464 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002465 if (!reg->precise)
2466 new_marks = true;
2467 reg->precise = true;
2468 }
2469 if (env->log.level & BPF_LOG_LEVEL) {
2470 print_verifier_state(env, func);
2471 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2472 new_marks ? "didn't have" : "already had",
2473 reg_mask, stack_mask);
2474 }
2475
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002476 if (!reg_mask && !stack_mask)
2477 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002478 if (!new_marks)
2479 break;
2480
2481 last_idx = st->last_insn_idx;
2482 first_idx = st->first_insn_idx;
2483 }
2484 return 0;
2485}
2486
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002487static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2488{
2489 return __mark_chain_precision(env, regno, -1);
2490}
2491
2492static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2493{
2494 return __mark_chain_precision(env, -1, spi);
2495}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002496
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002497static bool is_spillable_regtype(enum bpf_reg_type type)
2498{
2499 switch (type) {
2500 case PTR_TO_MAP_VALUE:
2501 case PTR_TO_MAP_VALUE_OR_NULL:
2502 case PTR_TO_STACK:
2503 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002504 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002505 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002506 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002507 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002508 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002509 case PTR_TO_SOCKET:
2510 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002511 case PTR_TO_SOCK_COMMON:
2512 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002513 case PTR_TO_TCP_SOCK:
2514 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002515 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002516 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002517 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002518 case PTR_TO_RDONLY_BUF:
2519 case PTR_TO_RDONLY_BUF_OR_NULL:
2520 case PTR_TO_RDWR_BUF:
2521 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002522 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002523 case PTR_TO_MEM:
2524 case PTR_TO_MEM_OR_NULL:
Yonghong Song69c087b2021-02-26 12:49:25 -08002525 case PTR_TO_FUNC:
2526 case PTR_TO_MAP_KEY:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002527 return true;
2528 default:
2529 return false;
2530 }
2531}
2532
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002533/* Does this register contain a constant zero? */
2534static bool register_is_null(struct bpf_reg_state *reg)
2535{
2536 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2537}
2538
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002539static bool register_is_const(struct bpf_reg_state *reg)
2540{
2541 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2542}
2543
Yonghong Song5689d492020-10-08 18:12:38 -07002544static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2545{
2546 return tnum_is_unknown(reg->var_off) &&
2547 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2548 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2549 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2550 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2551}
2552
2553static bool register_is_bounded(struct bpf_reg_state *reg)
2554{
2555 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2556}
2557
Jann Horn6e7e63c2020-04-17 02:00:06 +02002558static bool __is_pointer_value(bool allow_ptr_leaks,
2559 const struct bpf_reg_state *reg)
2560{
2561 if (allow_ptr_leaks)
2562 return false;
2563
2564 return reg->type != SCALAR_VALUE;
2565}
2566
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002567static void save_register_state(struct bpf_func_state *state,
2568 int spi, struct bpf_reg_state *reg)
2569{
2570 int i;
2571
2572 state->stack[spi].spilled_ptr = *reg;
2573 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2574
2575 for (i = 0; i < BPF_REG_SIZE; i++)
2576 state->stack[spi].slot_type[i] = STACK_SPILL;
2577}
2578
Andrei Matei01f810a2021-02-06 20:10:24 -05002579/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002580 * stack boundary and alignment are checked in check_mem_access()
2581 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002582static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2583 /* stack frame we're writing to */
2584 struct bpf_func_state *state,
2585 int off, int size, int value_regno,
2586 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002587{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002588 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002589 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002590 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002591 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002592
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002593 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002594 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002595 if (err)
2596 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002597 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2598 * so it's aligned access and [off, off + size) are within stack limits
2599 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002600 if (!env->allow_ptr_leaks &&
2601 state->stack[spi].slot_type[0] == STACK_SPILL &&
2602 size != BPF_REG_SIZE) {
2603 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2604 return -EACCES;
2605 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002606
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002607 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002608 if (value_regno >= 0)
2609 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002610
Yonghong Song5689d492020-10-08 18:12:38 -07002611 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002612 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002613 if (dst_reg != BPF_REG_FP) {
2614 /* The backtracking logic can only recognize explicit
2615 * stack slot address like [fp - 8]. Other spill of
2616 * scalar via different register has to be conervative.
2617 * Backtrack from here and mark all registers as precise
2618 * that contributed into 'reg' being a constant.
2619 */
2620 err = mark_chain_precision(env, value_regno);
2621 if (err)
2622 return err;
2623 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002624 save_register_state(state, spi, reg);
2625 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002626 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002627 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002628 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002629 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002630 return -EACCES;
2631 }
2632
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002633 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002634 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2635 return -EINVAL;
2636 }
2637
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002638 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002639 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002640
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002641 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2642 register_is_const(&state->stack[spi].spilled_ptr))
2643 sanitize = true;
2644 for (i = 0; i < BPF_REG_SIZE; i++)
2645 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2646 sanitize = true;
2647 break;
2648 }
2649 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002650 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2651 int soff = (-spi - 1) * BPF_REG_SIZE;
2652
2653 /* detected reuse of integer stack slot with a pointer
2654 * which means either llvm is reusing stack slot or
2655 * an attacker is trying to exploit CVE-2018-3639
2656 * (speculative store bypass)
2657 * Have to sanitize that slot with preemptive
2658 * store of zero.
2659 */
2660 if (*poff && *poff != soff) {
2661 /* disallow programs where single insn stores
2662 * into two different stack slots, since verifier
2663 * cannot sanitize them
2664 */
2665 verbose(env,
2666 "insn %d cannot access two stack slots fp%d and fp%d",
2667 insn_idx, *poff, soff);
2668 return -EINVAL;
2669 }
2670 *poff = soff;
2671 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002672 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002673 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002674 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002675 u8 type = STACK_MISC;
2676
Edward Cree679c7822018-08-22 20:02:19 +01002677 /* regular write of data into stack destroys any spilled ptr */
2678 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002679 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2680 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2681 for (i = 0; i < BPF_REG_SIZE; i++)
2682 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002683
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002684 /* only mark the slot as written if all 8 bytes were written
2685 * otherwise read propagation may incorrectly stop too soon
2686 * when stack slots are partially written.
2687 * This heuristic means that read propagation will be
2688 * conservative, since it will add reg_live_read marks
2689 * to stack slots all the way to first state when programs
2690 * writes+reads less than 8 bytes
2691 */
2692 if (size == BPF_REG_SIZE)
2693 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2694
2695 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002696 if (reg && register_is_null(reg)) {
2697 /* backtracking doesn't work for STACK_ZERO yet. */
2698 err = mark_chain_precision(env, value_regno);
2699 if (err)
2700 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002701 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002702 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002703
Jiong Wang0bae2d42018-12-15 03:34:40 -05002704 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002705 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002706 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002707 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002708 }
2709 return 0;
2710}
2711
Andrei Matei01f810a2021-02-06 20:10:24 -05002712/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2713 * known to contain a variable offset.
2714 * This function checks whether the write is permitted and conservatively
2715 * tracks the effects of the write, considering that each stack slot in the
2716 * dynamic range is potentially written to.
2717 *
2718 * 'off' includes 'regno->off'.
2719 * 'value_regno' can be -1, meaning that an unknown value is being written to
2720 * the stack.
2721 *
2722 * Spilled pointers in range are not marked as written because we don't know
2723 * what's going to be actually written. This means that read propagation for
2724 * future reads cannot be terminated by this write.
2725 *
2726 * For privileged programs, uninitialized stack slots are considered
2727 * initialized by this write (even though we don't know exactly what offsets
2728 * are going to be written to). The idea is that we don't want the verifier to
2729 * reject future reads that access slots written to through variable offsets.
2730 */
2731static int check_stack_write_var_off(struct bpf_verifier_env *env,
2732 /* func where register points to */
2733 struct bpf_func_state *state,
2734 int ptr_regno, int off, int size,
2735 int value_regno, int insn_idx)
2736{
2737 struct bpf_func_state *cur; /* state of the current function */
2738 int min_off, max_off;
2739 int i, err;
2740 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2741 bool writing_zero = false;
2742 /* set if the fact that we're writing a zero is used to let any
2743 * stack slots remain STACK_ZERO
2744 */
2745 bool zero_used = false;
2746
2747 cur = env->cur_state->frame[env->cur_state->curframe];
2748 ptr_reg = &cur->regs[ptr_regno];
2749 min_off = ptr_reg->smin_value + off;
2750 max_off = ptr_reg->smax_value + off + size;
2751 if (value_regno >= 0)
2752 value_reg = &cur->regs[value_regno];
2753 if (value_reg && register_is_null(value_reg))
2754 writing_zero = true;
2755
2756 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2757 state->acquired_refs, true);
2758 if (err)
2759 return err;
2760
2761
2762 /* Variable offset writes destroy any spilled pointers in range. */
2763 for (i = min_off; i < max_off; i++) {
2764 u8 new_type, *stype;
2765 int slot, spi;
2766
2767 slot = -i - 1;
2768 spi = slot / BPF_REG_SIZE;
2769 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2770
2771 if (!env->allow_ptr_leaks
2772 && *stype != NOT_INIT
2773 && *stype != SCALAR_VALUE) {
2774 /* Reject the write if there's are spilled pointers in
2775 * range. If we didn't reject here, the ptr status
2776 * would be erased below (even though not all slots are
2777 * actually overwritten), possibly opening the door to
2778 * leaks.
2779 */
2780 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2781 insn_idx, i);
2782 return -EINVAL;
2783 }
2784
2785 /* Erase all spilled pointers. */
2786 state->stack[spi].spilled_ptr.type = NOT_INIT;
2787
2788 /* Update the slot type. */
2789 new_type = STACK_MISC;
2790 if (writing_zero && *stype == STACK_ZERO) {
2791 new_type = STACK_ZERO;
2792 zero_used = true;
2793 }
2794 /* If the slot is STACK_INVALID, we check whether it's OK to
2795 * pretend that it will be initialized by this write. The slot
2796 * might not actually be written to, and so if we mark it as
2797 * initialized future reads might leak uninitialized memory.
2798 * For privileged programs, we will accept such reads to slots
2799 * that may or may not be written because, if we're reject
2800 * them, the error would be too confusing.
2801 */
2802 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2803 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2804 insn_idx, i);
2805 return -EINVAL;
2806 }
2807 *stype = new_type;
2808 }
2809 if (zero_used) {
2810 /* backtracking doesn't work for STACK_ZERO yet. */
2811 err = mark_chain_precision(env, value_regno);
2812 if (err)
2813 return err;
2814 }
2815 return 0;
2816}
2817
2818/* When register 'dst_regno' is assigned some values from stack[min_off,
2819 * max_off), we set the register's type according to the types of the
2820 * respective stack slots. If all the stack values are known to be zeros, then
2821 * so is the destination reg. Otherwise, the register is considered to be
2822 * SCALAR. This function does not deal with register filling; the caller must
2823 * ensure that all spilled registers in the stack range have been marked as
2824 * read.
2825 */
2826static void mark_reg_stack_read(struct bpf_verifier_env *env,
2827 /* func where src register points to */
2828 struct bpf_func_state *ptr_state,
2829 int min_off, int max_off, int dst_regno)
2830{
2831 struct bpf_verifier_state *vstate = env->cur_state;
2832 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2833 int i, slot, spi;
2834 u8 *stype;
2835 int zeros = 0;
2836
2837 for (i = min_off; i < max_off; i++) {
2838 slot = -i - 1;
2839 spi = slot / BPF_REG_SIZE;
2840 stype = ptr_state->stack[spi].slot_type;
2841 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2842 break;
2843 zeros++;
2844 }
2845 if (zeros == max_off - min_off) {
2846 /* any access_size read into register is zero extended,
2847 * so the whole register == const_zero
2848 */
2849 __mark_reg_const_zero(&state->regs[dst_regno]);
2850 /* backtracking doesn't support STACK_ZERO yet,
2851 * so mark it precise here, so that later
2852 * backtracking can stop here.
2853 * Backtracking may not need this if this register
2854 * doesn't participate in pointer adjustment.
2855 * Forward propagation of precise flag is not
2856 * necessary either. This mark is only to stop
2857 * backtracking. Any register that contributed
2858 * to const 0 was marked precise before spill.
2859 */
2860 state->regs[dst_regno].precise = true;
2861 } else {
2862 /* have read misc data from the stack */
2863 mark_reg_unknown(env, state->regs, dst_regno);
2864 }
2865 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2866}
2867
2868/* Read the stack at 'off' and put the results into the register indicated by
2869 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2870 * spilled reg.
2871 *
2872 * 'dst_regno' can be -1, meaning that the read value is not going to a
2873 * register.
2874 *
2875 * The access is assumed to be within the current stack bounds.
2876 */
2877static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2878 /* func where src register points to */
2879 struct bpf_func_state *reg_state,
2880 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002881{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002882 struct bpf_verifier_state *vstate = env->cur_state;
2883 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002884 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002885 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002886 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002887
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002888 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002889 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002890
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002891 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002892 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002893 if (reg->type != SCALAR_VALUE) {
2894 verbose_linfo(env, env->insn_idx, "; ");
2895 verbose(env, "invalid size of register fill\n");
2896 return -EACCES;
2897 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002898 if (dst_regno >= 0) {
2899 mark_reg_unknown(env, state->regs, dst_regno);
2900 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002901 }
2902 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2903 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002904 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002905 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002906 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002907 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002908 return -EACCES;
2909 }
2910 }
2911
Andrei Matei01f810a2021-02-06 20:10:24 -05002912 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002913 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05002914 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002915 /* mark reg as written since spilled pointer state likely
2916 * has its liveness marks cleared by is_state_visited()
2917 * which resets stack/reg liveness for state transitions
2918 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002919 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002920 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002921 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02002922 * it is acceptable to use this value as a SCALAR_VALUE
2923 * (e.g. for XADD).
2924 * We must not allow unprivileged callers to do that
2925 * with spilled pointers.
2926 */
2927 verbose(env, "leaking pointer from stack off %d\n",
2928 off);
2929 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002930 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002931 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002932 } else {
Andrei Matei01f810a2021-02-06 20:10:24 -05002933 u8 type;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002934
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002935 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002936 type = stype[(slot - i) % BPF_REG_SIZE];
2937 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002938 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05002939 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002940 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002941 verbose(env, "invalid read from stack off %d+%d size %d\n",
2942 off, i, size);
2943 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002944 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002945 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05002946 if (dst_regno >= 0)
2947 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002948 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002949 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002950}
2951
Andrei Matei01f810a2021-02-06 20:10:24 -05002952enum stack_access_src {
2953 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2954 ACCESS_HELPER = 2, /* the access is performed by a helper */
2955};
2956
2957static int check_stack_range_initialized(struct bpf_verifier_env *env,
2958 int regno, int off, int access_size,
2959 bool zero_size_allowed,
2960 enum stack_access_src type,
2961 struct bpf_call_arg_meta *meta);
2962
2963static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002964{
Andrei Matei01f810a2021-02-06 20:10:24 -05002965 return cur_regs(env) + regno;
2966}
2967
2968/* Read the stack at 'ptr_regno + off' and put the result into the register
2969 * 'dst_regno'.
2970 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2971 * but not its variable offset.
2972 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2973 *
2974 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2975 * filling registers (i.e. reads of spilled register cannot be detected when
2976 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2977 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2978 * offset; for a fixed offset check_stack_read_fixed_off should be used
2979 * instead.
2980 */
2981static int check_stack_read_var_off(struct bpf_verifier_env *env,
2982 int ptr_regno, int off, int size, int dst_regno)
2983{
2984 /* The state of the source register. */
2985 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2986 struct bpf_func_state *ptr_state = func(env, reg);
2987 int err;
2988 int min_off, max_off;
2989
2990 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002991 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002992 err = check_stack_range_initialized(env, ptr_regno, off, size,
2993 false, ACCESS_DIRECT, NULL);
2994 if (err)
2995 return err;
2996
2997 min_off = reg->smin_value + off;
2998 max_off = reg->smax_value + off;
2999 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3000 return 0;
3001}
3002
3003/* check_stack_read dispatches to check_stack_read_fixed_off or
3004 * check_stack_read_var_off.
3005 *
3006 * The caller must ensure that the offset falls within the allocated stack
3007 * bounds.
3008 *
3009 * 'dst_regno' is a register which will receive the value from the stack. It
3010 * can be -1, meaning that the read value is not going to a register.
3011 */
3012static int check_stack_read(struct bpf_verifier_env *env,
3013 int ptr_regno, int off, int size,
3014 int dst_regno)
3015{
3016 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3017 struct bpf_func_state *state = func(env, reg);
3018 int err;
3019 /* Some accesses are only permitted with a static offset. */
3020 bool var_off = !tnum_is_const(reg->var_off);
3021
3022 /* The offset is required to be static when reads don't go to a
3023 * register, in order to not leak pointers (see
3024 * check_stack_read_fixed_off).
3025 */
3026 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003027 char tn_buf[48];
3028
3029 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05003030 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003031 tn_buf, off, size);
3032 return -EACCES;
3033 }
Andrei Matei01f810a2021-02-06 20:10:24 -05003034 /* Variable offset is prohibited for unprivileged mode for simplicity
3035 * since it requires corresponding support in Spectre masking for stack
3036 * ALU. See also retrieve_ptr_limit().
3037 */
3038 if (!env->bypass_spec_v1 && var_off) {
3039 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003040
Andrei Matei01f810a2021-02-06 20:10:24 -05003041 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3042 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3043 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003044 return -EACCES;
3045 }
3046
Andrei Matei01f810a2021-02-06 20:10:24 -05003047 if (!var_off) {
3048 off += reg->var_off.value;
3049 err = check_stack_read_fixed_off(env, state, off, size,
3050 dst_regno);
3051 } else {
3052 /* Variable offset stack reads need more conservative handling
3053 * than fixed offset ones. Note that dst_regno >= 0 on this
3054 * branch.
3055 */
3056 err = check_stack_read_var_off(env, ptr_regno, off, size,
3057 dst_regno);
3058 }
3059 return err;
3060}
3061
3062
3063/* check_stack_write dispatches to check_stack_write_fixed_off or
3064 * check_stack_write_var_off.
3065 *
3066 * 'ptr_regno' is the register used as a pointer into the stack.
3067 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3068 * 'value_regno' is the register whose value we're writing to the stack. It can
3069 * be -1, meaning that we're not writing from a register.
3070 *
3071 * The caller must ensure that the offset falls within the maximum stack size.
3072 */
3073static int check_stack_write(struct bpf_verifier_env *env,
3074 int ptr_regno, int off, int size,
3075 int value_regno, int insn_idx)
3076{
3077 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3078 struct bpf_func_state *state = func(env, reg);
3079 int err;
3080
3081 if (tnum_is_const(reg->var_off)) {
3082 off += reg->var_off.value;
3083 err = check_stack_write_fixed_off(env, state, off, size,
3084 value_regno, insn_idx);
3085 } else {
3086 /* Variable offset stack reads need more conservative handling
3087 * than fixed offset ones.
3088 */
3089 err = check_stack_write_var_off(env, state,
3090 ptr_regno, off, size,
3091 value_regno, insn_idx);
3092 }
3093 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003094}
3095
Daniel Borkmann591fe982019-04-09 23:20:05 +02003096static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3097 int off, int size, enum bpf_access_type type)
3098{
3099 struct bpf_reg_state *regs = cur_regs(env);
3100 struct bpf_map *map = regs[regno].map_ptr;
3101 u32 cap = bpf_map_flags_to_cap(map);
3102
3103 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3104 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3105 map->value_size, off, size);
3106 return -EACCES;
3107 }
3108
3109 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3110 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3111 map->value_size, off, size);
3112 return -EACCES;
3113 }
3114
3115 return 0;
3116}
3117
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003118/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3119static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3120 int off, int size, u32 mem_size,
3121 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003122{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003123 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3124 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003125
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003126 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3127 return 0;
3128
3129 reg = &cur_regs(env)[regno];
3130 switch (reg->type) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003131 case PTR_TO_MAP_KEY:
3132 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3133 mem_size, off, size);
3134 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003135 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003136 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003137 mem_size, off, size);
3138 break;
3139 case PTR_TO_PACKET:
3140 case PTR_TO_PACKET_META:
3141 case PTR_TO_PACKET_END:
3142 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3143 off, size, regno, reg->id, off, mem_size);
3144 break;
3145 case PTR_TO_MEM:
3146 default:
3147 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3148 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003149 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003150
3151 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003152}
3153
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003154/* check read/write into a memory region with possible variable offset */
3155static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3156 int off, int size, u32 mem_size,
3157 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003158{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003159 struct bpf_verifier_state *vstate = env->cur_state;
3160 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003161 struct bpf_reg_state *reg = &state->regs[regno];
3162 int err;
3163
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003164 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01003165 * need to try adding each of min_value and max_value to off
3166 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003167 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07003168 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003169 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01003170
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003171 /* The minimum value is only important with signed
3172 * comparisons where we can't assume the floor of a
3173 * value is 0. If we are using signed variables for our
3174 * index'es we need to make sure that whatever we use
3175 * will have a set floor within our range.
3176 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01003177 if (reg->smin_value < 0 &&
3178 (reg->smin_value == S64_MIN ||
3179 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3180 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003181 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003182 regno);
3183 return -EACCES;
3184 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003185 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3186 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003187 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003188 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003189 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003190 return err;
3191 }
3192
Edward Creeb03c9f92017-08-07 15:26:36 +01003193 /* If we haven't set a max value then we need to bail since we can't be
3194 * sure we won't do bad things.
3195 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003196 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003197 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003198 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003199 regno);
3200 return -EACCES;
3201 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003202 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3203 mem_size, zero_size_allowed);
3204 if (err) {
3205 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003206 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003207 return err;
3208 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003209
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003210 return 0;
3211}
3212
3213/* check read/write into a map element with possible variable offset */
3214static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3215 int off, int size, bool zero_size_allowed)
3216{
3217 struct bpf_verifier_state *vstate = env->cur_state;
3218 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3219 struct bpf_reg_state *reg = &state->regs[regno];
3220 struct bpf_map *map = reg->map_ptr;
3221 int err;
3222
3223 err = check_mem_region_access(env, regno, off, size, map->value_size,
3224 zero_size_allowed);
3225 if (err)
3226 return err;
3227
3228 if (map_value_has_spin_lock(map)) {
3229 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003230
3231 /* if any part of struct bpf_spin_lock can be touched by
3232 * load/store reject this program.
3233 * To check that [x1, x2) overlaps with [y1, y2)
3234 * it is sufficient to check x1 < y2 && y1 < x2.
3235 */
3236 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3237 lock < reg->umax_value + off + size) {
3238 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3239 return -EACCES;
3240 }
3241 }
Edward Creef1174f72017-08-07 15:26:19 +01003242 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003243}
3244
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003245#define MAX_PACKET_OFF 0xffff
3246
Udip Pant7e407812020-08-25 16:20:00 -07003247static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3248{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02003249 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07003250}
3251
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003252static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003253 const struct bpf_call_arg_meta *meta,
3254 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003255{
Udip Pant7e407812020-08-25 16:20:00 -07003256 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3257
3258 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003259 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003260 case BPF_PROG_TYPE_LWT_IN:
3261 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003262 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003263 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003264 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003265 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003266 if (t == BPF_WRITE)
3267 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003268 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003269
3270 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003271 case BPF_PROG_TYPE_SCHED_CLS:
3272 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003273 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003274 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003275 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003276 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003277 if (meta)
3278 return meta->pkt_access;
3279
3280 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003281 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003282
3283 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3284 if (t == BPF_WRITE)
3285 env->seen_direct_write = true;
3286
3287 return true;
3288
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003289 default:
3290 return false;
3291 }
3292}
3293
Edward Creef1174f72017-08-07 15:26:19 +01003294static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003295 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003296{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003297 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003298 struct bpf_reg_state *reg = &regs[regno];
3299 int err;
3300
3301 /* We may have added a variable offset to the packet pointer; but any
3302 * reg->range we have comes after that. We are only checking the fixed
3303 * offset.
3304 */
3305
3306 /* We don't allow negative numbers, because we aren't tracking enough
3307 * detail to prove they're safe.
3308 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003309 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003310 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
Edward Creef1174f72017-08-07 15:26:19 +01003311 regno);
3312 return -EACCES;
3313 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003314
3315 err = reg->range < 0 ? -EINVAL :
3316 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003317 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003318 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003319 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003320 return err;
3321 }
Jiong Wange6478152018-11-08 04:08:42 -05003322
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003323 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003324 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3325 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003326 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003327 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3328 */
3329 env->prog->aux->max_pkt_offset =
3330 max_t(u32, env->prog->aux->max_pkt_offset,
3331 off + reg->umax_value + size - 1);
3332
Edward Creef1174f72017-08-07 15:26:19 +01003333 return err;
3334}
3335
3336/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003337static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003338 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003339 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003340{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003341 struct bpf_insn_access_aux info = {
3342 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003343 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003344 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003345
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003346 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003347 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003348 /* A non zero info.ctx_field_size indicates that this field is a
3349 * candidate for later verifier transformation to load the whole
3350 * field and then apply a mask when accessed with a narrower
3351 * access than actual ctx access size. A zero info.ctx_field_size
3352 * will only allow for whole field access and rejects any other
3353 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003354 */
Yonghong Song23994632017-06-22 15:07:39 -07003355 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003356
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003357 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3358 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003359 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003360 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003361 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003362 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003363 /* remember the offset of last byte accessed in ctx */
3364 if (env->prog->aux->max_ctx_offset < off + size)
3365 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003366 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003367 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003368
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003369 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003370 return -EACCES;
3371}
3372
Petar Penkovd58e4682018-09-14 07:46:18 -07003373static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3374 int size)
3375{
3376 if (size < 0 || off < 0 ||
3377 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3378 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3379 off, size);
3380 return -EACCES;
3381 }
3382 return 0;
3383}
3384
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003385static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3386 u32 regno, int off, int size,
3387 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003388{
3389 struct bpf_reg_state *regs = cur_regs(env);
3390 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003391 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003392 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003393
3394 if (reg->smin_value < 0) {
3395 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3396 regno);
3397 return -EACCES;
3398 }
3399
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003400 switch (reg->type) {
3401 case PTR_TO_SOCK_COMMON:
3402 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3403 break;
3404 case PTR_TO_SOCKET:
3405 valid = bpf_sock_is_valid_access(off, size, t, &info);
3406 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003407 case PTR_TO_TCP_SOCK:
3408 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3409 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003410 case PTR_TO_XDP_SOCK:
3411 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3412 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003413 default:
3414 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003415 }
3416
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003417
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003418 if (valid) {
3419 env->insn_aux_data[insn_idx].ctx_field_size =
3420 info.ctx_field_size;
3421 return 0;
3422 }
3423
3424 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3425 regno, reg_type_str[reg->type], off, size);
3426
3427 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003428}
3429
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003430static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3431{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003432 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003433}
3434
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003435static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3436{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003437 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003438
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003439 return reg->type == PTR_TO_CTX;
3440}
3441
3442static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3443{
3444 const struct bpf_reg_state *reg = reg_state(env, regno);
3445
3446 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003447}
3448
Daniel Borkmannca369602018-02-23 22:29:05 +01003449static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3450{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003451 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003452
3453 return type_is_pkt_pointer(reg->type);
3454}
3455
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003456static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3457{
3458 const struct bpf_reg_state *reg = reg_state(env, regno);
3459
3460 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3461 return reg->type == PTR_TO_FLOW_KEYS;
3462}
3463
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003464static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3465 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003466 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003467{
Edward Creef1174f72017-08-07 15:26:19 +01003468 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003469 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003470
3471 /* Byte size accesses are always allowed. */
3472 if (!strict || size == 1)
3473 return 0;
3474
David S. Millere4eda882017-05-22 12:27:07 -04003475 /* For platforms that do not have a Kconfig enabling
3476 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3477 * NET_IP_ALIGN is universally set to '2'. And on platforms
3478 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3479 * to this code only in strict mode where we want to emulate
3480 * the NET_IP_ALIGN==2 checking. Therefore use an
3481 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003482 */
David S. Millere4eda882017-05-22 12:27:07 -04003483 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003484
3485 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3486 if (!tnum_is_aligned(reg_off, size)) {
3487 char tn_buf[48];
3488
3489 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003490 verbose(env,
3491 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003492 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003493 return -EACCES;
3494 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003495
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003496 return 0;
3497}
3498
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003499static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3500 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003501 const char *pointer_desc,
3502 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003503{
Edward Creef1174f72017-08-07 15:26:19 +01003504 struct tnum reg_off;
3505
3506 /* Byte size accesses are always allowed. */
3507 if (!strict || size == 1)
3508 return 0;
3509
3510 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3511 if (!tnum_is_aligned(reg_off, size)) {
3512 char tn_buf[48];
3513
3514 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003515 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003516 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003517 return -EACCES;
3518 }
3519
3520 return 0;
3521}
3522
David S. Millere07b98d2017-05-10 11:38:07 -07003523static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003524 const struct bpf_reg_state *reg, int off,
3525 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003526{
Daniel Borkmannca369602018-02-23 22:29:05 +01003527 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003528 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003529
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003530 switch (reg->type) {
3531 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003532 case PTR_TO_PACKET_META:
3533 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3534 * right in front, treat it the very same way.
3535 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003536 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003537 case PTR_TO_FLOW_KEYS:
3538 pointer_desc = "flow keys ";
3539 break;
Yonghong Song69c087b2021-02-26 12:49:25 -08003540 case PTR_TO_MAP_KEY:
3541 pointer_desc = "key ";
3542 break;
Edward Creef1174f72017-08-07 15:26:19 +01003543 case PTR_TO_MAP_VALUE:
3544 pointer_desc = "value ";
3545 break;
3546 case PTR_TO_CTX:
3547 pointer_desc = "context ";
3548 break;
3549 case PTR_TO_STACK:
3550 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003551 /* The stack spill tracking logic in check_stack_write_fixed_off()
3552 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003553 * aligned.
3554 */
3555 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003556 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003557 case PTR_TO_SOCKET:
3558 pointer_desc = "sock ";
3559 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003560 case PTR_TO_SOCK_COMMON:
3561 pointer_desc = "sock_common ";
3562 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003563 case PTR_TO_TCP_SOCK:
3564 pointer_desc = "tcp_sock ";
3565 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003566 case PTR_TO_XDP_SOCK:
3567 pointer_desc = "xdp_sock ";
3568 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003569 default:
Edward Creef1174f72017-08-07 15:26:19 +01003570 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003571 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003572 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3573 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003574}
3575
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003576static int update_stack_depth(struct bpf_verifier_env *env,
3577 const struct bpf_func_state *func,
3578 int off)
3579{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003580 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003581
3582 if (stack >= -off)
3583 return 0;
3584
3585 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003586 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003587 return 0;
3588}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003589
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003590/* starting from main bpf function walk all instructions of the function
3591 * and recursively walk all callees that given function can call.
3592 * Ignore jump and exit insns.
3593 * Since recursion is prevented by check_cfg() this algorithm
3594 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3595 */
3596static int check_max_stack_depth(struct bpf_verifier_env *env)
3597{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003598 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3599 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003600 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003601 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003602 int ret_insn[MAX_CALL_FRAMES];
3603 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003604 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003605
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003606process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003607 /* protect against potential stack overflow that might happen when
3608 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3609 * depth for such case down to 256 so that the worst case scenario
3610 * would result in 8k stack size (32 which is tailcall limit * 256 =
3611 * 8k).
3612 *
3613 * To get the idea what might happen, see an example:
3614 * func1 -> sub rsp, 128
3615 * subfunc1 -> sub rsp, 256
3616 * tailcall1 -> add rsp, 256
3617 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3618 * subfunc2 -> sub rsp, 64
3619 * subfunc22 -> sub rsp, 128
3620 * tailcall2 -> add rsp, 128
3621 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3622 *
3623 * tailcall will unwind the current stack frame but it will not get rid
3624 * of caller's stack as shown on the example above.
3625 */
3626 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3627 verbose(env,
3628 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3629 depth);
3630 return -EACCES;
3631 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003632 /* round up to 32-bytes, since this is granularity
3633 * of interpreter stack size
3634 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003635 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003636 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003637 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003638 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003639 return -EACCES;
3640 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003641continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003642 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003643 for (; i < subprog_end; i++) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003644 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003645 continue;
3646 /* remember insn and function to return to */
3647 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003648 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003649
3650 /* find the callee */
3651 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003652 idx = find_subprog(env, i);
3653 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003654 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3655 i);
3656 return -EFAULT;
3657 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003658
3659 if (subprog[idx].has_tail_call)
3660 tail_call_reachable = true;
3661
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003662 frame++;
3663 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003664 verbose(env, "the call stack of %d frames is too deep !\n",
3665 frame);
3666 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003667 }
3668 goto process_func;
3669 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003670 /* if tail call got detected across bpf2bpf calls then mark each of the
3671 * currently present subprog frames as tail call reachable subprogs;
3672 * this info will be utilized by JIT so that we will be preserving the
3673 * tail call counter throughout bpf2bpf calls combined with tailcalls
3674 */
3675 if (tail_call_reachable)
3676 for (j = 0; j < frame; j++)
3677 subprog[ret_prog[j]].tail_call_reachable = true;
3678
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003679 /* end of for() loop means the last insn of the 'subprog'
3680 * was reached. Doesn't matter whether it was JA or EXIT
3681 */
3682 if (frame == 0)
3683 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003684 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003685 frame--;
3686 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003687 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003688 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003689}
3690
David S. Miller19d28fb2018-01-11 21:27:54 -05003691#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003692static int get_callee_stack_depth(struct bpf_verifier_env *env,
3693 const struct bpf_insn *insn, int idx)
3694{
3695 int start = idx + insn->imm + 1, subprog;
3696
3697 subprog = find_subprog(env, start);
3698 if (subprog < 0) {
3699 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3700 start);
3701 return -EFAULT;
3702 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003703 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003704}
David S. Miller19d28fb2018-01-11 21:27:54 -05003705#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003706
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003707int check_ctx_reg(struct bpf_verifier_env *env,
3708 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003709{
3710 /* Access to ctx or passing it to a helper is only allowed in
3711 * its original, unmodified form.
3712 */
3713
3714 if (reg->off) {
3715 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3716 regno, reg->off);
3717 return -EACCES;
3718 }
3719
3720 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3721 char tn_buf[48];
3722
3723 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3724 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3725 return -EACCES;
3726 }
3727
3728 return 0;
3729}
3730
Yonghong Songafbf21d2020-07-23 11:41:11 -07003731static int __check_buffer_access(struct bpf_verifier_env *env,
3732 const char *buf_info,
3733 const struct bpf_reg_state *reg,
3734 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003735{
3736 if (off < 0) {
3737 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003738 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003739 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003740 return -EACCES;
3741 }
3742 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3743 char tn_buf[48];
3744
3745 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3746 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003747 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003748 regno, off, tn_buf);
3749 return -EACCES;
3750 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003751
3752 return 0;
3753}
3754
3755static int check_tp_buffer_access(struct bpf_verifier_env *env,
3756 const struct bpf_reg_state *reg,
3757 int regno, int off, int size)
3758{
3759 int err;
3760
3761 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3762 if (err)
3763 return err;
3764
Matt Mullins9df1c282019-04-26 11:49:47 -07003765 if (off + size > env->prog->aux->max_tp_access)
3766 env->prog->aux->max_tp_access = off + size;
3767
3768 return 0;
3769}
3770
Yonghong Songafbf21d2020-07-23 11:41:11 -07003771static int check_buffer_access(struct bpf_verifier_env *env,
3772 const struct bpf_reg_state *reg,
3773 int regno, int off, int size,
3774 bool zero_size_allowed,
3775 const char *buf_info,
3776 u32 *max_access)
3777{
3778 int err;
3779
3780 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3781 if (err)
3782 return err;
3783
3784 if (off + size > *max_access)
3785 *max_access = off + size;
3786
3787 return 0;
3788}
3789
John Fastabend3f50f132020-03-30 14:36:39 -07003790/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3791static void zext_32_to_64(struct bpf_reg_state *reg)
3792{
3793 reg->var_off = tnum_subreg(reg->var_off);
3794 __reg_assign_32_into_64(reg);
3795}
Matt Mullins9df1c282019-04-26 11:49:47 -07003796
Jann Horn0c17d1d2017-12-18 20:11:55 -08003797/* truncate register to smaller size (in bytes)
3798 * must be called with size < BPF_REG_SIZE
3799 */
3800static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3801{
3802 u64 mask;
3803
3804 /* clear high bits in bit representation */
3805 reg->var_off = tnum_cast(reg->var_off, size);
3806
3807 /* fix arithmetic bounds */
3808 mask = ((u64)1 << (size * 8)) - 1;
3809 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3810 reg->umin_value &= mask;
3811 reg->umax_value &= mask;
3812 } else {
3813 reg->umin_value = 0;
3814 reg->umax_value = mask;
3815 }
3816 reg->smin_value = reg->umin_value;
3817 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003818
3819 /* If size is smaller than 32bit register the 32bit register
3820 * values are also truncated so we push 64-bit bounds into
3821 * 32-bit bounds. Above were truncated < 32-bits already.
3822 */
3823 if (size >= 4)
3824 return;
3825 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003826}
3827
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003828static bool bpf_map_is_rdonly(const struct bpf_map *map)
3829{
3830 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3831}
3832
3833static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3834{
3835 void *ptr;
3836 u64 addr;
3837 int err;
3838
3839 err = map->ops->map_direct_value_addr(map, &addr, off);
3840 if (err)
3841 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003842 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003843
3844 switch (size) {
3845 case sizeof(u8):
3846 *val = (u64)*(u8 *)ptr;
3847 break;
3848 case sizeof(u16):
3849 *val = (u64)*(u16 *)ptr;
3850 break;
3851 case sizeof(u32):
3852 *val = (u64)*(u32 *)ptr;
3853 break;
3854 case sizeof(u64):
3855 *val = *(u64 *)ptr;
3856 break;
3857 default:
3858 return -EINVAL;
3859 }
3860 return 0;
3861}
3862
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003863static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3864 struct bpf_reg_state *regs,
3865 int regno, int off, int size,
3866 enum bpf_access_type atype,
3867 int value_regno)
3868{
3869 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003870 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3871 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003872 u32 btf_id;
3873 int ret;
3874
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003875 if (off < 0) {
3876 verbose(env,
3877 "R%d is ptr_%s invalid negative access: off=%d\n",
3878 regno, tname, off);
3879 return -EACCES;
3880 }
3881 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3882 char tn_buf[48];
3883
3884 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3885 verbose(env,
3886 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3887 regno, tname, off, tn_buf);
3888 return -EACCES;
3889 }
3890
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003891 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003892 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3893 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003894 } else {
3895 if (atype != BPF_READ) {
3896 verbose(env, "only read is supported\n");
3897 return -EACCES;
3898 }
3899
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003900 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3901 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003902 }
3903
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003904 if (ret < 0)
3905 return ret;
3906
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003907 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003908 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003909
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003910 return 0;
3911}
3912
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003913static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3914 struct bpf_reg_state *regs,
3915 int regno, int off, int size,
3916 enum bpf_access_type atype,
3917 int value_regno)
3918{
3919 struct bpf_reg_state *reg = regs + regno;
3920 struct bpf_map *map = reg->map_ptr;
3921 const struct btf_type *t;
3922 const char *tname;
3923 u32 btf_id;
3924 int ret;
3925
3926 if (!btf_vmlinux) {
3927 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3928 return -ENOTSUPP;
3929 }
3930
3931 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3932 verbose(env, "map_ptr access not supported for map type %d\n",
3933 map->map_type);
3934 return -ENOTSUPP;
3935 }
3936
3937 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3938 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3939
3940 if (!env->allow_ptr_to_map_access) {
3941 verbose(env,
3942 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3943 tname);
3944 return -EPERM;
3945 }
3946
3947 if (off < 0) {
3948 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3949 regno, tname, off);
3950 return -EACCES;
3951 }
3952
3953 if (atype != BPF_READ) {
3954 verbose(env, "only read from %s is supported\n", tname);
3955 return -EACCES;
3956 }
3957
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003958 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003959 if (ret < 0)
3960 return ret;
3961
3962 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003963 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003964
3965 return 0;
3966}
3967
Andrei Matei01f810a2021-02-06 20:10:24 -05003968/* Check that the stack access at the given offset is within bounds. The
3969 * maximum valid offset is -1.
3970 *
3971 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3972 * -state->allocated_stack for reads.
3973 */
3974static int check_stack_slot_within_bounds(int off,
3975 struct bpf_func_state *state,
3976 enum bpf_access_type t)
3977{
3978 int min_valid_off;
3979
3980 if (t == BPF_WRITE)
3981 min_valid_off = -MAX_BPF_STACK;
3982 else
3983 min_valid_off = -state->allocated_stack;
3984
3985 if (off < min_valid_off || off > -1)
3986 return -EACCES;
3987 return 0;
3988}
3989
3990/* Check that the stack access at 'regno + off' falls within the maximum stack
3991 * bounds.
3992 *
3993 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3994 */
3995static int check_stack_access_within_bounds(
3996 struct bpf_verifier_env *env,
3997 int regno, int off, int access_size,
3998 enum stack_access_src src, enum bpf_access_type type)
3999{
4000 struct bpf_reg_state *regs = cur_regs(env);
4001 struct bpf_reg_state *reg = regs + regno;
4002 struct bpf_func_state *state = func(env, reg);
4003 int min_off, max_off;
4004 int err;
4005 char *err_extra;
4006
4007 if (src == ACCESS_HELPER)
4008 /* We don't know if helpers are reading or writing (or both). */
4009 err_extra = " indirect access to";
4010 else if (type == BPF_READ)
4011 err_extra = " read from";
4012 else
4013 err_extra = " write to";
4014
4015 if (tnum_is_const(reg->var_off)) {
4016 min_off = reg->var_off.value + off;
4017 if (access_size > 0)
4018 max_off = min_off + access_size - 1;
4019 else
4020 max_off = min_off;
4021 } else {
4022 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4023 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4024 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4025 err_extra, regno);
4026 return -EACCES;
4027 }
4028 min_off = reg->smin_value + off;
4029 if (access_size > 0)
4030 max_off = reg->smax_value + off + access_size - 1;
4031 else
4032 max_off = min_off;
4033 }
4034
4035 err = check_stack_slot_within_bounds(min_off, state, type);
4036 if (!err)
4037 err = check_stack_slot_within_bounds(max_off, state, type);
4038
4039 if (err) {
4040 if (tnum_is_const(reg->var_off)) {
4041 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4042 err_extra, regno, off, access_size);
4043 } else {
4044 char tn_buf[48];
4045
4046 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4047 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4048 err_extra, regno, tn_buf, access_size);
4049 }
4050 }
4051 return err;
4052}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004053
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004054/* check whether memory at (regno + off) is accessible for t = (read | write)
4055 * if t==write, value_regno is a register which value is stored into memory
4056 * if t==read, value_regno is a register which will receive the value from memory
4057 * if t==write && value_regno==-1, some unknown value is stored into memory
4058 * if t==read && value_regno==-1, don't care what we read from memory
4059 */
Daniel Borkmannca369602018-02-23 22:29:05 +01004060static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4061 int off, int bpf_size, enum bpf_access_type t,
4062 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004063{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004064 struct bpf_reg_state *regs = cur_regs(env);
4065 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004066 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004067 int size, err = 0;
4068
4069 size = bpf_size_to_bytes(bpf_size);
4070 if (size < 0)
4071 return size;
4072
Edward Creef1174f72017-08-07 15:26:19 +01004073 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01004074 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004075 if (err)
4076 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004077
Edward Creef1174f72017-08-07 15:26:19 +01004078 /* for access checks, reg->off is just part of off */
4079 off += reg->off;
4080
Yonghong Song69c087b2021-02-26 12:49:25 -08004081 if (reg->type == PTR_TO_MAP_KEY) {
4082 if (t == BPF_WRITE) {
4083 verbose(env, "write to change key R%d not allowed\n", regno);
4084 return -EACCES;
4085 }
4086
4087 err = check_mem_region_access(env, regno, off, size,
4088 reg->map_ptr->key_size, false);
4089 if (err)
4090 return err;
4091 if (value_regno >= 0)
4092 mark_reg_unknown(env, regs, value_regno);
4093 } else if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004094 if (t == BPF_WRITE && value_regno >= 0 &&
4095 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004096 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004097 return -EACCES;
4098 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02004099 err = check_map_access_type(env, regno, off, size, t);
4100 if (err)
4101 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004102 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004103 if (!err && t == BPF_READ && value_regno >= 0) {
4104 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004105
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004106 /* if map is read-only, track its contents as scalars */
4107 if (tnum_is_const(reg->var_off) &&
4108 bpf_map_is_rdonly(map) &&
4109 map->ops->map_direct_value_addr) {
4110 int map_off = off + reg->var_off.value;
4111 u64 val = 0;
4112
4113 err = bpf_map_direct_read(map, map_off, size,
4114 &val);
4115 if (err)
4116 return err;
4117
4118 regs[value_regno].type = SCALAR_VALUE;
4119 __mark_reg_known(&regs[value_regno], val);
4120 } else {
4121 mark_reg_unknown(env, regs, value_regno);
4122 }
4123 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004124 } else if (reg->type == PTR_TO_MEM) {
4125 if (t == BPF_WRITE && value_regno >= 0 &&
4126 is_pointer_value(env, value_regno)) {
4127 verbose(env, "R%d leaks addr into mem\n", value_regno);
4128 return -EACCES;
4129 }
4130 err = check_mem_region_access(env, regno, off, size,
4131 reg->mem_size, false);
4132 if (!err && t == BPF_READ && value_regno >= 0)
4133 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07004134 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01004135 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004136 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004137 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07004138
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004139 if (t == BPF_WRITE && value_regno >= 0 &&
4140 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004141 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004142 return -EACCES;
4143 }
Edward Creef1174f72017-08-07 15:26:19 +01004144
Daniel Borkmann58990d12018-06-07 17:40:03 +02004145 err = check_ctx_reg(env, reg, regno);
4146 if (err < 0)
4147 return err;
4148
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004149 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004150 if (err)
4151 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004152 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004153 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004154 * PTR_TO_PACKET[_META,_END]. In the latter
4155 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01004156 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004157 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004158 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004159 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004160 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004161 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004162 if (reg_type_may_be_null(reg_type))
4163 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01004164 /* A load of ctx field could have different
4165 * actual load size with the one encoded in the
4166 * insn. When the dst is PTR, it is for sure not
4167 * a sub-register.
4168 */
4169 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07004170 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004171 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4172 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004173 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004174 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004175 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004176 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004177 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004178
Edward Creef1174f72017-08-07 15:26:19 +01004179 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004180 /* Basic bounds checks. */
4181 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01004182 if (err)
4183 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004184
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004185 state = func(env, reg);
4186 err = update_stack_depth(env, state, off);
4187 if (err)
4188 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004189
Andrei Matei01f810a2021-02-06 20:10:24 -05004190 if (t == BPF_READ)
4191 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004192 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05004193 else
4194 err = check_stack_write(env, regno, off, size,
4195 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004196 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004197 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004198 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004199 return -EACCES;
4200 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004201 if (t == BPF_WRITE && value_regno >= 0 &&
4202 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004203 verbose(env, "R%d leaks addr into packet\n",
4204 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004205 return -EACCES;
4206 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08004207 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004208 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004209 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07004210 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4211 if (t == BPF_WRITE && value_regno >= 0 &&
4212 is_pointer_value(env, value_regno)) {
4213 verbose(env, "R%d leaks addr into flow keys\n",
4214 value_regno);
4215 return -EACCES;
4216 }
4217
4218 err = check_flow_keys_access(env, off, size);
4219 if (!err && t == BPF_READ && value_regno >= 0)
4220 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004221 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07004222 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004223 verbose(env, "R%d cannot write into %s\n",
4224 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07004225 return -EACCES;
4226 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08004227 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07004228 if (!err && value_regno >= 0)
4229 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07004230 } else if (reg->type == PTR_TO_TP_BUFFER) {
4231 err = check_tp_buffer_access(env, reg, regno, off, size);
4232 if (!err && t == BPF_READ && value_regno >= 0)
4233 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004234 } else if (reg->type == PTR_TO_BTF_ID) {
4235 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4236 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004237 } else if (reg->type == CONST_PTR_TO_MAP) {
4238 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4239 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004240 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4241 if (t == BPF_WRITE) {
4242 verbose(env, "R%d cannot write into %s\n",
4243 regno, reg_type_str[reg->type]);
4244 return -EACCES;
4245 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004246 err = check_buffer_access(env, reg, regno, off, size, false,
4247 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004248 &env->prog->aux->max_rdonly_access);
4249 if (!err && value_regno >= 0)
4250 mark_reg_unknown(env, regs, value_regno);
4251 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004252 err = check_buffer_access(env, reg, regno, off, size, false,
4253 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004254 &env->prog->aux->max_rdwr_access);
4255 if (!err && t == BPF_READ && value_regno >= 0)
4256 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004257 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004258 verbose(env, "R%d invalid mem access '%s'\n", regno,
4259 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004260 return -EACCES;
4261 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004262
Edward Creef1174f72017-08-07 15:26:19 +01004263 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004264 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004265 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08004266 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004267 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004268 return err;
4269}
4270
Brendan Jackman91c960b2021-01-14 18:17:44 +00004271static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004272{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004273 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004274 int err;
4275
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004276 switch (insn->imm) {
4277 case BPF_ADD:
4278 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004279 case BPF_AND:
4280 case BPF_AND | BPF_FETCH:
4281 case BPF_OR:
4282 case BPF_OR | BPF_FETCH:
4283 case BPF_XOR:
4284 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004285 case BPF_XCHG:
4286 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004287 break;
4288 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004289 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4290 return -EINVAL;
4291 }
4292
4293 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4294 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004295 return -EINVAL;
4296 }
4297
4298 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004299 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004300 if (err)
4301 return err;
4302
4303 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004304 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004305 if (err)
4306 return err;
4307
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004308 if (insn->imm == BPF_CMPXCHG) {
4309 /* Check comparison of R0 with memory location */
4310 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4311 if (err)
4312 return err;
4313 }
4314
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004315 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004316 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004317 return -EACCES;
4318 }
4319
Daniel Borkmannca369602018-02-23 22:29:05 +01004320 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004321 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004322 is_flow_key_reg(env, insn->dst_reg) ||
4323 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004324 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004325 insn->dst_reg,
4326 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004327 return -EACCES;
4328 }
4329
Brendan Jackman37086bf2021-02-02 13:50:02 +00004330 if (insn->imm & BPF_FETCH) {
4331 if (insn->imm == BPF_CMPXCHG)
4332 load_reg = BPF_REG_0;
4333 else
4334 load_reg = insn->src_reg;
4335
4336 /* check and record load of old value */
4337 err = check_reg_arg(env, load_reg, DST_OP);
4338 if (err)
4339 return err;
4340 } else {
4341 /* This instruction accesses a memory location but doesn't
4342 * actually load it into a register.
4343 */
4344 load_reg = -1;
4345 }
4346
Brendan Jackman91c960b2021-01-14 18:17:44 +00004347 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004348 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004349 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004350 if (err)
4351 return err;
4352
Brendan Jackman91c960b2021-01-14 18:17:44 +00004353 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004354 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4355 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4356 if (err)
4357 return err;
4358
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004359 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004360}
4361
Andrei Matei01f810a2021-02-06 20:10:24 -05004362/* When register 'regno' is used to read the stack (either directly or through
4363 * a helper function) make sure that it's within stack boundary and, depending
4364 * on the access type, that all elements of the stack are initialized.
4365 *
4366 * 'off' includes 'regno->off', but not its dynamic part (if any).
4367 *
4368 * All registers that have been spilled on the stack in the slots within the
4369 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004370 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004371static int check_stack_range_initialized(
4372 struct bpf_verifier_env *env, int regno, int off,
4373 int access_size, bool zero_size_allowed,
4374 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004375{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004376 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004377 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004378 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004379 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4380 enum bpf_access_type bounds_check_type;
4381 /* Some accesses can write anything into the stack, others are
4382 * read-only.
4383 */
4384 bool clobber = false;
4385
4386 if (access_size == 0 && !zero_size_allowed) {
4387 verbose(env, "invalid zero-sized read\n");
4388 return -EACCES;
4389 }
4390
4391 if (type == ACCESS_HELPER) {
4392 /* The bounds checks for writes are more permissive than for
4393 * reads. However, if raw_mode is not set, we'll do extra
4394 * checks below.
4395 */
4396 bounds_check_type = BPF_WRITE;
4397 clobber = true;
4398 } else {
4399 bounds_check_type = BPF_READ;
4400 }
4401 err = check_stack_access_within_bounds(env, regno, off, access_size,
4402 type, bounds_check_type);
4403 if (err)
4404 return err;
4405
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004406
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004407 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004408 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004409 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004410 /* Variable offset is prohibited for unprivileged mode for
4411 * simplicity since it requires corresponding support in
4412 * Spectre masking for stack ALU.
4413 * See also retrieve_ptr_limit().
4414 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004415 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004416 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004417
Andrey Ignatov088ec262019-04-03 23:22:39 -07004418 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004419 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4420 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004421 return -EACCES;
4422 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004423 /* Only initialized buffer on stack is allowed to be accessed
4424 * with variable offset. With uninitialized buffer it's hard to
4425 * guarantee that whole memory is marked as initialized on
4426 * helper return since specific bounds are unknown what may
4427 * cause uninitialized stack leaking.
4428 */
4429 if (meta && meta->raw_mode)
4430 meta = NULL;
4431
Andrei Matei01f810a2021-02-06 20:10:24 -05004432 min_off = reg->smin_value + off;
4433 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004434 }
4435
Daniel Borkmann435faee12016-04-13 00:10:51 +02004436 if (meta && meta->raw_mode) {
4437 meta->access_size = access_size;
4438 meta->regno = regno;
4439 return 0;
4440 }
4441
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004442 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004443 u8 *stype;
4444
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004445 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004446 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004447 if (state->allocated_stack <= slot)
4448 goto err;
4449 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4450 if (*stype == STACK_MISC)
4451 goto mark;
4452 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004453 if (clobber) {
4454 /* helper can write anything into the stack */
4455 *stype = STACK_MISC;
4456 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004457 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004458 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004459
4460 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4461 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4462 goto mark;
4463
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004464 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004465 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4466 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004467 if (clobber) {
4468 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4469 for (j = 0; j < BPF_REG_SIZE; j++)
4470 state->stack[spi].slot_type[j] = STACK_MISC;
4471 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004472 goto mark;
4473 }
4474
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004475err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004476 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004477 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4478 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004479 } else {
4480 char tn_buf[48];
4481
4482 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004483 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4484 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004485 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004486 return -EACCES;
4487mark:
4488 /* reading any byte out of 8-byte 'spill_slot' will cause
4489 * the whole slot to be marked as 'read'
4490 */
Edward Cree679c7822018-08-22 20:02:19 +01004491 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004492 state->stack[spi].spilled_ptr.parent,
4493 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004494 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004495 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004496}
4497
Gianluca Borello06c1c042017-01-09 10:19:49 -08004498static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4499 int access_size, bool zero_size_allowed,
4500 struct bpf_call_arg_meta *meta)
4501{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004502 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004503
Edward Creef1174f72017-08-07 15:26:19 +01004504 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004505 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004506 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004507 return check_packet_access(env, regno, reg->off, access_size,
4508 zero_size_allowed);
Yonghong Song69c087b2021-02-26 12:49:25 -08004509 case PTR_TO_MAP_KEY:
4510 return check_mem_region_access(env, regno, reg->off, access_size,
4511 reg->map_ptr->key_size, false);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004512 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004513 if (check_map_access_type(env, regno, reg->off, access_size,
4514 meta && meta->raw_mode ? BPF_WRITE :
4515 BPF_READ))
4516 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004517 return check_map_access(env, regno, reg->off, access_size,
4518 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004519 case PTR_TO_MEM:
4520 return check_mem_region_access(env, regno, reg->off,
4521 access_size, reg->mem_size,
4522 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004523 case PTR_TO_RDONLY_BUF:
4524 if (meta && meta->raw_mode)
4525 return -EACCES;
4526 return check_buffer_access(env, reg, regno, reg->off,
4527 access_size, zero_size_allowed,
4528 "rdonly",
4529 &env->prog->aux->max_rdonly_access);
4530 case PTR_TO_RDWR_BUF:
4531 return check_buffer_access(env, reg, regno, reg->off,
4532 access_size, zero_size_allowed,
4533 "rdwr",
4534 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004535 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004536 return check_stack_range_initialized(
4537 env,
4538 regno, reg->off, access_size,
4539 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004540 default: /* scalar_value or invalid ptr */
4541 /* Allow zero-byte read from NULL, regardless of pointer type */
4542 if (zero_size_allowed && access_size == 0 &&
4543 register_is_null(reg))
4544 return 0;
4545
4546 verbose(env, "R%d type=%s expected=%s\n", regno,
4547 reg_type_str[reg->type],
4548 reg_type_str[PTR_TO_STACK]);
4549 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004550 }
4551}
4552
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004553int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4554 u32 regno, u32 mem_size)
4555{
4556 if (register_is_null(reg))
4557 return 0;
4558
4559 if (reg_type_may_be_null(reg->type)) {
4560 /* Assuming that the register contains a value check if the memory
4561 * access is safe. Temporarily save and restore the register's state as
4562 * the conversion shouldn't be visible to a caller.
4563 */
4564 const struct bpf_reg_state saved_reg = *reg;
4565 int rv;
4566
4567 mark_ptr_not_null_reg(reg);
4568 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4569 *reg = saved_reg;
4570 return rv;
4571 }
4572
4573 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4574}
4575
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004576/* Implementation details:
4577 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4578 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4579 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4580 * value_or_null->value transition, since the verifier only cares about
4581 * the range of access to valid map value pointer and doesn't care about actual
4582 * address of the map element.
4583 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4584 * reg->id > 0 after value_or_null->value transition. By doing so
4585 * two bpf_map_lookups will be considered two different pointers that
4586 * point to different bpf_spin_locks.
4587 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4588 * dead-locks.
4589 * Since only one bpf_spin_lock is allowed the checks are simpler than
4590 * reg_is_refcounted() logic. The verifier needs to remember only
4591 * one spin_lock instead of array of acquired_refs.
4592 * cur_state->active_spin_lock remembers which map value element got locked
4593 * and clears it after bpf_spin_unlock.
4594 */
4595static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4596 bool is_lock)
4597{
4598 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4599 struct bpf_verifier_state *cur = env->cur_state;
4600 bool is_const = tnum_is_const(reg->var_off);
4601 struct bpf_map *map = reg->map_ptr;
4602 u64 val = reg->var_off.value;
4603
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004604 if (!is_const) {
4605 verbose(env,
4606 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4607 regno);
4608 return -EINVAL;
4609 }
4610 if (!map->btf) {
4611 verbose(env,
4612 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4613 map->name);
4614 return -EINVAL;
4615 }
4616 if (!map_value_has_spin_lock(map)) {
4617 if (map->spin_lock_off == -E2BIG)
4618 verbose(env,
4619 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4620 map->name);
4621 else if (map->spin_lock_off == -ENOENT)
4622 verbose(env,
4623 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4624 map->name);
4625 else
4626 verbose(env,
4627 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4628 map->name);
4629 return -EINVAL;
4630 }
4631 if (map->spin_lock_off != val + reg->off) {
4632 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4633 val + reg->off);
4634 return -EINVAL;
4635 }
4636 if (is_lock) {
4637 if (cur->active_spin_lock) {
4638 verbose(env,
4639 "Locking two bpf_spin_locks are not allowed\n");
4640 return -EINVAL;
4641 }
4642 cur->active_spin_lock = reg->id;
4643 } else {
4644 if (!cur->active_spin_lock) {
4645 verbose(env, "bpf_spin_unlock without taking a lock\n");
4646 return -EINVAL;
4647 }
4648 if (cur->active_spin_lock != reg->id) {
4649 verbose(env, "bpf_spin_unlock of different lock\n");
4650 return -EINVAL;
4651 }
4652 cur->active_spin_lock = 0;
4653 }
4654 return 0;
4655}
4656
Daniel Borkmann90133412018-01-20 01:24:29 +01004657static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4658{
4659 return type == ARG_PTR_TO_MEM ||
4660 type == ARG_PTR_TO_MEM_OR_NULL ||
4661 type == ARG_PTR_TO_UNINIT_MEM;
4662}
4663
4664static bool arg_type_is_mem_size(enum bpf_arg_type type)
4665{
4666 return type == ARG_CONST_SIZE ||
4667 type == ARG_CONST_SIZE_OR_ZERO;
4668}
4669
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004670static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4671{
4672 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4673}
4674
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004675static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4676{
4677 return type == ARG_PTR_TO_INT ||
4678 type == ARG_PTR_TO_LONG;
4679}
4680
4681static int int_ptr_type_to_size(enum bpf_arg_type type)
4682{
4683 if (type == ARG_PTR_TO_INT)
4684 return sizeof(u32);
4685 else if (type == ARG_PTR_TO_LONG)
4686 return sizeof(u64);
4687
4688 return -EINVAL;
4689}
4690
Lorenz Bauer912f4422020-08-21 11:29:46 +01004691static int resolve_map_arg_type(struct bpf_verifier_env *env,
4692 const struct bpf_call_arg_meta *meta,
4693 enum bpf_arg_type *arg_type)
4694{
4695 if (!meta->map_ptr) {
4696 /* kernel subsystem misconfigured verifier */
4697 verbose(env, "invalid map_ptr to access map->type\n");
4698 return -EACCES;
4699 }
4700
4701 switch (meta->map_ptr->map_type) {
4702 case BPF_MAP_TYPE_SOCKMAP:
4703 case BPF_MAP_TYPE_SOCKHASH:
4704 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01004705 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01004706 } else {
4707 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4708 return -EINVAL;
4709 }
4710 break;
4711
4712 default:
4713 break;
4714 }
4715 return 0;
4716}
4717
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004718struct bpf_reg_types {
4719 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004720 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004721};
4722
4723static const struct bpf_reg_types map_key_value_types = {
4724 .types = {
4725 PTR_TO_STACK,
4726 PTR_TO_PACKET,
4727 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004728 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004729 PTR_TO_MAP_VALUE,
4730 },
4731};
4732
4733static const struct bpf_reg_types sock_types = {
4734 .types = {
4735 PTR_TO_SOCK_COMMON,
4736 PTR_TO_SOCKET,
4737 PTR_TO_TCP_SOCK,
4738 PTR_TO_XDP_SOCK,
4739 },
4740};
4741
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004742#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004743static const struct bpf_reg_types btf_id_sock_common_types = {
4744 .types = {
4745 PTR_TO_SOCK_COMMON,
4746 PTR_TO_SOCKET,
4747 PTR_TO_TCP_SOCK,
4748 PTR_TO_XDP_SOCK,
4749 PTR_TO_BTF_ID,
4750 },
4751 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4752};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004753#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004754
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004755static const struct bpf_reg_types mem_types = {
4756 .types = {
4757 PTR_TO_STACK,
4758 PTR_TO_PACKET,
4759 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004760 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004761 PTR_TO_MAP_VALUE,
4762 PTR_TO_MEM,
4763 PTR_TO_RDONLY_BUF,
4764 PTR_TO_RDWR_BUF,
4765 },
4766};
4767
4768static const struct bpf_reg_types int_ptr_types = {
4769 .types = {
4770 PTR_TO_STACK,
4771 PTR_TO_PACKET,
4772 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004773 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004774 PTR_TO_MAP_VALUE,
4775 },
4776};
4777
4778static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4779static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4780static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4781static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4782static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4783static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4784static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004785static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Yonghong Song69c087b2021-02-26 12:49:25 -08004786static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4787static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
Florent Revestfff13c42021-04-19 17:52:39 +02004788static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004789
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004790static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004791 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4792 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4793 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4794 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4795 [ARG_CONST_SIZE] = &scalar_types,
4796 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4797 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4798 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4799 [ARG_PTR_TO_CTX] = &context_types,
4800 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4801 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004802#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004803 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004804#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004805 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4806 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4807 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4808 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4809 [ARG_PTR_TO_MEM] = &mem_types,
4810 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4811 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4812 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4813 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4814 [ARG_PTR_TO_INT] = &int_ptr_types,
4815 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004816 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Yonghong Song69c087b2021-02-26 12:49:25 -08004817 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4818 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
Florent Revestfff13c42021-04-19 17:52:39 +02004819 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004820};
4821
4822static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004823 enum bpf_arg_type arg_type,
4824 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004825{
4826 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4827 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004828 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004829 int i, j;
4830
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004831 compatible = compatible_reg_types[arg_type];
4832 if (!compatible) {
4833 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4834 return -EFAULT;
4835 }
4836
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004837 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4838 expected = compatible->types[i];
4839 if (expected == NOT_INIT)
4840 break;
4841
4842 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004843 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004844 }
4845
4846 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4847 for (j = 0; j + 1 < i; j++)
4848 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4849 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4850 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004851
4852found:
4853 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004854 if (!arg_btf_id) {
4855 if (!compatible->btf_id) {
4856 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4857 return -EFAULT;
4858 }
4859 arg_btf_id = compatible->btf_id;
4860 }
4861
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004862 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4863 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004864 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004865 regno, kernel_type_name(reg->btf, reg->btf_id),
4866 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004867 return -EACCES;
4868 }
4869
4870 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4871 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4872 regno);
4873 return -EACCES;
4874 }
4875 }
4876
4877 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004878}
4879
Yonghong Songaf7ec132020-06-23 16:08:09 -07004880static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4881 struct bpf_call_arg_meta *meta,
4882 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004883{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004884 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004885 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004886 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004887 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004888 int err = 0;
4889
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004890 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004891 return 0;
4892
Edward Creedc503a82017-08-15 20:34:35 +01004893 err = check_reg_arg(env, regno, SRC_OP);
4894 if (err)
4895 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004896
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004897 if (arg_type == ARG_ANYTHING) {
4898 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004899 verbose(env, "R%d leaks addr into helper function\n",
4900 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004901 return -EACCES;
4902 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004903 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004904 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004905
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004906 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004907 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004908 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004909 return -EACCES;
4910 }
4911
Lorenz Bauer912f4422020-08-21 11:29:46 +01004912 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4913 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4914 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4915 err = resolve_map_arg_type(env, meta, &arg_type);
4916 if (err)
4917 return err;
4918 }
4919
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004920 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4921 /* A NULL register has a SCALAR_VALUE type, so skip
4922 * type checking.
4923 */
4924 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004925
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004926 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004927 if (err)
4928 return err;
4929
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004930 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004931 err = check_ctx_reg(env, reg, regno);
4932 if (err < 0)
4933 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004934 }
4935
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004936skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004937 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004938 if (meta->ref_obj_id) {
4939 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4940 regno, reg->ref_obj_id,
4941 meta->ref_obj_id);
4942 return -EFAULT;
4943 }
4944 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004945 }
4946
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004947 if (arg_type == ARG_CONST_MAP_PTR) {
4948 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004949 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004950 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4951 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4952 * check that [key, key + map->key_size) are within
4953 * stack limits and initialized
4954 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004955 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004956 /* in function declaration map_ptr must come before
4957 * map_key, so that it's verified and known before
4958 * we have to check map_key here. Otherwise it means
4959 * that kernel subsystem misconfigured verifier
4960 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004961 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004962 return -EACCES;
4963 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004964 err = check_helper_mem_access(env, regno,
4965 meta->map_ptr->key_size, false,
4966 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004967 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004968 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4969 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004970 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004971 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4972 * check [value, value + map->value_size) validity
4973 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004974 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004975 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004976 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004977 return -EACCES;
4978 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004979 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004980 err = check_helper_mem_access(env, regno,
4981 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004982 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004983 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4984 if (!reg->btf_id) {
4985 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4986 return -EACCES;
4987 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004988 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004989 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004990 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4991 if (meta->func_id == BPF_FUNC_spin_lock) {
4992 if (process_spin_lock(env, regno, true))
4993 return -EACCES;
4994 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4995 if (process_spin_lock(env, regno, false))
4996 return -EACCES;
4997 } else {
4998 verbose(env, "verifier internal error\n");
4999 return -EFAULT;
5000 }
Yonghong Song69c087b2021-02-26 12:49:25 -08005001 } else if (arg_type == ARG_PTR_TO_FUNC) {
5002 meta->subprogno = reg->subprogno;
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01005003 } else if (arg_type_is_mem_ptr(arg_type)) {
5004 /* The access to this pointer is only checked when we hit the
5005 * next is_mem_size argument below.
5006 */
5007 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01005008 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005009 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005010
John Fastabend10060502020-03-30 14:36:19 -07005011 /* This is used to refine r0 return value bounds for helpers
5012 * that enforce this value as an upper bound on return values.
5013 * See do_refine_retval_range() for helpers that can refine
5014 * the return value. C type of helper is u32 so we pull register
5015 * bound from umax_value however, if negative verifier errors
5016 * out. Only upper bounds can be learned because retval is an
5017 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07005018 */
John Fastabend10060502020-03-30 14:36:19 -07005019 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07005020
Edward Creef1174f72017-08-07 15:26:19 +01005021 /* The register is SCALAR_VALUE; the access check
5022 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08005023 */
Edward Creef1174f72017-08-07 15:26:19 +01005024 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08005025 /* For unprivileged variable accesses, disable raw
5026 * mode so that the program is required to
5027 * initialize all the memory that the helper could
5028 * just partially fill up.
5029 */
5030 meta = NULL;
5031
Edward Creeb03c9f92017-08-07 15:26:36 +01005032 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005033 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005034 regno);
5035 return -EACCES;
5036 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08005037
Edward Creeb03c9f92017-08-07 15:26:36 +01005038 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01005039 err = check_helper_mem_access(env, regno - 1, 0,
5040 zero_size_allowed,
5041 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08005042 if (err)
5043 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08005044 }
Edward Creef1174f72017-08-07 15:26:19 +01005045
Edward Creeb03c9f92017-08-07 15:26:36 +01005046 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005047 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005048 regno);
5049 return -EACCES;
5050 }
5051 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01005052 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01005053 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005054 if (!err)
5055 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005056 } else if (arg_type_is_alloc_size(arg_type)) {
5057 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00005058 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005059 regno);
5060 return -EACCES;
5061 }
5062 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07005063 } else if (arg_type_is_int_ptr(arg_type)) {
5064 int size = int_ptr_type_to_size(arg_type);
5065
5066 err = check_helper_mem_access(env, regno, size, false, meta);
5067 if (err)
5068 return err;
5069 err = check_ptr_alignment(env, reg, 0, size, true);
Florent Revestfff13c42021-04-19 17:52:39 +02005070 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5071 struct bpf_map *map = reg->map_ptr;
5072 int map_off;
5073 u64 map_addr;
5074 char *str_ptr;
5075
Florent Revesta8fad732021-04-23 01:55:43 +02005076 if (!bpf_map_is_rdonly(map)) {
Florent Revestfff13c42021-04-19 17:52:39 +02005077 verbose(env, "R%d does not point to a readonly map'\n", regno);
5078 return -EACCES;
5079 }
5080
5081 if (!tnum_is_const(reg->var_off)) {
5082 verbose(env, "R%d is not a constant address'\n", regno);
5083 return -EACCES;
5084 }
5085
5086 if (!map->ops->map_direct_value_addr) {
5087 verbose(env, "no direct value access support for this map type\n");
5088 return -EACCES;
5089 }
5090
5091 err = check_map_access(env, regno, reg->off,
5092 map->value_size - reg->off, false);
5093 if (err)
5094 return err;
5095
5096 map_off = reg->off + reg->var_off.value;
5097 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5098 if (err) {
5099 verbose(env, "direct value access on string failed\n");
5100 return err;
5101 }
5102
5103 str_ptr = (char *)(long)(map_addr);
5104 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5105 verbose(env, "string is not zero-terminated\n");
5106 return -EINVAL;
5107 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005108 }
5109
5110 return err;
5111}
5112
Lorenz Bauer01262402020-08-21 11:29:47 +01005113static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5114{
5115 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07005116 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01005117
5118 if (func_id != BPF_FUNC_map_update_elem)
5119 return false;
5120
5121 /* It's not possible to get access to a locked struct sock in these
5122 * contexts, so updating is safe.
5123 */
5124 switch (type) {
5125 case BPF_PROG_TYPE_TRACING:
5126 if (eatype == BPF_TRACE_ITER)
5127 return true;
5128 break;
5129 case BPF_PROG_TYPE_SOCKET_FILTER:
5130 case BPF_PROG_TYPE_SCHED_CLS:
5131 case BPF_PROG_TYPE_SCHED_ACT:
5132 case BPF_PROG_TYPE_XDP:
5133 case BPF_PROG_TYPE_SK_REUSEPORT:
5134 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5135 case BPF_PROG_TYPE_SK_LOOKUP:
5136 return true;
5137 default:
5138 break;
5139 }
5140
5141 verbose(env, "cannot update sockmap in this context\n");
5142 return false;
5143}
5144
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005145static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5146{
5147 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5148}
5149
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005150static int check_map_func_compatibility(struct bpf_verifier_env *env,
5151 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00005152{
Kaixu Xia35578d72015-08-06 07:02:35 +00005153 if (!map)
5154 return 0;
5155
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005156 /* We need a two way check, first is from map perspective ... */
5157 switch (map->map_type) {
5158 case BPF_MAP_TYPE_PROG_ARRAY:
5159 if (func_id != BPF_FUNC_tail_call)
5160 goto error;
5161 break;
5162 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5163 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07005164 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005165 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005166 func_id != BPF_FUNC_perf_event_read_value &&
5167 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005168 goto error;
5169 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005170 case BPF_MAP_TYPE_RINGBUF:
5171 if (func_id != BPF_FUNC_ringbuf_output &&
5172 func_id != BPF_FUNC_ringbuf_reserve &&
5173 func_id != BPF_FUNC_ringbuf_submit &&
5174 func_id != BPF_FUNC_ringbuf_discard &&
5175 func_id != BPF_FUNC_ringbuf_query)
5176 goto error;
5177 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005178 case BPF_MAP_TYPE_STACK_TRACE:
5179 if (func_id != BPF_FUNC_get_stackid)
5180 goto error;
5181 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07005182 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04005183 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005184 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005185 goto error;
5186 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005187 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00005188 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07005189 if (func_id != BPF_FUNC_get_local_storage)
5190 goto error;
5191 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07005192 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005193 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02005194 if (func_id != BPF_FUNC_redirect_map &&
5195 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07005196 goto error;
5197 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005198 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5199 * appear.
5200 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02005201 case BPF_MAP_TYPE_CPUMAP:
5202 if (func_id != BPF_FUNC_redirect_map)
5203 goto error;
5204 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005205 case BPF_MAP_TYPE_XSKMAP:
5206 if (func_id != BPF_FUNC_redirect_map &&
5207 func_id != BPF_FUNC_map_lookup_elem)
5208 goto error;
5209 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005210 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07005211 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005212 if (func_id != BPF_FUNC_map_lookup_elem)
5213 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07005214 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005215 case BPF_MAP_TYPE_SOCKMAP:
5216 if (func_id != BPF_FUNC_sk_redirect_map &&
5217 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07005218 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005219 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005220 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005221 func_id != BPF_FUNC_map_lookup_elem &&
5222 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07005223 goto error;
5224 break;
John Fastabend81110382018-05-14 10:00:17 -07005225 case BPF_MAP_TYPE_SOCKHASH:
5226 if (func_id != BPF_FUNC_sk_redirect_hash &&
5227 func_id != BPF_FUNC_sock_hash_update &&
5228 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005229 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005230 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005231 func_id != BPF_FUNC_map_lookup_elem &&
5232 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07005233 goto error;
5234 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005235 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5236 if (func_id != BPF_FUNC_sk_select_reuseport)
5237 goto error;
5238 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005239 case BPF_MAP_TYPE_QUEUE:
5240 case BPF_MAP_TYPE_STACK:
5241 if (func_id != BPF_FUNC_map_peek_elem &&
5242 func_id != BPF_FUNC_map_pop_elem &&
5243 func_id != BPF_FUNC_map_push_elem)
5244 goto error;
5245 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005246 case BPF_MAP_TYPE_SK_STORAGE:
5247 if (func_id != BPF_FUNC_sk_storage_get &&
5248 func_id != BPF_FUNC_sk_storage_delete)
5249 goto error;
5250 break;
KP Singh8ea63682020-08-25 20:29:17 +02005251 case BPF_MAP_TYPE_INODE_STORAGE:
5252 if (func_id != BPF_FUNC_inode_storage_get &&
5253 func_id != BPF_FUNC_inode_storage_delete)
5254 goto error;
5255 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005256 case BPF_MAP_TYPE_TASK_STORAGE:
5257 if (func_id != BPF_FUNC_task_storage_get &&
5258 func_id != BPF_FUNC_task_storage_delete)
5259 goto error;
5260 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005261 default:
5262 break;
5263 }
5264
5265 /* ... and second from the function itself. */
5266 switch (func_id) {
5267 case BPF_FUNC_tail_call:
5268 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5269 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005270 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5271 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005272 return -EINVAL;
5273 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005274 break;
5275 case BPF_FUNC_perf_event_read:
5276 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07005277 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005278 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005279 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005280 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5281 goto error;
5282 break;
5283 case BPF_FUNC_get_stackid:
5284 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5285 goto error;
5286 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005287 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02005288 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005289 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5290 goto error;
5291 break;
John Fastabend97f91a72017-07-17 09:29:18 -07005292 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02005293 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005294 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005295 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5296 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07005297 goto error;
5298 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005299 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07005300 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07005301 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07005302 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5303 goto error;
5304 break;
John Fastabend81110382018-05-14 10:00:17 -07005305 case BPF_FUNC_sk_redirect_hash:
5306 case BPF_FUNC_msg_redirect_hash:
5307 case BPF_FUNC_sock_hash_update:
5308 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07005309 goto error;
5310 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005311 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00005312 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5313 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07005314 goto error;
5315 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005316 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005317 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5318 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5319 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005320 goto error;
5321 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005322 case BPF_FUNC_map_peek_elem:
5323 case BPF_FUNC_map_pop_elem:
5324 case BPF_FUNC_map_push_elem:
5325 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5326 map->map_type != BPF_MAP_TYPE_STACK)
5327 goto error;
5328 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005329 case BPF_FUNC_sk_storage_get:
5330 case BPF_FUNC_sk_storage_delete:
5331 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5332 goto error;
5333 break;
KP Singh8ea63682020-08-25 20:29:17 +02005334 case BPF_FUNC_inode_storage_get:
5335 case BPF_FUNC_inode_storage_delete:
5336 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5337 goto error;
5338 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005339 case BPF_FUNC_task_storage_get:
5340 case BPF_FUNC_task_storage_delete:
5341 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5342 goto error;
5343 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005344 default:
5345 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005346 }
5347
5348 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005349error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005350 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005351 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005352 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005353}
5354
Daniel Borkmann90133412018-01-20 01:24:29 +01005355static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005356{
5357 int count = 0;
5358
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005359 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005360 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005361 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005362 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005363 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005364 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005365 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005366 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005367 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005368 count++;
5369
Daniel Borkmann90133412018-01-20 01:24:29 +01005370 /* We only support one arg being in raw mode at the moment,
5371 * which is sufficient for the helper functions we have
5372 * right now.
5373 */
5374 return count <= 1;
5375}
5376
5377static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5378 enum bpf_arg_type arg_next)
5379{
5380 return (arg_type_is_mem_ptr(arg_curr) &&
5381 !arg_type_is_mem_size(arg_next)) ||
5382 (!arg_type_is_mem_ptr(arg_curr) &&
5383 arg_type_is_mem_size(arg_next));
5384}
5385
5386static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5387{
5388 /* bpf_xxx(..., buf, len) call will access 'len'
5389 * bytes from memory 'buf'. Both arg types need
5390 * to be paired, so make sure there's no buggy
5391 * helper function specification.
5392 */
5393 if (arg_type_is_mem_size(fn->arg1_type) ||
5394 arg_type_is_mem_ptr(fn->arg5_type) ||
5395 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5396 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5397 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5398 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5399 return false;
5400
5401 return true;
5402}
5403
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005404static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005405{
5406 int count = 0;
5407
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005408 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005409 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005410 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005411 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005412 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005413 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005414 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005415 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005416 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005417 count++;
5418
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005419 /* A reference acquiring function cannot acquire
5420 * another refcounted ptr.
5421 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005422 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005423 return false;
5424
Joe Stringerfd978bf72018-10-02 13:35:35 -07005425 /* We only support one arg being unreferenced at the moment,
5426 * which is sufficient for the helper functions we have right now.
5427 */
5428 return count <= 1;
5429}
5430
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005431static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5432{
5433 int i;
5434
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005435 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005436 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5437 return false;
5438
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005439 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5440 return false;
5441 }
5442
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005443 return true;
5444}
5445
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005446static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005447{
5448 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005449 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005450 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005451 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005452}
5453
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005454/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5455 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005456 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005457static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5458 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005459{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005460 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005461 int i;
5462
5463 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005464 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005465 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005466
Joe Stringerf3709f62018-10-02 13:35:29 -07005467 bpf_for_each_spilled_reg(i, state, reg) {
5468 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005469 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005470 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005471 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005472 }
5473}
5474
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005475static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5476{
5477 struct bpf_verifier_state *vstate = env->cur_state;
5478 int i;
5479
5480 for (i = 0; i <= vstate->curframe; i++)
5481 __clear_all_pkt_pointers(env, vstate->frame[i]);
5482}
5483
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005484enum {
5485 AT_PKT_END = -1,
5486 BEYOND_PKT_END = -2,
5487};
5488
5489static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5490{
5491 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5492 struct bpf_reg_state *reg = &state->regs[regn];
5493
5494 if (reg->type != PTR_TO_PACKET)
5495 /* PTR_TO_PACKET_META is not supported yet */
5496 return;
5497
5498 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5499 * How far beyond pkt_end it goes is unknown.
5500 * if (!range_open) it's the case of pkt >= pkt_end
5501 * if (range_open) it's the case of pkt > pkt_end
5502 * hence this pointer is at least 1 byte bigger than pkt_end
5503 */
5504 if (range_open)
5505 reg->range = BEYOND_PKT_END;
5506 else
5507 reg->range = AT_PKT_END;
5508}
5509
Joe Stringerfd978bf72018-10-02 13:35:35 -07005510static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005511 struct bpf_func_state *state,
5512 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005513{
5514 struct bpf_reg_state *regs = state->regs, *reg;
5515 int i;
5516
5517 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005518 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005519 mark_reg_unknown(env, regs, i);
5520
5521 bpf_for_each_spilled_reg(i, state, reg) {
5522 if (!reg)
5523 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005524 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005525 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005526 }
5527}
5528
5529/* The pointer with the specified id has released its reference to kernel
5530 * resources. Identify all copies of the same pointer and clear the reference.
5531 */
5532static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005533 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005534{
5535 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005536 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005537 int i;
5538
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005539 err = release_reference_state(cur_func(env), ref_obj_id);
5540 if (err)
5541 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005542
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005543 for (i = 0; i <= vstate->curframe; i++)
5544 release_reg_references(env, vstate->frame[i], ref_obj_id);
5545
5546 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005547}
5548
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005549static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5550 struct bpf_reg_state *regs)
5551{
5552 int i;
5553
5554 /* after the call registers r0 - r5 were scratched */
5555 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5556 mark_reg_not_init(env, regs, caller_saved[i]);
5557 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5558 }
5559}
5560
Yonghong Song14351372021-02-26 12:49:23 -08005561typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5562 struct bpf_func_state *caller,
5563 struct bpf_func_state *callee,
5564 int insn_idx);
5565
5566static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5567 int *insn_idx, int subprog,
5568 set_callee_state_fn set_callee_state_cb)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005569{
5570 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005571 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005572 struct bpf_func_state *caller, *callee;
Yonghong Song14351372021-02-26 12:49:23 -08005573 int err;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005574 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005575
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005576 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005577 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005578 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005579 return -E2BIG;
5580 }
5581
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005582 caller = state->frame[state->curframe];
5583 if (state->frame[state->curframe + 1]) {
5584 verbose(env, "verifier bug. Frame %d already allocated\n",
5585 state->curframe + 1);
5586 return -EFAULT;
5587 }
5588
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005589 func_info_aux = env->prog->aux->func_info_aux;
5590 if (func_info_aux)
5591 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
Martin KaFai Lau34747c42021-03-24 18:51:36 -07005592 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005593 if (err == -EFAULT)
5594 return err;
5595 if (is_global) {
5596 if (err) {
5597 verbose(env, "Caller passes invalid args into func#%d\n",
5598 subprog);
5599 return err;
5600 } else {
5601 if (env->log.level & BPF_LOG_LEVEL)
5602 verbose(env,
5603 "Func#%d is global and valid. Skipping.\n",
5604 subprog);
5605 clear_caller_saved_regs(env, caller->regs);
5606
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005607 /* All global functions return a 64-bit SCALAR_VALUE */
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005608 mark_reg_unknown(env, caller->regs, BPF_REG_0);
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005609 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005610
5611 /* continue with next insn after call */
5612 return 0;
5613 }
5614 }
5615
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005616 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5617 if (!callee)
5618 return -ENOMEM;
5619 state->frame[state->curframe + 1] = callee;
5620
5621 /* callee cannot access r0, r6 - r9 for reading and has to write
5622 * into its own stack before reading from it.
5623 * callee can read/write into caller's stack
5624 */
5625 init_func_state(env, callee,
5626 /* remember the callsite, it will be used by bpf_exit */
5627 *insn_idx /* callsite */,
5628 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04005629 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005630
Joe Stringerfd978bf72018-10-02 13:35:35 -07005631 /* Transfer references to the callee */
5632 err = transfer_reference_state(callee, caller);
5633 if (err)
5634 return err;
5635
Yonghong Song14351372021-02-26 12:49:23 -08005636 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5637 if (err)
5638 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005639
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005640 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005641
5642 /* only increment it after check_reg_arg() finished */
5643 state->curframe++;
5644
5645 /* and go analyze first insn of the callee */
Yonghong Song14351372021-02-26 12:49:23 -08005646 *insn_idx = env->subprog_info[subprog].start - 1;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005647
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005648 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005649 verbose(env, "caller:\n");
5650 print_verifier_state(env, caller);
5651 verbose(env, "callee:\n");
5652 print_verifier_state(env, callee);
5653 }
5654 return 0;
5655}
5656
Yonghong Song314ee052021-02-26 12:49:27 -08005657int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5658 struct bpf_func_state *caller,
5659 struct bpf_func_state *callee)
5660{
5661 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5662 * void *callback_ctx, u64 flags);
5663 * callback_fn(struct bpf_map *map, void *key, void *value,
5664 * void *callback_ctx);
5665 */
5666 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5667
5668 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5669 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5670 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5671
5672 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5673 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5674 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5675
5676 /* pointer to stack or null */
5677 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5678
5679 /* unused */
5680 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5681 return 0;
5682}
5683
Yonghong Song14351372021-02-26 12:49:23 -08005684static int set_callee_state(struct bpf_verifier_env *env,
5685 struct bpf_func_state *caller,
5686 struct bpf_func_state *callee, int insn_idx)
5687{
5688 int i;
5689
5690 /* copy r1 - r5 args that callee can access. The copy includes parent
5691 * pointers, which connects us up to the liveness chain
5692 */
5693 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5694 callee->regs[i] = caller->regs[i];
5695 return 0;
5696}
5697
5698static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5699 int *insn_idx)
5700{
5701 int subprog, target_insn;
5702
5703 target_insn = *insn_idx + insn->imm + 1;
5704 subprog = find_subprog(env, target_insn);
5705 if (subprog < 0) {
5706 verbose(env, "verifier bug. No program starts at insn %d\n",
5707 target_insn);
5708 return -EFAULT;
5709 }
5710
5711 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5712}
5713
Yonghong Song69c087b2021-02-26 12:49:25 -08005714static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5715 struct bpf_func_state *caller,
5716 struct bpf_func_state *callee,
5717 int insn_idx)
5718{
5719 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5720 struct bpf_map *map;
5721 int err;
5722
5723 if (bpf_map_ptr_poisoned(insn_aux)) {
5724 verbose(env, "tail_call abusing map_ptr\n");
5725 return -EINVAL;
5726 }
5727
5728 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5729 if (!map->ops->map_set_for_each_callback_args ||
5730 !map->ops->map_for_each_callback) {
5731 verbose(env, "callback function not allowed for map\n");
5732 return -ENOTSUPP;
5733 }
5734
5735 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5736 if (err)
5737 return err;
5738
5739 callee->in_callback_fn = true;
5740 return 0;
5741}
5742
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005743static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5744{
5745 struct bpf_verifier_state *state = env->cur_state;
5746 struct bpf_func_state *caller, *callee;
5747 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005748 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005749
5750 callee = state->frame[state->curframe];
5751 r0 = &callee->regs[BPF_REG_0];
5752 if (r0->type == PTR_TO_STACK) {
5753 /* technically it's ok to return caller's stack pointer
5754 * (or caller's caller's pointer) back to the caller,
5755 * since these pointers are valid. Only current stack
5756 * pointer will be invalid as soon as function exits,
5757 * but let's be conservative
5758 */
5759 verbose(env, "cannot return stack pointer to the caller\n");
5760 return -EINVAL;
5761 }
5762
5763 state->curframe--;
5764 caller = state->frame[state->curframe];
Yonghong Song69c087b2021-02-26 12:49:25 -08005765 if (callee->in_callback_fn) {
5766 /* enforce R0 return value range [0, 1]. */
5767 struct tnum range = tnum_range(0, 1);
5768
5769 if (r0->type != SCALAR_VALUE) {
5770 verbose(env, "R0 not a scalar value\n");
5771 return -EACCES;
5772 }
5773 if (!tnum_in(range, r0->var_off)) {
5774 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5775 return -EINVAL;
5776 }
5777 } else {
5778 /* return to the caller whatever r0 had in the callee */
5779 caller->regs[BPF_REG_0] = *r0;
5780 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005781
Joe Stringerfd978bf72018-10-02 13:35:35 -07005782 /* Transfer references to the caller */
5783 err = transfer_reference_state(caller, callee);
5784 if (err)
5785 return err;
5786
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005787 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005788 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005789 verbose(env, "returning from callee:\n");
5790 print_verifier_state(env, callee);
5791 verbose(env, "to caller at %d:\n", *insn_idx);
5792 print_verifier_state(env, caller);
5793 }
5794 /* clear everything in the callee */
5795 free_func_state(callee);
5796 state->frame[state->curframe + 1] = NULL;
5797 return 0;
5798}
5799
Yonghong Song849fa502018-04-28 22:28:09 -07005800static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5801 int func_id,
5802 struct bpf_call_arg_meta *meta)
5803{
5804 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5805
5806 if (ret_type != RET_INTEGER ||
5807 (func_id != BPF_FUNC_get_stack &&
Dave Marchevskyfd0b88f2021-04-16 13:47:02 -07005808 func_id != BPF_FUNC_get_task_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02005809 func_id != BPF_FUNC_probe_read_str &&
5810 func_id != BPF_FUNC_probe_read_kernel_str &&
5811 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07005812 return;
5813
John Fastabend10060502020-03-30 14:36:19 -07005814 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07005815 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01005816 ret_reg->smin_value = -MAX_ERRNO;
5817 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07005818 __reg_deduce_bounds(ret_reg);
5819 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07005820 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07005821}
5822
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005823static int
5824record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5825 int func_id, int insn_idx)
5826{
5827 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02005828 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005829
5830 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02005831 func_id != BPF_FUNC_map_lookup_elem &&
5832 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005833 func_id != BPF_FUNC_map_delete_elem &&
5834 func_id != BPF_FUNC_map_push_elem &&
5835 func_id != BPF_FUNC_map_pop_elem &&
Yonghong Song69c087b2021-02-26 12:49:25 -08005836 func_id != BPF_FUNC_map_peek_elem &&
Björn Töpele6a47502021-03-08 12:29:06 +01005837 func_id != BPF_FUNC_for_each_map_elem &&
5838 func_id != BPF_FUNC_redirect_map)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005839 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02005840
Daniel Borkmann591fe982019-04-09 23:20:05 +02005841 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005842 verbose(env, "kernel subsystem misconfigured verifier\n");
5843 return -EINVAL;
5844 }
5845
Daniel Borkmann591fe982019-04-09 23:20:05 +02005846 /* In case of read-only, some additional restrictions
5847 * need to be applied in order to prevent altering the
5848 * state of the map from program side.
5849 */
5850 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5851 (func_id == BPF_FUNC_map_delete_elem ||
5852 func_id == BPF_FUNC_map_update_elem ||
5853 func_id == BPF_FUNC_map_push_elem ||
5854 func_id == BPF_FUNC_map_pop_elem)) {
5855 verbose(env, "write into map forbidden\n");
5856 return -EACCES;
5857 }
5858
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005859 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005860 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005861 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005862 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005863 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005864 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005865 return 0;
5866}
5867
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005868static int
5869record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5870 int func_id, int insn_idx)
5871{
5872 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5873 struct bpf_reg_state *regs = cur_regs(env), *reg;
5874 struct bpf_map *map = meta->map_ptr;
5875 struct tnum range;
5876 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005877 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005878
5879 if (func_id != BPF_FUNC_tail_call)
5880 return 0;
5881 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5882 verbose(env, "kernel subsystem misconfigured verifier\n");
5883 return -EINVAL;
5884 }
5885
5886 range = tnum_range(0, map->max_entries - 1);
5887 reg = &regs[BPF_REG_3];
5888
5889 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5890 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5891 return 0;
5892 }
5893
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005894 err = mark_chain_precision(env, BPF_REG_3);
5895 if (err)
5896 return err;
5897
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005898 val = reg->var_off.value;
5899 if (bpf_map_key_unseen(aux))
5900 bpf_map_key_store(aux, val);
5901 else if (!bpf_map_key_poisoned(aux) &&
5902 bpf_map_key_immediate(aux) != val)
5903 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5904 return 0;
5905}
5906
Joe Stringerfd978bf72018-10-02 13:35:35 -07005907static int check_reference_leak(struct bpf_verifier_env *env)
5908{
5909 struct bpf_func_state *state = cur_func(env);
5910 int i;
5911
5912 for (i = 0; i < state->acquired_refs; i++) {
5913 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5914 state->refs[i].id, state->refs[i].insn_idx);
5915 }
5916 return state->acquired_refs ? -EINVAL : 0;
5917}
5918
Florent Revest7b155232021-04-19 17:52:40 +02005919static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5920 struct bpf_reg_state *regs)
5921{
5922 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5923 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5924 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5925 int err, fmt_map_off, num_args;
5926 u64 fmt_addr;
5927 char *fmt;
5928
5929 /* data must be an array of u64 */
5930 if (data_len_reg->var_off.value % 8)
5931 return -EINVAL;
5932 num_args = data_len_reg->var_off.value / 8;
5933
5934 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5935 * and map_direct_value_addr is set.
5936 */
5937 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5938 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5939 fmt_map_off);
Florent Revest8e8ee102021-04-23 01:55:42 +02005940 if (err) {
5941 verbose(env, "verifier bug\n");
5942 return -EFAULT;
5943 }
Florent Revest7b155232021-04-19 17:52:40 +02005944 fmt = (char *)(long)fmt_addr + fmt_map_off;
5945
5946 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5947 * can focus on validating the format specifiers.
5948 */
Florent Revest48cac3f2021-04-27 19:43:13 +02005949 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
Florent Revest7b155232021-04-19 17:52:40 +02005950 if (err < 0)
5951 verbose(env, "Invalid format string\n");
5952
5953 return err;
5954}
5955
Yonghong Song69c087b2021-02-26 12:49:25 -08005956static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5957 int *insn_idx_p)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005958{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005959 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005960 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005961 struct bpf_call_arg_meta meta;
Yonghong Song69c087b2021-02-26 12:49:25 -08005962 int insn_idx = *insn_idx_p;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005963 bool changes_data;
Yonghong Song69c087b2021-02-26 12:49:25 -08005964 int i, err, func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005965
5966 /* find function prototype */
Yonghong Song69c087b2021-02-26 12:49:25 -08005967 func_id = insn->imm;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005968 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005969 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5970 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005971 return -EINVAL;
5972 }
5973
Jakub Kicinski00176a32017-10-16 16:40:54 -07005974 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07005975 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005976 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005977 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5978 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005979 return -EINVAL;
5980 }
5981
5982 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01005983 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02005984 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005985 return -EINVAL;
5986 }
5987
Jiri Olsaeae2e832020-08-25 21:21:19 +02005988 if (fn->allowed && !fn->allowed(env->prog)) {
5989 verbose(env, "helper call is not allowed in probe\n");
5990 return -EINVAL;
5991 }
5992
Daniel Borkmann04514d12017-12-14 21:07:25 +01005993 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08005994 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01005995 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5996 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5997 func_id_name(func_id), func_id);
5998 return -EINVAL;
5999 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006000
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006001 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02006002 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006003
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006004 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006005 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006006 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02006007 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006008 return err;
6009 }
6010
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08006011 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006012 /* check args */
Dmitrii Banshchikov523a4cf2021-02-26 00:26:29 +04006013 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07006014 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07006015 if (err)
6016 return err;
6017 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006018
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006019 err = record_func_map(env, &meta, func_id, insn_idx);
6020 if (err)
6021 return err;
6022
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006023 err = record_func_key(env, &meta, func_id, insn_idx);
6024 if (err)
6025 return err;
6026
Daniel Borkmann435faee12016-04-13 00:10:51 +02006027 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6028 * is inferred from register state.
6029 */
6030 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01006031 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6032 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006033 if (err)
6034 return err;
6035 }
6036
Joe Stringerfd978bf72018-10-02 13:35:35 -07006037 if (func_id == BPF_FUNC_tail_call) {
6038 err = check_reference_leak(env);
6039 if (err) {
6040 verbose(env, "tail_call would lead to reference leak\n");
6041 return err;
6042 }
6043 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006044 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006045 if (err) {
6046 verbose(env, "func %s#%d reference has not been acquired before\n",
6047 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07006048 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006049 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07006050 }
6051
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006052 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07006053
6054 /* check that flags argument in get_local_storage(map, flags) is 0,
6055 * this is required because get_local_storage() can't return an error.
6056 */
6057 if (func_id == BPF_FUNC_get_local_storage &&
6058 !register_is_null(&regs[BPF_REG_2])) {
6059 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6060 return -EINVAL;
6061 }
6062
Yonghong Song69c087b2021-02-26 12:49:25 -08006063 if (func_id == BPF_FUNC_for_each_map_elem) {
6064 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6065 set_map_elem_callback_state);
6066 if (err < 0)
6067 return -EINVAL;
6068 }
6069
Florent Revest7b155232021-04-19 17:52:40 +02006070 if (func_id == BPF_FUNC_snprintf) {
6071 err = check_bpf_snprintf_call(env, regs);
6072 if (err < 0)
6073 return err;
6074 }
6075
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006076 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01006077 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006078 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01006079 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6080 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006081
Jiong Wang5327ed32019-05-24 23:25:12 +01006082 /* helper call returns 64-bit value. */
6083 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6084
Edward Creedc503a82017-08-15 20:34:35 +01006085 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006086 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01006087 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006088 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006089 } else if (fn->ret_type == RET_VOID) {
6090 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07006091 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6092 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01006093 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006094 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006095 /* remember map_ptr, so that check_map_access()
6096 * can check 'value_size' boundary of memory access
6097 * to map element returned from bpf_map_lookup_elem()
6098 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006099 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006100 verbose(env,
6101 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006102 return -EINVAL;
6103 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006104 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006105 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6106 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08006107 if (map_value_has_spin_lock(meta.map_ptr))
6108 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006109 } else {
6110 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006111 }
Joe Stringerc64b7982018-10-02 13:35:33 -07006112 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6113 mark_reg_known_zero(env, regs, BPF_REG_0);
6114 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08006115 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6116 mark_reg_known_zero(env, regs, BPF_REG_0);
6117 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006118 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6119 mark_reg_known_zero(env, regs, BPF_REG_0);
6120 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07006121 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6122 mark_reg_known_zero(env, regs, BPF_REG_0);
6123 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07006124 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07006125 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6126 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006127 const struct btf_type *t;
6128
6129 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006130 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006131 if (!btf_type_is_struct(t)) {
6132 u32 tsize;
6133 const struct btf_type *ret;
6134 const char *tname;
6135
6136 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006137 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006138 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006139 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006140 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6141 tname, PTR_ERR(ret));
6142 return -EINVAL;
6143 }
Hao Luo63d9b802020-09-29 16:50:48 -07006144 regs[BPF_REG_0].type =
6145 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6146 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006147 regs[BPF_REG_0].mem_size = tsize;
6148 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07006149 regs[BPF_REG_0].type =
6150 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6151 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006152 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006153 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6154 }
KP Singh3ca10322020-11-06 10:37:43 +00006155 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6156 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07006157 int ret_btf_id;
6158
6159 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00006160 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6161 PTR_TO_BTF_ID :
6162 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006163 ret_btf_id = *fn->ret_btf_id;
6164 if (ret_btf_id == 0) {
6165 verbose(env, "invalid return type %d of func %s#%d\n",
6166 fn->ret_type, func_id_name(func_id), func_id);
6167 return -EINVAL;
6168 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006169 /* current BPF helper definitions are only coming from
6170 * built-in code with type IDs from vmlinux BTF
6171 */
6172 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006173 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006174 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006175 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02006176 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006177 return -EINVAL;
6178 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006179
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07006180 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6181 regs[BPF_REG_0].id = ++env->id_gen;
6182
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006183 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006184 /* For release_reference() */
6185 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02006186 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006187 int id = acquire_reference_state(env, insn_idx);
6188
6189 if (id < 0)
6190 return id;
6191 /* For mark_ptr_or_null_reg() */
6192 regs[BPF_REG_0].id = id;
6193 /* For release_reference() */
6194 regs[BPF_REG_0].ref_obj_id = id;
6195 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006196
Yonghong Song849fa502018-04-28 22:28:09 -07006197 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6198
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006199 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00006200 if (err)
6201 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006202
Song Liufa28dcb2020-06-29 23:28:44 -07006203 if ((func_id == BPF_FUNC_get_stack ||
6204 func_id == BPF_FUNC_get_task_stack) &&
6205 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07006206 const char *err_str;
6207
6208#ifdef CONFIG_PERF_EVENTS
6209 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6210 err_str = "cannot get callchain buffer for func %s#%d\n";
6211#else
6212 err = -ENOTSUPP;
6213 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6214#endif
6215 if (err) {
6216 verbose(env, err_str, func_id_name(func_id), func_id);
6217 return err;
6218 }
6219
6220 env->prog->has_callchain_buf = true;
6221 }
6222
Song Liu5d99cb2c2020-07-23 11:06:45 -07006223 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6224 env->prog->call_get_stack = true;
6225
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006226 if (changes_data)
6227 clear_all_pkt_pointers(env);
6228 return 0;
6229}
6230
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006231/* mark_btf_func_reg_size() is used when the reg size is determined by
6232 * the BTF func_proto's return value size and argument.
6233 */
6234static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6235 size_t reg_size)
6236{
6237 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6238
6239 if (regno == BPF_REG_0) {
6240 /* Function return value */
6241 reg->live |= REG_LIVE_WRITTEN;
6242 reg->subreg_def = reg_size == sizeof(u64) ?
6243 DEF_NOT_SUBREG : env->insn_idx + 1;
6244 } else {
6245 /* Function argument */
6246 if (reg_size == sizeof(u64)) {
6247 mark_insn_zext(env, reg);
6248 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6249 } else {
6250 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6251 }
6252 }
6253}
6254
6255static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6256{
6257 const struct btf_type *t, *func, *func_proto, *ptr_type;
6258 struct bpf_reg_state *regs = cur_regs(env);
6259 const char *func_name, *ptr_type_name;
6260 u32 i, nargs, func_id, ptr_type_id;
6261 const struct btf_param *args;
6262 int err;
6263
6264 func_id = insn->imm;
6265 func = btf_type_by_id(btf_vmlinux, func_id);
6266 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6267 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6268
6269 if (!env->ops->check_kfunc_call ||
6270 !env->ops->check_kfunc_call(func_id)) {
6271 verbose(env, "calling kernel function %s is not allowed\n",
6272 func_name);
6273 return -EACCES;
6274 }
6275
6276 /* Check the arguments */
6277 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6278 if (err)
6279 return err;
6280
6281 for (i = 0; i < CALLER_SAVED_REGS; i++)
6282 mark_reg_not_init(env, regs, caller_saved[i]);
6283
6284 /* Check return type */
6285 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6286 if (btf_type_is_scalar(t)) {
6287 mark_reg_unknown(env, regs, BPF_REG_0);
6288 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6289 } else if (btf_type_is_ptr(t)) {
6290 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6291 &ptr_type_id);
6292 if (!btf_type_is_struct(ptr_type)) {
6293 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6294 ptr_type->name_off);
6295 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6296 func_name, btf_type_str(ptr_type),
6297 ptr_type_name);
6298 return -EINVAL;
6299 }
6300 mark_reg_known_zero(env, regs, BPF_REG_0);
6301 regs[BPF_REG_0].btf = btf_vmlinux;
6302 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6303 regs[BPF_REG_0].btf_id = ptr_type_id;
6304 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6305 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6306
6307 nargs = btf_type_vlen(func_proto);
6308 args = (const struct btf_param *)(func_proto + 1);
6309 for (i = 0; i < nargs; i++) {
6310 u32 regno = i + 1;
6311
6312 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6313 if (btf_type_is_ptr(t))
6314 mark_btf_func_reg_size(env, regno, sizeof(void *));
6315 else
6316 /* scalar. ensured by btf_check_kfunc_arg_match() */
6317 mark_btf_func_reg_size(env, regno, t->size);
6318 }
6319
6320 return 0;
6321}
6322
Edward Creeb03c9f92017-08-07 15:26:36 +01006323static bool signed_add_overflows(s64 a, s64 b)
6324{
6325 /* Do the add in u64, where overflow is well-defined */
6326 s64 res = (s64)((u64)a + (u64)b);
6327
6328 if (b < 0)
6329 return res > a;
6330 return res < a;
6331}
6332
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006333static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07006334{
6335 /* Do the add in u32, where overflow is well-defined */
6336 s32 res = (s32)((u32)a + (u32)b);
6337
6338 if (b < 0)
6339 return res > a;
6340 return res < a;
6341}
6342
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006343static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01006344{
6345 /* Do the sub in u64, where overflow is well-defined */
6346 s64 res = (s64)((u64)a - (u64)b);
6347
6348 if (b < 0)
6349 return res < a;
6350 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07006351}
6352
John Fastabend3f50f132020-03-30 14:36:39 -07006353static bool signed_sub32_overflows(s32 a, s32 b)
6354{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006355 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07006356 s32 res = (s32)((u32)a - (u32)b);
6357
6358 if (b < 0)
6359 return res < a;
6360 return res > a;
6361}
6362
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006363static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6364 const struct bpf_reg_state *reg,
6365 enum bpf_reg_type type)
6366{
6367 bool known = tnum_is_const(reg->var_off);
6368 s64 val = reg->var_off.value;
6369 s64 smin = reg->smin_value;
6370
6371 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6372 verbose(env, "math between %s pointer and %lld is not allowed\n",
6373 reg_type_str[type], val);
6374 return false;
6375 }
6376
6377 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6378 verbose(env, "%s pointer offset %d is not allowed\n",
6379 reg_type_str[type], reg->off);
6380 return false;
6381 }
6382
6383 if (smin == S64_MIN) {
6384 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6385 reg_type_str[type]);
6386 return false;
6387 }
6388
6389 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6390 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6391 smin, reg_type_str[type]);
6392 return false;
6393 }
6394
6395 return true;
6396}
6397
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006398static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6399{
6400 return &env->insn_aux_data[env->insn_idx];
6401}
6402
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006403enum {
6404 REASON_BOUNDS = -1,
6405 REASON_TYPE = -2,
6406 REASON_PATHS = -3,
6407 REASON_LIMIT = -4,
6408 REASON_STACK = -5,
6409};
6410
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006411static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006412 u32 *alu_limit, bool mask_to_left)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006413{
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006414 u32 max = 0, ptr_limit = 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006415
6416 switch (ptr_reg->type) {
6417 case PTR_TO_STACK:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006418 /* Offset 0 is out-of-bounds, but acceptable start for the
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006419 * left direction, see BPF_REG_FP. Also, unknown scalar
6420 * offset where we would need to deal with min/max bounds is
6421 * currently prohibited for unprivileged.
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006422 */
6423 max = MAX_BPF_STACK + mask_to_left;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006424 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006425 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006426 case PTR_TO_MAP_VALUE:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006427 max = ptr_reg->map_ptr->value_size;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006428 ptr_limit = (mask_to_left ?
6429 ptr_reg->smin_value :
6430 ptr_reg->umax_value) + ptr_reg->off;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006431 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006432 default:
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006433 return REASON_TYPE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006434 }
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006435
6436 if (ptr_limit >= max)
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006437 return REASON_LIMIT;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006438 *alu_limit = ptr_limit;
6439 return 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006440}
6441
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006442static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6443 const struct bpf_insn *insn)
6444{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006445 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006446}
6447
6448static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6449 u32 alu_state, u32 alu_limit)
6450{
6451 /* If we arrived here from different branches with different
6452 * state or limits to sanitize, then this won't work.
6453 */
6454 if (aux->alu_state &&
6455 (aux->alu_state != alu_state ||
6456 aux->alu_limit != alu_limit))
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006457 return REASON_PATHS;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006458
Brendan Jackmane6ac5932021-02-17 10:45:09 +00006459 /* Corresponding fixup done in do_misc_fixups(). */
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006460 aux->alu_state = alu_state;
6461 aux->alu_limit = alu_limit;
6462 return 0;
6463}
6464
6465static int sanitize_val_alu(struct bpf_verifier_env *env,
6466 struct bpf_insn *insn)
6467{
6468 struct bpf_insn_aux_data *aux = cur_aux(env);
6469
6470 if (can_skip_alu_sanitation(env, insn))
6471 return 0;
6472
6473 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6474}
6475
Daniel Borkmannf5288192021-03-24 11:25:39 +01006476static bool sanitize_needed(u8 opcode)
6477{
6478 return opcode == BPF_ADD || opcode == BPF_SUB;
6479}
6480
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006481struct bpf_sanitize_info {
6482 struct bpf_insn_aux_data aux;
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006483 bool mask_to_left;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006484};
6485
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006486static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6487 struct bpf_insn *insn,
6488 const struct bpf_reg_state *ptr_reg,
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01006489 const struct bpf_reg_state *off_reg,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006490 struct bpf_reg_state *dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006491 struct bpf_sanitize_info *info,
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006492 const bool commit_window)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006493{
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006494 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006495 struct bpf_verifier_state *vstate = env->cur_state;
Daniel Borkmann801c6052021-04-29 15:19:37 +00006496 bool off_is_imm = tnum_is_const(off_reg->var_off);
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01006497 bool off_is_neg = off_reg->smin_value < 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006498 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6499 u8 opcode = BPF_OP(insn->code);
6500 u32 alu_state, alu_limit;
6501 struct bpf_reg_state tmp;
6502 bool ret;
Piotr Krysiukf2323262021-03-16 09:47:02 +01006503 int err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006504
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006505 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006506 return 0;
6507
6508 /* We already marked aux for masking from non-speculative
6509 * paths, thus we got here in the first place. We only care
6510 * to explore bad access from here.
6511 */
6512 if (vstate->speculative)
6513 goto do_sim;
6514
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006515 if (!commit_window) {
6516 if (!tnum_is_const(off_reg->var_off) &&
6517 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6518 return REASON_BOUNDS;
6519
6520 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6521 (opcode == BPF_SUB && !off_is_neg);
6522 }
6523
6524 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
Piotr Krysiukf2323262021-03-16 09:47:02 +01006525 if (err < 0)
6526 return err;
6527
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006528 if (commit_window) {
6529 /* In commit phase we narrow the masking window based on
6530 * the observed pointer move after the simulated operation.
6531 */
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006532 alu_state = info->aux.alu_state;
6533 alu_limit = abs(info->aux.alu_limit - alu_limit);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006534 } else {
6535 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
Daniel Borkmann801c6052021-04-29 15:19:37 +00006536 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006537 alu_state |= ptr_is_dst_reg ?
6538 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6539 }
6540
Piotr Krysiukf2323262021-03-16 09:47:02 +01006541 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6542 if (err < 0)
6543 return err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006544do_sim:
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006545 /* If we're in commit phase, we're done here given we already
6546 * pushed the truncated dst_reg into the speculative verification
6547 * stack.
6548 */
6549 if (commit_window)
6550 return 0;
6551
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006552 /* Simulate and find potential out-of-bounds access under
6553 * speculative execution from truncation as a result of
6554 * masking when off was not within expected range. If off
6555 * sits in dst, then we temporarily need to move ptr there
6556 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6557 * for cases where we use K-based arithmetic in one direction
6558 * and truncated reg-based in the other in order to explore
6559 * bad access.
6560 */
6561 if (!ptr_is_dst_reg) {
6562 tmp = *dst_reg;
6563 *dst_reg = *ptr_reg;
6564 }
6565 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08006566 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006567 *dst_reg = tmp;
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006568 return !ret ? REASON_STACK : 0;
6569}
6570
6571static int sanitize_err(struct bpf_verifier_env *env,
6572 const struct bpf_insn *insn, int reason,
6573 const struct bpf_reg_state *off_reg,
6574 const struct bpf_reg_state *dst_reg)
6575{
6576 static const char *err = "pointer arithmetic with it prohibited for !root";
6577 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6578 u32 dst = insn->dst_reg, src = insn->src_reg;
6579
6580 switch (reason) {
6581 case REASON_BOUNDS:
6582 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6583 off_reg == dst_reg ? dst : src, err);
6584 break;
6585 case REASON_TYPE:
6586 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6587 off_reg == dst_reg ? src : dst, err);
6588 break;
6589 case REASON_PATHS:
6590 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6591 dst, op, err);
6592 break;
6593 case REASON_LIMIT:
6594 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6595 dst, op, err);
6596 break;
6597 case REASON_STACK:
6598 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6599 dst, err);
6600 break;
6601 default:
6602 verbose(env, "verifier internal error: unknown reason (%d)\n",
6603 reason);
6604 break;
6605 }
6606
6607 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006608}
6609
Andrei Matei01f810a2021-02-06 20:10:24 -05006610/* check that stack access falls within stack limits and that 'reg' doesn't
6611 * have a variable offset.
6612 *
6613 * Variable offset is prohibited for unprivileged mode for simplicity since it
6614 * requires corresponding support in Spectre masking for stack ALU. See also
6615 * retrieve_ptr_limit().
6616 *
6617 *
6618 * 'off' includes 'reg->off'.
6619 */
6620static int check_stack_access_for_ptr_arithmetic(
6621 struct bpf_verifier_env *env,
6622 int regno,
6623 const struct bpf_reg_state *reg,
6624 int off)
6625{
6626 if (!tnum_is_const(reg->var_off)) {
6627 char tn_buf[48];
6628
6629 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6630 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6631 regno, tn_buf, off);
6632 return -EACCES;
6633 }
6634
6635 if (off >= 0 || off < -MAX_BPF_STACK) {
6636 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6637 "prohibited for !root; off=%d\n", regno, off);
6638 return -EACCES;
6639 }
6640
6641 return 0;
6642}
6643
Daniel Borkmann073815b2021-03-23 15:05:48 +01006644static int sanitize_check_bounds(struct bpf_verifier_env *env,
6645 const struct bpf_insn *insn,
6646 const struct bpf_reg_state *dst_reg)
6647{
6648 u32 dst = insn->dst_reg;
6649
6650 /* For unprivileged we require that resulting offset must be in bounds
6651 * in order to be able to sanitize access later on.
6652 */
6653 if (env->bypass_spec_v1)
6654 return 0;
6655
6656 switch (dst_reg->type) {
6657 case PTR_TO_STACK:
6658 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6659 dst_reg->off + dst_reg->var_off.value))
6660 return -EACCES;
6661 break;
6662 case PTR_TO_MAP_VALUE:
6663 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6664 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6665 "prohibited for !root\n", dst);
6666 return -EACCES;
6667 }
6668 break;
6669 default:
6670 break;
6671 }
6672
6673 return 0;
6674}
Andrei Matei01f810a2021-02-06 20:10:24 -05006675
Edward Creef1174f72017-08-07 15:26:19 +01006676/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01006677 * Caller should also handle BPF_MOV case separately.
6678 * If we return -EACCES, caller may want to try again treating pointer as a
6679 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6680 */
6681static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6682 struct bpf_insn *insn,
6683 const struct bpf_reg_state *ptr_reg,
6684 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04006685{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006686 struct bpf_verifier_state *vstate = env->cur_state;
6687 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6688 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006689 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01006690 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6691 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6692 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6693 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006694 struct bpf_sanitize_info info = {};
Josef Bacik48461132016-09-28 10:54:32 -04006695 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann24c109b2021-03-23 08:51:02 +01006696 u32 dst = insn->dst_reg;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006697 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04006698
Edward Creef1174f72017-08-07 15:26:19 +01006699 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04006700
Daniel Borkmann6f161012018-01-18 01:15:21 +01006701 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6702 smin_val > smax_val || umin_val > umax_val) {
6703 /* Taint dst register if offset had invalid bounds derived from
6704 * e.g. dead branches.
6705 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006706 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01006707 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04006708 }
6709
Edward Creef1174f72017-08-07 15:26:19 +01006710 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6711 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07006712 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6713 __mark_reg_unknown(env, dst_reg);
6714 return 0;
6715 }
6716
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006717 verbose(env,
6718 "R%d 32-bit pointer arithmetic prohibited\n",
6719 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006720 return -EACCES;
6721 }
David S. Millerd1174412017-05-10 11:22:52 -07006722
Joe Stringeraad2eea2018-10-02 13:35:30 -07006723 switch (ptr_reg->type) {
6724 case PTR_TO_MAP_VALUE_OR_NULL:
6725 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6726 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006727 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006728 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07006729 /* smin_val represents the known value */
6730 if (known && smin_val == 0 && opcode == BPF_ADD)
6731 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05006732 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006733 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07006734 case PTR_TO_SOCKET:
6735 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006736 case PTR_TO_SOCK_COMMON:
6737 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006738 case PTR_TO_TCP_SOCK:
6739 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07006740 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07006741 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6742 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006743 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006744 default:
6745 break;
Edward Creef1174f72017-08-07 15:26:19 +01006746 }
6747
6748 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6749 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04006750 */
Edward Creef1174f72017-08-07 15:26:19 +01006751 dst_reg->type = ptr_reg->type;
6752 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05006753
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006754 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6755 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6756 return -EINVAL;
6757
John Fastabend3f50f132020-03-30 14:36:39 -07006758 /* pointer types do not carry 32-bit bounds at the moment. */
6759 __mark_reg32_unbounded(dst_reg);
6760
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006761 if (sanitize_needed(opcode)) {
6762 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006763 &info, false);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006764 if (ret < 0)
6765 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006766 }
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006767
Josef Bacik48461132016-09-28 10:54:32 -04006768 switch (opcode) {
6769 case BPF_ADD:
Edward Creef1174f72017-08-07 15:26:19 +01006770 /* We can take a fixed offset as long as it doesn't overflow
6771 * the s32 'off' field
6772 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006773 if (known && (ptr_reg->off + smin_val ==
6774 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006775 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006776 dst_reg->smin_value = smin_ptr;
6777 dst_reg->smax_value = smax_ptr;
6778 dst_reg->umin_value = umin_ptr;
6779 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006780 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01006781 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006782 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006783 break;
6784 }
Edward Creef1174f72017-08-07 15:26:19 +01006785 /* A new variable offset is created. Note that off_reg->off
6786 * == 0, since it's a scalar.
6787 * dst_reg gets the pointer type and since some positive
6788 * integer value was added to the pointer, give it a new 'id'
6789 * if it's a PTR_TO_PACKET.
6790 * this creates a new 'base' pointer, off_reg (variable) gets
6791 * added into the variable offset, and we copy the fixed offset
6792 * from ptr_reg.
6793 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006794 if (signed_add_overflows(smin_ptr, smin_val) ||
6795 signed_add_overflows(smax_ptr, smax_val)) {
6796 dst_reg->smin_value = S64_MIN;
6797 dst_reg->smax_value = S64_MAX;
6798 } else {
6799 dst_reg->smin_value = smin_ptr + smin_val;
6800 dst_reg->smax_value = smax_ptr + smax_val;
6801 }
6802 if (umin_ptr + umin_val < umin_ptr ||
6803 umax_ptr + umax_val < umax_ptr) {
6804 dst_reg->umin_value = 0;
6805 dst_reg->umax_value = U64_MAX;
6806 } else {
6807 dst_reg->umin_value = umin_ptr + umin_val;
6808 dst_reg->umax_value = umax_ptr + umax_val;
6809 }
Edward Creef1174f72017-08-07 15:26:19 +01006810 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6811 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006812 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006813 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006814 dst_reg->id = ++env->id_gen;
6815 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006816 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006817 }
Josef Bacik48461132016-09-28 10:54:32 -04006818 break;
6819 case BPF_SUB:
Edward Creef1174f72017-08-07 15:26:19 +01006820 if (dst_reg == off_reg) {
6821 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006822 verbose(env, "R%d tried to subtract pointer from scalar\n",
6823 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006824 return -EACCES;
6825 }
6826 /* We don't allow subtraction from FP, because (according to
6827 * test_verifier.c test "invalid fp arithmetic", JITs might not
6828 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01006829 */
Edward Creef1174f72017-08-07 15:26:19 +01006830 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006831 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6832 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006833 return -EACCES;
6834 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006835 if (known && (ptr_reg->off - smin_val ==
6836 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006837 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006838 dst_reg->smin_value = smin_ptr;
6839 dst_reg->smax_value = smax_ptr;
6840 dst_reg->umin_value = umin_ptr;
6841 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006842 dst_reg->var_off = ptr_reg->var_off;
6843 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01006844 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006845 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006846 break;
6847 }
Edward Creef1174f72017-08-07 15:26:19 +01006848 /* A new variable offset is created. If the subtrahend is known
6849 * nonnegative, then any reg->range we had before is still good.
6850 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006851 if (signed_sub_overflows(smin_ptr, smax_val) ||
6852 signed_sub_overflows(smax_ptr, smin_val)) {
6853 /* Overflow possible, we know nothing */
6854 dst_reg->smin_value = S64_MIN;
6855 dst_reg->smax_value = S64_MAX;
6856 } else {
6857 dst_reg->smin_value = smin_ptr - smax_val;
6858 dst_reg->smax_value = smax_ptr - smin_val;
6859 }
6860 if (umin_ptr < umax_val) {
6861 /* Overflow possible, we know nothing */
6862 dst_reg->umin_value = 0;
6863 dst_reg->umax_value = U64_MAX;
6864 } else {
6865 /* Cannot overflow (as long as bounds are consistent) */
6866 dst_reg->umin_value = umin_ptr - umax_val;
6867 dst_reg->umax_value = umax_ptr - umin_val;
6868 }
Edward Creef1174f72017-08-07 15:26:19 +01006869 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6870 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006871 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006872 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006873 dst_reg->id = ++env->id_gen;
6874 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01006875 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006876 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006877 }
6878 break;
6879 case BPF_AND:
6880 case BPF_OR:
6881 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006882 /* bitwise ops on pointers are troublesome, prohibit. */
6883 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6884 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006885 return -EACCES;
6886 default:
6887 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006888 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6889 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006890 return -EACCES;
6891 }
6892
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006893 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6894 return -EINVAL;
6895
Edward Creeb03c9f92017-08-07 15:26:36 +01006896 __update_reg_bounds(dst_reg);
6897 __reg_deduce_bounds(dst_reg);
6898 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006899
Daniel Borkmann073815b2021-03-23 15:05:48 +01006900 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6901 return -EACCES;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006902 if (sanitize_needed(opcode)) {
6903 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006904 &info, true);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006905 if (ret < 0)
6906 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006907 }
6908
Edward Creef1174f72017-08-07 15:26:19 +01006909 return 0;
6910}
6911
John Fastabend3f50f132020-03-30 14:36:39 -07006912static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6913 struct bpf_reg_state *src_reg)
6914{
6915 s32 smin_val = src_reg->s32_min_value;
6916 s32 smax_val = src_reg->s32_max_value;
6917 u32 umin_val = src_reg->u32_min_value;
6918 u32 umax_val = src_reg->u32_max_value;
6919
6920 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6921 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6922 dst_reg->s32_min_value = S32_MIN;
6923 dst_reg->s32_max_value = S32_MAX;
6924 } else {
6925 dst_reg->s32_min_value += smin_val;
6926 dst_reg->s32_max_value += smax_val;
6927 }
6928 if (dst_reg->u32_min_value + umin_val < umin_val ||
6929 dst_reg->u32_max_value + umax_val < umax_val) {
6930 dst_reg->u32_min_value = 0;
6931 dst_reg->u32_max_value = U32_MAX;
6932 } else {
6933 dst_reg->u32_min_value += umin_val;
6934 dst_reg->u32_max_value += umax_val;
6935 }
6936}
6937
John Fastabend07cd2632020-03-24 10:38:15 -07006938static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6939 struct bpf_reg_state *src_reg)
6940{
6941 s64 smin_val = src_reg->smin_value;
6942 s64 smax_val = src_reg->smax_value;
6943 u64 umin_val = src_reg->umin_value;
6944 u64 umax_val = src_reg->umax_value;
6945
6946 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6947 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6948 dst_reg->smin_value = S64_MIN;
6949 dst_reg->smax_value = S64_MAX;
6950 } else {
6951 dst_reg->smin_value += smin_val;
6952 dst_reg->smax_value += smax_val;
6953 }
6954 if (dst_reg->umin_value + umin_val < umin_val ||
6955 dst_reg->umax_value + umax_val < umax_val) {
6956 dst_reg->umin_value = 0;
6957 dst_reg->umax_value = U64_MAX;
6958 } else {
6959 dst_reg->umin_value += umin_val;
6960 dst_reg->umax_value += umax_val;
6961 }
John Fastabend3f50f132020-03-30 14:36:39 -07006962}
6963
6964static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6965 struct bpf_reg_state *src_reg)
6966{
6967 s32 smin_val = src_reg->s32_min_value;
6968 s32 smax_val = src_reg->s32_max_value;
6969 u32 umin_val = src_reg->u32_min_value;
6970 u32 umax_val = src_reg->u32_max_value;
6971
6972 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6973 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6974 /* Overflow possible, we know nothing */
6975 dst_reg->s32_min_value = S32_MIN;
6976 dst_reg->s32_max_value = S32_MAX;
6977 } else {
6978 dst_reg->s32_min_value -= smax_val;
6979 dst_reg->s32_max_value -= smin_val;
6980 }
6981 if (dst_reg->u32_min_value < umax_val) {
6982 /* Overflow possible, we know nothing */
6983 dst_reg->u32_min_value = 0;
6984 dst_reg->u32_max_value = U32_MAX;
6985 } else {
6986 /* Cannot overflow (as long as bounds are consistent) */
6987 dst_reg->u32_min_value -= umax_val;
6988 dst_reg->u32_max_value -= umin_val;
6989 }
John Fastabend07cd2632020-03-24 10:38:15 -07006990}
6991
6992static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6993 struct bpf_reg_state *src_reg)
6994{
6995 s64 smin_val = src_reg->smin_value;
6996 s64 smax_val = src_reg->smax_value;
6997 u64 umin_val = src_reg->umin_value;
6998 u64 umax_val = src_reg->umax_value;
6999
7000 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7001 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7002 /* Overflow possible, we know nothing */
7003 dst_reg->smin_value = S64_MIN;
7004 dst_reg->smax_value = S64_MAX;
7005 } else {
7006 dst_reg->smin_value -= smax_val;
7007 dst_reg->smax_value -= smin_val;
7008 }
7009 if (dst_reg->umin_value < umax_val) {
7010 /* Overflow possible, we know nothing */
7011 dst_reg->umin_value = 0;
7012 dst_reg->umax_value = U64_MAX;
7013 } else {
7014 /* Cannot overflow (as long as bounds are consistent) */
7015 dst_reg->umin_value -= umax_val;
7016 dst_reg->umax_value -= umin_val;
7017 }
John Fastabend3f50f132020-03-30 14:36:39 -07007018}
7019
7020static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7021 struct bpf_reg_state *src_reg)
7022{
7023 s32 smin_val = src_reg->s32_min_value;
7024 u32 umin_val = src_reg->u32_min_value;
7025 u32 umax_val = src_reg->u32_max_value;
7026
7027 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7028 /* Ain't nobody got time to multiply that sign */
7029 __mark_reg32_unbounded(dst_reg);
7030 return;
7031 }
7032 /* Both values are positive, so we can work with unsigned and
7033 * copy the result to signed (unless it exceeds S32_MAX).
7034 */
7035 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7036 /* Potential overflow, we know nothing */
7037 __mark_reg32_unbounded(dst_reg);
7038 return;
7039 }
7040 dst_reg->u32_min_value *= umin_val;
7041 dst_reg->u32_max_value *= umax_val;
7042 if (dst_reg->u32_max_value > S32_MAX) {
7043 /* Overflow possible, we know nothing */
7044 dst_reg->s32_min_value = S32_MIN;
7045 dst_reg->s32_max_value = S32_MAX;
7046 } else {
7047 dst_reg->s32_min_value = dst_reg->u32_min_value;
7048 dst_reg->s32_max_value = dst_reg->u32_max_value;
7049 }
John Fastabend07cd2632020-03-24 10:38:15 -07007050}
7051
7052static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7053 struct bpf_reg_state *src_reg)
7054{
7055 s64 smin_val = src_reg->smin_value;
7056 u64 umin_val = src_reg->umin_value;
7057 u64 umax_val = src_reg->umax_value;
7058
John Fastabend07cd2632020-03-24 10:38:15 -07007059 if (smin_val < 0 || dst_reg->smin_value < 0) {
7060 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07007061 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007062 return;
7063 }
7064 /* Both values are positive, so we can work with unsigned and
7065 * copy the result to signed (unless it exceeds S64_MAX).
7066 */
7067 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7068 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07007069 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007070 return;
7071 }
7072 dst_reg->umin_value *= umin_val;
7073 dst_reg->umax_value *= umax_val;
7074 if (dst_reg->umax_value > S64_MAX) {
7075 /* Overflow possible, we know nothing */
7076 dst_reg->smin_value = S64_MIN;
7077 dst_reg->smax_value = S64_MAX;
7078 } else {
7079 dst_reg->smin_value = dst_reg->umin_value;
7080 dst_reg->smax_value = dst_reg->umax_value;
7081 }
7082}
7083
John Fastabend3f50f132020-03-30 14:36:39 -07007084static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7085 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007086{
John Fastabend3f50f132020-03-30 14:36:39 -07007087 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7088 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7089 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7090 s32 smin_val = src_reg->s32_min_value;
7091 u32 umax_val = src_reg->u32_max_value;
7092
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007093 if (src_known && dst_known) {
7094 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007095 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007096 }
John Fastabend07cd2632020-03-24 10:38:15 -07007097
7098 /* We get our minimum from the var_off, since that's inherently
7099 * bitwise. Our maximum is the minimum of the operands' maxima.
7100 */
John Fastabend3f50f132020-03-30 14:36:39 -07007101 dst_reg->u32_min_value = var32_off.value;
7102 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7103 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7104 /* Lose signed bounds when ANDing negative numbers,
7105 * ain't nobody got time for that.
7106 */
7107 dst_reg->s32_min_value = S32_MIN;
7108 dst_reg->s32_max_value = S32_MAX;
7109 } else {
7110 /* ANDing two positives gives a positive, so safe to
7111 * cast result into s64.
7112 */
7113 dst_reg->s32_min_value = dst_reg->u32_min_value;
7114 dst_reg->s32_max_value = dst_reg->u32_max_value;
7115 }
John Fastabend3f50f132020-03-30 14:36:39 -07007116}
7117
7118static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7119 struct bpf_reg_state *src_reg)
7120{
7121 bool src_known = tnum_is_const(src_reg->var_off);
7122 bool dst_known = tnum_is_const(dst_reg->var_off);
7123 s64 smin_val = src_reg->smin_value;
7124 u64 umax_val = src_reg->umax_value;
7125
7126 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007127 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007128 return;
7129 }
7130
7131 /* We get our minimum from the var_off, since that's inherently
7132 * bitwise. Our maximum is the minimum of the operands' maxima.
7133 */
John Fastabend07cd2632020-03-24 10:38:15 -07007134 dst_reg->umin_value = dst_reg->var_off.value;
7135 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7136 if (dst_reg->smin_value < 0 || smin_val < 0) {
7137 /* Lose signed bounds when ANDing negative numbers,
7138 * ain't nobody got time for that.
7139 */
7140 dst_reg->smin_value = S64_MIN;
7141 dst_reg->smax_value = S64_MAX;
7142 } else {
7143 /* ANDing two positives gives a positive, so safe to
7144 * cast result into s64.
7145 */
7146 dst_reg->smin_value = dst_reg->umin_value;
7147 dst_reg->smax_value = dst_reg->umax_value;
7148 }
7149 /* We may learn something more from the var_off */
7150 __update_reg_bounds(dst_reg);
7151}
7152
John Fastabend3f50f132020-03-30 14:36:39 -07007153static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7154 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007155{
John Fastabend3f50f132020-03-30 14:36:39 -07007156 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7157 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7158 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007159 s32 smin_val = src_reg->s32_min_value;
7160 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007161
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007162 if (src_known && dst_known) {
7163 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007164 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007165 }
John Fastabend07cd2632020-03-24 10:38:15 -07007166
7167 /* We get our maximum from the var_off, and our minimum is the
7168 * maximum of the operands' minima
7169 */
John Fastabend3f50f132020-03-30 14:36:39 -07007170 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7171 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7172 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7173 /* Lose signed bounds when ORing negative numbers,
7174 * ain't nobody got time for that.
7175 */
7176 dst_reg->s32_min_value = S32_MIN;
7177 dst_reg->s32_max_value = S32_MAX;
7178 } else {
7179 /* ORing two positives gives a positive, so safe to
7180 * cast result into s64.
7181 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007182 dst_reg->s32_min_value = dst_reg->u32_min_value;
7183 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007184 }
7185}
7186
7187static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7188 struct bpf_reg_state *src_reg)
7189{
7190 bool src_known = tnum_is_const(src_reg->var_off);
7191 bool dst_known = tnum_is_const(dst_reg->var_off);
7192 s64 smin_val = src_reg->smin_value;
7193 u64 umin_val = src_reg->umin_value;
7194
7195 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007196 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007197 return;
7198 }
7199
7200 /* We get our maximum from the var_off, and our minimum is the
7201 * maximum of the operands' minima
7202 */
John Fastabend07cd2632020-03-24 10:38:15 -07007203 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7204 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7205 if (dst_reg->smin_value < 0 || smin_val < 0) {
7206 /* Lose signed bounds when ORing negative numbers,
7207 * ain't nobody got time for that.
7208 */
7209 dst_reg->smin_value = S64_MIN;
7210 dst_reg->smax_value = S64_MAX;
7211 } else {
7212 /* ORing two positives gives a positive, so safe to
7213 * cast result into s64.
7214 */
7215 dst_reg->smin_value = dst_reg->umin_value;
7216 dst_reg->smax_value = dst_reg->umax_value;
7217 }
7218 /* We may learn something more from the var_off */
7219 __update_reg_bounds(dst_reg);
7220}
7221
Yonghong Song2921c902020-08-24 23:46:08 -07007222static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7223 struct bpf_reg_state *src_reg)
7224{
7225 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7226 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7227 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7228 s32 smin_val = src_reg->s32_min_value;
7229
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007230 if (src_known && dst_known) {
7231 __mark_reg32_known(dst_reg, var32_off.value);
Yonghong Song2921c902020-08-24 23:46:08 -07007232 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007233 }
Yonghong Song2921c902020-08-24 23:46:08 -07007234
7235 /* We get both minimum and maximum from the var32_off. */
7236 dst_reg->u32_min_value = var32_off.value;
7237 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7238
7239 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7240 /* XORing two positive sign numbers gives a positive,
7241 * so safe to cast u32 result into s32.
7242 */
7243 dst_reg->s32_min_value = dst_reg->u32_min_value;
7244 dst_reg->s32_max_value = dst_reg->u32_max_value;
7245 } else {
7246 dst_reg->s32_min_value = S32_MIN;
7247 dst_reg->s32_max_value = S32_MAX;
7248 }
7249}
7250
7251static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7252 struct bpf_reg_state *src_reg)
7253{
7254 bool src_known = tnum_is_const(src_reg->var_off);
7255 bool dst_known = tnum_is_const(dst_reg->var_off);
7256 s64 smin_val = src_reg->smin_value;
7257
7258 if (src_known && dst_known) {
7259 /* dst_reg->var_off.value has been updated earlier */
7260 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7261 return;
7262 }
7263
7264 /* We get both minimum and maximum from the var_off. */
7265 dst_reg->umin_value = dst_reg->var_off.value;
7266 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7267
7268 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7269 /* XORing two positive sign numbers gives a positive,
7270 * so safe to cast u64 result into s64.
7271 */
7272 dst_reg->smin_value = dst_reg->umin_value;
7273 dst_reg->smax_value = dst_reg->umax_value;
7274 } else {
7275 dst_reg->smin_value = S64_MIN;
7276 dst_reg->smax_value = S64_MAX;
7277 }
7278
7279 __update_reg_bounds(dst_reg);
7280}
7281
John Fastabend3f50f132020-03-30 14:36:39 -07007282static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7283 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07007284{
John Fastabend07cd2632020-03-24 10:38:15 -07007285 /* We lose all sign bit information (except what we can pick
7286 * up from var_off)
7287 */
John Fastabend3f50f132020-03-30 14:36:39 -07007288 dst_reg->s32_min_value = S32_MIN;
7289 dst_reg->s32_max_value = S32_MAX;
7290 /* If we might shift our top bit out, then we know nothing */
7291 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7292 dst_reg->u32_min_value = 0;
7293 dst_reg->u32_max_value = U32_MAX;
7294 } else {
7295 dst_reg->u32_min_value <<= umin_val;
7296 dst_reg->u32_max_value <<= umax_val;
7297 }
7298}
7299
7300static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7301 struct bpf_reg_state *src_reg)
7302{
7303 u32 umax_val = src_reg->u32_max_value;
7304 u32 umin_val = src_reg->u32_min_value;
7305 /* u32 alu operation will zext upper bits */
7306 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7307
7308 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7309 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7310 /* Not required but being careful mark reg64 bounds as unknown so
7311 * that we are forced to pick them up from tnum and zext later and
7312 * if some path skips this step we are still safe.
7313 */
7314 __mark_reg64_unbounded(dst_reg);
7315 __update_reg32_bounds(dst_reg);
7316}
7317
7318static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7319 u64 umin_val, u64 umax_val)
7320{
7321 /* Special case <<32 because it is a common compiler pattern to sign
7322 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7323 * positive we know this shift will also be positive so we can track
7324 * bounds correctly. Otherwise we lose all sign bit information except
7325 * what we can pick up from var_off. Perhaps we can generalize this
7326 * later to shifts of any length.
7327 */
7328 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7329 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7330 else
7331 dst_reg->smax_value = S64_MAX;
7332
7333 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7334 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7335 else
7336 dst_reg->smin_value = S64_MIN;
7337
John Fastabend07cd2632020-03-24 10:38:15 -07007338 /* If we might shift our top bit out, then we know nothing */
7339 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7340 dst_reg->umin_value = 0;
7341 dst_reg->umax_value = U64_MAX;
7342 } else {
7343 dst_reg->umin_value <<= umin_val;
7344 dst_reg->umax_value <<= umax_val;
7345 }
John Fastabend3f50f132020-03-30 14:36:39 -07007346}
7347
7348static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7349 struct bpf_reg_state *src_reg)
7350{
7351 u64 umax_val = src_reg->umax_value;
7352 u64 umin_val = src_reg->umin_value;
7353
7354 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7355 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7356 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7357
John Fastabend07cd2632020-03-24 10:38:15 -07007358 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7359 /* We may learn something more from the var_off */
7360 __update_reg_bounds(dst_reg);
7361}
7362
John Fastabend3f50f132020-03-30 14:36:39 -07007363static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7364 struct bpf_reg_state *src_reg)
7365{
7366 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7367 u32 umax_val = src_reg->u32_max_value;
7368 u32 umin_val = src_reg->u32_min_value;
7369
7370 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7371 * be negative, then either:
7372 * 1) src_reg might be zero, so the sign bit of the result is
7373 * unknown, so we lose our signed bounds
7374 * 2) it's known negative, thus the unsigned bounds capture the
7375 * signed bounds
7376 * 3) the signed bounds cross zero, so they tell us nothing
7377 * about the result
7378 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01007379 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07007380 * Thus, in all cases it suffices to blow away our signed bounds
7381 * and rely on inferring new ones from the unsigned bounds and
7382 * var_off of the result.
7383 */
7384 dst_reg->s32_min_value = S32_MIN;
7385 dst_reg->s32_max_value = S32_MAX;
7386
7387 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7388 dst_reg->u32_min_value >>= umax_val;
7389 dst_reg->u32_max_value >>= umin_val;
7390
7391 __mark_reg64_unbounded(dst_reg);
7392 __update_reg32_bounds(dst_reg);
7393}
7394
John Fastabend07cd2632020-03-24 10:38:15 -07007395static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7396 struct bpf_reg_state *src_reg)
7397{
7398 u64 umax_val = src_reg->umax_value;
7399 u64 umin_val = src_reg->umin_value;
7400
7401 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7402 * be negative, then either:
7403 * 1) src_reg might be zero, so the sign bit of the result is
7404 * unknown, so we lose our signed bounds
7405 * 2) it's known negative, thus the unsigned bounds capture the
7406 * signed bounds
7407 * 3) the signed bounds cross zero, so they tell us nothing
7408 * about the result
7409 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01007410 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07007411 * Thus, in all cases it suffices to blow away our signed bounds
7412 * and rely on inferring new ones from the unsigned bounds and
7413 * var_off of the result.
7414 */
7415 dst_reg->smin_value = S64_MIN;
7416 dst_reg->smax_value = S64_MAX;
7417 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7418 dst_reg->umin_value >>= umax_val;
7419 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07007420
7421 /* Its not easy to operate on alu32 bounds here because it depends
7422 * on bits being shifted in. Take easy way out and mark unbounded
7423 * so we can recalculate later from tnum.
7424 */
7425 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007426 __update_reg_bounds(dst_reg);
7427}
7428
John Fastabend3f50f132020-03-30 14:36:39 -07007429static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7430 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007431{
John Fastabend3f50f132020-03-30 14:36:39 -07007432 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07007433
7434 /* Upon reaching here, src_known is true and
7435 * umax_val is equal to umin_val.
7436 */
John Fastabend3f50f132020-03-30 14:36:39 -07007437 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7438 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07007439
John Fastabend3f50f132020-03-30 14:36:39 -07007440 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7441
7442 /* blow away the dst_reg umin_value/umax_value and rely on
7443 * dst_reg var_off to refine the result.
7444 */
7445 dst_reg->u32_min_value = 0;
7446 dst_reg->u32_max_value = U32_MAX;
7447
7448 __mark_reg64_unbounded(dst_reg);
7449 __update_reg32_bounds(dst_reg);
7450}
7451
7452static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7453 struct bpf_reg_state *src_reg)
7454{
7455 u64 umin_val = src_reg->umin_value;
7456
7457 /* Upon reaching here, src_known is true and umax_val is equal
7458 * to umin_val.
7459 */
7460 dst_reg->smin_value >>= umin_val;
7461 dst_reg->smax_value >>= umin_val;
7462
7463 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07007464
7465 /* blow away the dst_reg umin_value/umax_value and rely on
7466 * dst_reg var_off to refine the result.
7467 */
7468 dst_reg->umin_value = 0;
7469 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07007470
7471 /* Its not easy to operate on alu32 bounds here because it depends
7472 * on bits being shifted in from upper 32-bits. Take easy way out
7473 * and mark unbounded so we can recalculate later from tnum.
7474 */
7475 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007476 __update_reg_bounds(dst_reg);
7477}
7478
Jann Horn468f6ea2017-12-18 20:11:56 -08007479/* WARNING: This function does calculations on 64-bit values, but the actual
7480 * execution may occur on 32-bit values. Therefore, things like bitshifts
7481 * need extra checks in the 32-bit case.
7482 */
Edward Creef1174f72017-08-07 15:26:19 +01007483static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7484 struct bpf_insn *insn,
7485 struct bpf_reg_state *dst_reg,
7486 struct bpf_reg_state src_reg)
7487{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007488 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01007489 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08007490 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01007491 s64 smin_val, smax_val;
7492 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07007493 s32 s32_min_val, s32_max_val;
7494 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08007495 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
John Fastabend3f50f132020-03-30 14:36:39 -07007496 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007497 int ret;
Jann Hornb7992072018-10-05 18:17:59 +02007498
Edward Creeb03c9f92017-08-07 15:26:36 +01007499 smin_val = src_reg.smin_value;
7500 smax_val = src_reg.smax_value;
7501 umin_val = src_reg.umin_value;
7502 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01007503
John Fastabend3f50f132020-03-30 14:36:39 -07007504 s32_min_val = src_reg.s32_min_value;
7505 s32_max_val = src_reg.s32_max_value;
7506 u32_min_val = src_reg.u32_min_value;
7507 u32_max_val = src_reg.u32_max_value;
7508
7509 if (alu32) {
7510 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007511 if ((src_known &&
7512 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7513 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7514 /* Taint dst register if offset had invalid bounds
7515 * derived from e.g. dead branches.
7516 */
7517 __mark_reg_unknown(env, dst_reg);
7518 return 0;
7519 }
7520 } else {
7521 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007522 if ((src_known &&
7523 (smin_val != smax_val || umin_val != umax_val)) ||
7524 smin_val > smax_val || umin_val > umax_val) {
7525 /* Taint dst register if offset had invalid bounds
7526 * derived from e.g. dead branches.
7527 */
7528 __mark_reg_unknown(env, dst_reg);
7529 return 0;
7530 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01007531 }
7532
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007533 if (!src_known &&
7534 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007535 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007536 return 0;
7537 }
7538
Daniel Borkmannf5288192021-03-24 11:25:39 +01007539 if (sanitize_needed(opcode)) {
7540 ret = sanitize_val_alu(env, insn);
7541 if (ret < 0)
7542 return sanitize_err(env, insn, ret, NULL, NULL);
7543 }
7544
John Fastabend3f50f132020-03-30 14:36:39 -07007545 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7546 * There are two classes of instructions: The first class we track both
7547 * alu32 and alu64 sign/unsigned bounds independently this provides the
7548 * greatest amount of precision when alu operations are mixed with jmp32
7549 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7550 * and BPF_OR. This is possible because these ops have fairly easy to
7551 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7552 * See alu32 verifier tests for examples. The second class of
7553 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7554 * with regards to tracking sign/unsigned bounds because the bits may
7555 * cross subreg boundaries in the alu64 case. When this happens we mark
7556 * the reg unbounded in the subreg bound space and use the resulting
7557 * tnum to calculate an approximation of the sign/unsigned bounds.
7558 */
Edward Creef1174f72017-08-07 15:26:19 +01007559 switch (opcode) {
7560 case BPF_ADD:
John Fastabend3f50f132020-03-30 14:36:39 -07007561 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007562 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007563 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01007564 break;
7565 case BPF_SUB:
John Fastabend3f50f132020-03-30 14:36:39 -07007566 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007567 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007568 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04007569 break;
7570 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07007571 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7572 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007573 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007574 break;
7575 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07007576 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7577 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007578 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007579 break;
7580 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07007581 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7582 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007583 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007584 break;
Yonghong Song2921c902020-08-24 23:46:08 -07007585 case BPF_XOR:
7586 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7587 scalar32_min_max_xor(dst_reg, &src_reg);
7588 scalar_min_max_xor(dst_reg, &src_reg);
7589 break;
Josef Bacik48461132016-09-28 10:54:32 -04007590 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007591 if (umax_val >= insn_bitness) {
7592 /* Shifts greater than 31 or 63 are undefined.
7593 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007594 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007595 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007596 break;
7597 }
John Fastabend3f50f132020-03-30 14:36:39 -07007598 if (alu32)
7599 scalar32_min_max_lsh(dst_reg, &src_reg);
7600 else
7601 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007602 break;
7603 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007604 if (umax_val >= insn_bitness) {
7605 /* Shifts greater than 31 or 63 are undefined.
7606 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007607 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007608 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007609 break;
7610 }
John Fastabend3f50f132020-03-30 14:36:39 -07007611 if (alu32)
7612 scalar32_min_max_rsh(dst_reg, &src_reg);
7613 else
7614 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007615 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007616 case BPF_ARSH:
7617 if (umax_val >= insn_bitness) {
7618 /* Shifts greater than 31 or 63 are undefined.
7619 * This includes shifts by a negative number.
7620 */
7621 mark_reg_unknown(env, regs, insn->dst_reg);
7622 break;
7623 }
John Fastabend3f50f132020-03-30 14:36:39 -07007624 if (alu32)
7625 scalar32_min_max_arsh(dst_reg, &src_reg);
7626 else
7627 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007628 break;
Josef Bacik48461132016-09-28 10:54:32 -04007629 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007630 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007631 break;
7632 }
7633
John Fastabend3f50f132020-03-30 14:36:39 -07007634 /* ALU32 ops are zero extended into 64bit register */
7635 if (alu32)
7636 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08007637
John Fastabend294f2fc2020-03-24 10:38:37 -07007638 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01007639 __reg_deduce_bounds(dst_reg);
7640 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007641 return 0;
7642}
7643
7644/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7645 * and var_off.
7646 */
7647static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7648 struct bpf_insn *insn)
7649{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007650 struct bpf_verifier_state *vstate = env->cur_state;
7651 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7652 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01007653 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7654 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007655 int err;
Edward Creef1174f72017-08-07 15:26:19 +01007656
7657 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007658 src_reg = NULL;
7659 if (dst_reg->type != SCALAR_VALUE)
7660 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007661 else
7662 /* Make sure ID is cleared otherwise dst_reg min/max could be
7663 * incorrectly propagated into other registers by find_equal_scalars()
7664 */
7665 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007666 if (BPF_SRC(insn->code) == BPF_X) {
7667 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007668 if (src_reg->type != SCALAR_VALUE) {
7669 if (dst_reg->type != SCALAR_VALUE) {
7670 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007671 * an arbitrary scalar. Disallow all math except
7672 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01007673 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07007674 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007675 mark_reg_unknown(env, regs, insn->dst_reg);
7676 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01007677 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007678 verbose(env, "R%d pointer %s pointer prohibited\n",
7679 insn->dst_reg,
7680 bpf_alu_string[opcode >> 4]);
7681 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01007682 } else {
7683 /* scalar += pointer
7684 * This is legal, but we have to reverse our
7685 * src/dest handling in computing the range
7686 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007687 err = mark_chain_precision(env, insn->dst_reg);
7688 if (err)
7689 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007690 return adjust_ptr_min_max_vals(env, insn,
7691 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007692 }
7693 } else if (ptr_reg) {
7694 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007695 err = mark_chain_precision(env, insn->src_reg);
7696 if (err)
7697 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007698 return adjust_ptr_min_max_vals(env, insn,
7699 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007700 }
7701 } else {
7702 /* Pretend the src is a reg with a known value, since we only
7703 * need to be able to read from this state.
7704 */
7705 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007706 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01007707 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007708 if (ptr_reg) /* pointer += K */
7709 return adjust_ptr_min_max_vals(env, insn,
7710 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007711 }
7712
7713 /* Got here implies adding two SCALAR_VALUEs */
7714 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007715 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007716 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007717 return -EINVAL;
7718 }
7719 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007720 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007721 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007722 return -EINVAL;
7723 }
7724 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007725}
7726
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007727/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007728static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007729{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007730 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007731 u8 opcode = BPF_OP(insn->code);
7732 int err;
7733
7734 if (opcode == BPF_END || opcode == BPF_NEG) {
7735 if (opcode == BPF_NEG) {
7736 if (BPF_SRC(insn->code) != 0 ||
7737 insn->src_reg != BPF_REG_0 ||
7738 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007739 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007740 return -EINVAL;
7741 }
7742 } else {
7743 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01007744 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7745 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007746 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007747 return -EINVAL;
7748 }
7749 }
7750
7751 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007752 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007753 if (err)
7754 return err;
7755
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007756 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007757 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007758 insn->dst_reg);
7759 return -EACCES;
7760 }
7761
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007762 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007763 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007764 if (err)
7765 return err;
7766
7767 } else if (opcode == BPF_MOV) {
7768
7769 if (BPF_SRC(insn->code) == BPF_X) {
7770 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007771 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007772 return -EINVAL;
7773 }
7774
7775 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007776 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007777 if (err)
7778 return err;
7779 } else {
7780 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007781 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007782 return -EINVAL;
7783 }
7784 }
7785
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007786 /* check dest operand, mark as required later */
7787 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007788 if (err)
7789 return err;
7790
7791 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05007792 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7793 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7794
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007795 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7796 /* case: R1 = R2
7797 * copy register state to dest reg
7798 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07007799 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7800 /* Assign src and dst registers the same ID
7801 * that will be used by find_equal_scalars()
7802 * to propagate min/max range.
7803 */
7804 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05007805 *dst_reg = *src_reg;
7806 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007807 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007808 } else {
Edward Creef1174f72017-08-07 15:26:19 +01007809 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007810 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007811 verbose(env,
7812 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007813 insn->src_reg);
7814 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05007815 } else if (src_reg->type == SCALAR_VALUE) {
7816 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007817 /* Make sure ID is cleared otherwise
7818 * dst_reg min/max could be incorrectly
7819 * propagated into src_reg by find_equal_scalars()
7820 */
7821 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05007822 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007823 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05007824 } else {
7825 mark_reg_unknown(env, regs,
7826 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007827 }
John Fastabend3f50f132020-03-30 14:36:39 -07007828 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007829 }
7830 } else {
7831 /* case: R = imm
7832 * remember the value we stored into this reg
7833 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007834 /* clear any state __mark_reg_known doesn't set */
7835 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007836 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08007837 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7838 __mark_reg_known(regs + insn->dst_reg,
7839 insn->imm);
7840 } else {
7841 __mark_reg_known(regs + insn->dst_reg,
7842 (u32)insn->imm);
7843 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007844 }
7845
7846 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007847 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007848 return -EINVAL;
7849
7850 } else { /* all other ALU ops: and, sub, xor, add, ... */
7851
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007852 if (BPF_SRC(insn->code) == BPF_X) {
7853 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007854 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007855 return -EINVAL;
7856 }
7857 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007858 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007859 if (err)
7860 return err;
7861 } else {
7862 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007863 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007864 return -EINVAL;
7865 }
7866 }
7867
7868 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007869 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007870 if (err)
7871 return err;
7872
7873 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7874 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007875 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007876 return -EINVAL;
7877 }
7878
Rabin Vincent229394e82016-01-12 20:17:08 +01007879 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7880 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7881 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7882
7883 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007884 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01007885 return -EINVAL;
7886 }
7887 }
7888
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007889 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007890 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007891 if (err)
7892 return err;
7893
Edward Creef1174f72017-08-07 15:26:19 +01007894 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007895 }
7896
7897 return 0;
7898}
7899
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007900static void __find_good_pkt_pointers(struct bpf_func_state *state,
7901 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007902 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007903{
7904 struct bpf_reg_state *reg;
7905 int i;
7906
7907 for (i = 0; i < MAX_BPF_REG; i++) {
7908 reg = &state->regs[i];
7909 if (reg->type == type && reg->id == dst_reg->id)
7910 /* keep the maximum range already checked */
7911 reg->range = max(reg->range, new_range);
7912 }
7913
7914 bpf_for_each_spilled_reg(i, state, reg) {
7915 if (!reg)
7916 continue;
7917 if (reg->type == type && reg->id == dst_reg->id)
7918 reg->range = max(reg->range, new_range);
7919 }
7920}
7921
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007922static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007923 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01007924 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007925 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007926{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007927 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007928
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007929 if (dst_reg->off < 0 ||
7930 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01007931 /* This doesn't give us any range */
7932 return;
7933
Edward Creeb03c9f92017-08-07 15:26:36 +01007934 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7935 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01007936 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7937 * than pkt_end, but that's because it's also less than pkt.
7938 */
7939 return;
7940
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007941 new_range = dst_reg->off;
7942 if (range_right_open)
7943 new_range--;
7944
7945 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007946 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007947 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007948 *
7949 * r2 = r3;
7950 * r2 += 8;
7951 * if (r2 > pkt_end) goto <handle exception>
7952 * <access okay>
7953 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007954 * r2 = r3;
7955 * r2 += 8;
7956 * if (r2 < pkt_end) goto <access okay>
7957 * <handle exception>
7958 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007959 * Where:
7960 * r2 == dst_reg, pkt_end == src_reg
7961 * r2=pkt(id=n,off=8,r=0)
7962 * r3=pkt(id=n,off=0,r=0)
7963 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007964 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007965 *
7966 * r2 = r3;
7967 * r2 += 8;
7968 * if (pkt_end >= r2) goto <access okay>
7969 * <handle exception>
7970 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007971 * r2 = r3;
7972 * r2 += 8;
7973 * if (pkt_end <= r2) goto <handle exception>
7974 * <access okay>
7975 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007976 * Where:
7977 * pkt_end == dst_reg, r2 == src_reg
7978 * r2=pkt(id=n,off=8,r=0)
7979 * r3=pkt(id=n,off=0,r=0)
7980 *
7981 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007982 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7983 * and [r3, r3 + 8-1) respectively is safe to access depending on
7984 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007985 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007986
Edward Creef1174f72017-08-07 15:26:19 +01007987 /* If our ids match, then we must have the same max_value. And we
7988 * don't care about the other reg's fixed offset, since if it's too big
7989 * the range won't allow anything.
7990 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7991 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007992 for (i = 0; i <= vstate->curframe; i++)
7993 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7994 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007995}
7996
John Fastabend3f50f132020-03-30 14:36:39 -07007997static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007998{
John Fastabend3f50f132020-03-30 14:36:39 -07007999 struct tnum subreg = tnum_subreg(reg->var_off);
8000 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008001
John Fastabend3f50f132020-03-30 14:36:39 -07008002 switch (opcode) {
8003 case BPF_JEQ:
8004 if (tnum_is_const(subreg))
8005 return !!tnum_equals_const(subreg, val);
8006 break;
8007 case BPF_JNE:
8008 if (tnum_is_const(subreg))
8009 return !tnum_equals_const(subreg, val);
8010 break;
8011 case BPF_JSET:
8012 if ((~subreg.mask & subreg.value) & val)
8013 return 1;
8014 if (!((subreg.mask | subreg.value) & val))
8015 return 0;
8016 break;
8017 case BPF_JGT:
8018 if (reg->u32_min_value > val)
8019 return 1;
8020 else if (reg->u32_max_value <= val)
8021 return 0;
8022 break;
8023 case BPF_JSGT:
8024 if (reg->s32_min_value > sval)
8025 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008026 else if (reg->s32_max_value <= sval)
John Fastabend3f50f132020-03-30 14:36:39 -07008027 return 0;
8028 break;
8029 case BPF_JLT:
8030 if (reg->u32_max_value < val)
8031 return 1;
8032 else if (reg->u32_min_value >= val)
8033 return 0;
8034 break;
8035 case BPF_JSLT:
8036 if (reg->s32_max_value < sval)
8037 return 1;
8038 else if (reg->s32_min_value >= sval)
8039 return 0;
8040 break;
8041 case BPF_JGE:
8042 if (reg->u32_min_value >= val)
8043 return 1;
8044 else if (reg->u32_max_value < val)
8045 return 0;
8046 break;
8047 case BPF_JSGE:
8048 if (reg->s32_min_value >= sval)
8049 return 1;
8050 else if (reg->s32_max_value < sval)
8051 return 0;
8052 break;
8053 case BPF_JLE:
8054 if (reg->u32_max_value <= val)
8055 return 1;
8056 else if (reg->u32_min_value > val)
8057 return 0;
8058 break;
8059 case BPF_JSLE:
8060 if (reg->s32_max_value <= sval)
8061 return 1;
8062 else if (reg->s32_min_value > sval)
8063 return 0;
8064 break;
Jiong Wang092ed092019-01-26 12:26:01 -05008065 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05008066
John Fastabend3f50f132020-03-30 14:36:39 -07008067 return -1;
8068}
8069
8070
8071static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8072{
8073 s64 sval = (s64)val;
8074
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008075 switch (opcode) {
8076 case BPF_JEQ:
8077 if (tnum_is_const(reg->var_off))
8078 return !!tnum_equals_const(reg->var_off, val);
8079 break;
8080 case BPF_JNE:
8081 if (tnum_is_const(reg->var_off))
8082 return !tnum_equals_const(reg->var_off, val);
8083 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08008084 case BPF_JSET:
8085 if ((~reg->var_off.mask & reg->var_off.value) & val)
8086 return 1;
8087 if (!((reg->var_off.mask | reg->var_off.value) & val))
8088 return 0;
8089 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008090 case BPF_JGT:
8091 if (reg->umin_value > val)
8092 return 1;
8093 else if (reg->umax_value <= val)
8094 return 0;
8095 break;
8096 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008097 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008098 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008099 else if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008100 return 0;
8101 break;
8102 case BPF_JLT:
8103 if (reg->umax_value < val)
8104 return 1;
8105 else if (reg->umin_value >= val)
8106 return 0;
8107 break;
8108 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008109 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008110 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008111 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008112 return 0;
8113 break;
8114 case BPF_JGE:
8115 if (reg->umin_value >= val)
8116 return 1;
8117 else if (reg->umax_value < val)
8118 return 0;
8119 break;
8120 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008121 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008122 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008123 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008124 return 0;
8125 break;
8126 case BPF_JLE:
8127 if (reg->umax_value <= val)
8128 return 1;
8129 else if (reg->umin_value > val)
8130 return 0;
8131 break;
8132 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008133 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008134 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008135 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008136 return 0;
8137 break;
8138 }
8139
8140 return -1;
8141}
8142
John Fastabend3f50f132020-03-30 14:36:39 -07008143/* compute branch direction of the expression "if (reg opcode val) goto target;"
8144 * and return:
8145 * 1 - branch will be taken and "goto target" will be executed
8146 * 0 - branch will not be taken and fall-through to next insn
8147 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8148 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05008149 */
John Fastabend3f50f132020-03-30 14:36:39 -07008150static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8151 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05008152{
John Fastabendcac616d2020-05-21 13:07:26 -07008153 if (__is_pointer_value(false, reg)) {
8154 if (!reg_type_not_null(reg->type))
8155 return -1;
8156
8157 /* If pointer is valid tests against zero will fail so we can
8158 * use this to direct branch taken.
8159 */
8160 if (val != 0)
8161 return -1;
8162
8163 switch (opcode) {
8164 case BPF_JEQ:
8165 return 0;
8166 case BPF_JNE:
8167 return 1;
8168 default:
8169 return -1;
8170 }
8171 }
Jiong Wang092ed092019-01-26 12:26:01 -05008172
John Fastabend3f50f132020-03-30 14:36:39 -07008173 if (is_jmp32)
8174 return is_branch32_taken(reg, val, opcode);
8175 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02008176}
8177
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008178static int flip_opcode(u32 opcode)
8179{
8180 /* How can we transform "a <op> b" into "b <op> a"? */
8181 static const u8 opcode_flip[16] = {
8182 /* these stay the same */
8183 [BPF_JEQ >> 4] = BPF_JEQ,
8184 [BPF_JNE >> 4] = BPF_JNE,
8185 [BPF_JSET >> 4] = BPF_JSET,
8186 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8187 [BPF_JGE >> 4] = BPF_JLE,
8188 [BPF_JGT >> 4] = BPF_JLT,
8189 [BPF_JLE >> 4] = BPF_JGE,
8190 [BPF_JLT >> 4] = BPF_JGT,
8191 [BPF_JSGE >> 4] = BPF_JSLE,
8192 [BPF_JSGT >> 4] = BPF_JSLT,
8193 [BPF_JSLE >> 4] = BPF_JSGE,
8194 [BPF_JSLT >> 4] = BPF_JSGT
8195 };
8196 return opcode_flip[opcode >> 4];
8197}
8198
8199static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8200 struct bpf_reg_state *src_reg,
8201 u8 opcode)
8202{
8203 struct bpf_reg_state *pkt;
8204
8205 if (src_reg->type == PTR_TO_PACKET_END) {
8206 pkt = dst_reg;
8207 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8208 pkt = src_reg;
8209 opcode = flip_opcode(opcode);
8210 } else {
8211 return -1;
8212 }
8213
8214 if (pkt->range >= 0)
8215 return -1;
8216
8217 switch (opcode) {
8218 case BPF_JLE:
8219 /* pkt <= pkt_end */
8220 fallthrough;
8221 case BPF_JGT:
8222 /* pkt > pkt_end */
8223 if (pkt->range == BEYOND_PKT_END)
8224 /* pkt has at last one extra byte beyond pkt_end */
8225 return opcode == BPF_JGT;
8226 break;
8227 case BPF_JLT:
8228 /* pkt < pkt_end */
8229 fallthrough;
8230 case BPF_JGE:
8231 /* pkt >= pkt_end */
8232 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8233 return opcode == BPF_JGE;
8234 break;
8235 }
8236 return -1;
8237}
8238
Josef Bacik48461132016-09-28 10:54:32 -04008239/* Adjusts the register min/max values in the case that the dst_reg is the
8240 * variable register that we are working on, and src_reg is a constant or we're
8241 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01008242 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04008243 */
8244static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008245 struct bpf_reg_state *false_reg,
8246 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05008247 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04008248{
John Fastabend3f50f132020-03-30 14:36:39 -07008249 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8250 struct tnum false_64off = false_reg->var_off;
8251 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8252 struct tnum true_64off = true_reg->var_off;
8253 s64 sval = (s64)val;
8254 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008255
Edward Creef1174f72017-08-07 15:26:19 +01008256 /* If the dst_reg is a pointer, we can't learn anything about its
8257 * variable offset from the compare (unless src_reg were a pointer into
8258 * the same object, but we don't bother with that.
8259 * Since false_reg and true_reg have the same type by construction, we
8260 * only need to check one of them for pointerness.
8261 */
8262 if (__is_pointer_value(false, false_reg))
8263 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02008264
Josef Bacik48461132016-09-28 10:54:32 -04008265 switch (opcode) {
8266 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04008267 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008268 {
8269 struct bpf_reg_state *reg =
8270 opcode == BPF_JEQ ? true_reg : false_reg;
8271
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008272 /* JEQ/JNE comparison doesn't change the register equivalence.
8273 * r1 = r2;
8274 * if (r1 == 42) goto label;
8275 * ...
8276 * label: // here both r1 and r2 are known to be 42.
8277 *
8278 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04008279 */
John Fastabend3f50f132020-03-30 14:36:39 -07008280 if (is_jmp32)
8281 __mark_reg32_known(reg, val32);
8282 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008283 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04008284 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008285 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008286 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07008287 if (is_jmp32) {
8288 false_32off = tnum_and(false_32off, tnum_const(~val32));
8289 if (is_power_of_2(val32))
8290 true_32off = tnum_or(true_32off,
8291 tnum_const(val32));
8292 } else {
8293 false_64off = tnum_and(false_64off, tnum_const(~val));
8294 if (is_power_of_2(val))
8295 true_64off = tnum_or(true_64off,
8296 tnum_const(val));
8297 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008298 break;
Josef Bacik48461132016-09-28 10:54:32 -04008299 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008300 case BPF_JGT:
8301 {
John Fastabend3f50f132020-03-30 14:36:39 -07008302 if (is_jmp32) {
8303 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8304 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8305
8306 false_reg->u32_max_value = min(false_reg->u32_max_value,
8307 false_umax);
8308 true_reg->u32_min_value = max(true_reg->u32_min_value,
8309 true_umin);
8310 } else {
8311 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8312 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8313
8314 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8315 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8316 }
Edward Creeb03c9f92017-08-07 15:26:36 +01008317 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008318 }
Josef Bacik48461132016-09-28 10:54:32 -04008319 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008320 case BPF_JSGT:
8321 {
John Fastabend3f50f132020-03-30 14:36:39 -07008322 if (is_jmp32) {
8323 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8324 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008325
John Fastabend3f50f132020-03-30 14:36:39 -07008326 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8327 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8328 } else {
8329 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8330 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8331
8332 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8333 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8334 }
Josef Bacik48461132016-09-28 10:54:32 -04008335 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008336 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008337 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008338 case BPF_JLT:
8339 {
John Fastabend3f50f132020-03-30 14:36:39 -07008340 if (is_jmp32) {
8341 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8342 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8343
8344 false_reg->u32_min_value = max(false_reg->u32_min_value,
8345 false_umin);
8346 true_reg->u32_max_value = min(true_reg->u32_max_value,
8347 true_umax);
8348 } else {
8349 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8350 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8351
8352 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8353 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8354 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008355 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008356 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008357 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008358 case BPF_JSLT:
8359 {
John Fastabend3f50f132020-03-30 14:36:39 -07008360 if (is_jmp32) {
8361 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8362 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008363
John Fastabend3f50f132020-03-30 14:36:39 -07008364 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8365 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8366 } else {
8367 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8368 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8369
8370 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8371 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8372 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008373 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008374 }
Josef Bacik48461132016-09-28 10:54:32 -04008375 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02008376 return;
Josef Bacik48461132016-09-28 10:54:32 -04008377 }
8378
John Fastabend3f50f132020-03-30 14:36:39 -07008379 if (is_jmp32) {
8380 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8381 tnum_subreg(false_32off));
8382 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8383 tnum_subreg(true_32off));
8384 __reg_combine_32_into_64(false_reg);
8385 __reg_combine_32_into_64(true_reg);
8386 } else {
8387 false_reg->var_off = false_64off;
8388 true_reg->var_off = true_64off;
8389 __reg_combine_64_into_32(false_reg);
8390 __reg_combine_64_into_32(true_reg);
8391 }
Josef Bacik48461132016-09-28 10:54:32 -04008392}
8393
Edward Creef1174f72017-08-07 15:26:19 +01008394/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8395 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04008396 */
8397static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008398 struct bpf_reg_state *false_reg,
8399 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05008400 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04008401{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008402 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02008403 /* This uses zero as "not present in table"; luckily the zero opcode,
8404 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01008405 */
Jann Horn0fc31b12020-03-30 18:03:24 +02008406 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07008407 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01008408}
8409
8410/* Regs are known to be equal, so intersect their min/max/var_off */
8411static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8412 struct bpf_reg_state *dst_reg)
8413{
Edward Creeb03c9f92017-08-07 15:26:36 +01008414 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8415 dst_reg->umin_value);
8416 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8417 dst_reg->umax_value);
8418 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8419 dst_reg->smin_value);
8420 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8421 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01008422 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8423 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01008424 /* We might have learned new bounds from the var_off. */
8425 __update_reg_bounds(src_reg);
8426 __update_reg_bounds(dst_reg);
8427 /* We might have learned something about the sign bit. */
8428 __reg_deduce_bounds(src_reg);
8429 __reg_deduce_bounds(dst_reg);
8430 /* We might have learned some bits from the bounds. */
8431 __reg_bound_offset(src_reg);
8432 __reg_bound_offset(dst_reg);
8433 /* Intersecting with the old var_off might have improved our bounds
8434 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8435 * then new var_off is (0; 0x7f...fc) which improves our umax.
8436 */
8437 __update_reg_bounds(src_reg);
8438 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008439}
8440
8441static void reg_combine_min_max(struct bpf_reg_state *true_src,
8442 struct bpf_reg_state *true_dst,
8443 struct bpf_reg_state *false_src,
8444 struct bpf_reg_state *false_dst,
8445 u8 opcode)
8446{
8447 switch (opcode) {
8448 case BPF_JEQ:
8449 __reg_combine_min_max(true_src, true_dst);
8450 break;
8451 case BPF_JNE:
8452 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01008453 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02008454 }
Josef Bacik48461132016-09-28 10:54:32 -04008455}
8456
Joe Stringerfd978bf72018-10-02 13:35:35 -07008457static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8458 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07008459 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02008460{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07008461 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8462 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01008463 /* Old offset (both fixed and variable parts) should
8464 * have been known-zero, because we don't allow pointer
8465 * arithmetic on pointers that might be NULL.
8466 */
Edward Creeb03c9f92017-08-07 15:26:36 +01008467 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8468 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01008469 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01008470 __mark_reg_known_zero(reg);
8471 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01008472 }
8473 if (is_null) {
8474 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008475 /* We don't need id and ref_obj_id from this point
8476 * onwards anymore, thus we should better reset it,
8477 * so that state pruning has chances to take effect.
8478 */
8479 reg->id = 0;
8480 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04008481
8482 return;
8483 }
8484
8485 mark_ptr_not_null_reg(reg);
8486
8487 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008488 /* For not-NULL ptr, reg->ref_obj_id will be reset
8489 * in release_reg_references().
8490 *
8491 * reg->id is still used by spin_lock ptr. Other
8492 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07008493 */
8494 reg->id = 0;
8495 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02008496 }
8497}
8498
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008499static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8500 bool is_null)
8501{
8502 struct bpf_reg_state *reg;
8503 int i;
8504
8505 for (i = 0; i < MAX_BPF_REG; i++)
8506 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8507
8508 bpf_for_each_spilled_reg(i, state, reg) {
8509 if (!reg)
8510 continue;
8511 mark_ptr_or_null_reg(state, reg, id, is_null);
8512 }
8513}
8514
Thomas Graf57a09bf2016-10-18 19:51:19 +02008515/* The logic is similar to find_good_pkt_pointers(), both could eventually
8516 * be folded together at some point.
8517 */
Joe Stringer840b9612018-10-02 13:35:32 -07008518static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8519 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02008520{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008521 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008522 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008523 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01008524 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008525 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02008526
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008527 if (ref_obj_id && ref_obj_id == id && is_null)
8528 /* regs[regno] is in the " == NULL" branch.
8529 * No one could have freed the reference state before
8530 * doing the NULL check.
8531 */
8532 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07008533
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008534 for (i = 0; i <= vstate->curframe; i++)
8535 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02008536}
8537
Daniel Borkmann5beca082017-11-01 23:58:10 +01008538static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8539 struct bpf_reg_state *dst_reg,
8540 struct bpf_reg_state *src_reg,
8541 struct bpf_verifier_state *this_branch,
8542 struct bpf_verifier_state *other_branch)
8543{
8544 if (BPF_SRC(insn->code) != BPF_X)
8545 return false;
8546
Jiong Wang092ed092019-01-26 12:26:01 -05008547 /* Pointers are always 64-bit. */
8548 if (BPF_CLASS(insn->code) == BPF_JMP32)
8549 return false;
8550
Daniel Borkmann5beca082017-11-01 23:58:10 +01008551 switch (BPF_OP(insn->code)) {
8552 case BPF_JGT:
8553 if ((dst_reg->type == PTR_TO_PACKET &&
8554 src_reg->type == PTR_TO_PACKET_END) ||
8555 (dst_reg->type == PTR_TO_PACKET_META &&
8556 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8557 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8558 find_good_pkt_pointers(this_branch, dst_reg,
8559 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008560 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008561 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8562 src_reg->type == PTR_TO_PACKET) ||
8563 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8564 src_reg->type == PTR_TO_PACKET_META)) {
8565 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8566 find_good_pkt_pointers(other_branch, src_reg,
8567 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008568 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008569 } else {
8570 return false;
8571 }
8572 break;
8573 case BPF_JLT:
8574 if ((dst_reg->type == PTR_TO_PACKET &&
8575 src_reg->type == PTR_TO_PACKET_END) ||
8576 (dst_reg->type == PTR_TO_PACKET_META &&
8577 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8578 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8579 find_good_pkt_pointers(other_branch, dst_reg,
8580 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008581 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008582 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8583 src_reg->type == PTR_TO_PACKET) ||
8584 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8585 src_reg->type == PTR_TO_PACKET_META)) {
8586 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8587 find_good_pkt_pointers(this_branch, src_reg,
8588 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008589 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008590 } else {
8591 return false;
8592 }
8593 break;
8594 case BPF_JGE:
8595 if ((dst_reg->type == PTR_TO_PACKET &&
8596 src_reg->type == PTR_TO_PACKET_END) ||
8597 (dst_reg->type == PTR_TO_PACKET_META &&
8598 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8599 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8600 find_good_pkt_pointers(this_branch, dst_reg,
8601 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008602 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008603 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8604 src_reg->type == PTR_TO_PACKET) ||
8605 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8606 src_reg->type == PTR_TO_PACKET_META)) {
8607 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8608 find_good_pkt_pointers(other_branch, src_reg,
8609 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008610 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008611 } else {
8612 return false;
8613 }
8614 break;
8615 case BPF_JLE:
8616 if ((dst_reg->type == PTR_TO_PACKET &&
8617 src_reg->type == PTR_TO_PACKET_END) ||
8618 (dst_reg->type == PTR_TO_PACKET_META &&
8619 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8620 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8621 find_good_pkt_pointers(other_branch, dst_reg,
8622 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008623 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008624 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8625 src_reg->type == PTR_TO_PACKET) ||
8626 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8627 src_reg->type == PTR_TO_PACKET_META)) {
8628 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8629 find_good_pkt_pointers(this_branch, src_reg,
8630 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008631 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008632 } else {
8633 return false;
8634 }
8635 break;
8636 default:
8637 return false;
8638 }
8639
8640 return true;
8641}
8642
Alexei Starovoitov75748832020-10-08 18:12:37 -07008643static void find_equal_scalars(struct bpf_verifier_state *vstate,
8644 struct bpf_reg_state *known_reg)
8645{
8646 struct bpf_func_state *state;
8647 struct bpf_reg_state *reg;
8648 int i, j;
8649
8650 for (i = 0; i <= vstate->curframe; i++) {
8651 state = vstate->frame[i];
8652 for (j = 0; j < MAX_BPF_REG; j++) {
8653 reg = &state->regs[j];
8654 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8655 *reg = *known_reg;
8656 }
8657
8658 bpf_for_each_spilled_reg(j, state, reg) {
8659 if (!reg)
8660 continue;
8661 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8662 *reg = *known_reg;
8663 }
8664 }
8665}
8666
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008667static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008668 struct bpf_insn *insn, int *insn_idx)
8669{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008670 struct bpf_verifier_state *this_branch = env->cur_state;
8671 struct bpf_verifier_state *other_branch;
8672 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008673 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008674 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05008675 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008676 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008677 int err;
8678
Jiong Wang092ed092019-01-26 12:26:01 -05008679 /* Only conditional jumps are expected to reach here. */
8680 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8681 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008682 return -EINVAL;
8683 }
8684
8685 if (BPF_SRC(insn->code) == BPF_X) {
8686 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008687 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008688 return -EINVAL;
8689 }
8690
8691 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008692 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008693 if (err)
8694 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008695
8696 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008697 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008698 insn->src_reg);
8699 return -EACCES;
8700 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008701 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008702 } else {
8703 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008704 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008705 return -EINVAL;
8706 }
8707 }
8708
8709 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008710 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008711 if (err)
8712 return err;
8713
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008714 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008715 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008716
John Fastabend3f50f132020-03-30 14:36:39 -07008717 if (BPF_SRC(insn->code) == BPF_K) {
8718 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8719 } else if (src_reg->type == SCALAR_VALUE &&
8720 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8721 pred = is_branch_taken(dst_reg,
8722 tnum_subreg(src_reg->var_off).value,
8723 opcode,
8724 is_jmp32);
8725 } else if (src_reg->type == SCALAR_VALUE &&
8726 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8727 pred = is_branch_taken(dst_reg,
8728 src_reg->var_off.value,
8729 opcode,
8730 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008731 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8732 reg_is_pkt_pointer_any(src_reg) &&
8733 !is_jmp32) {
8734 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07008735 }
8736
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008737 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07008738 /* If we get here with a dst_reg pointer type it is because
8739 * above is_branch_taken() special cased the 0 comparison.
8740 */
8741 if (!__is_pointer_value(false, dst_reg))
8742 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008743 if (BPF_SRC(insn->code) == BPF_X && !err &&
8744 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008745 err = mark_chain_precision(env, insn->src_reg);
8746 if (err)
8747 return err;
8748 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008749 if (pred == 1) {
8750 /* only follow the goto, ignore fall-through */
8751 *insn_idx += insn->off;
8752 return 0;
8753 } else if (pred == 0) {
8754 /* only follow fall-through branch, since
8755 * that's where the program will go
8756 */
8757 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008758 }
8759
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008760 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8761 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008762 if (!other_branch)
8763 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008764 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008765
Josef Bacik48461132016-09-28 10:54:32 -04008766 /* detect if we are comparing against a constant value so we can adjust
8767 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01008768 * this is only legit if both are scalars (or pointers to the same
8769 * object, I suppose, but we don't support that right now), because
8770 * otherwise the different base pointers mean the offsets aren't
8771 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04008772 */
8773 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05008774 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008775
Edward Creef1174f72017-08-07 15:26:19 +01008776 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05008777 src_reg->type == SCALAR_VALUE) {
8778 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008779 (is_jmp32 &&
8780 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008781 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008782 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008783 src_reg->var_off.value,
8784 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008785 opcode, is_jmp32);
8786 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008787 (is_jmp32 &&
8788 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008789 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008790 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008791 dst_reg->var_off.value,
8792 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008793 opcode, is_jmp32);
8794 else if (!is_jmp32 &&
8795 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01008796 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008797 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8798 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008799 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008800 if (src_reg->id &&
8801 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008802 find_equal_scalars(this_branch, src_reg);
8803 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8804 }
8805
Edward Creef1174f72017-08-07 15:26:19 +01008806 }
8807 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008808 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07008809 dst_reg, insn->imm, (u32)insn->imm,
8810 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04008811 }
8812
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008813 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8814 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008815 find_equal_scalars(this_branch, dst_reg);
8816 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8817 }
8818
Jiong Wang092ed092019-01-26 12:26:01 -05008819 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8820 * NOTE: these optimizations below are related with pointer comparison
8821 * which will never be JMP32.
8822 */
8823 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008824 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07008825 reg_type_may_be_null(dst_reg->type)) {
8826 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02008827 * safe or unknown depending R == 0 or R != 0 conditional.
8828 */
Joe Stringer840b9612018-10-02 13:35:32 -07008829 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8830 opcode == BPF_JNE);
8831 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8832 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008833 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8834 this_branch, other_branch) &&
8835 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008836 verbose(env, "R%d pointer comparison prohibited\n",
8837 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008838 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008839 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008840 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008841 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008842 return 0;
8843}
8844
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008845/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008846static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008847{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008848 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008849 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07008850 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008851 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008852 int err;
8853
8854 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008855 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008856 return -EINVAL;
8857 }
8858 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008859 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008860 return -EINVAL;
8861 }
8862
Edward Creedc503a82017-08-15 20:34:35 +01008863 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008864 if (err)
8865 return err;
8866
Hao Luo4976b712020-09-29 16:50:44 -07008867 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01008868 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01008869 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8870
Hao Luo4976b712020-09-29 16:50:44 -07008871 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008872 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008873 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01008874 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008875
Hao Luo4976b712020-09-29 16:50:44 -07008876 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8877 mark_reg_known_zero(env, regs, insn->dst_reg);
8878
8879 dst_reg->type = aux->btf_var.reg_type;
8880 switch (dst_reg->type) {
8881 case PTR_TO_MEM:
8882 dst_reg->mem_size = aux->btf_var.mem_size;
8883 break;
8884 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07008885 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08008886 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07008887 dst_reg->btf_id = aux->btf_var.btf_id;
8888 break;
8889 default:
8890 verbose(env, "bpf verifier is misconfigured\n");
8891 return -EFAULT;
8892 }
8893 return 0;
8894 }
8895
Yonghong Song69c087b2021-02-26 12:49:25 -08008896 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8897 struct bpf_prog_aux *aux = env->prog->aux;
8898 u32 subprogno = insn[1].imm;
8899
8900 if (!aux->func_info) {
8901 verbose(env, "missing btf func_info\n");
8902 return -EINVAL;
8903 }
8904 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8905 verbose(env, "callback function not static\n");
8906 return -EINVAL;
8907 }
8908
8909 dst_reg->type = PTR_TO_FUNC;
8910 dst_reg->subprogno = subprogno;
8911 return 0;
8912 }
8913
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008914 map = env->used_maps[aux->map_index];
8915 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07008916 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008917
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008918 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07008919 dst_reg->type = PTR_TO_MAP_VALUE;
8920 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008921 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07008922 dst_reg->id = ++env->id_gen;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008923 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
Hao Luo4976b712020-09-29 16:50:44 -07008924 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008925 } else {
8926 verbose(env, "bpf verifier is misconfigured\n");
8927 return -EINVAL;
8928 }
8929
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008930 return 0;
8931}
8932
Daniel Borkmann96be4322015-03-01 12:31:46 +01008933static bool may_access_skb(enum bpf_prog_type type)
8934{
8935 switch (type) {
8936 case BPF_PROG_TYPE_SOCKET_FILTER:
8937 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01008938 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01008939 return true;
8940 default:
8941 return false;
8942 }
8943}
8944
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008945/* verify safety of LD_ABS|LD_IND instructions:
8946 * - they can only appear in the programs where ctx == skb
8947 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8948 * preserve R6-R9, and store return value into R0
8949 *
8950 * Implicit input:
8951 * ctx == skb == R6 == CTX
8952 *
8953 * Explicit input:
8954 * SRC == any register
8955 * IMM == 32-bit immediate
8956 *
8957 * Output:
8958 * R0 - 8/16/32-bit skb data converted to cpu endianness
8959 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008960static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008961{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008962 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008963 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008964 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008965 int i, err;
8966
Udip Pant7e407812020-08-25 16:20:00 -07008967 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008968 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008969 return -EINVAL;
8970 }
8971
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02008972 if (!env->ops->gen_ld_abs) {
8973 verbose(env, "bpf verifier is misconfigured\n");
8974 return -EINVAL;
8975 }
8976
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008977 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07008978 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008979 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008980 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008981 return -EINVAL;
8982 }
8983
8984 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008985 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008986 if (err)
8987 return err;
8988
Joe Stringerfd978bf72018-10-02 13:35:35 -07008989 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8990 * gen_ld_abs() may terminate the program at runtime, leading to
8991 * reference leak.
8992 */
8993 err = check_reference_leak(env);
8994 if (err) {
8995 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8996 return err;
8997 }
8998
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008999 if (env->cur_state->active_spin_lock) {
9000 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9001 return -EINVAL;
9002 }
9003
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009004 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009005 verbose(env,
9006 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009007 return -EINVAL;
9008 }
9009
9010 if (mode == BPF_IND) {
9011 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01009012 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009013 if (err)
9014 return err;
9015 }
9016
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009017 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9018 if (err < 0)
9019 return err;
9020
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009021 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01009022 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009023 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009024 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9025 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009026
9027 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01009028 * the value fetched from the packet.
9029 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009030 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009031 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01009032 /* ld_abs load up to 32-bit skb data. */
9033 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009034 return 0;
9035}
9036
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009037static int check_return_code(struct bpf_verifier_env *env)
9038{
brakmo5cf1e912019-05-28 16:59:36 -07009039 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009040 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009041 struct bpf_reg_state *reg;
9042 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07009043 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009044 int err;
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009045 const bool is_subprog = env->cur_state->frame[0]->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009046
KP Singh9e4e01d2020-03-29 01:43:52 +01009047 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009048 if (!is_subprog &&
9049 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07009050 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009051 !prog->aux->attach_func_proto->type)
9052 return 0;
9053
9054 /* eBPF calling convetion is such that R0 is used
9055 * to return the value from eBPF program.
9056 * Make sure that it's readable at this time
9057 * of bpf_exit, which means that program wrote
9058 * something into it earlier
9059 */
9060 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9061 if (err)
9062 return err;
9063
9064 if (is_pointer_value(env, BPF_REG_0)) {
9065 verbose(env, "R0 leaks addr as return value\n");
9066 return -EACCES;
9067 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009068
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009069 reg = cur_regs(env) + BPF_REG_0;
9070 if (is_subprog) {
9071 if (reg->type != SCALAR_VALUE) {
9072 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9073 reg_type_str[reg->type]);
9074 return -EINVAL;
9075 }
9076 return 0;
9077 }
9078
Udip Pant7e407812020-08-25 16:20:00 -07009079 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02009080 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9081 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02009082 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9083 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9084 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9085 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9086 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02009087 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08009088 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9089 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9090 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009091 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009092 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07009093 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9094 range = tnum_range(0, 3);
9095 enforce_attach_type_range = tnum_range(2, 3);
9096 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009097 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009098 case BPF_PROG_TYPE_CGROUP_SOCK:
9099 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05009100 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08009101 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07009102 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009103 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07009104 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9105 if (!env->prog->aux->attach_btf_id)
9106 return 0;
9107 range = tnum_const(0);
9108 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07009109 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07009110 switch (env->prog->expected_attach_type) {
9111 case BPF_TRACE_FENTRY:
9112 case BPF_TRACE_FEXIT:
9113 range = tnum_const(0);
9114 break;
9115 case BPF_TRACE_RAW_TP:
9116 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07009117 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02009118 case BPF_TRACE_ITER:
9119 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009120 default:
9121 return -ENOTSUPP;
9122 }
Yonghong Song15d83c42020-05-09 10:59:00 -07009123 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02009124 case BPF_PROG_TYPE_SK_LOOKUP:
9125 range = tnum_range(SK_DROP, SK_PASS);
9126 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009127 case BPF_PROG_TYPE_EXT:
9128 /* freplace program can return anything as its return value
9129 * depends on the to-be-replaced kernel func or bpf program.
9130 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009131 default:
9132 return 0;
9133 }
9134
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009135 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009136 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009137 reg_type_str[reg->type]);
9138 return -EINVAL;
9139 }
9140
9141 if (!tnum_in(range, reg->var_off)) {
Yonghong Songbc2591d2021-02-26 12:49:22 -08009142 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009143 return -EINVAL;
9144 }
brakmo5cf1e912019-05-28 16:59:36 -07009145
9146 if (!tnum_is_unknown(enforce_attach_type_range) &&
9147 tnum_in(enforce_attach_type_range, reg->var_off))
9148 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009149 return 0;
9150}
9151
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009152/* non-recursive DFS pseudo code
9153 * 1 procedure DFS-iterative(G,v):
9154 * 2 label v as discovered
9155 * 3 let S be a stack
9156 * 4 S.push(v)
9157 * 5 while S is not empty
9158 * 6 t <- S.pop()
9159 * 7 if t is what we're looking for:
9160 * 8 return t
9161 * 9 for all edges e in G.adjacentEdges(t) do
9162 * 10 if edge e is already labelled
9163 * 11 continue with the next edge
9164 * 12 w <- G.adjacentVertex(t,e)
9165 * 13 if vertex w is not discovered and not explored
9166 * 14 label e as tree-edge
9167 * 15 label w as discovered
9168 * 16 S.push(w)
9169 * 17 continue at 5
9170 * 18 else if vertex w is discovered
9171 * 19 label e as back-edge
9172 * 20 else
9173 * 21 // vertex w is explored
9174 * 22 label e as forward- or cross-edge
9175 * 23 label t as explored
9176 * 24 S.pop()
9177 *
9178 * convention:
9179 * 0x10 - discovered
9180 * 0x11 - discovered and fall-through edge labelled
9181 * 0x12 - discovered and fall-through and branch edges labelled
9182 * 0x20 - explored
9183 */
9184
9185enum {
9186 DISCOVERED = 0x10,
9187 EXPLORED = 0x20,
9188 FALLTHROUGH = 1,
9189 BRANCH = 2,
9190};
9191
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009192static u32 state_htab_size(struct bpf_verifier_env *env)
9193{
9194 return env->prog->len;
9195}
9196
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009197static struct bpf_verifier_state_list **explored_state(
9198 struct bpf_verifier_env *env,
9199 int idx)
9200{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009201 struct bpf_verifier_state *cur = env->cur_state;
9202 struct bpf_func_state *state = cur->frame[cur->curframe];
9203
9204 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009205}
9206
9207static void init_explored_state(struct bpf_verifier_env *env, int idx)
9208{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009209 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009210}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009211
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009212enum {
9213 DONE_EXPLORING = 0,
9214 KEEP_EXPLORING = 1,
9215};
9216
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009217/* t, w, e - match pseudo-code above:
9218 * t - index of current instruction
9219 * w - next instruction
9220 * e - edge
9221 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07009222static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9223 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009224{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009225 int *insn_stack = env->cfg.insn_stack;
9226 int *insn_state = env->cfg.insn_state;
9227
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009228 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009229 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009230
9231 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009232 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009233
9234 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08009235 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009236 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009237 return -EINVAL;
9238 }
9239
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009240 if (e == BRANCH)
9241 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009242 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009243
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009244 if (insn_state[w] == 0) {
9245 /* tree-edge */
9246 insn_state[t] = DISCOVERED | e;
9247 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009248 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009249 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009250 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009251 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009252 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009253 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009254 return DONE_EXPLORING;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08009255 verbose_linfo(env, t, "%d: ", t);
9256 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009257 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009258 return -EINVAL;
9259 } else if (insn_state[w] == EXPLORED) {
9260 /* forward- or cross-edge */
9261 insn_state[t] = DISCOVERED | e;
9262 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009263 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009264 return -EFAULT;
9265 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009266 return DONE_EXPLORING;
9267}
9268
Yonghong Songefdb22d2021-02-26 12:49:20 -08009269static int visit_func_call_insn(int t, int insn_cnt,
9270 struct bpf_insn *insns,
9271 struct bpf_verifier_env *env,
9272 bool visit_callee)
9273{
9274 int ret;
9275
9276 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9277 if (ret)
9278 return ret;
9279
9280 if (t + 1 < insn_cnt)
9281 init_explored_state(env, t + 1);
9282 if (visit_callee) {
9283 init_explored_state(env, t);
9284 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9285 env, false);
9286 }
9287 return ret;
9288}
9289
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009290/* Visits the instruction at index t and returns one of the following:
9291 * < 0 - an error occurred
9292 * DONE_EXPLORING - the instruction was fully explored
9293 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9294 */
9295static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9296{
9297 struct bpf_insn *insns = env->prog->insnsi;
9298 int ret;
9299
Yonghong Song69c087b2021-02-26 12:49:25 -08009300 if (bpf_pseudo_func(insns + t))
9301 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9302
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009303 /* All non-branch instructions have a single fall-through edge. */
9304 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9305 BPF_CLASS(insns[t].code) != BPF_JMP32)
9306 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9307
9308 switch (BPF_OP(insns[t].code)) {
9309 case BPF_EXIT:
9310 return DONE_EXPLORING;
9311
9312 case BPF_CALL:
Yonghong Songefdb22d2021-02-26 12:49:20 -08009313 return visit_func_call_insn(t, insn_cnt, insns, env,
9314 insns[t].src_reg == BPF_PSEUDO_CALL);
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009315
9316 case BPF_JA:
9317 if (BPF_SRC(insns[t].code) != BPF_K)
9318 return -EINVAL;
9319
9320 /* unconditional jump with single edge */
9321 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9322 true);
9323 if (ret)
9324 return ret;
9325
9326 /* unconditional jmp is not a good pruning point,
9327 * but it's marked, since backtracking needs
9328 * to record jmp history in is_state_visited().
9329 */
9330 init_explored_state(env, t + insns[t].off + 1);
9331 /* tell verifier to check for equivalent states
9332 * after every call and jump
9333 */
9334 if (t + 1 < insn_cnt)
9335 init_explored_state(env, t + 1);
9336
9337 return ret;
9338
9339 default:
9340 /* conditional jump with two edges */
9341 init_explored_state(env, t);
9342 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9343 if (ret)
9344 return ret;
9345
9346 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9347 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009348}
9349
9350/* non-recursive depth-first-search to detect loops in BPF program
9351 * loop == back-edge in directed graph
9352 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009353static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009354{
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009355 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009356 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009357 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009358 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009359
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009360 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009361 if (!insn_state)
9362 return -ENOMEM;
9363
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009364 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009365 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07009366 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009367 return -ENOMEM;
9368 }
9369
9370 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9371 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009372 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009373
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009374 while (env->cfg.cur_stack > 0) {
9375 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009376
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009377 ret = visit_insn(t, insn_cnt, env);
9378 switch (ret) {
9379 case DONE_EXPLORING:
9380 insn_state[t] = EXPLORED;
9381 env->cfg.cur_stack--;
9382 break;
9383 case KEEP_EXPLORING:
9384 break;
9385 default:
9386 if (ret > 0) {
9387 verbose(env, "visit_insn internal bug\n");
9388 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009389 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009390 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009391 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009392 }
9393
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009394 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009395 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009396 ret = -EFAULT;
9397 goto err_free;
9398 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009399
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009400 for (i = 0; i < insn_cnt; i++) {
9401 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009402 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009403 ret = -EINVAL;
9404 goto err_free;
9405 }
9406 }
9407 ret = 0; /* cfg looks good */
9408
9409err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07009410 kvfree(insn_state);
9411 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009412 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009413 return ret;
9414}
9415
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009416static int check_abnormal_return(struct bpf_verifier_env *env)
9417{
9418 int i;
9419
9420 for (i = 1; i < env->subprog_cnt; i++) {
9421 if (env->subprog_info[i].has_ld_abs) {
9422 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9423 return -EINVAL;
9424 }
9425 if (env->subprog_info[i].has_tail_call) {
9426 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9427 return -EINVAL;
9428 }
9429 }
9430 return 0;
9431}
9432
Yonghong Song838e9692018-11-19 15:29:11 -08009433/* The minimum supported BTF func info size */
9434#define MIN_BPF_FUNCINFO_SIZE 8
9435#define MAX_FUNCINFO_REC_SIZE 252
9436
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009437static int check_btf_func(struct bpf_verifier_env *env,
9438 const union bpf_attr *attr,
9439 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08009440{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009441 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08009442 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08009443 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009444 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009445 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009446 struct bpf_prog *prog;
9447 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08009448 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08009449 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009450 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03009451 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08009452
9453 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009454 if (!nfuncs) {
9455 if (check_abnormal_return(env))
9456 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08009457 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009458 }
Yonghong Song838e9692018-11-19 15:29:11 -08009459
9460 if (nfuncs != env->subprog_cnt) {
9461 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9462 return -EINVAL;
9463 }
9464
9465 urec_size = attr->func_info_rec_size;
9466 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9467 urec_size > MAX_FUNCINFO_REC_SIZE ||
9468 urec_size % sizeof(u32)) {
9469 verbose(env, "invalid func info rec size %u\n", urec_size);
9470 return -EINVAL;
9471 }
9472
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009473 prog = env->prog;
9474 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08009475
9476 urecord = u64_to_user_ptr(attr->func_info);
9477 min_size = min_t(u32, krec_size, urec_size);
9478
Yonghong Songba64e7d2018-11-24 23:20:44 -08009479 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009480 if (!krecord)
9481 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009482 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9483 if (!info_aux)
9484 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009485
Yonghong Song838e9692018-11-19 15:29:11 -08009486 for (i = 0; i < nfuncs; i++) {
9487 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9488 if (ret) {
9489 if (ret == -E2BIG) {
9490 verbose(env, "nonzero tailing record in func info");
9491 /* set the size kernel expects so loader can zero
9492 * out the rest of the record.
9493 */
9494 if (put_user(min_size, &uattr->func_info_rec_size))
9495 ret = -EFAULT;
9496 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009497 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009498 }
9499
Yonghong Songba64e7d2018-11-24 23:20:44 -08009500 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009501 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009502 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009503 }
9504
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009505 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009506 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08009507 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009508 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009509 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009510 "nonzero insn_off %u for the first func info record",
9511 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009512 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009513 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009514 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08009515 verbose(env,
9516 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009517 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009518 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009519 }
9520
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009521 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009522 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009523 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009524 }
9525
9526 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08009527 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009528 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009529 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08009530 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009531 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009532 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009533 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009534
9535 func_proto = btf_type_by_id(btf, type->type);
9536 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9537 /* btf_func_check() already verified it during BTF load */
9538 goto err_free;
9539 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9540 scalar_return =
9541 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9542 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9543 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9544 goto err_free;
9545 }
9546 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9547 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9548 goto err_free;
9549 }
9550
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009551 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08009552 urecord += urec_size;
9553 }
9554
Yonghong Songba64e7d2018-11-24 23:20:44 -08009555 prog->aux->func_info = krecord;
9556 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009557 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08009558 return 0;
9559
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009560err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08009561 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009562 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08009563 return ret;
9564}
9565
Yonghong Songba64e7d2018-11-24 23:20:44 -08009566static void adjust_btf_func(struct bpf_verifier_env *env)
9567{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009568 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009569 int i;
9570
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009571 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08009572 return;
9573
9574 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009575 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009576}
9577
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009578#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9579 sizeof(((struct bpf_line_info *)(0))->line_col))
9580#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9581
9582static int check_btf_line(struct bpf_verifier_env *env,
9583 const union bpf_attr *attr,
9584 union bpf_attr __user *uattr)
9585{
9586 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9587 struct bpf_subprog_info *sub;
9588 struct bpf_line_info *linfo;
9589 struct bpf_prog *prog;
9590 const struct btf *btf;
9591 void __user *ulinfo;
9592 int err;
9593
9594 nr_linfo = attr->line_info_cnt;
9595 if (!nr_linfo)
9596 return 0;
9597
9598 rec_size = attr->line_info_rec_size;
9599 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9600 rec_size > MAX_LINEINFO_REC_SIZE ||
9601 rec_size & (sizeof(u32) - 1))
9602 return -EINVAL;
9603
9604 /* Need to zero it in case the userspace may
9605 * pass in a smaller bpf_line_info object.
9606 */
9607 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9608 GFP_KERNEL | __GFP_NOWARN);
9609 if (!linfo)
9610 return -ENOMEM;
9611
9612 prog = env->prog;
9613 btf = prog->aux->btf;
9614
9615 s = 0;
9616 sub = env->subprog_info;
9617 ulinfo = u64_to_user_ptr(attr->line_info);
9618 expected_size = sizeof(struct bpf_line_info);
9619 ncopy = min_t(u32, expected_size, rec_size);
9620 for (i = 0; i < nr_linfo; i++) {
9621 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9622 if (err) {
9623 if (err == -E2BIG) {
9624 verbose(env, "nonzero tailing record in line_info");
9625 if (put_user(expected_size,
9626 &uattr->line_info_rec_size))
9627 err = -EFAULT;
9628 }
9629 goto err_free;
9630 }
9631
9632 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9633 err = -EFAULT;
9634 goto err_free;
9635 }
9636
9637 /*
9638 * Check insn_off to ensure
9639 * 1) strictly increasing AND
9640 * 2) bounded by prog->len
9641 *
9642 * The linfo[0].insn_off == 0 check logically falls into
9643 * the later "missing bpf_line_info for func..." case
9644 * because the first linfo[0].insn_off must be the
9645 * first sub also and the first sub must have
9646 * subprog_info[0].start == 0.
9647 */
9648 if ((i && linfo[i].insn_off <= prev_offset) ||
9649 linfo[i].insn_off >= prog->len) {
9650 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9651 i, linfo[i].insn_off, prev_offset,
9652 prog->len);
9653 err = -EINVAL;
9654 goto err_free;
9655 }
9656
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08009657 if (!prog->insnsi[linfo[i].insn_off].code) {
9658 verbose(env,
9659 "Invalid insn code at line_info[%u].insn_off\n",
9660 i);
9661 err = -EINVAL;
9662 goto err_free;
9663 }
9664
Martin KaFai Lau23127b32018-12-13 10:41:46 -08009665 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9666 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009667 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9668 err = -EINVAL;
9669 goto err_free;
9670 }
9671
9672 if (s != env->subprog_cnt) {
9673 if (linfo[i].insn_off == sub[s].start) {
9674 sub[s].linfo_idx = i;
9675 s++;
9676 } else if (sub[s].start < linfo[i].insn_off) {
9677 verbose(env, "missing bpf_line_info for func#%u\n", s);
9678 err = -EINVAL;
9679 goto err_free;
9680 }
9681 }
9682
9683 prev_offset = linfo[i].insn_off;
9684 ulinfo += rec_size;
9685 }
9686
9687 if (s != env->subprog_cnt) {
9688 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9689 env->subprog_cnt - s, s);
9690 err = -EINVAL;
9691 goto err_free;
9692 }
9693
9694 prog->aux->linfo = linfo;
9695 prog->aux->nr_linfo = nr_linfo;
9696
9697 return 0;
9698
9699err_free:
9700 kvfree(linfo);
9701 return err;
9702}
9703
9704static int check_btf_info(struct bpf_verifier_env *env,
9705 const union bpf_attr *attr,
9706 union bpf_attr __user *uattr)
9707{
9708 struct btf *btf;
9709 int err;
9710
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009711 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9712 if (check_abnormal_return(env))
9713 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009714 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009715 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009716
9717 btf = btf_get_by_fd(attr->prog_btf_fd);
9718 if (IS_ERR(btf))
9719 return PTR_ERR(btf);
Alexei Starovoitov350a5c42021-03-07 14:52:48 -08009720 if (btf_is_kernel(btf)) {
9721 btf_put(btf);
9722 return -EACCES;
9723 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009724 env->prog->aux->btf = btf;
9725
9726 err = check_btf_func(env, attr, uattr);
9727 if (err)
9728 return err;
9729
9730 err = check_btf_line(env, attr, uattr);
9731 if (err)
9732 return err;
9733
9734 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009735}
9736
Edward Creef1174f72017-08-07 15:26:19 +01009737/* check %cur's range satisfies %old's */
9738static bool range_within(struct bpf_reg_state *old,
9739 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009740{
Edward Creeb03c9f92017-08-07 15:26:36 +01009741 return old->umin_value <= cur->umin_value &&
9742 old->umax_value >= cur->umax_value &&
9743 old->smin_value <= cur->smin_value &&
Daniel Borkmannfd675182021-02-05 20:48:21 +01009744 old->smax_value >= cur->smax_value &&
9745 old->u32_min_value <= cur->u32_min_value &&
9746 old->u32_max_value >= cur->u32_max_value &&
9747 old->s32_min_value <= cur->s32_min_value &&
9748 old->s32_max_value >= cur->s32_max_value;
Edward Creef1174f72017-08-07 15:26:19 +01009749}
9750
9751/* Maximum number of register states that can exist at once */
9752#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9753struct idpair {
9754 u32 old;
9755 u32 cur;
9756};
9757
9758/* If in the old state two registers had the same id, then they need to have
9759 * the same id in the new state as well. But that id could be different from
9760 * the old state, so we need to track the mapping from old to new ids.
9761 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9762 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9763 * regs with a different old id could still have new id 9, we don't care about
9764 * that.
9765 * So we look through our idmap to see if this old id has been seen before. If
9766 * so, we require the new id to match; otherwise, we add the id pair to the map.
9767 */
9768static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9769{
9770 unsigned int i;
9771
9772 for (i = 0; i < ID_MAP_SIZE; i++) {
9773 if (!idmap[i].old) {
9774 /* Reached an empty slot; haven't seen this id before */
9775 idmap[i].old = old_id;
9776 idmap[i].cur = cur_id;
9777 return true;
9778 }
9779 if (idmap[i].old == old_id)
9780 return idmap[i].cur == cur_id;
9781 }
9782 /* We ran out of idmap slots, which should be impossible */
9783 WARN_ON_ONCE(1);
9784 return false;
9785}
9786
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009787static void clean_func_state(struct bpf_verifier_env *env,
9788 struct bpf_func_state *st)
9789{
9790 enum bpf_reg_liveness live;
9791 int i, j;
9792
9793 for (i = 0; i < BPF_REG_FP; i++) {
9794 live = st->regs[i].live;
9795 /* liveness must not touch this register anymore */
9796 st->regs[i].live |= REG_LIVE_DONE;
9797 if (!(live & REG_LIVE_READ))
9798 /* since the register is unused, clear its state
9799 * to make further comparison simpler
9800 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009801 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009802 }
9803
9804 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9805 live = st->stack[i].spilled_ptr.live;
9806 /* liveness must not touch this stack slot anymore */
9807 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9808 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009809 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009810 for (j = 0; j < BPF_REG_SIZE; j++)
9811 st->stack[i].slot_type[j] = STACK_INVALID;
9812 }
9813 }
9814}
9815
9816static void clean_verifier_state(struct bpf_verifier_env *env,
9817 struct bpf_verifier_state *st)
9818{
9819 int i;
9820
9821 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9822 /* all regs in this state in all frames were already marked */
9823 return;
9824
9825 for (i = 0; i <= st->curframe; i++)
9826 clean_func_state(env, st->frame[i]);
9827}
9828
9829/* the parentage chains form a tree.
9830 * the verifier states are added to state lists at given insn and
9831 * pushed into state stack for future exploration.
9832 * when the verifier reaches bpf_exit insn some of the verifer states
9833 * stored in the state lists have their final liveness state already,
9834 * but a lot of states will get revised from liveness point of view when
9835 * the verifier explores other branches.
9836 * Example:
9837 * 1: r0 = 1
9838 * 2: if r1 == 100 goto pc+1
9839 * 3: r0 = 2
9840 * 4: exit
9841 * when the verifier reaches exit insn the register r0 in the state list of
9842 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9843 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9844 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9845 *
9846 * Since the verifier pushes the branch states as it sees them while exploring
9847 * the program the condition of walking the branch instruction for the second
9848 * time means that all states below this branch were already explored and
9849 * their final liveness markes are already propagated.
9850 * Hence when the verifier completes the search of state list in is_state_visited()
9851 * we can call this clean_live_states() function to mark all liveness states
9852 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9853 * will not be used.
9854 * This function also clears the registers and stack for states that !READ
9855 * to simplify state merging.
9856 *
9857 * Important note here that walking the same branch instruction in the callee
9858 * doesn't meant that the states are DONE. The verifier has to compare
9859 * the callsites
9860 */
9861static void clean_live_states(struct bpf_verifier_env *env, int insn,
9862 struct bpf_verifier_state *cur)
9863{
9864 struct bpf_verifier_state_list *sl;
9865 int i;
9866
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009867 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009868 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009869 if (sl->state.branches)
9870 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009871 if (sl->state.insn_idx != insn ||
9872 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009873 goto next;
9874 for (i = 0; i <= cur->curframe; i++)
9875 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9876 goto next;
9877 clean_verifier_state(env, &sl->state);
9878next:
9879 sl = sl->next;
9880 }
9881}
9882
Edward Creef1174f72017-08-07 15:26:19 +01009883/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01009884static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9885 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009886{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009887 bool equal;
9888
Edward Creedc503a82017-08-15 20:34:35 +01009889 if (!(rold->live & REG_LIVE_READ))
9890 /* explored state didn't use this */
9891 return true;
9892
Edward Cree679c7822018-08-22 20:02:19 +01009893 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009894
9895 if (rold->type == PTR_TO_STACK)
9896 /* two stack pointers are equal only if they're pointing to
9897 * the same stack frame, since fp-8 in foo != fp-8 in bar
9898 */
9899 return equal && rold->frameno == rcur->frameno;
9900
9901 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01009902 return true;
9903
9904 if (rold->type == NOT_INIT)
9905 /* explored state can't have used this */
9906 return true;
9907 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009908 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009909 switch (rold->type) {
9910 case SCALAR_VALUE:
9911 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009912 if (!rold->precise && !rcur->precise)
9913 return true;
Edward Creef1174f72017-08-07 15:26:19 +01009914 /* new val must satisfy old val knowledge */
9915 return range_within(rold, rcur) &&
9916 tnum_in(rold->var_off, rcur->var_off);
9917 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08009918 /* We're trying to use a pointer in place of a scalar.
9919 * Even if the scalar was unbounded, this could lead to
9920 * pointer leaks because scalars are allowed to leak
9921 * while pointers are not. We could make this safe in
9922 * special cases if root is calling us, but it's
9923 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01009924 */
Jann Horn179d1c52017-12-18 20:11:59 -08009925 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009926 }
Yonghong Song69c087b2021-02-26 12:49:25 -08009927 case PTR_TO_MAP_KEY:
Edward Creef1174f72017-08-07 15:26:19 +01009928 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01009929 /* If the new min/max/var_off satisfy the old ones and
9930 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009931 * 'id' is not compared, since it's only used for maps with
9932 * bpf_spin_lock inside map element and in such cases if
9933 * the rest of the prog is valid for one map element then
9934 * it's valid for all map elements regardless of the key
9935 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01009936 */
9937 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9938 range_within(rold, rcur) &&
9939 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01009940 case PTR_TO_MAP_VALUE_OR_NULL:
9941 /* a PTR_TO_MAP_VALUE could be safe to use as a
9942 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9943 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9944 * checked, doing so could have affected others with the same
9945 * id, and we can't check for that because we lost the id when
9946 * we converted to a PTR_TO_MAP_VALUE.
9947 */
9948 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9949 return false;
9950 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9951 return false;
9952 /* Check our ids match any regs they're supposed to */
9953 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009954 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01009955 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009956 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01009957 return false;
9958 /* We must have at least as much range as the old ptr
9959 * did, so that any accesses which were safe before are
9960 * still safe. This is true even if old range < old off,
9961 * since someone could have accessed through (ptr - k), or
9962 * even done ptr -= k in a register, to get a safe access.
9963 */
9964 if (rold->range > rcur->range)
9965 return false;
9966 /* If the offsets don't match, we can't trust our alignment;
9967 * nor can we be sure that we won't fall out of range.
9968 */
9969 if (rold->off != rcur->off)
9970 return false;
9971 /* id relations must be preserved */
9972 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9973 return false;
9974 /* new val must satisfy old val knowledge */
9975 return range_within(rold, rcur) &&
9976 tnum_in(rold->var_off, rcur->var_off);
9977 case PTR_TO_CTX:
9978 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01009979 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07009980 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07009981 case PTR_TO_SOCKET:
9982 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009983 case PTR_TO_SOCK_COMMON:
9984 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009985 case PTR_TO_TCP_SOCK:
9986 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009987 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01009988 /* Only valid matches are exact, which memcmp() above
9989 * would have accepted
9990 */
9991 default:
9992 /* Don't know what's going on, just say it's not safe */
9993 return false;
9994 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009995
Edward Creef1174f72017-08-07 15:26:19 +01009996 /* Shouldn't get here; if we do, say it's not safe */
9997 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009998 return false;
9999}
10000
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010001static bool stacksafe(struct bpf_func_state *old,
10002 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010003 struct idpair *idmap)
10004{
10005 int i, spi;
10006
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010007 /* walk slots of the explored stack and ignore any additional
10008 * slots in the current stack, since explored(safe) state
10009 * didn't use them
10010 */
10011 for (i = 0; i < old->allocated_stack; i++) {
10012 spi = i / BPF_REG_SIZE;
10013
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010014 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10015 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010016 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +000010017 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010018 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010019
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010020 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10021 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -080010022
10023 /* explored stack has more populated slots than current stack
10024 * and these slots were used
10025 */
10026 if (i >= cur->allocated_stack)
10027 return false;
10028
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010029 /* if old state was safe with misc data in the stack
10030 * it will be safe with zero-initialized stack.
10031 * The opposite is not true
10032 */
10033 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10034 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10035 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010036 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10037 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10038 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -070010039 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010040 * this verifier states are not equivalent,
10041 * return false to continue verification of this path
10042 */
10043 return false;
10044 if (i % BPF_REG_SIZE)
10045 continue;
10046 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10047 continue;
10048 if (!regsafe(&old->stack[spi].spilled_ptr,
10049 &cur->stack[spi].spilled_ptr,
10050 idmap))
10051 /* when explored and current stack slot are both storing
10052 * spilled registers, check that stored pointers types
10053 * are the same as well.
10054 * Ex: explored safe path could have stored
10055 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10056 * but current path has stored:
10057 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10058 * such verifier states are not equivalent.
10059 * return false to continue verification of this path
10060 */
10061 return false;
10062 }
10063 return true;
10064}
10065
Joe Stringerfd978bf72018-10-02 13:35:35 -070010066static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10067{
10068 if (old->acquired_refs != cur->acquired_refs)
10069 return false;
10070 return !memcmp(old->refs, cur->refs,
10071 sizeof(*old->refs) * old->acquired_refs);
10072}
10073
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010074/* compare two verifier states
10075 *
10076 * all states stored in state_list are known to be valid, since
10077 * verifier reached 'bpf_exit' instruction through them
10078 *
10079 * this function is called when verifier exploring different branches of
10080 * execution popped from the state stack. If it sees an old state that has
10081 * more strict register state and more strict stack state then this execution
10082 * branch doesn't need to be explored further, since verifier already
10083 * concluded that more strict state leads to valid finish.
10084 *
10085 * Therefore two states are equivalent if register state is more conservative
10086 * and explored stack state is more conservative than the current one.
10087 * Example:
10088 * explored current
10089 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10090 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10091 *
10092 * In other words if current stack state (one being explored) has more
10093 * valid slots than old one that already passed validation, it means
10094 * the verifier can stop exploring and conclude that current state is valid too
10095 *
10096 * Similarly with registers. If explored state has register type as invalid
10097 * whereas register type in current state is meaningful, it means that
10098 * the current state will reach 'bpf_exit' instruction safely
10099 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010100static bool func_states_equal(struct bpf_func_state *old,
10101 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010102{
Edward Creef1174f72017-08-07 15:26:19 +010010103 struct idpair *idmap;
10104 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010105 int i;
10106
Edward Creef1174f72017-08-07 15:26:19 +010010107 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
10108 /* If we failed to allocate the idmap, just say it's not safe */
10109 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -070010110 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010111
10112 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +010010113 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +010010114 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010115 }
10116
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010117 if (!stacksafe(old, cur, idmap))
10118 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -070010119
10120 if (!refsafe(old, cur))
10121 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +010010122 ret = true;
10123out_free:
10124 kfree(idmap);
10125 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010126}
10127
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010128static bool states_equal(struct bpf_verifier_env *env,
10129 struct bpf_verifier_state *old,
10130 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +010010131{
Edward Creedc503a82017-08-15 20:34:35 +010010132 int i;
10133
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010134 if (old->curframe != cur->curframe)
10135 return false;
10136
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010137 /* Verification state from speculative execution simulation
10138 * must never prune a non-speculative execution one.
10139 */
10140 if (old->speculative && !cur->speculative)
10141 return false;
10142
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010143 if (old->active_spin_lock != cur->active_spin_lock)
10144 return false;
10145
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010146 /* for states to be equal callsites have to be the same
10147 * and all frame states need to be equivalent
10148 */
10149 for (i = 0; i <= old->curframe; i++) {
10150 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10151 return false;
10152 if (!func_states_equal(old->frame[i], cur->frame[i]))
10153 return false;
10154 }
10155 return true;
10156}
10157
Jiong Wang5327ed32019-05-24 23:25:12 +010010158/* Return 0 if no propagation happened. Return negative error code if error
10159 * happened. Otherwise, return the propagated bit.
10160 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010161static int propagate_liveness_reg(struct bpf_verifier_env *env,
10162 struct bpf_reg_state *reg,
10163 struct bpf_reg_state *parent_reg)
10164{
Jiong Wang5327ed32019-05-24 23:25:12 +010010165 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10166 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010167 int err;
10168
Jiong Wang5327ed32019-05-24 23:25:12 +010010169 /* When comes here, read flags of PARENT_REG or REG could be any of
10170 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10171 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10172 */
10173 if (parent_flag == REG_LIVE_READ64 ||
10174 /* Or if there is no read flag from REG. */
10175 !flag ||
10176 /* Or if the read flag from REG is the same as PARENT_REG. */
10177 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010178 return 0;
10179
Jiong Wang5327ed32019-05-24 23:25:12 +010010180 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010181 if (err)
10182 return err;
10183
Jiong Wang5327ed32019-05-24 23:25:12 +010010184 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010185}
10186
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010187/* A write screens off any subsequent reads; but write marks come from the
10188 * straight-line code between a state and its parent. When we arrive at an
10189 * equivalent state (jump target or such) we didn't arrive by the straight-line
10190 * code, so read marks in the state must propagate to the parent regardless
10191 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +010010192 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010193 */
10194static int propagate_liveness(struct bpf_verifier_env *env,
10195 const struct bpf_verifier_state *vstate,
10196 struct bpf_verifier_state *vparent)
10197{
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010198 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010199 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010200 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010201
10202 if (vparent->curframe != vstate->curframe) {
10203 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10204 vparent->curframe, vstate->curframe);
10205 return -EFAULT;
10206 }
Edward Creedc503a82017-08-15 20:34:35 +010010207 /* Propagate read liveness of registers... */
10208 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -070010209 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010210 parent = vparent->frame[frame];
10211 state = vstate->frame[frame];
10212 parent_reg = parent->regs;
10213 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -070010214 /* We don't need to worry about FP liveness, it's read-only */
10215 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010216 err = propagate_liveness_reg(env, &state_reg[i],
10217 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +010010218 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010219 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +010010220 if (err == REG_LIVE_READ64)
10221 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +010010222 }
Edward Creedc503a82017-08-15 20:34:35 +010010223
Jiong Wang1b04aee2019-04-12 22:59:34 +010010224 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010225 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10226 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010227 parent_reg = &parent->stack[i].spilled_ptr;
10228 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010229 err = propagate_liveness_reg(env, state_reg,
10230 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +010010231 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010232 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010233 }
Edward Creedc503a82017-08-15 20:34:35 +010010234 }
Jiong Wang5327ed32019-05-24 23:25:12 +010010235 return 0;
Edward Creedc503a82017-08-15 20:34:35 +010010236}
10237
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010238/* find precise scalars in the previous equivalent state and
10239 * propagate them into the current state
10240 */
10241static int propagate_precision(struct bpf_verifier_env *env,
10242 const struct bpf_verifier_state *old)
10243{
10244 struct bpf_reg_state *state_reg;
10245 struct bpf_func_state *state;
10246 int i, err = 0;
10247
10248 state = old->frame[old->curframe];
10249 state_reg = state->regs;
10250 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10251 if (state_reg->type != SCALAR_VALUE ||
10252 !state_reg->precise)
10253 continue;
10254 if (env->log.level & BPF_LOG_LEVEL2)
10255 verbose(env, "propagating r%d\n", i);
10256 err = mark_chain_precision(env, i);
10257 if (err < 0)
10258 return err;
10259 }
10260
10261 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10262 if (state->stack[i].slot_type[0] != STACK_SPILL)
10263 continue;
10264 state_reg = &state->stack[i].spilled_ptr;
10265 if (state_reg->type != SCALAR_VALUE ||
10266 !state_reg->precise)
10267 continue;
10268 if (env->log.level & BPF_LOG_LEVEL2)
10269 verbose(env, "propagating fp%d\n",
10270 (-i - 1) * BPF_REG_SIZE);
10271 err = mark_chain_precision_stack(env, i);
10272 if (err < 0)
10273 return err;
10274 }
10275 return 0;
10276}
10277
Alexei Starovoitov25897262019-06-15 12:12:20 -070010278static bool states_maybe_looping(struct bpf_verifier_state *old,
10279 struct bpf_verifier_state *cur)
10280{
10281 struct bpf_func_state *fold, *fcur;
10282 int i, fr = cur->curframe;
10283
10284 if (old->curframe != fr)
10285 return false;
10286
10287 fold = old->frame[fr];
10288 fcur = cur->frame[fr];
10289 for (i = 0; i < MAX_BPF_REG; i++)
10290 if (memcmp(&fold->regs[i], &fcur->regs[i],
10291 offsetof(struct bpf_reg_state, parent)))
10292 return false;
10293 return true;
10294}
10295
10296
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010297static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010298{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010299 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010300 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +010010301 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080010302 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070010303 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010304
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010305 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010306 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010307 /* this 'insn_idx' instruction wasn't marked, so we will not
10308 * be doing state search here
10309 */
10310 return 0;
10311
Alexei Starovoitov25897262019-06-15 12:12:20 -070010312 /* bpf progs typically have pruning point every 4 instructions
10313 * http://vger.kernel.org/bpfconf2019.html#session-1
10314 * Do not add new state for future pruning if the verifier hasn't seen
10315 * at least 2 jumps and at least 8 instructions.
10316 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10317 * In tests that amounts to up to 50% reduction into total verifier
10318 * memory consumption and 20% verifier time speedup.
10319 */
10320 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10321 env->insn_processed - env->prev_insn_processed >= 8)
10322 add_new_state = true;
10323
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010324 pprev = explored_state(env, insn_idx);
10325 sl = *pprev;
10326
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010327 clean_live_states(env, insn_idx, cur);
10328
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010329 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010330 states_cnt++;
10331 if (sl->state.insn_idx != insn_idx)
10332 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010333 if (sl->state.branches) {
10334 if (states_maybe_looping(&sl->state, cur) &&
10335 states_equal(env, &sl->state, cur)) {
10336 verbose_linfo(env, insn_idx, "; ");
10337 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10338 return -EINVAL;
10339 }
10340 /* if the verifier is processing a loop, avoid adding new state
10341 * too often, since different loop iterations have distinct
10342 * states and may not help future pruning.
10343 * This threshold shouldn't be too low to make sure that
10344 * a loop with large bound will be rejected quickly.
10345 * The most abusive loop will be:
10346 * r1 += 1
10347 * if r1 < 1000000 goto pc-2
10348 * 1M insn_procssed limit / 100 == 10k peak states.
10349 * This threshold shouldn't be too high either, since states
10350 * at the end of the loop are likely to be useful in pruning.
10351 */
10352 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10353 env->insn_processed - env->prev_insn_processed < 100)
10354 add_new_state = false;
10355 goto miss;
10356 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010357 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010358 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010359 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +010010360 * prune the search.
10361 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +010010362 * If we have any write marks in env->cur_state, they
10363 * will prevent corresponding reads in the continuation
10364 * from reaching our parent (an explored_state). Our
10365 * own state will get the read marks recorded, but
10366 * they'll be immediately forgotten as we're pruning
10367 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010368 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010369 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010370
10371 /* if previous state reached the exit with precision and
10372 * current state is equivalent to it (except precsion marks)
10373 * the precision needs to be propagated back in
10374 * the current state.
10375 */
10376 err = err ? : push_jmp_history(env, cur);
10377 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010378 if (err)
10379 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010380 return 1;
Edward Creedc503a82017-08-15 20:34:35 +010010381 }
Alexei Starovoitov25897262019-06-15 12:12:20 -070010382miss:
10383 /* when new state is not going to be added do not increase miss count.
10384 * Otherwise several loop iterations will remove the state
10385 * recorded earlier. The goal of these heuristics is to have
10386 * states from some iterations of the loop (some in the beginning
10387 * and some at the end) to help pruning.
10388 */
10389 if (add_new_state)
10390 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010391 /* heuristic to determine whether this state is beneficial
10392 * to keep checking from state equivalence point of view.
10393 * Higher numbers increase max_states_per_insn and verification time,
10394 * but do not meaningfully decrease insn_processed.
10395 */
10396 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10397 /* the state is unlikely to be useful. Remove it to
10398 * speed up verification
10399 */
10400 *pprev = sl->next;
10401 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -070010402 u32 br = sl->state.branches;
10403
10404 WARN_ONCE(br,
10405 "BUG live_done but branches_to_explore %d\n",
10406 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010407 free_verifier_state(&sl->state, false);
10408 kfree(sl);
10409 env->peak_states--;
10410 } else {
10411 /* cannot free this state, since parentage chain may
10412 * walk it later. Add it for free_list instead to
10413 * be freed at the end of verification
10414 */
10415 sl->next = env->free_list;
10416 env->free_list = sl;
10417 }
10418 sl = *pprev;
10419 continue;
10420 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010421next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010422 pprev = &sl->next;
10423 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010424 }
10425
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010426 if (env->max_states_per_insn < states_cnt)
10427 env->max_states_per_insn = states_cnt;
10428
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070010429 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010430 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080010431
Alexei Starovoitov25897262019-06-15 12:12:20 -070010432 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010433 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -070010434
10435 /* There were no equivalent states, remember the current one.
10436 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010437 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -070010438 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010439 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -070010440 * again on the way to bpf_exit.
10441 * When looping the sl->state.branches will be > 0 and this state
10442 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010443 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010444 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010445 if (!new_sl)
10446 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010447 env->total_states++;
10448 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010449 env->prev_jmps_processed = env->jmps_processed;
10450 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010451
10452 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +010010453 new = &new_sl->state;
10454 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070010455 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +010010456 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070010457 kfree(new_sl);
10458 return err;
10459 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010460 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010461 WARN_ONCE(new->branches != 1,
10462 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010463
Alexei Starovoitov25897262019-06-15 12:12:20 -070010464 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010465 cur->first_insn_idx = insn_idx;
10466 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -070010467 new_sl->next = *explored_state(env, insn_idx);
10468 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -080010469 /* connect new state to parentage chain. Current frame needs all
10470 * registers connected. Only r6 - r9 of the callers are alive (pushed
10471 * to the stack implicitly by JITs) so in callers' frames connect just
10472 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10473 * the state of the call instruction (with WRITTEN set), and r0 comes
10474 * from callee with its full parentage chain, anyway.
10475 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +010010476 /* clear write marks in current state: the writes we did are not writes
10477 * our child did, so they don't screen off its reads from us.
10478 * (There are no read marks in current state, because reads always mark
10479 * their parent and current state never has children yet. Only
10480 * explored_states can get read marks.)
10481 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -070010482 for (j = 0; j <= cur->curframe; j++) {
10483 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10484 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10485 for (i = 0; i < BPF_REG_FP; i++)
10486 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10487 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010488
10489 /* all stack frames are accessible from callee, clear them all */
10490 for (j = 0; j <= cur->curframe; j++) {
10491 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +010010492 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010493
Edward Cree679c7822018-08-22 20:02:19 +010010494 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010495 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +010010496 frame->stack[i].spilled_ptr.parent =
10497 &newframe->stack[i].spilled_ptr;
10498 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010499 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010500 return 0;
10501}
10502
Joe Stringerc64b7982018-10-02 13:35:33 -070010503/* Return true if it's OK to have the same insn return a different type. */
10504static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10505{
10506 switch (type) {
10507 case PTR_TO_CTX:
10508 case PTR_TO_SOCKET:
10509 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010510 case PTR_TO_SOCK_COMMON:
10511 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010512 case PTR_TO_TCP_SOCK:
10513 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010514 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010515 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -070010516 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -070010517 return false;
10518 default:
10519 return true;
10520 }
10521}
10522
10523/* If an instruction was previously used with particular pointer types, then we
10524 * need to be careful to avoid cases such as the below, where it may be ok
10525 * for one branch accessing the pointer, but not ok for the other branch:
10526 *
10527 * R1 = sock_ptr
10528 * goto X;
10529 * ...
10530 * R1 = some_other_valid_ptr;
10531 * goto X;
10532 * ...
10533 * R2 = *(u32 *)(R1 + 0);
10534 */
10535static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10536{
10537 return src != prev && (!reg_type_mismatch_ok(src) ||
10538 !reg_type_mismatch_ok(prev));
10539}
10540
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010541static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010542{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010543 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010544 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010545 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010546 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010547 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010548 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010549 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010550
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010551 for (;;) {
10552 struct bpf_insn *insn;
10553 u8 class;
10554 int err;
10555
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010556 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010557 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010558 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010559 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010560 return -EFAULT;
10561 }
10562
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010563 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010564 class = BPF_CLASS(insn->code);
10565
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010566 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010567 verbose(env,
10568 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010569 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010570 return -E2BIG;
10571 }
10572
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010573 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010574 if (err < 0)
10575 return err;
10576 if (err == 1) {
10577 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010578 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010579 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010580 verbose(env, "\nfrom %d to %d%s: safe\n",
10581 env->prev_insn_idx, env->insn_idx,
10582 env->cur_state->speculative ?
10583 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010584 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010585 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010586 }
10587 goto process_bpf_exit;
10588 }
10589
Alexei Starovoitovc3494802018-12-03 22:46:04 -080010590 if (signal_pending(current))
10591 return -EAGAIN;
10592
Daniel Borkmann3c2ce602017-05-18 03:00:06 +020010593 if (need_resched())
10594 cond_resched();
10595
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010596 if (env->log.level & BPF_LOG_LEVEL2 ||
10597 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10598 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010599 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -070010600 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010601 verbose(env, "\nfrom %d to %d%s:",
10602 env->prev_insn_idx, env->insn_idx,
10603 env->cur_state->speculative ?
10604 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010605 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010606 do_print_state = false;
10607 }
10608
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010609 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010610 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010611 .cb_call = disasm_kfunc_name,
Daniel Borkmann7105e822017-12-20 13:42:57 +010010612 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +010010613 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +010010614 };
10615
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010616 verbose_linfo(env, env->insn_idx, "; ");
10617 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +010010618 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010619 }
10620
Jakub Kicinskicae19272017-12-27 18:39:05 -080010621 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010622 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10623 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -080010624 if (err)
10625 return err;
10626 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +010010627
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010628 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010629 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010630 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -070010631
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010632 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -070010633 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010634 if (err)
10635 return err;
10636
10637 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010638 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010639
10640 /* check for reserved fields is already done */
10641
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010642 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010643 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010644 if (err)
10645 return err;
10646
Edward Creedc503a82017-08-15 20:34:35 +010010647 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010648 if (err)
10649 return err;
10650
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -070010651 src_reg_type = regs[insn->src_reg].type;
10652
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010653 /* check that memory (src_reg + off) is readable,
10654 * the state of dst_reg will be updated by this func
10655 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010656 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10657 insn->off, BPF_SIZE(insn->code),
10658 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010659 if (err)
10660 return err;
10661
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010662 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010663
10664 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010665 /* saw a valid insn
10666 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010667 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010668 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010669 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010670
Joe Stringerc64b7982018-10-02 13:35:33 -070010671 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010672 /* ABuser program is trying to use the same insn
10673 * dst_reg = *(u32*) (src_reg + off)
10674 * with different pointer types:
10675 * src_reg == ctx in one branch and
10676 * src_reg == stack|map in some other branch.
10677 * Reject it.
10678 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010679 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010680 return -EINVAL;
10681 }
10682
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010683 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010684 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010685
Brendan Jackman91c960b2021-01-14 18:17:44 +000010686 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10687 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010688 if (err)
10689 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010690 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010691 continue;
10692 }
10693
Brendan Jackman5ca419f2021-01-14 18:17:46 +000010694 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10695 verbose(env, "BPF_STX uses reserved fields\n");
10696 return -EINVAL;
10697 }
10698
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010699 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010700 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010701 if (err)
10702 return err;
10703 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010704 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010705 if (err)
10706 return err;
10707
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010708 dst_reg_type = regs[insn->dst_reg].type;
10709
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010710 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010711 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10712 insn->off, BPF_SIZE(insn->code),
10713 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010714 if (err)
10715 return err;
10716
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010717 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010718
10719 if (*prev_dst_type == NOT_INIT) {
10720 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070010721 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010722 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010723 return -EINVAL;
10724 }
10725
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010726 } else if (class == BPF_ST) {
10727 if (BPF_MODE(insn->code) != BPF_MEM ||
10728 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010729 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010730 return -EINVAL;
10731 }
10732 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010733 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010734 if (err)
10735 return err;
10736
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010737 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070010738 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020010739 insn->dst_reg,
10740 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010741 return -EACCES;
10742 }
10743
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010744 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010745 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10746 insn->off, BPF_SIZE(insn->code),
10747 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010748 if (err)
10749 return err;
10750
Jiong Wang092ed092019-01-26 12:26:01 -050010751 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010752 u8 opcode = BPF_OP(insn->code);
10753
Alexei Starovoitov25897262019-06-15 12:12:20 -070010754 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010755 if (opcode == BPF_CALL) {
10756 if (BPF_SRC(insn->code) != BPF_K ||
10757 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010758 (insn->src_reg != BPF_REG_0 &&
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010759 insn->src_reg != BPF_PSEUDO_CALL &&
10760 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050010761 insn->dst_reg != BPF_REG_0 ||
10762 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010763 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010764 return -EINVAL;
10765 }
10766
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010767 if (env->cur_state->active_spin_lock &&
10768 (insn->src_reg == BPF_PSEUDO_CALL ||
10769 insn->imm != BPF_FUNC_spin_unlock)) {
10770 verbose(env, "function calls are not allowed while holding a lock\n");
10771 return -EINVAL;
10772 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010773 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010774 err = check_func_call(env, insn, &env->insn_idx);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010775 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10776 err = check_kfunc_call(env, insn);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010777 else
Yonghong Song69c087b2021-02-26 12:49:25 -080010778 err = check_helper_call(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010779 if (err)
10780 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010781 } else if (opcode == BPF_JA) {
10782 if (BPF_SRC(insn->code) != BPF_K ||
10783 insn->imm != 0 ||
10784 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010785 insn->dst_reg != BPF_REG_0 ||
10786 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010787 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010788 return -EINVAL;
10789 }
10790
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010791 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010792 continue;
10793
10794 } else if (opcode == BPF_EXIT) {
10795 if (BPF_SRC(insn->code) != BPF_K ||
10796 insn->imm != 0 ||
10797 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010798 insn->dst_reg != BPF_REG_0 ||
10799 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010800 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010801 return -EINVAL;
10802 }
10803
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010804 if (env->cur_state->active_spin_lock) {
10805 verbose(env, "bpf_spin_unlock is missing\n");
10806 return -EINVAL;
10807 }
10808
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010809 if (state->curframe) {
10810 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010811 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010812 if (err)
10813 return err;
10814 do_print_state = true;
10815 continue;
10816 }
10817
Joe Stringerfd978bf72018-10-02 13:35:35 -070010818 err = check_reference_leak(env);
10819 if (err)
10820 return err;
10821
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070010822 err = check_return_code(env);
10823 if (err)
10824 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010825process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -070010826 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010827 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010828 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010829 if (err < 0) {
10830 if (err != -ENOENT)
10831 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010832 break;
10833 } else {
10834 do_print_state = true;
10835 continue;
10836 }
10837 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010838 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010839 if (err)
10840 return err;
10841 }
10842 } else if (class == BPF_LD) {
10843 u8 mode = BPF_MODE(insn->code);
10844
10845 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080010846 err = check_ld_abs(env, insn);
10847 if (err)
10848 return err;
10849
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010850 } else if (mode == BPF_IMM) {
10851 err = check_ld_imm(env, insn);
10852 if (err)
10853 return err;
10854
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010855 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010856 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010857 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010858 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010859 return -EINVAL;
10860 }
10861 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010862 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010863 return -EINVAL;
10864 }
10865
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010866 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010867 }
10868
10869 return 0;
10870}
10871
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010872static int find_btf_percpu_datasec(struct btf *btf)
10873{
10874 const struct btf_type *t;
10875 const char *tname;
10876 int i, n;
10877
10878 /*
10879 * Both vmlinux and module each have their own ".data..percpu"
10880 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10881 * types to look at only module's own BTF types.
10882 */
10883 n = btf_nr_types(btf);
10884 if (btf_is_module(btf))
10885 i = btf_nr_types(btf_vmlinux);
10886 else
10887 i = 1;
10888
10889 for(; i < n; i++) {
10890 t = btf_type_by_id(btf, i);
10891 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10892 continue;
10893
10894 tname = btf_name_by_offset(btf, t->name_off);
10895 if (!strcmp(tname, ".data..percpu"))
10896 return i;
10897 }
10898
10899 return -ENOENT;
10900}
10901
Hao Luo4976b712020-09-29 16:50:44 -070010902/* replace pseudo btf_id with kernel symbol address */
10903static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10904 struct bpf_insn *insn,
10905 struct bpf_insn_aux_data *aux)
10906{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010907 const struct btf_var_secinfo *vsi;
10908 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010909 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070010910 const struct btf_type *t;
10911 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010912 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010913 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010914 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010915 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070010916 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010917 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070010918
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010919 btf_fd = insn[1].imm;
10920 if (btf_fd) {
10921 btf = btf_get_by_fd(btf_fd);
10922 if (IS_ERR(btf)) {
10923 verbose(env, "invalid module BTF object FD specified.\n");
10924 return -EINVAL;
10925 }
10926 } else {
10927 if (!btf_vmlinux) {
10928 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10929 return -EINVAL;
10930 }
10931 btf = btf_vmlinux;
10932 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070010933 }
10934
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010935 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070010936 if (!t) {
10937 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010938 err = -ENOENT;
10939 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010940 }
10941
10942 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010943 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10944 err = -EINVAL;
10945 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010946 }
10947
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010948 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010949 addr = kallsyms_lookup_name(sym_name);
10950 if (!addr) {
10951 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10952 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010953 err = -ENOENT;
10954 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010955 }
10956
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010957 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010958 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010959 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010960 for_each_vsi(i, datasec, vsi) {
10961 if (vsi->type == id) {
10962 percpu = true;
10963 break;
10964 }
10965 }
10966 }
10967
Hao Luo4976b712020-09-29 16:50:44 -070010968 insn[0].imm = (u32)addr;
10969 insn[1].imm = addr >> 32;
10970
10971 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010972 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010973 if (percpu) {
10974 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010975 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010976 aux->btf_var.btf_id = type;
10977 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070010978 const struct btf_type *ret;
10979 const char *tname;
10980 u32 tsize;
10981
10982 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010983 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070010984 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010985 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010986 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10987 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010988 err = -EINVAL;
10989 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010990 }
10991 aux->btf_var.reg_type = PTR_TO_MEM;
10992 aux->btf_var.mem_size = tsize;
10993 } else {
10994 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010995 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070010996 aux->btf_var.btf_id = type;
10997 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010998
10999 /* check whether we recorded this BTF (and maybe module) already */
11000 for (i = 0; i < env->used_btf_cnt; i++) {
11001 if (env->used_btfs[i].btf == btf) {
11002 btf_put(btf);
11003 return 0;
11004 }
11005 }
11006
11007 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11008 err = -E2BIG;
11009 goto err_put;
11010 }
11011
11012 btf_mod = &env->used_btfs[env->used_btf_cnt];
11013 btf_mod->btf = btf;
11014 btf_mod->module = NULL;
11015
11016 /* if we reference variables from kernel module, bump its refcount */
11017 if (btf_is_module(btf)) {
11018 btf_mod->module = btf_try_get_module(btf);
11019 if (!btf_mod->module) {
11020 err = -ENXIO;
11021 goto err_put;
11022 }
11023 }
11024
11025 env->used_btf_cnt++;
11026
Hao Luo4976b712020-09-29 16:50:44 -070011027 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011028err_put:
11029 btf_put(btf);
11030 return err;
Hao Luo4976b712020-09-29 16:50:44 -070011031}
11032
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011033static int check_map_prealloc(struct bpf_map *map)
11034{
11035 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070011036 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11037 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011038 !(map->map_flags & BPF_F_NO_PREALLOC);
11039}
11040
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011041static bool is_tracing_prog_type(enum bpf_prog_type type)
11042{
11043 switch (type) {
11044 case BPF_PROG_TYPE_KPROBE:
11045 case BPF_PROG_TYPE_TRACEPOINT:
11046 case BPF_PROG_TYPE_PERF_EVENT:
11047 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11048 return true;
11049 default:
11050 return false;
11051 }
11052}
11053
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011054static bool is_preallocated_map(struct bpf_map *map)
11055{
11056 if (!check_map_prealloc(map))
11057 return false;
11058 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11059 return false;
11060 return true;
11061}
11062
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011063static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11064 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011065 struct bpf_prog *prog)
11066
11067{
Udip Pant7e407812020-08-25 16:20:00 -070011068 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011069 /*
11070 * Validate that trace type programs use preallocated hash maps.
11071 *
11072 * For programs attached to PERF events this is mandatory as the
11073 * perf NMI can hit any arbitrary code sequence.
11074 *
11075 * All other trace types using preallocated hash maps are unsafe as
11076 * well because tracepoint or kprobes can be inside locked regions
11077 * of the memory allocator or at a place where a recursion into the
11078 * memory allocator would see inconsistent state.
11079 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011080 * On RT enabled kernels run-time allocation of all trace type
11081 * programs is strictly prohibited due to lock type constraints. On
11082 * !RT kernels it is allowed for backwards compatibility reasons for
11083 * now, but warnings are emitted so developers are made aware of
11084 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011085 */
Udip Pant7e407812020-08-25 16:20:00 -070011086 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11087 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011088 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011089 return -EINVAL;
11090 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011091 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11092 verbose(env, "trace type programs can only use preallocated hash map\n");
11093 return -EINVAL;
11094 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011095 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11096 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n");
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011097 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080011098
KP Singh9e7a4d92020-11-06 10:37:39 +000011099 if (map_value_has_spin_lock(map)) {
11100 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11101 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11102 return -EINVAL;
11103 }
11104
11105 if (is_tracing_prog_type(prog_type)) {
11106 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11107 return -EINVAL;
11108 }
11109
11110 if (prog->aux->sleepable) {
11111 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11112 return -EINVAL;
11113 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011114 }
11115
Jakub Kicinskia3884572018-01-11 20:29:09 -080011116 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070011117 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080011118 verbose(env, "offload device mismatch between prog and map\n");
11119 return -EINVAL;
11120 }
11121
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080011122 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11123 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11124 return -EINVAL;
11125 }
11126
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011127 if (prog->aux->sleepable)
11128 switch (map->map_type) {
11129 case BPF_MAP_TYPE_HASH:
11130 case BPF_MAP_TYPE_LRU_HASH:
11131 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011132 case BPF_MAP_TYPE_PERCPU_HASH:
11133 case BPF_MAP_TYPE_PERCPU_ARRAY:
11134 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11135 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11136 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011137 if (!is_preallocated_map(map)) {
11138 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011139 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011140 return -EINVAL;
11141 }
11142 break;
KP Singhba90c2c2021-02-04 19:36:21 +000011143 case BPF_MAP_TYPE_RINGBUF:
11144 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011145 default:
11146 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000011147 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011148 return -EINVAL;
11149 }
11150
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011151 return 0;
11152}
11153
Roman Gushchinb741f162018-09-28 14:45:43 +000011154static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11155{
11156 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11157 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11158}
11159
Hao Luo4976b712020-09-29 16:50:44 -070011160/* find and rewrite pseudo imm in ld_imm64 instructions:
11161 *
11162 * 1. if it accesses map FD, replace it with actual map pointer.
11163 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11164 *
11165 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011166 */
Hao Luo4976b712020-09-29 16:50:44 -070011167static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011168{
11169 struct bpf_insn *insn = env->prog->insnsi;
11170 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011171 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011172
Daniel Borkmannf1f77142017-01-13 23:38:15 +010011173 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010011174 if (err)
11175 return err;
11176
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011177 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011178 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011179 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011180 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011181 return -EINVAL;
11182 }
11183
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011184 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011185 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011186 struct bpf_map *map;
11187 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011188 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011189
11190 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11191 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11192 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011193 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011194 return -EINVAL;
11195 }
11196
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011197 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011198 /* valid generic load 64-bit imm */
11199 goto next_insn;
11200
Hao Luo4976b712020-09-29 16:50:44 -070011201 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11202 aux = &env->insn_aux_data[i];
11203 err = check_pseudo_btf_id(env, insn, aux);
11204 if (err)
11205 return err;
11206 goto next_insn;
11207 }
11208
Yonghong Song69c087b2021-02-26 12:49:25 -080011209 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11210 aux = &env->insn_aux_data[i];
11211 aux->ptr_type = PTR_TO_FUNC;
11212 goto next_insn;
11213 }
11214
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011215 /* In final convert_pseudo_ld_imm64() step, this is
11216 * converted into regular 64-bit imm load insn.
11217 */
11218 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
11219 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
11220 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
11221 insn[1].imm != 0)) {
11222 verbose(env,
11223 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011224 return -EINVAL;
11225 }
11226
Daniel Borkmann20182392019-03-04 21:08:53 +010011227 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +010011228 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011229 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011230 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010011231 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011232 return PTR_ERR(map);
11233 }
11234
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011235 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011236 if (err) {
11237 fdput(f);
11238 return err;
11239 }
11240
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011241 aux = &env->insn_aux_data[i];
11242 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
11243 addr = (unsigned long)map;
11244 } else {
11245 u32 off = insn[1].imm;
11246
11247 if (off >= BPF_MAX_VAR_OFF) {
11248 verbose(env, "direct value offset of %u is not allowed\n", off);
11249 fdput(f);
11250 return -EINVAL;
11251 }
11252
11253 if (!map->ops->map_direct_value_addr) {
11254 verbose(env, "no direct value access support for this map type\n");
11255 fdput(f);
11256 return -EINVAL;
11257 }
11258
11259 err = map->ops->map_direct_value_addr(map, &addr, off);
11260 if (err) {
11261 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11262 map->value_size, off);
11263 fdput(f);
11264 return err;
11265 }
11266
11267 aux->map_off = off;
11268 addr += off;
11269 }
11270
11271 insn[0].imm = (u32)addr;
11272 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011273
11274 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011275 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011276 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011277 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011278 fdput(f);
11279 goto next_insn;
11280 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011281 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011282
11283 if (env->used_map_cnt >= MAX_USED_MAPS) {
11284 fdput(f);
11285 return -E2BIG;
11286 }
11287
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011288 /* hold the map. If the program is rejected by verifier,
11289 * the map will be released by release_maps() or it
11290 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070011291 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011292 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080011293 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011294
11295 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070011296 env->used_maps[env->used_map_cnt++] = map;
11297
Roman Gushchinb741f162018-09-28 14:45:43 +000011298 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010011299 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000011300 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070011301 fdput(f);
11302 return -EBUSY;
11303 }
11304
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011305 fdput(f);
11306next_insn:
11307 insn++;
11308 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010011309 continue;
11310 }
11311
11312 /* Basic sanity check before we invest more work here. */
11313 if (!bpf_opcode_in_insntable(insn->code)) {
11314 verbose(env, "unknown opcode %02x\n", insn->code);
11315 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011316 }
11317 }
11318
11319 /* now all pseudo BPF_LD_IMM64 instructions load valid
11320 * 'struct bpf_map *' into a register instead of user map_fd.
11321 * These pointers will be used later by verifier to validate map access.
11322 */
11323 return 0;
11324}
11325
11326/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011327static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011328{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010011329 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11330 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011331}
11332
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011333/* drop refcnt of maps used by the rejected program */
11334static void release_btfs(struct bpf_verifier_env *env)
11335{
11336 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11337 env->used_btf_cnt);
11338}
11339
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011340/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011341static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011342{
11343 struct bpf_insn *insn = env->prog->insnsi;
11344 int insn_cnt = env->prog->len;
11345 int i;
11346
Yonghong Song69c087b2021-02-26 12:49:25 -080011347 for (i = 0; i < insn_cnt; i++, insn++) {
11348 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11349 continue;
11350 if (insn->src_reg == BPF_PSEUDO_FUNC)
11351 continue;
11352 insn->src_reg = 0;
11353 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011354}
11355
Alexei Starovoitov80419022017-03-15 18:26:41 -070011356/* single env->prog->insni[off] instruction was replaced with the range
11357 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11358 * [0, off) and [off, end) to new locations, so the patched range stays zero
11359 */
Jiong Wangb325fbc2019-05-24 23:25:13 +010011360static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11361 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070011362{
11363 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011364 struct bpf_insn *insn = new_prog->insnsi;
11365 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011366 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011367
Jiong Wangb325fbc2019-05-24 23:25:13 +010011368 /* aux info at OFF always needs adjustment, no matter fast path
11369 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11370 * original insn at old prog.
11371 */
11372 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11373
Alexei Starovoitov80419022017-03-15 18:26:41 -070011374 if (cnt == 1)
11375 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011376 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -070011377 new_data = vzalloc(array_size(prog_len,
11378 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -070011379 if (!new_data)
11380 return -ENOMEM;
11381 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11382 memcpy(new_data + off + cnt - 1, old_data + off,
11383 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010011384 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011385 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011386 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11387 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070011388 env->insn_aux_data = new_data;
11389 vfree(old_data);
11390 return 0;
11391}
11392
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011393static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11394{
11395 int i;
11396
11397 if (len == 1)
11398 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040011399 /* NOTE: fake 'exit' subprog should be updated as well. */
11400 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000011401 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011402 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040011403 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011404 }
11405}
11406
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011407static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
11408{
11409 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11410 int i, sz = prog->aux->size_poke_tab;
11411 struct bpf_jit_poke_descriptor *desc;
11412
11413 for (i = 0; i < sz; i++) {
11414 desc = &tab[i];
11415 desc->insn_idx += len - 1;
11416 }
11417}
11418
Alexei Starovoitov80419022017-03-15 18:26:41 -070011419static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11420 const struct bpf_insn *patch, u32 len)
11421{
11422 struct bpf_prog *new_prog;
11423
11424 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070011425 if (IS_ERR(new_prog)) {
11426 if (PTR_ERR(new_prog) == -ERANGE)
11427 verbose(env,
11428 "insn %d cannot be patched due to 16-bit range\n",
11429 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -070011430 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070011431 }
Jiong Wangb325fbc2019-05-24 23:25:13 +010011432 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -070011433 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011434 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011435 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070011436 return new_prog;
11437}
11438
Jakub Kicinski52875a02019-01-22 22:45:20 -080011439static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11440 u32 off, u32 cnt)
11441{
11442 int i, j;
11443
11444 /* find first prog starting at or after off (first to remove) */
11445 for (i = 0; i < env->subprog_cnt; i++)
11446 if (env->subprog_info[i].start >= off)
11447 break;
11448 /* find first prog starting at or after off + cnt (first to stay) */
11449 for (j = i; j < env->subprog_cnt; j++)
11450 if (env->subprog_info[j].start >= off + cnt)
11451 break;
11452 /* if j doesn't start exactly at off + cnt, we are just removing
11453 * the front of previous prog
11454 */
11455 if (env->subprog_info[j].start != off + cnt)
11456 j--;
11457
11458 if (j > i) {
11459 struct bpf_prog_aux *aux = env->prog->aux;
11460 int move;
11461
11462 /* move fake 'exit' subprog as well */
11463 move = env->subprog_cnt + 1 - j;
11464
11465 memmove(env->subprog_info + i,
11466 env->subprog_info + j,
11467 sizeof(*env->subprog_info) * move);
11468 env->subprog_cnt -= j - i;
11469
11470 /* remove func_info */
11471 if (aux->func_info) {
11472 move = aux->func_info_cnt - j;
11473
11474 memmove(aux->func_info + i,
11475 aux->func_info + j,
11476 sizeof(*aux->func_info) * move);
11477 aux->func_info_cnt -= j - i;
11478 /* func_info->insn_off is set after all code rewrites,
11479 * in adjust_btf_func() - no need to adjust
11480 */
11481 }
11482 } else {
11483 /* convert i from "first prog to remove" to "first to adjust" */
11484 if (env->subprog_info[i].start == off)
11485 i++;
11486 }
11487
11488 /* update fake 'exit' subprog as well */
11489 for (; i <= env->subprog_cnt; i++)
11490 env->subprog_info[i].start -= cnt;
11491
11492 return 0;
11493}
11494
11495static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11496 u32 cnt)
11497{
11498 struct bpf_prog *prog = env->prog;
11499 u32 i, l_off, l_cnt, nr_linfo;
11500 struct bpf_line_info *linfo;
11501
11502 nr_linfo = prog->aux->nr_linfo;
11503 if (!nr_linfo)
11504 return 0;
11505
11506 linfo = prog->aux->linfo;
11507
11508 /* find first line info to remove, count lines to be removed */
11509 for (i = 0; i < nr_linfo; i++)
11510 if (linfo[i].insn_off >= off)
11511 break;
11512
11513 l_off = i;
11514 l_cnt = 0;
11515 for (; i < nr_linfo; i++)
11516 if (linfo[i].insn_off < off + cnt)
11517 l_cnt++;
11518 else
11519 break;
11520
11521 /* First live insn doesn't match first live linfo, it needs to "inherit"
11522 * last removed linfo. prog is already modified, so prog->len == off
11523 * means no live instructions after (tail of the program was removed).
11524 */
11525 if (prog->len != off && l_cnt &&
11526 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11527 l_cnt--;
11528 linfo[--i].insn_off = off + cnt;
11529 }
11530
11531 /* remove the line info which refer to the removed instructions */
11532 if (l_cnt) {
11533 memmove(linfo + l_off, linfo + i,
11534 sizeof(*linfo) * (nr_linfo - i));
11535
11536 prog->aux->nr_linfo -= l_cnt;
11537 nr_linfo = prog->aux->nr_linfo;
11538 }
11539
11540 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11541 for (i = l_off; i < nr_linfo; i++)
11542 linfo[i].insn_off -= cnt;
11543
11544 /* fix up all subprogs (incl. 'exit') which start >= off */
11545 for (i = 0; i <= env->subprog_cnt; i++)
11546 if (env->subprog_info[i].linfo_idx > l_off) {
11547 /* program may have started in the removed region but
11548 * may not be fully removed
11549 */
11550 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11551 env->subprog_info[i].linfo_idx -= l_cnt;
11552 else
11553 env->subprog_info[i].linfo_idx = l_off;
11554 }
11555
11556 return 0;
11557}
11558
11559static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11560{
11561 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11562 unsigned int orig_prog_len = env->prog->len;
11563 int err;
11564
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011565 if (bpf_prog_is_dev_bound(env->prog->aux))
11566 bpf_prog_offload_remove_insns(env, off, cnt);
11567
Jakub Kicinski52875a02019-01-22 22:45:20 -080011568 err = bpf_remove_insns(env->prog, off, cnt);
11569 if (err)
11570 return err;
11571
11572 err = adjust_subprog_starts_after_remove(env, off, cnt);
11573 if (err)
11574 return err;
11575
11576 err = bpf_adj_linfo_after_remove(env, off, cnt);
11577 if (err)
11578 return err;
11579
11580 memmove(aux_data + off, aux_data + off + cnt,
11581 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11582
11583 return 0;
11584}
11585
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011586/* The verifier does more data flow analysis than llvm and will not
11587 * explore branches that are dead at run time. Malicious programs can
11588 * have dead code too. Therefore replace all dead at-run-time code
11589 * with 'ja -1'.
11590 *
11591 * Just nops are not optimal, e.g. if they would sit at the end of the
11592 * program and through another bug we would manage to jump there, then
11593 * we'd execute beyond program memory otherwise. Returning exception
11594 * code also wouldn't work since we can have subprogs where the dead
11595 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011596 */
11597static void sanitize_dead_code(struct bpf_verifier_env *env)
11598{
11599 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011600 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011601 struct bpf_insn *insn = env->prog->insnsi;
11602 const int insn_cnt = env->prog->len;
11603 int i;
11604
11605 for (i = 0; i < insn_cnt; i++) {
11606 if (aux_data[i].seen)
11607 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011608 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011609 }
11610}
11611
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011612static bool insn_is_cond_jump(u8 code)
11613{
11614 u8 op;
11615
Jiong Wang092ed092019-01-26 12:26:01 -050011616 if (BPF_CLASS(code) == BPF_JMP32)
11617 return true;
11618
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011619 if (BPF_CLASS(code) != BPF_JMP)
11620 return false;
11621
11622 op = BPF_OP(code);
11623 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11624}
11625
11626static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11627{
11628 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11629 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11630 struct bpf_insn *insn = env->prog->insnsi;
11631 const int insn_cnt = env->prog->len;
11632 int i;
11633
11634 for (i = 0; i < insn_cnt; i++, insn++) {
11635 if (!insn_is_cond_jump(insn->code))
11636 continue;
11637
11638 if (!aux_data[i + 1].seen)
11639 ja.off = insn->off;
11640 else if (!aux_data[i + 1 + insn->off].seen)
11641 ja.off = 0;
11642 else
11643 continue;
11644
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011645 if (bpf_prog_is_dev_bound(env->prog->aux))
11646 bpf_prog_offload_replace_insn(env, i, &ja);
11647
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011648 memcpy(insn, &ja, sizeof(ja));
11649 }
11650}
11651
Jakub Kicinski52875a02019-01-22 22:45:20 -080011652static int opt_remove_dead_code(struct bpf_verifier_env *env)
11653{
11654 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11655 int insn_cnt = env->prog->len;
11656 int i, err;
11657
11658 for (i = 0; i < insn_cnt; i++) {
11659 int j;
11660
11661 j = 0;
11662 while (i + j < insn_cnt && !aux_data[i + j].seen)
11663 j++;
11664 if (!j)
11665 continue;
11666
11667 err = verifier_remove_insns(env, i, j);
11668 if (err)
11669 return err;
11670 insn_cnt = env->prog->len;
11671 }
11672
11673 return 0;
11674}
11675
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011676static int opt_remove_nops(struct bpf_verifier_env *env)
11677{
11678 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11679 struct bpf_insn *insn = env->prog->insnsi;
11680 int insn_cnt = env->prog->len;
11681 int i, err;
11682
11683 for (i = 0; i < insn_cnt; i++) {
11684 if (memcmp(&insn[i], &ja, sizeof(ja)))
11685 continue;
11686
11687 err = verifier_remove_insns(env, i, 1);
11688 if (err)
11689 return err;
11690 insn_cnt--;
11691 i--;
11692 }
11693
11694 return 0;
11695}
11696
Jiong Wangd6c23082019-05-24 23:25:18 +010011697static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11698 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011699{
Jiong Wangd6c23082019-05-24 23:25:18 +010011700 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011701 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011702 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011703 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011704 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010011705 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011706
Jiong Wangd6c23082019-05-24 23:25:18 +010011707 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011708 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010011709 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11710 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11711 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011712 for (i = 0; i < len; i++) {
11713 int adj_idx = i + delta;
11714 struct bpf_insn insn;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011715 int load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011716
Jiong Wangd6c23082019-05-24 23:25:18 +010011717 insn = insns[adj_idx];
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011718 load_reg = insn_def_regno(&insn);
Jiong Wangd6c23082019-05-24 23:25:18 +010011719 if (!aux[adj_idx].zext_dst) {
11720 u8 code, class;
11721 u32 imm_rnd;
11722
11723 if (!rnd_hi32)
11724 continue;
11725
11726 code = insn.code;
11727 class = BPF_CLASS(code);
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011728 if (load_reg == -1)
Jiong Wangd6c23082019-05-24 23:25:18 +010011729 continue;
11730
11731 /* NOTE: arg "reg" (the fourth one) is only used for
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011732 * BPF_STX + SRC_OP, so it is safe to pass NULL
11733 * here.
Jiong Wangd6c23082019-05-24 23:25:18 +010011734 */
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011735 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
Jiong Wangd6c23082019-05-24 23:25:18 +010011736 if (class == BPF_LD &&
11737 BPF_MODE(code) == BPF_IMM)
11738 i++;
11739 continue;
11740 }
11741
11742 /* ctx load could be transformed into wider load. */
11743 if (class == BPF_LDX &&
11744 aux[adj_idx].ptr_type == PTR_TO_CTX)
11745 continue;
11746
11747 imm_rnd = get_random_int();
11748 rnd_hi32_patch[0] = insn;
11749 rnd_hi32_patch[1].imm = imm_rnd;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011750 rnd_hi32_patch[3].dst_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010011751 patch = rnd_hi32_patch;
11752 patch_len = 4;
11753 goto apply_patch_buffer;
11754 }
11755
Brendan Jackman39491862021-03-04 18:56:46 -080011756 /* Add in an zero-extend instruction if a) the JIT has requested
11757 * it or b) it's a CMPXCHG.
11758 *
11759 * The latter is because: BPF_CMPXCHG always loads a value into
11760 * R0, therefore always zero-extends. However some archs'
11761 * equivalent instruction only does this load when the
11762 * comparison is successful. This detail of CMPXCHG is
11763 * orthogonal to the general zero-extension behaviour of the
11764 * CPU, so it's treated independently of bpf_jit_needs_zext.
11765 */
11766 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011767 continue;
11768
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011769 if (WARN_ON(load_reg == -1)) {
11770 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11771 return -EFAULT;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011772 }
11773
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011774 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011775 zext_patch[1].dst_reg = load_reg;
11776 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010011777 patch = zext_patch;
11778 patch_len = 2;
11779apply_patch_buffer:
11780 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011781 if (!new_prog)
11782 return -ENOMEM;
11783 env->prog = new_prog;
11784 insns = new_prog->insnsi;
11785 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011786 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011787 }
11788
11789 return 0;
11790}
11791
Joe Stringerc64b7982018-10-02 13:35:33 -070011792/* convert load instructions that access fields of a context type into a
11793 * sequence of instructions that access fields of the underlying structure:
11794 * struct __sk_buff -> struct sk_buff
11795 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011796 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011797static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011798{
Jakub Kicinski00176a32017-10-16 16:40:54 -070011799 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011800 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011801 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011802 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011803 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011804 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011805 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011806 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011807
Daniel Borkmannb09928b2018-10-24 22:05:49 +020011808 if (ops->gen_prologue || env->seen_direct_write) {
11809 if (!ops->gen_prologue) {
11810 verbose(env, "bpf verifier is misconfigured\n");
11811 return -EINVAL;
11812 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011813 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11814 env->prog);
11815 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011816 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011817 return -EINVAL;
11818 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070011819 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011820 if (!new_prog)
11821 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011822
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011823 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011824 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011825 }
11826 }
11827
Joe Stringerc64b7982018-10-02 13:35:33 -070011828 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011829 return 0;
11830
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011831 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011832
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011833 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070011834 bpf_convert_ctx_access_t convert_ctx_access;
11835
Daniel Borkmann62c79892017-01-12 11:51:33 +010011836 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11837 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11838 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011839 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011840 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010011841 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11842 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11843 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011844 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011845 type = BPF_WRITE;
11846 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011847 continue;
11848
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011849 if (type == BPF_WRITE &&
11850 env->insn_aux_data[i + delta].sanitize_stack_off) {
11851 struct bpf_insn patch[] = {
11852 /* Sanitize suspicious stack slot with zero.
11853 * There are no memory dependencies for this store,
11854 * since it's only using frame pointer and immediate
11855 * constant of zero
11856 */
11857 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11858 env->insn_aux_data[i + delta].sanitize_stack_off,
11859 0),
11860 /* the original STX instruction will immediately
11861 * overwrite the same stack slot with appropriate value
11862 */
11863 *insn,
11864 };
11865
11866 cnt = ARRAY_SIZE(patch);
11867 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11868 if (!new_prog)
11869 return -ENOMEM;
11870
11871 delta += cnt - 1;
11872 env->prog = new_prog;
11873 insn = new_prog->insnsi + i + delta;
11874 continue;
11875 }
11876
Joe Stringerc64b7982018-10-02 13:35:33 -070011877 switch (env->insn_aux_data[i + delta].ptr_type) {
11878 case PTR_TO_CTX:
11879 if (!ops->convert_ctx_access)
11880 continue;
11881 convert_ctx_access = ops->convert_ctx_access;
11882 break;
11883 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011884 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070011885 convert_ctx_access = bpf_sock_convert_ctx_access;
11886 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011887 case PTR_TO_TCP_SOCK:
11888 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11889 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011890 case PTR_TO_XDP_SOCK:
11891 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11892 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011893 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011894 if (type == BPF_READ) {
11895 insn->code = BPF_LDX | BPF_PROBE_MEM |
11896 BPF_SIZE((insn)->code);
11897 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070011898 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011899 verbose(env, "Writes through BTF pointers are not allowed\n");
11900 return -EINVAL;
11901 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011902 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011903 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011904 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011905 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011906
Yonghong Song31fd8582017-06-13 15:52:13 -070011907 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011908 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070011909
11910 /* If the read access is a narrower load of the field,
11911 * convert to a 4/8-byte load, to minimum program type specific
11912 * convert_ctx_access changes. If conversion is successful,
11913 * we will apply proper mask to the result.
11914 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020011915 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011916 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11917 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070011918 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020011919 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070011920
Daniel Borkmannf96da092017-07-02 02:13:27 +020011921 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011922 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020011923 return -EINVAL;
11924 }
11925
11926 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070011927 if (ctx_field_size == 4)
11928 size_code = BPF_W;
11929 else if (ctx_field_size == 8)
11930 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011931
Daniel Borkmannbc231052018-06-02 23:06:39 +020011932 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070011933 insn->code = BPF_LDX | BPF_MEM | size_code;
11934 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011935
11936 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070011937 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11938 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020011939 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11940 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011941 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011942 return -EINVAL;
11943 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011944
11945 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020011946 u8 shift = bpf_ctx_narrow_access_offset(
11947 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011948 if (ctx_field_size <= 4) {
11949 if (shift)
11950 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11951 insn->dst_reg,
11952 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011953 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020011954 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011955 } else {
11956 if (shift)
11957 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11958 insn->dst_reg,
11959 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011960 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020011961 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011962 }
Yonghong Song31fd8582017-06-13 15:52:13 -070011963 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011964
Alexei Starovoitov80419022017-03-15 18:26:41 -070011965 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011966 if (!new_prog)
11967 return -ENOMEM;
11968
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011969 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011970
11971 /* keep walking new program and skip insns we just inserted */
11972 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011973 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011974 }
11975
11976 return 0;
11977}
11978
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011979static int jit_subprogs(struct bpf_verifier_env *env)
11980{
11981 struct bpf_prog *prog = env->prog, **func, *tmp;
11982 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011983 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011984 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011985 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011986 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011987
Jiong Wangf910cef2018-05-02 16:17:17 -040011988 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011989 return 0;
11990
Daniel Borkmann7105e822017-12-20 13:42:57 +010011991 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080011992 if (bpf_pseudo_func(insn)) {
11993 env->insn_aux_data[i].call_imm = insn->imm;
11994 /* subprog is encoded in insn[1].imm */
11995 continue;
11996 }
11997
Yonghong Song23a2d702021-02-04 15:48:27 -080011998 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011999 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012000 /* Upon error here we cannot fall back to interpreter but
12001 * need a hard reject of the program. Thus -EFAULT is
12002 * propagated in any case.
12003 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012004 subprog = find_subprog(env, i + insn->imm + 1);
12005 if (subprog < 0) {
12006 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12007 i + insn->imm + 1);
12008 return -EFAULT;
12009 }
12010 /* temporarily remember subprog id inside insn instead of
12011 * aux_data, since next loop will split up all insns into funcs
12012 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012013 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012014 /* remember original imm in case JIT fails and fallback
12015 * to interpreter will be needed
12016 */
12017 env->insn_aux_data[i].call_imm = insn->imm;
12018 /* point imm to __bpf_call_base+1 from JITs point of view */
12019 insn->imm = 1;
12020 }
12021
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012022 err = bpf_prog_alloc_jited_linfo(prog);
12023 if (err)
12024 goto out_undo_insn;
12025
12026 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070012027 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012028 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012029 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012030
Jiong Wangf910cef2018-05-02 16:17:17 -040012031 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012032 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040012033 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012034
12035 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012036 /* BPF_PROG_RUN doesn't call subprogs directly,
12037 * hence main prog stats include the runtime of subprogs.
12038 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080012039 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012040 */
12041 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012042 if (!func[i])
12043 goto out_free;
12044 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12045 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012046 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012047 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012048 if (bpf_prog_calc_tag(func[i]))
12049 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012050 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080012051 func[i]->aux->func_idx = i;
12052 /* the btf and func_info will be freed only at prog->aux */
12053 func[i]->aux->btf = prog->aux->btf;
12054 func[i]->aux->func_info = prog->aux->func_info;
12055
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012056 for (j = 0; j < prog->aux->size_poke_tab; j++) {
12057 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
12058 int ret;
12059
12060 if (!(insn_idx >= subprog_start &&
12061 insn_idx <= subprog_end))
12062 continue;
12063
12064 ret = bpf_jit_add_poke_descriptor(func[i],
12065 &prog->aux->poke_tab[j]);
12066 if (ret < 0) {
12067 verbose(env, "adding tail call poke descriptor failed\n");
12068 goto out_free;
12069 }
12070
12071 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
12072
12073 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
12074 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
12075 if (ret < 0) {
12076 verbose(env, "tracking tail call prog failed\n");
12077 goto out_free;
12078 }
12079 }
12080
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012081 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12082 * Long term would need debug info to populate names
12083 */
12084 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040012085 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012086 func[i]->jit_requested = 1;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012087 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012088 func[i]->aux->linfo = prog->aux->linfo;
12089 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12090 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12091 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070012092 num_exentries = 0;
12093 insn = func[i]->insnsi;
12094 for (j = 0; j < func[i]->len; j++, insn++) {
12095 if (BPF_CLASS(insn->code) == BPF_LDX &&
12096 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12097 num_exentries++;
12098 }
12099 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020012100 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012101 func[i] = bpf_int_jit_compile(func[i]);
12102 if (!func[i]->jited) {
12103 err = -ENOTSUPP;
12104 goto out_free;
12105 }
12106 cond_resched();
12107 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012108
12109 /* Untrack main program's aux structs so that during map_poke_run()
12110 * we will not stumble upon the unfilled poke descriptors; each
12111 * of the main program's poke descs got distributed across subprogs
12112 * and got tracked onto map, so we are sure that none of them will
12113 * be missed after the operation below
12114 */
12115 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12116 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12117
12118 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12119 }
12120
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012121 /* at this point all bpf functions were successfully JITed
12122 * now populate all bpf_calls with correct addresses and
12123 * run last pass of JIT
12124 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012125 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012126 insn = func[i]->insnsi;
12127 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012128 if (bpf_pseudo_func(insn)) {
12129 subprog = insn[1].imm;
12130 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12131 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12132 continue;
12133 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012134 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012135 continue;
12136 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090012137 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12138 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012139 }
Sandipan Das2162fed2018-05-24 12:26:45 +053012140
12141 /* we use the aux data to keep a list of the start addresses
12142 * of the JITed images for each function in the program
12143 *
12144 * for some architectures, such as powerpc64, the imm field
12145 * might not be large enough to hold the offset of the start
12146 * address of the callee's JITed image from __bpf_call_base
12147 *
12148 * in such cases, we can lookup the start address of a callee
12149 * by using its subprog id, available from the off field of
12150 * the call instruction, as an index for this list
12151 */
12152 func[i]->aux->func = func;
12153 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012154 }
Jiong Wangf910cef2018-05-02 16:17:17 -040012155 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012156 old_bpf_func = func[i]->bpf_func;
12157 tmp = bpf_int_jit_compile(func[i]);
12158 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12159 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012160 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012161 goto out_free;
12162 }
12163 cond_resched();
12164 }
12165
12166 /* finally lock prog and jit images for all functions and
12167 * populate kallsysm
12168 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012169 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012170 bpf_prog_lock_ro(func[i]);
12171 bpf_prog_kallsyms_add(func[i]);
12172 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010012173
12174 /* Last step: make now unused interpreter insns from main
12175 * prog consistent for later dump requests, so they can
12176 * later look the same as if they were interpreted only.
12177 */
12178 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012179 if (bpf_pseudo_func(insn)) {
12180 insn[0].imm = env->insn_aux_data[i].call_imm;
12181 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12182 continue;
12183 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012184 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010012185 continue;
12186 insn->off = env->insn_aux_data[i].call_imm;
12187 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053012188 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010012189 }
12190
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012191 prog->jited = 1;
12192 prog->bpf_func = func[0]->bpf_func;
12193 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040012194 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012195 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012196 return 0;
12197out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012198 for (i = 0; i < env->subprog_cnt; i++) {
12199 if (!func[i])
12200 continue;
12201
12202 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
12203 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
12204 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
12205 }
12206 bpf_jit_free(func[i]);
12207 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012208 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012209out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012210 /* cleanup main prog to be interpreted */
12211 prog->jit_requested = 0;
12212 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080012213 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012214 continue;
12215 insn->off = 0;
12216 insn->imm = env->insn_aux_data[i].call_imm;
12217 }
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012218 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012219 return err;
12220}
12221
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012222static int fixup_call_args(struct bpf_verifier_env *env)
12223{
David S. Miller19d28fb2018-01-11 21:27:54 -050012224#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012225 struct bpf_prog *prog = env->prog;
12226 struct bpf_insn *insn = prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012227 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012228 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050012229#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010012230 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012231
Quentin Monnete4052d02018-10-07 12:56:58 +010012232 if (env->prog->jit_requested &&
12233 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050012234 err = jit_subprogs(env);
12235 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012236 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012237 if (err == -EFAULT)
12238 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050012239 }
12240#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012241 if (has_kfunc_call) {
12242 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12243 return -EINVAL;
12244 }
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020012245 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12246 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12247 * have to be rejected, since interpreter doesn't support them yet.
12248 */
12249 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12250 return -EINVAL;
12251 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012252 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012253 if (bpf_pseudo_func(insn)) {
12254 /* When JIT fails the progs with callback calls
12255 * have to be rejected, since interpreter doesn't support them yet.
12256 */
12257 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12258 return -EINVAL;
12259 }
12260
Yonghong Song23a2d702021-02-04 15:48:27 -080012261 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012262 continue;
12263 depth = get_callee_stack_depth(env, insn, i);
12264 if (depth < 0)
12265 return depth;
12266 bpf_patch_call_args(insn, depth);
12267 }
David S. Miller19d28fb2018-01-11 21:27:54 -050012268 err = 0;
12269#endif
12270 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012271}
12272
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012273static int fixup_kfunc_call(struct bpf_verifier_env *env,
12274 struct bpf_insn *insn)
12275{
12276 const struct bpf_kfunc_desc *desc;
12277
12278 /* insn->imm has the btf func_id. Replace it with
12279 * an address (relative to __bpf_base_call).
12280 */
12281 desc = find_kfunc_desc(env->prog, insn->imm);
12282 if (!desc) {
12283 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12284 insn->imm);
12285 return -EFAULT;
12286 }
12287
12288 insn->imm = desc->imm;
12289
12290 return 0;
12291}
12292
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012293/* Do various post-verification rewrites in a single program pass.
12294 * These rewrites simplify JIT and interpreter implementations.
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012295 */
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012296static int do_misc_fixups(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012297{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012298 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012299 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012300 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012301 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012302 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020012303 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012304 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012305 struct bpf_insn insn_buf[16];
12306 struct bpf_prog *new_prog;
12307 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012308 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012309
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012310 for (i = 0; i < insn_cnt; i++, insn++) {
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012311 /* Make divide-by-zero exceptions impossible. */
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012312 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12313 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12314 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080012315 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012316 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012317 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12318 struct bpf_insn *patchlet;
12319 struct bpf_insn chk_and_div[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012320 /* [R,W]x div 0 -> 0 */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012321 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12322 BPF_JNE | BPF_K, insn->src_reg,
12323 0, 2, 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012324 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12325 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12326 *insn,
12327 };
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012328 struct bpf_insn chk_and_mod[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012329 /* [R,W]x mod 0 -> [R,W]x */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012330 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12331 BPF_JEQ | BPF_K, insn->src_reg,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012332 0, 1 + (is64 ? 0 : 1), 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012333 *insn,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012334 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12335 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012336 };
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012337
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012338 patchlet = isdiv ? chk_and_div : chk_and_mod;
12339 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012340 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012341
12342 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080012343 if (!new_prog)
12344 return -ENOMEM;
12345
12346 delta += cnt - 1;
12347 env->prog = prog = new_prog;
12348 insn = new_prog->insnsi + i + delta;
12349 continue;
12350 }
12351
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012352 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020012353 if (BPF_CLASS(insn->code) == BPF_LD &&
12354 (BPF_MODE(insn->code) == BPF_ABS ||
12355 BPF_MODE(insn->code) == BPF_IND)) {
12356 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12357 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12358 verbose(env, "bpf verifier is misconfigured\n");
12359 return -EINVAL;
12360 }
12361
12362 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12363 if (!new_prog)
12364 return -ENOMEM;
12365
12366 delta += cnt - 1;
12367 env->prog = prog = new_prog;
12368 insn = new_prog->insnsi + i + delta;
12369 continue;
12370 }
12371
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012372 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012373 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12374 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12375 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12376 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012377 struct bpf_insn *patch = &insn_buf[0];
Daniel Borkmann801c6052021-04-29 15:19:37 +000012378 bool issrc, isneg, isimm;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012379 u32 off_reg;
12380
12381 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010012382 if (!aux->alu_state ||
12383 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012384 continue;
12385
12386 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12387 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12388 BPF_ALU_SANITIZE_SRC;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012389 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012390
12391 off_reg = issrc ? insn->src_reg : insn->dst_reg;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012392 if (isimm) {
12393 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12394 } else {
12395 if (isneg)
12396 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12397 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12398 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12399 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12400 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12401 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12402 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12403 }
Daniel Borkmannb9b34dd2021-04-30 16:21:46 +020012404 if (!issrc)
12405 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12406 insn->src_reg = BPF_REG_AX;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012407 if (isneg)
12408 insn->code = insn->code == code_add ?
12409 code_sub : code_add;
12410 *patch++ = *insn;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012411 if (issrc && isneg && !isimm)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012412 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12413 cnt = patch - insn_buf;
12414
12415 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12416 if (!new_prog)
12417 return -ENOMEM;
12418
12419 delta += cnt - 1;
12420 env->prog = prog = new_prog;
12421 insn = new_prog->insnsi + i + delta;
12422 continue;
12423 }
12424
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012425 if (insn->code != (BPF_JMP | BPF_CALL))
12426 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012427 if (insn->src_reg == BPF_PSEUDO_CALL)
12428 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012429 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12430 ret = fixup_kfunc_call(env, insn);
12431 if (ret)
12432 return ret;
12433 continue;
12434 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012435
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012436 if (insn->imm == BPF_FUNC_get_route_realm)
12437 prog->dst_needed = 1;
12438 if (insn->imm == BPF_FUNC_get_prandom_u32)
12439 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050012440 if (insn->imm == BPF_FUNC_override_return)
12441 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012442 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040012443 /* If we tail call into other programs, we
12444 * cannot make any assumptions since they can
12445 * be replaced dynamically during runtime in
12446 * the program array.
12447 */
12448 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020012449 if (!allow_tail_call_in_subprogs(env))
12450 prog->aux->stack_depth = MAX_BPF_STACK;
12451 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040012452
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012453 /* mark bpf_tail_call as different opcode to avoid
12454 * conditional branch in the interpeter for every normal
12455 * call and to prevent accidental JITing by JIT compiler
12456 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012457 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012458 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070012459 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012460
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012461 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012462 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010012463 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012464 !bpf_map_key_poisoned(aux) &&
12465 !bpf_map_ptr_poisoned(aux) &&
12466 !bpf_map_ptr_unpriv(aux)) {
12467 struct bpf_jit_poke_descriptor desc = {
12468 .reason = BPF_POKE_REASON_TAIL_CALL,
12469 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12470 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012471 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012472 };
12473
12474 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12475 if (ret < 0) {
12476 verbose(env, "adding tail call poke descriptor failed\n");
12477 return ret;
12478 }
12479
12480 insn->imm = ret + 1;
12481 continue;
12482 }
12483
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012484 if (!bpf_map_ptr_unpriv(aux))
12485 continue;
12486
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012487 /* instead of changing every JIT dealing with tail_call
12488 * emit two extra insns:
12489 * if (index >= max_entries) goto out;
12490 * index &= array->index_mask;
12491 * to avoid out-of-bounds cpu speculation
12492 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012493 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000012494 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012495 return -EINVAL;
12496 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012497
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012498 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012499 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12500 map_ptr->max_entries, 2);
12501 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12502 container_of(map_ptr,
12503 struct bpf_array,
12504 map)->index_mask);
12505 insn_buf[2] = *insn;
12506 cnt = 3;
12507 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12508 if (!new_prog)
12509 return -ENOMEM;
12510
12511 delta += cnt - 1;
12512 env->prog = prog = new_prog;
12513 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012514 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012515 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012516
Daniel Borkmann89c63072017-08-19 03:12:45 +020012517 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020012518 * and other inlining handlers are currently limited to 64 bit
12519 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020012520 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080012521 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020012522 (insn->imm == BPF_FUNC_map_lookup_elem ||
12523 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020012524 insn->imm == BPF_FUNC_map_delete_elem ||
12525 insn->imm == BPF_FUNC_map_push_elem ||
12526 insn->imm == BPF_FUNC_map_pop_elem ||
Björn Töpele6a47502021-03-08 12:29:06 +010012527 insn->imm == BPF_FUNC_map_peek_elem ||
12528 insn->imm == BPF_FUNC_redirect_map)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012529 aux = &env->insn_aux_data[i + delta];
12530 if (bpf_map_ptr_poisoned(aux))
12531 goto patch_call_imm;
12532
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012533 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020012534 ops = map_ptr->ops;
12535 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12536 ops->map_gen_lookup) {
12537 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012538 if (cnt == -EOPNOTSUPP)
12539 goto patch_map_ops_generic;
12540 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020012541 verbose(env, "bpf verifier is misconfigured\n");
12542 return -EINVAL;
12543 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012544
Daniel Borkmann09772d92018-06-02 23:06:35 +020012545 new_prog = bpf_patch_insn_data(env, i + delta,
12546 insn_buf, cnt);
12547 if (!new_prog)
12548 return -ENOMEM;
12549
12550 delta += cnt - 1;
12551 env->prog = prog = new_prog;
12552 insn = new_prog->insnsi + i + delta;
12553 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012554 }
12555
Daniel Borkmann09772d92018-06-02 23:06:35 +020012556 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12557 (void *(*)(struct bpf_map *map, void *key))NULL));
12558 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12559 (int (*)(struct bpf_map *map, void *key))NULL));
12560 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12561 (int (*)(struct bpf_map *map, void *key, void *value,
12562 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020012563 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12564 (int (*)(struct bpf_map *map, void *value,
12565 u64 flags))NULL));
12566 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12567 (int (*)(struct bpf_map *map, void *value))NULL));
12568 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12569 (int (*)(struct bpf_map *map, void *value))NULL));
Björn Töpele6a47502021-03-08 12:29:06 +010012570 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12571 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12572
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012573patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020012574 switch (insn->imm) {
12575 case BPF_FUNC_map_lookup_elem:
12576 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12577 __bpf_call_base;
12578 continue;
12579 case BPF_FUNC_map_update_elem:
12580 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12581 __bpf_call_base;
12582 continue;
12583 case BPF_FUNC_map_delete_elem:
12584 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12585 __bpf_call_base;
12586 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020012587 case BPF_FUNC_map_push_elem:
12588 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12589 __bpf_call_base;
12590 continue;
12591 case BPF_FUNC_map_pop_elem:
12592 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12593 __bpf_call_base;
12594 continue;
12595 case BPF_FUNC_map_peek_elem:
12596 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12597 __bpf_call_base;
12598 continue;
Björn Töpele6a47502021-03-08 12:29:06 +010012599 case BPF_FUNC_redirect_map:
12600 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12601 __bpf_call_base;
12602 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020012603 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012604
Daniel Borkmann09772d92018-06-02 23:06:35 +020012605 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012606 }
12607
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012608 /* Implement bpf_jiffies64 inline. */
Martin KaFai Lau5576b992020-01-22 15:36:46 -080012609 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12610 insn->imm == BPF_FUNC_jiffies64) {
12611 struct bpf_insn ld_jiffies_addr[2] = {
12612 BPF_LD_IMM64(BPF_REG_0,
12613 (unsigned long)&jiffies),
12614 };
12615
12616 insn_buf[0] = ld_jiffies_addr[0];
12617 insn_buf[1] = ld_jiffies_addr[1];
12618 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12619 BPF_REG_0, 0);
12620 cnt = 3;
12621
12622 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12623 cnt);
12624 if (!new_prog)
12625 return -ENOMEM;
12626
12627 delta += cnt - 1;
12628 env->prog = prog = new_prog;
12629 insn = new_prog->insnsi + i + delta;
12630 continue;
12631 }
12632
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012633patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070012634 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012635 /* all functions that have prototype and verifier allowed
12636 * programs to call them, must be real in-kernel functions
12637 */
12638 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012639 verbose(env,
12640 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012641 func_id_name(insn->imm), insn->imm);
12642 return -EFAULT;
12643 }
12644 insn->imm = fn->func - __bpf_call_base;
12645 }
12646
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012647 /* Since poke tab is now finalized, publish aux to tracker. */
12648 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12649 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12650 if (!map_ptr->ops->map_poke_track ||
12651 !map_ptr->ops->map_poke_untrack ||
12652 !map_ptr->ops->map_poke_run) {
12653 verbose(env, "bpf verifier is misconfigured\n");
12654 return -EINVAL;
12655 }
12656
12657 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12658 if (ret < 0) {
12659 verbose(env, "tracking tail call prog failed\n");
12660 return ret;
12661 }
12662 }
12663
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012664 sort_kfunc_descs_by_imm(env->prog);
12665
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012666 return 0;
12667}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012668
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012669static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012670{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012671 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012672 int i;
12673
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012674 sl = env->free_list;
12675 while (sl) {
12676 sln = sl->next;
12677 free_verifier_state(&sl->state, false);
12678 kfree(sl);
12679 sl = sln;
12680 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012681 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012682
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012683 if (!env->explored_states)
12684 return;
12685
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012686 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012687 sl = env->explored_states[i];
12688
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070012689 while (sl) {
12690 sln = sl->next;
12691 free_verifier_state(&sl->state, false);
12692 kfree(sl);
12693 sl = sln;
12694 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012695 env->explored_states[i] = NULL;
12696 }
12697}
12698
12699/* The verifier is using insn_aux_data[] to store temporary data during
12700 * verification and to store information for passes that run after the
12701 * verification like dead code sanitization. do_check_common() for subprogram N
12702 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12703 * temporary data after do_check_common() finds that subprogram N cannot be
12704 * verified independently. pass_cnt counts the number of times
12705 * do_check_common() was run and insn->aux->seen tells the pass number
12706 * insn_aux_data was touched. These variables are compared to clear temporary
12707 * data from failed pass. For testing and experiments do_check_common() can be
12708 * run multiple times even when prior attempt to verify is unsuccessful.
12709 */
12710static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12711{
12712 struct bpf_insn *insn = env->prog->insnsi;
12713 struct bpf_insn_aux_data *aux;
12714 int i, class;
12715
12716 for (i = 0; i < env->prog->len; i++) {
12717 class = BPF_CLASS(insn[i].code);
12718 if (class != BPF_LDX && class != BPF_STX)
12719 continue;
12720 aux = &env->insn_aux_data[i];
12721 if (aux->seen != env->pass_cnt)
12722 continue;
12723 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12724 }
12725}
12726
12727static int do_check_common(struct bpf_verifier_env *env, int subprog)
12728{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012729 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012730 struct bpf_verifier_state *state;
12731 struct bpf_reg_state *regs;
12732 int ret, i;
12733
12734 env->prev_linfo = NULL;
12735 env->pass_cnt++;
12736
12737 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12738 if (!state)
12739 return -ENOMEM;
12740 state->curframe = 0;
12741 state->speculative = false;
12742 state->branches = 1;
12743 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12744 if (!state->frame[0]) {
12745 kfree(state);
12746 return -ENOMEM;
12747 }
12748 env->cur_state = state;
12749 init_func_state(env, state->frame[0],
12750 BPF_MAIN_FUNC /* callsite */,
12751 0 /* frameno */,
12752 subprog);
12753
12754 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012755 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012756 ret = btf_prepare_func_args(env, subprog, regs);
12757 if (ret)
12758 goto out;
12759 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12760 if (regs[i].type == PTR_TO_CTX)
12761 mark_reg_known_zero(env, regs, i);
12762 else if (regs[i].type == SCALAR_VALUE)
12763 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040012764 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12765 const u32 mem_size = regs[i].mem_size;
12766
12767 mark_reg_known_zero(env, regs, i);
12768 regs[i].mem_size = mem_size;
12769 regs[i].id = ++env->id_gen;
12770 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012771 }
12772 } else {
12773 /* 1st arg to a function */
12774 regs[BPF_REG_1].type = PTR_TO_CTX;
12775 mark_reg_known_zero(env, regs, BPF_REG_1);
Martin KaFai Lau34747c42021-03-24 18:51:36 -070012776 ret = btf_check_subprog_arg_match(env, subprog, regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012777 if (ret == -EFAULT)
12778 /* unlikely verifier bug. abort.
12779 * ret == 0 and ret < 0 are sadly acceptable for
12780 * main() function due to backward compatibility.
12781 * Like socket filter program may be written as:
12782 * int bpf_prog(struct pt_regs *ctx)
12783 * and never dereference that ctx in the program.
12784 * 'struct pt_regs' is a type mismatch for socket
12785 * filter that should be using 'struct __sk_buff'.
12786 */
12787 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012788 }
12789
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012790 ret = do_check(env);
12791out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080012792 /* check for NULL is necessary, since cur_state can be freed inside
12793 * do_check() under memory pressure.
12794 */
12795 if (env->cur_state) {
12796 free_verifier_state(env->cur_state, true);
12797 env->cur_state = NULL;
12798 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012799 while (!pop_stack(env, NULL, NULL, false));
12800 if (!ret && pop_log)
12801 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012802 free_states(env);
12803 if (ret)
12804 /* clean aux data in case subprog was rejected */
12805 sanitize_insn_aux_data(env);
12806 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012807}
12808
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012809/* Verify all global functions in a BPF program one by one based on their BTF.
12810 * All global functions must pass verification. Otherwise the whole program is rejected.
12811 * Consider:
12812 * int bar(int);
12813 * int foo(int f)
12814 * {
12815 * return bar(f);
12816 * }
12817 * int bar(int b)
12818 * {
12819 * ...
12820 * }
12821 * foo() will be verified first for R1=any_scalar_value. During verification it
12822 * will be assumed that bar() already verified successfully and call to bar()
12823 * from foo() will be checked for type match only. Later bar() will be verified
12824 * independently to check that it's safe for R1=any_scalar_value.
12825 */
12826static int do_check_subprogs(struct bpf_verifier_env *env)
12827{
12828 struct bpf_prog_aux *aux = env->prog->aux;
12829 int i, ret;
12830
12831 if (!aux->func_info)
12832 return 0;
12833
12834 for (i = 1; i < env->subprog_cnt; i++) {
12835 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12836 continue;
12837 env->insn_idx = env->subprog_info[i].start;
12838 WARN_ON_ONCE(env->insn_idx == 0);
12839 ret = do_check_common(env, i);
12840 if (ret) {
12841 return ret;
12842 } else if (env->log.level & BPF_LOG_LEVEL) {
12843 verbose(env,
12844 "Func#%d is safe for any args that match its prototype\n",
12845 i);
12846 }
12847 }
12848 return 0;
12849}
12850
12851static int do_check_main(struct bpf_verifier_env *env)
12852{
12853 int ret;
12854
12855 env->insn_idx = 0;
12856 ret = do_check_common(env, 0);
12857 if (!ret)
12858 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12859 return ret;
12860}
12861
12862
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012863static void print_verification_stats(struct bpf_verifier_env *env)
12864{
12865 int i;
12866
12867 if (env->log.level & BPF_LOG_STATS) {
12868 verbose(env, "verification time %lld usec\n",
12869 div_u64(env->verification_time, 1000));
12870 verbose(env, "stack depth ");
12871 for (i = 0; i < env->subprog_cnt; i++) {
12872 u32 depth = env->subprog_info[i].stack_depth;
12873
12874 verbose(env, "%d", depth);
12875 if (i + 1 < env->subprog_cnt)
12876 verbose(env, "+");
12877 }
12878 verbose(env, "\n");
12879 }
12880 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12881 "total_states %d peak_states %d mark_read %d\n",
12882 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12883 env->max_states_per_insn, env->total_states,
12884 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012885}
12886
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012887static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12888{
12889 const struct btf_type *t, *func_proto;
12890 const struct bpf_struct_ops *st_ops;
12891 const struct btf_member *member;
12892 struct bpf_prog *prog = env->prog;
12893 u32 btf_id, member_idx;
12894 const char *mname;
12895
Toke Høiland-Jørgensen12aa8a92021-03-26 11:03:13 +010012896 if (!prog->gpl_compatible) {
12897 verbose(env, "struct ops programs must have a GPL compatible license\n");
12898 return -EINVAL;
12899 }
12900
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012901 btf_id = prog->aux->attach_btf_id;
12902 st_ops = bpf_struct_ops_find(btf_id);
12903 if (!st_ops) {
12904 verbose(env, "attach_btf_id %u is not a supported struct\n",
12905 btf_id);
12906 return -ENOTSUPP;
12907 }
12908
12909 t = st_ops->type;
12910 member_idx = prog->expected_attach_type;
12911 if (member_idx >= btf_type_vlen(t)) {
12912 verbose(env, "attach to invalid member idx %u of struct %s\n",
12913 member_idx, st_ops->name);
12914 return -EINVAL;
12915 }
12916
12917 member = &btf_type_member(t)[member_idx];
12918 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12919 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12920 NULL);
12921 if (!func_proto) {
12922 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12923 mname, member_idx, st_ops->name);
12924 return -EINVAL;
12925 }
12926
12927 if (st_ops->check_member) {
12928 int err = st_ops->check_member(t, member);
12929
12930 if (err) {
12931 verbose(env, "attach to unsupported member %s of struct %s\n",
12932 mname, st_ops->name);
12933 return err;
12934 }
12935 }
12936
12937 prog->aux->attach_func_proto = func_proto;
12938 prog->aux->attach_func_name = mname;
12939 env->ops = st_ops->verifier_ops;
12940
12941 return 0;
12942}
KP Singh6ba43b72020-03-04 20:18:50 +010012943#define SECURITY_PREFIX "security_"
12944
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012945static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010012946{
KP Singh69191752020-03-05 21:49:55 +010012947 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012948 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010012949 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010012950
KP Singh6ba43b72020-03-04 20:18:50 +010012951 return -EINVAL;
12952}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012953
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012954/* list of non-sleepable functions that are otherwise on
12955 * ALLOW_ERROR_INJECTION list
12956 */
12957BTF_SET_START(btf_non_sleepable_error_inject)
12958/* Three functions below can be called from sleepable and non-sleepable context.
12959 * Assume non-sleepable from bpf safety point of view.
12960 */
12961BTF_ID(func, __add_to_page_cache_locked)
12962BTF_ID(func, should_fail_alloc_page)
12963BTF_ID(func, should_failslab)
12964BTF_SET_END(btf_non_sleepable_error_inject)
12965
12966static int check_non_sleepable_error_inject(u32 btf_id)
12967{
12968 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12969}
12970
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012971int bpf_check_attach_target(struct bpf_verifier_log *log,
12972 const struct bpf_prog *prog,
12973 const struct bpf_prog *tgt_prog,
12974 u32 btf_id,
12975 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070012976{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012977 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012978 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012979 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012980 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012981 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012982 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012983 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012984 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012985
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012986 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012987 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012988 return -EINVAL;
12989 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012990 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012991 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012992 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012993 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12994 return -EINVAL;
12995 }
12996 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012997 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012998 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012999 return -EINVAL;
13000 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013001 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013002 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013003 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013004 return -EINVAL;
13005 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013006 if (tgt_prog) {
13007 struct bpf_prog_aux *aux = tgt_prog->aux;
13008
13009 for (i = 0; i < aux->func_info_cnt; i++)
13010 if (aux->func_info[i].type_id == btf_id) {
13011 subprog = i;
13012 break;
13013 }
13014 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013015 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013016 return -EINVAL;
13017 }
13018 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013019 if (prog_extension) {
13020 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013021 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013022 "Cannot replace static functions\n");
13023 return -EINVAL;
13024 }
13025 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013026 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013027 "Extension programs should be JITed\n");
13028 return -EINVAL;
13029 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013030 }
13031 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013032 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013033 return -EINVAL;
13034 }
13035 if (tgt_prog->type == prog->type) {
13036 /* Cannot fentry/fexit another fentry/fexit program.
13037 * Cannot attach program extension to another extension.
13038 * It's ok to attach fentry/fexit to extension program.
13039 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013040 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013041 return -EINVAL;
13042 }
13043 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13044 prog_extension &&
13045 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13046 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13047 /* Program extensions can extend all program types
13048 * except fentry/fexit. The reason is the following.
13049 * The fentry/fexit programs are used for performance
13050 * analysis, stats and can be attached to any program
13051 * type except themselves. When extension program is
13052 * replacing XDP function it is necessary to allow
13053 * performance analysis of all functions. Both original
13054 * XDP program and its program extension. Hence
13055 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13056 * allowed. If extending of fentry/fexit was allowed it
13057 * would be possible to create long call chain
13058 * fentry->extension->fentry->extension beyond
13059 * reasonable stack size. Hence extending fentry is not
13060 * allowed.
13061 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013062 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013063 return -EINVAL;
13064 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013065 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013066 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013067 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013068 return -EINVAL;
13069 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013070 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013071
13072 switch (prog->expected_attach_type) {
13073 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013074 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013075 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013076 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13077 return -EINVAL;
13078 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070013079 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013080 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013081 btf_id);
13082 return -EINVAL;
13083 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013084 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013085 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013086 btf_id, tname);
13087 return -EINVAL;
13088 }
13089 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013090 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013091 if (!btf_type_is_ptr(t))
13092 /* should never happen in valid vmlinux build */
13093 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013094 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013095 if (!btf_type_is_func_proto(t))
13096 /* should never happen in valid vmlinux build */
13097 return -EINVAL;
13098
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013099 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070013100 case BPF_TRACE_ITER:
13101 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013102 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070013103 btf_id);
13104 return -EINVAL;
13105 }
13106 t = btf_type_by_id(btf, t->type);
13107 if (!btf_type_is_func_proto(t))
13108 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013109 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13110 if (ret)
13111 return ret;
13112 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013113 default:
13114 if (!prog_extension)
13115 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050013116 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010013117 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010013118 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013119 case BPF_TRACE_FENTRY:
13120 case BPF_TRACE_FEXIT:
13121 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013122 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013123 btf_id);
13124 return -EINVAL;
13125 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013126 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013127 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013128 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013129 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013130 if (!btf_type_is_func_proto(t))
13131 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013132
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020013133 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13134 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13135 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13136 return -EINVAL;
13137
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013138 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013139 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013140
13141 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013142 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013143 return ret;
13144
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013145 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080013146 if (subprog == 0)
13147 addr = (long) tgt_prog->bpf_func;
13148 else
13149 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013150 } else {
13151 addr = kallsyms_lookup_name(tname);
13152 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013153 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013154 "The address of function %s cannot be found\n",
13155 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013156 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013157 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013158 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070013159
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013160 if (prog->aux->sleepable) {
13161 ret = -EINVAL;
13162 switch (prog->type) {
13163 case BPF_PROG_TYPE_TRACING:
13164 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13165 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13166 */
13167 if (!check_non_sleepable_error_inject(btf_id) &&
13168 within_error_injection_list(addr))
13169 ret = 0;
13170 break;
13171 case BPF_PROG_TYPE_LSM:
13172 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13173 * Only some of them are sleepable.
13174 */
KP Singh423f1612020-11-13 00:59:29 +000013175 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013176 ret = 0;
13177 break;
13178 default:
13179 break;
13180 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013181 if (ret) {
13182 bpf_log(log, "%s is not sleepable\n", tname);
13183 return ret;
13184 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013185 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020013186 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013187 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013188 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020013189 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013190 ret = check_attach_modify_return(addr, tname);
13191 if (ret) {
13192 bpf_log(log, "%s() is not modifiable\n", tname);
13193 return ret;
13194 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070013195 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013196
13197 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013198 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013199 tgt_info->tgt_addr = addr;
13200 tgt_info->tgt_name = tname;
13201 tgt_info->tgt_type = t;
13202 return 0;
13203}
13204
Jiri Olsa35e38152021-04-29 13:47:12 +020013205BTF_SET_START(btf_id_deny)
13206BTF_ID_UNUSED
13207#ifdef CONFIG_SMP
13208BTF_ID(func, migrate_disable)
13209BTF_ID(func, migrate_enable)
13210#endif
13211#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13212BTF_ID(func, rcu_read_unlock_strict)
13213#endif
13214BTF_SET_END(btf_id_deny)
13215
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013216static int check_attach_btf_id(struct bpf_verifier_env *env)
13217{
13218 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013219 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013220 struct bpf_attach_target_info tgt_info = {};
13221 u32 btf_id = prog->aux->attach_btf_id;
13222 struct bpf_trampoline *tr;
13223 int ret;
13224 u64 key;
13225
13226 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13227 prog->type != BPF_PROG_TYPE_LSM) {
13228 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13229 return -EINVAL;
13230 }
13231
13232 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13233 return check_struct_ops_btf_id(env);
13234
13235 if (prog->type != BPF_PROG_TYPE_TRACING &&
13236 prog->type != BPF_PROG_TYPE_LSM &&
13237 prog->type != BPF_PROG_TYPE_EXT)
13238 return 0;
13239
13240 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13241 if (ret)
13242 return ret;
13243
13244 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013245 /* to make freplace equivalent to their targets, they need to
13246 * inherit env->ops and expected_attach_type for the rest of the
13247 * verification
13248 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013249 env->ops = bpf_verifier_ops[tgt_prog->type];
13250 prog->expected_attach_type = tgt_prog->expected_attach_type;
13251 }
13252
13253 /* store info about the attachment target that will be used later */
13254 prog->aux->attach_func_proto = tgt_info.tgt_type;
13255 prog->aux->attach_func_name = tgt_info.tgt_name;
13256
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020013257 if (tgt_prog) {
13258 prog->aux->saved_dst_prog_type = tgt_prog->type;
13259 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13260 }
13261
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013262 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13263 prog->aux->attach_btf_trace = true;
13264 return 0;
13265 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13266 if (!bpf_iter_prog_supported(prog))
13267 return -EINVAL;
13268 return 0;
13269 }
13270
13271 if (prog->type == BPF_PROG_TYPE_LSM) {
13272 ret = bpf_lsm_verify_prog(&env->log, prog);
13273 if (ret < 0)
13274 return ret;
Jiri Olsa35e38152021-04-29 13:47:12 +020013275 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13276 btf_id_set_contains(&btf_id_deny, btf_id)) {
13277 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013278 }
13279
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080013280 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013281 tr = bpf_trampoline_get(key, &tgt_info);
13282 if (!tr)
13283 return -ENOMEM;
13284
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013285 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013286 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013287}
13288
Alan Maguire76654e62020-09-28 12:31:03 +010013289struct btf *bpf_get_btf_vmlinux(void)
13290{
13291 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13292 mutex_lock(&bpf_verifier_lock);
13293 if (!btf_vmlinux)
13294 btf_vmlinux = btf_parse_vmlinux();
13295 mutex_unlock(&bpf_verifier_lock);
13296 }
13297 return btf_vmlinux;
13298}
13299
Yonghong Song838e9692018-11-19 15:29:11 -080013300int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
13301 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013302{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013303 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013304 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070013305 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013306 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013307 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013308
Arnd Bergmanneba0c922017-11-02 12:05:52 +010013309 /* no program is valid */
13310 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13311 return -EINVAL;
13312
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013313 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013314 * allocate/free it every time bpf_check() is called
13315 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013316 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013317 if (!env)
13318 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070013319 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013320
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013321 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070013322 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013323 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013324 ret = -ENOMEM;
13325 if (!env->insn_aux_data)
13326 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013327 for (i = 0; i < len; i++)
13328 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013329 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070013330 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013331 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013332
Alan Maguire76654e62020-09-28 12:31:03 +010013333 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013334
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013335 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070013336 if (!is_priv)
13337 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013338
13339 if (attr->log_level || attr->log_buf || attr->log_size) {
13340 /* user requested verbose verifier output
13341 * and supplied buffer to store the verification trace
13342 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070013343 log->level = attr->log_level;
13344 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13345 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013346
13347 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070013348 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070013349 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013350 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013351 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013352 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020013353
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013354 if (IS_ERR(btf_vmlinux)) {
13355 /* Either gcc or pahole or kernel are broken. */
13356 verbose(env, "in-kernel BTF is malformed\n");
13357 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013358 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013359 }
13360
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020013361 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13362 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070013363 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080013364 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13365 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013366
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013367 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050013368 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070013369 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013370 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13371 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13372 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013373
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070013374 if (is_priv)
13375 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13376
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070013377 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013378 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013379 GFP_USER);
13380 ret = -ENOMEM;
13381 if (!env->explored_states)
13382 goto skip_full_check;
13383
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013384 ret = add_subprog_and_kfunc(env);
13385 if (ret < 0)
13386 goto skip_full_check;
13387
Martin KaFai Laud9762e82018-12-13 10:41:48 -080013388 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070013389 if (ret < 0)
13390 goto skip_full_check;
13391
Martin KaFai Lauc454a462018-12-07 16:42:25 -080013392 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080013393 if (ret < 0)
13394 goto skip_full_check;
13395
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013396 ret = check_attach_btf_id(env);
13397 if (ret)
13398 goto skip_full_check;
13399
Hao Luo4976b712020-09-29 16:50:44 -070013400 ret = resolve_pseudo_ldimm64(env);
13401 if (ret < 0)
13402 goto skip_full_check;
13403
Yinjun Zhangceb11672021-05-20 10:58:34 +020013404 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13405 ret = bpf_prog_offload_verifier_prep(env->prog);
13406 if (ret)
13407 goto skip_full_check;
13408 }
13409
Martin KaFai Laud9762e82018-12-13 10:41:48 -080013410 ret = check_cfg(env);
13411 if (ret < 0)
13412 goto skip_full_check;
13413
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013414 ret = do_check_subprogs(env);
13415 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013416
Quentin Monnetc941ce92018-10-07 12:56:47 +010013417 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13418 ret = bpf_prog_offload_finalize(env);
13419
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013420skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013421 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013422
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013423 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080013424 ret = check_max_stack_depth(env);
13425
Jakub Kicinski9b38c402018-12-19 22:13:06 -080013426 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013427 if (is_priv) {
13428 if (ret == 0)
13429 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080013430 if (ret == 0)
13431 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080013432 if (ret == 0)
13433 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080013434 } else {
13435 if (ret == 0)
13436 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013437 }
13438
Jakub Kicinski9b38c402018-12-19 22:13:06 -080013439 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013440 /* program is valid, convert *(u32*)(ctx + off) accesses */
13441 ret = convert_ctx_accesses(env);
13442
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013443 if (ret == 0)
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013444 ret = do_misc_fixups(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013445
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010013446 /* do 32-bit optimization after insn patching has done so those patched
13447 * insns could be handled correctly.
13448 */
Jiong Wangd6c23082019-05-24 23:25:18 +010013449 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13450 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13451 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13452 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010013453 }
13454
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080013455 if (ret == 0)
13456 ret = fixup_call_args(env);
13457
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013458 env->verification_time = ktime_get_ns() - start_time;
13459 print_verification_stats(env);
13460
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013461 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013462 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013463 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013464 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013465 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013466 }
13467
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013468 if (ret)
13469 goto err_release_maps;
13470
13471 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013472 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013473 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13474 sizeof(env->used_maps[0]),
13475 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013476
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013477 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013478 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013479 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013480 }
13481
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013482 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013483 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013484 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013485 }
13486 if (env->used_btf_cnt) {
13487 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13488 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13489 sizeof(env->used_btfs[0]),
13490 GFP_KERNEL);
13491 if (!env->prog->aux->used_btfs) {
13492 ret = -ENOMEM;
13493 goto err_release_maps;
13494 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013495
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013496 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13497 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13498 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13499 }
13500 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013501 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13502 * bpf_ld_imm64 instructions
13503 */
13504 convert_pseudo_ld_imm64(env);
13505 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013506
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013507 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080013508
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013509err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013510 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013511 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070013512 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013513 */
13514 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013515 if (!env->prog->aux->used_btfs)
13516 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020013517
13518 /* extension progs temporarily inherit the attach_type of their targets
13519 for verification purposes, so set it back to zero before returning
13520 */
13521 if (env->prog->type == BPF_PROG_TYPE_EXT)
13522 env->prog->expected_attach_type = 0;
13523
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013524 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013525err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070013526 if (!is_priv)
13527 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013528 vfree(env->insn_aux_data);
13529err_free_env:
13530 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013531 return ret;
13532}