blob: f9bda5476ea55c5823c97c83488c42325d65388b [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 Laud9762e842018-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.
Zhen Lei8fb33b62021-05-25 10:56:59 +080050 * Since it's analyzing all paths 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
Zhen Lei8fb33b62021-05-25 10:56:59 +0800135 * returns either pointer to map value or NULL.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700136 *
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 Nakryiko457f44362020-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 Laud9762e842018-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 Laud9762e842018-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 Nakryiko457f44362020-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 Nakryiko457f44362020-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 Nakryiko457f44362020-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 Nakryiko457f44362020-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 Nakryiko457f44362020-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 Nakryiko457f44362020-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
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100740/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
741 * small to hold src. This is different from krealloc since we don't want to preserve
742 * the contents of dst.
743 *
744 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
745 * not be allocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700746 */
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100747static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700748{
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100749 size_t bytes;
750
751 if (ZERO_OR_NULL_PTR(src))
752 goto out;
753
754 if (unlikely(check_mul_overflow(n, size, &bytes)))
755 return NULL;
756
757 if (ksize(dst) < bytes) {
758 kfree(dst);
759 dst = kmalloc_track_caller(bytes, flags);
760 if (!dst)
761 return NULL;
762 }
763
764 memcpy(dst, src, bytes);
765out:
766 return dst ? dst : ZERO_SIZE_PTR;
767}
768
769/* resize an array from old_n items to new_n items. the array is reallocated if it's too
770 * small to hold new_n items. new items are zeroed out if the array grows.
771 *
772 * Contrary to krealloc_array, does not free arr if new_n is zero.
773 */
774static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
775{
776 if (!new_n || old_n == new_n)
777 goto out;
778
779 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
780 if (!arr)
781 return NULL;
782
783 if (new_n > old_n)
784 memset(arr + old_n * size, 0, (new_n - old_n) * size);
785
786out:
787 return arr ? arr : ZERO_SIZE_PTR;
788}
789
790static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
791{
792 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
793 sizeof(struct bpf_reference_state), GFP_KERNEL);
794 if (!dst->refs)
795 return -ENOMEM;
796
797 dst->acquired_refs = src->acquired_refs;
798 return 0;
799}
800
801static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
802{
803 size_t n = src->allocated_stack / BPF_REG_SIZE;
804
805 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
806 GFP_KERNEL);
807 if (!dst->stack)
808 return -ENOMEM;
809
810 dst->allocated_stack = src->allocated_stack;
811 return 0;
812}
813
814static int resize_reference_state(struct bpf_func_state *state, size_t n)
815{
816 state->refs = realloc_array(state->refs, state->acquired_refs, n,
817 sizeof(struct bpf_reference_state));
818 if (!state->refs)
819 return -ENOMEM;
820
821 state->acquired_refs = n;
822 return 0;
823}
824
825static int grow_stack_state(struct bpf_func_state *state, int size)
826{
827 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
828
829 if (old_n >= n)
830 return 0;
831
832 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
833 if (!state->stack)
834 return -ENOMEM;
835
836 state->allocated_stack = size;
837 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700838}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700839
Joe Stringerfd978bf72018-10-02 13:35:35 -0700840/* Acquire a pointer id from the env and update the state->refs to include
841 * this new pointer reference.
842 * On success, returns a valid pointer id to associate with the register
843 * On failure, returns a negative errno.
844 */
845static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
846{
847 struct bpf_func_state *state = cur_func(env);
848 int new_ofs = state->acquired_refs;
849 int id, err;
850
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100851 err = resize_reference_state(state, state->acquired_refs + 1);
Joe Stringerfd978bf72018-10-02 13:35:35 -0700852 if (err)
853 return err;
854 id = ++env->id_gen;
855 state->refs[new_ofs].id = id;
856 state->refs[new_ofs].insn_idx = insn_idx;
857
858 return id;
859}
860
861/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800862static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700863{
864 int i, last_idx;
865
Joe Stringerfd978bf72018-10-02 13:35:35 -0700866 last_idx = state->acquired_refs - 1;
867 for (i = 0; i < state->acquired_refs; i++) {
868 if (state->refs[i].id == ptr_id) {
869 if (last_idx && i != last_idx)
870 memcpy(&state->refs[i], &state->refs[last_idx],
871 sizeof(*state->refs));
872 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
873 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700874 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700875 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700876 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800877 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700878}
879
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800880static void free_func_state(struct bpf_func_state *state)
881{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800882 if (!state)
883 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700884 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800885 kfree(state->stack);
886 kfree(state);
887}
888
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700889static void clear_jmp_history(struct bpf_verifier_state *state)
890{
891 kfree(state->jmp_history);
892 state->jmp_history = NULL;
893 state->jmp_history_cnt = 0;
894}
895
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700896static void free_verifier_state(struct bpf_verifier_state *state,
897 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700898{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800899 int i;
900
901 for (i = 0; i <= state->curframe; i++) {
902 free_func_state(state->frame[i]);
903 state->frame[i] = NULL;
904 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700905 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700906 if (free_self)
907 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700908}
909
910/* copy verifier state from src to dst growing dst stack space
911 * when necessary to accommodate larger src stack
912 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800913static int copy_func_state(struct bpf_func_state *dst,
914 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700915{
916 int err;
917
Joe Stringerfd978bf72018-10-02 13:35:35 -0700918 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
919 err = copy_reference_state(dst, src);
920 if (err)
921 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700922 return copy_stack_state(dst, src);
923}
924
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800925static int copy_verifier_state(struct bpf_verifier_state *dst_state,
926 const struct bpf_verifier_state *src)
927{
928 struct bpf_func_state *dst;
929 int i, err;
930
Lorenz Bauer06ab6a52021-04-29 14:46:55 +0100931 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
932 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
933 GFP_USER);
934 if (!dst_state->jmp_history)
935 return -ENOMEM;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700936 dst_state->jmp_history_cnt = src->jmp_history_cnt;
937
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800938 /* if dst has more stack frames then src frame, free them */
939 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
940 free_func_state(dst_state->frame[i]);
941 dst_state->frame[i] = NULL;
942 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100943 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800944 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800945 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700946 dst_state->branches = src->branches;
947 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700948 dst_state->first_insn_idx = src->first_insn_idx;
949 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800950 for (i = 0; i <= src->curframe; i++) {
951 dst = dst_state->frame[i];
952 if (!dst) {
953 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
954 if (!dst)
955 return -ENOMEM;
956 dst_state->frame[i] = dst;
957 }
958 err = copy_func_state(dst, src->frame[i]);
959 if (err)
960 return err;
961 }
962 return 0;
963}
964
Alexei Starovoitov25897262019-06-15 12:12:20 -0700965static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
966{
967 while (st) {
968 u32 br = --st->branches;
969
970 /* WARN_ON(br > 1) technically makes sense here,
971 * but see comment in push_stack(), hence:
972 */
973 WARN_ONCE((int)br < 0,
974 "BUG update_branch_counts:branches_to_explore=%d\n",
975 br);
976 if (br)
977 break;
978 st = st->parent;
979 }
980}
981
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700982static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700983 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700984{
985 struct bpf_verifier_state *cur = env->cur_state;
986 struct bpf_verifier_stack_elem *elem, *head = env->head;
987 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700988
989 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700990 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700991
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700992 if (cur) {
993 err = copy_verifier_state(cur, &head->st);
994 if (err)
995 return err;
996 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700997 if (pop_log)
998 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700999 if (insn_idx)
1000 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001001 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001002 *prev_insn_idx = head->prev_insn_idx;
1003 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001004 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001005 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001006 env->head = elem;
1007 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001008 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001009}
1010
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001011static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001012 int insn_idx, int prev_insn_idx,
1013 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001014{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001015 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001016 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001017 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001018
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001019 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001020 if (!elem)
1021 goto err;
1022
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001023 elem->insn_idx = insn_idx;
1024 elem->prev_insn_idx = prev_insn_idx;
1025 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001026 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001027 env->head = elem;
1028 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001029 err = copy_verifier_state(&elem->st, cur);
1030 if (err)
1031 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001032 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -07001033 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1034 verbose(env, "The sequence of %d jumps is too complex.\n",
1035 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001036 goto err;
1037 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07001038 if (elem->st.parent) {
1039 ++elem->st.parent->branches;
1040 /* WARN_ON(branches > 2) technically makes sense here,
1041 * but
1042 * 1. speculative states will bump 'branches' for non-branch
1043 * instructions
1044 * 2. is_state_visited() heuristics may decide not to create
1045 * a new state for a sequence of branches and all such current
1046 * and cloned states will be pointing to a single parent state
1047 * which might have large 'branches' count.
1048 */
1049 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001050 return &elem->st;
1051err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001052 free_verifier_state(env->cur_state, true);
1053 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001054 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001055 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001056 return NULL;
1057}
1058
1059#define CALLER_SAVED_REGS 6
1060static const int caller_saved[CALLER_SAVED_REGS] = {
1061 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1062};
1063
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001064static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1065 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001066
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001067/* This helper doesn't clear reg->id */
1068static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001069{
Edward Creeb03c9f92017-08-07 15:26:36 +01001070 reg->var_off = tnum_const(imm);
1071 reg->smin_value = (s64)imm;
1072 reg->smax_value = (s64)imm;
1073 reg->umin_value = imm;
1074 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001075
1076 reg->s32_min_value = (s32)imm;
1077 reg->s32_max_value = (s32)imm;
1078 reg->u32_min_value = (u32)imm;
1079 reg->u32_max_value = (u32)imm;
1080}
1081
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001082/* Mark the unknown part of a register (variable offset or scalar value) as
1083 * known to have the value @imm.
1084 */
1085static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1086{
1087 /* Clear id, off, and union(map_ptr, range) */
1088 memset(((u8 *)reg) + sizeof(reg->type), 0,
1089 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1090 ___mark_reg_known(reg, imm);
1091}
1092
John Fastabend3f50f132020-03-30 14:36:39 -07001093static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1094{
1095 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1096 reg->s32_min_value = (s32)imm;
1097 reg->s32_max_value = (s32)imm;
1098 reg->u32_min_value = (u32)imm;
1099 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001100}
1101
Edward Creef1174f72017-08-07 15:26:19 +01001102/* Mark the 'variable offset' part of a register as zero. This should be
1103 * used only on registers holding a pointer type.
1104 */
1105static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1106{
Edward Creeb03c9f92017-08-07 15:26:36 +01001107 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001108}
1109
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001110static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1111{
1112 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001113 reg->type = SCALAR_VALUE;
1114}
1115
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001116static void mark_reg_known_zero(struct bpf_verifier_env *env,
1117 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001118{
1119 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001120 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001121 /* Something bad happened, let's kill all regs */
1122 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001123 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001124 return;
1125 }
1126 __mark_reg_known_zero(regs + regno);
1127}
1128
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001129static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1130{
1131 switch (reg->type) {
1132 case PTR_TO_MAP_VALUE_OR_NULL: {
1133 const struct bpf_map *map = reg->map_ptr;
1134
1135 if (map->inner_map_meta) {
1136 reg->type = CONST_PTR_TO_MAP;
1137 reg->map_ptr = map->inner_map_meta;
1138 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1139 reg->type = PTR_TO_XDP_SOCK;
1140 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1141 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1142 reg->type = PTR_TO_SOCKET;
1143 } else {
1144 reg->type = PTR_TO_MAP_VALUE;
1145 }
1146 break;
1147 }
1148 case PTR_TO_SOCKET_OR_NULL:
1149 reg->type = PTR_TO_SOCKET;
1150 break;
1151 case PTR_TO_SOCK_COMMON_OR_NULL:
1152 reg->type = PTR_TO_SOCK_COMMON;
1153 break;
1154 case PTR_TO_TCP_SOCK_OR_NULL:
1155 reg->type = PTR_TO_TCP_SOCK;
1156 break;
1157 case PTR_TO_BTF_ID_OR_NULL:
1158 reg->type = PTR_TO_BTF_ID;
1159 break;
1160 case PTR_TO_MEM_OR_NULL:
1161 reg->type = PTR_TO_MEM;
1162 break;
1163 case PTR_TO_RDONLY_BUF_OR_NULL:
1164 reg->type = PTR_TO_RDONLY_BUF;
1165 break;
1166 case PTR_TO_RDWR_BUF_OR_NULL:
1167 reg->type = PTR_TO_RDWR_BUF;
1168 break;
1169 default:
Dan Carpenter33ccec52021-02-17 10:45:25 +03001170 WARN_ONCE(1, "unknown nullable register type");
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001171 }
1172}
1173
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001174static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1175{
1176 return type_is_pkt_pointer(reg->type);
1177}
1178
1179static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1180{
1181 return reg_is_pkt_pointer(reg) ||
1182 reg->type == PTR_TO_PACKET_END;
1183}
1184
1185/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1186static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1187 enum bpf_reg_type which)
1188{
1189 /* The register can already have a range from prior markings.
1190 * This is fine as long as it hasn't been advanced from its
1191 * origin.
1192 */
1193 return reg->type == which &&
1194 reg->id == 0 &&
1195 reg->off == 0 &&
1196 tnum_equals_const(reg->var_off, 0);
1197}
1198
John Fastabend3f50f132020-03-30 14:36:39 -07001199/* Reset the min/max bounds of a register */
1200static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1201{
1202 reg->smin_value = S64_MIN;
1203 reg->smax_value = S64_MAX;
1204 reg->umin_value = 0;
1205 reg->umax_value = U64_MAX;
1206
1207 reg->s32_min_value = S32_MIN;
1208 reg->s32_max_value = S32_MAX;
1209 reg->u32_min_value = 0;
1210 reg->u32_max_value = U32_MAX;
1211}
1212
1213static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1214{
1215 reg->smin_value = S64_MIN;
1216 reg->smax_value = S64_MAX;
1217 reg->umin_value = 0;
1218 reg->umax_value = U64_MAX;
1219}
1220
1221static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1222{
1223 reg->s32_min_value = S32_MIN;
1224 reg->s32_max_value = S32_MAX;
1225 reg->u32_min_value = 0;
1226 reg->u32_max_value = U32_MAX;
1227}
1228
1229static void __update_reg32_bounds(struct bpf_reg_state *reg)
1230{
1231 struct tnum var32_off = tnum_subreg(reg->var_off);
1232
1233 /* min signed is max(sign bit) | min(other bits) */
1234 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1235 var32_off.value | (var32_off.mask & S32_MIN));
1236 /* max signed is min(sign bit) | max(other bits) */
1237 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1238 var32_off.value | (var32_off.mask & S32_MAX));
1239 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1240 reg->u32_max_value = min(reg->u32_max_value,
1241 (u32)(var32_off.value | var32_off.mask));
1242}
1243
1244static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001245{
1246 /* min signed is max(sign bit) | min(other bits) */
1247 reg->smin_value = max_t(s64, reg->smin_value,
1248 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1249 /* max signed is min(sign bit) | max(other bits) */
1250 reg->smax_value = min_t(s64, reg->smax_value,
1251 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1252 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1253 reg->umax_value = min(reg->umax_value,
1254 reg->var_off.value | reg->var_off.mask);
1255}
1256
John Fastabend3f50f132020-03-30 14:36:39 -07001257static void __update_reg_bounds(struct bpf_reg_state *reg)
1258{
1259 __update_reg32_bounds(reg);
1260 __update_reg64_bounds(reg);
1261}
1262
Edward Creeb03c9f92017-08-07 15:26:36 +01001263/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001264static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1265{
1266 /* Learn sign from signed bounds.
1267 * If we cannot cross the sign boundary, then signed and unsigned bounds
1268 * are the same, so combine. This works even in the negative case, e.g.
1269 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1270 */
1271 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1272 reg->s32_min_value = reg->u32_min_value =
1273 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1274 reg->s32_max_value = reg->u32_max_value =
1275 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1276 return;
1277 }
1278 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1279 * boundary, so we must be careful.
1280 */
1281 if ((s32)reg->u32_max_value >= 0) {
1282 /* Positive. We can't learn anything from the smin, but smax
1283 * is positive, hence safe.
1284 */
1285 reg->s32_min_value = reg->u32_min_value;
1286 reg->s32_max_value = reg->u32_max_value =
1287 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1288 } else if ((s32)reg->u32_min_value < 0) {
1289 /* Negative. We can't learn anything from the smax, but smin
1290 * is negative, hence safe.
1291 */
1292 reg->s32_min_value = reg->u32_min_value =
1293 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1294 reg->s32_max_value = reg->u32_max_value;
1295 }
1296}
1297
1298static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001299{
1300 /* Learn sign from signed bounds.
1301 * If we cannot cross the sign boundary, then signed and unsigned bounds
1302 * are the same, so combine. This works even in the negative case, e.g.
1303 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1304 */
1305 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1306 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1307 reg->umin_value);
1308 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1309 reg->umax_value);
1310 return;
1311 }
1312 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1313 * boundary, so we must be careful.
1314 */
1315 if ((s64)reg->umax_value >= 0) {
1316 /* Positive. We can't learn anything from the smin, but smax
1317 * is positive, hence safe.
1318 */
1319 reg->smin_value = reg->umin_value;
1320 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1321 reg->umax_value);
1322 } else if ((s64)reg->umin_value < 0) {
1323 /* Negative. We can't learn anything from the smax, but smin
1324 * is negative, hence safe.
1325 */
1326 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1327 reg->umin_value);
1328 reg->smax_value = reg->umax_value;
1329 }
1330}
1331
John Fastabend3f50f132020-03-30 14:36:39 -07001332static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1333{
1334 __reg32_deduce_bounds(reg);
1335 __reg64_deduce_bounds(reg);
1336}
1337
Edward Creeb03c9f92017-08-07 15:26:36 +01001338/* Attempts to improve var_off based on unsigned min/max information */
1339static void __reg_bound_offset(struct bpf_reg_state *reg)
1340{
John Fastabend3f50f132020-03-30 14:36:39 -07001341 struct tnum var64_off = tnum_intersect(reg->var_off,
1342 tnum_range(reg->umin_value,
1343 reg->umax_value));
1344 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1345 tnum_range(reg->u32_min_value,
1346 reg->u32_max_value));
1347
1348 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001349}
1350
John Fastabend3f50f132020-03-30 14:36:39 -07001351static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001352{
John Fastabend3f50f132020-03-30 14:36:39 -07001353 reg->umin_value = reg->u32_min_value;
1354 reg->umax_value = reg->u32_max_value;
1355 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1356 * but must be positive otherwise set to worse case bounds
1357 * and refine later from tnum.
1358 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001359 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001360 reg->smax_value = reg->s32_max_value;
1361 else
1362 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001363 if (reg->s32_min_value >= 0)
1364 reg->smin_value = reg->s32_min_value;
1365 else
1366 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001367}
1368
1369static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1370{
1371 /* special case when 64-bit register has upper 32-bit register
1372 * zeroed. Typically happens after zext or <<32, >>32 sequence
1373 * allowing us to use 32-bit bounds directly,
1374 */
1375 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1376 __reg_assign_32_into_64(reg);
1377 } else {
1378 /* Otherwise the best we can do is push lower 32bit known and
1379 * unknown bits into register (var_off set from jmp logic)
1380 * then learn as much as possible from the 64-bit tnum
1381 * known and unknown bits. The previous smin/smax bounds are
1382 * invalid here because of jmp32 compare so mark them unknown
1383 * so they do not impact tnum bounds calculation.
1384 */
1385 __mark_reg64_unbounded(reg);
1386 __update_reg_bounds(reg);
1387 }
1388
1389 /* Intersecting with the old var_off might have improved our bounds
1390 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1391 * then new var_off is (0; 0x7f...fc) which improves our umax.
1392 */
1393 __reg_deduce_bounds(reg);
1394 __reg_bound_offset(reg);
1395 __update_reg_bounds(reg);
1396}
1397
1398static bool __reg64_bound_s32(s64 a)
1399{
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001400 return a > S32_MIN && a < S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001401}
1402
1403static bool __reg64_bound_u32(u64 a)
1404{
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001405 return a > U32_MIN && a < U32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001406}
1407
1408static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1409{
1410 __mark_reg32_unbounded(reg);
1411
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001412 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001413 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001414 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001415 }
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001416 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001417 reg->u32_min_value = (u32)reg->umin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001418 reg->u32_max_value = (u32)reg->umax_value;
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001419 }
John Fastabend3f50f132020-03-30 14:36:39 -07001420
1421 /* Intersecting with the old var_off might have improved our bounds
1422 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1423 * then new var_off is (0; 0x7f...fc) which improves our umax.
1424 */
1425 __reg_deduce_bounds(reg);
1426 __reg_bound_offset(reg);
1427 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001428}
1429
Edward Creef1174f72017-08-07 15:26:19 +01001430/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001431static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1432 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001433{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001434 /*
1435 * Clear type, id, off, and union(map_ptr, range) and
1436 * padding between 'type' and union
1437 */
1438 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001439 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001440 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001441 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001442 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001443 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001444}
1445
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001446static void mark_reg_unknown(struct bpf_verifier_env *env,
1447 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001448{
1449 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001450 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001451 /* Something bad happened, let's kill all regs except FP */
1452 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001453 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001454 return;
1455 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001456 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001457}
1458
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001459static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1460 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001461{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001462 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001463 reg->type = NOT_INIT;
1464}
1465
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001466static void mark_reg_not_init(struct bpf_verifier_env *env,
1467 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001468{
Edward Creef1174f72017-08-07 15:26:19 +01001469 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001470 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001471 /* Something bad happened, let's kill all regs except FP */
1472 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001473 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001474 return;
1475 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001476 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001477}
1478
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001479static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1480 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001481 enum bpf_reg_type reg_type,
1482 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001483{
1484 if (reg_type == SCALAR_VALUE) {
1485 mark_reg_unknown(env, regs, regno);
1486 return;
1487 }
1488 mark_reg_known_zero(env, regs, regno);
1489 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001490 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001491 regs[regno].btf_id = btf_id;
1492}
1493
Jiong Wang5327ed32019-05-24 23:25:12 +01001494#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001495static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001496 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001497{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001498 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001499 int i;
1500
Edward Creedc503a82017-08-15 20:34:35 +01001501 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001502 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001503 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001504 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001505 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001506 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001507
1508 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001509 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001510 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001511 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001512}
1513
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001514#define BPF_MAIN_FUNC (-1)
1515static void init_func_state(struct bpf_verifier_env *env,
1516 struct bpf_func_state *state,
1517 int callsite, int frameno, int subprogno)
1518{
1519 state->callsite = callsite;
1520 state->frameno = frameno;
1521 state->subprogno = subprogno;
1522 init_reg_state(env, state);
1523}
1524
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001525enum reg_arg_type {
1526 SRC_OP, /* register is used as source operand */
1527 DST_OP, /* register is used as destination operand */
1528 DST_OP_NO_MARK /* same as above, check only, don't mark */
1529};
1530
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001531static int cmp_subprogs(const void *a, const void *b)
1532{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001533 return ((struct bpf_subprog_info *)a)->start -
1534 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001535}
1536
1537static int find_subprog(struct bpf_verifier_env *env, int off)
1538{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001539 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001540
Jiong Wang9c8105b2018-05-02 16:17:18 -04001541 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1542 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001543 if (!p)
1544 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001545 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001546
1547}
1548
1549static int add_subprog(struct bpf_verifier_env *env, int off)
1550{
1551 int insn_cnt = env->prog->len;
1552 int ret;
1553
1554 if (off >= insn_cnt || off < 0) {
1555 verbose(env, "call to invalid destination\n");
1556 return -EINVAL;
1557 }
1558 ret = find_subprog(env, off);
1559 if (ret >= 0)
Yonghong Song282a0f42021-02-26 12:49:24 -08001560 return ret;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001561 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001562 verbose(env, "too many subprograms\n");
1563 return -E2BIG;
1564 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001565 /* determine subprog starts. The end is one before the next starts */
Jiong Wang9c8105b2018-05-02 16:17:18 -04001566 env->subprog_info[env->subprog_cnt++].start = off;
1567 sort(env->subprog_info, env->subprog_cnt,
1568 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Yonghong Song282a0f42021-02-26 12:49:24 -08001569 return env->subprog_cnt - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001570}
1571
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001572struct bpf_kfunc_desc {
1573 struct btf_func_model func_model;
1574 u32 func_id;
1575 s32 imm;
1576};
1577
1578#define MAX_KFUNC_DESCS 256
1579struct bpf_kfunc_desc_tab {
1580 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1581 u32 nr_descs;
1582};
1583
1584static int kfunc_desc_cmp_by_id(const void *a, const void *b)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001585{
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001586 const struct bpf_kfunc_desc *d0 = a;
1587 const struct bpf_kfunc_desc *d1 = b;
1588
1589 /* func_id is not greater than BTF_MAX_TYPE */
1590 return d0->func_id - d1->func_id;
1591}
1592
1593static const struct bpf_kfunc_desc *
1594find_kfunc_desc(const struct bpf_prog *prog, u32 func_id)
1595{
1596 struct bpf_kfunc_desc desc = {
1597 .func_id = func_id,
1598 };
1599 struct bpf_kfunc_desc_tab *tab;
1600
1601 tab = prog->aux->kfunc_tab;
1602 return bsearch(&desc, tab->descs, tab->nr_descs,
1603 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id);
1604}
1605
1606static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id)
1607{
1608 const struct btf_type *func, *func_proto;
1609 struct bpf_kfunc_desc_tab *tab;
1610 struct bpf_prog_aux *prog_aux;
1611 struct bpf_kfunc_desc *desc;
1612 const char *func_name;
1613 unsigned long addr;
1614 int err;
1615
1616 prog_aux = env->prog->aux;
1617 tab = prog_aux->kfunc_tab;
1618 if (!tab) {
1619 if (!btf_vmlinux) {
1620 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1621 return -ENOTSUPP;
1622 }
1623
1624 if (!env->prog->jit_requested) {
1625 verbose(env, "JIT is required for calling kernel function\n");
1626 return -ENOTSUPP;
1627 }
1628
1629 if (!bpf_jit_supports_kfunc_call()) {
1630 verbose(env, "JIT does not support calling kernel function\n");
1631 return -ENOTSUPP;
1632 }
1633
1634 if (!env->prog->gpl_compatible) {
1635 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1636 return -EINVAL;
1637 }
1638
1639 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1640 if (!tab)
1641 return -ENOMEM;
1642 prog_aux->kfunc_tab = tab;
1643 }
1644
1645 if (find_kfunc_desc(env->prog, func_id))
1646 return 0;
1647
1648 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1649 verbose(env, "too many different kernel function calls\n");
1650 return -E2BIG;
1651 }
1652
1653 func = btf_type_by_id(btf_vmlinux, func_id);
1654 if (!func || !btf_type_is_func(func)) {
1655 verbose(env, "kernel btf_id %u is not a function\n",
1656 func_id);
1657 return -EINVAL;
1658 }
1659 func_proto = btf_type_by_id(btf_vmlinux, func->type);
1660 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1661 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1662 func_id);
1663 return -EINVAL;
1664 }
1665
1666 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
1667 addr = kallsyms_lookup_name(func_name);
1668 if (!addr) {
1669 verbose(env, "cannot find address for kernel function %s\n",
1670 func_name);
1671 return -EINVAL;
1672 }
1673
1674 desc = &tab->descs[tab->nr_descs++];
1675 desc->func_id = func_id;
1676 desc->imm = BPF_CAST_CALL(addr) - __bpf_call_base;
1677 err = btf_distill_func_proto(&env->log, btf_vmlinux,
1678 func_proto, func_name,
1679 &desc->func_model);
1680 if (!err)
1681 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1682 kfunc_desc_cmp_by_id, NULL);
1683 return err;
1684}
1685
1686static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1687{
1688 const struct bpf_kfunc_desc *d0 = a;
1689 const struct bpf_kfunc_desc *d1 = b;
1690
1691 if (d0->imm > d1->imm)
1692 return 1;
1693 else if (d0->imm < d1->imm)
1694 return -1;
1695 return 0;
1696}
1697
1698static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1699{
1700 struct bpf_kfunc_desc_tab *tab;
1701
1702 tab = prog->aux->kfunc_tab;
1703 if (!tab)
1704 return;
1705
1706 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1707 kfunc_desc_cmp_by_imm, NULL);
1708}
1709
1710bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1711{
1712 return !!prog->aux->kfunc_tab;
1713}
1714
1715const struct btf_func_model *
1716bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1717 const struct bpf_insn *insn)
1718{
1719 const struct bpf_kfunc_desc desc = {
1720 .imm = insn->imm,
1721 };
1722 const struct bpf_kfunc_desc *res;
1723 struct bpf_kfunc_desc_tab *tab;
1724
1725 tab = prog->aux->kfunc_tab;
1726 res = bsearch(&desc, tab->descs, tab->nr_descs,
1727 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
1728
1729 return res ? &res->func_model : NULL;
1730}
1731
1732static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
1733{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001734 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001735 struct bpf_insn *insn = env->prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001736 int i, ret, insn_cnt = env->prog->len;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001737
Jiong Wangf910cef2018-05-02 16:17:17 -04001738 /* Add entry function. */
1739 ret = add_subprog(env, 0);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001740 if (ret)
Jiong Wangf910cef2018-05-02 16:17:17 -04001741 return ret;
1742
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001743 for (i = 0; i < insn_cnt; i++, insn++) {
1744 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
1745 !bpf_pseudo_kfunc_call(insn))
Yonghong Song69c087b2021-02-26 12:49:25 -08001746 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001747
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001748 if (!env->bpf_capable) {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001749 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 -08001750 return -EPERM;
1751 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001752
1753 if (bpf_pseudo_func(insn)) {
1754 ret = add_subprog(env, i + insn->imm + 1);
1755 if (ret >= 0)
1756 /* remember subprog */
1757 insn[1].imm = ret;
1758 } else if (bpf_pseudo_call(insn)) {
1759 ret = add_subprog(env, i + insn->imm + 1);
1760 } else {
1761 ret = add_kfunc_call(env, insn->imm);
1762 }
1763
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001764 if (ret < 0)
1765 return ret;
1766 }
1767
Jiong Wang4cb3d992018-05-02 16:17:19 -04001768 /* Add a fake 'exit' subprog which could simplify subprog iteration
1769 * logic. 'subprog_cnt' should not be increased.
1770 */
1771 subprog[env->subprog_cnt].start = insn_cnt;
1772
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001773 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001774 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001775 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001776
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001777 return 0;
1778}
1779
1780static int check_subprogs(struct bpf_verifier_env *env)
1781{
1782 int i, subprog_start, subprog_end, off, cur_subprog = 0;
1783 struct bpf_subprog_info *subprog = env->subprog_info;
1784 struct bpf_insn *insn = env->prog->insnsi;
1785 int insn_cnt = env->prog->len;
1786
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001787 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001788 subprog_start = subprog[cur_subprog].start;
1789 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001790 for (i = 0; i < insn_cnt; i++) {
1791 u8 code = insn[i].code;
1792
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001793 if (code == (BPF_JMP | BPF_CALL) &&
1794 insn[i].imm == BPF_FUNC_tail_call &&
1795 insn[i].src_reg != BPF_PSEUDO_CALL)
1796 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001797 if (BPF_CLASS(code) == BPF_LD &&
1798 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1799 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001800 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001801 goto next;
1802 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1803 goto next;
1804 off = i + insn[i].off + 1;
1805 if (off < subprog_start || off >= subprog_end) {
1806 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1807 return -EINVAL;
1808 }
1809next:
1810 if (i == subprog_end - 1) {
1811 /* to avoid fall-through from one subprog into another
1812 * the last insn of the subprog should be either exit
1813 * or unconditional jump back
1814 */
1815 if (code != (BPF_JMP | BPF_EXIT) &&
1816 code != (BPF_JMP | BPF_JA)) {
1817 verbose(env, "last insn is not an exit or jmp\n");
1818 return -EINVAL;
1819 }
1820 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001821 cur_subprog++;
1822 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001823 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001824 }
1825 }
1826 return 0;
1827}
1828
Edward Cree679c7822018-08-22 20:02:19 +01001829/* Parentage chain of this register (or stack slot) should take care of all
1830 * issues like callee-saved registers, stack slot allocation time, etc.
1831 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001832static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001833 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001834 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001835{
1836 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001837 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001838
1839 while (parent) {
1840 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001841 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001842 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001843 if (parent->live & REG_LIVE_DONE) {
1844 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1845 reg_type_str[parent->type],
1846 parent->var_off.value, parent->off);
1847 return -EFAULT;
1848 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001849 /* The first condition is more likely to be true than the
1850 * second, checked it first.
1851 */
1852 if ((parent->live & REG_LIVE_READ) == flag ||
1853 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001854 /* The parentage chain never changes and
1855 * this parent was already marked as LIVE_READ.
1856 * There is no need to keep walking the chain again and
1857 * keep re-marking all parents as LIVE_READ.
1858 * This case happens when the same register is read
1859 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001860 * Also, if parent has the stronger REG_LIVE_READ64 set,
1861 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001862 */
1863 break;
Edward Creedc503a82017-08-15 20:34:35 +01001864 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001865 parent->live |= flag;
1866 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1867 if (flag == REG_LIVE_READ64)
1868 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001869 state = parent;
1870 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001871 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001872 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001873 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001874
1875 if (env->longest_mark_read_walk < cnt)
1876 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001877 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001878}
1879
Jiong Wang5327ed32019-05-24 23:25:12 +01001880/* This function is supposed to be used by the following 32-bit optimization
1881 * code only. It returns TRUE if the source or destination register operates
1882 * on 64-bit, otherwise return FALSE.
1883 */
1884static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1885 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1886{
1887 u8 code, class, op;
1888
1889 code = insn->code;
1890 class = BPF_CLASS(code);
1891 op = BPF_OP(code);
1892 if (class == BPF_JMP) {
1893 /* BPF_EXIT for "main" will reach here. Return TRUE
1894 * conservatively.
1895 */
1896 if (op == BPF_EXIT)
1897 return true;
1898 if (op == BPF_CALL) {
1899 /* BPF to BPF call will reach here because of marking
1900 * caller saved clobber with DST_OP_NO_MARK for which we
1901 * don't care the register def because they are anyway
1902 * marked as NOT_INIT already.
1903 */
1904 if (insn->src_reg == BPF_PSEUDO_CALL)
1905 return false;
1906 /* Helper call will reach here because of arg type
1907 * check, conservatively return TRUE.
1908 */
1909 if (t == SRC_OP)
1910 return true;
1911
1912 return false;
1913 }
1914 }
1915
1916 if (class == BPF_ALU64 || class == BPF_JMP ||
1917 /* BPF_END always use BPF_ALU class. */
1918 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1919 return true;
1920
1921 if (class == BPF_ALU || class == BPF_JMP32)
1922 return false;
1923
1924 if (class == BPF_LDX) {
1925 if (t != SRC_OP)
1926 return BPF_SIZE(code) == BPF_DW;
1927 /* LDX source must be ptr. */
1928 return true;
1929 }
1930
1931 if (class == BPF_STX) {
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001932 /* BPF_STX (including atomic variants) has multiple source
1933 * operands, one of which is a ptr. Check whether the caller is
1934 * asking about it.
1935 */
1936 if (t == SRC_OP && reg->type != SCALAR_VALUE)
Jiong Wang5327ed32019-05-24 23:25:12 +01001937 return true;
1938 return BPF_SIZE(code) == BPF_DW;
1939 }
1940
1941 if (class == BPF_LD) {
1942 u8 mode = BPF_MODE(code);
1943
1944 /* LD_IMM64 */
1945 if (mode == BPF_IMM)
1946 return true;
1947
1948 /* Both LD_IND and LD_ABS return 32-bit data. */
1949 if (t != SRC_OP)
1950 return false;
1951
1952 /* Implicit ctx ptr. */
1953 if (regno == BPF_REG_6)
1954 return true;
1955
1956 /* Explicit source could be any width. */
1957 return true;
1958 }
1959
1960 if (class == BPF_ST)
1961 /* The only source register for BPF_ST is a ptr. */
1962 return true;
1963
1964 /* Conservatively return true at default. */
1965 return true;
1966}
1967
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001968/* Return the regno defined by the insn, or -1. */
1969static int insn_def_regno(const struct bpf_insn *insn)
Jiong Wangb325fbc2019-05-24 23:25:13 +01001970{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001971 switch (BPF_CLASS(insn->code)) {
1972 case BPF_JMP:
1973 case BPF_JMP32:
1974 case BPF_ST:
1975 return -1;
1976 case BPF_STX:
1977 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
1978 (insn->imm & BPF_FETCH)) {
1979 if (insn->imm == BPF_CMPXCHG)
1980 return BPF_REG_0;
1981 else
1982 return insn->src_reg;
1983 } else {
1984 return -1;
1985 }
1986 default:
1987 return insn->dst_reg;
1988 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01001989}
1990
1991/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1992static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1993{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001994 int dst_reg = insn_def_regno(insn);
1995
1996 if (dst_reg == -1)
Jiong Wangb325fbc2019-05-24 23:25:13 +01001997 return false;
1998
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01001999 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
Jiong Wangb325fbc2019-05-24 23:25:13 +01002000}
2001
Jiong Wang5327ed32019-05-24 23:25:12 +01002002static void mark_insn_zext(struct bpf_verifier_env *env,
2003 struct bpf_reg_state *reg)
2004{
2005 s32 def_idx = reg->subreg_def;
2006
2007 if (def_idx == DEF_NOT_SUBREG)
2008 return;
2009
2010 env->insn_aux_data[def_idx - 1].zext_dst = true;
2011 /* The dst will be zero extended, so won't be sub-register anymore. */
2012 reg->subreg_def = DEF_NOT_SUBREG;
2013}
2014
Edward Creedc503a82017-08-15 20:34:35 +01002015static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002016 enum reg_arg_type t)
2017{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002018 struct bpf_verifier_state *vstate = env->cur_state;
2019 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01002020 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01002021 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01002022 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01002023
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002024 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002025 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002026 return -EINVAL;
2027 }
2028
Jiong Wangc342dc12019-04-12 22:59:37 +01002029 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01002030 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002031 if (t == SRC_OP) {
2032 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01002033 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002034 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002035 return -EACCES;
2036 }
Edward Cree679c7822018-08-22 20:02:19 +01002037 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01002038 if (regno == BPF_REG_FP)
2039 return 0;
2040
Jiong Wang5327ed32019-05-24 23:25:12 +01002041 if (rw64)
2042 mark_insn_zext(env, reg);
2043
2044 return mark_reg_read(env, reg, reg->parent,
2045 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002046 } else {
2047 /* check whether register used as dest operand can be written to */
2048 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002049 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002050 return -EACCES;
2051 }
Jiong Wangc342dc12019-04-12 22:59:37 +01002052 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01002053 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002054 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002055 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002056 }
2057 return 0;
2058}
2059
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002060/* for any branch, call, exit record the history of jmps in the given state */
2061static int push_jmp_history(struct bpf_verifier_env *env,
2062 struct bpf_verifier_state *cur)
2063{
2064 u32 cnt = cur->jmp_history_cnt;
2065 struct bpf_idx_pair *p;
2066
2067 cnt++;
2068 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2069 if (!p)
2070 return -ENOMEM;
2071 p[cnt - 1].idx = env->insn_idx;
2072 p[cnt - 1].prev_idx = env->prev_insn_idx;
2073 cur->jmp_history = p;
2074 cur->jmp_history_cnt = cnt;
2075 return 0;
2076}
2077
2078/* Backtrack one insn at a time. If idx is not at the top of recorded
2079 * history then previous instruction came from straight line execution.
2080 */
2081static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2082 u32 *history)
2083{
2084 u32 cnt = *history;
2085
2086 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2087 i = st->jmp_history[cnt - 1].prev_idx;
2088 (*history)--;
2089 } else {
2090 i--;
2091 }
2092 return i;
2093}
2094
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002095static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2096{
2097 const struct btf_type *func;
2098
2099 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2100 return NULL;
2101
2102 func = btf_type_by_id(btf_vmlinux, insn->imm);
2103 return btf_name_by_offset(btf_vmlinux, func->name_off);
2104}
2105
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002106/* For given verifier state backtrack_insn() is called from the last insn to
2107 * the first insn. Its purpose is to compute a bitmask of registers and
2108 * stack slots that needs precision in the parent verifier state.
2109 */
2110static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2111 u32 *reg_mask, u64 *stack_mask)
2112{
2113 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002114 .cb_call = disasm_kfunc_name,
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002115 .cb_print = verbose,
2116 .private_data = env,
2117 };
2118 struct bpf_insn *insn = env->prog->insnsi + idx;
2119 u8 class = BPF_CLASS(insn->code);
2120 u8 opcode = BPF_OP(insn->code);
2121 u8 mode = BPF_MODE(insn->code);
2122 u32 dreg = 1u << insn->dst_reg;
2123 u32 sreg = 1u << insn->src_reg;
2124 u32 spi;
2125
2126 if (insn->code == 0)
2127 return 0;
2128 if (env->log.level & BPF_LOG_LEVEL) {
2129 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2130 verbose(env, "%d: ", idx);
2131 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2132 }
2133
2134 if (class == BPF_ALU || class == BPF_ALU64) {
2135 if (!(*reg_mask & dreg))
2136 return 0;
2137 if (opcode == BPF_MOV) {
2138 if (BPF_SRC(insn->code) == BPF_X) {
2139 /* dreg = sreg
2140 * dreg needs precision after this insn
2141 * sreg needs precision before this insn
2142 */
2143 *reg_mask &= ~dreg;
2144 *reg_mask |= sreg;
2145 } else {
2146 /* dreg = K
2147 * dreg needs precision after this insn.
2148 * Corresponding register is already marked
2149 * as precise=true in this verifier state.
2150 * No further markings in parent are necessary
2151 */
2152 *reg_mask &= ~dreg;
2153 }
2154 } else {
2155 if (BPF_SRC(insn->code) == BPF_X) {
2156 /* dreg += sreg
2157 * both dreg and sreg need precision
2158 * before this insn
2159 */
2160 *reg_mask |= sreg;
2161 } /* else dreg += K
2162 * dreg still needs precision before this insn
2163 */
2164 }
2165 } else if (class == BPF_LDX) {
2166 if (!(*reg_mask & dreg))
2167 return 0;
2168 *reg_mask &= ~dreg;
2169
2170 /* scalars can only be spilled into stack w/o losing precision.
2171 * Load from any other memory can be zero extended.
2172 * The desire to keep that precision is already indicated
2173 * by 'precise' mark in corresponding register of this state.
2174 * No further tracking necessary.
2175 */
2176 if (insn->src_reg != BPF_REG_FP)
2177 return 0;
2178 if (BPF_SIZE(insn->code) != BPF_DW)
2179 return 0;
2180
2181 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2182 * that [fp - off] slot contains scalar that needs to be
2183 * tracked with precision
2184 */
2185 spi = (-insn->off - 1) / BPF_REG_SIZE;
2186 if (spi >= 64) {
2187 verbose(env, "BUG spi %d\n", spi);
2188 WARN_ONCE(1, "verifier backtracking bug");
2189 return -EFAULT;
2190 }
2191 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002192 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002193 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002194 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002195 * to access memory. It means backtracking
2196 * encountered a case of pointer subtraction.
2197 */
2198 return -ENOTSUPP;
2199 /* scalars can only be spilled into stack */
2200 if (insn->dst_reg != BPF_REG_FP)
2201 return 0;
2202 if (BPF_SIZE(insn->code) != BPF_DW)
2203 return 0;
2204 spi = (-insn->off - 1) / BPF_REG_SIZE;
2205 if (spi >= 64) {
2206 verbose(env, "BUG spi %d\n", spi);
2207 WARN_ONCE(1, "verifier backtracking bug");
2208 return -EFAULT;
2209 }
2210 if (!(*stack_mask & (1ull << spi)))
2211 return 0;
2212 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002213 if (class == BPF_STX)
2214 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002215 } else if (class == BPF_JMP || class == BPF_JMP32) {
2216 if (opcode == BPF_CALL) {
2217 if (insn->src_reg == BPF_PSEUDO_CALL)
2218 return -ENOTSUPP;
2219 /* regular helper call sets R0 */
2220 *reg_mask &= ~1;
2221 if (*reg_mask & 0x3f) {
2222 /* if backtracing was looking for registers R1-R5
2223 * they should have been found already.
2224 */
2225 verbose(env, "BUG regs %x\n", *reg_mask);
2226 WARN_ONCE(1, "verifier backtracking bug");
2227 return -EFAULT;
2228 }
2229 } else if (opcode == BPF_EXIT) {
2230 return -ENOTSUPP;
2231 }
2232 } else if (class == BPF_LD) {
2233 if (!(*reg_mask & dreg))
2234 return 0;
2235 *reg_mask &= ~dreg;
2236 /* It's ld_imm64 or ld_abs or ld_ind.
2237 * For ld_imm64 no further tracking of precision
2238 * into parent is necessary
2239 */
2240 if (mode == BPF_IND || mode == BPF_ABS)
2241 /* to be analyzed */
2242 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002243 }
2244 return 0;
2245}
2246
2247/* the scalar precision tracking algorithm:
2248 * . at the start all registers have precise=false.
2249 * . scalar ranges are tracked as normal through alu and jmp insns.
2250 * . once precise value of the scalar register is used in:
2251 * . ptr + scalar alu
2252 * . if (scalar cond K|scalar)
2253 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2254 * backtrack through the verifier states and mark all registers and
2255 * stack slots with spilled constants that these scalar regisers
2256 * should be precise.
2257 * . during state pruning two registers (or spilled stack slots)
2258 * are equivalent if both are not precise.
2259 *
2260 * Note the verifier cannot simply walk register parentage chain,
2261 * since many different registers and stack slots could have been
2262 * used to compute single precise scalar.
2263 *
2264 * The approach of starting with precise=true for all registers and then
2265 * backtrack to mark a register as not precise when the verifier detects
2266 * that program doesn't care about specific value (e.g., when helper
2267 * takes register as ARG_ANYTHING parameter) is not safe.
2268 *
2269 * It's ok to walk single parentage chain of the verifier states.
2270 * It's possible that this backtracking will go all the way till 1st insn.
2271 * All other branches will be explored for needing precision later.
2272 *
2273 * The backtracking needs to deal with cases like:
2274 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
2275 * r9 -= r8
2276 * r5 = r9
2277 * if r5 > 0x79f goto pc+7
2278 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2279 * r5 += 1
2280 * ...
2281 * call bpf_perf_event_output#25
2282 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2283 *
2284 * and this case:
2285 * r6 = 1
2286 * call foo // uses callee's r6 inside to compute r0
2287 * r0 += r6
2288 * if r0 == 0 goto
2289 *
2290 * to track above reg_mask/stack_mask needs to be independent for each frame.
2291 *
2292 * Also if parent's curframe > frame where backtracking started,
2293 * the verifier need to mark registers in both frames, otherwise callees
2294 * may incorrectly prune callers. This is similar to
2295 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2296 *
2297 * For now backtracking falls back into conservative marking.
2298 */
2299static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2300 struct bpf_verifier_state *st)
2301{
2302 struct bpf_func_state *func;
2303 struct bpf_reg_state *reg;
2304 int i, j;
2305
2306 /* big hammer: mark all scalars precise in this path.
2307 * pop_stack may still get !precise scalars.
2308 */
2309 for (; st; st = st->parent)
2310 for (i = 0; i <= st->curframe; i++) {
2311 func = st->frame[i];
2312 for (j = 0; j < BPF_REG_FP; j++) {
2313 reg = &func->regs[j];
2314 if (reg->type != SCALAR_VALUE)
2315 continue;
2316 reg->precise = true;
2317 }
2318 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2319 if (func->stack[j].slot_type[0] != STACK_SPILL)
2320 continue;
2321 reg = &func->stack[j].spilled_ptr;
2322 if (reg->type != SCALAR_VALUE)
2323 continue;
2324 reg->precise = true;
2325 }
2326 }
2327}
2328
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002329static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2330 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002331{
2332 struct bpf_verifier_state *st = env->cur_state;
2333 int first_idx = st->first_insn_idx;
2334 int last_idx = env->insn_idx;
2335 struct bpf_func_state *func;
2336 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002337 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2338 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002339 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002340 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002341 int i, err;
2342
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002343 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002344 return 0;
2345
2346 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002347 if (regno >= 0) {
2348 reg = &func->regs[regno];
2349 if (reg->type != SCALAR_VALUE) {
2350 WARN_ONCE(1, "backtracing misuse");
2351 return -EFAULT;
2352 }
2353 if (!reg->precise)
2354 new_marks = true;
2355 else
2356 reg_mask = 0;
2357 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002358 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002359
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002360 while (spi >= 0) {
2361 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2362 stack_mask = 0;
2363 break;
2364 }
2365 reg = &func->stack[spi].spilled_ptr;
2366 if (reg->type != SCALAR_VALUE) {
2367 stack_mask = 0;
2368 break;
2369 }
2370 if (!reg->precise)
2371 new_marks = true;
2372 else
2373 stack_mask = 0;
2374 reg->precise = true;
2375 break;
2376 }
2377
2378 if (!new_marks)
2379 return 0;
2380 if (!reg_mask && !stack_mask)
2381 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002382 for (;;) {
2383 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002384 u32 history = st->jmp_history_cnt;
2385
2386 if (env->log.level & BPF_LOG_LEVEL)
2387 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2388 for (i = last_idx;;) {
2389 if (skip_first) {
2390 err = 0;
2391 skip_first = false;
2392 } else {
2393 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2394 }
2395 if (err == -ENOTSUPP) {
2396 mark_all_scalars_precise(env, st);
2397 return 0;
2398 } else if (err) {
2399 return err;
2400 }
2401 if (!reg_mask && !stack_mask)
2402 /* Found assignment(s) into tracked register in this state.
2403 * Since this state is already marked, just return.
2404 * Nothing to be tracked further in the parent state.
2405 */
2406 return 0;
2407 if (i == first_idx)
2408 break;
2409 i = get_prev_insn_idx(st, i, &history);
2410 if (i >= env->prog->len) {
2411 /* This can happen if backtracking reached insn 0
2412 * and there are still reg_mask or stack_mask
2413 * to backtrack.
2414 * It means the backtracking missed the spot where
2415 * particular register was initialized with a constant.
2416 */
2417 verbose(env, "BUG backtracking idx %d\n", i);
2418 WARN_ONCE(1, "verifier backtracking bug");
2419 return -EFAULT;
2420 }
2421 }
2422 st = st->parent;
2423 if (!st)
2424 break;
2425
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002426 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002427 func = st->frame[st->curframe];
2428 bitmap_from_u64(mask, reg_mask);
2429 for_each_set_bit(i, mask, 32) {
2430 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002431 if (reg->type != SCALAR_VALUE) {
2432 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002433 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002434 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002435 if (!reg->precise)
2436 new_marks = true;
2437 reg->precise = true;
2438 }
2439
2440 bitmap_from_u64(mask, stack_mask);
2441 for_each_set_bit(i, mask, 64) {
2442 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002443 /* the sequence of instructions:
2444 * 2: (bf) r3 = r10
2445 * 3: (7b) *(u64 *)(r3 -8) = r0
2446 * 4: (79) r4 = *(u64 *)(r10 -8)
2447 * doesn't contain jmps. It's backtracked
2448 * as a single block.
2449 * During backtracking insn 3 is not recognized as
2450 * stack access, so at the end of backtracking
2451 * stack slot fp-8 is still marked in stack_mask.
2452 * However the parent state may not have accessed
2453 * fp-8 and it's "unallocated" stack space.
2454 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002455 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002456 mark_all_scalars_precise(env, st);
2457 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002458 }
2459
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002460 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2461 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002462 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002463 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002464 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002465 if (reg->type != SCALAR_VALUE) {
2466 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002467 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002468 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002469 if (!reg->precise)
2470 new_marks = true;
2471 reg->precise = true;
2472 }
2473 if (env->log.level & BPF_LOG_LEVEL) {
2474 print_verifier_state(env, func);
2475 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2476 new_marks ? "didn't have" : "already had",
2477 reg_mask, stack_mask);
2478 }
2479
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002480 if (!reg_mask && !stack_mask)
2481 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002482 if (!new_marks)
2483 break;
2484
2485 last_idx = st->last_insn_idx;
2486 first_idx = st->first_insn_idx;
2487 }
2488 return 0;
2489}
2490
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002491static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2492{
2493 return __mark_chain_precision(env, regno, -1);
2494}
2495
2496static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2497{
2498 return __mark_chain_precision(env, -1, spi);
2499}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002500
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002501static bool is_spillable_regtype(enum bpf_reg_type type)
2502{
2503 switch (type) {
2504 case PTR_TO_MAP_VALUE:
2505 case PTR_TO_MAP_VALUE_OR_NULL:
2506 case PTR_TO_STACK:
2507 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002508 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002509 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002510 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002511 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002512 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002513 case PTR_TO_SOCKET:
2514 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002515 case PTR_TO_SOCK_COMMON:
2516 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002517 case PTR_TO_TCP_SOCK:
2518 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002519 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002520 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002521 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002522 case PTR_TO_RDONLY_BUF:
2523 case PTR_TO_RDONLY_BUF_OR_NULL:
2524 case PTR_TO_RDWR_BUF:
2525 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002526 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002527 case PTR_TO_MEM:
2528 case PTR_TO_MEM_OR_NULL:
Yonghong Song69c087b2021-02-26 12:49:25 -08002529 case PTR_TO_FUNC:
2530 case PTR_TO_MAP_KEY:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002531 return true;
2532 default:
2533 return false;
2534 }
2535}
2536
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002537/* Does this register contain a constant zero? */
2538static bool register_is_null(struct bpf_reg_state *reg)
2539{
2540 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2541}
2542
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002543static bool register_is_const(struct bpf_reg_state *reg)
2544{
2545 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2546}
2547
Yonghong Song5689d492020-10-08 18:12:38 -07002548static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2549{
2550 return tnum_is_unknown(reg->var_off) &&
2551 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2552 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2553 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2554 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2555}
2556
2557static bool register_is_bounded(struct bpf_reg_state *reg)
2558{
2559 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2560}
2561
Jann Horn6e7e63c2020-04-17 02:00:06 +02002562static bool __is_pointer_value(bool allow_ptr_leaks,
2563 const struct bpf_reg_state *reg)
2564{
2565 if (allow_ptr_leaks)
2566 return false;
2567
2568 return reg->type != SCALAR_VALUE;
2569}
2570
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002571static void save_register_state(struct bpf_func_state *state,
2572 int spi, struct bpf_reg_state *reg)
2573{
2574 int i;
2575
2576 state->stack[spi].spilled_ptr = *reg;
2577 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2578
2579 for (i = 0; i < BPF_REG_SIZE; i++)
2580 state->stack[spi].slot_type[i] = STACK_SPILL;
2581}
2582
Andrei Matei01f810a2021-02-06 20:10:24 -05002583/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002584 * stack boundary and alignment are checked in check_mem_access()
2585 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002586static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2587 /* stack frame we're writing to */
2588 struct bpf_func_state *state,
2589 int off, int size, int value_regno,
2590 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002591{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002592 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002593 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002594 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002595 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002596
Lorenz Bauerc69431a2021-04-29 14:46:54 +01002597 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002598 if (err)
2599 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002600 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2601 * so it's aligned access and [off, off + size) are within stack limits
2602 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002603 if (!env->allow_ptr_leaks &&
2604 state->stack[spi].slot_type[0] == STACK_SPILL &&
2605 size != BPF_REG_SIZE) {
2606 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2607 return -EACCES;
2608 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002609
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002610 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002611 if (value_regno >= 0)
2612 reg = &cur->regs[value_regno];
Daniel Borkmann2039f262021-07-13 08:18:31 +00002613 if (!env->bypass_spec_v4) {
2614 bool sanitize = reg && is_spillable_regtype(reg->type);
2615
2616 for (i = 0; i < size; i++) {
2617 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2618 sanitize = true;
2619 break;
2620 }
2621 }
2622
2623 if (sanitize)
2624 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2625 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002626
Yonghong Song5689d492020-10-08 18:12:38 -07002627 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002628 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002629 if (dst_reg != BPF_REG_FP) {
2630 /* The backtracking logic can only recognize explicit
2631 * stack slot address like [fp - 8]. Other spill of
Zhen Lei8fb33b62021-05-25 10:56:59 +08002632 * scalar via different register has to be conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002633 * Backtrack from here and mark all registers as precise
2634 * that contributed into 'reg' being a constant.
2635 */
2636 err = mark_chain_precision(env, value_regno);
2637 if (err)
2638 return err;
2639 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002640 save_register_state(state, spi, reg);
2641 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002642 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002643 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002644 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002645 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002646 return -EACCES;
2647 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002648 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002649 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2650 return -EINVAL;
2651 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002652 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002653 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002654 u8 type = STACK_MISC;
2655
Edward Cree679c7822018-08-22 20:02:19 +01002656 /* regular write of data into stack destroys any spilled ptr */
2657 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002658 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2659 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2660 for (i = 0; i < BPF_REG_SIZE; i++)
2661 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002662
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002663 /* only mark the slot as written if all 8 bytes were written
2664 * otherwise read propagation may incorrectly stop too soon
2665 * when stack slots are partially written.
2666 * This heuristic means that read propagation will be
2667 * conservative, since it will add reg_live_read marks
2668 * to stack slots all the way to first state when programs
2669 * writes+reads less than 8 bytes
2670 */
2671 if (size == BPF_REG_SIZE)
2672 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2673
2674 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002675 if (reg && register_is_null(reg)) {
2676 /* backtracking doesn't work for STACK_ZERO yet. */
2677 err = mark_chain_precision(env, value_regno);
2678 if (err)
2679 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002680 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002681 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002682
Jiong Wang0bae2d42018-12-15 03:34:40 -05002683 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002684 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002685 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002686 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002687 }
2688 return 0;
2689}
2690
Andrei Matei01f810a2021-02-06 20:10:24 -05002691/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2692 * known to contain a variable offset.
2693 * This function checks whether the write is permitted and conservatively
2694 * tracks the effects of the write, considering that each stack slot in the
2695 * dynamic range is potentially written to.
2696 *
2697 * 'off' includes 'regno->off'.
2698 * 'value_regno' can be -1, meaning that an unknown value is being written to
2699 * the stack.
2700 *
2701 * Spilled pointers in range are not marked as written because we don't know
2702 * what's going to be actually written. This means that read propagation for
2703 * future reads cannot be terminated by this write.
2704 *
2705 * For privileged programs, uninitialized stack slots are considered
2706 * initialized by this write (even though we don't know exactly what offsets
2707 * are going to be written to). The idea is that we don't want the verifier to
2708 * reject future reads that access slots written to through variable offsets.
2709 */
2710static int check_stack_write_var_off(struct bpf_verifier_env *env,
2711 /* func where register points to */
2712 struct bpf_func_state *state,
2713 int ptr_regno, int off, int size,
2714 int value_regno, int insn_idx)
2715{
2716 struct bpf_func_state *cur; /* state of the current function */
2717 int min_off, max_off;
2718 int i, err;
2719 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2720 bool writing_zero = false;
2721 /* set if the fact that we're writing a zero is used to let any
2722 * stack slots remain STACK_ZERO
2723 */
2724 bool zero_used = false;
2725
2726 cur = env->cur_state->frame[env->cur_state->curframe];
2727 ptr_reg = &cur->regs[ptr_regno];
2728 min_off = ptr_reg->smin_value + off;
2729 max_off = ptr_reg->smax_value + off + size;
2730 if (value_regno >= 0)
2731 value_reg = &cur->regs[value_regno];
2732 if (value_reg && register_is_null(value_reg))
2733 writing_zero = true;
2734
Lorenz Bauerc69431a2021-04-29 14:46:54 +01002735 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
Andrei Matei01f810a2021-02-06 20:10:24 -05002736 if (err)
2737 return err;
2738
2739
2740 /* Variable offset writes destroy any spilled pointers in range. */
2741 for (i = min_off; i < max_off; i++) {
2742 u8 new_type, *stype;
2743 int slot, spi;
2744
2745 slot = -i - 1;
2746 spi = slot / BPF_REG_SIZE;
2747 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2748
2749 if (!env->allow_ptr_leaks
2750 && *stype != NOT_INIT
2751 && *stype != SCALAR_VALUE) {
2752 /* Reject the write if there's are spilled pointers in
2753 * range. If we didn't reject here, the ptr status
2754 * would be erased below (even though not all slots are
2755 * actually overwritten), possibly opening the door to
2756 * leaks.
2757 */
2758 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2759 insn_idx, i);
2760 return -EINVAL;
2761 }
2762
2763 /* Erase all spilled pointers. */
2764 state->stack[spi].spilled_ptr.type = NOT_INIT;
2765
2766 /* Update the slot type. */
2767 new_type = STACK_MISC;
2768 if (writing_zero && *stype == STACK_ZERO) {
2769 new_type = STACK_ZERO;
2770 zero_used = true;
2771 }
2772 /* If the slot is STACK_INVALID, we check whether it's OK to
2773 * pretend that it will be initialized by this write. The slot
2774 * might not actually be written to, and so if we mark it as
2775 * initialized future reads might leak uninitialized memory.
2776 * For privileged programs, we will accept such reads to slots
2777 * that may or may not be written because, if we're reject
2778 * them, the error would be too confusing.
2779 */
2780 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2781 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2782 insn_idx, i);
2783 return -EINVAL;
2784 }
2785 *stype = new_type;
2786 }
2787 if (zero_used) {
2788 /* backtracking doesn't work for STACK_ZERO yet. */
2789 err = mark_chain_precision(env, value_regno);
2790 if (err)
2791 return err;
2792 }
2793 return 0;
2794}
2795
2796/* When register 'dst_regno' is assigned some values from stack[min_off,
2797 * max_off), we set the register's type according to the types of the
2798 * respective stack slots. If all the stack values are known to be zeros, then
2799 * so is the destination reg. Otherwise, the register is considered to be
2800 * SCALAR. This function does not deal with register filling; the caller must
2801 * ensure that all spilled registers in the stack range have been marked as
2802 * read.
2803 */
2804static void mark_reg_stack_read(struct bpf_verifier_env *env,
2805 /* func where src register points to */
2806 struct bpf_func_state *ptr_state,
2807 int min_off, int max_off, int dst_regno)
2808{
2809 struct bpf_verifier_state *vstate = env->cur_state;
2810 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2811 int i, slot, spi;
2812 u8 *stype;
2813 int zeros = 0;
2814
2815 for (i = min_off; i < max_off; i++) {
2816 slot = -i - 1;
2817 spi = slot / BPF_REG_SIZE;
2818 stype = ptr_state->stack[spi].slot_type;
2819 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2820 break;
2821 zeros++;
2822 }
2823 if (zeros == max_off - min_off) {
2824 /* any access_size read into register is zero extended,
2825 * so the whole register == const_zero
2826 */
2827 __mark_reg_const_zero(&state->regs[dst_regno]);
2828 /* backtracking doesn't support STACK_ZERO yet,
2829 * so mark it precise here, so that later
2830 * backtracking can stop here.
2831 * Backtracking may not need this if this register
2832 * doesn't participate in pointer adjustment.
2833 * Forward propagation of precise flag is not
2834 * necessary either. This mark is only to stop
2835 * backtracking. Any register that contributed
2836 * to const 0 was marked precise before spill.
2837 */
2838 state->regs[dst_regno].precise = true;
2839 } else {
2840 /* have read misc data from the stack */
2841 mark_reg_unknown(env, state->regs, dst_regno);
2842 }
2843 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2844}
2845
2846/* Read the stack at 'off' and put the results into the register indicated by
2847 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2848 * spilled reg.
2849 *
2850 * 'dst_regno' can be -1, meaning that the read value is not going to a
2851 * register.
2852 *
2853 * The access is assumed to be within the current stack bounds.
2854 */
2855static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2856 /* func where src register points to */
2857 struct bpf_func_state *reg_state,
2858 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002859{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002860 struct bpf_verifier_state *vstate = env->cur_state;
2861 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002862 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002863 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002864 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002865
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002866 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002867 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002868
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002869 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002870 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002871 if (reg->type != SCALAR_VALUE) {
2872 verbose_linfo(env, env->insn_idx, "; ");
2873 verbose(env, "invalid size of register fill\n");
2874 return -EACCES;
2875 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002876 if (dst_regno >= 0) {
2877 mark_reg_unknown(env, state->regs, dst_regno);
2878 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002879 }
2880 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2881 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002882 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002883 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002884 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002885 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002886 return -EACCES;
2887 }
2888 }
2889
Andrei Matei01f810a2021-02-06 20:10:24 -05002890 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002891 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05002892 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002893 /* mark reg as written since spilled pointer state likely
2894 * has its liveness marks cleared by is_state_visited()
2895 * which resets stack/reg liveness for state transitions
2896 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002897 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002898 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002899 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02002900 * it is acceptable to use this value as a SCALAR_VALUE
2901 * (e.g. for XADD).
2902 * We must not allow unprivileged callers to do that
2903 * with spilled pointers.
2904 */
2905 verbose(env, "leaking pointer from stack off %d\n",
2906 off);
2907 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002908 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002909 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002910 } else {
Andrei Matei01f810a2021-02-06 20:10:24 -05002911 u8 type;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002912
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002913 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002914 type = stype[(slot - i) % BPF_REG_SIZE];
2915 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002916 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05002917 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002918 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002919 verbose(env, "invalid read from stack off %d+%d size %d\n",
2920 off, i, size);
2921 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002922 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002923 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05002924 if (dst_regno >= 0)
2925 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002926 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002927 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002928}
2929
Andrei Matei01f810a2021-02-06 20:10:24 -05002930enum stack_access_src {
2931 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2932 ACCESS_HELPER = 2, /* the access is performed by a helper */
2933};
2934
2935static int check_stack_range_initialized(struct bpf_verifier_env *env,
2936 int regno, int off, int access_size,
2937 bool zero_size_allowed,
2938 enum stack_access_src type,
2939 struct bpf_call_arg_meta *meta);
2940
2941static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002942{
Andrei Matei01f810a2021-02-06 20:10:24 -05002943 return cur_regs(env) + regno;
2944}
2945
2946/* Read the stack at 'ptr_regno + off' and put the result into the register
2947 * 'dst_regno'.
2948 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2949 * but not its variable offset.
2950 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2951 *
2952 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2953 * filling registers (i.e. reads of spilled register cannot be detected when
2954 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2955 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2956 * offset; for a fixed offset check_stack_read_fixed_off should be used
2957 * instead.
2958 */
2959static int check_stack_read_var_off(struct bpf_verifier_env *env,
2960 int ptr_regno, int off, int size, int dst_regno)
2961{
2962 /* The state of the source register. */
2963 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2964 struct bpf_func_state *ptr_state = func(env, reg);
2965 int err;
2966 int min_off, max_off;
2967
2968 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002969 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002970 err = check_stack_range_initialized(env, ptr_regno, off, size,
2971 false, ACCESS_DIRECT, NULL);
2972 if (err)
2973 return err;
2974
2975 min_off = reg->smin_value + off;
2976 max_off = reg->smax_value + off;
2977 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2978 return 0;
2979}
2980
2981/* check_stack_read dispatches to check_stack_read_fixed_off or
2982 * check_stack_read_var_off.
2983 *
2984 * The caller must ensure that the offset falls within the allocated stack
2985 * bounds.
2986 *
2987 * 'dst_regno' is a register which will receive the value from the stack. It
2988 * can be -1, meaning that the read value is not going to a register.
2989 */
2990static int check_stack_read(struct bpf_verifier_env *env,
2991 int ptr_regno, int off, int size,
2992 int dst_regno)
2993{
2994 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2995 struct bpf_func_state *state = func(env, reg);
2996 int err;
2997 /* Some accesses are only permitted with a static offset. */
2998 bool var_off = !tnum_is_const(reg->var_off);
2999
3000 /* The offset is required to be static when reads don't go to a
3001 * register, in order to not leak pointers (see
3002 * check_stack_read_fixed_off).
3003 */
3004 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003005 char tn_buf[48];
3006
3007 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05003008 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 +01003009 tn_buf, off, size);
3010 return -EACCES;
3011 }
Andrei Matei01f810a2021-02-06 20:10:24 -05003012 /* Variable offset is prohibited for unprivileged mode for simplicity
3013 * since it requires corresponding support in Spectre masking for stack
3014 * ALU. See also retrieve_ptr_limit().
3015 */
3016 if (!env->bypass_spec_v1 && var_off) {
3017 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003018
Andrei Matei01f810a2021-02-06 20:10:24 -05003019 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3020 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3021 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003022 return -EACCES;
3023 }
3024
Andrei Matei01f810a2021-02-06 20:10:24 -05003025 if (!var_off) {
3026 off += reg->var_off.value;
3027 err = check_stack_read_fixed_off(env, state, off, size,
3028 dst_regno);
3029 } else {
3030 /* Variable offset stack reads need more conservative handling
3031 * than fixed offset ones. Note that dst_regno >= 0 on this
3032 * branch.
3033 */
3034 err = check_stack_read_var_off(env, ptr_regno, off, size,
3035 dst_regno);
3036 }
3037 return err;
3038}
3039
3040
3041/* check_stack_write dispatches to check_stack_write_fixed_off or
3042 * check_stack_write_var_off.
3043 *
3044 * 'ptr_regno' is the register used as a pointer into the stack.
3045 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3046 * 'value_regno' is the register whose value we're writing to the stack. It can
3047 * be -1, meaning that we're not writing from a register.
3048 *
3049 * The caller must ensure that the offset falls within the maximum stack size.
3050 */
3051static int check_stack_write(struct bpf_verifier_env *env,
3052 int ptr_regno, int off, int size,
3053 int value_regno, int insn_idx)
3054{
3055 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3056 struct bpf_func_state *state = func(env, reg);
3057 int err;
3058
3059 if (tnum_is_const(reg->var_off)) {
3060 off += reg->var_off.value;
3061 err = check_stack_write_fixed_off(env, state, off, size,
3062 value_regno, insn_idx);
3063 } else {
3064 /* Variable offset stack reads need more conservative handling
3065 * than fixed offset ones.
3066 */
3067 err = check_stack_write_var_off(env, state,
3068 ptr_regno, off, size,
3069 value_regno, insn_idx);
3070 }
3071 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003072}
3073
Daniel Borkmann591fe982019-04-09 23:20:05 +02003074static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3075 int off, int size, enum bpf_access_type type)
3076{
3077 struct bpf_reg_state *regs = cur_regs(env);
3078 struct bpf_map *map = regs[regno].map_ptr;
3079 u32 cap = bpf_map_flags_to_cap(map);
3080
3081 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3082 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3083 map->value_size, off, size);
3084 return -EACCES;
3085 }
3086
3087 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3088 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3089 map->value_size, off, size);
3090 return -EACCES;
3091 }
3092
3093 return 0;
3094}
3095
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003096/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3097static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3098 int off, int size, u32 mem_size,
3099 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003100{
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003101 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3102 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003103
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003104 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3105 return 0;
3106
3107 reg = &cur_regs(env)[regno];
3108 switch (reg->type) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003109 case PTR_TO_MAP_KEY:
3110 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3111 mem_size, off, size);
3112 break;
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003113 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003114 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003115 mem_size, off, size);
3116 break;
3117 case PTR_TO_PACKET:
3118 case PTR_TO_PACKET_META:
3119 case PTR_TO_PACKET_END:
3120 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3121 off, size, regno, reg->id, off, mem_size);
3122 break;
3123 case PTR_TO_MEM:
3124 default:
3125 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3126 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003127 }
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003128
3129 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003130}
3131
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003132/* check read/write into a memory region with possible variable offset */
3133static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3134 int off, int size, u32 mem_size,
3135 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003136{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003137 struct bpf_verifier_state *vstate = env->cur_state;
3138 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003139 struct bpf_reg_state *reg = &state->regs[regno];
3140 int err;
3141
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003142 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01003143 * need to try adding each of min_value and max_value to off
3144 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003145 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07003146 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003147 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01003148
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003149 /* The minimum value is only important with signed
3150 * comparisons where we can't assume the floor of a
3151 * value is 0. If we are using signed variables for our
3152 * index'es we need to make sure that whatever we use
3153 * will have a set floor within our range.
3154 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01003155 if (reg->smin_value < 0 &&
3156 (reg->smin_value == S64_MIN ||
3157 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3158 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003159 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 -08003160 regno);
3161 return -EACCES;
3162 }
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003163 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3164 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003165 if (err) {
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003166 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003167 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003168 return err;
3169 }
3170
Edward Creeb03c9f92017-08-07 15:26:36 +01003171 /* If we haven't set a max value then we need to bail since we can't be
3172 * sure we won't do bad things.
3173 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003174 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003175 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003176 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003177 regno);
3178 return -EACCES;
3179 }
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003180 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3181 mem_size, zero_size_allowed);
3182 if (err) {
3183 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003184 regno);
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003185 return err;
3186 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003187
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003188 return 0;
3189}
3190
3191/* check read/write into a map element with possible variable offset */
3192static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3193 int off, int size, bool zero_size_allowed)
3194{
3195 struct bpf_verifier_state *vstate = env->cur_state;
3196 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3197 struct bpf_reg_state *reg = &state->regs[regno];
3198 struct bpf_map *map = reg->map_ptr;
3199 int err;
3200
3201 err = check_mem_region_access(env, regno, off, size, map->value_size,
3202 zero_size_allowed);
3203 if (err)
3204 return err;
3205
3206 if (map_value_has_spin_lock(map)) {
3207 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003208
3209 /* if any part of struct bpf_spin_lock can be touched by
3210 * load/store reject this program.
3211 * To check that [x1, x2) overlaps with [y1, y2)
3212 * it is sufficient to check x1 < y2 && y1 < x2.
3213 */
3214 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3215 lock < reg->umax_value + off + size) {
3216 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3217 return -EACCES;
3218 }
3219 }
Edward Creef1174f72017-08-07 15:26:19 +01003220 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003221}
3222
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003223#define MAX_PACKET_OFF 0xffff
3224
Udip Pant7e407812020-08-25 16:20:00 -07003225static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3226{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02003227 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07003228}
3229
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003230static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003231 const struct bpf_call_arg_meta *meta,
3232 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003233{
Udip Pant7e407812020-08-25 16:20:00 -07003234 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3235
3236 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003237 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003238 case BPF_PROG_TYPE_LWT_IN:
3239 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003240 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003241 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003242 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003243 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003244 if (t == BPF_WRITE)
3245 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003246 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003247
3248 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003249 case BPF_PROG_TYPE_SCHED_CLS:
3250 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003251 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003252 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003253 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003254 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003255 if (meta)
3256 return meta->pkt_access;
3257
3258 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003259 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003260
3261 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3262 if (t == BPF_WRITE)
3263 env->seen_direct_write = true;
3264
3265 return true;
3266
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003267 default:
3268 return false;
3269 }
3270}
3271
Edward Creef1174f72017-08-07 15:26:19 +01003272static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003273 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003274{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003275 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003276 struct bpf_reg_state *reg = &regs[regno];
3277 int err;
3278
3279 /* We may have added a variable offset to the packet pointer; but any
3280 * reg->range we have comes after that. We are only checking the fixed
3281 * offset.
3282 */
3283
3284 /* We don't allow negative numbers, because we aren't tracking enough
3285 * detail to prove they're safe.
3286 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003287 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003288 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 +01003289 regno);
3290 return -EACCES;
3291 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003292
3293 err = reg->range < 0 ? -EINVAL :
3294 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003295 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003296 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003297 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003298 return err;
3299 }
Jiong Wange6478152018-11-08 04:08:42 -05003300
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003301 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003302 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3303 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f44362020-05-29 00:54:20 -07003304 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003305 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3306 */
3307 env->prog->aux->max_pkt_offset =
3308 max_t(u32, env->prog->aux->max_pkt_offset,
3309 off + reg->umax_value + size - 1);
3310
Edward Creef1174f72017-08-07 15:26:19 +01003311 return err;
3312}
3313
3314/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003315static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003316 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003317 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003318{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003319 struct bpf_insn_access_aux info = {
3320 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003321 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003322 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003323
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003324 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003325 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003326 /* A non zero info.ctx_field_size indicates that this field is a
3327 * candidate for later verifier transformation to load the whole
3328 * field and then apply a mask when accessed with a narrower
3329 * access than actual ctx access size. A zero info.ctx_field_size
3330 * will only allow for whole field access and rejects any other
3331 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003332 */
Yonghong Song23994632017-06-22 15:07:39 -07003333 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003334
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003335 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3336 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003337 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003338 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003339 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003340 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003341 /* remember the offset of last byte accessed in ctx */
3342 if (env->prog->aux->max_ctx_offset < off + size)
3343 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003344 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003345 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003346
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003347 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003348 return -EACCES;
3349}
3350
Petar Penkovd58e4682018-09-14 07:46:18 -07003351static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3352 int size)
3353{
3354 if (size < 0 || off < 0 ||
3355 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3356 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3357 off, size);
3358 return -EACCES;
3359 }
3360 return 0;
3361}
3362
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003363static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3364 u32 regno, int off, int size,
3365 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003366{
3367 struct bpf_reg_state *regs = cur_regs(env);
3368 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003369 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003370 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003371
3372 if (reg->smin_value < 0) {
3373 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3374 regno);
3375 return -EACCES;
3376 }
3377
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003378 switch (reg->type) {
3379 case PTR_TO_SOCK_COMMON:
3380 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3381 break;
3382 case PTR_TO_SOCKET:
3383 valid = bpf_sock_is_valid_access(off, size, t, &info);
3384 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003385 case PTR_TO_TCP_SOCK:
3386 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3387 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003388 case PTR_TO_XDP_SOCK:
3389 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3390 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003391 default:
3392 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003393 }
3394
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003395
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003396 if (valid) {
3397 env->insn_aux_data[insn_idx].ctx_field_size =
3398 info.ctx_field_size;
3399 return 0;
3400 }
3401
3402 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3403 regno, reg_type_str[reg->type], off, size);
3404
3405 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003406}
3407
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003408static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3409{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003410 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003411}
3412
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003413static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3414{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003415 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003416
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003417 return reg->type == PTR_TO_CTX;
3418}
3419
3420static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3421{
3422 const struct bpf_reg_state *reg = reg_state(env, regno);
3423
3424 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003425}
3426
Daniel Borkmannca369602018-02-23 22:29:05 +01003427static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3428{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003429 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003430
3431 return type_is_pkt_pointer(reg->type);
3432}
3433
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003434static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3435{
3436 const struct bpf_reg_state *reg = reg_state(env, regno);
3437
3438 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3439 return reg->type == PTR_TO_FLOW_KEYS;
3440}
3441
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003442static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3443 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003444 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003445{
Edward Creef1174f72017-08-07 15:26:19 +01003446 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003447 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003448
3449 /* Byte size accesses are always allowed. */
3450 if (!strict || size == 1)
3451 return 0;
3452
David S. Millere4eda882017-05-22 12:27:07 -04003453 /* For platforms that do not have a Kconfig enabling
3454 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3455 * NET_IP_ALIGN is universally set to '2'. And on platforms
3456 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3457 * to this code only in strict mode where we want to emulate
3458 * the NET_IP_ALIGN==2 checking. Therefore use an
3459 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003460 */
David S. Millere4eda882017-05-22 12:27:07 -04003461 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003462
3463 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3464 if (!tnum_is_aligned(reg_off, size)) {
3465 char tn_buf[48];
3466
3467 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003468 verbose(env,
3469 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003470 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003471 return -EACCES;
3472 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003473
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003474 return 0;
3475}
3476
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003477static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3478 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003479 const char *pointer_desc,
3480 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003481{
Edward Creef1174f72017-08-07 15:26:19 +01003482 struct tnum reg_off;
3483
3484 /* Byte size accesses are always allowed. */
3485 if (!strict || size == 1)
3486 return 0;
3487
3488 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3489 if (!tnum_is_aligned(reg_off, size)) {
3490 char tn_buf[48];
3491
3492 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003493 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003494 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003495 return -EACCES;
3496 }
3497
3498 return 0;
3499}
3500
David S. Millere07b98d2017-05-10 11:38:07 -07003501static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003502 const struct bpf_reg_state *reg, int off,
3503 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003504{
Daniel Borkmannca369602018-02-23 22:29:05 +01003505 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003506 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003507
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003508 switch (reg->type) {
3509 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003510 case PTR_TO_PACKET_META:
3511 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3512 * right in front, treat it the very same way.
3513 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003514 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003515 case PTR_TO_FLOW_KEYS:
3516 pointer_desc = "flow keys ";
3517 break;
Yonghong Song69c087b2021-02-26 12:49:25 -08003518 case PTR_TO_MAP_KEY:
3519 pointer_desc = "key ";
3520 break;
Edward Creef1174f72017-08-07 15:26:19 +01003521 case PTR_TO_MAP_VALUE:
3522 pointer_desc = "value ";
3523 break;
3524 case PTR_TO_CTX:
3525 pointer_desc = "context ";
3526 break;
3527 case PTR_TO_STACK:
3528 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003529 /* The stack spill tracking logic in check_stack_write_fixed_off()
3530 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003531 * aligned.
3532 */
3533 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003534 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003535 case PTR_TO_SOCKET:
3536 pointer_desc = "sock ";
3537 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003538 case PTR_TO_SOCK_COMMON:
3539 pointer_desc = "sock_common ";
3540 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003541 case PTR_TO_TCP_SOCK:
3542 pointer_desc = "tcp_sock ";
3543 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003544 case PTR_TO_XDP_SOCK:
3545 pointer_desc = "xdp_sock ";
3546 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003547 default:
Edward Creef1174f72017-08-07 15:26:19 +01003548 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003549 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003550 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3551 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003552}
3553
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003554static int update_stack_depth(struct bpf_verifier_env *env,
3555 const struct bpf_func_state *func,
3556 int off)
3557{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003558 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003559
3560 if (stack >= -off)
3561 return 0;
3562
3563 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003564 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003565 return 0;
3566}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003567
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003568/* starting from main bpf function walk all instructions of the function
3569 * and recursively walk all callees that given function can call.
3570 * Ignore jump and exit insns.
3571 * Since recursion is prevented by check_cfg() this algorithm
3572 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3573 */
3574static int check_max_stack_depth(struct bpf_verifier_env *env)
3575{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003576 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3577 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003578 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003579 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003580 int ret_insn[MAX_CALL_FRAMES];
3581 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003582 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003583
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003584process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003585 /* protect against potential stack overflow that might happen when
3586 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3587 * depth for such case down to 256 so that the worst case scenario
3588 * would result in 8k stack size (32 which is tailcall limit * 256 =
3589 * 8k).
3590 *
3591 * To get the idea what might happen, see an example:
3592 * func1 -> sub rsp, 128
3593 * subfunc1 -> sub rsp, 256
3594 * tailcall1 -> add rsp, 256
3595 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3596 * subfunc2 -> sub rsp, 64
3597 * subfunc22 -> sub rsp, 128
3598 * tailcall2 -> add rsp, 128
3599 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3600 *
3601 * tailcall will unwind the current stack frame but it will not get rid
3602 * of caller's stack as shown on the example above.
3603 */
3604 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3605 verbose(env,
3606 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3607 depth);
3608 return -EACCES;
3609 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003610 /* round up to 32-bytes, since this is granularity
3611 * of interpreter stack size
3612 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003613 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003614 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003615 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003616 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003617 return -EACCES;
3618 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003619continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003620 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003621 for (; i < subprog_end; i++) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003622 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003623 continue;
3624 /* remember insn and function to return to */
3625 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003626 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003627
3628 /* find the callee */
3629 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003630 idx = find_subprog(env, i);
3631 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003632 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3633 i);
3634 return -EFAULT;
3635 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003636
3637 if (subprog[idx].has_tail_call)
3638 tail_call_reachable = true;
3639
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003640 frame++;
3641 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003642 verbose(env, "the call stack of %d frames is too deep !\n",
3643 frame);
3644 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003645 }
3646 goto process_func;
3647 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003648 /* if tail call got detected across bpf2bpf calls then mark each of the
3649 * currently present subprog frames as tail call reachable subprogs;
3650 * this info will be utilized by JIT so that we will be preserving the
3651 * tail call counter throughout bpf2bpf calls combined with tailcalls
3652 */
3653 if (tail_call_reachable)
3654 for (j = 0; j < frame; j++)
3655 subprog[ret_prog[j]].tail_call_reachable = true;
Daniel Borkmann5dd0a6b2021-07-12 22:57:35 +02003656 if (subprog[0].tail_call_reachable)
3657 env->prog->aux->tail_call_reachable = true;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003658
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003659 /* end of for() loop means the last insn of the 'subprog'
3660 * was reached. Doesn't matter whether it was JA or EXIT
3661 */
3662 if (frame == 0)
3663 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003664 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003665 frame--;
3666 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003667 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003668 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003669}
3670
David S. Miller19d28fb2018-01-11 21:27:54 -05003671#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003672static int get_callee_stack_depth(struct bpf_verifier_env *env,
3673 const struct bpf_insn *insn, int idx)
3674{
3675 int start = idx + insn->imm + 1, subprog;
3676
3677 subprog = find_subprog(env, start);
3678 if (subprog < 0) {
3679 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3680 start);
3681 return -EFAULT;
3682 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003683 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003684}
David S. Miller19d28fb2018-01-11 21:27:54 -05003685#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003686
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003687int check_ctx_reg(struct bpf_verifier_env *env,
3688 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003689{
3690 /* Access to ctx or passing it to a helper is only allowed in
3691 * its original, unmodified form.
3692 */
3693
3694 if (reg->off) {
3695 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3696 regno, reg->off);
3697 return -EACCES;
3698 }
3699
3700 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3701 char tn_buf[48];
3702
3703 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3704 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3705 return -EACCES;
3706 }
3707
3708 return 0;
3709}
3710
Yonghong Songafbf21d2020-07-23 11:41:11 -07003711static int __check_buffer_access(struct bpf_verifier_env *env,
3712 const char *buf_info,
3713 const struct bpf_reg_state *reg,
3714 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003715{
3716 if (off < 0) {
3717 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003718 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003719 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003720 return -EACCES;
3721 }
3722 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3723 char tn_buf[48];
3724
3725 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3726 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003727 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003728 regno, off, tn_buf);
3729 return -EACCES;
3730 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003731
3732 return 0;
3733}
3734
3735static int check_tp_buffer_access(struct bpf_verifier_env *env,
3736 const struct bpf_reg_state *reg,
3737 int regno, int off, int size)
3738{
3739 int err;
3740
3741 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3742 if (err)
3743 return err;
3744
Matt Mullins9df1c282019-04-26 11:49:47 -07003745 if (off + size > env->prog->aux->max_tp_access)
3746 env->prog->aux->max_tp_access = off + size;
3747
3748 return 0;
3749}
3750
Yonghong Songafbf21d2020-07-23 11:41:11 -07003751static int check_buffer_access(struct bpf_verifier_env *env,
3752 const struct bpf_reg_state *reg,
3753 int regno, int off, int size,
3754 bool zero_size_allowed,
3755 const char *buf_info,
3756 u32 *max_access)
3757{
3758 int err;
3759
3760 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3761 if (err)
3762 return err;
3763
3764 if (off + size > *max_access)
3765 *max_access = off + size;
3766
3767 return 0;
3768}
3769
John Fastabend3f50f132020-03-30 14:36:39 -07003770/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3771static void zext_32_to_64(struct bpf_reg_state *reg)
3772{
3773 reg->var_off = tnum_subreg(reg->var_off);
3774 __reg_assign_32_into_64(reg);
3775}
Matt Mullins9df1c282019-04-26 11:49:47 -07003776
Jann Horn0c17d1d2017-12-18 20:11:55 -08003777/* truncate register to smaller size (in bytes)
3778 * must be called with size < BPF_REG_SIZE
3779 */
3780static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3781{
3782 u64 mask;
3783
3784 /* clear high bits in bit representation */
3785 reg->var_off = tnum_cast(reg->var_off, size);
3786
3787 /* fix arithmetic bounds */
3788 mask = ((u64)1 << (size * 8)) - 1;
3789 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3790 reg->umin_value &= mask;
3791 reg->umax_value &= mask;
3792 } else {
3793 reg->umin_value = 0;
3794 reg->umax_value = mask;
3795 }
3796 reg->smin_value = reg->umin_value;
3797 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003798
3799 /* If size is smaller than 32bit register the 32bit register
3800 * values are also truncated so we push 64-bit bounds into
3801 * 32-bit bounds. Above were truncated < 32-bits already.
3802 */
3803 if (size >= 4)
3804 return;
3805 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003806}
3807
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003808static bool bpf_map_is_rdonly(const struct bpf_map *map)
3809{
3810 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3811}
3812
3813static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3814{
3815 void *ptr;
3816 u64 addr;
3817 int err;
3818
3819 err = map->ops->map_direct_value_addr(map, &addr, off);
3820 if (err)
3821 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003822 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003823
3824 switch (size) {
3825 case sizeof(u8):
3826 *val = (u64)*(u8 *)ptr;
3827 break;
3828 case sizeof(u16):
3829 *val = (u64)*(u16 *)ptr;
3830 break;
3831 case sizeof(u32):
3832 *val = (u64)*(u32 *)ptr;
3833 break;
3834 case sizeof(u64):
3835 *val = *(u64 *)ptr;
3836 break;
3837 default:
3838 return -EINVAL;
3839 }
3840 return 0;
3841}
3842
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003843static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3844 struct bpf_reg_state *regs,
3845 int regno, int off, int size,
3846 enum bpf_access_type atype,
3847 int value_regno)
3848{
3849 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003850 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3851 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003852 u32 btf_id;
3853 int ret;
3854
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003855 if (off < 0) {
3856 verbose(env,
3857 "R%d is ptr_%s invalid negative access: off=%d\n",
3858 regno, tname, off);
3859 return -EACCES;
3860 }
3861 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3862 char tn_buf[48];
3863
3864 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3865 verbose(env,
3866 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3867 regno, tname, off, tn_buf);
3868 return -EACCES;
3869 }
3870
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003871 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003872 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3873 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003874 } else {
3875 if (atype != BPF_READ) {
3876 verbose(env, "only read is supported\n");
3877 return -EACCES;
3878 }
3879
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003880 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3881 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003882 }
3883
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003884 if (ret < 0)
3885 return ret;
3886
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003887 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003888 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003889
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003890 return 0;
3891}
3892
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003893static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3894 struct bpf_reg_state *regs,
3895 int regno, int off, int size,
3896 enum bpf_access_type atype,
3897 int value_regno)
3898{
3899 struct bpf_reg_state *reg = regs + regno;
3900 struct bpf_map *map = reg->map_ptr;
3901 const struct btf_type *t;
3902 const char *tname;
3903 u32 btf_id;
3904 int ret;
3905
3906 if (!btf_vmlinux) {
3907 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3908 return -ENOTSUPP;
3909 }
3910
3911 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3912 verbose(env, "map_ptr access not supported for map type %d\n",
3913 map->map_type);
3914 return -ENOTSUPP;
3915 }
3916
3917 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3918 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3919
3920 if (!env->allow_ptr_to_map_access) {
3921 verbose(env,
3922 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3923 tname);
3924 return -EPERM;
3925 }
3926
3927 if (off < 0) {
3928 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3929 regno, tname, off);
3930 return -EACCES;
3931 }
3932
3933 if (atype != BPF_READ) {
3934 verbose(env, "only read from %s is supported\n", tname);
3935 return -EACCES;
3936 }
3937
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003938 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003939 if (ret < 0)
3940 return ret;
3941
3942 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003943 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003944
3945 return 0;
3946}
3947
Andrei Matei01f810a2021-02-06 20:10:24 -05003948/* Check that the stack access at the given offset is within bounds. The
3949 * maximum valid offset is -1.
3950 *
3951 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3952 * -state->allocated_stack for reads.
3953 */
3954static int check_stack_slot_within_bounds(int off,
3955 struct bpf_func_state *state,
3956 enum bpf_access_type t)
3957{
3958 int min_valid_off;
3959
3960 if (t == BPF_WRITE)
3961 min_valid_off = -MAX_BPF_STACK;
3962 else
3963 min_valid_off = -state->allocated_stack;
3964
3965 if (off < min_valid_off || off > -1)
3966 return -EACCES;
3967 return 0;
3968}
3969
3970/* Check that the stack access at 'regno + off' falls within the maximum stack
3971 * bounds.
3972 *
3973 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3974 */
3975static int check_stack_access_within_bounds(
3976 struct bpf_verifier_env *env,
3977 int regno, int off, int access_size,
3978 enum stack_access_src src, enum bpf_access_type type)
3979{
3980 struct bpf_reg_state *regs = cur_regs(env);
3981 struct bpf_reg_state *reg = regs + regno;
3982 struct bpf_func_state *state = func(env, reg);
3983 int min_off, max_off;
3984 int err;
3985 char *err_extra;
3986
3987 if (src == ACCESS_HELPER)
3988 /* We don't know if helpers are reading or writing (or both). */
3989 err_extra = " indirect access to";
3990 else if (type == BPF_READ)
3991 err_extra = " read from";
3992 else
3993 err_extra = " write to";
3994
3995 if (tnum_is_const(reg->var_off)) {
3996 min_off = reg->var_off.value + off;
3997 if (access_size > 0)
3998 max_off = min_off + access_size - 1;
3999 else
4000 max_off = min_off;
4001 } else {
4002 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4003 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4004 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4005 err_extra, regno);
4006 return -EACCES;
4007 }
4008 min_off = reg->smin_value + off;
4009 if (access_size > 0)
4010 max_off = reg->smax_value + off + access_size - 1;
4011 else
4012 max_off = min_off;
4013 }
4014
4015 err = check_stack_slot_within_bounds(min_off, state, type);
4016 if (!err)
4017 err = check_stack_slot_within_bounds(max_off, state, type);
4018
4019 if (err) {
4020 if (tnum_is_const(reg->var_off)) {
4021 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4022 err_extra, regno, off, access_size);
4023 } else {
4024 char tn_buf[48];
4025
4026 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4027 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4028 err_extra, regno, tn_buf, access_size);
4029 }
4030 }
4031 return err;
4032}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004033
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004034/* check whether memory at (regno + off) is accessible for t = (read | write)
4035 * if t==write, value_regno is a register which value is stored into memory
4036 * if t==read, value_regno is a register which will receive the value from memory
4037 * if t==write && value_regno==-1, some unknown value is stored into memory
4038 * if t==read && value_regno==-1, don't care what we read from memory
4039 */
Daniel Borkmannca369602018-02-23 22:29:05 +01004040static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4041 int off, int bpf_size, enum bpf_access_type t,
4042 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004043{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004044 struct bpf_reg_state *regs = cur_regs(env);
4045 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004046 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004047 int size, err = 0;
4048
4049 size = bpf_size_to_bytes(bpf_size);
4050 if (size < 0)
4051 return size;
4052
Edward Creef1174f72017-08-07 15:26:19 +01004053 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01004054 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004055 if (err)
4056 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004057
Edward Creef1174f72017-08-07 15:26:19 +01004058 /* for access checks, reg->off is just part of off */
4059 off += reg->off;
4060
Yonghong Song69c087b2021-02-26 12:49:25 -08004061 if (reg->type == PTR_TO_MAP_KEY) {
4062 if (t == BPF_WRITE) {
4063 verbose(env, "write to change key R%d not allowed\n", regno);
4064 return -EACCES;
4065 }
4066
4067 err = check_mem_region_access(env, regno, off, size,
4068 reg->map_ptr->key_size, false);
4069 if (err)
4070 return err;
4071 if (value_regno >= 0)
4072 mark_reg_unknown(env, regs, value_regno);
4073 } else if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004074 if (t == BPF_WRITE && value_regno >= 0 &&
4075 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004076 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004077 return -EACCES;
4078 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02004079 err = check_map_access_type(env, regno, off, size, t);
4080 if (err)
4081 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004082 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004083 if (!err && t == BPF_READ && value_regno >= 0) {
4084 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004085
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004086 /* if map is read-only, track its contents as scalars */
4087 if (tnum_is_const(reg->var_off) &&
4088 bpf_map_is_rdonly(map) &&
4089 map->ops->map_direct_value_addr) {
4090 int map_off = off + reg->var_off.value;
4091 u64 val = 0;
4092
4093 err = bpf_map_direct_read(map, map_off, size,
4094 &val);
4095 if (err)
4096 return err;
4097
4098 regs[value_regno].type = SCALAR_VALUE;
4099 __mark_reg_known(&regs[value_regno], val);
4100 } else {
4101 mark_reg_unknown(env, regs, value_regno);
4102 }
4103 }
Andrii Nakryiko457f44362020-05-29 00:54:20 -07004104 } else if (reg->type == PTR_TO_MEM) {
4105 if (t == BPF_WRITE && value_regno >= 0 &&
4106 is_pointer_value(env, value_regno)) {
4107 verbose(env, "R%d leaks addr into mem\n", value_regno);
4108 return -EACCES;
4109 }
4110 err = check_mem_region_access(env, regno, off, size,
4111 reg->mem_size, false);
4112 if (!err && t == BPF_READ && value_regno >= 0)
4113 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07004114 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01004115 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004116 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004117 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07004118
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004119 if (t == BPF_WRITE && value_regno >= 0 &&
4120 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004121 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004122 return -EACCES;
4123 }
Edward Creef1174f72017-08-07 15:26:19 +01004124
Daniel Borkmann58990d12018-06-07 17:40:03 +02004125 err = check_ctx_reg(env, reg, regno);
4126 if (err < 0)
4127 return err;
4128
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004129 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004130 if (err)
4131 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004132 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004133 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004134 * PTR_TO_PACKET[_META,_END]. In the latter
4135 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01004136 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004137 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004138 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004139 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004140 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004141 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004142 if (reg_type_may_be_null(reg_type))
4143 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01004144 /* A load of ctx field could have different
4145 * actual load size with the one encoded in the
4146 * insn. When the dst is PTR, it is for sure not
4147 * a sub-register.
4148 */
4149 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07004150 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004151 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4152 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004153 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004154 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004155 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004156 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004157 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004158
Edward Creef1174f72017-08-07 15:26:19 +01004159 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004160 /* Basic bounds checks. */
4161 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01004162 if (err)
4163 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004164
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004165 state = func(env, reg);
4166 err = update_stack_depth(env, state, off);
4167 if (err)
4168 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004169
Andrei Matei01f810a2021-02-06 20:10:24 -05004170 if (t == BPF_READ)
4171 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004172 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05004173 else
4174 err = check_stack_write(env, regno, off, size,
4175 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004176 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004177 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004178 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004179 return -EACCES;
4180 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004181 if (t == BPF_WRITE && value_regno >= 0 &&
4182 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004183 verbose(env, "R%d leaks addr into packet\n",
4184 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004185 return -EACCES;
4186 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08004187 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004188 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004189 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07004190 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4191 if (t == BPF_WRITE && value_regno >= 0 &&
4192 is_pointer_value(env, value_regno)) {
4193 verbose(env, "R%d leaks addr into flow keys\n",
4194 value_regno);
4195 return -EACCES;
4196 }
4197
4198 err = check_flow_keys_access(env, off, size);
4199 if (!err && t == BPF_READ && value_regno >= 0)
4200 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004201 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07004202 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004203 verbose(env, "R%d cannot write into %s\n",
4204 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07004205 return -EACCES;
4206 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08004207 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07004208 if (!err && value_regno >= 0)
4209 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07004210 } else if (reg->type == PTR_TO_TP_BUFFER) {
4211 err = check_tp_buffer_access(env, reg, regno, off, size);
4212 if (!err && t == BPF_READ && value_regno >= 0)
4213 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004214 } else if (reg->type == PTR_TO_BTF_ID) {
4215 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4216 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004217 } else if (reg->type == CONST_PTR_TO_MAP) {
4218 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4219 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004220 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4221 if (t == BPF_WRITE) {
4222 verbose(env, "R%d cannot write into %s\n",
4223 regno, reg_type_str[reg->type]);
4224 return -EACCES;
4225 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004226 err = check_buffer_access(env, reg, regno, off, size, false,
4227 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004228 &env->prog->aux->max_rdonly_access);
4229 if (!err && value_regno >= 0)
4230 mark_reg_unknown(env, regs, value_regno);
4231 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004232 err = check_buffer_access(env, reg, regno, off, size, false,
4233 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004234 &env->prog->aux->max_rdwr_access);
4235 if (!err && t == BPF_READ && value_regno >= 0)
4236 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004237 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004238 verbose(env, "R%d invalid mem access '%s'\n", regno,
4239 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004240 return -EACCES;
4241 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004242
Edward Creef1174f72017-08-07 15:26:19 +01004243 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004244 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004245 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08004246 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004247 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004248 return err;
4249}
4250
Brendan Jackman91c960b2021-01-14 18:17:44 +00004251static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004252{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004253 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004254 int err;
4255
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004256 switch (insn->imm) {
4257 case BPF_ADD:
4258 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004259 case BPF_AND:
4260 case BPF_AND | BPF_FETCH:
4261 case BPF_OR:
4262 case BPF_OR | BPF_FETCH:
4263 case BPF_XOR:
4264 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004265 case BPF_XCHG:
4266 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004267 break;
4268 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004269 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4270 return -EINVAL;
4271 }
4272
4273 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4274 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004275 return -EINVAL;
4276 }
4277
4278 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004279 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004280 if (err)
4281 return err;
4282
4283 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004284 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004285 if (err)
4286 return err;
4287
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004288 if (insn->imm == BPF_CMPXCHG) {
4289 /* Check comparison of R0 with memory location */
4290 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4291 if (err)
4292 return err;
4293 }
4294
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004295 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004296 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004297 return -EACCES;
4298 }
4299
Daniel Borkmannca369602018-02-23 22:29:05 +01004300 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004301 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004302 is_flow_key_reg(env, insn->dst_reg) ||
4303 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004304 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004305 insn->dst_reg,
4306 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004307 return -EACCES;
4308 }
4309
Brendan Jackman37086bf2021-02-02 13:50:02 +00004310 if (insn->imm & BPF_FETCH) {
4311 if (insn->imm == BPF_CMPXCHG)
4312 load_reg = BPF_REG_0;
4313 else
4314 load_reg = insn->src_reg;
4315
4316 /* check and record load of old value */
4317 err = check_reg_arg(env, load_reg, DST_OP);
4318 if (err)
4319 return err;
4320 } else {
4321 /* This instruction accesses a memory location but doesn't
4322 * actually load it into a register.
4323 */
4324 load_reg = -1;
4325 }
4326
Brendan Jackman91c960b2021-01-14 18:17:44 +00004327 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004328 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004329 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004330 if (err)
4331 return err;
4332
Brendan Jackman91c960b2021-01-14 18:17:44 +00004333 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004334 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4335 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4336 if (err)
4337 return err;
4338
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004339 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004340}
4341
Andrei Matei01f810a2021-02-06 20:10:24 -05004342/* When register 'regno' is used to read the stack (either directly or through
4343 * a helper function) make sure that it's within stack boundary and, depending
4344 * on the access type, that all elements of the stack are initialized.
4345 *
4346 * 'off' includes 'regno->off', but not its dynamic part (if any).
4347 *
4348 * All registers that have been spilled on the stack in the slots within the
4349 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004350 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004351static int check_stack_range_initialized(
4352 struct bpf_verifier_env *env, int regno, int off,
4353 int access_size, bool zero_size_allowed,
4354 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004355{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004356 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004357 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004358 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004359 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4360 enum bpf_access_type bounds_check_type;
4361 /* Some accesses can write anything into the stack, others are
4362 * read-only.
4363 */
4364 bool clobber = false;
4365
4366 if (access_size == 0 && !zero_size_allowed) {
4367 verbose(env, "invalid zero-sized read\n");
4368 return -EACCES;
4369 }
4370
4371 if (type == ACCESS_HELPER) {
4372 /* The bounds checks for writes are more permissive than for
4373 * reads. However, if raw_mode is not set, we'll do extra
4374 * checks below.
4375 */
4376 bounds_check_type = BPF_WRITE;
4377 clobber = true;
4378 } else {
4379 bounds_check_type = BPF_READ;
4380 }
4381 err = check_stack_access_within_bounds(env, regno, off, access_size,
4382 type, bounds_check_type);
4383 if (err)
4384 return err;
4385
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004386
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004387 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004388 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004389 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004390 /* Variable offset is prohibited for unprivileged mode for
4391 * simplicity since it requires corresponding support in
4392 * Spectre masking for stack ALU.
4393 * See also retrieve_ptr_limit().
4394 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004395 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004396 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004397
Andrey Ignatov088ec262019-04-03 23:22:39 -07004398 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004399 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4400 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004401 return -EACCES;
4402 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004403 /* Only initialized buffer on stack is allowed to be accessed
4404 * with variable offset. With uninitialized buffer it's hard to
4405 * guarantee that whole memory is marked as initialized on
4406 * helper return since specific bounds are unknown what may
4407 * cause uninitialized stack leaking.
4408 */
4409 if (meta && meta->raw_mode)
4410 meta = NULL;
4411
Andrei Matei01f810a2021-02-06 20:10:24 -05004412 min_off = reg->smin_value + off;
4413 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004414 }
4415
Daniel Borkmann435faee12016-04-13 00:10:51 +02004416 if (meta && meta->raw_mode) {
4417 meta->access_size = access_size;
4418 meta->regno = regno;
4419 return 0;
4420 }
4421
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004422 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004423 u8 *stype;
4424
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004425 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004426 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004427 if (state->allocated_stack <= slot)
4428 goto err;
4429 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4430 if (*stype == STACK_MISC)
4431 goto mark;
4432 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004433 if (clobber) {
4434 /* helper can write anything into the stack */
4435 *stype = STACK_MISC;
4436 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004437 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004438 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004439
4440 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4441 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4442 goto mark;
4443
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004444 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004445 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4446 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004447 if (clobber) {
4448 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4449 for (j = 0; j < BPF_REG_SIZE; j++)
4450 state->stack[spi].slot_type[j] = STACK_MISC;
4451 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004452 goto mark;
4453 }
4454
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004455err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004456 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004457 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4458 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004459 } else {
4460 char tn_buf[48];
4461
4462 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004463 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4464 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004465 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004466 return -EACCES;
4467mark:
4468 /* reading any byte out of 8-byte 'spill_slot' will cause
4469 * the whole slot to be marked as 'read'
4470 */
Edward Cree679c7822018-08-22 20:02:19 +01004471 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004472 state->stack[spi].spilled_ptr.parent,
4473 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004474 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004475 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004476}
4477
Gianluca Borello06c1c042017-01-09 10:19:49 -08004478static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4479 int access_size, bool zero_size_allowed,
4480 struct bpf_call_arg_meta *meta)
4481{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004482 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004483
Edward Creef1174f72017-08-07 15:26:19 +01004484 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004485 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004486 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004487 return check_packet_access(env, regno, reg->off, access_size,
4488 zero_size_allowed);
Yonghong Song69c087b2021-02-26 12:49:25 -08004489 case PTR_TO_MAP_KEY:
4490 return check_mem_region_access(env, regno, reg->off, access_size,
4491 reg->map_ptr->key_size, false);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004492 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004493 if (check_map_access_type(env, regno, reg->off, access_size,
4494 meta && meta->raw_mode ? BPF_WRITE :
4495 BPF_READ))
4496 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004497 return check_map_access(env, regno, reg->off, access_size,
4498 zero_size_allowed);
Andrii Nakryiko457f44362020-05-29 00:54:20 -07004499 case PTR_TO_MEM:
4500 return check_mem_region_access(env, regno, reg->off,
4501 access_size, reg->mem_size,
4502 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004503 case PTR_TO_RDONLY_BUF:
4504 if (meta && meta->raw_mode)
4505 return -EACCES;
4506 return check_buffer_access(env, reg, regno, reg->off,
4507 access_size, zero_size_allowed,
4508 "rdonly",
4509 &env->prog->aux->max_rdonly_access);
4510 case PTR_TO_RDWR_BUF:
4511 return check_buffer_access(env, reg, regno, reg->off,
4512 access_size, zero_size_allowed,
4513 "rdwr",
4514 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004515 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004516 return check_stack_range_initialized(
4517 env,
4518 regno, reg->off, access_size,
4519 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004520 default: /* scalar_value or invalid ptr */
4521 /* Allow zero-byte read from NULL, regardless of pointer type */
4522 if (zero_size_allowed && access_size == 0 &&
4523 register_is_null(reg))
4524 return 0;
4525
4526 verbose(env, "R%d type=%s expected=%s\n", regno,
4527 reg_type_str[reg->type],
4528 reg_type_str[PTR_TO_STACK]);
4529 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004530 }
4531}
4532
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004533int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4534 u32 regno, u32 mem_size)
4535{
4536 if (register_is_null(reg))
4537 return 0;
4538
4539 if (reg_type_may_be_null(reg->type)) {
4540 /* Assuming that the register contains a value check if the memory
4541 * access is safe. Temporarily save and restore the register's state as
4542 * the conversion shouldn't be visible to a caller.
4543 */
4544 const struct bpf_reg_state saved_reg = *reg;
4545 int rv;
4546
4547 mark_ptr_not_null_reg(reg);
4548 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4549 *reg = saved_reg;
4550 return rv;
4551 }
4552
4553 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4554}
4555
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004556/* Implementation details:
4557 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4558 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4559 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4560 * value_or_null->value transition, since the verifier only cares about
4561 * the range of access to valid map value pointer and doesn't care about actual
4562 * address of the map element.
4563 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4564 * reg->id > 0 after value_or_null->value transition. By doing so
4565 * two bpf_map_lookups will be considered two different pointers that
4566 * point to different bpf_spin_locks.
4567 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4568 * dead-locks.
4569 * Since only one bpf_spin_lock is allowed the checks are simpler than
4570 * reg_is_refcounted() logic. The verifier needs to remember only
4571 * one spin_lock instead of array of acquired_refs.
4572 * cur_state->active_spin_lock remembers which map value element got locked
4573 * and clears it after bpf_spin_unlock.
4574 */
4575static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4576 bool is_lock)
4577{
4578 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4579 struct bpf_verifier_state *cur = env->cur_state;
4580 bool is_const = tnum_is_const(reg->var_off);
4581 struct bpf_map *map = reg->map_ptr;
4582 u64 val = reg->var_off.value;
4583
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004584 if (!is_const) {
4585 verbose(env,
4586 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4587 regno);
4588 return -EINVAL;
4589 }
4590 if (!map->btf) {
4591 verbose(env,
4592 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4593 map->name);
4594 return -EINVAL;
4595 }
4596 if (!map_value_has_spin_lock(map)) {
4597 if (map->spin_lock_off == -E2BIG)
4598 verbose(env,
4599 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4600 map->name);
4601 else if (map->spin_lock_off == -ENOENT)
4602 verbose(env,
4603 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4604 map->name);
4605 else
4606 verbose(env,
4607 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4608 map->name);
4609 return -EINVAL;
4610 }
4611 if (map->spin_lock_off != val + reg->off) {
4612 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4613 val + reg->off);
4614 return -EINVAL;
4615 }
4616 if (is_lock) {
4617 if (cur->active_spin_lock) {
4618 verbose(env,
4619 "Locking two bpf_spin_locks are not allowed\n");
4620 return -EINVAL;
4621 }
4622 cur->active_spin_lock = reg->id;
4623 } else {
4624 if (!cur->active_spin_lock) {
4625 verbose(env, "bpf_spin_unlock without taking a lock\n");
4626 return -EINVAL;
4627 }
4628 if (cur->active_spin_lock != reg->id) {
4629 verbose(env, "bpf_spin_unlock of different lock\n");
4630 return -EINVAL;
4631 }
4632 cur->active_spin_lock = 0;
4633 }
4634 return 0;
4635}
4636
Daniel Borkmann90133412018-01-20 01:24:29 +01004637static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4638{
4639 return type == ARG_PTR_TO_MEM ||
4640 type == ARG_PTR_TO_MEM_OR_NULL ||
4641 type == ARG_PTR_TO_UNINIT_MEM;
4642}
4643
4644static bool arg_type_is_mem_size(enum bpf_arg_type type)
4645{
4646 return type == ARG_CONST_SIZE ||
4647 type == ARG_CONST_SIZE_OR_ZERO;
4648}
4649
Andrii Nakryiko457f44362020-05-29 00:54:20 -07004650static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4651{
4652 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4653}
4654
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004655static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4656{
4657 return type == ARG_PTR_TO_INT ||
4658 type == ARG_PTR_TO_LONG;
4659}
4660
4661static int int_ptr_type_to_size(enum bpf_arg_type type)
4662{
4663 if (type == ARG_PTR_TO_INT)
4664 return sizeof(u32);
4665 else if (type == ARG_PTR_TO_LONG)
4666 return sizeof(u64);
4667
4668 return -EINVAL;
4669}
4670
Lorenz Bauer912f4422020-08-21 11:29:46 +01004671static int resolve_map_arg_type(struct bpf_verifier_env *env,
4672 const struct bpf_call_arg_meta *meta,
4673 enum bpf_arg_type *arg_type)
4674{
4675 if (!meta->map_ptr) {
4676 /* kernel subsystem misconfigured verifier */
4677 verbose(env, "invalid map_ptr to access map->type\n");
4678 return -EACCES;
4679 }
4680
4681 switch (meta->map_ptr->map_type) {
4682 case BPF_MAP_TYPE_SOCKMAP:
4683 case BPF_MAP_TYPE_SOCKHASH:
4684 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01004685 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01004686 } else {
4687 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4688 return -EINVAL;
4689 }
4690 break;
4691
4692 default:
4693 break;
4694 }
4695 return 0;
4696}
4697
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004698struct bpf_reg_types {
4699 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004700 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004701};
4702
4703static const struct bpf_reg_types map_key_value_types = {
4704 .types = {
4705 PTR_TO_STACK,
4706 PTR_TO_PACKET,
4707 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004708 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004709 PTR_TO_MAP_VALUE,
4710 },
4711};
4712
4713static const struct bpf_reg_types sock_types = {
4714 .types = {
4715 PTR_TO_SOCK_COMMON,
4716 PTR_TO_SOCKET,
4717 PTR_TO_TCP_SOCK,
4718 PTR_TO_XDP_SOCK,
4719 },
4720};
4721
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004722#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004723static const struct bpf_reg_types btf_id_sock_common_types = {
4724 .types = {
4725 PTR_TO_SOCK_COMMON,
4726 PTR_TO_SOCKET,
4727 PTR_TO_TCP_SOCK,
4728 PTR_TO_XDP_SOCK,
4729 PTR_TO_BTF_ID,
4730 },
4731 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4732};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004733#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004734
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004735static const struct bpf_reg_types mem_types = {
4736 .types = {
4737 PTR_TO_STACK,
4738 PTR_TO_PACKET,
4739 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004740 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004741 PTR_TO_MAP_VALUE,
4742 PTR_TO_MEM,
4743 PTR_TO_RDONLY_BUF,
4744 PTR_TO_RDWR_BUF,
4745 },
4746};
4747
4748static const struct bpf_reg_types int_ptr_types = {
4749 .types = {
4750 PTR_TO_STACK,
4751 PTR_TO_PACKET,
4752 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004753 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004754 PTR_TO_MAP_VALUE,
4755 },
4756};
4757
4758static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4759static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4760static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4761static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4762static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4763static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4764static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004765static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Yonghong Song69c087b2021-02-26 12:49:25 -08004766static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4767static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
Florent Revestfff13c42021-04-19 17:52:39 +02004768static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004769
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004770static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004771 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4772 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4773 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4774 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4775 [ARG_CONST_SIZE] = &scalar_types,
4776 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4777 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4778 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4779 [ARG_PTR_TO_CTX] = &context_types,
4780 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4781 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004782#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004783 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004784#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004785 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4786 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4787 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4788 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4789 [ARG_PTR_TO_MEM] = &mem_types,
4790 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4791 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4792 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4793 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4794 [ARG_PTR_TO_INT] = &int_ptr_types,
4795 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004796 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Yonghong Song69c087b2021-02-26 12:49:25 -08004797 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4798 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
Florent Revestfff13c42021-04-19 17:52:39 +02004799 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004800};
4801
4802static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004803 enum bpf_arg_type arg_type,
4804 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004805{
4806 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4807 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004808 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004809 int i, j;
4810
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004811 compatible = compatible_reg_types[arg_type];
4812 if (!compatible) {
4813 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4814 return -EFAULT;
4815 }
4816
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004817 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4818 expected = compatible->types[i];
4819 if (expected == NOT_INIT)
4820 break;
4821
4822 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004823 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004824 }
4825
4826 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4827 for (j = 0; j + 1 < i; j++)
4828 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4829 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4830 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004831
4832found:
4833 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004834 if (!arg_btf_id) {
4835 if (!compatible->btf_id) {
4836 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4837 return -EFAULT;
4838 }
4839 arg_btf_id = compatible->btf_id;
4840 }
4841
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004842 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4843 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004844 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004845 regno, kernel_type_name(reg->btf, reg->btf_id),
4846 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004847 return -EACCES;
4848 }
4849
4850 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4851 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4852 regno);
4853 return -EACCES;
4854 }
4855 }
4856
4857 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004858}
4859
Yonghong Songaf7ec132020-06-23 16:08:09 -07004860static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4861 struct bpf_call_arg_meta *meta,
4862 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004863{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004864 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004865 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004866 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004867 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004868 int err = 0;
4869
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004870 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004871 return 0;
4872
Edward Creedc503a82017-08-15 20:34:35 +01004873 err = check_reg_arg(env, regno, SRC_OP);
4874 if (err)
4875 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004876
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004877 if (arg_type == ARG_ANYTHING) {
4878 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004879 verbose(env, "R%d leaks addr into helper function\n",
4880 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004881 return -EACCES;
4882 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004883 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004884 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004885
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004886 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004887 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004888 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004889 return -EACCES;
4890 }
4891
Lorenz Bauer912f4422020-08-21 11:29:46 +01004892 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4893 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4894 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4895 err = resolve_map_arg_type(env, meta, &arg_type);
4896 if (err)
4897 return err;
4898 }
4899
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004900 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4901 /* A NULL register has a SCALAR_VALUE type, so skip
4902 * type checking.
4903 */
4904 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004905
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004906 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004907 if (err)
4908 return err;
4909
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004910 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004911 err = check_ctx_reg(env, reg, regno);
4912 if (err < 0)
4913 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004914 }
4915
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004916skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004917 if (reg->ref_obj_id) {
Andrii Nakryiko457f44362020-05-29 00:54:20 -07004918 if (meta->ref_obj_id) {
4919 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4920 regno, reg->ref_obj_id,
4921 meta->ref_obj_id);
4922 return -EFAULT;
4923 }
4924 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004925 }
4926
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004927 if (arg_type == ARG_CONST_MAP_PTR) {
4928 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004929 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004930 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4931 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4932 * check that [key, key + map->key_size) are within
4933 * stack limits and initialized
4934 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004935 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004936 /* in function declaration map_ptr must come before
4937 * map_key, so that it's verified and known before
4938 * we have to check map_key here. Otherwise it means
4939 * that kernel subsystem misconfigured verifier
4940 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004941 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004942 return -EACCES;
4943 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004944 err = check_helper_mem_access(env, regno,
4945 meta->map_ptr->key_size, false,
4946 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004947 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004948 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4949 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004950 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004951 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4952 * check [value, value + map->value_size) validity
4953 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004954 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004955 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004956 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004957 return -EACCES;
4958 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004959 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004960 err = check_helper_mem_access(env, regno,
4961 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004962 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004963 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4964 if (!reg->btf_id) {
4965 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4966 return -EACCES;
4967 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004968 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004969 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004970 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4971 if (meta->func_id == BPF_FUNC_spin_lock) {
4972 if (process_spin_lock(env, regno, true))
4973 return -EACCES;
4974 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4975 if (process_spin_lock(env, regno, false))
4976 return -EACCES;
4977 } else {
4978 verbose(env, "verifier internal error\n");
4979 return -EFAULT;
4980 }
Yonghong Song69c087b2021-02-26 12:49:25 -08004981 } else if (arg_type == ARG_PTR_TO_FUNC) {
4982 meta->subprogno = reg->subprogno;
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01004983 } else if (arg_type_is_mem_ptr(arg_type)) {
4984 /* The access to this pointer is only checked when we hit the
4985 * next is_mem_size argument below.
4986 */
4987 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01004988 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004989 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004990
John Fastabend10060502020-03-30 14:36:19 -07004991 /* This is used to refine r0 return value bounds for helpers
4992 * that enforce this value as an upper bound on return values.
4993 * See do_refine_retval_range() for helpers that can refine
4994 * the return value. C type of helper is u32 so we pull register
4995 * bound from umax_value however, if negative verifier errors
4996 * out. Only upper bounds can be learned because retval is an
4997 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004998 */
John Fastabend10060502020-03-30 14:36:19 -07004999 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07005000
Edward Creef1174f72017-08-07 15:26:19 +01005001 /* The register is SCALAR_VALUE; the access check
5002 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08005003 */
Edward Creef1174f72017-08-07 15:26:19 +01005004 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08005005 /* For unprivileged variable accesses, disable raw
5006 * mode so that the program is required to
5007 * initialize all the memory that the helper could
5008 * just partially fill up.
5009 */
5010 meta = NULL;
5011
Edward Creeb03c9f92017-08-07 15:26:36 +01005012 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005013 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005014 regno);
5015 return -EACCES;
5016 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08005017
Edward Creeb03c9f92017-08-07 15:26:36 +01005018 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01005019 err = check_helper_mem_access(env, regno - 1, 0,
5020 zero_size_allowed,
5021 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08005022 if (err)
5023 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08005024 }
Edward Creef1174f72017-08-07 15:26:19 +01005025
Edward Creeb03c9f92017-08-07 15:26:36 +01005026 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005027 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005028 regno);
5029 return -EACCES;
5030 }
5031 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01005032 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01005033 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005034 if (!err)
5035 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f44362020-05-29 00:54:20 -07005036 } else if (arg_type_is_alloc_size(arg_type)) {
5037 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00005038 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f44362020-05-29 00:54:20 -07005039 regno);
5040 return -EACCES;
5041 }
5042 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07005043 } else if (arg_type_is_int_ptr(arg_type)) {
5044 int size = int_ptr_type_to_size(arg_type);
5045
5046 err = check_helper_mem_access(env, regno, size, false, meta);
5047 if (err)
5048 return err;
5049 err = check_ptr_alignment(env, reg, 0, size, true);
Florent Revestfff13c42021-04-19 17:52:39 +02005050 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5051 struct bpf_map *map = reg->map_ptr;
5052 int map_off;
5053 u64 map_addr;
5054 char *str_ptr;
5055
Florent Revesta8fad732021-04-23 01:55:43 +02005056 if (!bpf_map_is_rdonly(map)) {
Florent Revestfff13c42021-04-19 17:52:39 +02005057 verbose(env, "R%d does not point to a readonly map'\n", regno);
5058 return -EACCES;
5059 }
5060
5061 if (!tnum_is_const(reg->var_off)) {
5062 verbose(env, "R%d is not a constant address'\n", regno);
5063 return -EACCES;
5064 }
5065
5066 if (!map->ops->map_direct_value_addr) {
5067 verbose(env, "no direct value access support for this map type\n");
5068 return -EACCES;
5069 }
5070
5071 err = check_map_access(env, regno, reg->off,
5072 map->value_size - reg->off, false);
5073 if (err)
5074 return err;
5075
5076 map_off = reg->off + reg->var_off.value;
5077 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5078 if (err) {
5079 verbose(env, "direct value access on string failed\n");
5080 return err;
5081 }
5082
5083 str_ptr = (char *)(long)(map_addr);
5084 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5085 verbose(env, "string is not zero-terminated\n");
5086 return -EINVAL;
5087 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005088 }
5089
5090 return err;
5091}
5092
Lorenz Bauer01262402020-08-21 11:29:47 +01005093static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5094{
5095 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07005096 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01005097
5098 if (func_id != BPF_FUNC_map_update_elem)
5099 return false;
5100
5101 /* It's not possible to get access to a locked struct sock in these
5102 * contexts, so updating is safe.
5103 */
5104 switch (type) {
5105 case BPF_PROG_TYPE_TRACING:
5106 if (eatype == BPF_TRACE_ITER)
5107 return true;
5108 break;
5109 case BPF_PROG_TYPE_SOCKET_FILTER:
5110 case BPF_PROG_TYPE_SCHED_CLS:
5111 case BPF_PROG_TYPE_SCHED_ACT:
5112 case BPF_PROG_TYPE_XDP:
5113 case BPF_PROG_TYPE_SK_REUSEPORT:
5114 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5115 case BPF_PROG_TYPE_SK_LOOKUP:
5116 return true;
5117 default:
5118 break;
5119 }
5120
5121 verbose(env, "cannot update sockmap in this context\n");
5122 return false;
5123}
5124
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005125static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5126{
5127 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5128}
5129
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005130static int check_map_func_compatibility(struct bpf_verifier_env *env,
5131 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00005132{
Kaixu Xia35578d72015-08-06 07:02:35 +00005133 if (!map)
5134 return 0;
5135
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005136 /* We need a two way check, first is from map perspective ... */
5137 switch (map->map_type) {
5138 case BPF_MAP_TYPE_PROG_ARRAY:
5139 if (func_id != BPF_FUNC_tail_call)
5140 goto error;
5141 break;
5142 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5143 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07005144 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005145 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005146 func_id != BPF_FUNC_perf_event_read_value &&
5147 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005148 goto error;
5149 break;
Andrii Nakryiko457f44362020-05-29 00:54:20 -07005150 case BPF_MAP_TYPE_RINGBUF:
5151 if (func_id != BPF_FUNC_ringbuf_output &&
5152 func_id != BPF_FUNC_ringbuf_reserve &&
5153 func_id != BPF_FUNC_ringbuf_submit &&
5154 func_id != BPF_FUNC_ringbuf_discard &&
5155 func_id != BPF_FUNC_ringbuf_query)
5156 goto error;
5157 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005158 case BPF_MAP_TYPE_STACK_TRACE:
5159 if (func_id != BPF_FUNC_get_stackid)
5160 goto error;
5161 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07005162 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04005163 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005164 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005165 goto error;
5166 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005167 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00005168 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07005169 if (func_id != BPF_FUNC_get_local_storage)
5170 goto error;
5171 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07005172 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005173 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02005174 if (func_id != BPF_FUNC_redirect_map &&
5175 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07005176 goto error;
5177 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005178 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5179 * appear.
5180 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02005181 case BPF_MAP_TYPE_CPUMAP:
5182 if (func_id != BPF_FUNC_redirect_map)
5183 goto error;
5184 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005185 case BPF_MAP_TYPE_XSKMAP:
5186 if (func_id != BPF_FUNC_redirect_map &&
5187 func_id != BPF_FUNC_map_lookup_elem)
5188 goto error;
5189 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005190 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07005191 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005192 if (func_id != BPF_FUNC_map_lookup_elem)
5193 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07005194 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005195 case BPF_MAP_TYPE_SOCKMAP:
5196 if (func_id != BPF_FUNC_sk_redirect_map &&
5197 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07005198 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005199 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005200 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005201 func_id != BPF_FUNC_map_lookup_elem &&
5202 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07005203 goto error;
5204 break;
John Fastabend81110382018-05-14 10:00:17 -07005205 case BPF_MAP_TYPE_SOCKHASH:
5206 if (func_id != BPF_FUNC_sk_redirect_hash &&
5207 func_id != BPF_FUNC_sock_hash_update &&
5208 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005209 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005210 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005211 func_id != BPF_FUNC_map_lookup_elem &&
5212 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07005213 goto error;
5214 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005215 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5216 if (func_id != BPF_FUNC_sk_select_reuseport)
5217 goto error;
5218 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005219 case BPF_MAP_TYPE_QUEUE:
5220 case BPF_MAP_TYPE_STACK:
5221 if (func_id != BPF_FUNC_map_peek_elem &&
5222 func_id != BPF_FUNC_map_pop_elem &&
5223 func_id != BPF_FUNC_map_push_elem)
5224 goto error;
5225 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005226 case BPF_MAP_TYPE_SK_STORAGE:
5227 if (func_id != BPF_FUNC_sk_storage_get &&
5228 func_id != BPF_FUNC_sk_storage_delete)
5229 goto error;
5230 break;
KP Singh8ea63682020-08-25 20:29:17 +02005231 case BPF_MAP_TYPE_INODE_STORAGE:
5232 if (func_id != BPF_FUNC_inode_storage_get &&
5233 func_id != BPF_FUNC_inode_storage_delete)
5234 goto error;
5235 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005236 case BPF_MAP_TYPE_TASK_STORAGE:
5237 if (func_id != BPF_FUNC_task_storage_get &&
5238 func_id != BPF_FUNC_task_storage_delete)
5239 goto error;
5240 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005241 default:
5242 break;
5243 }
5244
5245 /* ... and second from the function itself. */
5246 switch (func_id) {
5247 case BPF_FUNC_tail_call:
5248 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5249 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005250 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5251 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005252 return -EINVAL;
5253 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005254 break;
5255 case BPF_FUNC_perf_event_read:
5256 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07005257 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005258 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005259 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005260 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5261 goto error;
5262 break;
5263 case BPF_FUNC_get_stackid:
5264 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5265 goto error;
5266 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005267 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02005268 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005269 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5270 goto error;
5271 break;
John Fastabend97f91a72017-07-17 09:29:18 -07005272 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02005273 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005274 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005275 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5276 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07005277 goto error;
5278 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005279 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07005280 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07005281 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07005282 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5283 goto error;
5284 break;
John Fastabend81110382018-05-14 10:00:17 -07005285 case BPF_FUNC_sk_redirect_hash:
5286 case BPF_FUNC_msg_redirect_hash:
5287 case BPF_FUNC_sock_hash_update:
5288 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07005289 goto error;
5290 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005291 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00005292 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5293 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07005294 goto error;
5295 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005296 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005297 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5298 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5299 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005300 goto error;
5301 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005302 case BPF_FUNC_map_peek_elem:
5303 case BPF_FUNC_map_pop_elem:
5304 case BPF_FUNC_map_push_elem:
5305 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5306 map->map_type != BPF_MAP_TYPE_STACK)
5307 goto error;
5308 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005309 case BPF_FUNC_sk_storage_get:
5310 case BPF_FUNC_sk_storage_delete:
5311 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5312 goto error;
5313 break;
KP Singh8ea63682020-08-25 20:29:17 +02005314 case BPF_FUNC_inode_storage_get:
5315 case BPF_FUNC_inode_storage_delete:
5316 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5317 goto error;
5318 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005319 case BPF_FUNC_task_storage_get:
5320 case BPF_FUNC_task_storage_delete:
5321 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5322 goto error;
5323 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005324 default:
5325 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005326 }
5327
5328 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005329error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005330 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005331 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005332 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005333}
5334
Daniel Borkmann90133412018-01-20 01:24:29 +01005335static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005336{
5337 int count = 0;
5338
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005339 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005340 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005341 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005342 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005343 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005344 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005345 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005346 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005347 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005348 count++;
5349
Daniel Borkmann90133412018-01-20 01:24:29 +01005350 /* We only support one arg being in raw mode at the moment,
5351 * which is sufficient for the helper functions we have
5352 * right now.
5353 */
5354 return count <= 1;
5355}
5356
5357static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5358 enum bpf_arg_type arg_next)
5359{
5360 return (arg_type_is_mem_ptr(arg_curr) &&
5361 !arg_type_is_mem_size(arg_next)) ||
5362 (!arg_type_is_mem_ptr(arg_curr) &&
5363 arg_type_is_mem_size(arg_next));
5364}
5365
5366static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5367{
5368 /* bpf_xxx(..., buf, len) call will access 'len'
5369 * bytes from memory 'buf'. Both arg types need
5370 * to be paired, so make sure there's no buggy
5371 * helper function specification.
5372 */
5373 if (arg_type_is_mem_size(fn->arg1_type) ||
5374 arg_type_is_mem_ptr(fn->arg5_type) ||
5375 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5376 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5377 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5378 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5379 return false;
5380
5381 return true;
5382}
5383
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005384static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005385{
5386 int count = 0;
5387
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005388 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005389 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005390 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005391 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005392 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005393 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005394 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005395 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005396 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005397 count++;
5398
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005399 /* A reference acquiring function cannot acquire
5400 * another refcounted ptr.
5401 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005402 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005403 return false;
5404
Joe Stringerfd978bf72018-10-02 13:35:35 -07005405 /* We only support one arg being unreferenced at the moment,
5406 * which is sufficient for the helper functions we have right now.
5407 */
5408 return count <= 1;
5409}
5410
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005411static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5412{
5413 int i;
5414
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005415 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005416 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5417 return false;
5418
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005419 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5420 return false;
5421 }
5422
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005423 return true;
5424}
5425
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005426static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005427{
5428 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005429 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005430 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005431 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005432}
5433
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005434/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5435 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005436 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005437static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5438 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005439{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005440 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005441 int i;
5442
5443 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005444 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005445 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005446
Joe Stringerf3709f62018-10-02 13:35:29 -07005447 bpf_for_each_spilled_reg(i, state, reg) {
5448 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005449 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005450 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005451 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005452 }
5453}
5454
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005455static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5456{
5457 struct bpf_verifier_state *vstate = env->cur_state;
5458 int i;
5459
5460 for (i = 0; i <= vstate->curframe; i++)
5461 __clear_all_pkt_pointers(env, vstate->frame[i]);
5462}
5463
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005464enum {
5465 AT_PKT_END = -1,
5466 BEYOND_PKT_END = -2,
5467};
5468
5469static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5470{
5471 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5472 struct bpf_reg_state *reg = &state->regs[regn];
5473
5474 if (reg->type != PTR_TO_PACKET)
5475 /* PTR_TO_PACKET_META is not supported yet */
5476 return;
5477
5478 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5479 * How far beyond pkt_end it goes is unknown.
5480 * if (!range_open) it's the case of pkt >= pkt_end
5481 * if (range_open) it's the case of pkt > pkt_end
5482 * hence this pointer is at least 1 byte bigger than pkt_end
5483 */
5484 if (range_open)
5485 reg->range = BEYOND_PKT_END;
5486 else
5487 reg->range = AT_PKT_END;
5488}
5489
Joe Stringerfd978bf72018-10-02 13:35:35 -07005490static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005491 struct bpf_func_state *state,
5492 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005493{
5494 struct bpf_reg_state *regs = state->regs, *reg;
5495 int i;
5496
5497 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005498 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005499 mark_reg_unknown(env, regs, i);
5500
5501 bpf_for_each_spilled_reg(i, state, reg) {
5502 if (!reg)
5503 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005504 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005505 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005506 }
5507}
5508
5509/* The pointer with the specified id has released its reference to kernel
5510 * resources. Identify all copies of the same pointer and clear the reference.
5511 */
5512static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005513 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005514{
5515 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005516 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005517 int i;
5518
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005519 err = release_reference_state(cur_func(env), ref_obj_id);
5520 if (err)
5521 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005522
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005523 for (i = 0; i <= vstate->curframe; i++)
5524 release_reg_references(env, vstate->frame[i], ref_obj_id);
5525
5526 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005527}
5528
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005529static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5530 struct bpf_reg_state *regs)
5531{
5532 int i;
5533
5534 /* after the call registers r0 - r5 were scratched */
5535 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5536 mark_reg_not_init(env, regs, caller_saved[i]);
5537 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5538 }
5539}
5540
Yonghong Song14351372021-02-26 12:49:23 -08005541typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5542 struct bpf_func_state *caller,
5543 struct bpf_func_state *callee,
5544 int insn_idx);
5545
5546static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5547 int *insn_idx, int subprog,
5548 set_callee_state_fn set_callee_state_cb)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005549{
5550 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005551 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005552 struct bpf_func_state *caller, *callee;
Yonghong Song14351372021-02-26 12:49:23 -08005553 int err;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005554 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005555
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005556 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005557 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005558 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005559 return -E2BIG;
5560 }
5561
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005562 caller = state->frame[state->curframe];
5563 if (state->frame[state->curframe + 1]) {
5564 verbose(env, "verifier bug. Frame %d already allocated\n",
5565 state->curframe + 1);
5566 return -EFAULT;
5567 }
5568
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005569 func_info_aux = env->prog->aux->func_info_aux;
5570 if (func_info_aux)
5571 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
Martin KaFai Lau34747c42021-03-24 18:51:36 -07005572 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005573 if (err == -EFAULT)
5574 return err;
5575 if (is_global) {
5576 if (err) {
5577 verbose(env, "Caller passes invalid args into func#%d\n",
5578 subprog);
5579 return err;
5580 } else {
5581 if (env->log.level & BPF_LOG_LEVEL)
5582 verbose(env,
5583 "Func#%d is global and valid. Skipping.\n",
5584 subprog);
5585 clear_caller_saved_regs(env, caller->regs);
5586
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005587 /* All global functions return a 64-bit SCALAR_VALUE */
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005588 mark_reg_unknown(env, caller->regs, BPF_REG_0);
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005589 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005590
5591 /* continue with next insn after call */
5592 return 0;
5593 }
5594 }
5595
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005596 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5597 if (!callee)
5598 return -ENOMEM;
5599 state->frame[state->curframe + 1] = callee;
5600
5601 /* callee cannot access r0, r6 - r9 for reading and has to write
5602 * into its own stack before reading from it.
5603 * callee can read/write into caller's stack
5604 */
5605 init_func_state(env, callee,
5606 /* remember the callsite, it will be used by bpf_exit */
5607 *insn_idx /* callsite */,
5608 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04005609 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005610
Joe Stringerfd978bf72018-10-02 13:35:35 -07005611 /* Transfer references to the callee */
Lorenz Bauerc69431a2021-04-29 14:46:54 +01005612 err = copy_reference_state(callee, caller);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005613 if (err)
5614 return err;
5615
Yonghong Song14351372021-02-26 12:49:23 -08005616 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5617 if (err)
5618 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005619
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005620 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005621
5622 /* only increment it after check_reg_arg() finished */
5623 state->curframe++;
5624
5625 /* and go analyze first insn of the callee */
Yonghong Song14351372021-02-26 12:49:23 -08005626 *insn_idx = env->subprog_info[subprog].start - 1;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005627
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005628 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005629 verbose(env, "caller:\n");
5630 print_verifier_state(env, caller);
5631 verbose(env, "callee:\n");
5632 print_verifier_state(env, callee);
5633 }
5634 return 0;
5635}
5636
Yonghong Song314ee052021-02-26 12:49:27 -08005637int map_set_for_each_callback_args(struct bpf_verifier_env *env,
5638 struct bpf_func_state *caller,
5639 struct bpf_func_state *callee)
5640{
5641 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
5642 * void *callback_ctx, u64 flags);
5643 * callback_fn(struct bpf_map *map, void *key, void *value,
5644 * void *callback_ctx);
5645 */
5646 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
5647
5648 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
5649 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
5650 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5651
5652 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
5653 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
5654 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
5655
5656 /* pointer to stack or null */
5657 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
5658
5659 /* unused */
5660 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
5661 return 0;
5662}
5663
Yonghong Song14351372021-02-26 12:49:23 -08005664static int set_callee_state(struct bpf_verifier_env *env,
5665 struct bpf_func_state *caller,
5666 struct bpf_func_state *callee, int insn_idx)
5667{
5668 int i;
5669
5670 /* copy r1 - r5 args that callee can access. The copy includes parent
5671 * pointers, which connects us up to the liveness chain
5672 */
5673 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5674 callee->regs[i] = caller->regs[i];
5675 return 0;
5676}
5677
5678static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5679 int *insn_idx)
5680{
5681 int subprog, target_insn;
5682
5683 target_insn = *insn_idx + insn->imm + 1;
5684 subprog = find_subprog(env, target_insn);
5685 if (subprog < 0) {
5686 verbose(env, "verifier bug. No program starts at insn %d\n",
5687 target_insn);
5688 return -EFAULT;
5689 }
5690
5691 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5692}
5693
Yonghong Song69c087b2021-02-26 12:49:25 -08005694static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5695 struct bpf_func_state *caller,
5696 struct bpf_func_state *callee,
5697 int insn_idx)
5698{
5699 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5700 struct bpf_map *map;
5701 int err;
5702
5703 if (bpf_map_ptr_poisoned(insn_aux)) {
5704 verbose(env, "tail_call abusing map_ptr\n");
5705 return -EINVAL;
5706 }
5707
5708 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5709 if (!map->ops->map_set_for_each_callback_args ||
5710 !map->ops->map_for_each_callback) {
5711 verbose(env, "callback function not allowed for map\n");
5712 return -ENOTSUPP;
5713 }
5714
5715 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5716 if (err)
5717 return err;
5718
5719 callee->in_callback_fn = true;
5720 return 0;
5721}
5722
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005723static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5724{
5725 struct bpf_verifier_state *state = env->cur_state;
5726 struct bpf_func_state *caller, *callee;
5727 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005728 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005729
5730 callee = state->frame[state->curframe];
5731 r0 = &callee->regs[BPF_REG_0];
5732 if (r0->type == PTR_TO_STACK) {
5733 /* technically it's ok to return caller's stack pointer
5734 * (or caller's caller's pointer) back to the caller,
5735 * since these pointers are valid. Only current stack
5736 * pointer will be invalid as soon as function exits,
5737 * but let's be conservative
5738 */
5739 verbose(env, "cannot return stack pointer to the caller\n");
5740 return -EINVAL;
5741 }
5742
5743 state->curframe--;
5744 caller = state->frame[state->curframe];
Yonghong Song69c087b2021-02-26 12:49:25 -08005745 if (callee->in_callback_fn) {
5746 /* enforce R0 return value range [0, 1]. */
5747 struct tnum range = tnum_range(0, 1);
5748
5749 if (r0->type != SCALAR_VALUE) {
5750 verbose(env, "R0 not a scalar value\n");
5751 return -EACCES;
5752 }
5753 if (!tnum_in(range, r0->var_off)) {
5754 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5755 return -EINVAL;
5756 }
5757 } else {
5758 /* return to the caller whatever r0 had in the callee */
5759 caller->regs[BPF_REG_0] = *r0;
5760 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005761
Joe Stringerfd978bf72018-10-02 13:35:35 -07005762 /* Transfer references to the caller */
Lorenz Bauerc69431a2021-04-29 14:46:54 +01005763 err = copy_reference_state(caller, callee);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005764 if (err)
5765 return err;
5766
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005767 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005768 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005769 verbose(env, "returning from callee:\n");
5770 print_verifier_state(env, callee);
5771 verbose(env, "to caller at %d:\n", *insn_idx);
5772 print_verifier_state(env, caller);
5773 }
5774 /* clear everything in the callee */
5775 free_func_state(callee);
5776 state->frame[state->curframe + 1] = NULL;
5777 return 0;
5778}
5779
Yonghong Song849fa502018-04-28 22:28:09 -07005780static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5781 int func_id,
5782 struct bpf_call_arg_meta *meta)
5783{
5784 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5785
5786 if (ret_type != RET_INTEGER ||
5787 (func_id != BPF_FUNC_get_stack &&
Dave Marchevskyfd0b88f2021-04-16 13:47:02 -07005788 func_id != BPF_FUNC_get_task_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02005789 func_id != BPF_FUNC_probe_read_str &&
5790 func_id != BPF_FUNC_probe_read_kernel_str &&
5791 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07005792 return;
5793
John Fastabend10060502020-03-30 14:36:19 -07005794 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07005795 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01005796 ret_reg->smin_value = -MAX_ERRNO;
5797 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07005798 __reg_deduce_bounds(ret_reg);
5799 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07005800 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07005801}
5802
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005803static int
5804record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5805 int func_id, int insn_idx)
5806{
5807 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02005808 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005809
5810 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02005811 func_id != BPF_FUNC_map_lookup_elem &&
5812 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005813 func_id != BPF_FUNC_map_delete_elem &&
5814 func_id != BPF_FUNC_map_push_elem &&
5815 func_id != BPF_FUNC_map_pop_elem &&
Yonghong Song69c087b2021-02-26 12:49:25 -08005816 func_id != BPF_FUNC_map_peek_elem &&
Björn Töpele6a47502021-03-08 12:29:06 +01005817 func_id != BPF_FUNC_for_each_map_elem &&
5818 func_id != BPF_FUNC_redirect_map)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005819 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02005820
Daniel Borkmann591fe982019-04-09 23:20:05 +02005821 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005822 verbose(env, "kernel subsystem misconfigured verifier\n");
5823 return -EINVAL;
5824 }
5825
Daniel Borkmann591fe982019-04-09 23:20:05 +02005826 /* In case of read-only, some additional restrictions
5827 * need to be applied in order to prevent altering the
5828 * state of the map from program side.
5829 */
5830 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5831 (func_id == BPF_FUNC_map_delete_elem ||
5832 func_id == BPF_FUNC_map_update_elem ||
5833 func_id == BPF_FUNC_map_push_elem ||
5834 func_id == BPF_FUNC_map_pop_elem)) {
5835 verbose(env, "write into map forbidden\n");
5836 return -EACCES;
5837 }
5838
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005839 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005840 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005841 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005842 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005843 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005844 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005845 return 0;
5846}
5847
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005848static int
5849record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5850 int func_id, int insn_idx)
5851{
5852 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5853 struct bpf_reg_state *regs = cur_regs(env), *reg;
5854 struct bpf_map *map = meta->map_ptr;
5855 struct tnum range;
5856 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005857 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005858
5859 if (func_id != BPF_FUNC_tail_call)
5860 return 0;
5861 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5862 verbose(env, "kernel subsystem misconfigured verifier\n");
5863 return -EINVAL;
5864 }
5865
5866 range = tnum_range(0, map->max_entries - 1);
5867 reg = &regs[BPF_REG_3];
5868
5869 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5870 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5871 return 0;
5872 }
5873
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005874 err = mark_chain_precision(env, BPF_REG_3);
5875 if (err)
5876 return err;
5877
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005878 val = reg->var_off.value;
5879 if (bpf_map_key_unseen(aux))
5880 bpf_map_key_store(aux, val);
5881 else if (!bpf_map_key_poisoned(aux) &&
5882 bpf_map_key_immediate(aux) != val)
5883 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5884 return 0;
5885}
5886
Joe Stringerfd978bf72018-10-02 13:35:35 -07005887static int check_reference_leak(struct bpf_verifier_env *env)
5888{
5889 struct bpf_func_state *state = cur_func(env);
5890 int i;
5891
5892 for (i = 0; i < state->acquired_refs; i++) {
5893 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5894 state->refs[i].id, state->refs[i].insn_idx);
5895 }
5896 return state->acquired_refs ? -EINVAL : 0;
5897}
5898
Florent Revest7b155232021-04-19 17:52:40 +02005899static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
5900 struct bpf_reg_state *regs)
5901{
5902 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
5903 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
5904 struct bpf_map *fmt_map = fmt_reg->map_ptr;
5905 int err, fmt_map_off, num_args;
5906 u64 fmt_addr;
5907 char *fmt;
5908
5909 /* data must be an array of u64 */
5910 if (data_len_reg->var_off.value % 8)
5911 return -EINVAL;
5912 num_args = data_len_reg->var_off.value / 8;
5913
5914 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
5915 * and map_direct_value_addr is set.
5916 */
5917 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
5918 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
5919 fmt_map_off);
Florent Revest8e8ee102021-04-23 01:55:42 +02005920 if (err) {
5921 verbose(env, "verifier bug\n");
5922 return -EFAULT;
5923 }
Florent Revest7b155232021-04-19 17:52:40 +02005924 fmt = (char *)(long)fmt_addr + fmt_map_off;
5925
5926 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
5927 * can focus on validating the format specifiers.
5928 */
Florent Revest48cac3f2021-04-27 19:43:13 +02005929 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
Florent Revest7b155232021-04-19 17:52:40 +02005930 if (err < 0)
5931 verbose(env, "Invalid format string\n");
5932
5933 return err;
5934}
5935
Yonghong Song69c087b2021-02-26 12:49:25 -08005936static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5937 int *insn_idx_p)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005938{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005939 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005940 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005941 struct bpf_call_arg_meta meta;
Yonghong Song69c087b2021-02-26 12:49:25 -08005942 int insn_idx = *insn_idx_p;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005943 bool changes_data;
Yonghong Song69c087b2021-02-26 12:49:25 -08005944 int i, err, func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005945
5946 /* find function prototype */
Yonghong Song69c087b2021-02-26 12:49:25 -08005947 func_id = insn->imm;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005948 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005949 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5950 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005951 return -EINVAL;
5952 }
5953
Jakub Kicinski00176a32017-10-16 16:40:54 -07005954 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07005955 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005956 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005957 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5958 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005959 return -EINVAL;
5960 }
5961
5962 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01005963 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02005964 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005965 return -EINVAL;
5966 }
5967
Jiri Olsaeae2e832020-08-25 21:21:19 +02005968 if (fn->allowed && !fn->allowed(env->prog)) {
5969 verbose(env, "helper call is not allowed in probe\n");
5970 return -EINVAL;
5971 }
5972
Daniel Borkmann04514d12017-12-14 21:07:25 +01005973 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08005974 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01005975 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5976 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5977 func_id_name(func_id), func_id);
5978 return -EINVAL;
5979 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005980
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005981 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02005982 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005983
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005984 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005985 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005986 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005987 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005988 return err;
5989 }
5990
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08005991 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005992 /* check args */
Dmitrii Banshchikov523a4cf2021-02-26 00:26:29 +04005993 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005994 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005995 if (err)
5996 return err;
5997 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005998
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005999 err = record_func_map(env, &meta, func_id, insn_idx);
6000 if (err)
6001 return err;
6002
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006003 err = record_func_key(env, &meta, func_id, insn_idx);
6004 if (err)
6005 return err;
6006
Daniel Borkmann435faee12016-04-13 00:10:51 +02006007 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6008 * is inferred from register state.
6009 */
6010 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01006011 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6012 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006013 if (err)
6014 return err;
6015 }
6016
Joe Stringerfd978bf72018-10-02 13:35:35 -07006017 if (func_id == BPF_FUNC_tail_call) {
6018 err = check_reference_leak(env);
6019 if (err) {
6020 verbose(env, "tail_call would lead to reference leak\n");
6021 return err;
6022 }
6023 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006024 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006025 if (err) {
6026 verbose(env, "func %s#%d reference has not been acquired before\n",
6027 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07006028 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006029 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07006030 }
6031
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006032 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07006033
6034 /* check that flags argument in get_local_storage(map, flags) is 0,
6035 * this is required because get_local_storage() can't return an error.
6036 */
6037 if (func_id == BPF_FUNC_get_local_storage &&
6038 !register_is_null(&regs[BPF_REG_2])) {
6039 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6040 return -EINVAL;
6041 }
6042
Yonghong Song69c087b2021-02-26 12:49:25 -08006043 if (func_id == BPF_FUNC_for_each_map_elem) {
6044 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6045 set_map_elem_callback_state);
6046 if (err < 0)
6047 return -EINVAL;
6048 }
6049
Florent Revest7b155232021-04-19 17:52:40 +02006050 if (func_id == BPF_FUNC_snprintf) {
6051 err = check_bpf_snprintf_call(env, regs);
6052 if (err < 0)
6053 return err;
6054 }
6055
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006056 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01006057 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006058 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01006059 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6060 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006061
Jiong Wang5327ed32019-05-24 23:25:12 +01006062 /* helper call returns 64-bit value. */
6063 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6064
Edward Creedc503a82017-08-15 20:34:35 +01006065 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006066 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01006067 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006068 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006069 } else if (fn->ret_type == RET_VOID) {
6070 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07006071 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6072 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01006073 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006074 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006075 /* remember map_ptr, so that check_map_access()
6076 * can check 'value_size' boundary of memory access
6077 * to map element returned from bpf_map_lookup_elem()
6078 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006079 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006080 verbose(env,
6081 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006082 return -EINVAL;
6083 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006084 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006085 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6086 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08006087 if (map_value_has_spin_lock(meta.map_ptr))
6088 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006089 } else {
6090 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006091 }
Joe Stringerc64b7982018-10-02 13:35:33 -07006092 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6093 mark_reg_known_zero(env, regs, BPF_REG_0);
6094 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08006095 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6096 mark_reg_known_zero(env, regs, BPF_REG_0);
6097 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006098 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6099 mark_reg_known_zero(env, regs, BPF_REG_0);
6100 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f44362020-05-29 00:54:20 -07006101 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6102 mark_reg_known_zero(env, regs, BPF_REG_0);
6103 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f44362020-05-29 00:54:20 -07006104 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07006105 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6106 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006107 const struct btf_type *t;
6108
6109 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006110 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006111 if (!btf_type_is_struct(t)) {
6112 u32 tsize;
6113 const struct btf_type *ret;
6114 const char *tname;
6115
6116 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006117 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006118 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006119 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006120 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6121 tname, PTR_ERR(ret));
6122 return -EINVAL;
6123 }
Hao Luo63d9b802020-09-29 16:50:48 -07006124 regs[BPF_REG_0].type =
6125 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6126 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006127 regs[BPF_REG_0].mem_size = tsize;
6128 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07006129 regs[BPF_REG_0].type =
6130 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6131 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006132 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006133 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6134 }
KP Singh3ca10322020-11-06 10:37:43 +00006135 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6136 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07006137 int ret_btf_id;
6138
6139 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00006140 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6141 PTR_TO_BTF_ID :
6142 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006143 ret_btf_id = *fn->ret_btf_id;
6144 if (ret_btf_id == 0) {
6145 verbose(env, "invalid return type %d of func %s#%d\n",
6146 fn->ret_type, func_id_name(func_id), func_id);
6147 return -EINVAL;
6148 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006149 /* current BPF helper definitions are only coming from
6150 * built-in code with type IDs from vmlinux BTF
6151 */
6152 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006153 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006154 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006155 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02006156 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006157 return -EINVAL;
6158 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006159
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07006160 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6161 regs[BPF_REG_0].id = ++env->id_gen;
6162
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006163 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006164 /* For release_reference() */
6165 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02006166 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006167 int id = acquire_reference_state(env, insn_idx);
6168
6169 if (id < 0)
6170 return id;
6171 /* For mark_ptr_or_null_reg() */
6172 regs[BPF_REG_0].id = id;
6173 /* For release_reference() */
6174 regs[BPF_REG_0].ref_obj_id = id;
6175 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006176
Yonghong Song849fa502018-04-28 22:28:09 -07006177 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6178
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006179 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00006180 if (err)
6181 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006182
Song Liufa28dcb2020-06-29 23:28:44 -07006183 if ((func_id == BPF_FUNC_get_stack ||
6184 func_id == BPF_FUNC_get_task_stack) &&
6185 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07006186 const char *err_str;
6187
6188#ifdef CONFIG_PERF_EVENTS
6189 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6190 err_str = "cannot get callchain buffer for func %s#%d\n";
6191#else
6192 err = -ENOTSUPP;
6193 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6194#endif
6195 if (err) {
6196 verbose(env, err_str, func_id_name(func_id), func_id);
6197 return err;
6198 }
6199
6200 env->prog->has_callchain_buf = true;
6201 }
6202
Song Liu5d99cb2c2020-07-23 11:06:45 -07006203 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6204 env->prog->call_get_stack = true;
6205
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006206 if (changes_data)
6207 clear_all_pkt_pointers(env);
6208 return 0;
6209}
6210
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006211/* mark_btf_func_reg_size() is used when the reg size is determined by
6212 * the BTF func_proto's return value size and argument.
6213 */
6214static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6215 size_t reg_size)
6216{
6217 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6218
6219 if (regno == BPF_REG_0) {
6220 /* Function return value */
6221 reg->live |= REG_LIVE_WRITTEN;
6222 reg->subreg_def = reg_size == sizeof(u64) ?
6223 DEF_NOT_SUBREG : env->insn_idx + 1;
6224 } else {
6225 /* Function argument */
6226 if (reg_size == sizeof(u64)) {
6227 mark_insn_zext(env, reg);
6228 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6229 } else {
6230 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6231 }
6232 }
6233}
6234
6235static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6236{
6237 const struct btf_type *t, *func, *func_proto, *ptr_type;
6238 struct bpf_reg_state *regs = cur_regs(env);
6239 const char *func_name, *ptr_type_name;
6240 u32 i, nargs, func_id, ptr_type_id;
6241 const struct btf_param *args;
6242 int err;
6243
6244 func_id = insn->imm;
6245 func = btf_type_by_id(btf_vmlinux, func_id);
6246 func_name = btf_name_by_offset(btf_vmlinux, func->name_off);
6247 func_proto = btf_type_by_id(btf_vmlinux, func->type);
6248
6249 if (!env->ops->check_kfunc_call ||
6250 !env->ops->check_kfunc_call(func_id)) {
6251 verbose(env, "calling kernel function %s is not allowed\n",
6252 func_name);
6253 return -EACCES;
6254 }
6255
6256 /* Check the arguments */
6257 err = btf_check_kfunc_arg_match(env, btf_vmlinux, func_id, regs);
6258 if (err)
6259 return err;
6260
6261 for (i = 0; i < CALLER_SAVED_REGS; i++)
6262 mark_reg_not_init(env, regs, caller_saved[i]);
6263
6264 /* Check return type */
6265 t = btf_type_skip_modifiers(btf_vmlinux, func_proto->type, NULL);
6266 if (btf_type_is_scalar(t)) {
6267 mark_reg_unknown(env, regs, BPF_REG_0);
6268 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6269 } else if (btf_type_is_ptr(t)) {
6270 ptr_type = btf_type_skip_modifiers(btf_vmlinux, t->type,
6271 &ptr_type_id);
6272 if (!btf_type_is_struct(ptr_type)) {
6273 ptr_type_name = btf_name_by_offset(btf_vmlinux,
6274 ptr_type->name_off);
6275 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6276 func_name, btf_type_str(ptr_type),
6277 ptr_type_name);
6278 return -EINVAL;
6279 }
6280 mark_reg_known_zero(env, regs, BPF_REG_0);
6281 regs[BPF_REG_0].btf = btf_vmlinux;
6282 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6283 regs[BPF_REG_0].btf_id = ptr_type_id;
6284 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6285 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6286
6287 nargs = btf_type_vlen(func_proto);
6288 args = (const struct btf_param *)(func_proto + 1);
6289 for (i = 0; i < nargs; i++) {
6290 u32 regno = i + 1;
6291
6292 t = btf_type_skip_modifiers(btf_vmlinux, args[i].type, NULL);
6293 if (btf_type_is_ptr(t))
6294 mark_btf_func_reg_size(env, regno, sizeof(void *));
6295 else
6296 /* scalar. ensured by btf_check_kfunc_arg_match() */
6297 mark_btf_func_reg_size(env, regno, t->size);
6298 }
6299
6300 return 0;
6301}
6302
Edward Creeb03c9f92017-08-07 15:26:36 +01006303static bool signed_add_overflows(s64 a, s64 b)
6304{
6305 /* Do the add in u64, where overflow is well-defined */
6306 s64 res = (s64)((u64)a + (u64)b);
6307
6308 if (b < 0)
6309 return res > a;
6310 return res < a;
6311}
6312
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006313static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07006314{
6315 /* Do the add in u32, where overflow is well-defined */
6316 s32 res = (s32)((u32)a + (u32)b);
6317
6318 if (b < 0)
6319 return res > a;
6320 return res < a;
6321}
6322
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006323static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01006324{
6325 /* Do the sub 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;
David S. Millerd1174412017-05-10 11:22:52 -07006331}
6332
John Fastabend3f50f132020-03-30 14:36:39 -07006333static bool signed_sub32_overflows(s32 a, s32 b)
6334{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006335 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07006336 s32 res = (s32)((u32)a - (u32)b);
6337
6338 if (b < 0)
6339 return res < a;
6340 return res > a;
6341}
6342
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006343static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6344 const struct bpf_reg_state *reg,
6345 enum bpf_reg_type type)
6346{
6347 bool known = tnum_is_const(reg->var_off);
6348 s64 val = reg->var_off.value;
6349 s64 smin = reg->smin_value;
6350
6351 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6352 verbose(env, "math between %s pointer and %lld is not allowed\n",
6353 reg_type_str[type], val);
6354 return false;
6355 }
6356
6357 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6358 verbose(env, "%s pointer offset %d is not allowed\n",
6359 reg_type_str[type], reg->off);
6360 return false;
6361 }
6362
6363 if (smin == S64_MIN) {
6364 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6365 reg_type_str[type]);
6366 return false;
6367 }
6368
6369 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6370 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6371 smin, reg_type_str[type]);
6372 return false;
6373 }
6374
6375 return true;
6376}
6377
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006378static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6379{
6380 return &env->insn_aux_data[env->insn_idx];
6381}
6382
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006383enum {
6384 REASON_BOUNDS = -1,
6385 REASON_TYPE = -2,
6386 REASON_PATHS = -3,
6387 REASON_LIMIT = -4,
6388 REASON_STACK = -5,
6389};
6390
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006391static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006392 u32 *alu_limit, bool mask_to_left)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006393{
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006394 u32 max = 0, ptr_limit = 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006395
6396 switch (ptr_reg->type) {
6397 case PTR_TO_STACK:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006398 /* Offset 0 is out-of-bounds, but acceptable start for the
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006399 * left direction, see BPF_REG_FP. Also, unknown scalar
6400 * offset where we would need to deal with min/max bounds is
6401 * currently prohibited for unprivileged.
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006402 */
6403 max = MAX_BPF_STACK + mask_to_left;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006404 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006405 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006406 case PTR_TO_MAP_VALUE:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006407 max = ptr_reg->map_ptr->value_size;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006408 ptr_limit = (mask_to_left ?
6409 ptr_reg->smin_value :
6410 ptr_reg->umax_value) + ptr_reg->off;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006411 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006412 default:
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006413 return REASON_TYPE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006414 }
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006415
6416 if (ptr_limit >= max)
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006417 return REASON_LIMIT;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006418 *alu_limit = ptr_limit;
6419 return 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006420}
6421
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006422static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6423 const struct bpf_insn *insn)
6424{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006425 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006426}
6427
6428static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6429 u32 alu_state, u32 alu_limit)
6430{
6431 /* If we arrived here from different branches with different
6432 * state or limits to sanitize, then this won't work.
6433 */
6434 if (aux->alu_state &&
6435 (aux->alu_state != alu_state ||
6436 aux->alu_limit != alu_limit))
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006437 return REASON_PATHS;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006438
Brendan Jackmane6ac5932021-02-17 10:45:09 +00006439 /* Corresponding fixup done in do_misc_fixups(). */
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006440 aux->alu_state = alu_state;
6441 aux->alu_limit = alu_limit;
6442 return 0;
6443}
6444
6445static int sanitize_val_alu(struct bpf_verifier_env *env,
6446 struct bpf_insn *insn)
6447{
6448 struct bpf_insn_aux_data *aux = cur_aux(env);
6449
6450 if (can_skip_alu_sanitation(env, insn))
6451 return 0;
6452
6453 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6454}
6455
Daniel Borkmannf5288192021-03-24 11:25:39 +01006456static bool sanitize_needed(u8 opcode)
6457{
6458 return opcode == BPF_ADD || opcode == BPF_SUB;
6459}
6460
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006461struct bpf_sanitize_info {
6462 struct bpf_insn_aux_data aux;
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006463 bool mask_to_left;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006464};
6465
Daniel Borkmann9183671a2021-05-28 15:47:32 +00006466static struct bpf_verifier_state *
6467sanitize_speculative_path(struct bpf_verifier_env *env,
6468 const struct bpf_insn *insn,
6469 u32 next_idx, u32 curr_idx)
6470{
6471 struct bpf_verifier_state *branch;
6472 struct bpf_reg_state *regs;
6473
6474 branch = push_stack(env, next_idx, curr_idx, true);
6475 if (branch && insn) {
6476 regs = branch->frame[branch->curframe]->regs;
6477 if (BPF_SRC(insn->code) == BPF_K) {
6478 mark_reg_unknown(env, regs, insn->dst_reg);
6479 } else if (BPF_SRC(insn->code) == BPF_X) {
6480 mark_reg_unknown(env, regs, insn->dst_reg);
6481 mark_reg_unknown(env, regs, insn->src_reg);
6482 }
6483 }
6484 return branch;
6485}
6486
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006487static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6488 struct bpf_insn *insn,
6489 const struct bpf_reg_state *ptr_reg,
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01006490 const struct bpf_reg_state *off_reg,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006491 struct bpf_reg_state *dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006492 struct bpf_sanitize_info *info,
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006493 const bool commit_window)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006494{
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006495 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006496 struct bpf_verifier_state *vstate = env->cur_state;
Daniel Borkmann801c6052021-04-29 15:19:37 +00006497 bool off_is_imm = tnum_is_const(off_reg->var_off);
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01006498 bool off_is_neg = off_reg->smin_value < 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006499 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6500 u8 opcode = BPF_OP(insn->code);
6501 u32 alu_state, alu_limit;
6502 struct bpf_reg_state tmp;
6503 bool ret;
Piotr Krysiukf2323262021-03-16 09:47:02 +01006504 int err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006505
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006506 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006507 return 0;
6508
6509 /* We already marked aux for masking from non-speculative
6510 * paths, thus we got here in the first place. We only care
6511 * to explore bad access from here.
6512 */
6513 if (vstate->speculative)
6514 goto do_sim;
6515
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006516 if (!commit_window) {
6517 if (!tnum_is_const(off_reg->var_off) &&
6518 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
6519 return REASON_BOUNDS;
6520
6521 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
6522 (opcode == BPF_SUB && !off_is_neg);
6523 }
6524
6525 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
Piotr Krysiukf2323262021-03-16 09:47:02 +01006526 if (err < 0)
6527 return err;
6528
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006529 if (commit_window) {
6530 /* In commit phase we narrow the masking window based on
6531 * the observed pointer move after the simulated operation.
6532 */
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006533 alu_state = info->aux.alu_state;
6534 alu_limit = abs(info->aux.alu_limit - alu_limit);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006535 } else {
6536 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
Daniel Borkmann801c6052021-04-29 15:19:37 +00006537 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006538 alu_state |= ptr_is_dst_reg ?
6539 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
Daniel Borkmanne042aa52021-07-16 09:18:21 +00006540
6541 /* Limit pruning on unknown scalars to enable deep search for
6542 * potential masking differences from other program paths.
6543 */
6544 if (!off_is_imm)
6545 env->explore_alu_limits = true;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006546 }
6547
Piotr Krysiukf2323262021-03-16 09:47:02 +01006548 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
6549 if (err < 0)
6550 return err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006551do_sim:
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006552 /* If we're in commit phase, we're done here given we already
6553 * pushed the truncated dst_reg into the speculative verification
6554 * stack.
Daniel Borkmanna7036192021-05-04 08:58:25 +00006555 *
6556 * Also, when register is a known constant, we rewrite register-based
6557 * operation to immediate-based, and thus do not need masking (and as
6558 * a consequence, do not need to simulate the zero-truncation either).
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006559 */
Daniel Borkmanna7036192021-05-04 08:58:25 +00006560 if (commit_window || off_is_imm)
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006561 return 0;
6562
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006563 /* Simulate and find potential out-of-bounds access under
6564 * speculative execution from truncation as a result of
6565 * masking when off was not within expected range. If off
6566 * sits in dst, then we temporarily need to move ptr there
6567 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6568 * for cases where we use K-based arithmetic in one direction
6569 * and truncated reg-based in the other in order to explore
6570 * bad access.
6571 */
6572 if (!ptr_is_dst_reg) {
6573 tmp = *dst_reg;
6574 *dst_reg = *ptr_reg;
6575 }
Daniel Borkmann9183671a2021-05-28 15:47:32 +00006576 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
6577 env->insn_idx);
Xu Yu08032782019-03-21 18:00:35 +08006578 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006579 *dst_reg = tmp;
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006580 return !ret ? REASON_STACK : 0;
6581}
6582
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +00006583static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
6584{
6585 struct bpf_verifier_state *vstate = env->cur_state;
6586
6587 /* If we simulate paths under speculation, we don't update the
6588 * insn as 'seen' such that when we verify unreachable paths in
6589 * the non-speculative domain, sanitize_dead_code() can still
6590 * rewrite/sanitize them.
6591 */
6592 if (!vstate->speculative)
6593 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
6594}
6595
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006596static int sanitize_err(struct bpf_verifier_env *env,
6597 const struct bpf_insn *insn, int reason,
6598 const struct bpf_reg_state *off_reg,
6599 const struct bpf_reg_state *dst_reg)
6600{
6601 static const char *err = "pointer arithmetic with it prohibited for !root";
6602 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
6603 u32 dst = insn->dst_reg, src = insn->src_reg;
6604
6605 switch (reason) {
6606 case REASON_BOUNDS:
6607 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
6608 off_reg == dst_reg ? dst : src, err);
6609 break;
6610 case REASON_TYPE:
6611 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
6612 off_reg == dst_reg ? src : dst, err);
6613 break;
6614 case REASON_PATHS:
6615 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
6616 dst, op, err);
6617 break;
6618 case REASON_LIMIT:
6619 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
6620 dst, op, err);
6621 break;
6622 case REASON_STACK:
6623 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
6624 dst, err);
6625 break;
6626 default:
6627 verbose(env, "verifier internal error: unknown reason (%d)\n",
6628 reason);
6629 break;
6630 }
6631
6632 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006633}
6634
Andrei Matei01f810a2021-02-06 20:10:24 -05006635/* check that stack access falls within stack limits and that 'reg' doesn't
6636 * have a variable offset.
6637 *
6638 * Variable offset is prohibited for unprivileged mode for simplicity since it
6639 * requires corresponding support in Spectre masking for stack ALU. See also
6640 * retrieve_ptr_limit().
6641 *
6642 *
6643 * 'off' includes 'reg->off'.
6644 */
6645static int check_stack_access_for_ptr_arithmetic(
6646 struct bpf_verifier_env *env,
6647 int regno,
6648 const struct bpf_reg_state *reg,
6649 int off)
6650{
6651 if (!tnum_is_const(reg->var_off)) {
6652 char tn_buf[48];
6653
6654 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6655 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6656 regno, tn_buf, off);
6657 return -EACCES;
6658 }
6659
6660 if (off >= 0 || off < -MAX_BPF_STACK) {
6661 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6662 "prohibited for !root; off=%d\n", regno, off);
6663 return -EACCES;
6664 }
6665
6666 return 0;
6667}
6668
Daniel Borkmann073815b2021-03-23 15:05:48 +01006669static int sanitize_check_bounds(struct bpf_verifier_env *env,
6670 const struct bpf_insn *insn,
6671 const struct bpf_reg_state *dst_reg)
6672{
6673 u32 dst = insn->dst_reg;
6674
6675 /* For unprivileged we require that resulting offset must be in bounds
6676 * in order to be able to sanitize access later on.
6677 */
6678 if (env->bypass_spec_v1)
6679 return 0;
6680
6681 switch (dst_reg->type) {
6682 case PTR_TO_STACK:
6683 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
6684 dst_reg->off + dst_reg->var_off.value))
6685 return -EACCES;
6686 break;
6687 case PTR_TO_MAP_VALUE:
6688 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
6689 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6690 "prohibited for !root\n", dst);
6691 return -EACCES;
6692 }
6693 break;
6694 default:
6695 break;
6696 }
6697
6698 return 0;
6699}
Andrei Matei01f810a2021-02-06 20:10:24 -05006700
Edward Creef1174f72017-08-07 15:26:19 +01006701/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01006702 * Caller should also handle BPF_MOV case separately.
6703 * If we return -EACCES, caller may want to try again treating pointer as a
6704 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6705 */
6706static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6707 struct bpf_insn *insn,
6708 const struct bpf_reg_state *ptr_reg,
6709 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04006710{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006711 struct bpf_verifier_state *vstate = env->cur_state;
6712 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6713 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006714 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01006715 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6716 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6717 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6718 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006719 struct bpf_sanitize_info info = {};
Josef Bacik48461132016-09-28 10:54:32 -04006720 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann24c109b2021-03-23 08:51:02 +01006721 u32 dst = insn->dst_reg;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006722 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04006723
Edward Creef1174f72017-08-07 15:26:19 +01006724 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04006725
Daniel Borkmann6f161012018-01-18 01:15:21 +01006726 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6727 smin_val > smax_val || umin_val > umax_val) {
6728 /* Taint dst register if offset had invalid bounds derived from
6729 * e.g. dead branches.
6730 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006731 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01006732 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04006733 }
6734
Edward Creef1174f72017-08-07 15:26:19 +01006735 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6736 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07006737 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6738 __mark_reg_unknown(env, dst_reg);
6739 return 0;
6740 }
6741
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006742 verbose(env,
6743 "R%d 32-bit pointer arithmetic prohibited\n",
6744 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006745 return -EACCES;
6746 }
David S. Millerd1174412017-05-10 11:22:52 -07006747
Joe Stringeraad2eea2018-10-02 13:35:30 -07006748 switch (ptr_reg->type) {
6749 case PTR_TO_MAP_VALUE_OR_NULL:
6750 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6751 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006752 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006753 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07006754 /* smin_val represents the known value */
6755 if (known && smin_val == 0 && opcode == BPF_ADD)
6756 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05006757 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006758 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07006759 case PTR_TO_SOCKET:
6760 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006761 case PTR_TO_SOCK_COMMON:
6762 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006763 case PTR_TO_TCP_SOCK:
6764 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07006765 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07006766 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6767 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006768 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006769 default:
6770 break;
Edward Creef1174f72017-08-07 15:26:19 +01006771 }
6772
6773 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6774 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04006775 */
Edward Creef1174f72017-08-07 15:26:19 +01006776 dst_reg->type = ptr_reg->type;
6777 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05006778
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006779 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6780 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6781 return -EINVAL;
6782
John Fastabend3f50f132020-03-30 14:36:39 -07006783 /* pointer types do not carry 32-bit bounds at the moment. */
6784 __mark_reg32_unbounded(dst_reg);
6785
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006786 if (sanitize_needed(opcode)) {
6787 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006788 &info, false);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006789 if (ret < 0)
6790 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006791 }
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006792
Josef Bacik48461132016-09-28 10:54:32 -04006793 switch (opcode) {
6794 case BPF_ADD:
Edward Creef1174f72017-08-07 15:26:19 +01006795 /* We can take a fixed offset as long as it doesn't overflow
6796 * the s32 'off' field
6797 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006798 if (known && (ptr_reg->off + smin_val ==
6799 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006800 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006801 dst_reg->smin_value = smin_ptr;
6802 dst_reg->smax_value = smax_ptr;
6803 dst_reg->umin_value = umin_ptr;
6804 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006805 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01006806 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006807 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006808 break;
6809 }
Edward Creef1174f72017-08-07 15:26:19 +01006810 /* A new variable offset is created. Note that off_reg->off
6811 * == 0, since it's a scalar.
6812 * dst_reg gets the pointer type and since some positive
6813 * integer value was added to the pointer, give it a new 'id'
6814 * if it's a PTR_TO_PACKET.
6815 * this creates a new 'base' pointer, off_reg (variable) gets
6816 * added into the variable offset, and we copy the fixed offset
6817 * from ptr_reg.
6818 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006819 if (signed_add_overflows(smin_ptr, smin_val) ||
6820 signed_add_overflows(smax_ptr, smax_val)) {
6821 dst_reg->smin_value = S64_MIN;
6822 dst_reg->smax_value = S64_MAX;
6823 } else {
6824 dst_reg->smin_value = smin_ptr + smin_val;
6825 dst_reg->smax_value = smax_ptr + smax_val;
6826 }
6827 if (umin_ptr + umin_val < umin_ptr ||
6828 umax_ptr + umax_val < umax_ptr) {
6829 dst_reg->umin_value = 0;
6830 dst_reg->umax_value = U64_MAX;
6831 } else {
6832 dst_reg->umin_value = umin_ptr + umin_val;
6833 dst_reg->umax_value = umax_ptr + umax_val;
6834 }
Edward Creef1174f72017-08-07 15:26:19 +01006835 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6836 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006837 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006838 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006839 dst_reg->id = ++env->id_gen;
6840 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006841 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006842 }
Josef Bacik48461132016-09-28 10:54:32 -04006843 break;
6844 case BPF_SUB:
Edward Creef1174f72017-08-07 15:26:19 +01006845 if (dst_reg == off_reg) {
6846 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006847 verbose(env, "R%d tried to subtract pointer from scalar\n",
6848 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006849 return -EACCES;
6850 }
6851 /* We don't allow subtraction from FP, because (according to
6852 * test_verifier.c test "invalid fp arithmetic", JITs might not
6853 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01006854 */
Edward Creef1174f72017-08-07 15:26:19 +01006855 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006856 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6857 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006858 return -EACCES;
6859 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006860 if (known && (ptr_reg->off - smin_val ==
6861 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006862 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006863 dst_reg->smin_value = smin_ptr;
6864 dst_reg->smax_value = smax_ptr;
6865 dst_reg->umin_value = umin_ptr;
6866 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006867 dst_reg->var_off = ptr_reg->var_off;
6868 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01006869 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006870 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006871 break;
6872 }
Edward Creef1174f72017-08-07 15:26:19 +01006873 /* A new variable offset is created. If the subtrahend is known
6874 * nonnegative, then any reg->range we had before is still good.
6875 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006876 if (signed_sub_overflows(smin_ptr, smax_val) ||
6877 signed_sub_overflows(smax_ptr, smin_val)) {
6878 /* Overflow possible, we know nothing */
6879 dst_reg->smin_value = S64_MIN;
6880 dst_reg->smax_value = S64_MAX;
6881 } else {
6882 dst_reg->smin_value = smin_ptr - smax_val;
6883 dst_reg->smax_value = smax_ptr - smin_val;
6884 }
6885 if (umin_ptr < umax_val) {
6886 /* Overflow possible, we know nothing */
6887 dst_reg->umin_value = 0;
6888 dst_reg->umax_value = U64_MAX;
6889 } else {
6890 /* Cannot overflow (as long as bounds are consistent) */
6891 dst_reg->umin_value = umin_ptr - umax_val;
6892 dst_reg->umax_value = umax_ptr - umin_val;
6893 }
Edward Creef1174f72017-08-07 15:26:19 +01006894 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6895 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006896 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006897 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006898 dst_reg->id = ++env->id_gen;
6899 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01006900 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006901 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006902 }
6903 break;
6904 case BPF_AND:
6905 case BPF_OR:
6906 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006907 /* bitwise ops on pointers are troublesome, prohibit. */
6908 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6909 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006910 return -EACCES;
6911 default:
6912 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006913 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6914 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006915 return -EACCES;
6916 }
6917
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006918 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6919 return -EINVAL;
6920
Edward Creeb03c9f92017-08-07 15:26:36 +01006921 __update_reg_bounds(dst_reg);
6922 __reg_deduce_bounds(dst_reg);
6923 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006924
Daniel Borkmann073815b2021-03-23 15:05:48 +01006925 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
6926 return -EACCES;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006927 if (sanitize_needed(opcode)) {
6928 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00006929 &info, true);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006930 if (ret < 0)
6931 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006932 }
6933
Edward Creef1174f72017-08-07 15:26:19 +01006934 return 0;
6935}
6936
John Fastabend3f50f132020-03-30 14:36:39 -07006937static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6938 struct bpf_reg_state *src_reg)
6939{
6940 s32 smin_val = src_reg->s32_min_value;
6941 s32 smax_val = src_reg->s32_max_value;
6942 u32 umin_val = src_reg->u32_min_value;
6943 u32 umax_val = src_reg->u32_max_value;
6944
6945 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6946 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6947 dst_reg->s32_min_value = S32_MIN;
6948 dst_reg->s32_max_value = S32_MAX;
6949 } else {
6950 dst_reg->s32_min_value += smin_val;
6951 dst_reg->s32_max_value += smax_val;
6952 }
6953 if (dst_reg->u32_min_value + umin_val < umin_val ||
6954 dst_reg->u32_max_value + umax_val < umax_val) {
6955 dst_reg->u32_min_value = 0;
6956 dst_reg->u32_max_value = U32_MAX;
6957 } else {
6958 dst_reg->u32_min_value += umin_val;
6959 dst_reg->u32_max_value += umax_val;
6960 }
6961}
6962
John Fastabend07cd2632020-03-24 10:38:15 -07006963static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6964 struct bpf_reg_state *src_reg)
6965{
6966 s64 smin_val = src_reg->smin_value;
6967 s64 smax_val = src_reg->smax_value;
6968 u64 umin_val = src_reg->umin_value;
6969 u64 umax_val = src_reg->umax_value;
6970
6971 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6972 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6973 dst_reg->smin_value = S64_MIN;
6974 dst_reg->smax_value = S64_MAX;
6975 } else {
6976 dst_reg->smin_value += smin_val;
6977 dst_reg->smax_value += smax_val;
6978 }
6979 if (dst_reg->umin_value + umin_val < umin_val ||
6980 dst_reg->umax_value + umax_val < umax_val) {
6981 dst_reg->umin_value = 0;
6982 dst_reg->umax_value = U64_MAX;
6983 } else {
6984 dst_reg->umin_value += umin_val;
6985 dst_reg->umax_value += umax_val;
6986 }
John Fastabend3f50f132020-03-30 14:36:39 -07006987}
6988
6989static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6990 struct bpf_reg_state *src_reg)
6991{
6992 s32 smin_val = src_reg->s32_min_value;
6993 s32 smax_val = src_reg->s32_max_value;
6994 u32 umin_val = src_reg->u32_min_value;
6995 u32 umax_val = src_reg->u32_max_value;
6996
6997 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6998 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6999 /* Overflow possible, we know nothing */
7000 dst_reg->s32_min_value = S32_MIN;
7001 dst_reg->s32_max_value = S32_MAX;
7002 } else {
7003 dst_reg->s32_min_value -= smax_val;
7004 dst_reg->s32_max_value -= smin_val;
7005 }
7006 if (dst_reg->u32_min_value < umax_val) {
7007 /* Overflow possible, we know nothing */
7008 dst_reg->u32_min_value = 0;
7009 dst_reg->u32_max_value = U32_MAX;
7010 } else {
7011 /* Cannot overflow (as long as bounds are consistent) */
7012 dst_reg->u32_min_value -= umax_val;
7013 dst_reg->u32_max_value -= umin_val;
7014 }
John Fastabend07cd2632020-03-24 10:38:15 -07007015}
7016
7017static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7018 struct bpf_reg_state *src_reg)
7019{
7020 s64 smin_val = src_reg->smin_value;
7021 s64 smax_val = src_reg->smax_value;
7022 u64 umin_val = src_reg->umin_value;
7023 u64 umax_val = src_reg->umax_value;
7024
7025 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7026 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7027 /* Overflow possible, we know nothing */
7028 dst_reg->smin_value = S64_MIN;
7029 dst_reg->smax_value = S64_MAX;
7030 } else {
7031 dst_reg->smin_value -= smax_val;
7032 dst_reg->smax_value -= smin_val;
7033 }
7034 if (dst_reg->umin_value < umax_val) {
7035 /* Overflow possible, we know nothing */
7036 dst_reg->umin_value = 0;
7037 dst_reg->umax_value = U64_MAX;
7038 } else {
7039 /* Cannot overflow (as long as bounds are consistent) */
7040 dst_reg->umin_value -= umax_val;
7041 dst_reg->umax_value -= umin_val;
7042 }
John Fastabend3f50f132020-03-30 14:36:39 -07007043}
7044
7045static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7046 struct bpf_reg_state *src_reg)
7047{
7048 s32 smin_val = src_reg->s32_min_value;
7049 u32 umin_val = src_reg->u32_min_value;
7050 u32 umax_val = src_reg->u32_max_value;
7051
7052 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7053 /* Ain't nobody got time to multiply that sign */
7054 __mark_reg32_unbounded(dst_reg);
7055 return;
7056 }
7057 /* Both values are positive, so we can work with unsigned and
7058 * copy the result to signed (unless it exceeds S32_MAX).
7059 */
7060 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7061 /* Potential overflow, we know nothing */
7062 __mark_reg32_unbounded(dst_reg);
7063 return;
7064 }
7065 dst_reg->u32_min_value *= umin_val;
7066 dst_reg->u32_max_value *= umax_val;
7067 if (dst_reg->u32_max_value > S32_MAX) {
7068 /* Overflow possible, we know nothing */
7069 dst_reg->s32_min_value = S32_MIN;
7070 dst_reg->s32_max_value = S32_MAX;
7071 } else {
7072 dst_reg->s32_min_value = dst_reg->u32_min_value;
7073 dst_reg->s32_max_value = dst_reg->u32_max_value;
7074 }
John Fastabend07cd2632020-03-24 10:38:15 -07007075}
7076
7077static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7078 struct bpf_reg_state *src_reg)
7079{
7080 s64 smin_val = src_reg->smin_value;
7081 u64 umin_val = src_reg->umin_value;
7082 u64 umax_val = src_reg->umax_value;
7083
John Fastabend07cd2632020-03-24 10:38:15 -07007084 if (smin_val < 0 || dst_reg->smin_value < 0) {
7085 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07007086 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007087 return;
7088 }
7089 /* Both values are positive, so we can work with unsigned and
7090 * copy the result to signed (unless it exceeds S64_MAX).
7091 */
7092 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7093 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07007094 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007095 return;
7096 }
7097 dst_reg->umin_value *= umin_val;
7098 dst_reg->umax_value *= umax_val;
7099 if (dst_reg->umax_value > S64_MAX) {
7100 /* Overflow possible, we know nothing */
7101 dst_reg->smin_value = S64_MIN;
7102 dst_reg->smax_value = S64_MAX;
7103 } else {
7104 dst_reg->smin_value = dst_reg->umin_value;
7105 dst_reg->smax_value = dst_reg->umax_value;
7106 }
7107}
7108
John Fastabend3f50f132020-03-30 14:36:39 -07007109static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7110 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007111{
John Fastabend3f50f132020-03-30 14:36:39 -07007112 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7113 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7114 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7115 s32 smin_val = src_reg->s32_min_value;
7116 u32 umax_val = src_reg->u32_max_value;
7117
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007118 if (src_known && dst_known) {
7119 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007120 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007121 }
John Fastabend07cd2632020-03-24 10:38:15 -07007122
7123 /* We get our minimum from the var_off, since that's inherently
7124 * bitwise. Our maximum is the minimum of the operands' maxima.
7125 */
John Fastabend3f50f132020-03-30 14:36:39 -07007126 dst_reg->u32_min_value = var32_off.value;
7127 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7128 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7129 /* Lose signed bounds when ANDing negative numbers,
7130 * ain't nobody got time for that.
7131 */
7132 dst_reg->s32_min_value = S32_MIN;
7133 dst_reg->s32_max_value = S32_MAX;
7134 } else {
7135 /* ANDing two positives gives a positive, so safe to
7136 * cast result into s64.
7137 */
7138 dst_reg->s32_min_value = dst_reg->u32_min_value;
7139 dst_reg->s32_max_value = dst_reg->u32_max_value;
7140 }
John Fastabend3f50f132020-03-30 14:36:39 -07007141}
7142
7143static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7144 struct bpf_reg_state *src_reg)
7145{
7146 bool src_known = tnum_is_const(src_reg->var_off);
7147 bool dst_known = tnum_is_const(dst_reg->var_off);
7148 s64 smin_val = src_reg->smin_value;
7149 u64 umax_val = src_reg->umax_value;
7150
7151 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007152 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007153 return;
7154 }
7155
7156 /* We get our minimum from the var_off, since that's inherently
7157 * bitwise. Our maximum is the minimum of the operands' maxima.
7158 */
John Fastabend07cd2632020-03-24 10:38:15 -07007159 dst_reg->umin_value = dst_reg->var_off.value;
7160 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7161 if (dst_reg->smin_value < 0 || smin_val < 0) {
7162 /* Lose signed bounds when ANDing negative numbers,
7163 * ain't nobody got time for that.
7164 */
7165 dst_reg->smin_value = S64_MIN;
7166 dst_reg->smax_value = S64_MAX;
7167 } else {
7168 /* ANDing two positives gives a positive, so safe to
7169 * cast result into s64.
7170 */
7171 dst_reg->smin_value = dst_reg->umin_value;
7172 dst_reg->smax_value = dst_reg->umax_value;
7173 }
7174 /* We may learn something more from the var_off */
7175 __update_reg_bounds(dst_reg);
7176}
7177
John Fastabend3f50f132020-03-30 14:36:39 -07007178static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7179 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007180{
John Fastabend3f50f132020-03-30 14:36:39 -07007181 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7182 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7183 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007184 s32 smin_val = src_reg->s32_min_value;
7185 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007186
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007187 if (src_known && dst_known) {
7188 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007189 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007190 }
John Fastabend07cd2632020-03-24 10:38:15 -07007191
7192 /* We get our maximum from the var_off, and our minimum is the
7193 * maximum of the operands' minima
7194 */
John Fastabend3f50f132020-03-30 14:36:39 -07007195 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7196 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7197 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7198 /* Lose signed bounds when ORing negative numbers,
7199 * ain't nobody got time for that.
7200 */
7201 dst_reg->s32_min_value = S32_MIN;
7202 dst_reg->s32_max_value = S32_MAX;
7203 } else {
7204 /* ORing two positives gives a positive, so safe to
7205 * cast result into s64.
7206 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007207 dst_reg->s32_min_value = dst_reg->u32_min_value;
7208 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007209 }
7210}
7211
7212static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7213 struct bpf_reg_state *src_reg)
7214{
7215 bool src_known = tnum_is_const(src_reg->var_off);
7216 bool dst_known = tnum_is_const(dst_reg->var_off);
7217 s64 smin_val = src_reg->smin_value;
7218 u64 umin_val = src_reg->umin_value;
7219
7220 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007221 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007222 return;
7223 }
7224
7225 /* We get our maximum from the var_off, and our minimum is the
7226 * maximum of the operands' minima
7227 */
John Fastabend07cd2632020-03-24 10:38:15 -07007228 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7229 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7230 if (dst_reg->smin_value < 0 || smin_val < 0) {
7231 /* Lose signed bounds when ORing negative numbers,
7232 * ain't nobody got time for that.
7233 */
7234 dst_reg->smin_value = S64_MIN;
7235 dst_reg->smax_value = S64_MAX;
7236 } else {
7237 /* ORing two positives gives a positive, so safe to
7238 * cast result into s64.
7239 */
7240 dst_reg->smin_value = dst_reg->umin_value;
7241 dst_reg->smax_value = dst_reg->umax_value;
7242 }
7243 /* We may learn something more from the var_off */
7244 __update_reg_bounds(dst_reg);
7245}
7246
Yonghong Song2921c902020-08-24 23:46:08 -07007247static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7248 struct bpf_reg_state *src_reg)
7249{
7250 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7251 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7252 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7253 s32 smin_val = src_reg->s32_min_value;
7254
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007255 if (src_known && dst_known) {
7256 __mark_reg32_known(dst_reg, var32_off.value);
Yonghong Song2921c902020-08-24 23:46:08 -07007257 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007258 }
Yonghong Song2921c902020-08-24 23:46:08 -07007259
7260 /* We get both minimum and maximum from the var32_off. */
7261 dst_reg->u32_min_value = var32_off.value;
7262 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7263
7264 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7265 /* XORing two positive sign numbers gives a positive,
7266 * so safe to cast u32 result into s32.
7267 */
7268 dst_reg->s32_min_value = dst_reg->u32_min_value;
7269 dst_reg->s32_max_value = dst_reg->u32_max_value;
7270 } else {
7271 dst_reg->s32_min_value = S32_MIN;
7272 dst_reg->s32_max_value = S32_MAX;
7273 }
7274}
7275
7276static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7277 struct bpf_reg_state *src_reg)
7278{
7279 bool src_known = tnum_is_const(src_reg->var_off);
7280 bool dst_known = tnum_is_const(dst_reg->var_off);
7281 s64 smin_val = src_reg->smin_value;
7282
7283 if (src_known && dst_known) {
7284 /* dst_reg->var_off.value has been updated earlier */
7285 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7286 return;
7287 }
7288
7289 /* We get both minimum and maximum from the var_off. */
7290 dst_reg->umin_value = dst_reg->var_off.value;
7291 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7292
7293 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7294 /* XORing two positive sign numbers gives a positive,
7295 * so safe to cast u64 result into s64.
7296 */
7297 dst_reg->smin_value = dst_reg->umin_value;
7298 dst_reg->smax_value = dst_reg->umax_value;
7299 } else {
7300 dst_reg->smin_value = S64_MIN;
7301 dst_reg->smax_value = S64_MAX;
7302 }
7303
7304 __update_reg_bounds(dst_reg);
7305}
7306
John Fastabend3f50f132020-03-30 14:36:39 -07007307static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7308 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07007309{
John Fastabend07cd2632020-03-24 10:38:15 -07007310 /* We lose all sign bit information (except what we can pick
7311 * up from var_off)
7312 */
John Fastabend3f50f132020-03-30 14:36:39 -07007313 dst_reg->s32_min_value = S32_MIN;
7314 dst_reg->s32_max_value = S32_MAX;
7315 /* If we might shift our top bit out, then we know nothing */
7316 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7317 dst_reg->u32_min_value = 0;
7318 dst_reg->u32_max_value = U32_MAX;
7319 } else {
7320 dst_reg->u32_min_value <<= umin_val;
7321 dst_reg->u32_max_value <<= umax_val;
7322 }
7323}
7324
7325static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7326 struct bpf_reg_state *src_reg)
7327{
7328 u32 umax_val = src_reg->u32_max_value;
7329 u32 umin_val = src_reg->u32_min_value;
7330 /* u32 alu operation will zext upper bits */
7331 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7332
7333 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7334 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7335 /* Not required but being careful mark reg64 bounds as unknown so
7336 * that we are forced to pick them up from tnum and zext later and
7337 * if some path skips this step we are still safe.
7338 */
7339 __mark_reg64_unbounded(dst_reg);
7340 __update_reg32_bounds(dst_reg);
7341}
7342
7343static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7344 u64 umin_val, u64 umax_val)
7345{
7346 /* Special case <<32 because it is a common compiler pattern to sign
7347 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7348 * positive we know this shift will also be positive so we can track
7349 * bounds correctly. Otherwise we lose all sign bit information except
7350 * what we can pick up from var_off. Perhaps we can generalize this
7351 * later to shifts of any length.
7352 */
7353 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7354 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7355 else
7356 dst_reg->smax_value = S64_MAX;
7357
7358 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7359 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7360 else
7361 dst_reg->smin_value = S64_MIN;
7362
John Fastabend07cd2632020-03-24 10:38:15 -07007363 /* If we might shift our top bit out, then we know nothing */
7364 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7365 dst_reg->umin_value = 0;
7366 dst_reg->umax_value = U64_MAX;
7367 } else {
7368 dst_reg->umin_value <<= umin_val;
7369 dst_reg->umax_value <<= umax_val;
7370 }
John Fastabend3f50f132020-03-30 14:36:39 -07007371}
7372
7373static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7374 struct bpf_reg_state *src_reg)
7375{
7376 u64 umax_val = src_reg->umax_value;
7377 u64 umin_val = src_reg->umin_value;
7378
7379 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7380 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7381 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7382
John Fastabend07cd2632020-03-24 10:38:15 -07007383 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7384 /* We may learn something more from the var_off */
7385 __update_reg_bounds(dst_reg);
7386}
7387
John Fastabend3f50f132020-03-30 14:36:39 -07007388static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7389 struct bpf_reg_state *src_reg)
7390{
7391 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7392 u32 umax_val = src_reg->u32_max_value;
7393 u32 umin_val = src_reg->u32_min_value;
7394
7395 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7396 * be negative, then either:
7397 * 1) src_reg might be zero, so the sign bit of the result is
7398 * unknown, so we lose our signed bounds
7399 * 2) it's known negative, thus the unsigned bounds capture the
7400 * signed bounds
7401 * 3) the signed bounds cross zero, so they tell us nothing
7402 * about the result
7403 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01007404 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07007405 * Thus, in all cases it suffices to blow away our signed bounds
7406 * and rely on inferring new ones from the unsigned bounds and
7407 * var_off of the result.
7408 */
7409 dst_reg->s32_min_value = S32_MIN;
7410 dst_reg->s32_max_value = S32_MAX;
7411
7412 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7413 dst_reg->u32_min_value >>= umax_val;
7414 dst_reg->u32_max_value >>= umin_val;
7415
7416 __mark_reg64_unbounded(dst_reg);
7417 __update_reg32_bounds(dst_reg);
7418}
7419
John Fastabend07cd2632020-03-24 10:38:15 -07007420static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7421 struct bpf_reg_state *src_reg)
7422{
7423 u64 umax_val = src_reg->umax_value;
7424 u64 umin_val = src_reg->umin_value;
7425
7426 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7427 * be negative, then either:
7428 * 1) src_reg might be zero, so the sign bit of the result is
7429 * unknown, so we lose our signed bounds
7430 * 2) it's known negative, thus the unsigned bounds capture the
7431 * signed bounds
7432 * 3) the signed bounds cross zero, so they tell us nothing
7433 * about the result
7434 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01007435 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07007436 * Thus, in all cases it suffices to blow away our signed bounds
7437 * and rely on inferring new ones from the unsigned bounds and
7438 * var_off of the result.
7439 */
7440 dst_reg->smin_value = S64_MIN;
7441 dst_reg->smax_value = S64_MAX;
7442 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
7443 dst_reg->umin_value >>= umax_val;
7444 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07007445
7446 /* Its not easy to operate on alu32 bounds here because it depends
7447 * on bits being shifted in. Take easy way out and mark unbounded
7448 * so we can recalculate later from tnum.
7449 */
7450 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007451 __update_reg_bounds(dst_reg);
7452}
7453
John Fastabend3f50f132020-03-30 14:36:39 -07007454static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
7455 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007456{
John Fastabend3f50f132020-03-30 14:36:39 -07007457 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07007458
7459 /* Upon reaching here, src_known is true and
7460 * umax_val is equal to umin_val.
7461 */
John Fastabend3f50f132020-03-30 14:36:39 -07007462 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
7463 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07007464
John Fastabend3f50f132020-03-30 14:36:39 -07007465 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
7466
7467 /* blow away the dst_reg umin_value/umax_value and rely on
7468 * dst_reg var_off to refine the result.
7469 */
7470 dst_reg->u32_min_value = 0;
7471 dst_reg->u32_max_value = U32_MAX;
7472
7473 __mark_reg64_unbounded(dst_reg);
7474 __update_reg32_bounds(dst_reg);
7475}
7476
7477static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
7478 struct bpf_reg_state *src_reg)
7479{
7480 u64 umin_val = src_reg->umin_value;
7481
7482 /* Upon reaching here, src_known is true and umax_val is equal
7483 * to umin_val.
7484 */
7485 dst_reg->smin_value >>= umin_val;
7486 dst_reg->smax_value >>= umin_val;
7487
7488 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07007489
7490 /* blow away the dst_reg umin_value/umax_value and rely on
7491 * dst_reg var_off to refine the result.
7492 */
7493 dst_reg->umin_value = 0;
7494 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07007495
7496 /* Its not easy to operate on alu32 bounds here because it depends
7497 * on bits being shifted in from upper 32-bits. Take easy way out
7498 * and mark unbounded so we can recalculate later from tnum.
7499 */
7500 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007501 __update_reg_bounds(dst_reg);
7502}
7503
Jann Horn468f6ea2017-12-18 20:11:56 -08007504/* WARNING: This function does calculations on 64-bit values, but the actual
7505 * execution may occur on 32-bit values. Therefore, things like bitshifts
7506 * need extra checks in the 32-bit case.
7507 */
Edward Creef1174f72017-08-07 15:26:19 +01007508static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
7509 struct bpf_insn *insn,
7510 struct bpf_reg_state *dst_reg,
7511 struct bpf_reg_state src_reg)
7512{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007513 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01007514 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08007515 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01007516 s64 smin_val, smax_val;
7517 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07007518 s32 s32_min_val, s32_max_val;
7519 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08007520 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
John Fastabend3f50f132020-03-30 14:36:39 -07007521 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007522 int ret;
Jann Hornb7992072018-10-05 18:17:59 +02007523
Edward Creeb03c9f92017-08-07 15:26:36 +01007524 smin_val = src_reg.smin_value;
7525 smax_val = src_reg.smax_value;
7526 umin_val = src_reg.umin_value;
7527 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01007528
John Fastabend3f50f132020-03-30 14:36:39 -07007529 s32_min_val = src_reg.s32_min_value;
7530 s32_max_val = src_reg.s32_max_value;
7531 u32_min_val = src_reg.u32_min_value;
7532 u32_max_val = src_reg.u32_max_value;
7533
7534 if (alu32) {
7535 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007536 if ((src_known &&
7537 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7538 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7539 /* Taint dst register if offset had invalid bounds
7540 * derived from e.g. dead branches.
7541 */
7542 __mark_reg_unknown(env, dst_reg);
7543 return 0;
7544 }
7545 } else {
7546 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007547 if ((src_known &&
7548 (smin_val != smax_val || umin_val != umax_val)) ||
7549 smin_val > smax_val || umin_val > umax_val) {
7550 /* Taint dst register if offset had invalid bounds
7551 * derived from e.g. dead branches.
7552 */
7553 __mark_reg_unknown(env, dst_reg);
7554 return 0;
7555 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01007556 }
7557
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007558 if (!src_known &&
7559 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007560 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007561 return 0;
7562 }
7563
Daniel Borkmannf5288192021-03-24 11:25:39 +01007564 if (sanitize_needed(opcode)) {
7565 ret = sanitize_val_alu(env, insn);
7566 if (ret < 0)
7567 return sanitize_err(env, insn, ret, NULL, NULL);
7568 }
7569
John Fastabend3f50f132020-03-30 14:36:39 -07007570 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7571 * There are two classes of instructions: The first class we track both
7572 * alu32 and alu64 sign/unsigned bounds independently this provides the
7573 * greatest amount of precision when alu operations are mixed with jmp32
7574 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7575 * and BPF_OR. This is possible because these ops have fairly easy to
7576 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7577 * See alu32 verifier tests for examples. The second class of
7578 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7579 * with regards to tracking sign/unsigned bounds because the bits may
7580 * cross subreg boundaries in the alu64 case. When this happens we mark
7581 * the reg unbounded in the subreg bound space and use the resulting
7582 * tnum to calculate an approximation of the sign/unsigned bounds.
7583 */
Edward Creef1174f72017-08-07 15:26:19 +01007584 switch (opcode) {
7585 case BPF_ADD:
John Fastabend3f50f132020-03-30 14:36:39 -07007586 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007587 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007588 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01007589 break;
7590 case BPF_SUB:
John Fastabend3f50f132020-03-30 14:36:39 -07007591 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007592 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007593 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04007594 break;
7595 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07007596 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7597 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007598 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007599 break;
7600 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07007601 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7602 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007603 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007604 break;
7605 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07007606 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7607 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007608 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007609 break;
Yonghong Song2921c902020-08-24 23:46:08 -07007610 case BPF_XOR:
7611 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7612 scalar32_min_max_xor(dst_reg, &src_reg);
7613 scalar_min_max_xor(dst_reg, &src_reg);
7614 break;
Josef Bacik48461132016-09-28 10:54:32 -04007615 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007616 if (umax_val >= insn_bitness) {
7617 /* Shifts greater than 31 or 63 are undefined.
7618 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007619 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007620 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007621 break;
7622 }
John Fastabend3f50f132020-03-30 14:36:39 -07007623 if (alu32)
7624 scalar32_min_max_lsh(dst_reg, &src_reg);
7625 else
7626 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007627 break;
7628 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007629 if (umax_val >= insn_bitness) {
7630 /* Shifts greater than 31 or 63 are undefined.
7631 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007632 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007633 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007634 break;
7635 }
John Fastabend3f50f132020-03-30 14:36:39 -07007636 if (alu32)
7637 scalar32_min_max_rsh(dst_reg, &src_reg);
7638 else
7639 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007640 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007641 case BPF_ARSH:
7642 if (umax_val >= insn_bitness) {
7643 /* Shifts greater than 31 or 63 are undefined.
7644 * This includes shifts by a negative number.
7645 */
7646 mark_reg_unknown(env, regs, insn->dst_reg);
7647 break;
7648 }
John Fastabend3f50f132020-03-30 14:36:39 -07007649 if (alu32)
7650 scalar32_min_max_arsh(dst_reg, &src_reg);
7651 else
7652 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007653 break;
Josef Bacik48461132016-09-28 10:54:32 -04007654 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007655 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007656 break;
7657 }
7658
John Fastabend3f50f132020-03-30 14:36:39 -07007659 /* ALU32 ops are zero extended into 64bit register */
7660 if (alu32)
7661 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08007662
John Fastabend294f2fc2020-03-24 10:38:37 -07007663 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01007664 __reg_deduce_bounds(dst_reg);
7665 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007666 return 0;
7667}
7668
7669/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7670 * and var_off.
7671 */
7672static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7673 struct bpf_insn *insn)
7674{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007675 struct bpf_verifier_state *vstate = env->cur_state;
7676 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7677 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01007678 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7679 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007680 int err;
Edward Creef1174f72017-08-07 15:26:19 +01007681
7682 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007683 src_reg = NULL;
7684 if (dst_reg->type != SCALAR_VALUE)
7685 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007686 else
7687 /* Make sure ID is cleared otherwise dst_reg min/max could be
7688 * incorrectly propagated into other registers by find_equal_scalars()
7689 */
7690 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007691 if (BPF_SRC(insn->code) == BPF_X) {
7692 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007693 if (src_reg->type != SCALAR_VALUE) {
7694 if (dst_reg->type != SCALAR_VALUE) {
7695 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007696 * an arbitrary scalar. Disallow all math except
7697 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01007698 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07007699 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007700 mark_reg_unknown(env, regs, insn->dst_reg);
7701 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01007702 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007703 verbose(env, "R%d pointer %s pointer prohibited\n",
7704 insn->dst_reg,
7705 bpf_alu_string[opcode >> 4]);
7706 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01007707 } else {
7708 /* scalar += pointer
7709 * This is legal, but we have to reverse our
7710 * src/dest handling in computing the range
7711 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007712 err = mark_chain_precision(env, insn->dst_reg);
7713 if (err)
7714 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007715 return adjust_ptr_min_max_vals(env, insn,
7716 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007717 }
7718 } else if (ptr_reg) {
7719 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007720 err = mark_chain_precision(env, insn->src_reg);
7721 if (err)
7722 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007723 return adjust_ptr_min_max_vals(env, insn,
7724 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007725 }
7726 } else {
7727 /* Pretend the src is a reg with a known value, since we only
7728 * need to be able to read from this state.
7729 */
7730 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007731 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01007732 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007733 if (ptr_reg) /* pointer += K */
7734 return adjust_ptr_min_max_vals(env, insn,
7735 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007736 }
7737
7738 /* Got here implies adding two SCALAR_VALUEs */
7739 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007740 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007741 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007742 return -EINVAL;
7743 }
7744 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007745 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007746 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007747 return -EINVAL;
7748 }
7749 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007750}
7751
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007752/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007753static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007754{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007755 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007756 u8 opcode = BPF_OP(insn->code);
7757 int err;
7758
7759 if (opcode == BPF_END || opcode == BPF_NEG) {
7760 if (opcode == BPF_NEG) {
7761 if (BPF_SRC(insn->code) != 0 ||
7762 insn->src_reg != BPF_REG_0 ||
7763 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007764 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007765 return -EINVAL;
7766 }
7767 } else {
7768 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01007769 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7770 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007771 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007772 return -EINVAL;
7773 }
7774 }
7775
7776 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007777 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007778 if (err)
7779 return err;
7780
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007781 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007782 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007783 insn->dst_reg);
7784 return -EACCES;
7785 }
7786
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007787 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007788 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007789 if (err)
7790 return err;
7791
7792 } else if (opcode == BPF_MOV) {
7793
7794 if (BPF_SRC(insn->code) == BPF_X) {
7795 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007796 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007797 return -EINVAL;
7798 }
7799
7800 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007801 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007802 if (err)
7803 return err;
7804 } else {
7805 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007806 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007807 return -EINVAL;
7808 }
7809 }
7810
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007811 /* check dest operand, mark as required later */
7812 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007813 if (err)
7814 return err;
7815
7816 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05007817 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7818 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7819
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007820 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7821 /* case: R1 = R2
7822 * copy register state to dest reg
7823 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07007824 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7825 /* Assign src and dst registers the same ID
7826 * that will be used by find_equal_scalars()
7827 * to propagate min/max range.
7828 */
7829 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05007830 *dst_reg = *src_reg;
7831 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007832 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007833 } else {
Edward Creef1174f72017-08-07 15:26:19 +01007834 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007835 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007836 verbose(env,
7837 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007838 insn->src_reg);
7839 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05007840 } else if (src_reg->type == SCALAR_VALUE) {
7841 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007842 /* Make sure ID is cleared otherwise
7843 * dst_reg min/max could be incorrectly
7844 * propagated into src_reg by find_equal_scalars()
7845 */
7846 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05007847 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007848 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05007849 } else {
7850 mark_reg_unknown(env, regs,
7851 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007852 }
John Fastabend3f50f132020-03-30 14:36:39 -07007853 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007854 }
7855 } else {
7856 /* case: R = imm
7857 * remember the value we stored into this reg
7858 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007859 /* clear any state __mark_reg_known doesn't set */
7860 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007861 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08007862 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7863 __mark_reg_known(regs + insn->dst_reg,
7864 insn->imm);
7865 } else {
7866 __mark_reg_known(regs + insn->dst_reg,
7867 (u32)insn->imm);
7868 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007869 }
7870
7871 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007872 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007873 return -EINVAL;
7874
7875 } else { /* all other ALU ops: and, sub, xor, add, ... */
7876
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007877 if (BPF_SRC(insn->code) == BPF_X) {
7878 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007879 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007880 return -EINVAL;
7881 }
7882 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007883 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007884 if (err)
7885 return err;
7886 } else {
7887 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007888 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007889 return -EINVAL;
7890 }
7891 }
7892
7893 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007894 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007895 if (err)
7896 return err;
7897
7898 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7899 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007900 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007901 return -EINVAL;
7902 }
7903
Rabin Vincent229394e82016-01-12 20:17:08 +01007904 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7905 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7906 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7907
7908 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007909 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01007910 return -EINVAL;
7911 }
7912 }
7913
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007914 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007915 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007916 if (err)
7917 return err;
7918
Edward Creef1174f72017-08-07 15:26:19 +01007919 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007920 }
7921
7922 return 0;
7923}
7924
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007925static void __find_good_pkt_pointers(struct bpf_func_state *state,
7926 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007927 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007928{
7929 struct bpf_reg_state *reg;
7930 int i;
7931
7932 for (i = 0; i < MAX_BPF_REG; i++) {
7933 reg = &state->regs[i];
7934 if (reg->type == type && reg->id == dst_reg->id)
7935 /* keep the maximum range already checked */
7936 reg->range = max(reg->range, new_range);
7937 }
7938
7939 bpf_for_each_spilled_reg(i, state, reg) {
7940 if (!reg)
7941 continue;
7942 if (reg->type == type && reg->id == dst_reg->id)
7943 reg->range = max(reg->range, new_range);
7944 }
7945}
7946
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007947static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007948 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01007949 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007950 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007951{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007952 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007953
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007954 if (dst_reg->off < 0 ||
7955 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01007956 /* This doesn't give us any range */
7957 return;
7958
Edward Creeb03c9f92017-08-07 15:26:36 +01007959 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7960 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01007961 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7962 * than pkt_end, but that's because it's also less than pkt.
7963 */
7964 return;
7965
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007966 new_range = dst_reg->off;
7967 if (range_right_open)
7968 new_range--;
7969
7970 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007971 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007972 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007973 *
7974 * r2 = r3;
7975 * r2 += 8;
7976 * if (r2 > pkt_end) goto <handle exception>
7977 * <access okay>
7978 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007979 * r2 = r3;
7980 * r2 += 8;
7981 * if (r2 < pkt_end) goto <access okay>
7982 * <handle exception>
7983 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007984 * Where:
7985 * r2 == dst_reg, pkt_end == src_reg
7986 * r2=pkt(id=n,off=8,r=0)
7987 * r3=pkt(id=n,off=0,r=0)
7988 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007989 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007990 *
7991 * r2 = r3;
7992 * r2 += 8;
7993 * if (pkt_end >= r2) goto <access okay>
7994 * <handle exception>
7995 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007996 * r2 = r3;
7997 * r2 += 8;
7998 * if (pkt_end <= r2) goto <handle exception>
7999 * <access okay>
8000 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008001 * Where:
8002 * pkt_end == dst_reg, r2 == src_reg
8003 * r2=pkt(id=n,off=8,r=0)
8004 * r3=pkt(id=n,off=0,r=0)
8005 *
8006 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008007 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8008 * and [r3, r3 + 8-1) respectively is safe to access depending on
8009 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008010 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008011
Edward Creef1174f72017-08-07 15:26:19 +01008012 /* If our ids match, then we must have the same max_value. And we
8013 * don't care about the other reg's fixed offset, since if it's too big
8014 * the range won't allow anything.
8015 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8016 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008017 for (i = 0; i <= vstate->curframe; i++)
8018 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8019 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008020}
8021
John Fastabend3f50f132020-03-30 14:36:39 -07008022static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008023{
John Fastabend3f50f132020-03-30 14:36:39 -07008024 struct tnum subreg = tnum_subreg(reg->var_off);
8025 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008026
John Fastabend3f50f132020-03-30 14:36:39 -07008027 switch (opcode) {
8028 case BPF_JEQ:
8029 if (tnum_is_const(subreg))
8030 return !!tnum_equals_const(subreg, val);
8031 break;
8032 case BPF_JNE:
8033 if (tnum_is_const(subreg))
8034 return !tnum_equals_const(subreg, val);
8035 break;
8036 case BPF_JSET:
8037 if ((~subreg.mask & subreg.value) & val)
8038 return 1;
8039 if (!((subreg.mask | subreg.value) & val))
8040 return 0;
8041 break;
8042 case BPF_JGT:
8043 if (reg->u32_min_value > val)
8044 return 1;
8045 else if (reg->u32_max_value <= val)
8046 return 0;
8047 break;
8048 case BPF_JSGT:
8049 if (reg->s32_min_value > sval)
8050 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008051 else if (reg->s32_max_value <= sval)
John Fastabend3f50f132020-03-30 14:36:39 -07008052 return 0;
8053 break;
8054 case BPF_JLT:
8055 if (reg->u32_max_value < val)
8056 return 1;
8057 else if (reg->u32_min_value >= val)
8058 return 0;
8059 break;
8060 case BPF_JSLT:
8061 if (reg->s32_max_value < sval)
8062 return 1;
8063 else if (reg->s32_min_value >= sval)
8064 return 0;
8065 break;
8066 case BPF_JGE:
8067 if (reg->u32_min_value >= val)
8068 return 1;
8069 else if (reg->u32_max_value < val)
8070 return 0;
8071 break;
8072 case BPF_JSGE:
8073 if (reg->s32_min_value >= sval)
8074 return 1;
8075 else if (reg->s32_max_value < sval)
8076 return 0;
8077 break;
8078 case BPF_JLE:
8079 if (reg->u32_max_value <= val)
8080 return 1;
8081 else if (reg->u32_min_value > val)
8082 return 0;
8083 break;
8084 case BPF_JSLE:
8085 if (reg->s32_max_value <= sval)
8086 return 1;
8087 else if (reg->s32_min_value > sval)
8088 return 0;
8089 break;
Jiong Wang092ed092019-01-26 12:26:01 -05008090 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05008091
John Fastabend3f50f132020-03-30 14:36:39 -07008092 return -1;
8093}
8094
8095
8096static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8097{
8098 s64 sval = (s64)val;
8099
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008100 switch (opcode) {
8101 case BPF_JEQ:
8102 if (tnum_is_const(reg->var_off))
8103 return !!tnum_equals_const(reg->var_off, val);
8104 break;
8105 case BPF_JNE:
8106 if (tnum_is_const(reg->var_off))
8107 return !tnum_equals_const(reg->var_off, val);
8108 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08008109 case BPF_JSET:
8110 if ((~reg->var_off.mask & reg->var_off.value) & val)
8111 return 1;
8112 if (!((reg->var_off.mask | reg->var_off.value) & val))
8113 return 0;
8114 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008115 case BPF_JGT:
8116 if (reg->umin_value > val)
8117 return 1;
8118 else if (reg->umax_value <= val)
8119 return 0;
8120 break;
8121 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008122 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008123 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008124 else if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008125 return 0;
8126 break;
8127 case BPF_JLT:
8128 if (reg->umax_value < val)
8129 return 1;
8130 else if (reg->umin_value >= val)
8131 return 0;
8132 break;
8133 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008134 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008135 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008136 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008137 return 0;
8138 break;
8139 case BPF_JGE:
8140 if (reg->umin_value >= val)
8141 return 1;
8142 else if (reg->umax_value < val)
8143 return 0;
8144 break;
8145 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008146 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008147 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008148 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008149 return 0;
8150 break;
8151 case BPF_JLE:
8152 if (reg->umax_value <= val)
8153 return 1;
8154 else if (reg->umin_value > val)
8155 return 0;
8156 break;
8157 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008158 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008159 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008160 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008161 return 0;
8162 break;
8163 }
8164
8165 return -1;
8166}
8167
John Fastabend3f50f132020-03-30 14:36:39 -07008168/* compute branch direction of the expression "if (reg opcode val) goto target;"
8169 * and return:
8170 * 1 - branch will be taken and "goto target" will be executed
8171 * 0 - branch will not be taken and fall-through to next insn
8172 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8173 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05008174 */
John Fastabend3f50f132020-03-30 14:36:39 -07008175static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8176 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05008177{
John Fastabendcac616d2020-05-21 13:07:26 -07008178 if (__is_pointer_value(false, reg)) {
8179 if (!reg_type_not_null(reg->type))
8180 return -1;
8181
8182 /* If pointer is valid tests against zero will fail so we can
8183 * use this to direct branch taken.
8184 */
8185 if (val != 0)
8186 return -1;
8187
8188 switch (opcode) {
8189 case BPF_JEQ:
8190 return 0;
8191 case BPF_JNE:
8192 return 1;
8193 default:
8194 return -1;
8195 }
8196 }
Jiong Wang092ed092019-01-26 12:26:01 -05008197
John Fastabend3f50f132020-03-30 14:36:39 -07008198 if (is_jmp32)
8199 return is_branch32_taken(reg, val, opcode);
8200 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02008201}
8202
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008203static int flip_opcode(u32 opcode)
8204{
8205 /* How can we transform "a <op> b" into "b <op> a"? */
8206 static const u8 opcode_flip[16] = {
8207 /* these stay the same */
8208 [BPF_JEQ >> 4] = BPF_JEQ,
8209 [BPF_JNE >> 4] = BPF_JNE,
8210 [BPF_JSET >> 4] = BPF_JSET,
8211 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8212 [BPF_JGE >> 4] = BPF_JLE,
8213 [BPF_JGT >> 4] = BPF_JLT,
8214 [BPF_JLE >> 4] = BPF_JGE,
8215 [BPF_JLT >> 4] = BPF_JGT,
8216 [BPF_JSGE >> 4] = BPF_JSLE,
8217 [BPF_JSGT >> 4] = BPF_JSLT,
8218 [BPF_JSLE >> 4] = BPF_JSGE,
8219 [BPF_JSLT >> 4] = BPF_JSGT
8220 };
8221 return opcode_flip[opcode >> 4];
8222}
8223
8224static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8225 struct bpf_reg_state *src_reg,
8226 u8 opcode)
8227{
8228 struct bpf_reg_state *pkt;
8229
8230 if (src_reg->type == PTR_TO_PACKET_END) {
8231 pkt = dst_reg;
8232 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8233 pkt = src_reg;
8234 opcode = flip_opcode(opcode);
8235 } else {
8236 return -1;
8237 }
8238
8239 if (pkt->range >= 0)
8240 return -1;
8241
8242 switch (opcode) {
8243 case BPF_JLE:
8244 /* pkt <= pkt_end */
8245 fallthrough;
8246 case BPF_JGT:
8247 /* pkt > pkt_end */
8248 if (pkt->range == BEYOND_PKT_END)
8249 /* pkt has at last one extra byte beyond pkt_end */
8250 return opcode == BPF_JGT;
8251 break;
8252 case BPF_JLT:
8253 /* pkt < pkt_end */
8254 fallthrough;
8255 case BPF_JGE:
8256 /* pkt >= pkt_end */
8257 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8258 return opcode == BPF_JGE;
8259 break;
8260 }
8261 return -1;
8262}
8263
Josef Bacik48461132016-09-28 10:54:32 -04008264/* Adjusts the register min/max values in the case that the dst_reg is the
8265 * variable register that we are working on, and src_reg is a constant or we're
8266 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01008267 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04008268 */
8269static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008270 struct bpf_reg_state *false_reg,
8271 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05008272 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04008273{
John Fastabend3f50f132020-03-30 14:36:39 -07008274 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8275 struct tnum false_64off = false_reg->var_off;
8276 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8277 struct tnum true_64off = true_reg->var_off;
8278 s64 sval = (s64)val;
8279 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008280
Edward Creef1174f72017-08-07 15:26:19 +01008281 /* If the dst_reg is a pointer, we can't learn anything about its
8282 * variable offset from the compare (unless src_reg were a pointer into
8283 * the same object, but we don't bother with that.
8284 * Since false_reg and true_reg have the same type by construction, we
8285 * only need to check one of them for pointerness.
8286 */
8287 if (__is_pointer_value(false, false_reg))
8288 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02008289
Josef Bacik48461132016-09-28 10:54:32 -04008290 switch (opcode) {
8291 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04008292 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008293 {
8294 struct bpf_reg_state *reg =
8295 opcode == BPF_JEQ ? true_reg : false_reg;
8296
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008297 /* JEQ/JNE comparison doesn't change the register equivalence.
8298 * r1 = r2;
8299 * if (r1 == 42) goto label;
8300 * ...
8301 * label: // here both r1 and r2 are known to be 42.
8302 *
8303 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04008304 */
John Fastabend3f50f132020-03-30 14:36:39 -07008305 if (is_jmp32)
8306 __mark_reg32_known(reg, val32);
8307 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008308 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04008309 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008310 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008311 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07008312 if (is_jmp32) {
8313 false_32off = tnum_and(false_32off, tnum_const(~val32));
8314 if (is_power_of_2(val32))
8315 true_32off = tnum_or(true_32off,
8316 tnum_const(val32));
8317 } else {
8318 false_64off = tnum_and(false_64off, tnum_const(~val));
8319 if (is_power_of_2(val))
8320 true_64off = tnum_or(true_64off,
8321 tnum_const(val));
8322 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008323 break;
Josef Bacik48461132016-09-28 10:54:32 -04008324 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008325 case BPF_JGT:
8326 {
John Fastabend3f50f132020-03-30 14:36:39 -07008327 if (is_jmp32) {
8328 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8329 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8330
8331 false_reg->u32_max_value = min(false_reg->u32_max_value,
8332 false_umax);
8333 true_reg->u32_min_value = max(true_reg->u32_min_value,
8334 true_umin);
8335 } else {
8336 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8337 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8338
8339 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8340 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8341 }
Edward Creeb03c9f92017-08-07 15:26:36 +01008342 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008343 }
Josef Bacik48461132016-09-28 10:54:32 -04008344 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008345 case BPF_JSGT:
8346 {
John Fastabend3f50f132020-03-30 14:36:39 -07008347 if (is_jmp32) {
8348 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8349 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008350
John Fastabend3f50f132020-03-30 14:36:39 -07008351 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8352 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8353 } else {
8354 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8355 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8356
8357 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8358 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8359 }
Josef Bacik48461132016-09-28 10:54:32 -04008360 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008361 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008362 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008363 case BPF_JLT:
8364 {
John Fastabend3f50f132020-03-30 14:36:39 -07008365 if (is_jmp32) {
8366 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8367 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8368
8369 false_reg->u32_min_value = max(false_reg->u32_min_value,
8370 false_umin);
8371 true_reg->u32_max_value = min(true_reg->u32_max_value,
8372 true_umax);
8373 } else {
8374 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8375 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8376
8377 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8378 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8379 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008380 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008381 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008382 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008383 case BPF_JSLT:
8384 {
John Fastabend3f50f132020-03-30 14:36:39 -07008385 if (is_jmp32) {
8386 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8387 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008388
John Fastabend3f50f132020-03-30 14:36:39 -07008389 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8390 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8391 } else {
8392 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8393 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8394
8395 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8396 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8397 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008398 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008399 }
Josef Bacik48461132016-09-28 10:54:32 -04008400 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02008401 return;
Josef Bacik48461132016-09-28 10:54:32 -04008402 }
8403
John Fastabend3f50f132020-03-30 14:36:39 -07008404 if (is_jmp32) {
8405 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8406 tnum_subreg(false_32off));
8407 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8408 tnum_subreg(true_32off));
8409 __reg_combine_32_into_64(false_reg);
8410 __reg_combine_32_into_64(true_reg);
8411 } else {
8412 false_reg->var_off = false_64off;
8413 true_reg->var_off = true_64off;
8414 __reg_combine_64_into_32(false_reg);
8415 __reg_combine_64_into_32(true_reg);
8416 }
Josef Bacik48461132016-09-28 10:54:32 -04008417}
8418
Edward Creef1174f72017-08-07 15:26:19 +01008419/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8420 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04008421 */
8422static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008423 struct bpf_reg_state *false_reg,
8424 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05008425 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04008426{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008427 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02008428 /* This uses zero as "not present in table"; luckily the zero opcode,
8429 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01008430 */
Jann Horn0fc31b12020-03-30 18:03:24 +02008431 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07008432 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01008433}
8434
8435/* Regs are known to be equal, so intersect their min/max/var_off */
8436static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
8437 struct bpf_reg_state *dst_reg)
8438{
Edward Creeb03c9f92017-08-07 15:26:36 +01008439 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
8440 dst_reg->umin_value);
8441 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
8442 dst_reg->umax_value);
8443 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
8444 dst_reg->smin_value);
8445 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
8446 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01008447 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
8448 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01008449 /* We might have learned new bounds from the var_off. */
8450 __update_reg_bounds(src_reg);
8451 __update_reg_bounds(dst_reg);
8452 /* We might have learned something about the sign bit. */
8453 __reg_deduce_bounds(src_reg);
8454 __reg_deduce_bounds(dst_reg);
8455 /* We might have learned some bits from the bounds. */
8456 __reg_bound_offset(src_reg);
8457 __reg_bound_offset(dst_reg);
8458 /* Intersecting with the old var_off might have improved our bounds
8459 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
8460 * then new var_off is (0; 0x7f...fc) which improves our umax.
8461 */
8462 __update_reg_bounds(src_reg);
8463 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008464}
8465
8466static void reg_combine_min_max(struct bpf_reg_state *true_src,
8467 struct bpf_reg_state *true_dst,
8468 struct bpf_reg_state *false_src,
8469 struct bpf_reg_state *false_dst,
8470 u8 opcode)
8471{
8472 switch (opcode) {
8473 case BPF_JEQ:
8474 __reg_combine_min_max(true_src, true_dst);
8475 break;
8476 case BPF_JNE:
8477 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01008478 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02008479 }
Josef Bacik48461132016-09-28 10:54:32 -04008480}
8481
Joe Stringerfd978bf72018-10-02 13:35:35 -07008482static void mark_ptr_or_null_reg(struct bpf_func_state *state,
8483 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07008484 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02008485{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07008486 if (reg_type_may_be_null(reg->type) && reg->id == id &&
8487 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01008488 /* Old offset (both fixed and variable parts) should
8489 * have been known-zero, because we don't allow pointer
8490 * arithmetic on pointers that might be NULL.
8491 */
Edward Creeb03c9f92017-08-07 15:26:36 +01008492 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
8493 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01008494 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01008495 __mark_reg_known_zero(reg);
8496 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01008497 }
8498 if (is_null) {
8499 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008500 /* We don't need id and ref_obj_id from this point
8501 * onwards anymore, thus we should better reset it,
8502 * so that state pruning has chances to take effect.
8503 */
8504 reg->id = 0;
8505 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04008506
8507 return;
8508 }
8509
8510 mark_ptr_not_null_reg(reg);
8511
8512 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008513 /* For not-NULL ptr, reg->ref_obj_id will be reset
8514 * in release_reg_references().
8515 *
8516 * reg->id is still used by spin_lock ptr. Other
8517 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07008518 */
8519 reg->id = 0;
8520 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02008521 }
8522}
8523
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008524static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8525 bool is_null)
8526{
8527 struct bpf_reg_state *reg;
8528 int i;
8529
8530 for (i = 0; i < MAX_BPF_REG; i++)
8531 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8532
8533 bpf_for_each_spilled_reg(i, state, reg) {
8534 if (!reg)
8535 continue;
8536 mark_ptr_or_null_reg(state, reg, id, is_null);
8537 }
8538}
8539
Thomas Graf57a09bf2016-10-18 19:51:19 +02008540/* The logic is similar to find_good_pkt_pointers(), both could eventually
8541 * be folded together at some point.
8542 */
Joe Stringer840b9612018-10-02 13:35:32 -07008543static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8544 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02008545{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008546 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008547 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008548 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01008549 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008550 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02008551
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008552 if (ref_obj_id && ref_obj_id == id && is_null)
8553 /* regs[regno] is in the " == NULL" branch.
8554 * No one could have freed the reference state before
8555 * doing the NULL check.
8556 */
8557 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07008558
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008559 for (i = 0; i <= vstate->curframe; i++)
8560 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02008561}
8562
Daniel Borkmann5beca082017-11-01 23:58:10 +01008563static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8564 struct bpf_reg_state *dst_reg,
8565 struct bpf_reg_state *src_reg,
8566 struct bpf_verifier_state *this_branch,
8567 struct bpf_verifier_state *other_branch)
8568{
8569 if (BPF_SRC(insn->code) != BPF_X)
8570 return false;
8571
Jiong Wang092ed092019-01-26 12:26:01 -05008572 /* Pointers are always 64-bit. */
8573 if (BPF_CLASS(insn->code) == BPF_JMP32)
8574 return false;
8575
Daniel Borkmann5beca082017-11-01 23:58:10 +01008576 switch (BPF_OP(insn->code)) {
8577 case BPF_JGT:
8578 if ((dst_reg->type == PTR_TO_PACKET &&
8579 src_reg->type == PTR_TO_PACKET_END) ||
8580 (dst_reg->type == PTR_TO_PACKET_META &&
8581 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8582 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8583 find_good_pkt_pointers(this_branch, dst_reg,
8584 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008585 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008586 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8587 src_reg->type == PTR_TO_PACKET) ||
8588 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8589 src_reg->type == PTR_TO_PACKET_META)) {
8590 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8591 find_good_pkt_pointers(other_branch, src_reg,
8592 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008593 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008594 } else {
8595 return false;
8596 }
8597 break;
8598 case BPF_JLT:
8599 if ((dst_reg->type == PTR_TO_PACKET &&
8600 src_reg->type == PTR_TO_PACKET_END) ||
8601 (dst_reg->type == PTR_TO_PACKET_META &&
8602 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8603 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8604 find_good_pkt_pointers(other_branch, dst_reg,
8605 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008606 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008607 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8608 src_reg->type == PTR_TO_PACKET) ||
8609 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8610 src_reg->type == PTR_TO_PACKET_META)) {
8611 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8612 find_good_pkt_pointers(this_branch, src_reg,
8613 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008614 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008615 } else {
8616 return false;
8617 }
8618 break;
8619 case BPF_JGE:
8620 if ((dst_reg->type == PTR_TO_PACKET &&
8621 src_reg->type == PTR_TO_PACKET_END) ||
8622 (dst_reg->type == PTR_TO_PACKET_META &&
8623 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8624 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8625 find_good_pkt_pointers(this_branch, dst_reg,
8626 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008627 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008628 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8629 src_reg->type == PTR_TO_PACKET) ||
8630 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8631 src_reg->type == PTR_TO_PACKET_META)) {
8632 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8633 find_good_pkt_pointers(other_branch, src_reg,
8634 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008635 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008636 } else {
8637 return false;
8638 }
8639 break;
8640 case BPF_JLE:
8641 if ((dst_reg->type == PTR_TO_PACKET &&
8642 src_reg->type == PTR_TO_PACKET_END) ||
8643 (dst_reg->type == PTR_TO_PACKET_META &&
8644 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8645 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8646 find_good_pkt_pointers(other_branch, dst_reg,
8647 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008648 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008649 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8650 src_reg->type == PTR_TO_PACKET) ||
8651 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8652 src_reg->type == PTR_TO_PACKET_META)) {
8653 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8654 find_good_pkt_pointers(this_branch, src_reg,
8655 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008656 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008657 } else {
8658 return false;
8659 }
8660 break;
8661 default:
8662 return false;
8663 }
8664
8665 return true;
8666}
8667
Alexei Starovoitov75748832020-10-08 18:12:37 -07008668static void find_equal_scalars(struct bpf_verifier_state *vstate,
8669 struct bpf_reg_state *known_reg)
8670{
8671 struct bpf_func_state *state;
8672 struct bpf_reg_state *reg;
8673 int i, j;
8674
8675 for (i = 0; i <= vstate->curframe; i++) {
8676 state = vstate->frame[i];
8677 for (j = 0; j < MAX_BPF_REG; j++) {
8678 reg = &state->regs[j];
8679 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8680 *reg = *known_reg;
8681 }
8682
8683 bpf_for_each_spilled_reg(j, state, reg) {
8684 if (!reg)
8685 continue;
8686 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8687 *reg = *known_reg;
8688 }
8689 }
8690}
8691
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008692static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008693 struct bpf_insn *insn, int *insn_idx)
8694{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008695 struct bpf_verifier_state *this_branch = env->cur_state;
8696 struct bpf_verifier_state *other_branch;
8697 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008698 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008699 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05008700 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008701 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008702 int err;
8703
Jiong Wang092ed092019-01-26 12:26:01 -05008704 /* Only conditional jumps are expected to reach here. */
8705 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8706 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008707 return -EINVAL;
8708 }
8709
8710 if (BPF_SRC(insn->code) == BPF_X) {
8711 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008712 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008713 return -EINVAL;
8714 }
8715
8716 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008717 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008718 if (err)
8719 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008720
8721 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008722 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008723 insn->src_reg);
8724 return -EACCES;
8725 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008726 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008727 } else {
8728 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008729 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008730 return -EINVAL;
8731 }
8732 }
8733
8734 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008735 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008736 if (err)
8737 return err;
8738
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008739 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008740 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008741
John Fastabend3f50f132020-03-30 14:36:39 -07008742 if (BPF_SRC(insn->code) == BPF_K) {
8743 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8744 } else if (src_reg->type == SCALAR_VALUE &&
8745 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8746 pred = is_branch_taken(dst_reg,
8747 tnum_subreg(src_reg->var_off).value,
8748 opcode,
8749 is_jmp32);
8750 } else if (src_reg->type == SCALAR_VALUE &&
8751 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8752 pred = is_branch_taken(dst_reg,
8753 src_reg->var_off.value,
8754 opcode,
8755 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008756 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8757 reg_is_pkt_pointer_any(src_reg) &&
8758 !is_jmp32) {
8759 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07008760 }
8761
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008762 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07008763 /* If we get here with a dst_reg pointer type it is because
8764 * above is_branch_taken() special cased the 0 comparison.
8765 */
8766 if (!__is_pointer_value(false, dst_reg))
8767 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008768 if (BPF_SRC(insn->code) == BPF_X && !err &&
8769 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008770 err = mark_chain_precision(env, insn->src_reg);
8771 if (err)
8772 return err;
8773 }
Daniel Borkmann9183671a2021-05-28 15:47:32 +00008774
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008775 if (pred == 1) {
Daniel Borkmann9183671a2021-05-28 15:47:32 +00008776 /* Only follow the goto, ignore fall-through. If needed, push
8777 * the fall-through branch for simulation under speculative
8778 * execution.
8779 */
8780 if (!env->bypass_spec_v1 &&
8781 !sanitize_speculative_path(env, insn, *insn_idx + 1,
8782 *insn_idx))
8783 return -EFAULT;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008784 *insn_idx += insn->off;
8785 return 0;
8786 } else if (pred == 0) {
Daniel Borkmann9183671a2021-05-28 15:47:32 +00008787 /* Only follow the fall-through branch, since that's where the
8788 * program will go. If needed, push the goto branch for
8789 * simulation under speculative execution.
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008790 */
Daniel Borkmann9183671a2021-05-28 15:47:32 +00008791 if (!env->bypass_spec_v1 &&
8792 !sanitize_speculative_path(env, insn,
8793 *insn_idx + insn->off + 1,
8794 *insn_idx))
8795 return -EFAULT;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008796 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008797 }
8798
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008799 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8800 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008801 if (!other_branch)
8802 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008803 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008804
Josef Bacik48461132016-09-28 10:54:32 -04008805 /* detect if we are comparing against a constant value so we can adjust
8806 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01008807 * this is only legit if both are scalars (or pointers to the same
8808 * object, I suppose, but we don't support that right now), because
8809 * otherwise the different base pointers mean the offsets aren't
8810 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04008811 */
8812 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05008813 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008814
Edward Creef1174f72017-08-07 15:26:19 +01008815 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05008816 src_reg->type == SCALAR_VALUE) {
8817 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008818 (is_jmp32 &&
8819 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008820 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008821 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008822 src_reg->var_off.value,
8823 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008824 opcode, is_jmp32);
8825 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008826 (is_jmp32 &&
8827 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008828 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008829 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008830 dst_reg->var_off.value,
8831 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008832 opcode, is_jmp32);
8833 else if (!is_jmp32 &&
8834 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01008835 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008836 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8837 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008838 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008839 if (src_reg->id &&
8840 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008841 find_equal_scalars(this_branch, src_reg);
8842 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8843 }
8844
Edward Creef1174f72017-08-07 15:26:19 +01008845 }
8846 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008847 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07008848 dst_reg, insn->imm, (u32)insn->imm,
8849 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04008850 }
8851
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008852 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8853 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008854 find_equal_scalars(this_branch, dst_reg);
8855 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8856 }
8857
Jiong Wang092ed092019-01-26 12:26:01 -05008858 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8859 * NOTE: these optimizations below are related with pointer comparison
8860 * which will never be JMP32.
8861 */
8862 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008863 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07008864 reg_type_may_be_null(dst_reg->type)) {
8865 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02008866 * safe or unknown depending R == 0 or R != 0 conditional.
8867 */
Joe Stringer840b9612018-10-02 13:35:32 -07008868 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8869 opcode == BPF_JNE);
8870 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8871 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008872 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8873 this_branch, other_branch) &&
8874 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008875 verbose(env, "R%d pointer comparison prohibited\n",
8876 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008877 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008878 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008879 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008880 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008881 return 0;
8882}
8883
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008884/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008885static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008886{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008887 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008888 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07008889 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008890 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008891 int err;
8892
8893 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008894 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008895 return -EINVAL;
8896 }
8897 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008898 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008899 return -EINVAL;
8900 }
8901
Edward Creedc503a82017-08-15 20:34:35 +01008902 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008903 if (err)
8904 return err;
8905
Hao Luo4976b712020-09-29 16:50:44 -07008906 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01008907 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01008908 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8909
Hao Luo4976b712020-09-29 16:50:44 -07008910 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008911 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008912 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01008913 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008914
Hao Luo4976b712020-09-29 16:50:44 -07008915 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8916 mark_reg_known_zero(env, regs, insn->dst_reg);
8917
8918 dst_reg->type = aux->btf_var.reg_type;
8919 switch (dst_reg->type) {
8920 case PTR_TO_MEM:
8921 dst_reg->mem_size = aux->btf_var.mem_size;
8922 break;
8923 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07008924 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08008925 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07008926 dst_reg->btf_id = aux->btf_var.btf_id;
8927 break;
8928 default:
8929 verbose(env, "bpf verifier is misconfigured\n");
8930 return -EFAULT;
8931 }
8932 return 0;
8933 }
8934
Yonghong Song69c087b2021-02-26 12:49:25 -08008935 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8936 struct bpf_prog_aux *aux = env->prog->aux;
8937 u32 subprogno = insn[1].imm;
8938
8939 if (!aux->func_info) {
8940 verbose(env, "missing btf func_info\n");
8941 return -EINVAL;
8942 }
8943 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8944 verbose(env, "callback function not static\n");
8945 return -EINVAL;
8946 }
8947
8948 dst_reg->type = PTR_TO_FUNC;
8949 dst_reg->subprogno = subprogno;
8950 return 0;
8951 }
8952
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008953 map = env->used_maps[aux->map_index];
8954 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07008955 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008956
Alexei Starovoitov387544b2021-05-13 17:36:10 -07008957 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
8958 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07008959 dst_reg->type = PTR_TO_MAP_VALUE;
8960 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008961 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07008962 dst_reg->id = ++env->id_gen;
Alexei Starovoitov387544b2021-05-13 17:36:10 -07008963 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
8964 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
Hao Luo4976b712020-09-29 16:50:44 -07008965 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008966 } else {
8967 verbose(env, "bpf verifier is misconfigured\n");
8968 return -EINVAL;
8969 }
8970
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008971 return 0;
8972}
8973
Daniel Borkmann96be4322015-03-01 12:31:46 +01008974static bool may_access_skb(enum bpf_prog_type type)
8975{
8976 switch (type) {
8977 case BPF_PROG_TYPE_SOCKET_FILTER:
8978 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01008979 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01008980 return true;
8981 default:
8982 return false;
8983 }
8984}
8985
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008986/* verify safety of LD_ABS|LD_IND instructions:
8987 * - they can only appear in the programs where ctx == skb
8988 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8989 * preserve R6-R9, and store return value into R0
8990 *
8991 * Implicit input:
8992 * ctx == skb == R6 == CTX
8993 *
8994 * Explicit input:
8995 * SRC == any register
8996 * IMM == 32-bit immediate
8997 *
8998 * Output:
8999 * R0 - 8/16/32-bit skb data converted to cpu endianness
9000 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009001static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009002{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009003 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009004 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009005 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009006 int i, err;
9007
Udip Pant7e407812020-08-25 16:20:00 -07009008 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009009 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009010 return -EINVAL;
9011 }
9012
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02009013 if (!env->ops->gen_ld_abs) {
9014 verbose(env, "bpf verifier is misconfigured\n");
9015 return -EINVAL;
9016 }
9017
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009018 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07009019 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009020 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009021 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009022 return -EINVAL;
9023 }
9024
9025 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009026 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009027 if (err)
9028 return err;
9029
Joe Stringerfd978bf72018-10-02 13:35:35 -07009030 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9031 * gen_ld_abs() may terminate the program at runtime, leading to
9032 * reference leak.
9033 */
9034 err = check_reference_leak(env);
9035 if (err) {
9036 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9037 return err;
9038 }
9039
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009040 if (env->cur_state->active_spin_lock) {
9041 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9042 return -EINVAL;
9043 }
9044
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009045 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009046 verbose(env,
9047 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009048 return -EINVAL;
9049 }
9050
9051 if (mode == BPF_IND) {
9052 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01009053 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009054 if (err)
9055 return err;
9056 }
9057
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009058 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9059 if (err < 0)
9060 return err;
9061
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009062 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01009063 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009064 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009065 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9066 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009067
9068 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01009069 * the value fetched from the packet.
9070 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009071 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009072 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01009073 /* ld_abs load up to 32-bit skb data. */
9074 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009075 return 0;
9076}
9077
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009078static int check_return_code(struct bpf_verifier_env *env)
9079{
brakmo5cf1e912019-05-28 16:59:36 -07009080 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009081 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009082 struct bpf_reg_state *reg;
9083 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07009084 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009085 int err;
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009086 const bool is_subprog = env->cur_state->frame[0]->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009087
KP Singh9e4e01d2020-03-29 01:43:52 +01009088 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009089 if (!is_subprog &&
9090 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07009091 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009092 !prog->aux->attach_func_proto->type)
9093 return 0;
9094
Zhen Lei8fb33b62021-05-25 10:56:59 +08009095 /* eBPF calling convention is such that R0 is used
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009096 * to return the value from eBPF program.
9097 * Make sure that it's readable at this time
9098 * of bpf_exit, which means that program wrote
9099 * something into it earlier
9100 */
9101 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9102 if (err)
9103 return err;
9104
9105 if (is_pointer_value(env, BPF_REG_0)) {
9106 verbose(env, "R0 leaks addr as return value\n");
9107 return -EACCES;
9108 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009109
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009110 reg = cur_regs(env) + BPF_REG_0;
9111 if (is_subprog) {
9112 if (reg->type != SCALAR_VALUE) {
9113 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9114 reg_type_str[reg->type]);
9115 return -EINVAL;
9116 }
9117 return 0;
9118 }
9119
Udip Pant7e407812020-08-25 16:20:00 -07009120 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02009121 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9122 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02009123 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9124 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9125 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9126 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9127 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02009128 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08009129 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9130 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9131 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009132 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009133 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07009134 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9135 range = tnum_range(0, 3);
9136 enforce_attach_type_range = tnum_range(2, 3);
9137 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009138 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009139 case BPF_PROG_TYPE_CGROUP_SOCK:
9140 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05009141 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08009142 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07009143 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009144 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07009145 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9146 if (!env->prog->aux->attach_btf_id)
9147 return 0;
9148 range = tnum_const(0);
9149 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07009150 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07009151 switch (env->prog->expected_attach_type) {
9152 case BPF_TRACE_FENTRY:
9153 case BPF_TRACE_FEXIT:
9154 range = tnum_const(0);
9155 break;
9156 case BPF_TRACE_RAW_TP:
9157 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07009158 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02009159 case BPF_TRACE_ITER:
9160 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009161 default:
9162 return -ENOTSUPP;
9163 }
Yonghong Song15d83c42020-05-09 10:59:00 -07009164 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02009165 case BPF_PROG_TYPE_SK_LOOKUP:
9166 range = tnum_range(SK_DROP, SK_PASS);
9167 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009168 case BPF_PROG_TYPE_EXT:
9169 /* freplace program can return anything as its return value
9170 * depends on the to-be-replaced kernel func or bpf program.
9171 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009172 default:
9173 return 0;
9174 }
9175
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009176 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009177 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009178 reg_type_str[reg->type]);
9179 return -EINVAL;
9180 }
9181
9182 if (!tnum_in(range, reg->var_off)) {
Yonghong Songbc2591d2021-02-26 12:49:22 -08009183 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009184 return -EINVAL;
9185 }
brakmo5cf1e912019-05-28 16:59:36 -07009186
9187 if (!tnum_is_unknown(enforce_attach_type_range) &&
9188 tnum_in(enforce_attach_type_range, reg->var_off))
9189 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009190 return 0;
9191}
9192
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009193/* non-recursive DFS pseudo code
9194 * 1 procedure DFS-iterative(G,v):
9195 * 2 label v as discovered
9196 * 3 let S be a stack
9197 * 4 S.push(v)
9198 * 5 while S is not empty
9199 * 6 t <- S.pop()
9200 * 7 if t is what we're looking for:
9201 * 8 return t
9202 * 9 for all edges e in G.adjacentEdges(t) do
9203 * 10 if edge e is already labelled
9204 * 11 continue with the next edge
9205 * 12 w <- G.adjacentVertex(t,e)
9206 * 13 if vertex w is not discovered and not explored
9207 * 14 label e as tree-edge
9208 * 15 label w as discovered
9209 * 16 S.push(w)
9210 * 17 continue at 5
9211 * 18 else if vertex w is discovered
9212 * 19 label e as back-edge
9213 * 20 else
9214 * 21 // vertex w is explored
9215 * 22 label e as forward- or cross-edge
9216 * 23 label t as explored
9217 * 24 S.pop()
9218 *
9219 * convention:
9220 * 0x10 - discovered
9221 * 0x11 - discovered and fall-through edge labelled
9222 * 0x12 - discovered and fall-through and branch edges labelled
9223 * 0x20 - explored
9224 */
9225
9226enum {
9227 DISCOVERED = 0x10,
9228 EXPLORED = 0x20,
9229 FALLTHROUGH = 1,
9230 BRANCH = 2,
9231};
9232
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009233static u32 state_htab_size(struct bpf_verifier_env *env)
9234{
9235 return env->prog->len;
9236}
9237
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009238static struct bpf_verifier_state_list **explored_state(
9239 struct bpf_verifier_env *env,
9240 int idx)
9241{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009242 struct bpf_verifier_state *cur = env->cur_state;
9243 struct bpf_func_state *state = cur->frame[cur->curframe];
9244
9245 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009246}
9247
9248static void init_explored_state(struct bpf_verifier_env *env, int idx)
9249{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009250 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009251}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009252
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009253enum {
9254 DONE_EXPLORING = 0,
9255 KEEP_EXPLORING = 1,
9256};
9257
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009258/* t, w, e - match pseudo-code above:
9259 * t - index of current instruction
9260 * w - next instruction
9261 * e - edge
9262 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07009263static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9264 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009265{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009266 int *insn_stack = env->cfg.insn_stack;
9267 int *insn_state = env->cfg.insn_state;
9268
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009269 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009270 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009271
9272 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009273 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009274
9275 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e842018-12-13 10:41:48 -08009276 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009277 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009278 return -EINVAL;
9279 }
9280
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009281 if (e == BRANCH)
9282 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009283 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009284
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009285 if (insn_state[w] == 0) {
9286 /* tree-edge */
9287 insn_state[t] = DISCOVERED | e;
9288 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009289 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009290 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009291 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009292 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009293 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009294 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009295 return DONE_EXPLORING;
Martin KaFai Laud9762e842018-12-13 10:41:48 -08009296 verbose_linfo(env, t, "%d: ", t);
9297 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009298 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009299 return -EINVAL;
9300 } else if (insn_state[w] == EXPLORED) {
9301 /* forward- or cross-edge */
9302 insn_state[t] = DISCOVERED | e;
9303 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009304 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009305 return -EFAULT;
9306 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009307 return DONE_EXPLORING;
9308}
9309
Yonghong Songefdb22d2021-02-26 12:49:20 -08009310static int visit_func_call_insn(int t, int insn_cnt,
9311 struct bpf_insn *insns,
9312 struct bpf_verifier_env *env,
9313 bool visit_callee)
9314{
9315 int ret;
9316
9317 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9318 if (ret)
9319 return ret;
9320
9321 if (t + 1 < insn_cnt)
9322 init_explored_state(env, t + 1);
9323 if (visit_callee) {
9324 init_explored_state(env, t);
9325 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
9326 env, false);
9327 }
9328 return ret;
9329}
9330
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009331/* Visits the instruction at index t and returns one of the following:
9332 * < 0 - an error occurred
9333 * DONE_EXPLORING - the instruction was fully explored
9334 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9335 */
9336static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9337{
9338 struct bpf_insn *insns = env->prog->insnsi;
9339 int ret;
9340
Yonghong Song69c087b2021-02-26 12:49:25 -08009341 if (bpf_pseudo_func(insns + t))
9342 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9343
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009344 /* All non-branch instructions have a single fall-through edge. */
9345 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9346 BPF_CLASS(insns[t].code) != BPF_JMP32)
9347 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9348
9349 switch (BPF_OP(insns[t].code)) {
9350 case BPF_EXIT:
9351 return DONE_EXPLORING;
9352
9353 case BPF_CALL:
Yonghong Songefdb22d2021-02-26 12:49:20 -08009354 return visit_func_call_insn(t, insn_cnt, insns, env,
9355 insns[t].src_reg == BPF_PSEUDO_CALL);
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009356
9357 case BPF_JA:
9358 if (BPF_SRC(insns[t].code) != BPF_K)
9359 return -EINVAL;
9360
9361 /* unconditional jump with single edge */
9362 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9363 true);
9364 if (ret)
9365 return ret;
9366
9367 /* unconditional jmp is not a good pruning point,
9368 * but it's marked, since backtracking needs
9369 * to record jmp history in is_state_visited().
9370 */
9371 init_explored_state(env, t + insns[t].off + 1);
9372 /* tell verifier to check for equivalent states
9373 * after every call and jump
9374 */
9375 if (t + 1 < insn_cnt)
9376 init_explored_state(env, t + 1);
9377
9378 return ret;
9379
9380 default:
9381 /* conditional jump with two edges */
9382 init_explored_state(env, t);
9383 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9384 if (ret)
9385 return ret;
9386
9387 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9388 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009389}
9390
9391/* non-recursive depth-first-search to detect loops in BPF program
9392 * loop == back-edge in directed graph
9393 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009394static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009395{
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009396 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009397 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009398 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009399 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009400
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009401 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009402 if (!insn_state)
9403 return -ENOMEM;
9404
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009405 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009406 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07009407 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009408 return -ENOMEM;
9409 }
9410
9411 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
9412 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009413 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009414
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009415 while (env->cfg.cur_stack > 0) {
9416 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009417
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009418 ret = visit_insn(t, insn_cnt, env);
9419 switch (ret) {
9420 case DONE_EXPLORING:
9421 insn_state[t] = EXPLORED;
9422 env->cfg.cur_stack--;
9423 break;
9424 case KEEP_EXPLORING:
9425 break;
9426 default:
9427 if (ret > 0) {
9428 verbose(env, "visit_insn internal bug\n");
9429 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08009430 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009431 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009432 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009433 }
9434
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009435 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009436 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009437 ret = -EFAULT;
9438 goto err_free;
9439 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009440
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009441 for (i = 0; i < insn_cnt; i++) {
9442 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009443 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009444 ret = -EINVAL;
9445 goto err_free;
9446 }
9447 }
9448 ret = 0; /* cfg looks good */
9449
9450err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07009451 kvfree(insn_state);
9452 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009453 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009454 return ret;
9455}
9456
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009457static int check_abnormal_return(struct bpf_verifier_env *env)
9458{
9459 int i;
9460
9461 for (i = 1; i < env->subprog_cnt; i++) {
9462 if (env->subprog_info[i].has_ld_abs) {
9463 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
9464 return -EINVAL;
9465 }
9466 if (env->subprog_info[i].has_tail_call) {
9467 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
9468 return -EINVAL;
9469 }
9470 }
9471 return 0;
9472}
9473
Yonghong Song838e9692018-11-19 15:29:11 -08009474/* The minimum supported BTF func info size */
9475#define MIN_BPF_FUNCINFO_SIZE 8
9476#define MAX_FUNCINFO_REC_SIZE 252
9477
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009478static int check_btf_func(struct bpf_verifier_env *env,
9479 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009480 bpfptr_t uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08009481{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009482 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b2818e2019-01-16 10:43:01 -08009483 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08009484 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009485 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009486 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009487 struct bpf_prog *prog;
9488 const struct btf *btf;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009489 bpfptr_t urecord;
Peter Oskolkovd0b2818e2019-01-16 10:43:01 -08009490 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009491 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03009492 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08009493
9494 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009495 if (!nfuncs) {
9496 if (check_abnormal_return(env))
9497 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08009498 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009499 }
Yonghong Song838e9692018-11-19 15:29:11 -08009500
9501 if (nfuncs != env->subprog_cnt) {
9502 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
9503 return -EINVAL;
9504 }
9505
9506 urec_size = attr->func_info_rec_size;
9507 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
9508 urec_size > MAX_FUNCINFO_REC_SIZE ||
9509 urec_size % sizeof(u32)) {
9510 verbose(env, "invalid func info rec size %u\n", urec_size);
9511 return -EINVAL;
9512 }
9513
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009514 prog = env->prog;
9515 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08009516
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009517 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
Yonghong Song838e9692018-11-19 15:29:11 -08009518 min_size = min_t(u32, krec_size, urec_size);
9519
Yonghong Songba64e7d2018-11-24 23:20:44 -08009520 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009521 if (!krecord)
9522 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009523 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
9524 if (!info_aux)
9525 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009526
Yonghong Song838e9692018-11-19 15:29:11 -08009527 for (i = 0; i < nfuncs; i++) {
9528 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
9529 if (ret) {
9530 if (ret == -E2BIG) {
9531 verbose(env, "nonzero tailing record in func info");
9532 /* set the size kernel expects so loader can zero
9533 * out the rest of the record.
9534 */
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009535 if (copy_to_bpfptr_offset(uattr,
9536 offsetof(union bpf_attr, func_info_rec_size),
9537 &min_size, sizeof(min_size)))
Yonghong Song838e9692018-11-19 15:29:11 -08009538 ret = -EFAULT;
9539 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009540 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009541 }
9542
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009543 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009544 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009545 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009546 }
9547
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009548 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009549 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08009550 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009551 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009552 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009553 "nonzero insn_off %u for the first func info record",
9554 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009555 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009556 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009557 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08009558 verbose(env,
9559 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009560 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009561 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009562 }
9563
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009564 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009565 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009566 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009567 }
9568
9569 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08009570 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009571 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009572 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08009573 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009574 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009575 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009576 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009577
9578 func_proto = btf_type_by_id(btf, type->type);
9579 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9580 /* btf_func_check() already verified it during BTF load */
9581 goto err_free;
9582 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9583 scalar_return =
9584 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9585 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9586 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9587 goto err_free;
9588 }
9589 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9590 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9591 goto err_free;
9592 }
9593
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009594 prev_offset = krecord[i].insn_off;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009595 bpfptr_add(&urecord, urec_size);
Yonghong Song838e9692018-11-19 15:29:11 -08009596 }
9597
Yonghong Songba64e7d2018-11-24 23:20:44 -08009598 prog->aux->func_info = krecord;
9599 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009600 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08009601 return 0;
9602
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009603err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08009604 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009605 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08009606 return ret;
9607}
9608
Yonghong Songba64e7d2018-11-24 23:20:44 -08009609static void adjust_btf_func(struct bpf_verifier_env *env)
9610{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009611 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009612 int i;
9613
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009614 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08009615 return;
9616
9617 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009618 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009619}
9620
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009621#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9622 sizeof(((struct bpf_line_info *)(0))->line_col))
9623#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9624
9625static int check_btf_line(struct bpf_verifier_env *env,
9626 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009627 bpfptr_t uattr)
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009628{
9629 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9630 struct bpf_subprog_info *sub;
9631 struct bpf_line_info *linfo;
9632 struct bpf_prog *prog;
9633 const struct btf *btf;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009634 bpfptr_t ulinfo;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009635 int err;
9636
9637 nr_linfo = attr->line_info_cnt;
9638 if (!nr_linfo)
9639 return 0;
9640
9641 rec_size = attr->line_info_rec_size;
9642 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9643 rec_size > MAX_LINEINFO_REC_SIZE ||
9644 rec_size & (sizeof(u32) - 1))
9645 return -EINVAL;
9646
9647 /* Need to zero it in case the userspace may
9648 * pass in a smaller bpf_line_info object.
9649 */
9650 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9651 GFP_KERNEL | __GFP_NOWARN);
9652 if (!linfo)
9653 return -ENOMEM;
9654
9655 prog = env->prog;
9656 btf = prog->aux->btf;
9657
9658 s = 0;
9659 sub = env->subprog_info;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009660 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009661 expected_size = sizeof(struct bpf_line_info);
9662 ncopy = min_t(u32, expected_size, rec_size);
9663 for (i = 0; i < nr_linfo; i++) {
9664 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9665 if (err) {
9666 if (err == -E2BIG) {
9667 verbose(env, "nonzero tailing record in line_info");
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009668 if (copy_to_bpfptr_offset(uattr,
9669 offsetof(union bpf_attr, line_info_rec_size),
9670 &expected_size, sizeof(expected_size)))
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009671 err = -EFAULT;
9672 }
9673 goto err_free;
9674 }
9675
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009676 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009677 err = -EFAULT;
9678 goto err_free;
9679 }
9680
9681 /*
9682 * Check insn_off to ensure
9683 * 1) strictly increasing AND
9684 * 2) bounded by prog->len
9685 *
9686 * The linfo[0].insn_off == 0 check logically falls into
9687 * the later "missing bpf_line_info for func..." case
9688 * because the first linfo[0].insn_off must be the
9689 * first sub also and the first sub must have
9690 * subprog_info[0].start == 0.
9691 */
9692 if ((i && linfo[i].insn_off <= prev_offset) ||
9693 linfo[i].insn_off >= prog->len) {
9694 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9695 i, linfo[i].insn_off, prev_offset,
9696 prog->len);
9697 err = -EINVAL;
9698 goto err_free;
9699 }
9700
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08009701 if (!prog->insnsi[linfo[i].insn_off].code) {
9702 verbose(env,
9703 "Invalid insn code at line_info[%u].insn_off\n",
9704 i);
9705 err = -EINVAL;
9706 goto err_free;
9707 }
9708
Martin KaFai Lau23127b32018-12-13 10:41:46 -08009709 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9710 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009711 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9712 err = -EINVAL;
9713 goto err_free;
9714 }
9715
9716 if (s != env->subprog_cnt) {
9717 if (linfo[i].insn_off == sub[s].start) {
9718 sub[s].linfo_idx = i;
9719 s++;
9720 } else if (sub[s].start < linfo[i].insn_off) {
9721 verbose(env, "missing bpf_line_info for func#%u\n", s);
9722 err = -EINVAL;
9723 goto err_free;
9724 }
9725 }
9726
9727 prev_offset = linfo[i].insn_off;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009728 bpfptr_add(&ulinfo, rec_size);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009729 }
9730
9731 if (s != env->subprog_cnt) {
9732 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9733 env->subprog_cnt - s, s);
9734 err = -EINVAL;
9735 goto err_free;
9736 }
9737
9738 prog->aux->linfo = linfo;
9739 prog->aux->nr_linfo = nr_linfo;
9740
9741 return 0;
9742
9743err_free:
9744 kvfree(linfo);
9745 return err;
9746}
9747
9748static int check_btf_info(struct bpf_verifier_env *env,
9749 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -07009750 bpfptr_t uattr)
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009751{
9752 struct btf *btf;
9753 int err;
9754
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009755 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9756 if (check_abnormal_return(env))
9757 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009758 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009759 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009760
9761 btf = btf_get_by_fd(attr->prog_btf_fd);
9762 if (IS_ERR(btf))
9763 return PTR_ERR(btf);
Alexei Starovoitov350a5c42021-03-07 14:52:48 -08009764 if (btf_is_kernel(btf)) {
9765 btf_put(btf);
9766 return -EACCES;
9767 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009768 env->prog->aux->btf = btf;
9769
9770 err = check_btf_func(env, attr, uattr);
9771 if (err)
9772 return err;
9773
9774 err = check_btf_line(env, attr, uattr);
9775 if (err)
9776 return err;
9777
9778 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009779}
9780
Edward Creef1174f72017-08-07 15:26:19 +01009781/* check %cur's range satisfies %old's */
9782static bool range_within(struct bpf_reg_state *old,
9783 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009784{
Edward Creeb03c9f92017-08-07 15:26:36 +01009785 return old->umin_value <= cur->umin_value &&
9786 old->umax_value >= cur->umax_value &&
9787 old->smin_value <= cur->smin_value &&
Daniel Borkmannfd675184f2021-02-05 20:48:21 +01009788 old->smax_value >= cur->smax_value &&
9789 old->u32_min_value <= cur->u32_min_value &&
9790 old->u32_max_value >= cur->u32_max_value &&
9791 old->s32_min_value <= cur->s32_min_value &&
9792 old->s32_max_value >= cur->s32_max_value;
Edward Creef1174f72017-08-07 15:26:19 +01009793}
9794
Edward Creef1174f72017-08-07 15:26:19 +01009795/* If in the old state two registers had the same id, then they need to have
9796 * the same id in the new state as well. But that id could be different from
9797 * the old state, so we need to track the mapping from old to new ids.
9798 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9799 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9800 * regs with a different old id could still have new id 9, we don't care about
9801 * that.
9802 * So we look through our idmap to see if this old id has been seen before. If
9803 * so, we require the new id to match; otherwise, we add the id pair to the map.
9804 */
Lorenz Bauerc9e73e32021-04-29 14:46:56 +01009805static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009806{
9807 unsigned int i;
9808
Lorenz Bauerc9e73e32021-04-29 14:46:56 +01009809 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
Edward Creef1174f72017-08-07 15:26:19 +01009810 if (!idmap[i].old) {
9811 /* Reached an empty slot; haven't seen this id before */
9812 idmap[i].old = old_id;
9813 idmap[i].cur = cur_id;
9814 return true;
9815 }
9816 if (idmap[i].old == old_id)
9817 return idmap[i].cur == cur_id;
9818 }
9819 /* We ran out of idmap slots, which should be impossible */
9820 WARN_ON_ONCE(1);
9821 return false;
9822}
9823
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009824static void clean_func_state(struct bpf_verifier_env *env,
9825 struct bpf_func_state *st)
9826{
9827 enum bpf_reg_liveness live;
9828 int i, j;
9829
9830 for (i = 0; i < BPF_REG_FP; i++) {
9831 live = st->regs[i].live;
9832 /* liveness must not touch this register anymore */
9833 st->regs[i].live |= REG_LIVE_DONE;
9834 if (!(live & REG_LIVE_READ))
9835 /* since the register is unused, clear its state
9836 * to make further comparison simpler
9837 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009838 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009839 }
9840
9841 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9842 live = st->stack[i].spilled_ptr.live;
9843 /* liveness must not touch this stack slot anymore */
9844 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9845 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009846 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009847 for (j = 0; j < BPF_REG_SIZE; j++)
9848 st->stack[i].slot_type[j] = STACK_INVALID;
9849 }
9850 }
9851}
9852
9853static void clean_verifier_state(struct bpf_verifier_env *env,
9854 struct bpf_verifier_state *st)
9855{
9856 int i;
9857
9858 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9859 /* all regs in this state in all frames were already marked */
9860 return;
9861
9862 for (i = 0; i <= st->curframe; i++)
9863 clean_func_state(env, st->frame[i]);
9864}
9865
9866/* the parentage chains form a tree.
9867 * the verifier states are added to state lists at given insn and
9868 * pushed into state stack for future exploration.
9869 * when the verifier reaches bpf_exit insn some of the verifer states
9870 * stored in the state lists have their final liveness state already,
9871 * but a lot of states will get revised from liveness point of view when
9872 * the verifier explores other branches.
9873 * Example:
9874 * 1: r0 = 1
9875 * 2: if r1 == 100 goto pc+1
9876 * 3: r0 = 2
9877 * 4: exit
9878 * when the verifier reaches exit insn the register r0 in the state list of
9879 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9880 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9881 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9882 *
9883 * Since the verifier pushes the branch states as it sees them while exploring
9884 * the program the condition of walking the branch instruction for the second
9885 * time means that all states below this branch were already explored and
Zhen Lei8fb33b62021-05-25 10:56:59 +08009886 * their final liveness marks are already propagated.
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009887 * Hence when the verifier completes the search of state list in is_state_visited()
9888 * we can call this clean_live_states() function to mark all liveness states
9889 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9890 * will not be used.
9891 * This function also clears the registers and stack for states that !READ
9892 * to simplify state merging.
9893 *
9894 * Important note here that walking the same branch instruction in the callee
9895 * doesn't meant that the states are DONE. The verifier has to compare
9896 * the callsites
9897 */
9898static void clean_live_states(struct bpf_verifier_env *env, int insn,
9899 struct bpf_verifier_state *cur)
9900{
9901 struct bpf_verifier_state_list *sl;
9902 int i;
9903
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009904 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009905 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009906 if (sl->state.branches)
9907 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009908 if (sl->state.insn_idx != insn ||
9909 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009910 goto next;
9911 for (i = 0; i <= cur->curframe; i++)
9912 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9913 goto next;
9914 clean_verifier_state(env, &sl->state);
9915next:
9916 sl = sl->next;
9917 }
9918}
9919
Edward Creef1174f72017-08-07 15:26:19 +01009920/* Returns true if (rold safe implies rcur safe) */
Daniel Borkmanne042aa52021-07-16 09:18:21 +00009921static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
9922 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009923{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009924 bool equal;
9925
Edward Creedc503a82017-08-15 20:34:35 +01009926 if (!(rold->live & REG_LIVE_READ))
9927 /* explored state didn't use this */
9928 return true;
9929
Edward Cree679c7822018-08-22 20:02:19 +01009930 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009931
9932 if (rold->type == PTR_TO_STACK)
9933 /* two stack pointers are equal only if they're pointing to
9934 * the same stack frame, since fp-8 in foo != fp-8 in bar
9935 */
9936 return equal && rold->frameno == rcur->frameno;
9937
9938 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01009939 return true;
9940
9941 if (rold->type == NOT_INIT)
9942 /* explored state can't have used this */
9943 return true;
9944 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009945 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009946 switch (rold->type) {
9947 case SCALAR_VALUE:
Daniel Borkmanne042aa52021-07-16 09:18:21 +00009948 if (env->explore_alu_limits)
9949 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009950 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009951 if (!rold->precise && !rcur->precise)
9952 return true;
Edward Creef1174f72017-08-07 15:26:19 +01009953 /* new val must satisfy old val knowledge */
9954 return range_within(rold, rcur) &&
9955 tnum_in(rold->var_off, rcur->var_off);
9956 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08009957 /* We're trying to use a pointer in place of a scalar.
9958 * Even if the scalar was unbounded, this could lead to
9959 * pointer leaks because scalars are allowed to leak
9960 * while pointers are not. We could make this safe in
9961 * special cases if root is calling us, but it's
9962 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01009963 */
Jann Horn179d1c52017-12-18 20:11:59 -08009964 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009965 }
Yonghong Song69c087b2021-02-26 12:49:25 -08009966 case PTR_TO_MAP_KEY:
Edward Creef1174f72017-08-07 15:26:19 +01009967 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01009968 /* If the new min/max/var_off satisfy the old ones and
9969 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009970 * 'id' is not compared, since it's only used for maps with
9971 * bpf_spin_lock inside map element and in such cases if
9972 * the rest of the prog is valid for one map element then
9973 * it's valid for all map elements regardless of the key
9974 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01009975 */
9976 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9977 range_within(rold, rcur) &&
9978 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01009979 case PTR_TO_MAP_VALUE_OR_NULL:
9980 /* a PTR_TO_MAP_VALUE could be safe to use as a
9981 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9982 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9983 * checked, doing so could have affected others with the same
9984 * id, and we can't check for that because we lost the id when
9985 * we converted to a PTR_TO_MAP_VALUE.
9986 */
9987 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9988 return false;
9989 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9990 return false;
9991 /* Check our ids match any regs they're supposed to */
9992 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009993 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01009994 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009995 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01009996 return false;
9997 /* We must have at least as much range as the old ptr
9998 * did, so that any accesses which were safe before are
9999 * still safe. This is true even if old range < old off,
10000 * since someone could have accessed through (ptr - k), or
10001 * even done ptr -= k in a register, to get a safe access.
10002 */
10003 if (rold->range > rcur->range)
10004 return false;
10005 /* If the offsets don't match, we can't trust our alignment;
10006 * nor can we be sure that we won't fall out of range.
10007 */
10008 if (rold->off != rcur->off)
10009 return false;
10010 /* id relations must be preserved */
10011 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10012 return false;
10013 /* new val must satisfy old val knowledge */
10014 return range_within(rold, rcur) &&
10015 tnum_in(rold->var_off, rcur->var_off);
10016 case PTR_TO_CTX:
10017 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +010010018 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -070010019 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -070010020 case PTR_TO_SOCKET:
10021 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010022 case PTR_TO_SOCK_COMMON:
10023 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010024 case PTR_TO_TCP_SOCK:
10025 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010026 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +010010027 /* Only valid matches are exact, which memcmp() above
10028 * would have accepted
10029 */
10030 default:
10031 /* Don't know what's going on, just say it's not safe */
10032 return false;
10033 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010034
Edward Creef1174f72017-08-07 15:26:19 +010010035 /* Shouldn't get here; if we do, say it's not safe */
10036 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010037 return false;
10038}
10039
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010040static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10041 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010042{
10043 int i, spi;
10044
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010045 /* walk slots of the explored stack and ignore any additional
10046 * slots in the current stack, since explored(safe) state
10047 * didn't use them
10048 */
10049 for (i = 0; i < old->allocated_stack; i++) {
10050 spi = i / BPF_REG_SIZE;
10051
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010052 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10053 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010054 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +000010055 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010056 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010057
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010058 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10059 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -080010060
10061 /* explored stack has more populated slots than current stack
10062 * and these slots were used
10063 */
10064 if (i >= cur->allocated_stack)
10065 return false;
10066
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010067 /* if old state was safe with misc data in the stack
10068 * it will be safe with zero-initialized stack.
10069 * The opposite is not true
10070 */
10071 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10072 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10073 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010074 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10075 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10076 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -070010077 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010078 * this verifier states are not equivalent,
10079 * return false to continue verification of this path
10080 */
10081 return false;
10082 if (i % BPF_REG_SIZE)
10083 continue;
10084 if (old->stack[spi].slot_type[0] != STACK_SPILL)
10085 continue;
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010086 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10087 &cur->stack[spi].spilled_ptr, idmap))
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010088 /* when explored and current stack slot are both storing
10089 * spilled registers, check that stored pointers types
10090 * are the same as well.
10091 * Ex: explored safe path could have stored
10092 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10093 * but current path has stored:
10094 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10095 * such verifier states are not equivalent.
10096 * return false to continue verification of this path
10097 */
10098 return false;
10099 }
10100 return true;
10101}
10102
Joe Stringerfd978bf72018-10-02 13:35:35 -070010103static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10104{
10105 if (old->acquired_refs != cur->acquired_refs)
10106 return false;
10107 return !memcmp(old->refs, cur->refs,
10108 sizeof(*old->refs) * old->acquired_refs);
10109}
10110
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010111/* compare two verifier states
10112 *
10113 * all states stored in state_list are known to be valid, since
10114 * verifier reached 'bpf_exit' instruction through them
10115 *
10116 * this function is called when verifier exploring different branches of
10117 * execution popped from the state stack. If it sees an old state that has
10118 * more strict register state and more strict stack state then this execution
10119 * branch doesn't need to be explored further, since verifier already
10120 * concluded that more strict state leads to valid finish.
10121 *
10122 * Therefore two states are equivalent if register state is more conservative
10123 * and explored stack state is more conservative than the current one.
10124 * Example:
10125 * explored current
10126 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10127 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10128 *
10129 * In other words if current stack state (one being explored) has more
10130 * valid slots than old one that already passed validation, it means
10131 * the verifier can stop exploring and conclude that current state is valid too
10132 *
10133 * Similarly with registers. If explored state has register type as invalid
10134 * whereas register type in current state is meaningful, it means that
10135 * the current state will reach 'bpf_exit' instruction safely
10136 */
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010137static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010138 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010139{
10140 int i;
10141
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010142 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10143 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010144 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10145 env->idmap_scratch))
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010146 return false;
10147
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010148 if (!stacksafe(env, old, cur, env->idmap_scratch))
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -070010149 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010150
Joe Stringerfd978bf72018-10-02 13:35:35 -070010151 if (!refsafe(old, cur))
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010152 return false;
10153
10154 return true;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010155}
10156
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010157static bool states_equal(struct bpf_verifier_env *env,
10158 struct bpf_verifier_state *old,
10159 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +010010160{
Edward Creedc503a82017-08-15 20:34:35 +010010161 int i;
10162
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010163 if (old->curframe != cur->curframe)
10164 return false;
10165
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010166 /* Verification state from speculative execution simulation
10167 * must never prune a non-speculative execution one.
10168 */
10169 if (old->speculative && !cur->speculative)
10170 return false;
10171
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010172 if (old->active_spin_lock != cur->active_spin_lock)
10173 return false;
10174
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010175 /* for states to be equal callsites have to be the same
10176 * and all frame states need to be equivalent
10177 */
10178 for (i = 0; i <= old->curframe; i++) {
10179 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10180 return false;
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010181 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010182 return false;
10183 }
10184 return true;
10185}
10186
Jiong Wang5327ed32019-05-24 23:25:12 +010010187/* Return 0 if no propagation happened. Return negative error code if error
10188 * happened. Otherwise, return the propagated bit.
10189 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010190static int propagate_liveness_reg(struct bpf_verifier_env *env,
10191 struct bpf_reg_state *reg,
10192 struct bpf_reg_state *parent_reg)
10193{
Jiong Wang5327ed32019-05-24 23:25:12 +010010194 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10195 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010196 int err;
10197
Jiong Wang5327ed32019-05-24 23:25:12 +010010198 /* When comes here, read flags of PARENT_REG or REG could be any of
10199 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10200 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10201 */
10202 if (parent_flag == REG_LIVE_READ64 ||
10203 /* Or if there is no read flag from REG. */
10204 !flag ||
10205 /* Or if the read flag from REG is the same as PARENT_REG. */
10206 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010207 return 0;
10208
Jiong Wang5327ed32019-05-24 23:25:12 +010010209 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010210 if (err)
10211 return err;
10212
Jiong Wang5327ed32019-05-24 23:25:12 +010010213 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010214}
10215
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010216/* A write screens off any subsequent reads; but write marks come from the
10217 * straight-line code between a state and its parent. When we arrive at an
10218 * equivalent state (jump target or such) we didn't arrive by the straight-line
10219 * code, so read marks in the state must propagate to the parent regardless
10220 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +010010221 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010222 */
10223static int propagate_liveness(struct bpf_verifier_env *env,
10224 const struct bpf_verifier_state *vstate,
10225 struct bpf_verifier_state *vparent)
10226{
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010227 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010228 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010229 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010230
10231 if (vparent->curframe != vstate->curframe) {
10232 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10233 vparent->curframe, vstate->curframe);
10234 return -EFAULT;
10235 }
Edward Creedc503a82017-08-15 20:34:35 +010010236 /* Propagate read liveness of registers... */
10237 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -070010238 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010239 parent = vparent->frame[frame];
10240 state = vstate->frame[frame];
10241 parent_reg = parent->regs;
10242 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -070010243 /* We don't need to worry about FP liveness, it's read-only */
10244 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010245 err = propagate_liveness_reg(env, &state_reg[i],
10246 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +010010247 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010248 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +010010249 if (err == REG_LIVE_READ64)
10250 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +010010251 }
Edward Creedc503a82017-08-15 20:34:35 +010010252
Jiong Wang1b04aee2019-04-12 22:59:34 +010010253 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010254 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10255 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010256 parent_reg = &parent->stack[i].spilled_ptr;
10257 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010258 err = propagate_liveness_reg(env, state_reg,
10259 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +010010260 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010261 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010262 }
Edward Creedc503a82017-08-15 20:34:35 +010010263 }
Jiong Wang5327ed32019-05-24 23:25:12 +010010264 return 0;
Edward Creedc503a82017-08-15 20:34:35 +010010265}
10266
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010267/* find precise scalars in the previous equivalent state and
10268 * propagate them into the current state
10269 */
10270static int propagate_precision(struct bpf_verifier_env *env,
10271 const struct bpf_verifier_state *old)
10272{
10273 struct bpf_reg_state *state_reg;
10274 struct bpf_func_state *state;
10275 int i, err = 0;
10276
10277 state = old->frame[old->curframe];
10278 state_reg = state->regs;
10279 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10280 if (state_reg->type != SCALAR_VALUE ||
10281 !state_reg->precise)
10282 continue;
10283 if (env->log.level & BPF_LOG_LEVEL2)
10284 verbose(env, "propagating r%d\n", i);
10285 err = mark_chain_precision(env, i);
10286 if (err < 0)
10287 return err;
10288 }
10289
10290 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
10291 if (state->stack[i].slot_type[0] != STACK_SPILL)
10292 continue;
10293 state_reg = &state->stack[i].spilled_ptr;
10294 if (state_reg->type != SCALAR_VALUE ||
10295 !state_reg->precise)
10296 continue;
10297 if (env->log.level & BPF_LOG_LEVEL2)
10298 verbose(env, "propagating fp%d\n",
10299 (-i - 1) * BPF_REG_SIZE);
10300 err = mark_chain_precision_stack(env, i);
10301 if (err < 0)
10302 return err;
10303 }
10304 return 0;
10305}
10306
Alexei Starovoitov25897262019-06-15 12:12:20 -070010307static bool states_maybe_looping(struct bpf_verifier_state *old,
10308 struct bpf_verifier_state *cur)
10309{
10310 struct bpf_func_state *fold, *fcur;
10311 int i, fr = cur->curframe;
10312
10313 if (old->curframe != fr)
10314 return false;
10315
10316 fold = old->frame[fr];
10317 fcur = cur->frame[fr];
10318 for (i = 0; i < MAX_BPF_REG; i++)
10319 if (memcmp(&fold->regs[i], &fcur->regs[i],
10320 offsetof(struct bpf_reg_state, parent)))
10321 return false;
10322 return true;
10323}
10324
10325
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010326static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010327{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010328 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010329 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +010010330 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080010331 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070010332 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010333
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010334 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010335 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010336 /* this 'insn_idx' instruction wasn't marked, so we will not
10337 * be doing state search here
10338 */
10339 return 0;
10340
Alexei Starovoitov25897262019-06-15 12:12:20 -070010341 /* bpf progs typically have pruning point every 4 instructions
10342 * http://vger.kernel.org/bpfconf2019.html#session-1
10343 * Do not add new state for future pruning if the verifier hasn't seen
10344 * at least 2 jumps and at least 8 instructions.
10345 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
10346 * In tests that amounts to up to 50% reduction into total verifier
10347 * memory consumption and 20% verifier time speedup.
10348 */
10349 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
10350 env->insn_processed - env->prev_insn_processed >= 8)
10351 add_new_state = true;
10352
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010353 pprev = explored_state(env, insn_idx);
10354 sl = *pprev;
10355
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010356 clean_live_states(env, insn_idx, cur);
10357
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010358 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010359 states_cnt++;
10360 if (sl->state.insn_idx != insn_idx)
10361 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010362 if (sl->state.branches) {
10363 if (states_maybe_looping(&sl->state, cur) &&
10364 states_equal(env, &sl->state, cur)) {
10365 verbose_linfo(env, insn_idx, "; ");
10366 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
10367 return -EINVAL;
10368 }
10369 /* if the verifier is processing a loop, avoid adding new state
10370 * too often, since different loop iterations have distinct
10371 * states and may not help future pruning.
10372 * This threshold shouldn't be too low to make sure that
10373 * a loop with large bound will be rejected quickly.
10374 * The most abusive loop will be:
10375 * r1 += 1
10376 * if r1 < 1000000 goto pc-2
10377 * 1M insn_procssed limit / 100 == 10k peak states.
10378 * This threshold shouldn't be too high either, since states
10379 * at the end of the loop are likely to be useful in pruning.
10380 */
10381 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
10382 env->insn_processed - env->prev_insn_processed < 100)
10383 add_new_state = false;
10384 goto miss;
10385 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010386 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010387 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010388 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +010010389 * prune the search.
10390 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +010010391 * If we have any write marks in env->cur_state, they
10392 * will prevent corresponding reads in the continuation
10393 * from reaching our parent (an explored_state). Our
10394 * own state will get the read marks recorded, but
10395 * they'll be immediately forgotten as we're pruning
10396 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010397 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010398 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010399
10400 /* if previous state reached the exit with precision and
10401 * current state is equivalent to it (except precsion marks)
10402 * the precision needs to be propagated back in
10403 * the current state.
10404 */
10405 err = err ? : push_jmp_history(env, cur);
10406 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010407 if (err)
10408 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010409 return 1;
Edward Creedc503a82017-08-15 20:34:35 +010010410 }
Alexei Starovoitov25897262019-06-15 12:12:20 -070010411miss:
10412 /* when new state is not going to be added do not increase miss count.
10413 * Otherwise several loop iterations will remove the state
10414 * recorded earlier. The goal of these heuristics is to have
10415 * states from some iterations of the loop (some in the beginning
10416 * and some at the end) to help pruning.
10417 */
10418 if (add_new_state)
10419 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010420 /* heuristic to determine whether this state is beneficial
10421 * to keep checking from state equivalence point of view.
10422 * Higher numbers increase max_states_per_insn and verification time,
10423 * but do not meaningfully decrease insn_processed.
10424 */
10425 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
10426 /* the state is unlikely to be useful. Remove it to
10427 * speed up verification
10428 */
10429 *pprev = sl->next;
10430 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -070010431 u32 br = sl->state.branches;
10432
10433 WARN_ONCE(br,
10434 "BUG live_done but branches_to_explore %d\n",
10435 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010436 free_verifier_state(&sl->state, false);
10437 kfree(sl);
10438 env->peak_states--;
10439 } else {
10440 /* cannot free this state, since parentage chain may
10441 * walk it later. Add it for free_list instead to
10442 * be freed at the end of verification
10443 */
10444 sl->next = env->free_list;
10445 env->free_list = sl;
10446 }
10447 sl = *pprev;
10448 continue;
10449 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010450next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070010451 pprev = &sl->next;
10452 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010453 }
10454
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010455 if (env->max_states_per_insn < states_cnt)
10456 env->max_states_per_insn = states_cnt;
10457
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070010458 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010459 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080010460
Alexei Starovoitov25897262019-06-15 12:12:20 -070010461 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010462 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -070010463
10464 /* There were no equivalent states, remember the current one.
10465 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010466 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -070010467 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010468 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -070010469 * again on the way to bpf_exit.
10470 * When looping the sl->state.branches will be > 0 and this state
10471 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010472 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010473 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010474 if (!new_sl)
10475 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010476 env->total_states++;
10477 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010478 env->prev_jmps_processed = env->jmps_processed;
10479 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010480
10481 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +010010482 new = &new_sl->state;
10483 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070010484 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +010010485 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070010486 kfree(new_sl);
10487 return err;
10488 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010489 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -070010490 WARN_ONCE(new->branches != 1,
10491 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010492
Alexei Starovoitov25897262019-06-15 12:12:20 -070010493 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010494 cur->first_insn_idx = insn_idx;
10495 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -070010496 new_sl->next = *explored_state(env, insn_idx);
10497 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -080010498 /* connect new state to parentage chain. Current frame needs all
10499 * registers connected. Only r6 - r9 of the callers are alive (pushed
10500 * to the stack implicitly by JITs) so in callers' frames connect just
10501 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
10502 * the state of the call instruction (with WRITTEN set), and r0 comes
10503 * from callee with its full parentage chain, anyway.
10504 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +010010505 /* clear write marks in current state: the writes we did are not writes
10506 * our child did, so they don't screen off its reads from us.
10507 * (There are no read marks in current state, because reads always mark
10508 * their parent and current state never has children yet. Only
10509 * explored_states can get read marks.)
10510 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -070010511 for (j = 0; j <= cur->curframe; j++) {
10512 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
10513 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
10514 for (i = 0; i < BPF_REG_FP; i++)
10515 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
10516 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010517
10518 /* all stack frames are accessible from callee, clear them all */
10519 for (j = 0; j <= cur->curframe; j++) {
10520 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +010010521 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010522
Edward Cree679c7822018-08-22 20:02:19 +010010523 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010524 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +010010525 frame->stack[i].spilled_ptr.parent =
10526 &newframe->stack[i].spilled_ptr;
10527 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010528 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010529 return 0;
10530}
10531
Joe Stringerc64b7982018-10-02 13:35:33 -070010532/* Return true if it's OK to have the same insn return a different type. */
10533static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10534{
10535 switch (type) {
10536 case PTR_TO_CTX:
10537 case PTR_TO_SOCKET:
10538 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010539 case PTR_TO_SOCK_COMMON:
10540 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010541 case PTR_TO_TCP_SOCK:
10542 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010543 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010544 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -070010545 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -070010546 return false;
10547 default:
10548 return true;
10549 }
10550}
10551
10552/* If an instruction was previously used with particular pointer types, then we
10553 * need to be careful to avoid cases such as the below, where it may be ok
10554 * for one branch accessing the pointer, but not ok for the other branch:
10555 *
10556 * R1 = sock_ptr
10557 * goto X;
10558 * ...
10559 * R1 = some_other_valid_ptr;
10560 * goto X;
10561 * ...
10562 * R2 = *(u32 *)(R1 + 0);
10563 */
10564static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10565{
10566 return src != prev && (!reg_type_mismatch_ok(src) ||
10567 !reg_type_mismatch_ok(prev));
10568}
10569
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010570static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010571{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010572 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010573 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010574 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010575 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010576 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010577 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010578 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010579
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010580 for (;;) {
10581 struct bpf_insn *insn;
10582 u8 class;
10583 int err;
10584
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010585 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010586 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010587 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010588 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010589 return -EFAULT;
10590 }
10591
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010592 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010593 class = BPF_CLASS(insn->code);
10594
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010595 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010596 verbose(env,
10597 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010598 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010599 return -E2BIG;
10600 }
10601
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010602 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010603 if (err < 0)
10604 return err;
10605 if (err == 1) {
10606 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010607 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010608 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010609 verbose(env, "\nfrom %d to %d%s: safe\n",
10610 env->prev_insn_idx, env->insn_idx,
10611 env->cur_state->speculative ?
10612 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010613 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010614 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010615 }
10616 goto process_bpf_exit;
10617 }
10618
Alexei Starovoitovc3494802018-12-03 22:46:04 -080010619 if (signal_pending(current))
10620 return -EAGAIN;
10621
Daniel Borkmann3c2ce602017-05-18 03:00:06 +020010622 if (need_resched())
10623 cond_resched();
10624
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010625 if (env->log.level & BPF_LOG_LEVEL2 ||
10626 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10627 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010628 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -070010629 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010630 verbose(env, "\nfrom %d to %d%s:",
10631 env->prev_insn_idx, env->insn_idx,
10632 env->cur_state->speculative ?
10633 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010634 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010635 do_print_state = false;
10636 }
10637
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010638 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010639 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010640 .cb_call = disasm_kfunc_name,
Daniel Borkmann7105e822017-12-20 13:42:57 +010010641 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +010010642 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +010010643 };
10644
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010645 verbose_linfo(env, env->insn_idx, "; ");
10646 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +010010647 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010648 }
10649
Jakub Kicinskicae19272017-12-27 18:39:05 -080010650 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010651 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10652 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -080010653 if (err)
10654 return err;
10655 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +010010656
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010657 regs = cur_regs(env);
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +000010658 sanitize_mark_insn_seen(env);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010659 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -070010660
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010661 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -070010662 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010663 if (err)
10664 return err;
10665
10666 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010667 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010668
10669 /* check for reserved fields is already done */
10670
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010671 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010672 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010673 if (err)
10674 return err;
10675
Edward Creedc503a82017-08-15 20:34:35 +010010676 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010677 if (err)
10678 return err;
10679
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -070010680 src_reg_type = regs[insn->src_reg].type;
10681
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010682 /* check that memory (src_reg + off) is readable,
10683 * the state of dst_reg will be updated by this func
10684 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010685 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10686 insn->off, BPF_SIZE(insn->code),
10687 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010688 if (err)
10689 return err;
10690
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010691 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010692
10693 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010694 /* saw a valid insn
10695 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010696 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010697 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010698 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010699
Joe Stringerc64b7982018-10-02 13:35:33 -070010700 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010701 /* ABuser program is trying to use the same insn
10702 * dst_reg = *(u32*) (src_reg + off)
10703 * with different pointer types:
10704 * src_reg == ctx in one branch and
10705 * src_reg == stack|map in some other branch.
10706 * Reject it.
10707 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010708 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010709 return -EINVAL;
10710 }
10711
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010712 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010713 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010714
Brendan Jackman91c960b2021-01-14 18:17:44 +000010715 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10716 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010717 if (err)
10718 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010719 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010720 continue;
10721 }
10722
Brendan Jackman5ca419f2021-01-14 18:17:46 +000010723 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10724 verbose(env, "BPF_STX uses reserved fields\n");
10725 return -EINVAL;
10726 }
10727
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010728 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010729 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010730 if (err)
10731 return err;
10732 /* check src2 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
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010737 dst_reg_type = regs[insn->dst_reg].type;
10738
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010739 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010740 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10741 insn->off, BPF_SIZE(insn->code),
10742 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010743 if (err)
10744 return err;
10745
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010746 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010747
10748 if (*prev_dst_type == NOT_INIT) {
10749 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070010750 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010751 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010752 return -EINVAL;
10753 }
10754
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010755 } else if (class == BPF_ST) {
10756 if (BPF_MODE(insn->code) != BPF_MEM ||
10757 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010758 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010759 return -EINVAL;
10760 }
10761 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010762 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010763 if (err)
10764 return err;
10765
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010766 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070010767 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020010768 insn->dst_reg,
10769 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010770 return -EACCES;
10771 }
10772
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010773 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010774 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10775 insn->off, BPF_SIZE(insn->code),
10776 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010777 if (err)
10778 return err;
10779
Jiong Wang092ed092019-01-26 12:26:01 -050010780 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010781 u8 opcode = BPF_OP(insn->code);
10782
Alexei Starovoitov25897262019-06-15 12:12:20 -070010783 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010784 if (opcode == BPF_CALL) {
10785 if (BPF_SRC(insn->code) != BPF_K ||
10786 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010787 (insn->src_reg != BPF_REG_0 &&
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010788 insn->src_reg != BPF_PSEUDO_CALL &&
10789 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050010790 insn->dst_reg != BPF_REG_0 ||
10791 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010792 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010793 return -EINVAL;
10794 }
10795
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010796 if (env->cur_state->active_spin_lock &&
10797 (insn->src_reg == BPF_PSEUDO_CALL ||
10798 insn->imm != BPF_FUNC_spin_unlock)) {
10799 verbose(env, "function calls are not allowed while holding a lock\n");
10800 return -EINVAL;
10801 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010802 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010803 err = check_func_call(env, insn, &env->insn_idx);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070010804 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
10805 err = check_kfunc_call(env, insn);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010806 else
Yonghong Song69c087b2021-02-26 12:49:25 -080010807 err = check_helper_call(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010808 if (err)
10809 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010810 } else if (opcode == BPF_JA) {
10811 if (BPF_SRC(insn->code) != BPF_K ||
10812 insn->imm != 0 ||
10813 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010814 insn->dst_reg != BPF_REG_0 ||
10815 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010816 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010817 return -EINVAL;
10818 }
10819
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010820 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010821 continue;
10822
10823 } else if (opcode == BPF_EXIT) {
10824 if (BPF_SRC(insn->code) != BPF_K ||
10825 insn->imm != 0 ||
10826 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010827 insn->dst_reg != BPF_REG_0 ||
10828 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010829 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010830 return -EINVAL;
10831 }
10832
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010833 if (env->cur_state->active_spin_lock) {
10834 verbose(env, "bpf_spin_unlock is missing\n");
10835 return -EINVAL;
10836 }
10837
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010838 if (state->curframe) {
10839 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010840 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010841 if (err)
10842 return err;
10843 do_print_state = true;
10844 continue;
10845 }
10846
Joe Stringerfd978bf72018-10-02 13:35:35 -070010847 err = check_reference_leak(env);
10848 if (err)
10849 return err;
10850
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070010851 err = check_return_code(env);
10852 if (err)
10853 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010854process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -070010855 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010856 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010857 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010858 if (err < 0) {
10859 if (err != -ENOENT)
10860 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010861 break;
10862 } else {
10863 do_print_state = true;
10864 continue;
10865 }
10866 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010867 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010868 if (err)
10869 return err;
10870 }
10871 } else if (class == BPF_LD) {
10872 u8 mode = BPF_MODE(insn->code);
10873
10874 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080010875 err = check_ld_abs(env, insn);
10876 if (err)
10877 return err;
10878
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010879 } else if (mode == BPF_IMM) {
10880 err = check_ld_imm(env, insn);
10881 if (err)
10882 return err;
10883
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010884 env->insn_idx++;
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +000010885 sanitize_mark_insn_seen(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010886 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010887 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010888 return -EINVAL;
10889 }
10890 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010891 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010892 return -EINVAL;
10893 }
10894
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010895 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010896 }
10897
10898 return 0;
10899}
10900
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010901static int find_btf_percpu_datasec(struct btf *btf)
10902{
10903 const struct btf_type *t;
10904 const char *tname;
10905 int i, n;
10906
10907 /*
10908 * Both vmlinux and module each have their own ".data..percpu"
10909 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10910 * types to look at only module's own BTF types.
10911 */
10912 n = btf_nr_types(btf);
10913 if (btf_is_module(btf))
10914 i = btf_nr_types(btf_vmlinux);
10915 else
10916 i = 1;
10917
10918 for(; i < n; i++) {
10919 t = btf_type_by_id(btf, i);
10920 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10921 continue;
10922
10923 tname = btf_name_by_offset(btf, t->name_off);
10924 if (!strcmp(tname, ".data..percpu"))
10925 return i;
10926 }
10927
10928 return -ENOENT;
10929}
10930
Hao Luo4976b712020-09-29 16:50:44 -070010931/* replace pseudo btf_id with kernel symbol address */
10932static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10933 struct bpf_insn *insn,
10934 struct bpf_insn_aux_data *aux)
10935{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010936 const struct btf_var_secinfo *vsi;
10937 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010938 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070010939 const struct btf_type *t;
10940 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010941 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010942 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010943 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010944 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070010945 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010946 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070010947
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010948 btf_fd = insn[1].imm;
10949 if (btf_fd) {
10950 btf = btf_get_by_fd(btf_fd);
10951 if (IS_ERR(btf)) {
10952 verbose(env, "invalid module BTF object FD specified.\n");
10953 return -EINVAL;
10954 }
10955 } else {
10956 if (!btf_vmlinux) {
10957 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10958 return -EINVAL;
10959 }
10960 btf = btf_vmlinux;
10961 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070010962 }
10963
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010964 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070010965 if (!t) {
10966 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010967 err = -ENOENT;
10968 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010969 }
10970
10971 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010972 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10973 err = -EINVAL;
10974 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010975 }
10976
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010977 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010978 addr = kallsyms_lookup_name(sym_name);
10979 if (!addr) {
10980 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10981 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010982 err = -ENOENT;
10983 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010984 }
10985
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010986 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010987 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010988 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010989 for_each_vsi(i, datasec, vsi) {
10990 if (vsi->type == id) {
10991 percpu = true;
10992 break;
10993 }
10994 }
10995 }
10996
Hao Luo4976b712020-09-29 16:50:44 -070010997 insn[0].imm = (u32)addr;
10998 insn[1].imm = addr >> 32;
10999
11000 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011001 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011002 if (percpu) {
11003 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011004 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011005 aux->btf_var.btf_id = type;
11006 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070011007 const struct btf_type *ret;
11008 const char *tname;
11009 u32 tsize;
11010
11011 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011012 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070011013 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011014 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070011015 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11016 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011017 err = -EINVAL;
11018 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070011019 }
11020 aux->btf_var.reg_type = PTR_TO_MEM;
11021 aux->btf_var.mem_size = tsize;
11022 } else {
11023 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011024 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070011025 aux->btf_var.btf_id = type;
11026 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011027
11028 /* check whether we recorded this BTF (and maybe module) already */
11029 for (i = 0; i < env->used_btf_cnt; i++) {
11030 if (env->used_btfs[i].btf == btf) {
11031 btf_put(btf);
11032 return 0;
11033 }
11034 }
11035
11036 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11037 err = -E2BIG;
11038 goto err_put;
11039 }
11040
11041 btf_mod = &env->used_btfs[env->used_btf_cnt];
11042 btf_mod->btf = btf;
11043 btf_mod->module = NULL;
11044
11045 /* if we reference variables from kernel module, bump its refcount */
11046 if (btf_is_module(btf)) {
11047 btf_mod->module = btf_try_get_module(btf);
11048 if (!btf_mod->module) {
11049 err = -ENXIO;
11050 goto err_put;
11051 }
11052 }
11053
11054 env->used_btf_cnt++;
11055
Hao Luo4976b712020-09-29 16:50:44 -070011056 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011057err_put:
11058 btf_put(btf);
11059 return err;
Hao Luo4976b712020-09-29 16:50:44 -070011060}
11061
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011062static int check_map_prealloc(struct bpf_map *map)
11063{
11064 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070011065 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11066 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011067 !(map->map_flags & BPF_F_NO_PREALLOC);
11068}
11069
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011070static bool is_tracing_prog_type(enum bpf_prog_type type)
11071{
11072 switch (type) {
11073 case BPF_PROG_TYPE_KPROBE:
11074 case BPF_PROG_TYPE_TRACEPOINT:
11075 case BPF_PROG_TYPE_PERF_EVENT:
11076 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11077 return true;
11078 default:
11079 return false;
11080 }
11081}
11082
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011083static bool is_preallocated_map(struct bpf_map *map)
11084{
11085 if (!check_map_prealloc(map))
11086 return false;
11087 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11088 return false;
11089 return true;
11090}
11091
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011092static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11093 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011094 struct bpf_prog *prog)
11095
11096{
Udip Pant7e407812020-08-25 16:20:00 -070011097 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011098 /*
11099 * Validate that trace type programs use preallocated hash maps.
11100 *
11101 * For programs attached to PERF events this is mandatory as the
11102 * perf NMI can hit any arbitrary code sequence.
11103 *
11104 * All other trace types using preallocated hash maps are unsafe as
11105 * well because tracepoint or kprobes can be inside locked regions
11106 * of the memory allocator or at a place where a recursion into the
11107 * memory allocator would see inconsistent state.
11108 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011109 * On RT enabled kernels run-time allocation of all trace type
11110 * programs is strictly prohibited due to lock type constraints. On
11111 * !RT kernels it is allowed for backwards compatibility reasons for
11112 * now, but warnings are emitted so developers are made aware of
11113 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011114 */
Udip Pant7e407812020-08-25 16:20:00 -070011115 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11116 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011117 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011118 return -EINVAL;
11119 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011120 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11121 verbose(env, "trace type programs can only use preallocated hash map\n");
11122 return -EINVAL;
11123 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011124 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11125 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 -070011126 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080011127
KP Singh9e7a4d92020-11-06 10:37:39 +000011128 if (map_value_has_spin_lock(map)) {
11129 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11130 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11131 return -EINVAL;
11132 }
11133
11134 if (is_tracing_prog_type(prog_type)) {
11135 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11136 return -EINVAL;
11137 }
11138
11139 if (prog->aux->sleepable) {
11140 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11141 return -EINVAL;
11142 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011143 }
11144
Jakub Kicinskia3884572018-01-11 20:29:09 -080011145 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070011146 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080011147 verbose(env, "offload device mismatch between prog and map\n");
11148 return -EINVAL;
11149 }
11150
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080011151 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11152 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11153 return -EINVAL;
11154 }
11155
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011156 if (prog->aux->sleepable)
11157 switch (map->map_type) {
11158 case BPF_MAP_TYPE_HASH:
11159 case BPF_MAP_TYPE_LRU_HASH:
11160 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011161 case BPF_MAP_TYPE_PERCPU_HASH:
11162 case BPF_MAP_TYPE_PERCPU_ARRAY:
11163 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11164 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11165 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011166 if (!is_preallocated_map(map)) {
11167 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011168 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011169 return -EINVAL;
11170 }
11171 break;
KP Singhba90c2c2021-02-04 19:36:21 +000011172 case BPF_MAP_TYPE_RINGBUF:
11173 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011174 default:
11175 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000011176 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011177 return -EINVAL;
11178 }
11179
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011180 return 0;
11181}
11182
Roman Gushchinb741f162018-09-28 14:45:43 +000011183static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11184{
11185 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11186 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11187}
11188
Hao Luo4976b712020-09-29 16:50:44 -070011189/* find and rewrite pseudo imm in ld_imm64 instructions:
11190 *
11191 * 1. if it accesses map FD, replace it with actual map pointer.
11192 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11193 *
11194 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011195 */
Hao Luo4976b712020-09-29 16:50:44 -070011196static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011197{
11198 struct bpf_insn *insn = env->prog->insnsi;
11199 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011200 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011201
Daniel Borkmannf1f77142017-01-13 23:38:15 +010011202 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010011203 if (err)
11204 return err;
11205
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011206 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011207 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011208 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011209 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011210 return -EINVAL;
11211 }
11212
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011213 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011214 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011215 struct bpf_map *map;
11216 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011217 u64 addr;
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011218 u32 fd;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011219
11220 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11221 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11222 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011223 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011224 return -EINVAL;
11225 }
11226
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011227 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011228 /* valid generic load 64-bit imm */
11229 goto next_insn;
11230
Hao Luo4976b712020-09-29 16:50:44 -070011231 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11232 aux = &env->insn_aux_data[i];
11233 err = check_pseudo_btf_id(env, insn, aux);
11234 if (err)
11235 return err;
11236 goto next_insn;
11237 }
11238
Yonghong Song69c087b2021-02-26 12:49:25 -080011239 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11240 aux = &env->insn_aux_data[i];
11241 aux->ptr_type = PTR_TO_FUNC;
11242 goto next_insn;
11243 }
11244
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011245 /* In final convert_pseudo_ld_imm64() step, this is
11246 * converted into regular 64-bit imm load insn.
11247 */
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011248 switch (insn[0].src_reg) {
11249 case BPF_PSEUDO_MAP_VALUE:
11250 case BPF_PSEUDO_MAP_IDX_VALUE:
11251 break;
11252 case BPF_PSEUDO_MAP_FD:
11253 case BPF_PSEUDO_MAP_IDX:
11254 if (insn[1].imm == 0)
11255 break;
11256 fallthrough;
11257 default:
11258 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011259 return -EINVAL;
11260 }
11261
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011262 switch (insn[0].src_reg) {
11263 case BPF_PSEUDO_MAP_IDX_VALUE:
11264 case BPF_PSEUDO_MAP_IDX:
11265 if (bpfptr_is_null(env->fd_array)) {
11266 verbose(env, "fd_idx without fd_array is invalid\n");
11267 return -EPROTO;
11268 }
11269 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11270 insn[0].imm * sizeof(fd),
11271 sizeof(fd)))
11272 return -EFAULT;
11273 break;
11274 default:
11275 fd = insn[0].imm;
11276 break;
11277 }
11278
11279 f = fdget(fd);
Daniel Borkmannc2101292015-10-29 14:58:07 +010011280 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011281 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011282 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010011283 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011284 return PTR_ERR(map);
11285 }
11286
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011287 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011288 if (err) {
11289 fdput(f);
11290 return err;
11291 }
11292
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011293 aux = &env->insn_aux_data[i];
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011294 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
11295 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011296 addr = (unsigned long)map;
11297 } else {
11298 u32 off = insn[1].imm;
11299
11300 if (off >= BPF_MAX_VAR_OFF) {
11301 verbose(env, "direct value offset of %u is not allowed\n", off);
11302 fdput(f);
11303 return -EINVAL;
11304 }
11305
11306 if (!map->ops->map_direct_value_addr) {
11307 verbose(env, "no direct value access support for this map type\n");
11308 fdput(f);
11309 return -EINVAL;
11310 }
11311
11312 err = map->ops->map_direct_value_addr(map, &addr, off);
11313 if (err) {
11314 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
11315 map->value_size, off);
11316 fdput(f);
11317 return err;
11318 }
11319
11320 aux->map_off = off;
11321 addr += off;
11322 }
11323
11324 insn[0].imm = (u32)addr;
11325 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011326
11327 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011328 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011329 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011330 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011331 fdput(f);
11332 goto next_insn;
11333 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011334 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011335
11336 if (env->used_map_cnt >= MAX_USED_MAPS) {
11337 fdput(f);
11338 return -E2BIG;
11339 }
11340
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011341 /* hold the map. If the program is rejected by verifier,
11342 * the map will be released by release_maps() or it
11343 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070011344 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011345 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080011346 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011347
11348 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070011349 env->used_maps[env->used_map_cnt++] = map;
11350
Roman Gushchinb741f162018-09-28 14:45:43 +000011351 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010011352 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000011353 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070011354 fdput(f);
11355 return -EBUSY;
11356 }
11357
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011358 fdput(f);
11359next_insn:
11360 insn++;
11361 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010011362 continue;
11363 }
11364
11365 /* Basic sanity check before we invest more work here. */
11366 if (!bpf_opcode_in_insntable(insn->code)) {
11367 verbose(env, "unknown opcode %02x\n", insn->code);
11368 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011369 }
11370 }
11371
11372 /* now all pseudo BPF_LD_IMM64 instructions load valid
11373 * 'struct bpf_map *' into a register instead of user map_fd.
11374 * These pointers will be used later by verifier to validate map access.
11375 */
11376 return 0;
11377}
11378
11379/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011380static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011381{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010011382 __bpf_free_used_maps(env->prog->aux, env->used_maps,
11383 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011384}
11385
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011386/* drop refcnt of maps used by the rejected program */
11387static void release_btfs(struct bpf_verifier_env *env)
11388{
11389 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
11390 env->used_btf_cnt);
11391}
11392
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011393/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011394static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011395{
11396 struct bpf_insn *insn = env->prog->insnsi;
11397 int insn_cnt = env->prog->len;
11398 int i;
11399
Yonghong Song69c087b2021-02-26 12:49:25 -080011400 for (i = 0; i < insn_cnt; i++, insn++) {
11401 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
11402 continue;
11403 if (insn->src_reg == BPF_PSEUDO_FUNC)
11404 continue;
11405 insn->src_reg = 0;
11406 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011407}
11408
Alexei Starovoitov80419022017-03-15 18:26:41 -070011409/* single env->prog->insni[off] instruction was replaced with the range
11410 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
11411 * [0, off) and [off, end) to new locations, so the patched range stays zero
11412 */
Jiong Wangb325fbc2019-05-24 23:25:13 +010011413static int adjust_insn_aux_data(struct bpf_verifier_env *env,
11414 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070011415{
11416 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011417 struct bpf_insn *insn = new_prog->insnsi;
Daniel Borkmannd203b0f2021-05-28 13:03:30 +000011418 u32 old_seen = old_data[off].seen;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011419 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011420 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011421
Jiong Wangb325fbc2019-05-24 23:25:13 +010011422 /* aux info at OFF always needs adjustment, no matter fast path
11423 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
11424 * original insn at old prog.
11425 */
11426 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
11427
Alexei Starovoitov80419022017-03-15 18:26:41 -070011428 if (cnt == 1)
11429 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011430 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -070011431 new_data = vzalloc(array_size(prog_len,
11432 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -070011433 if (!new_data)
11434 return -ENOMEM;
11435 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
11436 memcpy(new_data + off + cnt - 1, old_data + off,
11437 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010011438 for (i = off; i < off + cnt - 1; i++) {
Daniel Borkmannd203b0f2021-05-28 13:03:30 +000011439 /* Expand insni[off]'s seen count to the patched range. */
11440 new_data[i].seen = old_seen;
Jiong Wangb325fbc2019-05-24 23:25:13 +010011441 new_data[i].zext_dst = insn_has_def32(env, insn + i);
11442 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070011443 env->insn_aux_data = new_data;
11444 vfree(old_data);
11445 return 0;
11446}
11447
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011448static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
11449{
11450 int i;
11451
11452 if (len == 1)
11453 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040011454 /* NOTE: fake 'exit' subprog should be updated as well. */
11455 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000011456 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011457 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040011458 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011459 }
11460}
11461
John Fastabend7506d212021-06-16 15:55:00 -070011462static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011463{
11464 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
11465 int i, sz = prog->aux->size_poke_tab;
11466 struct bpf_jit_poke_descriptor *desc;
11467
11468 for (i = 0; i < sz; i++) {
11469 desc = &tab[i];
John Fastabend7506d212021-06-16 15:55:00 -070011470 if (desc->insn_idx <= off)
11471 continue;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011472 desc->insn_idx += len - 1;
11473 }
11474}
11475
Alexei Starovoitov80419022017-03-15 18:26:41 -070011476static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
11477 const struct bpf_insn *patch, u32 len)
11478{
11479 struct bpf_prog *new_prog;
11480
11481 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070011482 if (IS_ERR(new_prog)) {
11483 if (PTR_ERR(new_prog) == -ERANGE)
11484 verbose(env,
11485 "insn %d cannot be patched due to 16-bit range\n",
11486 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -070011487 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070011488 }
Jiong Wangb325fbc2019-05-24 23:25:13 +010011489 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -070011490 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011491 adjust_subprog_starts(env, off, len);
John Fastabend7506d212021-06-16 15:55:00 -070011492 adjust_poke_descs(new_prog, off, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070011493 return new_prog;
11494}
11495
Jakub Kicinski52875a02019-01-22 22:45:20 -080011496static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
11497 u32 off, u32 cnt)
11498{
11499 int i, j;
11500
11501 /* find first prog starting at or after off (first to remove) */
11502 for (i = 0; i < env->subprog_cnt; i++)
11503 if (env->subprog_info[i].start >= off)
11504 break;
11505 /* find first prog starting at or after off + cnt (first to stay) */
11506 for (j = i; j < env->subprog_cnt; j++)
11507 if (env->subprog_info[j].start >= off + cnt)
11508 break;
11509 /* if j doesn't start exactly at off + cnt, we are just removing
11510 * the front of previous prog
11511 */
11512 if (env->subprog_info[j].start != off + cnt)
11513 j--;
11514
11515 if (j > i) {
11516 struct bpf_prog_aux *aux = env->prog->aux;
11517 int move;
11518
11519 /* move fake 'exit' subprog as well */
11520 move = env->subprog_cnt + 1 - j;
11521
11522 memmove(env->subprog_info + i,
11523 env->subprog_info + j,
11524 sizeof(*env->subprog_info) * move);
11525 env->subprog_cnt -= j - i;
11526
11527 /* remove func_info */
11528 if (aux->func_info) {
11529 move = aux->func_info_cnt - j;
11530
11531 memmove(aux->func_info + i,
11532 aux->func_info + j,
11533 sizeof(*aux->func_info) * move);
11534 aux->func_info_cnt -= j - i;
11535 /* func_info->insn_off is set after all code rewrites,
11536 * in adjust_btf_func() - no need to adjust
11537 */
11538 }
11539 } else {
11540 /* convert i from "first prog to remove" to "first to adjust" */
11541 if (env->subprog_info[i].start == off)
11542 i++;
11543 }
11544
11545 /* update fake 'exit' subprog as well */
11546 for (; i <= env->subprog_cnt; i++)
11547 env->subprog_info[i].start -= cnt;
11548
11549 return 0;
11550}
11551
11552static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
11553 u32 cnt)
11554{
11555 struct bpf_prog *prog = env->prog;
11556 u32 i, l_off, l_cnt, nr_linfo;
11557 struct bpf_line_info *linfo;
11558
11559 nr_linfo = prog->aux->nr_linfo;
11560 if (!nr_linfo)
11561 return 0;
11562
11563 linfo = prog->aux->linfo;
11564
11565 /* find first line info to remove, count lines to be removed */
11566 for (i = 0; i < nr_linfo; i++)
11567 if (linfo[i].insn_off >= off)
11568 break;
11569
11570 l_off = i;
11571 l_cnt = 0;
11572 for (; i < nr_linfo; i++)
11573 if (linfo[i].insn_off < off + cnt)
11574 l_cnt++;
11575 else
11576 break;
11577
11578 /* First live insn doesn't match first live linfo, it needs to "inherit"
11579 * last removed linfo. prog is already modified, so prog->len == off
11580 * means no live instructions after (tail of the program was removed).
11581 */
11582 if (prog->len != off && l_cnt &&
11583 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11584 l_cnt--;
11585 linfo[--i].insn_off = off + cnt;
11586 }
11587
11588 /* remove the line info which refer to the removed instructions */
11589 if (l_cnt) {
11590 memmove(linfo + l_off, linfo + i,
11591 sizeof(*linfo) * (nr_linfo - i));
11592
11593 prog->aux->nr_linfo -= l_cnt;
11594 nr_linfo = prog->aux->nr_linfo;
11595 }
11596
11597 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11598 for (i = l_off; i < nr_linfo; i++)
11599 linfo[i].insn_off -= cnt;
11600
11601 /* fix up all subprogs (incl. 'exit') which start >= off */
11602 for (i = 0; i <= env->subprog_cnt; i++)
11603 if (env->subprog_info[i].linfo_idx > l_off) {
11604 /* program may have started in the removed region but
11605 * may not be fully removed
11606 */
11607 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11608 env->subprog_info[i].linfo_idx -= l_cnt;
11609 else
11610 env->subprog_info[i].linfo_idx = l_off;
11611 }
11612
11613 return 0;
11614}
11615
11616static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11617{
11618 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11619 unsigned int orig_prog_len = env->prog->len;
11620 int err;
11621
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011622 if (bpf_prog_is_dev_bound(env->prog->aux))
11623 bpf_prog_offload_remove_insns(env, off, cnt);
11624
Jakub Kicinski52875a02019-01-22 22:45:20 -080011625 err = bpf_remove_insns(env->prog, off, cnt);
11626 if (err)
11627 return err;
11628
11629 err = adjust_subprog_starts_after_remove(env, off, cnt);
11630 if (err)
11631 return err;
11632
11633 err = bpf_adj_linfo_after_remove(env, off, cnt);
11634 if (err)
11635 return err;
11636
11637 memmove(aux_data + off, aux_data + off + cnt,
11638 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11639
11640 return 0;
11641}
11642
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011643/* The verifier does more data flow analysis than llvm and will not
11644 * explore branches that are dead at run time. Malicious programs can
11645 * have dead code too. Therefore replace all dead at-run-time code
11646 * with 'ja -1'.
11647 *
11648 * Just nops are not optimal, e.g. if they would sit at the end of the
11649 * program and through another bug we would manage to jump there, then
11650 * we'd execute beyond program memory otherwise. Returning exception
11651 * code also wouldn't work since we can have subprogs where the dead
11652 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011653 */
11654static void sanitize_dead_code(struct bpf_verifier_env *env)
11655{
11656 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011657 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011658 struct bpf_insn *insn = env->prog->insnsi;
11659 const int insn_cnt = env->prog->len;
11660 int i;
11661
11662 for (i = 0; i < insn_cnt; i++) {
11663 if (aux_data[i].seen)
11664 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011665 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011666 }
11667}
11668
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011669static bool insn_is_cond_jump(u8 code)
11670{
11671 u8 op;
11672
Jiong Wang092ed092019-01-26 12:26:01 -050011673 if (BPF_CLASS(code) == BPF_JMP32)
11674 return true;
11675
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011676 if (BPF_CLASS(code) != BPF_JMP)
11677 return false;
11678
11679 op = BPF_OP(code);
11680 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11681}
11682
11683static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11684{
11685 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11686 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11687 struct bpf_insn *insn = env->prog->insnsi;
11688 const int insn_cnt = env->prog->len;
11689 int i;
11690
11691 for (i = 0; i < insn_cnt; i++, insn++) {
11692 if (!insn_is_cond_jump(insn->code))
11693 continue;
11694
11695 if (!aux_data[i + 1].seen)
11696 ja.off = insn->off;
11697 else if (!aux_data[i + 1 + insn->off].seen)
11698 ja.off = 0;
11699 else
11700 continue;
11701
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011702 if (bpf_prog_is_dev_bound(env->prog->aux))
11703 bpf_prog_offload_replace_insn(env, i, &ja);
11704
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011705 memcpy(insn, &ja, sizeof(ja));
11706 }
11707}
11708
Jakub Kicinski52875a02019-01-22 22:45:20 -080011709static int opt_remove_dead_code(struct bpf_verifier_env *env)
11710{
11711 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11712 int insn_cnt = env->prog->len;
11713 int i, err;
11714
11715 for (i = 0; i < insn_cnt; i++) {
11716 int j;
11717
11718 j = 0;
11719 while (i + j < insn_cnt && !aux_data[i + j].seen)
11720 j++;
11721 if (!j)
11722 continue;
11723
11724 err = verifier_remove_insns(env, i, j);
11725 if (err)
11726 return err;
11727 insn_cnt = env->prog->len;
11728 }
11729
11730 return 0;
11731}
11732
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011733static int opt_remove_nops(struct bpf_verifier_env *env)
11734{
11735 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11736 struct bpf_insn *insn = env->prog->insnsi;
11737 int insn_cnt = env->prog->len;
11738 int i, err;
11739
11740 for (i = 0; i < insn_cnt; i++) {
11741 if (memcmp(&insn[i], &ja, sizeof(ja)))
11742 continue;
11743
11744 err = verifier_remove_insns(env, i, 1);
11745 if (err)
11746 return err;
11747 insn_cnt--;
11748 i--;
11749 }
11750
11751 return 0;
11752}
11753
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011754static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11755 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011756{
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011757 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011758 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011759 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011760 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011761 struct bpf_prog *new_prog;
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011762 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011763
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011764 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011765 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011766 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11767 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11768 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011769 for (i = 0; i < len; i++) {
11770 int adj_idx = i + delta;
11771 struct bpf_insn insn;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011772 int load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011773
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011774 insn = insns[adj_idx];
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011775 load_reg = insn_def_regno(&insn);
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011776 if (!aux[adj_idx].zext_dst) {
11777 u8 code, class;
11778 u32 imm_rnd;
11779
11780 if (!rnd_hi32)
11781 continue;
11782
11783 code = insn.code;
11784 class = BPF_CLASS(code);
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011785 if (load_reg == -1)
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011786 continue;
11787
11788 /* NOTE: arg "reg" (the fourth one) is only used for
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011789 * BPF_STX + SRC_OP, so it is safe to pass NULL
11790 * here.
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011791 */
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011792 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011793 if (class == BPF_LD &&
11794 BPF_MODE(code) == BPF_IMM)
11795 i++;
11796 continue;
11797 }
11798
11799 /* ctx load could be transformed into wider load. */
11800 if (class == BPF_LDX &&
11801 aux[adj_idx].ptr_type == PTR_TO_CTX)
11802 continue;
11803
11804 imm_rnd = get_random_int();
11805 rnd_hi32_patch[0] = insn;
11806 rnd_hi32_patch[1].imm = imm_rnd;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011807 rnd_hi32_patch[3].dst_reg = load_reg;
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011808 patch = rnd_hi32_patch;
11809 patch_len = 4;
11810 goto apply_patch_buffer;
11811 }
11812
Brendan Jackman39491862021-03-04 18:56:46 -080011813 /* Add in an zero-extend instruction if a) the JIT has requested
11814 * it or b) it's a CMPXCHG.
11815 *
11816 * The latter is because: BPF_CMPXCHG always loads a value into
11817 * R0, therefore always zero-extends. However some archs'
11818 * equivalent instruction only does this load when the
11819 * comparison is successful. This detail of CMPXCHG is
11820 * orthogonal to the general zero-extension behaviour of the
11821 * CPU, so it's treated independently of bpf_jit_needs_zext.
11822 */
11823 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011824 continue;
11825
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010011826 if (WARN_ON(load_reg == -1)) {
11827 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
11828 return -EFAULT;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011829 }
11830
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011831 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011832 zext_patch[1].dst_reg = load_reg;
11833 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011834 patch = zext_patch;
11835 patch_len = 2;
11836apply_patch_buffer:
11837 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011838 if (!new_prog)
11839 return -ENOMEM;
11840 env->prog = new_prog;
11841 insns = new_prog->insnsi;
11842 aux = env->insn_aux_data;
Jiong Wangd6c2308c2019-05-24 23:25:18 +010011843 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011844 }
11845
11846 return 0;
11847}
11848
Joe Stringerc64b7982018-10-02 13:35:33 -070011849/* convert load instructions that access fields of a context type into a
11850 * sequence of instructions that access fields of the underlying structure:
11851 * struct __sk_buff -> struct sk_buff
11852 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011853 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011854static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011855{
Jakub Kicinski00176a32017-10-16 16:40:54 -070011856 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011857 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011858 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011859 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011860 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011861 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011862 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011863 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011864
Daniel Borkmannb09928b2018-10-24 22:05:49 +020011865 if (ops->gen_prologue || env->seen_direct_write) {
11866 if (!ops->gen_prologue) {
11867 verbose(env, "bpf verifier is misconfigured\n");
11868 return -EINVAL;
11869 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011870 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11871 env->prog);
11872 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011873 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011874 return -EINVAL;
11875 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070011876 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011877 if (!new_prog)
11878 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011879
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011880 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011881 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011882 }
11883 }
11884
Joe Stringerc64b7982018-10-02 13:35:33 -070011885 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011886 return 0;
11887
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011888 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011889
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011890 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070011891 bpf_convert_ctx_access_t convert_ctx_access;
Daniel Borkmann2039f262021-07-13 08:18:31 +000011892 bool ctx_access;
Joe Stringerc64b7982018-10-02 13:35:33 -070011893
Daniel Borkmann62c79892017-01-12 11:51:33 +010011894 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11895 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11896 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Daniel Borkmann2039f262021-07-13 08:18:31 +000011897 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011898 type = BPF_READ;
Daniel Borkmann2039f262021-07-13 08:18:31 +000011899 ctx_access = true;
11900 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11901 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11902 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
11903 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
11904 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
11905 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
11906 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
11907 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011908 type = BPF_WRITE;
Daniel Borkmann2039f262021-07-13 08:18:31 +000011909 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
11910 } else {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011911 continue;
Daniel Borkmann2039f262021-07-13 08:18:31 +000011912 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011913
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011914 if (type == BPF_WRITE &&
Daniel Borkmann2039f262021-07-13 08:18:31 +000011915 env->insn_aux_data[i + delta].sanitize_stack_spill) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011916 struct bpf_insn patch[] = {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011917 *insn,
Daniel Borkmann2039f262021-07-13 08:18:31 +000011918 BPF_ST_NOSPEC(),
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011919 };
11920
11921 cnt = ARRAY_SIZE(patch);
11922 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11923 if (!new_prog)
11924 return -ENOMEM;
11925
11926 delta += cnt - 1;
11927 env->prog = new_prog;
11928 insn = new_prog->insnsi + i + delta;
11929 continue;
11930 }
11931
Daniel Borkmann2039f262021-07-13 08:18:31 +000011932 if (!ctx_access)
11933 continue;
11934
Joe Stringerc64b7982018-10-02 13:35:33 -070011935 switch (env->insn_aux_data[i + delta].ptr_type) {
11936 case PTR_TO_CTX:
11937 if (!ops->convert_ctx_access)
11938 continue;
11939 convert_ctx_access = ops->convert_ctx_access;
11940 break;
11941 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011942 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070011943 convert_ctx_access = bpf_sock_convert_ctx_access;
11944 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011945 case PTR_TO_TCP_SOCK:
11946 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11947 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011948 case PTR_TO_XDP_SOCK:
11949 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11950 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011951 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011952 if (type == BPF_READ) {
11953 insn->code = BPF_LDX | BPF_PROBE_MEM |
11954 BPF_SIZE((insn)->code);
11955 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070011956 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011957 verbose(env, "Writes through BTF pointers are not allowed\n");
11958 return -EINVAL;
11959 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011960 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011961 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011962 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011963 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011964
Yonghong Song31fd8582017-06-13 15:52:13 -070011965 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011966 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070011967
11968 /* If the read access is a narrower load of the field,
11969 * convert to a 4/8-byte load, to minimum program type specific
11970 * convert_ctx_access changes. If conversion is successful,
11971 * we will apply proper mask to the result.
11972 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020011973 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011974 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11975 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070011976 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020011977 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070011978
Daniel Borkmannf96da092017-07-02 02:13:27 +020011979 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011980 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020011981 return -EINVAL;
11982 }
11983
11984 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070011985 if (ctx_field_size == 4)
11986 size_code = BPF_W;
11987 else if (ctx_field_size == 8)
11988 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011989
Daniel Borkmannbc231052018-06-02 23:06:39 +020011990 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070011991 insn->code = BPF_LDX | BPF_MEM | size_code;
11992 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011993
11994 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070011995 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11996 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020011997 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11998 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011999 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012000 return -EINVAL;
12001 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020012002
12003 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020012004 u8 shift = bpf_ctx_narrow_access_offset(
12005 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012006 if (ctx_field_size <= 4) {
12007 if (shift)
12008 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12009 insn->dst_reg,
12010 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070012011 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020012012 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012013 } else {
12014 if (shift)
12015 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12016 insn->dst_reg,
12017 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070012018 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020012019 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012020 }
Yonghong Song31fd8582017-06-13 15:52:13 -070012021 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012022
Alexei Starovoitov80419022017-03-15 18:26:41 -070012023 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012024 if (!new_prog)
12025 return -ENOMEM;
12026
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012027 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012028
12029 /* keep walking new program and skip insns we just inserted */
12030 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012031 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012032 }
12033
12034 return 0;
12035}
12036
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012037static int jit_subprogs(struct bpf_verifier_env *env)
12038{
12039 struct bpf_prog *prog = env->prog, **func, *tmp;
12040 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012041 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010012042 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012043 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070012044 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012045
Jiong Wangf910cef2018-05-02 16:17:17 -040012046 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012047 return 0;
12048
Daniel Borkmann7105e822017-12-20 13:42:57 +010012049 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012050 if (bpf_pseudo_func(insn)) {
12051 env->insn_aux_data[i].call_imm = insn->imm;
12052 /* subprog is encoded in insn[1].imm */
12053 continue;
12054 }
12055
Yonghong Song23a2d702021-02-04 15:48:27 -080012056 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012057 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012058 /* Upon error here we cannot fall back to interpreter but
12059 * need a hard reject of the program. Thus -EFAULT is
12060 * propagated in any case.
12061 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012062 subprog = find_subprog(env, i + insn->imm + 1);
12063 if (subprog < 0) {
12064 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12065 i + insn->imm + 1);
12066 return -EFAULT;
12067 }
12068 /* temporarily remember subprog id inside insn instead of
12069 * aux_data, since next loop will split up all insns into funcs
12070 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012071 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012072 /* remember original imm in case JIT fails and fallback
12073 * to interpreter will be needed
12074 */
12075 env->insn_aux_data[i].call_imm = insn->imm;
12076 /* point imm to __bpf_call_base+1 from JITs point of view */
12077 insn->imm = 1;
12078 }
12079
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012080 err = bpf_prog_alloc_jited_linfo(prog);
12081 if (err)
12082 goto out_undo_insn;
12083
12084 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070012085 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012086 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012087 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012088
Jiong Wangf910cef2018-05-02 16:17:17 -040012089 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012090 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040012091 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012092
12093 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012094 /* BPF_PROG_RUN doesn't call subprogs directly,
12095 * hence main prog stats include the runtime of subprogs.
12096 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080012097 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012098 */
12099 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012100 if (!func[i])
12101 goto out_free;
12102 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12103 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012104 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012105 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012106 if (bpf_prog_calc_tag(func[i]))
12107 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012108 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080012109 func[i]->aux->func_idx = i;
John Fastabendf263a812021-07-07 15:38:47 -070012110 /* Below members will be freed only at prog->aux */
Yonghong Songba64e7d2018-11-24 23:20:44 -080012111 func[i]->aux->btf = prog->aux->btf;
12112 func[i]->aux->func_info = prog->aux->func_info;
John Fastabendf263a812021-07-07 15:38:47 -070012113 func[i]->aux->poke_tab = prog->aux->poke_tab;
12114 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
Yonghong Songba64e7d2018-11-24 23:20:44 -080012115
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012116 for (j = 0; j < prog->aux->size_poke_tab; j++) {
John Fastabendf263a812021-07-07 15:38:47 -070012117 struct bpf_jit_poke_descriptor *poke;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012118
John Fastabendf263a812021-07-07 15:38:47 -070012119 poke = &prog->aux->poke_tab[j];
12120 if (poke->insn_idx < subprog_end &&
12121 poke->insn_idx >= subprog_start)
12122 poke->aux = func[i]->aux;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012123 }
12124
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012125 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12126 * Long term would need debug info to populate names
12127 */
12128 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040012129 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012130 func[i]->jit_requested = 1;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012131 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012132 func[i]->aux->linfo = prog->aux->linfo;
12133 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12134 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12135 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070012136 num_exentries = 0;
12137 insn = func[i]->insnsi;
12138 for (j = 0; j < func[i]->len; j++, insn++) {
12139 if (BPF_CLASS(insn->code) == BPF_LDX &&
12140 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12141 num_exentries++;
12142 }
12143 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020012144 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012145 func[i] = bpf_int_jit_compile(func[i]);
12146 if (!func[i]->jited) {
12147 err = -ENOTSUPP;
12148 goto out_free;
12149 }
12150 cond_resched();
12151 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012152
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012153 /* at this point all bpf functions were successfully JITed
12154 * now populate all bpf_calls with correct addresses and
12155 * run last pass of JIT
12156 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012157 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012158 insn = func[i]->insnsi;
12159 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012160 if (bpf_pseudo_func(insn)) {
12161 subprog = insn[1].imm;
12162 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12163 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12164 continue;
12165 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012166 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012167 continue;
12168 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090012169 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
12170 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012171 }
Sandipan Das2162fed2018-05-24 12:26:45 +053012172
12173 /* we use the aux data to keep a list of the start addresses
12174 * of the JITed images for each function in the program
12175 *
12176 * for some architectures, such as powerpc64, the imm field
12177 * might not be large enough to hold the offset of the start
12178 * address of the callee's JITed image from __bpf_call_base
12179 *
12180 * in such cases, we can lookup the start address of a callee
12181 * by using its subprog id, available from the off field of
12182 * the call instruction, as an index for this list
12183 */
12184 func[i]->aux->func = func;
12185 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012186 }
Jiong Wangf910cef2018-05-02 16:17:17 -040012187 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012188 old_bpf_func = func[i]->bpf_func;
12189 tmp = bpf_int_jit_compile(func[i]);
12190 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12191 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012192 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012193 goto out_free;
12194 }
12195 cond_resched();
12196 }
12197
12198 /* finally lock prog and jit images for all functions and
12199 * populate kallsysm
12200 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012201 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012202 bpf_prog_lock_ro(func[i]);
12203 bpf_prog_kallsyms_add(func[i]);
12204 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010012205
12206 /* Last step: make now unused interpreter insns from main
12207 * prog consistent for later dump requests, so they can
12208 * later look the same as if they were interpreted only.
12209 */
12210 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012211 if (bpf_pseudo_func(insn)) {
12212 insn[0].imm = env->insn_aux_data[i].call_imm;
12213 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
12214 continue;
12215 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012216 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010012217 continue;
12218 insn->off = env->insn_aux_data[i].call_imm;
12219 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053012220 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010012221 }
12222
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012223 prog->jited = 1;
12224 prog->bpf_func = func[0]->bpf_func;
12225 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040012226 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012227 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012228 return 0;
12229out_free:
John Fastabendf263a812021-07-07 15:38:47 -070012230 /* We failed JIT'ing, so at this point we need to unregister poke
12231 * descriptors from subprogs, so that kernel is not attempting to
12232 * patch it anymore as we're freeing the subprog JIT memory.
12233 */
12234 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12235 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12236 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12237 }
12238 /* At this point we're guaranteed that poke descriptors are not
12239 * live anymore. We can just unlink its descriptor table as it's
12240 * released with the main prog.
12241 */
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012242 for (i = 0; i < env->subprog_cnt; i++) {
12243 if (!func[i])
12244 continue;
John Fastabendf263a812021-07-07 15:38:47 -070012245 func[i]->aux->poke_tab = NULL;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012246 bpf_jit_free(func[i]);
12247 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012248 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012249out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012250 /* cleanup main prog to be interpreted */
12251 prog->jit_requested = 0;
12252 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080012253 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012254 continue;
12255 insn->off = 0;
12256 insn->imm = env->insn_aux_data[i].call_imm;
12257 }
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012258 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012259 return err;
12260}
12261
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012262static int fixup_call_args(struct bpf_verifier_env *env)
12263{
David S. Miller19d28fb2018-01-11 21:27:54 -050012264#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012265 struct bpf_prog *prog = env->prog;
12266 struct bpf_insn *insn = prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012267 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012268 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050012269#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010012270 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012271
Quentin Monnete4052d02018-10-07 12:56:58 +010012272 if (env->prog->jit_requested &&
12273 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050012274 err = jit_subprogs(env);
12275 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012276 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012277 if (err == -EFAULT)
12278 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050012279 }
12280#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012281 if (has_kfunc_call) {
12282 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
12283 return -EINVAL;
12284 }
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020012285 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
12286 /* When JIT fails the progs with bpf2bpf calls and tail_calls
12287 * have to be rejected, since interpreter doesn't support them yet.
12288 */
12289 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
12290 return -EINVAL;
12291 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012292 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012293 if (bpf_pseudo_func(insn)) {
12294 /* When JIT fails the progs with callback calls
12295 * have to be rejected, since interpreter doesn't support them yet.
12296 */
12297 verbose(env, "callbacks are not allowed in non-JITed programs\n");
12298 return -EINVAL;
12299 }
12300
Yonghong Song23a2d702021-02-04 15:48:27 -080012301 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012302 continue;
12303 depth = get_callee_stack_depth(env, insn, i);
12304 if (depth < 0)
12305 return depth;
12306 bpf_patch_call_args(insn, depth);
12307 }
David S. Miller19d28fb2018-01-11 21:27:54 -050012308 err = 0;
12309#endif
12310 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012311}
12312
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012313static int fixup_kfunc_call(struct bpf_verifier_env *env,
12314 struct bpf_insn *insn)
12315{
12316 const struct bpf_kfunc_desc *desc;
12317
12318 /* insn->imm has the btf func_id. Replace it with
12319 * an address (relative to __bpf_base_call).
12320 */
12321 desc = find_kfunc_desc(env->prog, insn->imm);
12322 if (!desc) {
12323 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
12324 insn->imm);
12325 return -EFAULT;
12326 }
12327
12328 insn->imm = desc->imm;
12329
12330 return 0;
12331}
12332
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012333/* Do various post-verification rewrites in a single program pass.
12334 * These rewrites simplify JIT and interpreter implementations.
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012335 */
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012336static int do_misc_fixups(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012337{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012338 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012339 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012340 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012341 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012342 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020012343 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012344 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012345 struct bpf_insn insn_buf[16];
12346 struct bpf_prog *new_prog;
12347 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012348 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012349
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012350 for (i = 0; i < insn_cnt; i++, insn++) {
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012351 /* Make divide-by-zero exceptions impossible. */
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012352 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
12353 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
12354 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080012355 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012356 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012357 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
12358 struct bpf_insn *patchlet;
12359 struct bpf_insn chk_and_div[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012360 /* [R,W]x div 0 -> 0 */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012361 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12362 BPF_JNE | BPF_K, insn->src_reg,
12363 0, 2, 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012364 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
12365 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12366 *insn,
12367 };
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012368 struct bpf_insn chk_and_mod[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012369 /* [R,W]x mod 0 -> [R,W]x */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012370 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
12371 BPF_JEQ | BPF_K, insn->src_reg,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012372 0, 1 + (is64 ? 0 : 1), 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012373 *insn,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012374 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
12375 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012376 };
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012377
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000012378 patchlet = isdiv ? chk_and_div : chk_and_mod;
12379 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010012380 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010012381
12382 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080012383 if (!new_prog)
12384 return -ENOMEM;
12385
12386 delta += cnt - 1;
12387 env->prog = prog = new_prog;
12388 insn = new_prog->insnsi + i + delta;
12389 continue;
12390 }
12391
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012392 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020012393 if (BPF_CLASS(insn->code) == BPF_LD &&
12394 (BPF_MODE(insn->code) == BPF_ABS ||
12395 BPF_MODE(insn->code) == BPF_IND)) {
12396 cnt = env->ops->gen_ld_abs(insn, insn_buf);
12397 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
12398 verbose(env, "bpf verifier is misconfigured\n");
12399 return -EINVAL;
12400 }
12401
12402 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12403 if (!new_prog)
12404 return -ENOMEM;
12405
12406 delta += cnt - 1;
12407 env->prog = prog = new_prog;
12408 insn = new_prog->insnsi + i + delta;
12409 continue;
12410 }
12411
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012412 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012413 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
12414 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
12415 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
12416 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012417 struct bpf_insn *patch = &insn_buf[0];
Daniel Borkmann801c6052021-04-29 15:19:37 +000012418 bool issrc, isneg, isimm;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012419 u32 off_reg;
12420
12421 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010012422 if (!aux->alu_state ||
12423 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012424 continue;
12425
12426 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
12427 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
12428 BPF_ALU_SANITIZE_SRC;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012429 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012430
12431 off_reg = issrc ? insn->src_reg : insn->dst_reg;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012432 if (isimm) {
12433 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12434 } else {
12435 if (isneg)
12436 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12437 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
12438 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
12439 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
12440 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
12441 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
12442 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
12443 }
Daniel Borkmannb9b34dd2021-04-30 16:21:46 +020012444 if (!issrc)
12445 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
12446 insn->src_reg = BPF_REG_AX;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012447 if (isneg)
12448 insn->code = insn->code == code_add ?
12449 code_sub : code_add;
12450 *patch++ = *insn;
Daniel Borkmann801c6052021-04-29 15:19:37 +000012451 if (issrc && isneg && !isimm)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010012452 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
12453 cnt = patch - insn_buf;
12454
12455 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12456 if (!new_prog)
12457 return -ENOMEM;
12458
12459 delta += cnt - 1;
12460 env->prog = prog = new_prog;
12461 insn = new_prog->insnsi + i + delta;
12462 continue;
12463 }
12464
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012465 if (insn->code != (BPF_JMP | BPF_CALL))
12466 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012467 if (insn->src_reg == BPF_PSEUDO_CALL)
12468 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012469 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
12470 ret = fixup_kfunc_call(env, insn);
12471 if (ret)
12472 return ret;
12473 continue;
12474 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012475
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012476 if (insn->imm == BPF_FUNC_get_route_realm)
12477 prog->dst_needed = 1;
12478 if (insn->imm == BPF_FUNC_get_prandom_u32)
12479 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050012480 if (insn->imm == BPF_FUNC_override_return)
12481 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012482 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040012483 /* If we tail call into other programs, we
12484 * cannot make any assumptions since they can
12485 * be replaced dynamically during runtime in
12486 * the program array.
12487 */
12488 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020012489 if (!allow_tail_call_in_subprogs(env))
12490 prog->aux->stack_depth = MAX_BPF_STACK;
12491 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040012492
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012493 /* mark bpf_tail_call as different opcode to avoid
Zhen Lei8fb33b62021-05-25 10:56:59 +080012494 * conditional branch in the interpreter for every normal
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012495 * call and to prevent accidental JITing by JIT compiler
12496 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012497 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012498 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070012499 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012500
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012501 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012502 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010012503 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012504 !bpf_map_key_poisoned(aux) &&
12505 !bpf_map_ptr_poisoned(aux) &&
12506 !bpf_map_ptr_unpriv(aux)) {
12507 struct bpf_jit_poke_descriptor desc = {
12508 .reason = BPF_POKE_REASON_TAIL_CALL,
12509 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
12510 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012511 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012512 };
12513
12514 ret = bpf_jit_add_poke_descriptor(prog, &desc);
12515 if (ret < 0) {
12516 verbose(env, "adding tail call poke descriptor failed\n");
12517 return ret;
12518 }
12519
12520 insn->imm = ret + 1;
12521 continue;
12522 }
12523
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012524 if (!bpf_map_ptr_unpriv(aux))
12525 continue;
12526
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012527 /* instead of changing every JIT dealing with tail_call
12528 * emit two extra insns:
12529 * if (index >= max_entries) goto out;
12530 * index &= array->index_mask;
12531 * to avoid out-of-bounds cpu speculation
12532 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012533 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000012534 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012535 return -EINVAL;
12536 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012537
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012538 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080012539 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
12540 map_ptr->max_entries, 2);
12541 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
12542 container_of(map_ptr,
12543 struct bpf_array,
12544 map)->index_mask);
12545 insn_buf[2] = *insn;
12546 cnt = 3;
12547 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
12548 if (!new_prog)
12549 return -ENOMEM;
12550
12551 delta += cnt - 1;
12552 env->prog = prog = new_prog;
12553 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012554 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012555 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012556
Daniel Borkmann89c63072017-08-19 03:12:45 +020012557 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020012558 * and other inlining handlers are currently limited to 64 bit
12559 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020012560 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080012561 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020012562 (insn->imm == BPF_FUNC_map_lookup_elem ||
12563 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020012564 insn->imm == BPF_FUNC_map_delete_elem ||
12565 insn->imm == BPF_FUNC_map_push_elem ||
12566 insn->imm == BPF_FUNC_map_pop_elem ||
Björn Töpele6a47502021-03-08 12:29:06 +010012567 insn->imm == BPF_FUNC_map_peek_elem ||
12568 insn->imm == BPF_FUNC_redirect_map)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020012569 aux = &env->insn_aux_data[i + delta];
12570 if (bpf_map_ptr_poisoned(aux))
12571 goto patch_call_imm;
12572
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012573 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020012574 ops = map_ptr->ops;
12575 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12576 ops->map_gen_lookup) {
12577 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012578 if (cnt == -EOPNOTSUPP)
12579 goto patch_map_ops_generic;
12580 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020012581 verbose(env, "bpf verifier is misconfigured\n");
12582 return -EINVAL;
12583 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012584
Daniel Borkmann09772d92018-06-02 23:06:35 +020012585 new_prog = bpf_patch_insn_data(env, i + delta,
12586 insn_buf, cnt);
12587 if (!new_prog)
12588 return -ENOMEM;
12589
12590 delta += cnt - 1;
12591 env->prog = prog = new_prog;
12592 insn = new_prog->insnsi + i + delta;
12593 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012594 }
12595
Daniel Borkmann09772d92018-06-02 23:06:35 +020012596 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12597 (void *(*)(struct bpf_map *map, void *key))NULL));
12598 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12599 (int (*)(struct bpf_map *map, void *key))NULL));
12600 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12601 (int (*)(struct bpf_map *map, void *key, void *value,
12602 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020012603 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12604 (int (*)(struct bpf_map *map, void *value,
12605 u64 flags))NULL));
12606 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12607 (int (*)(struct bpf_map *map, void *value))NULL));
12608 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12609 (int (*)(struct bpf_map *map, void *value))NULL));
Björn Töpele6a47502021-03-08 12:29:06 +010012610 BUILD_BUG_ON(!__same_type(ops->map_redirect,
12611 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
12612
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012613patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020012614 switch (insn->imm) {
12615 case BPF_FUNC_map_lookup_elem:
12616 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12617 __bpf_call_base;
12618 continue;
12619 case BPF_FUNC_map_update_elem:
12620 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12621 __bpf_call_base;
12622 continue;
12623 case BPF_FUNC_map_delete_elem:
12624 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12625 __bpf_call_base;
12626 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020012627 case BPF_FUNC_map_push_elem:
12628 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12629 __bpf_call_base;
12630 continue;
12631 case BPF_FUNC_map_pop_elem:
12632 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12633 __bpf_call_base;
12634 continue;
12635 case BPF_FUNC_map_peek_elem:
12636 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12637 __bpf_call_base;
12638 continue;
Björn Töpele6a47502021-03-08 12:29:06 +010012639 case BPF_FUNC_redirect_map:
12640 insn->imm = BPF_CAST_CALL(ops->map_redirect) -
12641 __bpf_call_base;
12642 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020012643 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012644
Daniel Borkmann09772d92018-06-02 23:06:35 +020012645 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012646 }
12647
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012648 /* Implement bpf_jiffies64 inline. */
Martin KaFai Lau5576b992020-01-22 15:36:46 -080012649 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12650 insn->imm == BPF_FUNC_jiffies64) {
12651 struct bpf_insn ld_jiffies_addr[2] = {
12652 BPF_LD_IMM64(BPF_REG_0,
12653 (unsigned long)&jiffies),
12654 };
12655
12656 insn_buf[0] = ld_jiffies_addr[0];
12657 insn_buf[1] = ld_jiffies_addr[1];
12658 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12659 BPF_REG_0, 0);
12660 cnt = 3;
12661
12662 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12663 cnt);
12664 if (!new_prog)
12665 return -ENOMEM;
12666
12667 delta += cnt - 1;
12668 env->prog = prog = new_prog;
12669 insn = new_prog->insnsi + i + delta;
12670 continue;
12671 }
12672
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012673patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070012674 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012675 /* all functions that have prototype and verifier allowed
12676 * programs to call them, must be real in-kernel functions
12677 */
12678 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012679 verbose(env,
12680 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012681 func_id_name(insn->imm), insn->imm);
12682 return -EFAULT;
12683 }
12684 insn->imm = fn->func - __bpf_call_base;
12685 }
12686
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012687 /* Since poke tab is now finalized, publish aux to tracker. */
12688 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12689 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12690 if (!map_ptr->ops->map_poke_track ||
12691 !map_ptr->ops->map_poke_untrack ||
12692 !map_ptr->ops->map_poke_run) {
12693 verbose(env, "bpf verifier is misconfigured\n");
12694 return -EINVAL;
12695 }
12696
12697 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12698 if (ret < 0) {
12699 verbose(env, "tracking tail call prog failed\n");
12700 return ret;
12701 }
12702 }
12703
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012704 sort_kfunc_descs_by_imm(env->prog);
12705
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012706 return 0;
12707}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012708
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012709static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012710{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012711 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012712 int i;
12713
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012714 sl = env->free_list;
12715 while (sl) {
12716 sln = sl->next;
12717 free_verifier_state(&sl->state, false);
12718 kfree(sl);
12719 sl = sln;
12720 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012721 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012722
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012723 if (!env->explored_states)
12724 return;
12725
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012726 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012727 sl = env->explored_states[i];
12728
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070012729 while (sl) {
12730 sln = sl->next;
12731 free_verifier_state(&sl->state, false);
12732 kfree(sl);
12733 sl = sln;
12734 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012735 env->explored_states[i] = NULL;
12736 }
12737}
12738
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012739static int do_check_common(struct bpf_verifier_env *env, int subprog)
12740{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012741 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012742 struct bpf_verifier_state *state;
12743 struct bpf_reg_state *regs;
12744 int ret, i;
12745
12746 env->prev_linfo = NULL;
12747 env->pass_cnt++;
12748
12749 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12750 if (!state)
12751 return -ENOMEM;
12752 state->curframe = 0;
12753 state->speculative = false;
12754 state->branches = 1;
12755 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12756 if (!state->frame[0]) {
12757 kfree(state);
12758 return -ENOMEM;
12759 }
12760 env->cur_state = state;
12761 init_func_state(env, state->frame[0],
12762 BPF_MAIN_FUNC /* callsite */,
12763 0 /* frameno */,
12764 subprog);
12765
12766 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012767 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012768 ret = btf_prepare_func_args(env, subprog, regs);
12769 if (ret)
12770 goto out;
12771 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12772 if (regs[i].type == PTR_TO_CTX)
12773 mark_reg_known_zero(env, regs, i);
12774 else if (regs[i].type == SCALAR_VALUE)
12775 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040012776 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12777 const u32 mem_size = regs[i].mem_size;
12778
12779 mark_reg_known_zero(env, regs, i);
12780 regs[i].mem_size = mem_size;
12781 regs[i].id = ++env->id_gen;
12782 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012783 }
12784 } else {
12785 /* 1st arg to a function */
12786 regs[BPF_REG_1].type = PTR_TO_CTX;
12787 mark_reg_known_zero(env, regs, BPF_REG_1);
Martin KaFai Lau34747c42021-03-24 18:51:36 -070012788 ret = btf_check_subprog_arg_match(env, subprog, regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012789 if (ret == -EFAULT)
12790 /* unlikely verifier bug. abort.
12791 * ret == 0 and ret < 0 are sadly acceptable for
12792 * main() function due to backward compatibility.
12793 * Like socket filter program may be written as:
12794 * int bpf_prog(struct pt_regs *ctx)
12795 * and never dereference that ctx in the program.
12796 * 'struct pt_regs' is a type mismatch for socket
12797 * filter that should be using 'struct __sk_buff'.
12798 */
12799 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012800 }
12801
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012802 ret = do_check(env);
12803out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080012804 /* check for NULL is necessary, since cur_state can be freed inside
12805 * do_check() under memory pressure.
12806 */
12807 if (env->cur_state) {
12808 free_verifier_state(env->cur_state, true);
12809 env->cur_state = NULL;
12810 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012811 while (!pop_stack(env, NULL, NULL, false));
12812 if (!ret && pop_log)
12813 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012814 free_states(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012815 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012816}
12817
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012818/* Verify all global functions in a BPF program one by one based on their BTF.
12819 * All global functions must pass verification. Otherwise the whole program is rejected.
12820 * Consider:
12821 * int bar(int);
12822 * int foo(int f)
12823 * {
12824 * return bar(f);
12825 * }
12826 * int bar(int b)
12827 * {
12828 * ...
12829 * }
12830 * foo() will be verified first for R1=any_scalar_value. During verification it
12831 * will be assumed that bar() already verified successfully and call to bar()
12832 * from foo() will be checked for type match only. Later bar() will be verified
12833 * independently to check that it's safe for R1=any_scalar_value.
12834 */
12835static int do_check_subprogs(struct bpf_verifier_env *env)
12836{
12837 struct bpf_prog_aux *aux = env->prog->aux;
12838 int i, ret;
12839
12840 if (!aux->func_info)
12841 return 0;
12842
12843 for (i = 1; i < env->subprog_cnt; i++) {
12844 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12845 continue;
12846 env->insn_idx = env->subprog_info[i].start;
12847 WARN_ON_ONCE(env->insn_idx == 0);
12848 ret = do_check_common(env, i);
12849 if (ret) {
12850 return ret;
12851 } else if (env->log.level & BPF_LOG_LEVEL) {
12852 verbose(env,
12853 "Func#%d is safe for any args that match its prototype\n",
12854 i);
12855 }
12856 }
12857 return 0;
12858}
12859
12860static int do_check_main(struct bpf_verifier_env *env)
12861{
12862 int ret;
12863
12864 env->insn_idx = 0;
12865 ret = do_check_common(env, 0);
12866 if (!ret)
12867 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12868 return ret;
12869}
12870
12871
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012872static void print_verification_stats(struct bpf_verifier_env *env)
12873{
12874 int i;
12875
12876 if (env->log.level & BPF_LOG_STATS) {
12877 verbose(env, "verification time %lld usec\n",
12878 div_u64(env->verification_time, 1000));
12879 verbose(env, "stack depth ");
12880 for (i = 0; i < env->subprog_cnt; i++) {
12881 u32 depth = env->subprog_info[i].stack_depth;
12882
12883 verbose(env, "%d", depth);
12884 if (i + 1 < env->subprog_cnt)
12885 verbose(env, "+");
12886 }
12887 verbose(env, "\n");
12888 }
12889 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12890 "total_states %d peak_states %d mark_read %d\n",
12891 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12892 env->max_states_per_insn, env->total_states,
12893 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012894}
12895
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012896static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12897{
12898 const struct btf_type *t, *func_proto;
12899 const struct bpf_struct_ops *st_ops;
12900 const struct btf_member *member;
12901 struct bpf_prog *prog = env->prog;
12902 u32 btf_id, member_idx;
12903 const char *mname;
12904
Toke Høiland-Jørgensen12aa8a92021-03-26 11:03:13 +010012905 if (!prog->gpl_compatible) {
12906 verbose(env, "struct ops programs must have a GPL compatible license\n");
12907 return -EINVAL;
12908 }
12909
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012910 btf_id = prog->aux->attach_btf_id;
12911 st_ops = bpf_struct_ops_find(btf_id);
12912 if (!st_ops) {
12913 verbose(env, "attach_btf_id %u is not a supported struct\n",
12914 btf_id);
12915 return -ENOTSUPP;
12916 }
12917
12918 t = st_ops->type;
12919 member_idx = prog->expected_attach_type;
12920 if (member_idx >= btf_type_vlen(t)) {
12921 verbose(env, "attach to invalid member idx %u of struct %s\n",
12922 member_idx, st_ops->name);
12923 return -EINVAL;
12924 }
12925
12926 member = &btf_type_member(t)[member_idx];
12927 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12928 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12929 NULL);
12930 if (!func_proto) {
12931 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12932 mname, member_idx, st_ops->name);
12933 return -EINVAL;
12934 }
12935
12936 if (st_ops->check_member) {
12937 int err = st_ops->check_member(t, member);
12938
12939 if (err) {
12940 verbose(env, "attach to unsupported member %s of struct %s\n",
12941 mname, st_ops->name);
12942 return err;
12943 }
12944 }
12945
12946 prog->aux->attach_func_proto = func_proto;
12947 prog->aux->attach_func_name = mname;
12948 env->ops = st_ops->verifier_ops;
12949
12950 return 0;
12951}
KP Singh6ba43b72020-03-04 20:18:50 +010012952#define SECURITY_PREFIX "security_"
12953
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012954static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010012955{
KP Singh69191752020-03-05 21:49:55 +010012956 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012957 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010012958 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010012959
KP Singh6ba43b72020-03-04 20:18:50 +010012960 return -EINVAL;
12961}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012962
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012963/* list of non-sleepable functions that are otherwise on
12964 * ALLOW_ERROR_INJECTION list
12965 */
12966BTF_SET_START(btf_non_sleepable_error_inject)
12967/* Three functions below can be called from sleepable and non-sleepable context.
12968 * Assume non-sleepable from bpf safety point of view.
12969 */
12970BTF_ID(func, __add_to_page_cache_locked)
12971BTF_ID(func, should_fail_alloc_page)
12972BTF_ID(func, should_failslab)
12973BTF_SET_END(btf_non_sleepable_error_inject)
12974
12975static int check_non_sleepable_error_inject(u32 btf_id)
12976{
12977 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12978}
12979
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012980int bpf_check_attach_target(struct bpf_verifier_log *log,
12981 const struct bpf_prog *prog,
12982 const struct bpf_prog *tgt_prog,
12983 u32 btf_id,
12984 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070012985{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012986 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012987 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012988 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012989 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012990 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012991 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012992 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012993 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012994
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012995 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012996 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012997 return -EINVAL;
12998 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012999 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013000 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013001 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013002 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13003 return -EINVAL;
13004 }
13005 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013006 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013007 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013008 return -EINVAL;
13009 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013010 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013011 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013012 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013013 return -EINVAL;
13014 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013015 if (tgt_prog) {
13016 struct bpf_prog_aux *aux = tgt_prog->aux;
13017
13018 for (i = 0; i < aux->func_info_cnt; i++)
13019 if (aux->func_info[i].type_id == btf_id) {
13020 subprog = i;
13021 break;
13022 }
13023 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013024 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013025 return -EINVAL;
13026 }
13027 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013028 if (prog_extension) {
13029 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013030 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013031 "Cannot replace static functions\n");
13032 return -EINVAL;
13033 }
13034 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013035 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013036 "Extension programs should be JITed\n");
13037 return -EINVAL;
13038 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013039 }
13040 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013041 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013042 return -EINVAL;
13043 }
13044 if (tgt_prog->type == prog->type) {
13045 /* Cannot fentry/fexit another fentry/fexit program.
13046 * Cannot attach program extension to another extension.
13047 * It's ok to attach fentry/fexit to extension program.
13048 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013049 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013050 return -EINVAL;
13051 }
13052 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13053 prog_extension &&
13054 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13055 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13056 /* Program extensions can extend all program types
13057 * except fentry/fexit. The reason is the following.
13058 * The fentry/fexit programs are used for performance
13059 * analysis, stats and can be attached to any program
13060 * type except themselves. When extension program is
13061 * replacing XDP function it is necessary to allow
13062 * performance analysis of all functions. Both original
13063 * XDP program and its program extension. Hence
13064 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13065 * allowed. If extending of fentry/fexit was allowed it
13066 * would be possible to create long call chain
13067 * fentry->extension->fentry->extension beyond
13068 * reasonable stack size. Hence extending fentry is not
13069 * allowed.
13070 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013071 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013072 return -EINVAL;
13073 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013074 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013075 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013076 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013077 return -EINVAL;
13078 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013079 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013080
13081 switch (prog->expected_attach_type) {
13082 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013083 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013084 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013085 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13086 return -EINVAL;
13087 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070013088 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013089 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013090 btf_id);
13091 return -EINVAL;
13092 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013093 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013094 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013095 btf_id, tname);
13096 return -EINVAL;
13097 }
13098 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013099 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013100 if (!btf_type_is_ptr(t))
13101 /* should never happen in valid vmlinux build */
13102 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013103 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013104 if (!btf_type_is_func_proto(t))
13105 /* should never happen in valid vmlinux build */
13106 return -EINVAL;
13107
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013108 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070013109 case BPF_TRACE_ITER:
13110 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013111 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070013112 btf_id);
13113 return -EINVAL;
13114 }
13115 t = btf_type_by_id(btf, t->type);
13116 if (!btf_type_is_func_proto(t))
13117 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013118 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13119 if (ret)
13120 return ret;
13121 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013122 default:
13123 if (!prog_extension)
13124 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050013125 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010013126 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010013127 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013128 case BPF_TRACE_FENTRY:
13129 case BPF_TRACE_FEXIT:
13130 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013131 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013132 btf_id);
13133 return -EINVAL;
13134 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013135 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013136 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013137 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013138 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013139 if (!btf_type_is_func_proto(t))
13140 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013141
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020013142 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13143 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13144 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13145 return -EINVAL;
13146
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013147 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013148 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013149
13150 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013151 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013152 return ret;
13153
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013154 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080013155 if (subprog == 0)
13156 addr = (long) tgt_prog->bpf_func;
13157 else
13158 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013159 } else {
13160 addr = kallsyms_lookup_name(tname);
13161 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013162 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013163 "The address of function %s cannot be found\n",
13164 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013165 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013166 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013167 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070013168
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013169 if (prog->aux->sleepable) {
13170 ret = -EINVAL;
13171 switch (prog->type) {
13172 case BPF_PROG_TYPE_TRACING:
13173 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
13174 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
13175 */
13176 if (!check_non_sleepable_error_inject(btf_id) &&
13177 within_error_injection_list(addr))
13178 ret = 0;
13179 break;
13180 case BPF_PROG_TYPE_LSM:
13181 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
13182 * Only some of them are sleepable.
13183 */
KP Singh423f1612020-11-13 00:59:29 +000013184 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013185 ret = 0;
13186 break;
13187 default:
13188 break;
13189 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013190 if (ret) {
13191 bpf_log(log, "%s is not sleepable\n", tname);
13192 return ret;
13193 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013194 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020013195 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013196 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013197 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020013198 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013199 ret = check_attach_modify_return(addr, tname);
13200 if (ret) {
13201 bpf_log(log, "%s() is not modifiable\n", tname);
13202 return ret;
13203 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070013204 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013205
13206 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013207 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013208 tgt_info->tgt_addr = addr;
13209 tgt_info->tgt_name = tname;
13210 tgt_info->tgt_type = t;
13211 return 0;
13212}
13213
Jiri Olsa35e38152021-04-29 13:47:12 +020013214BTF_SET_START(btf_id_deny)
13215BTF_ID_UNUSED
13216#ifdef CONFIG_SMP
13217BTF_ID(func, migrate_disable)
13218BTF_ID(func, migrate_enable)
13219#endif
13220#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
13221BTF_ID(func, rcu_read_unlock_strict)
13222#endif
13223BTF_SET_END(btf_id_deny)
13224
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013225static int check_attach_btf_id(struct bpf_verifier_env *env)
13226{
13227 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013228 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013229 struct bpf_attach_target_info tgt_info = {};
13230 u32 btf_id = prog->aux->attach_btf_id;
13231 struct bpf_trampoline *tr;
13232 int ret;
13233 u64 key;
13234
Alexei Starovoitov79a7f8b2021-05-13 17:36:03 -070013235 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
13236 if (prog->aux->sleepable)
13237 /* attach_btf_id checked to be zero already */
13238 return 0;
13239 verbose(env, "Syscall programs can only be sleepable\n");
13240 return -EINVAL;
13241 }
13242
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013243 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
13244 prog->type != BPF_PROG_TYPE_LSM) {
13245 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
13246 return -EINVAL;
13247 }
13248
13249 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
13250 return check_struct_ops_btf_id(env);
13251
13252 if (prog->type != BPF_PROG_TYPE_TRACING &&
13253 prog->type != BPF_PROG_TYPE_LSM &&
13254 prog->type != BPF_PROG_TYPE_EXT)
13255 return 0;
13256
13257 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
13258 if (ret)
13259 return ret;
13260
13261 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013262 /* to make freplace equivalent to their targets, they need to
13263 * inherit env->ops and expected_attach_type for the rest of the
13264 * verification
13265 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013266 env->ops = bpf_verifier_ops[tgt_prog->type];
13267 prog->expected_attach_type = tgt_prog->expected_attach_type;
13268 }
13269
13270 /* store info about the attachment target that will be used later */
13271 prog->aux->attach_func_proto = tgt_info.tgt_type;
13272 prog->aux->attach_func_name = tgt_info.tgt_name;
13273
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020013274 if (tgt_prog) {
13275 prog->aux->saved_dst_prog_type = tgt_prog->type;
13276 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
13277 }
13278
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013279 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
13280 prog->aux->attach_btf_trace = true;
13281 return 0;
13282 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
13283 if (!bpf_iter_prog_supported(prog))
13284 return -EINVAL;
13285 return 0;
13286 }
13287
13288 if (prog->type == BPF_PROG_TYPE_LSM) {
13289 ret = bpf_lsm_verify_prog(&env->log, prog);
13290 if (ret < 0)
13291 return ret;
Jiri Olsa35e38152021-04-29 13:47:12 +020013292 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
13293 btf_id_set_contains(&btf_id_deny, btf_id)) {
13294 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013295 }
13296
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080013297 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013298 tr = bpf_trampoline_get(key, &tgt_info);
13299 if (!tr)
13300 return -ENOMEM;
13301
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020013302 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013303 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013304}
13305
Alan Maguire76654e62020-09-28 12:31:03 +010013306struct btf *bpf_get_btf_vmlinux(void)
13307{
13308 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
13309 mutex_lock(&bpf_verifier_lock);
13310 if (!btf_vmlinux)
13311 btf_vmlinux = btf_parse_vmlinux();
13312 mutex_unlock(&bpf_verifier_lock);
13313 }
13314 return btf_vmlinux;
13315}
13316
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070013317int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013318{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013319 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013320 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070013321 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013322 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013323 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013324
Arnd Bergmanneba0c922017-11-02 12:05:52 +010013325 /* no program is valid */
13326 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
13327 return -EINVAL;
13328
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013329 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013330 * allocate/free it every time bpf_check() is called
13331 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013332 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013333 if (!env)
13334 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070013335 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013336
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013337 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070013338 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013339 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013340 ret = -ENOMEM;
13341 if (!env->insn_aux_data)
13342 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080013343 for (i = 0; i < len; i++)
13344 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013345 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070013346 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov387544b2021-05-13 17:36:10 -070013347 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013348 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013349
Alan Maguire76654e62020-09-28 12:31:03 +010013350 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013351
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013352 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070013353 if (!is_priv)
13354 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013355
13356 if (attr->log_level || attr->log_buf || attr->log_size) {
13357 /* user requested verbose verifier output
13358 * and supplied buffer to store the verification trace
13359 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070013360 log->level = attr->log_level;
13361 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
13362 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013363
13364 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070013365 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070013366 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013367 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013368 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013369 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020013370
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013371 if (IS_ERR(btf_vmlinux)) {
13372 /* Either gcc or pahole or kernel are broken. */
13373 verbose(env, "in-kernel BTF is malformed\n");
13374 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013375 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070013376 }
13377
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020013378 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
13379 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070013380 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080013381 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
13382 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013383
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013384 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050013385 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070013386 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013387 env->bypass_spec_v1 = bpf_bypass_spec_v1();
13388 env->bypass_spec_v4 = bpf_bypass_spec_v4();
13389 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013390
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070013391 if (is_priv)
13392 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
13393
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070013394 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013395 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013396 GFP_USER);
13397 ret = -ENOMEM;
13398 if (!env->explored_states)
13399 goto skip_full_check;
13400
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013401 ret = add_subprog_and_kfunc(env);
13402 if (ret < 0)
13403 goto skip_full_check;
13404
Martin KaFai Laud9762e842018-12-13 10:41:48 -080013405 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070013406 if (ret < 0)
13407 goto skip_full_check;
13408
Martin KaFai Lauc454a462018-12-07 16:42:25 -080013409 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080013410 if (ret < 0)
13411 goto skip_full_check;
13412
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013413 ret = check_attach_btf_id(env);
13414 if (ret)
13415 goto skip_full_check;
13416
Hao Luo4976b712020-09-29 16:50:44 -070013417 ret = resolve_pseudo_ldimm64(env);
13418 if (ret < 0)
13419 goto skip_full_check;
13420
Yinjun Zhangceb11672021-05-20 10:58:34 +020013421 if (bpf_prog_is_dev_bound(env->prog->aux)) {
13422 ret = bpf_prog_offload_verifier_prep(env->prog);
13423 if (ret)
13424 goto skip_full_check;
13425 }
13426
Martin KaFai Laud9762e842018-12-13 10:41:48 -080013427 ret = check_cfg(env);
13428 if (ret < 0)
13429 goto skip_full_check;
13430
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013431 ret = do_check_subprogs(env);
13432 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013433
Quentin Monnetc941ce92018-10-07 12:56:47 +010013434 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
13435 ret = bpf_prog_offload_finalize(env);
13436
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013437skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013438 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013439
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013440 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080013441 ret = check_max_stack_depth(env);
13442
Jakub Kicinski9b38c402018-12-19 22:13:06 -080013443 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013444 if (is_priv) {
13445 if (ret == 0)
13446 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080013447 if (ret == 0)
13448 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080013449 if (ret == 0)
13450 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080013451 } else {
13452 if (ret == 0)
13453 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080013454 }
13455
Jakub Kicinski9b38c402018-12-19 22:13:06 -080013456 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013457 /* program is valid, convert *(u32*)(ctx + off) accesses */
13458 ret = convert_ctx_accesses(env);
13459
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013460 if (ret == 0)
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013461 ret = do_misc_fixups(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013462
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010013463 /* do 32-bit optimization after insn patching has done so those patched
13464 * insns could be handled correctly.
13465 */
Jiong Wangd6c2308c2019-05-24 23:25:18 +010013466 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
13467 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
13468 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
13469 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010013470 }
13471
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080013472 if (ret == 0)
13473 ret = fixup_call_args(env);
13474
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013475 env->verification_time = ktime_get_ns() - start_time;
13476 print_verification_stats(env);
13477
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013478 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013479 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013480 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013481 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013482 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013483 }
13484
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013485 if (ret)
13486 goto err_release_maps;
13487
13488 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013489 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013490 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
13491 sizeof(env->used_maps[0]),
13492 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013493
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013494 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013495 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013496 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013497 }
13498
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013499 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013500 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013501 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013502 }
13503 if (env->used_btf_cnt) {
13504 /* if program passed verifier, update used_btfs in bpf_prog_aux */
13505 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
13506 sizeof(env->used_btfs[0]),
13507 GFP_KERNEL);
13508 if (!env->prog->aux->used_btfs) {
13509 ret = -ENOMEM;
13510 goto err_release_maps;
13511 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013512
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013513 memcpy(env->prog->aux->used_btfs, env->used_btfs,
13514 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
13515 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
13516 }
13517 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013518 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
13519 * bpf_ld_imm64 instructions
13520 */
13521 convert_pseudo_ld_imm64(env);
13522 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013523
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013524 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080013525
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070013526err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013527 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013528 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070013529 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070013530 */
13531 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080013532 if (!env->prog->aux->used_btfs)
13533 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020013534
13535 /* extension progs temporarily inherit the attach_type of their targets
13536 for verification purposes, so set it back to zero before returning
13537 */
13538 if (env->prog->type == BPF_PROG_TYPE_EXT)
13539 env->prog->expected_attach_type = 0;
13540
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070013541 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013542err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070013543 if (!is_priv)
13544 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010013545 vfree(env->insn_aux_data);
13546err_free_env:
13547 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013548 return ret;
13549}