blob: 53afe9461b030f411f80867f0953ebcbbfe1b8ef [file] [log] [blame]
Thomas Gleixner5b497af2019-05-29 07:18:09 -07001// SPDX-License-Identifier: GPL-2.0-only
Alexei Starovoitov51580e72014-09-26 00:17:02 -07002/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003 * Copyright (c) 2016 Facebook
Joe Stringerfd978bf72018-10-02 13:35:35 -07004 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
Alexei Starovoitov51580e72014-09-26 00:17:02 -07005 */
Yonghong Song838e9692018-11-19 15:29:11 -08006#include <uapi/linux/btf.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -07007#include <linux/kernel.h>
8#include <linux/types.h>
9#include <linux/slab.h>
10#include <linux/bpf.h>
Yonghong Song838e9692018-11-19 15:29:11 -080011#include <linux/btf.h>
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012#include <linux/bpf_verifier.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013#include <linux/filter.h>
14#include <net/netlink.h>
15#include <linux/file.h>
16#include <linux/vmalloc.h>
Thomas Grafebb676d2016-10-27 11:23:51 +020017#include <linux/stringify.h>
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080018#include <linux/bsearch.h>
19#include <linux/sort.h>
Yonghong Songc195651e2018-04-28 22:28:08 -070020#include <linux/perf_event.h>
Martin KaFai Laud9762e82018-12-13 10:41:48 -080021#include <linux/ctype.h>
KP Singh6ba43b72020-03-04 20:18:50 +010022#include <linux/error-injection.h>
KP Singh9e4e01d2020-03-29 01:43:52 +010023#include <linux/bpf_lsm.h>
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070024#include <linux/btf_ids.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070025
Jakub Kicinskif4ac7e02017-10-09 10:30:12 -070026#include "disasm.h"
27
Jakub Kicinski00176a32017-10-16 16:40:54 -070028static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
Alexei Starovoitov91cc1a92019-11-14 10:57:15 -080029#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
Jakub Kicinski00176a32017-10-16 16:40:54 -070030 [_id] = & _name ## _verifier_ops,
31#define BPF_MAP_TYPE(_id, _ops)
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070032#define BPF_LINK_TYPE(_id, _name)
Jakub Kicinski00176a32017-10-16 16:40:54 -070033#include <linux/bpf_types.h>
34#undef BPF_PROG_TYPE
35#undef BPF_MAP_TYPE
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070036#undef BPF_LINK_TYPE
Jakub Kicinski00176a32017-10-16 16:40:54 -070037};
38
Alexei Starovoitov51580e72014-09-26 00:17:02 -070039/* bpf_check() is a static code analyzer that walks eBPF program
40 * instruction by instruction and updates register/stack state.
41 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
42 *
43 * The first pass is depth-first-search to check that the program is a DAG.
44 * It rejects the following programs:
45 * - larger than BPF_MAXINSNS insns
46 * - if loop is present (detected via back-edge)
47 * - unreachable insns exist (shouldn't be a forest. program = one function)
48 * - out of bounds or malformed jumps
49 * The second pass is all possible path descent from the 1st insn.
50 * Since it's analyzing all pathes through the program, the length of the
Gary Lineba38a92017-03-01 16:25:51 +080051 * analysis is limited to 64k insn, which may be hit even if total number of
Alexei Starovoitov51580e72014-09-26 00:17:02 -070052 * insn is less then 4K, but there are too many branches that change stack/regs.
53 * Number of 'branches to be analyzed' is limited to 1k
54 *
55 * On entry to each instruction, each register has a type, and the instruction
56 * changes the types of the registers depending on instruction semantics.
57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
58 * copied to R1.
59 *
60 * All registers are 64-bit.
61 * R0 - return register
62 * R1-R5 argument passing registers
63 * R6-R9 callee saved registers
64 * R10 - frame pointer read-only
65 *
66 * At the start of BPF program the register R1 contains a pointer to bpf_context
67 * and has type PTR_TO_CTX.
68 *
69 * Verifier tracks arithmetic operations on pointers in case:
70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
72 * 1st insn copies R10 (which has FRAME_PTR) type into R1
73 * and 2nd arithmetic instruction is pattern matched to recognize
74 * that it wants to construct a pointer to some element within stack.
75 * So after 2nd insn, the register R1 has type PTR_TO_STACK
76 * (and -20 constant is saved for further stack bounds checking).
77 * Meaning that this reg is a pointer to stack plus known immediate constant.
78 *
Edward Creef1174f72017-08-07 15:26:19 +010079 * Most of the time the registers have SCALAR_VALUE type, which
Alexei Starovoitov51580e72014-09-26 00:17:02 -070080 * means the register has some value, but it's not a valid pointer.
Edward Creef1174f72017-08-07 15:26:19 +010081 * (like pointer plus pointer becomes SCALAR_VALUE type)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070082 *
83 * When verifier sees load or store instructions the type of base register
Joe Stringerc64b7982018-10-02 13:35:33 -070084 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
85 * four pointer types recognized by check_mem_access() function.
Alexei Starovoitov51580e72014-09-26 00:17:02 -070086 *
87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
88 * and the range of [ptr, ptr + map's value_size) is accessible.
89 *
90 * registers used to pass values to function calls are checked against
91 * function argument constraints.
92 *
93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
94 * It means that the register type passed to this function must be
95 * PTR_TO_STACK and it will be used inside the function as
96 * 'pointer to map element key'
97 *
98 * For example the argument constraints for bpf_map_lookup_elem():
99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
100 * .arg1_type = ARG_CONST_MAP_PTR,
101 * .arg2_type = ARG_PTR_TO_MAP_KEY,
102 *
103 * ret_type says that this function returns 'pointer to map elem value or null'
104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
105 * 2nd argument should be a pointer to stack, which will be used inside
106 * the helper function as a pointer to map element key.
107 *
108 * On the kernel side the helper function looks like:
109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
110 * {
111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
112 * void *key = (void *) (unsigned long) r2;
113 * void *value;
114 *
115 * here kernel can access 'key' and 'map' pointers safely, knowing that
116 * [key, key + map->key_size) bytes are valid and were initialized on
117 * the stack of eBPF program.
118 * }
119 *
120 * Corresponding eBPF program may look like:
121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
125 * here verifier looks at prototype of map_lookup_elem() and sees:
126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
128 *
129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
131 * and were initialized prior to this call.
132 * If it's ok, then verifier allows this BPF_CALL insn and looks at
133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
135 * returns ether pointer to map value or NULL.
136 *
137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
138 * insn, the register holding that pointer in the true branch changes state to
139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
140 * branch. See check_cond_jmp_op().
141 *
142 * After the call R0 is set to return type of the function and registers R1-R5
143 * are set to NOT_INIT to indicate that they are no longer readable.
Joe Stringerfd978bf72018-10-02 13:35:35 -0700144 *
145 * The following reference types represent a potential reference to a kernel
146 * resource which, after first being allocated, must be checked and freed by
147 * the BPF program:
148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
149 *
150 * When the verifier sees a helper call return a reference type, it allocates a
151 * pointer id for the reference and stores it in the current function state.
152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
154 * passes through a NULL-check conditional. For the branch wherein the state is
155 * changed to CONST_IMM, the verifier releases the reference.
Joe Stringer6acc9b42018-10-02 13:35:36 -0700156 *
157 * For each helper function that allocates a reference, such as
158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
159 * bpf_sk_release(). When a reference type passes into the release function,
160 * the verifier also releases the reference. If any unchecked or unreleased
161 * reference remains at the end of the program, the verifier rejects it.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700162 */
163
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700164/* verifier_state + insn_idx are pushed to stack when branch is encountered */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100165struct bpf_verifier_stack_elem {
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700166 /* verifer state is 'st'
167 * before processing instruction 'insn_idx'
168 * and after processing instruction 'prev_insn_idx'
169 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100170 struct bpf_verifier_state st;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700171 int insn_idx;
172 int prev_insn_idx;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100173 struct bpf_verifier_stack_elem *next;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700174 /* length of verifier log at the time this state was pushed on stack */
175 u32 log_pos;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700176};
177
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700178#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
Alexei Starovoitovceefbc92018-12-03 22:46:06 -0800179#define BPF_COMPLEXITY_LIMIT_STATES 64
Daniel Borkmann07016152016-04-05 22:33:17 +0200180
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100181#define BPF_MAP_KEY_POISON (1ULL << 63)
182#define BPF_MAP_KEY_SEEN (1ULL << 62)
183
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200184#define BPF_MAP_PTR_UNPRIV 1UL
185#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
186 POISON_POINTER_DELTA))
187#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
188
189static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
190{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200192}
193
194static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
195{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200197}
198
199static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
200 const struct bpf_map *map, bool unpriv)
201{
202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
203 unpriv |= bpf_map_ptr_unpriv(aux);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100204 aux->map_ptr_state = (unsigned long)map |
205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
206}
207
208static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
209{
210 return aux->map_key_state & BPF_MAP_KEY_POISON;
211}
212
213static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
214{
215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
216}
217
218static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
219{
220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
221}
222
223static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
224{
225 bool poisoned = bpf_map_key_poisoned(aux);
226
227 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200229}
Martin KaFai Laufad73a12017-03-22 10:00:32 -0700230
Yonghong Song23a2d702021-02-04 15:48:27 -0800231static bool bpf_pseudo_call(const struct bpf_insn *insn)
232{
233 return insn->code == (BPF_JMP | BPF_CALL) &&
234 insn->src_reg == BPF_PSEUDO_CALL;
235}
236
Yonghong Song69c087b2021-02-26 12:49:25 -0800237static bool bpf_pseudo_func(const struct bpf_insn *insn)
238{
239 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
240 insn->src_reg == BPF_PSEUDO_FUNC;
241}
242
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200243struct bpf_call_arg_meta {
244 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200245 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200246 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200247 int regno;
248 int access_size;
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700249 int mem_size;
John Fastabend10060502020-03-30 14:36:19 -0700250 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700251 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800252 int func_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800253 struct btf *btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700254 u32 btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800255 struct btf *ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700256 u32 ret_btf_id;
Yonghong Song69c087b2021-02-26 12:49:25 -0800257 u32 subprogno;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200258};
259
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700260struct btf *btf_vmlinux;
261
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700262static DEFINE_MUTEX(bpf_verifier_lock);
263
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800264static const struct bpf_line_info *
265find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
266{
267 const struct bpf_line_info *linfo;
268 const struct bpf_prog *prog;
269 u32 i, nr_linfo;
270
271 prog = env->prog;
272 nr_linfo = prog->aux->nr_linfo;
273
274 if (!nr_linfo || insn_off >= prog->len)
275 return NULL;
276
277 linfo = prog->aux->linfo;
278 for (i = 1; i < nr_linfo; i++)
279 if (insn_off < linfo[i].insn_off)
280 break;
281
282 return &linfo[i - 1];
283}
284
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700285void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
286 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700287{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700288 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700289
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700290 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700291
292 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
293 "verifier log line truncated - local buffer too short\n");
294
295 n = min(log->len_total - log->len_used - 1, n);
296 log->kbuf[n] = '\0';
297
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700298 if (log->level == BPF_LOG_KERNEL) {
299 pr_err("BPF:%s\n", log->kbuf);
300 return;
301 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700302 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
303 log->len_used += n;
304 else
305 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700306}
Jiri Olsaabe08842018-03-23 11:41:28 +0100307
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700308static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
309{
310 char zero = 0;
311
312 if (!bpf_verifier_log_needed(log))
313 return;
314
315 log->len_used = new_pos;
316 if (put_user(zero, log->ubuf + new_pos))
317 log->ubuf = NULL;
318}
319
Jiri Olsaabe08842018-03-23 11:41:28 +0100320/* log_level controls verbosity level of eBPF verifier.
321 * bpf_verifier_log_write() is used to dump the verification trace to the log,
322 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000323 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100324__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
325 const char *fmt, ...)
326{
327 va_list args;
328
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700329 if (!bpf_verifier_log_needed(&env->log))
330 return;
331
Jiri Olsaabe08842018-03-23 11:41:28 +0100332 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700333 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100334 va_end(args);
335}
336EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
337
338__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
339{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700340 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100341 va_list args;
342
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700343 if (!bpf_verifier_log_needed(&env->log))
344 return;
345
Jiri Olsaabe08842018-03-23 11:41:28 +0100346 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700347 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100348 va_end(args);
349}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700350
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700351__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
352 const char *fmt, ...)
353{
354 va_list args;
355
356 if (!bpf_verifier_log_needed(log))
357 return;
358
359 va_start(args, fmt);
360 bpf_verifier_vlog(log, fmt, args);
361 va_end(args);
362}
363
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800364static const char *ltrim(const char *s)
365{
366 while (isspace(*s))
367 s++;
368
369 return s;
370}
371
372__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
373 u32 insn_off,
374 const char *prefix_fmt, ...)
375{
376 const struct bpf_line_info *linfo;
377
378 if (!bpf_verifier_log_needed(&env->log))
379 return;
380
381 linfo = find_linfo(env, insn_off);
382 if (!linfo || linfo == env->prev_linfo)
383 return;
384
385 if (prefix_fmt) {
386 va_list args;
387
388 va_start(args, prefix_fmt);
389 bpf_verifier_vlog(&env->log, prefix_fmt, args);
390 va_end(args);
391 }
392
393 verbose(env, "%s\n",
394 ltrim(btf_name_by_offset(env->prog->aux->btf,
395 linfo->line_off)));
396
397 env->prev_linfo = linfo;
398}
399
Yonghong Songbc2591d2021-02-26 12:49:22 -0800400static void verbose_invalid_scalar(struct bpf_verifier_env *env,
401 struct bpf_reg_state *reg,
402 struct tnum *range, const char *ctx,
403 const char *reg_name)
404{
405 char tn_buf[48];
406
407 verbose(env, "At %s the register %s ", ctx, reg_name);
408 if (!tnum_is_unknown(reg->var_off)) {
409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
410 verbose(env, "has value %s", tn_buf);
411 } else {
412 verbose(env, "has unknown scalar value");
413 }
414 tnum_strn(tn_buf, sizeof(tn_buf), *range);
415 verbose(env, " should have been in %s\n", tn_buf);
416}
417
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200418static bool type_is_pkt_pointer(enum bpf_reg_type type)
419{
420 return type == PTR_TO_PACKET ||
421 type == PTR_TO_PACKET_META;
422}
423
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800424static bool type_is_sk_pointer(enum bpf_reg_type type)
425{
426 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800427 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700428 type == PTR_TO_TCP_SOCK ||
429 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800430}
431
John Fastabendcac616d2020-05-21 13:07:26 -0700432static bool reg_type_not_null(enum bpf_reg_type type)
433{
434 return type == PTR_TO_SOCKET ||
435 type == PTR_TO_TCP_SOCK ||
436 type == PTR_TO_MAP_VALUE ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800437 type == PTR_TO_MAP_KEY ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700438 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700439}
440
Joe Stringer840b9612018-10-02 13:35:32 -0700441static bool reg_type_may_be_null(enum bpf_reg_type type)
442{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700443 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800444 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800445 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700446 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700447 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700448 type == PTR_TO_MEM_OR_NULL ||
449 type == PTR_TO_RDONLY_BUF_OR_NULL ||
450 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700451}
452
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800453static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
454{
455 return reg->type == PTR_TO_MAP_VALUE &&
456 map_value_has_spin_lock(reg->map_ptr);
457}
458
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700459static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
460{
461 return type == PTR_TO_SOCKET ||
462 type == PTR_TO_SOCKET_OR_NULL ||
463 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700464 type == PTR_TO_TCP_SOCK_OR_NULL ||
465 type == PTR_TO_MEM ||
466 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700467}
468
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700469static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700470{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700471 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700472}
473
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100474static bool arg_type_may_be_null(enum bpf_arg_type type)
475{
476 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
477 type == ARG_PTR_TO_MEM_OR_NULL ||
478 type == ARG_PTR_TO_CTX_OR_NULL ||
479 type == ARG_PTR_TO_SOCKET_OR_NULL ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800480 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
481 type == ARG_PTR_TO_STACK_OR_NULL;
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100482}
483
Joe Stringerfd978bf72018-10-02 13:35:35 -0700484/* Determine whether the function releases some resources allocated by another
485 * function call. The first reference type argument will be assumed to be
486 * released by release_reference().
487 */
488static bool is_release_function(enum bpf_func_id func_id)
489{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700490 return func_id == BPF_FUNC_sk_release ||
491 func_id == BPF_FUNC_ringbuf_submit ||
492 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700493}
494
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200495static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800496{
497 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800498 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200499 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700500 func_id == BPF_FUNC_map_lookup_elem ||
501 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200502}
503
504static bool is_acquire_function(enum bpf_func_id func_id,
505 const struct bpf_map *map)
506{
507 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
508
509 if (func_id == BPF_FUNC_sk_lookup_tcp ||
510 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700511 func_id == BPF_FUNC_skc_lookup_tcp ||
512 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200513 return true;
514
515 if (func_id == BPF_FUNC_map_lookup_elem &&
516 (map_type == BPF_MAP_TYPE_SOCKMAP ||
517 map_type == BPF_MAP_TYPE_SOCKHASH))
518 return true;
519
520 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800521}
522
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700523static bool is_ptr_cast_function(enum bpf_func_id func_id)
524{
525 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700526 func_id == BPF_FUNC_sk_fullsock ||
527 func_id == BPF_FUNC_skc_to_tcp_sock ||
528 func_id == BPF_FUNC_skc_to_tcp6_sock ||
529 func_id == BPF_FUNC_skc_to_udp6_sock ||
530 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
531 func_id == BPF_FUNC_skc_to_tcp_request_sock;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700532}
533
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700534/* string representation of 'enum bpf_reg_type' */
535static const char * const reg_type_str[] = {
536 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100537 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700538 [PTR_TO_CTX] = "ctx",
539 [CONST_PTR_TO_MAP] = "map_ptr",
540 [PTR_TO_MAP_VALUE] = "map_value",
541 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700542 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700543 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200544 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700545 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700546 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700547 [PTR_TO_SOCKET] = "sock",
548 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800549 [PTR_TO_SOCK_COMMON] = "sock_common",
550 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800551 [PTR_TO_TCP_SOCK] = "tcp_sock",
552 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700553 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700554 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700555 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700556 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700557 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700558 [PTR_TO_MEM] = "mem",
559 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700560 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
561 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
562 [PTR_TO_RDWR_BUF] = "rdwr_buf",
563 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Yonghong Song69c087b2021-02-26 12:49:25 -0800564 [PTR_TO_FUNC] = "func",
565 [PTR_TO_MAP_KEY] = "map_key",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700566};
567
Edward Cree8efea212018-08-22 20:02:44 +0100568static char slot_type_char[] = {
569 [STACK_INVALID] = '?',
570 [STACK_SPILL] = 'r',
571 [STACK_MISC] = 'm',
572 [STACK_ZERO] = '0',
573};
574
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800575static void print_liveness(struct bpf_verifier_env *env,
576 enum bpf_reg_liveness live)
577{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800578 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800579 verbose(env, "_");
580 if (live & REG_LIVE_READ)
581 verbose(env, "r");
582 if (live & REG_LIVE_WRITTEN)
583 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800584 if (live & REG_LIVE_DONE)
585 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800586}
587
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800588static struct bpf_func_state *func(struct bpf_verifier_env *env,
589 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700590{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800591 struct bpf_verifier_state *cur = env->cur_state;
592
593 return cur->frame[reg->frameno];
594}
595
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800596static const char *kernel_type_name(const struct btf* btf, u32 id)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700597{
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800598 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700599}
600
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800601static void print_verifier_state(struct bpf_verifier_env *env,
602 const struct bpf_func_state *state)
603{
604 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700605 enum bpf_reg_type t;
606 int i;
607
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800608 if (state->frameno)
609 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700610 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700611 reg = &state->regs[i];
612 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700613 if (t == NOT_INIT)
614 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800615 verbose(env, " R%d", i);
616 print_liveness(env, reg->live);
617 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700618 if (t == SCALAR_VALUE && reg->precise)
619 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100620 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
621 tnum_is_const(reg->var_off)) {
622 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700623 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100624 } else {
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700625 if (t == PTR_TO_BTF_ID ||
626 t == PTR_TO_BTF_ID_OR_NULL ||
627 t == PTR_TO_PERCPU_BTF_ID)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800628 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700629 verbose(env, "(id=%d", reg->id);
630 if (reg_type_may_be_refcounted_or_null(t))
631 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100632 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700633 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200634 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700635 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100636 else if (t == CONST_PTR_TO_MAP ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800637 t == PTR_TO_MAP_KEY ||
Edward Creef1174f72017-08-07 15:26:19 +0100638 t == PTR_TO_MAP_VALUE ||
639 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700640 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100641 reg->map_ptr->key_size,
642 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100643 if (tnum_is_const(reg->var_off)) {
644 /* Typically an immediate SCALAR_VALUE, but
645 * could be a pointer whose offset is too big
646 * for reg->off
647 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700648 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100649 } else {
650 if (reg->smin_value != reg->umin_value &&
651 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700652 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100653 (long long)reg->smin_value);
654 if (reg->smax_value != reg->umax_value &&
655 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700656 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100657 (long long)reg->smax_value);
658 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700659 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100660 (unsigned long long)reg->umin_value);
661 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700662 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100663 (unsigned long long)reg->umax_value);
664 if (!tnum_is_unknown(reg->var_off)) {
665 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100666
Edward Cree7d1238f2017-08-07 15:26:56 +0100667 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700668 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100669 }
John Fastabend3f50f132020-03-30 14:36:39 -0700670 if (reg->s32_min_value != reg->smin_value &&
671 reg->s32_min_value != S32_MIN)
672 verbose(env, ",s32_min_value=%d",
673 (int)(reg->s32_min_value));
674 if (reg->s32_max_value != reg->smax_value &&
675 reg->s32_max_value != S32_MAX)
676 verbose(env, ",s32_max_value=%d",
677 (int)(reg->s32_max_value));
678 if (reg->u32_min_value != reg->umin_value &&
679 reg->u32_min_value != U32_MIN)
680 verbose(env, ",u32_min_value=%d",
681 (int)(reg->u32_min_value));
682 if (reg->u32_max_value != reg->umax_value &&
683 reg->u32_max_value != U32_MAX)
684 verbose(env, ",u32_max_value=%d",
685 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100686 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700687 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100688 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700689 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700690 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100691 char types_buf[BPF_REG_SIZE + 1];
692 bool valid = false;
693 int j;
694
695 for (j = 0; j < BPF_REG_SIZE; j++) {
696 if (state->stack[i].slot_type[j] != STACK_INVALID)
697 valid = true;
698 types_buf[j] = slot_type_char[
699 state->stack[i].slot_type[j]];
700 }
701 types_buf[BPF_REG_SIZE] = 0;
702 if (!valid)
703 continue;
704 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
705 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700706 if (state->stack[i].slot_type[0] == STACK_SPILL) {
707 reg = &state->stack[i].spilled_ptr;
708 t = reg->type;
709 verbose(env, "=%s", reg_type_str[t]);
710 if (t == SCALAR_VALUE && reg->precise)
711 verbose(env, "P");
712 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
713 verbose(env, "%lld", reg->var_off.value + reg->off);
714 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100715 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700716 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700717 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700718 if (state->acquired_refs && state->refs[0].id) {
719 verbose(env, " refs=%d", state->refs[0].id);
720 for (i = 1; i < state->acquired_refs; i++)
721 if (state->refs[i].id)
722 verbose(env, ",%d", state->refs[i].id);
723 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700724 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700725}
726
Joe Stringer84dbf352018-10-02 13:35:34 -0700727#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
728static int copy_##NAME##_state(struct bpf_func_state *dst, \
729 const struct bpf_func_state *src) \
730{ \
731 if (!src->FIELD) \
732 return 0; \
733 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
734 /* internal bug, make state invalid to reject the program */ \
735 memset(dst, 0, sizeof(*dst)); \
736 return -EFAULT; \
737 } \
738 memcpy(dst->FIELD, src->FIELD, \
739 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
740 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700741}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700742/* copy_reference_state() */
743COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700744/* copy_stack_state() */
745COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
746#undef COPY_STATE_FN
747
748#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
749static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
750 bool copy_old) \
751{ \
752 u32 old_size = state->COUNT; \
753 struct bpf_##NAME##_state *new_##FIELD; \
754 int slot = size / SIZE; \
755 \
756 if (size <= old_size || !size) { \
757 if (copy_old) \
758 return 0; \
759 state->COUNT = slot * SIZE; \
760 if (!size && old_size) { \
761 kfree(state->FIELD); \
762 state->FIELD = NULL; \
763 } \
764 return 0; \
765 } \
766 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
767 GFP_KERNEL); \
768 if (!new_##FIELD) \
769 return -ENOMEM; \
770 if (copy_old) { \
771 if (state->FIELD) \
772 memcpy(new_##FIELD, state->FIELD, \
773 sizeof(*new_##FIELD) * (old_size / SIZE)); \
774 memset(new_##FIELD + old_size / SIZE, 0, \
775 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
776 } \
777 state->COUNT = slot * SIZE; \
778 kfree(state->FIELD); \
779 state->FIELD = new_##FIELD; \
780 return 0; \
781}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700782/* realloc_reference_state() */
783REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700784/* realloc_stack_state() */
785REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
786#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700787
788/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
789 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800790 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700791 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
792 * which realloc_stack_state() copies over. It points to previous
793 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700794 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700795static int realloc_func_state(struct bpf_func_state *state, int stack_size,
796 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700797{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700798 int err = realloc_reference_state(state, refs_size, copy_old);
799 if (err)
800 return err;
801 return realloc_stack_state(state, stack_size, copy_old);
802}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700803
Joe Stringerfd978bf72018-10-02 13:35:35 -0700804/* Acquire a pointer id from the env and update the state->refs to include
805 * this new pointer reference.
806 * On success, returns a valid pointer id to associate with the register
807 * On failure, returns a negative errno.
808 */
809static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
810{
811 struct bpf_func_state *state = cur_func(env);
812 int new_ofs = state->acquired_refs;
813 int id, err;
814
815 err = realloc_reference_state(state, state->acquired_refs + 1, true);
816 if (err)
817 return err;
818 id = ++env->id_gen;
819 state->refs[new_ofs].id = id;
820 state->refs[new_ofs].insn_idx = insn_idx;
821
822 return id;
823}
824
825/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800826static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700827{
828 int i, last_idx;
829
Joe Stringerfd978bf72018-10-02 13:35:35 -0700830 last_idx = state->acquired_refs - 1;
831 for (i = 0; i < state->acquired_refs; i++) {
832 if (state->refs[i].id == ptr_id) {
833 if (last_idx && i != last_idx)
834 memcpy(&state->refs[i], &state->refs[last_idx],
835 sizeof(*state->refs));
836 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
837 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700838 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700839 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700840 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800841 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700842}
843
844static int transfer_reference_state(struct bpf_func_state *dst,
845 struct bpf_func_state *src)
846{
847 int err = realloc_reference_state(dst, src->acquired_refs, false);
848 if (err)
849 return err;
850 err = copy_reference_state(dst, src);
851 if (err)
852 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700853 return 0;
854}
855
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800856static void free_func_state(struct bpf_func_state *state)
857{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800858 if (!state)
859 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700860 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800861 kfree(state->stack);
862 kfree(state);
863}
864
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700865static void clear_jmp_history(struct bpf_verifier_state *state)
866{
867 kfree(state->jmp_history);
868 state->jmp_history = NULL;
869 state->jmp_history_cnt = 0;
870}
871
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700872static void free_verifier_state(struct bpf_verifier_state *state,
873 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700874{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800875 int i;
876
877 for (i = 0; i <= state->curframe; i++) {
878 free_func_state(state->frame[i]);
879 state->frame[i] = NULL;
880 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700881 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700882 if (free_self)
883 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700884}
885
886/* copy verifier state from src to dst growing dst stack space
887 * when necessary to accommodate larger src stack
888 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800889static int copy_func_state(struct bpf_func_state *dst,
890 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700891{
892 int err;
893
Joe Stringerfd978bf72018-10-02 13:35:35 -0700894 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
895 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700896 if (err)
897 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700898 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
899 err = copy_reference_state(dst, src);
900 if (err)
901 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700902 return copy_stack_state(dst, src);
903}
904
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800905static int copy_verifier_state(struct bpf_verifier_state *dst_state,
906 const struct bpf_verifier_state *src)
907{
908 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700909 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800910 int i, err;
911
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700912 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
913 kfree(dst_state->jmp_history);
914 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
915 if (!dst_state->jmp_history)
916 return -ENOMEM;
917 }
918 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
919 dst_state->jmp_history_cnt = src->jmp_history_cnt;
920
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800921 /* if dst has more stack frames then src frame, free them */
922 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
923 free_func_state(dst_state->frame[i]);
924 dst_state->frame[i] = NULL;
925 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100926 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800927 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800928 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700929 dst_state->branches = src->branches;
930 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700931 dst_state->first_insn_idx = src->first_insn_idx;
932 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800933 for (i = 0; i <= src->curframe; i++) {
934 dst = dst_state->frame[i];
935 if (!dst) {
936 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
937 if (!dst)
938 return -ENOMEM;
939 dst_state->frame[i] = dst;
940 }
941 err = copy_func_state(dst, src->frame[i]);
942 if (err)
943 return err;
944 }
945 return 0;
946}
947
Alexei Starovoitov25897262019-06-15 12:12:20 -0700948static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
949{
950 while (st) {
951 u32 br = --st->branches;
952
953 /* WARN_ON(br > 1) technically makes sense here,
954 * but see comment in push_stack(), hence:
955 */
956 WARN_ONCE((int)br < 0,
957 "BUG update_branch_counts:branches_to_explore=%d\n",
958 br);
959 if (br)
960 break;
961 st = st->parent;
962 }
963}
964
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700965static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700966 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700967{
968 struct bpf_verifier_state *cur = env->cur_state;
969 struct bpf_verifier_stack_elem *elem, *head = env->head;
970 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700971
972 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700973 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700974
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700975 if (cur) {
976 err = copy_verifier_state(cur, &head->st);
977 if (err)
978 return err;
979 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700980 if (pop_log)
981 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700982 if (insn_idx)
983 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700984 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700985 *prev_insn_idx = head->prev_insn_idx;
986 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700987 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700988 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700989 env->head = elem;
990 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700991 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700992}
993
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100994static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100995 int insn_idx, int prev_insn_idx,
996 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700997{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700998 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100999 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001000 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001001
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001002 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001003 if (!elem)
1004 goto err;
1005
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001006 elem->insn_idx = insn_idx;
1007 elem->prev_insn_idx = prev_insn_idx;
1008 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001009 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001010 env->head = elem;
1011 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001012 err = copy_verifier_state(&elem->st, cur);
1013 if (err)
1014 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001015 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -07001016 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1017 verbose(env, "The sequence of %d jumps is too complex.\n",
1018 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001019 goto err;
1020 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07001021 if (elem->st.parent) {
1022 ++elem->st.parent->branches;
1023 /* WARN_ON(branches > 2) technically makes sense here,
1024 * but
1025 * 1. speculative states will bump 'branches' for non-branch
1026 * instructions
1027 * 2. is_state_visited() heuristics may decide not to create
1028 * a new state for a sequence of branches and all such current
1029 * and cloned states will be pointing to a single parent state
1030 * which might have large 'branches' count.
1031 */
1032 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001033 return &elem->st;
1034err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001035 free_verifier_state(env->cur_state, true);
1036 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001037 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001038 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001039 return NULL;
1040}
1041
1042#define CALLER_SAVED_REGS 6
1043static const int caller_saved[CALLER_SAVED_REGS] = {
1044 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1045};
1046
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001047static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1048 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001049
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001050/* This helper doesn't clear reg->id */
1051static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001052{
Edward Creeb03c9f92017-08-07 15:26:36 +01001053 reg->var_off = tnum_const(imm);
1054 reg->smin_value = (s64)imm;
1055 reg->smax_value = (s64)imm;
1056 reg->umin_value = imm;
1057 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001058
1059 reg->s32_min_value = (s32)imm;
1060 reg->s32_max_value = (s32)imm;
1061 reg->u32_min_value = (u32)imm;
1062 reg->u32_max_value = (u32)imm;
1063}
1064
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001065/* Mark the unknown part of a register (variable offset or scalar value) as
1066 * known to have the value @imm.
1067 */
1068static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1069{
1070 /* Clear id, off, and union(map_ptr, range) */
1071 memset(((u8 *)reg) + sizeof(reg->type), 0,
1072 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1073 ___mark_reg_known(reg, imm);
1074}
1075
John Fastabend3f50f132020-03-30 14:36:39 -07001076static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1077{
1078 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1079 reg->s32_min_value = (s32)imm;
1080 reg->s32_max_value = (s32)imm;
1081 reg->u32_min_value = (u32)imm;
1082 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001083}
1084
Edward Creef1174f72017-08-07 15:26:19 +01001085/* Mark the 'variable offset' part of a register as zero. This should be
1086 * used only on registers holding a pointer type.
1087 */
1088static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1089{
Edward Creeb03c9f92017-08-07 15:26:36 +01001090 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001091}
1092
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001093static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1094{
1095 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001096 reg->type = SCALAR_VALUE;
1097}
1098
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001099static void mark_reg_known_zero(struct bpf_verifier_env *env,
1100 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001101{
1102 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001103 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001104 /* Something bad happened, let's kill all regs */
1105 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001106 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001107 return;
1108 }
1109 __mark_reg_known_zero(regs + regno);
1110}
1111
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001112static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1113{
1114 switch (reg->type) {
1115 case PTR_TO_MAP_VALUE_OR_NULL: {
1116 const struct bpf_map *map = reg->map_ptr;
1117
1118 if (map->inner_map_meta) {
1119 reg->type = CONST_PTR_TO_MAP;
1120 reg->map_ptr = map->inner_map_meta;
1121 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1122 reg->type = PTR_TO_XDP_SOCK;
1123 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1124 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1125 reg->type = PTR_TO_SOCKET;
1126 } else {
1127 reg->type = PTR_TO_MAP_VALUE;
1128 }
1129 break;
1130 }
1131 case PTR_TO_SOCKET_OR_NULL:
1132 reg->type = PTR_TO_SOCKET;
1133 break;
1134 case PTR_TO_SOCK_COMMON_OR_NULL:
1135 reg->type = PTR_TO_SOCK_COMMON;
1136 break;
1137 case PTR_TO_TCP_SOCK_OR_NULL:
1138 reg->type = PTR_TO_TCP_SOCK;
1139 break;
1140 case PTR_TO_BTF_ID_OR_NULL:
1141 reg->type = PTR_TO_BTF_ID;
1142 break;
1143 case PTR_TO_MEM_OR_NULL:
1144 reg->type = PTR_TO_MEM;
1145 break;
1146 case PTR_TO_RDONLY_BUF_OR_NULL:
1147 reg->type = PTR_TO_RDONLY_BUF;
1148 break;
1149 case PTR_TO_RDWR_BUF_OR_NULL:
1150 reg->type = PTR_TO_RDWR_BUF;
1151 break;
1152 default:
1153 WARN_ON("unknown nullable register type");
1154 }
1155}
1156
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001157static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1158{
1159 return type_is_pkt_pointer(reg->type);
1160}
1161
1162static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1163{
1164 return reg_is_pkt_pointer(reg) ||
1165 reg->type == PTR_TO_PACKET_END;
1166}
1167
1168/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1169static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1170 enum bpf_reg_type which)
1171{
1172 /* The register can already have a range from prior markings.
1173 * This is fine as long as it hasn't been advanced from its
1174 * origin.
1175 */
1176 return reg->type == which &&
1177 reg->id == 0 &&
1178 reg->off == 0 &&
1179 tnum_equals_const(reg->var_off, 0);
1180}
1181
John Fastabend3f50f132020-03-30 14:36:39 -07001182/* Reset the min/max bounds of a register */
1183static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1184{
1185 reg->smin_value = S64_MIN;
1186 reg->smax_value = S64_MAX;
1187 reg->umin_value = 0;
1188 reg->umax_value = U64_MAX;
1189
1190 reg->s32_min_value = S32_MIN;
1191 reg->s32_max_value = S32_MAX;
1192 reg->u32_min_value = 0;
1193 reg->u32_max_value = U32_MAX;
1194}
1195
1196static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1197{
1198 reg->smin_value = S64_MIN;
1199 reg->smax_value = S64_MAX;
1200 reg->umin_value = 0;
1201 reg->umax_value = U64_MAX;
1202}
1203
1204static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1205{
1206 reg->s32_min_value = S32_MIN;
1207 reg->s32_max_value = S32_MAX;
1208 reg->u32_min_value = 0;
1209 reg->u32_max_value = U32_MAX;
1210}
1211
1212static void __update_reg32_bounds(struct bpf_reg_state *reg)
1213{
1214 struct tnum var32_off = tnum_subreg(reg->var_off);
1215
1216 /* min signed is max(sign bit) | min(other bits) */
1217 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1218 var32_off.value | (var32_off.mask & S32_MIN));
1219 /* max signed is min(sign bit) | max(other bits) */
1220 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1221 var32_off.value | (var32_off.mask & S32_MAX));
1222 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1223 reg->u32_max_value = min(reg->u32_max_value,
1224 (u32)(var32_off.value | var32_off.mask));
1225}
1226
1227static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001228{
1229 /* min signed is max(sign bit) | min(other bits) */
1230 reg->smin_value = max_t(s64, reg->smin_value,
1231 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1232 /* max signed is min(sign bit) | max(other bits) */
1233 reg->smax_value = min_t(s64, reg->smax_value,
1234 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1235 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1236 reg->umax_value = min(reg->umax_value,
1237 reg->var_off.value | reg->var_off.mask);
1238}
1239
John Fastabend3f50f132020-03-30 14:36:39 -07001240static void __update_reg_bounds(struct bpf_reg_state *reg)
1241{
1242 __update_reg32_bounds(reg);
1243 __update_reg64_bounds(reg);
1244}
1245
Edward Creeb03c9f92017-08-07 15:26:36 +01001246/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001247static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1248{
1249 /* Learn sign from signed bounds.
1250 * If we cannot cross the sign boundary, then signed and unsigned bounds
1251 * are the same, so combine. This works even in the negative case, e.g.
1252 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1253 */
1254 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1255 reg->s32_min_value = reg->u32_min_value =
1256 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1257 reg->s32_max_value = reg->u32_max_value =
1258 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1259 return;
1260 }
1261 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1262 * boundary, so we must be careful.
1263 */
1264 if ((s32)reg->u32_max_value >= 0) {
1265 /* Positive. We can't learn anything from the smin, but smax
1266 * is positive, hence safe.
1267 */
1268 reg->s32_min_value = reg->u32_min_value;
1269 reg->s32_max_value = reg->u32_max_value =
1270 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1271 } else if ((s32)reg->u32_min_value < 0) {
1272 /* Negative. We can't learn anything from the smax, but smin
1273 * is negative, hence safe.
1274 */
1275 reg->s32_min_value = reg->u32_min_value =
1276 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1277 reg->s32_max_value = reg->u32_max_value;
1278 }
1279}
1280
1281static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001282{
1283 /* Learn sign from signed bounds.
1284 * If we cannot cross the sign boundary, then signed and unsigned bounds
1285 * are the same, so combine. This works even in the negative case, e.g.
1286 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1287 */
1288 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1289 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1290 reg->umin_value);
1291 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1292 reg->umax_value);
1293 return;
1294 }
1295 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1296 * boundary, so we must be careful.
1297 */
1298 if ((s64)reg->umax_value >= 0) {
1299 /* Positive. We can't learn anything from the smin, but smax
1300 * is positive, hence safe.
1301 */
1302 reg->smin_value = reg->umin_value;
1303 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1304 reg->umax_value);
1305 } else if ((s64)reg->umin_value < 0) {
1306 /* Negative. We can't learn anything from the smax, but smin
1307 * is negative, hence safe.
1308 */
1309 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1310 reg->umin_value);
1311 reg->smax_value = reg->umax_value;
1312 }
1313}
1314
John Fastabend3f50f132020-03-30 14:36:39 -07001315static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1316{
1317 __reg32_deduce_bounds(reg);
1318 __reg64_deduce_bounds(reg);
1319}
1320
Edward Creeb03c9f92017-08-07 15:26:36 +01001321/* Attempts to improve var_off based on unsigned min/max information */
1322static void __reg_bound_offset(struct bpf_reg_state *reg)
1323{
John Fastabend3f50f132020-03-30 14:36:39 -07001324 struct tnum var64_off = tnum_intersect(reg->var_off,
1325 tnum_range(reg->umin_value,
1326 reg->umax_value));
1327 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1328 tnum_range(reg->u32_min_value,
1329 reg->u32_max_value));
1330
1331 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001332}
1333
John Fastabend3f50f132020-03-30 14:36:39 -07001334static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001335{
John Fastabend3f50f132020-03-30 14:36:39 -07001336 reg->umin_value = reg->u32_min_value;
1337 reg->umax_value = reg->u32_max_value;
1338 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1339 * but must be positive otherwise set to worse case bounds
1340 * and refine later from tnum.
1341 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001342 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001343 reg->smax_value = reg->s32_max_value;
1344 else
1345 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001346 if (reg->s32_min_value >= 0)
1347 reg->smin_value = reg->s32_min_value;
1348 else
1349 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001350}
1351
1352static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1353{
1354 /* special case when 64-bit register has upper 32-bit register
1355 * zeroed. Typically happens after zext or <<32, >>32 sequence
1356 * allowing us to use 32-bit bounds directly,
1357 */
1358 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1359 __reg_assign_32_into_64(reg);
1360 } else {
1361 /* Otherwise the best we can do is push lower 32bit known and
1362 * unknown bits into register (var_off set from jmp logic)
1363 * then learn as much as possible from the 64-bit tnum
1364 * known and unknown bits. The previous smin/smax bounds are
1365 * invalid here because of jmp32 compare so mark them unknown
1366 * so they do not impact tnum bounds calculation.
1367 */
1368 __mark_reg64_unbounded(reg);
1369 __update_reg_bounds(reg);
1370 }
1371
1372 /* Intersecting with the old var_off might have improved our bounds
1373 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1374 * then new var_off is (0; 0x7f...fc) which improves our umax.
1375 */
1376 __reg_deduce_bounds(reg);
1377 __reg_bound_offset(reg);
1378 __update_reg_bounds(reg);
1379}
1380
1381static bool __reg64_bound_s32(s64 a)
1382{
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001383 return a > S32_MIN && a < S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001384}
1385
1386static bool __reg64_bound_u32(u64 a)
1387{
1388 if (a > U32_MIN && a < U32_MAX)
1389 return true;
1390 return false;
1391}
1392
1393static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1394{
1395 __mark_reg32_unbounded(reg);
1396
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001397 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001398 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001399 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001400 }
John Fastabend3f50f132020-03-30 14:36:39 -07001401 if (__reg64_bound_u32(reg->umin_value))
1402 reg->u32_min_value = (u32)reg->umin_value;
1403 if (__reg64_bound_u32(reg->umax_value))
1404 reg->u32_max_value = (u32)reg->umax_value;
1405
1406 /* Intersecting with the old var_off might have improved our bounds
1407 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1408 * then new var_off is (0; 0x7f...fc) which improves our umax.
1409 */
1410 __reg_deduce_bounds(reg);
1411 __reg_bound_offset(reg);
1412 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001413}
1414
Edward Creef1174f72017-08-07 15:26:19 +01001415/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001416static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1417 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001418{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001419 /*
1420 * Clear type, id, off, and union(map_ptr, range) and
1421 * padding between 'type' and union
1422 */
1423 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001424 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001425 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001426 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001427 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001428 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001429}
1430
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001431static void mark_reg_unknown(struct bpf_verifier_env *env,
1432 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001433{
1434 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001435 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001436 /* Something bad happened, let's kill all regs except FP */
1437 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001438 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001439 return;
1440 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001441 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001442}
1443
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001444static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1445 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001446{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001447 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001448 reg->type = NOT_INIT;
1449}
1450
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001451static void mark_reg_not_init(struct bpf_verifier_env *env,
1452 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001453{
Edward Creef1174f72017-08-07 15:26:19 +01001454 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001455 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001456 /* Something bad happened, let's kill all regs except FP */
1457 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001458 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001459 return;
1460 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001461 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001462}
1463
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001464static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1465 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001466 enum bpf_reg_type reg_type,
1467 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001468{
1469 if (reg_type == SCALAR_VALUE) {
1470 mark_reg_unknown(env, regs, regno);
1471 return;
1472 }
1473 mark_reg_known_zero(env, regs, regno);
1474 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001475 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001476 regs[regno].btf_id = btf_id;
1477}
1478
Jiong Wang5327ed32019-05-24 23:25:12 +01001479#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001480static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001481 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001482{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001483 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001484 int i;
1485
Edward Creedc503a82017-08-15 20:34:35 +01001486 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001487 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001488 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001489 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001490 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001491 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001492
1493 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001494 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001495 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001496 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001497}
1498
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001499#define BPF_MAIN_FUNC (-1)
1500static void init_func_state(struct bpf_verifier_env *env,
1501 struct bpf_func_state *state,
1502 int callsite, int frameno, int subprogno)
1503{
1504 state->callsite = callsite;
1505 state->frameno = frameno;
1506 state->subprogno = subprogno;
1507 init_reg_state(env, state);
1508}
1509
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001510enum reg_arg_type {
1511 SRC_OP, /* register is used as source operand */
1512 DST_OP, /* register is used as destination operand */
1513 DST_OP_NO_MARK /* same as above, check only, don't mark */
1514};
1515
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001516static int cmp_subprogs(const void *a, const void *b)
1517{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001518 return ((struct bpf_subprog_info *)a)->start -
1519 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001520}
1521
1522static int find_subprog(struct bpf_verifier_env *env, int off)
1523{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001524 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001525
Jiong Wang9c8105b2018-05-02 16:17:18 -04001526 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1527 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001528 if (!p)
1529 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001530 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001531
1532}
1533
1534static int add_subprog(struct bpf_verifier_env *env, int off)
1535{
1536 int insn_cnt = env->prog->len;
1537 int ret;
1538
1539 if (off >= insn_cnt || off < 0) {
1540 verbose(env, "call to invalid destination\n");
1541 return -EINVAL;
1542 }
1543 ret = find_subprog(env, off);
1544 if (ret >= 0)
Yonghong Song282a0f42021-02-26 12:49:24 -08001545 return ret;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001546 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001547 verbose(env, "too many subprograms\n");
1548 return -E2BIG;
1549 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001550 env->subprog_info[env->subprog_cnt++].start = off;
1551 sort(env->subprog_info, env->subprog_cnt,
1552 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Yonghong Song282a0f42021-02-26 12:49:24 -08001553 return env->subprog_cnt - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001554}
1555
1556static int check_subprogs(struct bpf_verifier_env *env)
1557{
1558 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001559 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001560 struct bpf_insn *insn = env->prog->insnsi;
1561 int insn_cnt = env->prog->len;
1562
Jiong Wangf910cef2018-05-02 16:17:17 -04001563 /* Add entry function. */
1564 ret = add_subprog(env, 0);
1565 if (ret < 0)
1566 return ret;
1567
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001568 /* determine subprog starts. The end is one before the next starts */
1569 for (i = 0; i < insn_cnt; i++) {
Yonghong Song69c087b2021-02-26 12:49:25 -08001570 if (bpf_pseudo_func(insn + i)) {
1571 if (!env->bpf_capable) {
1572 verbose(env,
1573 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
1574 return -EPERM;
1575 }
1576 ret = add_subprog(env, i + insn[i].imm + 1);
1577 if (ret < 0)
1578 return ret;
1579 /* remember subprog */
1580 insn[i + 1].imm = ret;
1581 continue;
1582 }
Yonghong Song23a2d702021-02-04 15:48:27 -08001583 if (!bpf_pseudo_call(insn + i))
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001584 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001585 if (!env->bpf_capable) {
1586 verbose(env,
1587 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001588 return -EPERM;
1589 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001590 ret = add_subprog(env, i + insn[i].imm + 1);
1591 if (ret < 0)
1592 return ret;
1593 }
1594
Jiong Wang4cb3d992018-05-02 16:17:19 -04001595 /* Add a fake 'exit' subprog which could simplify subprog iteration
1596 * logic. 'subprog_cnt' should not be increased.
1597 */
1598 subprog[env->subprog_cnt].start = insn_cnt;
1599
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001600 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001601 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001602 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001603
1604 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001605 subprog_start = subprog[cur_subprog].start;
1606 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001607 for (i = 0; i < insn_cnt; i++) {
1608 u8 code = insn[i].code;
1609
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001610 if (code == (BPF_JMP | BPF_CALL) &&
1611 insn[i].imm == BPF_FUNC_tail_call &&
1612 insn[i].src_reg != BPF_PSEUDO_CALL)
1613 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001614 if (BPF_CLASS(code) == BPF_LD &&
1615 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1616 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001617 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001618 goto next;
1619 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1620 goto next;
1621 off = i + insn[i].off + 1;
1622 if (off < subprog_start || off >= subprog_end) {
1623 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1624 return -EINVAL;
1625 }
1626next:
1627 if (i == subprog_end - 1) {
1628 /* to avoid fall-through from one subprog into another
1629 * the last insn of the subprog should be either exit
1630 * or unconditional jump back
1631 */
1632 if (code != (BPF_JMP | BPF_EXIT) &&
1633 code != (BPF_JMP | BPF_JA)) {
1634 verbose(env, "last insn is not an exit or jmp\n");
1635 return -EINVAL;
1636 }
1637 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001638 cur_subprog++;
1639 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001640 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001641 }
1642 }
1643 return 0;
1644}
1645
Edward Cree679c7822018-08-22 20:02:19 +01001646/* Parentage chain of this register (or stack slot) should take care of all
1647 * issues like callee-saved registers, stack slot allocation time, etc.
1648 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001649static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001650 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001651 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001652{
1653 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001654 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001655
1656 while (parent) {
1657 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001658 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001659 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001660 if (parent->live & REG_LIVE_DONE) {
1661 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1662 reg_type_str[parent->type],
1663 parent->var_off.value, parent->off);
1664 return -EFAULT;
1665 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001666 /* The first condition is more likely to be true than the
1667 * second, checked it first.
1668 */
1669 if ((parent->live & REG_LIVE_READ) == flag ||
1670 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001671 /* The parentage chain never changes and
1672 * this parent was already marked as LIVE_READ.
1673 * There is no need to keep walking the chain again and
1674 * keep re-marking all parents as LIVE_READ.
1675 * This case happens when the same register is read
1676 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001677 * Also, if parent has the stronger REG_LIVE_READ64 set,
1678 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001679 */
1680 break;
Edward Creedc503a82017-08-15 20:34:35 +01001681 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001682 parent->live |= flag;
1683 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1684 if (flag == REG_LIVE_READ64)
1685 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001686 state = parent;
1687 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001688 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001689 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001690 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001691
1692 if (env->longest_mark_read_walk < cnt)
1693 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001694 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001695}
1696
Jiong Wang5327ed32019-05-24 23:25:12 +01001697/* This function is supposed to be used by the following 32-bit optimization
1698 * code only. It returns TRUE if the source or destination register operates
1699 * on 64-bit, otherwise return FALSE.
1700 */
1701static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1702 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1703{
1704 u8 code, class, op;
1705
1706 code = insn->code;
1707 class = BPF_CLASS(code);
1708 op = BPF_OP(code);
1709 if (class == BPF_JMP) {
1710 /* BPF_EXIT for "main" will reach here. Return TRUE
1711 * conservatively.
1712 */
1713 if (op == BPF_EXIT)
1714 return true;
1715 if (op == BPF_CALL) {
1716 /* BPF to BPF call will reach here because of marking
1717 * caller saved clobber with DST_OP_NO_MARK for which we
1718 * don't care the register def because they are anyway
1719 * marked as NOT_INIT already.
1720 */
1721 if (insn->src_reg == BPF_PSEUDO_CALL)
1722 return false;
1723 /* Helper call will reach here because of arg type
1724 * check, conservatively return TRUE.
1725 */
1726 if (t == SRC_OP)
1727 return true;
1728
1729 return false;
1730 }
1731 }
1732
1733 if (class == BPF_ALU64 || class == BPF_JMP ||
1734 /* BPF_END always use BPF_ALU class. */
1735 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1736 return true;
1737
1738 if (class == BPF_ALU || class == BPF_JMP32)
1739 return false;
1740
1741 if (class == BPF_LDX) {
1742 if (t != SRC_OP)
1743 return BPF_SIZE(code) == BPF_DW;
1744 /* LDX source must be ptr. */
1745 return true;
1746 }
1747
1748 if (class == BPF_STX) {
1749 if (reg->type != SCALAR_VALUE)
1750 return true;
1751 return BPF_SIZE(code) == BPF_DW;
1752 }
1753
1754 if (class == BPF_LD) {
1755 u8 mode = BPF_MODE(code);
1756
1757 /* LD_IMM64 */
1758 if (mode == BPF_IMM)
1759 return true;
1760
1761 /* Both LD_IND and LD_ABS return 32-bit data. */
1762 if (t != SRC_OP)
1763 return false;
1764
1765 /* Implicit ctx ptr. */
1766 if (regno == BPF_REG_6)
1767 return true;
1768
1769 /* Explicit source could be any width. */
1770 return true;
1771 }
1772
1773 if (class == BPF_ST)
1774 /* The only source register for BPF_ST is a ptr. */
1775 return true;
1776
1777 /* Conservatively return true at default. */
1778 return true;
1779}
1780
Jiong Wangb325fbc2019-05-24 23:25:13 +01001781/* Return TRUE if INSN doesn't have explicit value define. */
1782static bool insn_no_def(struct bpf_insn *insn)
1783{
1784 u8 class = BPF_CLASS(insn->code);
1785
1786 return (class == BPF_JMP || class == BPF_JMP32 ||
1787 class == BPF_STX || class == BPF_ST);
1788}
1789
1790/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1791static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1792{
1793 if (insn_no_def(insn))
1794 return false;
1795
1796 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1797}
1798
Jiong Wang5327ed32019-05-24 23:25:12 +01001799static void mark_insn_zext(struct bpf_verifier_env *env,
1800 struct bpf_reg_state *reg)
1801{
1802 s32 def_idx = reg->subreg_def;
1803
1804 if (def_idx == DEF_NOT_SUBREG)
1805 return;
1806
1807 env->insn_aux_data[def_idx - 1].zext_dst = true;
1808 /* The dst will be zero extended, so won't be sub-register anymore. */
1809 reg->subreg_def = DEF_NOT_SUBREG;
1810}
1811
Edward Creedc503a82017-08-15 20:34:35 +01001812static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001813 enum reg_arg_type t)
1814{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001815 struct bpf_verifier_state *vstate = env->cur_state;
1816 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001817 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001818 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001819 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001820
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001821 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001822 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001823 return -EINVAL;
1824 }
1825
Jiong Wangc342dc12019-04-12 22:59:37 +01001826 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001827 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001828 if (t == SRC_OP) {
1829 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001830 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001831 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001832 return -EACCES;
1833 }
Edward Cree679c7822018-08-22 20:02:19 +01001834 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001835 if (regno == BPF_REG_FP)
1836 return 0;
1837
Jiong Wang5327ed32019-05-24 23:25:12 +01001838 if (rw64)
1839 mark_insn_zext(env, reg);
1840
1841 return mark_reg_read(env, reg, reg->parent,
1842 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001843 } else {
1844 /* check whether register used as dest operand can be written to */
1845 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001846 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001847 return -EACCES;
1848 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001849 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001850 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001851 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001852 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001853 }
1854 return 0;
1855}
1856
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001857/* for any branch, call, exit record the history of jmps in the given state */
1858static int push_jmp_history(struct bpf_verifier_env *env,
1859 struct bpf_verifier_state *cur)
1860{
1861 u32 cnt = cur->jmp_history_cnt;
1862 struct bpf_idx_pair *p;
1863
1864 cnt++;
1865 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1866 if (!p)
1867 return -ENOMEM;
1868 p[cnt - 1].idx = env->insn_idx;
1869 p[cnt - 1].prev_idx = env->prev_insn_idx;
1870 cur->jmp_history = p;
1871 cur->jmp_history_cnt = cnt;
1872 return 0;
1873}
1874
1875/* Backtrack one insn at a time. If idx is not at the top of recorded
1876 * history then previous instruction came from straight line execution.
1877 */
1878static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1879 u32 *history)
1880{
1881 u32 cnt = *history;
1882
1883 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1884 i = st->jmp_history[cnt - 1].prev_idx;
1885 (*history)--;
1886 } else {
1887 i--;
1888 }
1889 return i;
1890}
1891
1892/* For given verifier state backtrack_insn() is called from the last insn to
1893 * the first insn. Its purpose is to compute a bitmask of registers and
1894 * stack slots that needs precision in the parent verifier state.
1895 */
1896static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1897 u32 *reg_mask, u64 *stack_mask)
1898{
1899 const struct bpf_insn_cbs cbs = {
1900 .cb_print = verbose,
1901 .private_data = env,
1902 };
1903 struct bpf_insn *insn = env->prog->insnsi + idx;
1904 u8 class = BPF_CLASS(insn->code);
1905 u8 opcode = BPF_OP(insn->code);
1906 u8 mode = BPF_MODE(insn->code);
1907 u32 dreg = 1u << insn->dst_reg;
1908 u32 sreg = 1u << insn->src_reg;
1909 u32 spi;
1910
1911 if (insn->code == 0)
1912 return 0;
1913 if (env->log.level & BPF_LOG_LEVEL) {
1914 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1915 verbose(env, "%d: ", idx);
1916 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1917 }
1918
1919 if (class == BPF_ALU || class == BPF_ALU64) {
1920 if (!(*reg_mask & dreg))
1921 return 0;
1922 if (opcode == BPF_MOV) {
1923 if (BPF_SRC(insn->code) == BPF_X) {
1924 /* dreg = sreg
1925 * dreg needs precision after this insn
1926 * sreg needs precision before this insn
1927 */
1928 *reg_mask &= ~dreg;
1929 *reg_mask |= sreg;
1930 } else {
1931 /* dreg = K
1932 * dreg needs precision after this insn.
1933 * Corresponding register is already marked
1934 * as precise=true in this verifier state.
1935 * No further markings in parent are necessary
1936 */
1937 *reg_mask &= ~dreg;
1938 }
1939 } else {
1940 if (BPF_SRC(insn->code) == BPF_X) {
1941 /* dreg += sreg
1942 * both dreg and sreg need precision
1943 * before this insn
1944 */
1945 *reg_mask |= sreg;
1946 } /* else dreg += K
1947 * dreg still needs precision before this insn
1948 */
1949 }
1950 } else if (class == BPF_LDX) {
1951 if (!(*reg_mask & dreg))
1952 return 0;
1953 *reg_mask &= ~dreg;
1954
1955 /* scalars can only be spilled into stack w/o losing precision.
1956 * Load from any other memory can be zero extended.
1957 * The desire to keep that precision is already indicated
1958 * by 'precise' mark in corresponding register of this state.
1959 * No further tracking necessary.
1960 */
1961 if (insn->src_reg != BPF_REG_FP)
1962 return 0;
1963 if (BPF_SIZE(insn->code) != BPF_DW)
1964 return 0;
1965
1966 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1967 * that [fp - off] slot contains scalar that needs to be
1968 * tracked with precision
1969 */
1970 spi = (-insn->off - 1) / BPF_REG_SIZE;
1971 if (spi >= 64) {
1972 verbose(env, "BUG spi %d\n", spi);
1973 WARN_ONCE(1, "verifier backtracking bug");
1974 return -EFAULT;
1975 }
1976 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001977 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001978 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001979 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001980 * to access memory. It means backtracking
1981 * encountered a case of pointer subtraction.
1982 */
1983 return -ENOTSUPP;
1984 /* scalars can only be spilled into stack */
1985 if (insn->dst_reg != BPF_REG_FP)
1986 return 0;
1987 if (BPF_SIZE(insn->code) != BPF_DW)
1988 return 0;
1989 spi = (-insn->off - 1) / BPF_REG_SIZE;
1990 if (spi >= 64) {
1991 verbose(env, "BUG spi %d\n", spi);
1992 WARN_ONCE(1, "verifier backtracking bug");
1993 return -EFAULT;
1994 }
1995 if (!(*stack_mask & (1ull << spi)))
1996 return 0;
1997 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001998 if (class == BPF_STX)
1999 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002000 } else if (class == BPF_JMP || class == BPF_JMP32) {
2001 if (opcode == BPF_CALL) {
2002 if (insn->src_reg == BPF_PSEUDO_CALL)
2003 return -ENOTSUPP;
2004 /* regular helper call sets R0 */
2005 *reg_mask &= ~1;
2006 if (*reg_mask & 0x3f) {
2007 /* if backtracing was looking for registers R1-R5
2008 * they should have been found already.
2009 */
2010 verbose(env, "BUG regs %x\n", *reg_mask);
2011 WARN_ONCE(1, "verifier backtracking bug");
2012 return -EFAULT;
2013 }
2014 } else if (opcode == BPF_EXIT) {
2015 return -ENOTSUPP;
2016 }
2017 } else if (class == BPF_LD) {
2018 if (!(*reg_mask & dreg))
2019 return 0;
2020 *reg_mask &= ~dreg;
2021 /* It's ld_imm64 or ld_abs or ld_ind.
2022 * For ld_imm64 no further tracking of precision
2023 * into parent is necessary
2024 */
2025 if (mode == BPF_IND || mode == BPF_ABS)
2026 /* to be analyzed */
2027 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002028 }
2029 return 0;
2030}
2031
2032/* the scalar precision tracking algorithm:
2033 * . at the start all registers have precise=false.
2034 * . scalar ranges are tracked as normal through alu and jmp insns.
2035 * . once precise value of the scalar register is used in:
2036 * . ptr + scalar alu
2037 * . if (scalar cond K|scalar)
2038 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2039 * backtrack through the verifier states and mark all registers and
2040 * stack slots with spilled constants that these scalar regisers
2041 * should be precise.
2042 * . during state pruning two registers (or spilled stack slots)
2043 * are equivalent if both are not precise.
2044 *
2045 * Note the verifier cannot simply walk register parentage chain,
2046 * since many different registers and stack slots could have been
2047 * used to compute single precise scalar.
2048 *
2049 * The approach of starting with precise=true for all registers and then
2050 * backtrack to mark a register as not precise when the verifier detects
2051 * that program doesn't care about specific value (e.g., when helper
2052 * takes register as ARG_ANYTHING parameter) is not safe.
2053 *
2054 * It's ok to walk single parentage chain of the verifier states.
2055 * It's possible that this backtracking will go all the way till 1st insn.
2056 * All other branches will be explored for needing precision later.
2057 *
2058 * The backtracking needs to deal with cases like:
2059 * 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)
2060 * r9 -= r8
2061 * r5 = r9
2062 * if r5 > 0x79f goto pc+7
2063 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2064 * r5 += 1
2065 * ...
2066 * call bpf_perf_event_output#25
2067 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2068 *
2069 * and this case:
2070 * r6 = 1
2071 * call foo // uses callee's r6 inside to compute r0
2072 * r0 += r6
2073 * if r0 == 0 goto
2074 *
2075 * to track above reg_mask/stack_mask needs to be independent for each frame.
2076 *
2077 * Also if parent's curframe > frame where backtracking started,
2078 * the verifier need to mark registers in both frames, otherwise callees
2079 * may incorrectly prune callers. This is similar to
2080 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2081 *
2082 * For now backtracking falls back into conservative marking.
2083 */
2084static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2085 struct bpf_verifier_state *st)
2086{
2087 struct bpf_func_state *func;
2088 struct bpf_reg_state *reg;
2089 int i, j;
2090
2091 /* big hammer: mark all scalars precise in this path.
2092 * pop_stack may still get !precise scalars.
2093 */
2094 for (; st; st = st->parent)
2095 for (i = 0; i <= st->curframe; i++) {
2096 func = st->frame[i];
2097 for (j = 0; j < BPF_REG_FP; j++) {
2098 reg = &func->regs[j];
2099 if (reg->type != SCALAR_VALUE)
2100 continue;
2101 reg->precise = true;
2102 }
2103 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2104 if (func->stack[j].slot_type[0] != STACK_SPILL)
2105 continue;
2106 reg = &func->stack[j].spilled_ptr;
2107 if (reg->type != SCALAR_VALUE)
2108 continue;
2109 reg->precise = true;
2110 }
2111 }
2112}
2113
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002114static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2115 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002116{
2117 struct bpf_verifier_state *st = env->cur_state;
2118 int first_idx = st->first_insn_idx;
2119 int last_idx = env->insn_idx;
2120 struct bpf_func_state *func;
2121 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002122 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2123 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002124 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002125 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002126 int i, err;
2127
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002128 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002129 return 0;
2130
2131 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002132 if (regno >= 0) {
2133 reg = &func->regs[regno];
2134 if (reg->type != SCALAR_VALUE) {
2135 WARN_ONCE(1, "backtracing misuse");
2136 return -EFAULT;
2137 }
2138 if (!reg->precise)
2139 new_marks = true;
2140 else
2141 reg_mask = 0;
2142 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002143 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002144
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002145 while (spi >= 0) {
2146 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2147 stack_mask = 0;
2148 break;
2149 }
2150 reg = &func->stack[spi].spilled_ptr;
2151 if (reg->type != SCALAR_VALUE) {
2152 stack_mask = 0;
2153 break;
2154 }
2155 if (!reg->precise)
2156 new_marks = true;
2157 else
2158 stack_mask = 0;
2159 reg->precise = true;
2160 break;
2161 }
2162
2163 if (!new_marks)
2164 return 0;
2165 if (!reg_mask && !stack_mask)
2166 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002167 for (;;) {
2168 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002169 u32 history = st->jmp_history_cnt;
2170
2171 if (env->log.level & BPF_LOG_LEVEL)
2172 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2173 for (i = last_idx;;) {
2174 if (skip_first) {
2175 err = 0;
2176 skip_first = false;
2177 } else {
2178 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2179 }
2180 if (err == -ENOTSUPP) {
2181 mark_all_scalars_precise(env, st);
2182 return 0;
2183 } else if (err) {
2184 return err;
2185 }
2186 if (!reg_mask && !stack_mask)
2187 /* Found assignment(s) into tracked register in this state.
2188 * Since this state is already marked, just return.
2189 * Nothing to be tracked further in the parent state.
2190 */
2191 return 0;
2192 if (i == first_idx)
2193 break;
2194 i = get_prev_insn_idx(st, i, &history);
2195 if (i >= env->prog->len) {
2196 /* This can happen if backtracking reached insn 0
2197 * and there are still reg_mask or stack_mask
2198 * to backtrack.
2199 * It means the backtracking missed the spot where
2200 * particular register was initialized with a constant.
2201 */
2202 verbose(env, "BUG backtracking idx %d\n", i);
2203 WARN_ONCE(1, "verifier backtracking bug");
2204 return -EFAULT;
2205 }
2206 }
2207 st = st->parent;
2208 if (!st)
2209 break;
2210
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002211 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002212 func = st->frame[st->curframe];
2213 bitmap_from_u64(mask, reg_mask);
2214 for_each_set_bit(i, mask, 32) {
2215 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002216 if (reg->type != SCALAR_VALUE) {
2217 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002218 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002219 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002220 if (!reg->precise)
2221 new_marks = true;
2222 reg->precise = true;
2223 }
2224
2225 bitmap_from_u64(mask, stack_mask);
2226 for_each_set_bit(i, mask, 64) {
2227 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002228 /* the sequence of instructions:
2229 * 2: (bf) r3 = r10
2230 * 3: (7b) *(u64 *)(r3 -8) = r0
2231 * 4: (79) r4 = *(u64 *)(r10 -8)
2232 * doesn't contain jmps. It's backtracked
2233 * as a single block.
2234 * During backtracking insn 3 is not recognized as
2235 * stack access, so at the end of backtracking
2236 * stack slot fp-8 is still marked in stack_mask.
2237 * However the parent state may not have accessed
2238 * fp-8 and it's "unallocated" stack space.
2239 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002240 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002241 mark_all_scalars_precise(env, st);
2242 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002243 }
2244
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002245 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2246 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002247 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002248 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002249 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002250 if (reg->type != SCALAR_VALUE) {
2251 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002252 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002253 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002254 if (!reg->precise)
2255 new_marks = true;
2256 reg->precise = true;
2257 }
2258 if (env->log.level & BPF_LOG_LEVEL) {
2259 print_verifier_state(env, func);
2260 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2261 new_marks ? "didn't have" : "already had",
2262 reg_mask, stack_mask);
2263 }
2264
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002265 if (!reg_mask && !stack_mask)
2266 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002267 if (!new_marks)
2268 break;
2269
2270 last_idx = st->last_insn_idx;
2271 first_idx = st->first_insn_idx;
2272 }
2273 return 0;
2274}
2275
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002276static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2277{
2278 return __mark_chain_precision(env, regno, -1);
2279}
2280
2281static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2282{
2283 return __mark_chain_precision(env, -1, spi);
2284}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002285
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002286static bool is_spillable_regtype(enum bpf_reg_type type)
2287{
2288 switch (type) {
2289 case PTR_TO_MAP_VALUE:
2290 case PTR_TO_MAP_VALUE_OR_NULL:
2291 case PTR_TO_STACK:
2292 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002293 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002294 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002295 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002296 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002297 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002298 case PTR_TO_SOCKET:
2299 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002300 case PTR_TO_SOCK_COMMON:
2301 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002302 case PTR_TO_TCP_SOCK:
2303 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002304 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002305 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002306 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002307 case PTR_TO_RDONLY_BUF:
2308 case PTR_TO_RDONLY_BUF_OR_NULL:
2309 case PTR_TO_RDWR_BUF:
2310 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002311 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002312 case PTR_TO_MEM:
2313 case PTR_TO_MEM_OR_NULL:
Yonghong Song69c087b2021-02-26 12:49:25 -08002314 case PTR_TO_FUNC:
2315 case PTR_TO_MAP_KEY:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002316 return true;
2317 default:
2318 return false;
2319 }
2320}
2321
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002322/* Does this register contain a constant zero? */
2323static bool register_is_null(struct bpf_reg_state *reg)
2324{
2325 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2326}
2327
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002328static bool register_is_const(struct bpf_reg_state *reg)
2329{
2330 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2331}
2332
Yonghong Song5689d492020-10-08 18:12:38 -07002333static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2334{
2335 return tnum_is_unknown(reg->var_off) &&
2336 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2337 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2338 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2339 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2340}
2341
2342static bool register_is_bounded(struct bpf_reg_state *reg)
2343{
2344 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2345}
2346
Jann Horn6e7e63c2020-04-17 02:00:06 +02002347static bool __is_pointer_value(bool allow_ptr_leaks,
2348 const struct bpf_reg_state *reg)
2349{
2350 if (allow_ptr_leaks)
2351 return false;
2352
2353 return reg->type != SCALAR_VALUE;
2354}
2355
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002356static void save_register_state(struct bpf_func_state *state,
2357 int spi, struct bpf_reg_state *reg)
2358{
2359 int i;
2360
2361 state->stack[spi].spilled_ptr = *reg;
2362 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2363
2364 for (i = 0; i < BPF_REG_SIZE; i++)
2365 state->stack[spi].slot_type[i] = STACK_SPILL;
2366}
2367
Andrei Matei01f810a2021-02-06 20:10:24 -05002368/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002369 * stack boundary and alignment are checked in check_mem_access()
2370 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002371static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2372 /* stack frame we're writing to */
2373 struct bpf_func_state *state,
2374 int off, int size, int value_regno,
2375 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002376{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002377 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002378 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002379 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002380 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002381
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002382 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002383 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002384 if (err)
2385 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002386 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2387 * so it's aligned access and [off, off + size) are within stack limits
2388 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002389 if (!env->allow_ptr_leaks &&
2390 state->stack[spi].slot_type[0] == STACK_SPILL &&
2391 size != BPF_REG_SIZE) {
2392 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2393 return -EACCES;
2394 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002395
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002396 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002397 if (value_regno >= 0)
2398 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002399
Yonghong Song5689d492020-10-08 18:12:38 -07002400 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002401 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002402 if (dst_reg != BPF_REG_FP) {
2403 /* The backtracking logic can only recognize explicit
2404 * stack slot address like [fp - 8]. Other spill of
2405 * scalar via different register has to be conervative.
2406 * Backtrack from here and mark all registers as precise
2407 * that contributed into 'reg' being a constant.
2408 */
2409 err = mark_chain_precision(env, value_regno);
2410 if (err)
2411 return err;
2412 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002413 save_register_state(state, spi, reg);
2414 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002415 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002416 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002417 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002418 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002419 return -EACCES;
2420 }
2421
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002422 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002423 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2424 return -EINVAL;
2425 }
2426
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002427 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002428 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002429
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002430 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2431 register_is_const(&state->stack[spi].spilled_ptr))
2432 sanitize = true;
2433 for (i = 0; i < BPF_REG_SIZE; i++)
2434 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2435 sanitize = true;
2436 break;
2437 }
2438 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002439 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2440 int soff = (-spi - 1) * BPF_REG_SIZE;
2441
2442 /* detected reuse of integer stack slot with a pointer
2443 * which means either llvm is reusing stack slot or
2444 * an attacker is trying to exploit CVE-2018-3639
2445 * (speculative store bypass)
2446 * Have to sanitize that slot with preemptive
2447 * store of zero.
2448 */
2449 if (*poff && *poff != soff) {
2450 /* disallow programs where single insn stores
2451 * into two different stack slots, since verifier
2452 * cannot sanitize them
2453 */
2454 verbose(env,
2455 "insn %d cannot access two stack slots fp%d and fp%d",
2456 insn_idx, *poff, soff);
2457 return -EINVAL;
2458 }
2459 *poff = soff;
2460 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002461 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002462 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002463 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002464 u8 type = STACK_MISC;
2465
Edward Cree679c7822018-08-22 20:02:19 +01002466 /* regular write of data into stack destroys any spilled ptr */
2467 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002468 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2469 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2470 for (i = 0; i < BPF_REG_SIZE; i++)
2471 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002472
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002473 /* only mark the slot as written if all 8 bytes were written
2474 * otherwise read propagation may incorrectly stop too soon
2475 * when stack slots are partially written.
2476 * This heuristic means that read propagation will be
2477 * conservative, since it will add reg_live_read marks
2478 * to stack slots all the way to first state when programs
2479 * writes+reads less than 8 bytes
2480 */
2481 if (size == BPF_REG_SIZE)
2482 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2483
2484 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002485 if (reg && register_is_null(reg)) {
2486 /* backtracking doesn't work for STACK_ZERO yet. */
2487 err = mark_chain_precision(env, value_regno);
2488 if (err)
2489 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002490 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002491 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002492
Jiong Wang0bae2d42018-12-15 03:34:40 -05002493 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002494 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002495 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002496 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002497 }
2498 return 0;
2499}
2500
Andrei Matei01f810a2021-02-06 20:10:24 -05002501/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2502 * known to contain a variable offset.
2503 * This function checks whether the write is permitted and conservatively
2504 * tracks the effects of the write, considering that each stack slot in the
2505 * dynamic range is potentially written to.
2506 *
2507 * 'off' includes 'regno->off'.
2508 * 'value_regno' can be -1, meaning that an unknown value is being written to
2509 * the stack.
2510 *
2511 * Spilled pointers in range are not marked as written because we don't know
2512 * what's going to be actually written. This means that read propagation for
2513 * future reads cannot be terminated by this write.
2514 *
2515 * For privileged programs, uninitialized stack slots are considered
2516 * initialized by this write (even though we don't know exactly what offsets
2517 * are going to be written to). The idea is that we don't want the verifier to
2518 * reject future reads that access slots written to through variable offsets.
2519 */
2520static int check_stack_write_var_off(struct bpf_verifier_env *env,
2521 /* func where register points to */
2522 struct bpf_func_state *state,
2523 int ptr_regno, int off, int size,
2524 int value_regno, int insn_idx)
2525{
2526 struct bpf_func_state *cur; /* state of the current function */
2527 int min_off, max_off;
2528 int i, err;
2529 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2530 bool writing_zero = false;
2531 /* set if the fact that we're writing a zero is used to let any
2532 * stack slots remain STACK_ZERO
2533 */
2534 bool zero_used = false;
2535
2536 cur = env->cur_state->frame[env->cur_state->curframe];
2537 ptr_reg = &cur->regs[ptr_regno];
2538 min_off = ptr_reg->smin_value + off;
2539 max_off = ptr_reg->smax_value + off + size;
2540 if (value_regno >= 0)
2541 value_reg = &cur->regs[value_regno];
2542 if (value_reg && register_is_null(value_reg))
2543 writing_zero = true;
2544
2545 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2546 state->acquired_refs, true);
2547 if (err)
2548 return err;
2549
2550
2551 /* Variable offset writes destroy any spilled pointers in range. */
2552 for (i = min_off; i < max_off; i++) {
2553 u8 new_type, *stype;
2554 int slot, spi;
2555
2556 slot = -i - 1;
2557 spi = slot / BPF_REG_SIZE;
2558 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2559
2560 if (!env->allow_ptr_leaks
2561 && *stype != NOT_INIT
2562 && *stype != SCALAR_VALUE) {
2563 /* Reject the write if there's are spilled pointers in
2564 * range. If we didn't reject here, the ptr status
2565 * would be erased below (even though not all slots are
2566 * actually overwritten), possibly opening the door to
2567 * leaks.
2568 */
2569 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2570 insn_idx, i);
2571 return -EINVAL;
2572 }
2573
2574 /* Erase all spilled pointers. */
2575 state->stack[spi].spilled_ptr.type = NOT_INIT;
2576
2577 /* Update the slot type. */
2578 new_type = STACK_MISC;
2579 if (writing_zero && *stype == STACK_ZERO) {
2580 new_type = STACK_ZERO;
2581 zero_used = true;
2582 }
2583 /* If the slot is STACK_INVALID, we check whether it's OK to
2584 * pretend that it will be initialized by this write. The slot
2585 * might not actually be written to, and so if we mark it as
2586 * initialized future reads might leak uninitialized memory.
2587 * For privileged programs, we will accept such reads to slots
2588 * that may or may not be written because, if we're reject
2589 * them, the error would be too confusing.
2590 */
2591 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2592 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2593 insn_idx, i);
2594 return -EINVAL;
2595 }
2596 *stype = new_type;
2597 }
2598 if (zero_used) {
2599 /* backtracking doesn't work for STACK_ZERO yet. */
2600 err = mark_chain_precision(env, value_regno);
2601 if (err)
2602 return err;
2603 }
2604 return 0;
2605}
2606
2607/* When register 'dst_regno' is assigned some values from stack[min_off,
2608 * max_off), we set the register's type according to the types of the
2609 * respective stack slots. If all the stack values are known to be zeros, then
2610 * so is the destination reg. Otherwise, the register is considered to be
2611 * SCALAR. This function does not deal with register filling; the caller must
2612 * ensure that all spilled registers in the stack range have been marked as
2613 * read.
2614 */
2615static void mark_reg_stack_read(struct bpf_verifier_env *env,
2616 /* func where src register points to */
2617 struct bpf_func_state *ptr_state,
2618 int min_off, int max_off, int dst_regno)
2619{
2620 struct bpf_verifier_state *vstate = env->cur_state;
2621 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2622 int i, slot, spi;
2623 u8 *stype;
2624 int zeros = 0;
2625
2626 for (i = min_off; i < max_off; i++) {
2627 slot = -i - 1;
2628 spi = slot / BPF_REG_SIZE;
2629 stype = ptr_state->stack[spi].slot_type;
2630 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2631 break;
2632 zeros++;
2633 }
2634 if (zeros == max_off - min_off) {
2635 /* any access_size read into register is zero extended,
2636 * so the whole register == const_zero
2637 */
2638 __mark_reg_const_zero(&state->regs[dst_regno]);
2639 /* backtracking doesn't support STACK_ZERO yet,
2640 * so mark it precise here, so that later
2641 * backtracking can stop here.
2642 * Backtracking may not need this if this register
2643 * doesn't participate in pointer adjustment.
2644 * Forward propagation of precise flag is not
2645 * necessary either. This mark is only to stop
2646 * backtracking. Any register that contributed
2647 * to const 0 was marked precise before spill.
2648 */
2649 state->regs[dst_regno].precise = true;
2650 } else {
2651 /* have read misc data from the stack */
2652 mark_reg_unknown(env, state->regs, dst_regno);
2653 }
2654 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2655}
2656
2657/* Read the stack at 'off' and put the results into the register indicated by
2658 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2659 * spilled reg.
2660 *
2661 * 'dst_regno' can be -1, meaning that the read value is not going to a
2662 * register.
2663 *
2664 * The access is assumed to be within the current stack bounds.
2665 */
2666static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2667 /* func where src register points to */
2668 struct bpf_func_state *reg_state,
2669 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002670{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002671 struct bpf_verifier_state *vstate = env->cur_state;
2672 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002673 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002674 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002675 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002676
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002677 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002678 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002679
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002680 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002681 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002682 if (reg->type != SCALAR_VALUE) {
2683 verbose_linfo(env, env->insn_idx, "; ");
2684 verbose(env, "invalid size of register fill\n");
2685 return -EACCES;
2686 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002687 if (dst_regno >= 0) {
2688 mark_reg_unknown(env, state->regs, dst_regno);
2689 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002690 }
2691 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2692 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002693 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002694 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002695 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002696 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002697 return -EACCES;
2698 }
2699 }
2700
Andrei Matei01f810a2021-02-06 20:10:24 -05002701 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002702 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05002703 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002704 /* mark reg as written since spilled pointer state likely
2705 * has its liveness marks cleared by is_state_visited()
2706 * which resets stack/reg liveness for state transitions
2707 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002708 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002709 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002710 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02002711 * it is acceptable to use this value as a SCALAR_VALUE
2712 * (e.g. for XADD).
2713 * We must not allow unprivileged callers to do that
2714 * with spilled pointers.
2715 */
2716 verbose(env, "leaking pointer from stack off %d\n",
2717 off);
2718 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002719 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002720 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002721 } else {
Andrei Matei01f810a2021-02-06 20:10:24 -05002722 u8 type;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002723
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002724 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002725 type = stype[(slot - i) % BPF_REG_SIZE];
2726 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002727 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05002728 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002729 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002730 verbose(env, "invalid read from stack off %d+%d size %d\n",
2731 off, i, size);
2732 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002733 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002734 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05002735 if (dst_regno >= 0)
2736 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002737 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002738 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002739}
2740
Andrei Matei01f810a2021-02-06 20:10:24 -05002741enum stack_access_src {
2742 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2743 ACCESS_HELPER = 2, /* the access is performed by a helper */
2744};
2745
2746static int check_stack_range_initialized(struct bpf_verifier_env *env,
2747 int regno, int off, int access_size,
2748 bool zero_size_allowed,
2749 enum stack_access_src type,
2750 struct bpf_call_arg_meta *meta);
2751
2752static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002753{
Andrei Matei01f810a2021-02-06 20:10:24 -05002754 return cur_regs(env) + regno;
2755}
2756
2757/* Read the stack at 'ptr_regno + off' and put the result into the register
2758 * 'dst_regno'.
2759 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2760 * but not its variable offset.
2761 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2762 *
2763 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2764 * filling registers (i.e. reads of spilled register cannot be detected when
2765 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2766 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2767 * offset; for a fixed offset check_stack_read_fixed_off should be used
2768 * instead.
2769 */
2770static int check_stack_read_var_off(struct bpf_verifier_env *env,
2771 int ptr_regno, int off, int size, int dst_regno)
2772{
2773 /* The state of the source register. */
2774 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2775 struct bpf_func_state *ptr_state = func(env, reg);
2776 int err;
2777 int min_off, max_off;
2778
2779 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002780 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002781 err = check_stack_range_initialized(env, ptr_regno, off, size,
2782 false, ACCESS_DIRECT, NULL);
2783 if (err)
2784 return err;
2785
2786 min_off = reg->smin_value + off;
2787 max_off = reg->smax_value + off;
2788 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2789 return 0;
2790}
2791
2792/* check_stack_read dispatches to check_stack_read_fixed_off or
2793 * check_stack_read_var_off.
2794 *
2795 * The caller must ensure that the offset falls within the allocated stack
2796 * bounds.
2797 *
2798 * 'dst_regno' is a register which will receive the value from the stack. It
2799 * can be -1, meaning that the read value is not going to a register.
2800 */
2801static int check_stack_read(struct bpf_verifier_env *env,
2802 int ptr_regno, int off, int size,
2803 int dst_regno)
2804{
2805 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2806 struct bpf_func_state *state = func(env, reg);
2807 int err;
2808 /* Some accesses are only permitted with a static offset. */
2809 bool var_off = !tnum_is_const(reg->var_off);
2810
2811 /* The offset is required to be static when reads don't go to a
2812 * register, in order to not leak pointers (see
2813 * check_stack_read_fixed_off).
2814 */
2815 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002816 char tn_buf[48];
2817
2818 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05002819 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 +01002820 tn_buf, off, size);
2821 return -EACCES;
2822 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002823 /* Variable offset is prohibited for unprivileged mode for simplicity
2824 * since it requires corresponding support in Spectre masking for stack
2825 * ALU. See also retrieve_ptr_limit().
2826 */
2827 if (!env->bypass_spec_v1 && var_off) {
2828 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002829
Andrei Matei01f810a2021-02-06 20:10:24 -05002830 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2831 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2832 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002833 return -EACCES;
2834 }
2835
Andrei Matei01f810a2021-02-06 20:10:24 -05002836 if (!var_off) {
2837 off += reg->var_off.value;
2838 err = check_stack_read_fixed_off(env, state, off, size,
2839 dst_regno);
2840 } else {
2841 /* Variable offset stack reads need more conservative handling
2842 * than fixed offset ones. Note that dst_regno >= 0 on this
2843 * branch.
2844 */
2845 err = check_stack_read_var_off(env, ptr_regno, off, size,
2846 dst_regno);
2847 }
2848 return err;
2849}
2850
2851
2852/* check_stack_write dispatches to check_stack_write_fixed_off or
2853 * check_stack_write_var_off.
2854 *
2855 * 'ptr_regno' is the register used as a pointer into the stack.
2856 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2857 * 'value_regno' is the register whose value we're writing to the stack. It can
2858 * be -1, meaning that we're not writing from a register.
2859 *
2860 * The caller must ensure that the offset falls within the maximum stack size.
2861 */
2862static int check_stack_write(struct bpf_verifier_env *env,
2863 int ptr_regno, int off, int size,
2864 int value_regno, int insn_idx)
2865{
2866 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2867 struct bpf_func_state *state = func(env, reg);
2868 int err;
2869
2870 if (tnum_is_const(reg->var_off)) {
2871 off += reg->var_off.value;
2872 err = check_stack_write_fixed_off(env, state, off, size,
2873 value_regno, insn_idx);
2874 } else {
2875 /* Variable offset stack reads need more conservative handling
2876 * than fixed offset ones.
2877 */
2878 err = check_stack_write_var_off(env, state,
2879 ptr_regno, off, size,
2880 value_regno, insn_idx);
2881 }
2882 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002883}
2884
Daniel Borkmann591fe982019-04-09 23:20:05 +02002885static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2886 int off, int size, enum bpf_access_type type)
2887{
2888 struct bpf_reg_state *regs = cur_regs(env);
2889 struct bpf_map *map = regs[regno].map_ptr;
2890 u32 cap = bpf_map_flags_to_cap(map);
2891
2892 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2893 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2894 map->value_size, off, size);
2895 return -EACCES;
2896 }
2897
2898 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2899 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2900 map->value_size, off, size);
2901 return -EACCES;
2902 }
2903
2904 return 0;
2905}
2906
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002907/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2908static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2909 int off, int size, u32 mem_size,
2910 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002911{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002912 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2913 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002914
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002915 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2916 return 0;
2917
2918 reg = &cur_regs(env)[regno];
2919 switch (reg->type) {
Yonghong Song69c087b2021-02-26 12:49:25 -08002920 case PTR_TO_MAP_KEY:
2921 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
2922 mem_size, off, size);
2923 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002924 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002925 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002926 mem_size, off, size);
2927 break;
2928 case PTR_TO_PACKET:
2929 case PTR_TO_PACKET_META:
2930 case PTR_TO_PACKET_END:
2931 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2932 off, size, regno, reg->id, off, mem_size);
2933 break;
2934 case PTR_TO_MEM:
2935 default:
2936 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2937 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002938 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002939
2940 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002941}
2942
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002943/* check read/write into a memory region with possible variable offset */
2944static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2945 int off, int size, u32 mem_size,
2946 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002947{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002948 struct bpf_verifier_state *vstate = env->cur_state;
2949 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002950 struct bpf_reg_state *reg = &state->regs[regno];
2951 int err;
2952
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002953 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002954 * need to try adding each of min_value and max_value to off
2955 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002956 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002957 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002958 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002959
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002960 /* The minimum value is only important with signed
2961 * comparisons where we can't assume the floor of a
2962 * value is 0. If we are using signed variables for our
2963 * index'es we need to make sure that whatever we use
2964 * will have a set floor within our range.
2965 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002966 if (reg->smin_value < 0 &&
2967 (reg->smin_value == S64_MIN ||
2968 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2969 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002970 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 -08002971 regno);
2972 return -EACCES;
2973 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002974 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2975 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002976 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002977 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002978 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002979 return err;
2980 }
2981
Edward Creeb03c9f92017-08-07 15:26:36 +01002982 /* If we haven't set a max value then we need to bail since we can't be
2983 * sure we won't do bad things.
2984 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002985 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002986 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002987 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002988 regno);
2989 return -EACCES;
2990 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002991 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2992 mem_size, zero_size_allowed);
2993 if (err) {
2994 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002995 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002996 return err;
2997 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002998
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002999 return 0;
3000}
3001
3002/* check read/write into a map element with possible variable offset */
3003static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3004 int off, int size, bool zero_size_allowed)
3005{
3006 struct bpf_verifier_state *vstate = env->cur_state;
3007 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3008 struct bpf_reg_state *reg = &state->regs[regno];
3009 struct bpf_map *map = reg->map_ptr;
3010 int err;
3011
3012 err = check_mem_region_access(env, regno, off, size, map->value_size,
3013 zero_size_allowed);
3014 if (err)
3015 return err;
3016
3017 if (map_value_has_spin_lock(map)) {
3018 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003019
3020 /* if any part of struct bpf_spin_lock can be touched by
3021 * load/store reject this program.
3022 * To check that [x1, x2) overlaps with [y1, y2)
3023 * it is sufficient to check x1 < y2 && y1 < x2.
3024 */
3025 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3026 lock < reg->umax_value + off + size) {
3027 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3028 return -EACCES;
3029 }
3030 }
Edward Creef1174f72017-08-07 15:26:19 +01003031 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003032}
3033
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003034#define MAX_PACKET_OFF 0xffff
3035
Udip Pant7e407812020-08-25 16:20:00 -07003036static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3037{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02003038 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07003039}
3040
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003041static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003042 const struct bpf_call_arg_meta *meta,
3043 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003044{
Udip Pant7e407812020-08-25 16:20:00 -07003045 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3046
3047 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003048 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003049 case BPF_PROG_TYPE_LWT_IN:
3050 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003051 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003052 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003053 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003054 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003055 if (t == BPF_WRITE)
3056 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003057 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003058
3059 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003060 case BPF_PROG_TYPE_SCHED_CLS:
3061 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003062 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003063 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003064 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003065 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003066 if (meta)
3067 return meta->pkt_access;
3068
3069 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003070 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003071
3072 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3073 if (t == BPF_WRITE)
3074 env->seen_direct_write = true;
3075
3076 return true;
3077
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003078 default:
3079 return false;
3080 }
3081}
3082
Edward Creef1174f72017-08-07 15:26:19 +01003083static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003084 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003085{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003086 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003087 struct bpf_reg_state *reg = &regs[regno];
3088 int err;
3089
3090 /* We may have added a variable offset to the packet pointer; but any
3091 * reg->range we have comes after that. We are only checking the fixed
3092 * offset.
3093 */
3094
3095 /* We don't allow negative numbers, because we aren't tracking enough
3096 * detail to prove they're safe.
3097 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003098 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003099 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 +01003100 regno);
3101 return -EACCES;
3102 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003103
3104 err = reg->range < 0 ? -EINVAL :
3105 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003106 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003107 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003108 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003109 return err;
3110 }
Jiong Wange6478152018-11-08 04:08:42 -05003111
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003112 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003113 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3114 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003115 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003116 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3117 */
3118 env->prog->aux->max_pkt_offset =
3119 max_t(u32, env->prog->aux->max_pkt_offset,
3120 off + reg->umax_value + size - 1);
3121
Edward Creef1174f72017-08-07 15:26:19 +01003122 return err;
3123}
3124
3125/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003126static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003127 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003128 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003129{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003130 struct bpf_insn_access_aux info = {
3131 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003132 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003133 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003134
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003135 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003136 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003137 /* A non zero info.ctx_field_size indicates that this field is a
3138 * candidate for later verifier transformation to load the whole
3139 * field and then apply a mask when accessed with a narrower
3140 * access than actual ctx access size. A zero info.ctx_field_size
3141 * will only allow for whole field access and rejects any other
3142 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003143 */
Yonghong Song23994632017-06-22 15:07:39 -07003144 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003145
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003146 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3147 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003148 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003149 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003150 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003151 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003152 /* remember the offset of last byte accessed in ctx */
3153 if (env->prog->aux->max_ctx_offset < off + size)
3154 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003155 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003156 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003157
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003158 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003159 return -EACCES;
3160}
3161
Petar Penkovd58e4682018-09-14 07:46:18 -07003162static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3163 int size)
3164{
3165 if (size < 0 || off < 0 ||
3166 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3167 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3168 off, size);
3169 return -EACCES;
3170 }
3171 return 0;
3172}
3173
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003174static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3175 u32 regno, int off, int size,
3176 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003177{
3178 struct bpf_reg_state *regs = cur_regs(env);
3179 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003180 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003181 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003182
3183 if (reg->smin_value < 0) {
3184 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3185 regno);
3186 return -EACCES;
3187 }
3188
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003189 switch (reg->type) {
3190 case PTR_TO_SOCK_COMMON:
3191 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3192 break;
3193 case PTR_TO_SOCKET:
3194 valid = bpf_sock_is_valid_access(off, size, t, &info);
3195 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003196 case PTR_TO_TCP_SOCK:
3197 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3198 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003199 case PTR_TO_XDP_SOCK:
3200 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3201 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003202 default:
3203 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003204 }
3205
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003206
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003207 if (valid) {
3208 env->insn_aux_data[insn_idx].ctx_field_size =
3209 info.ctx_field_size;
3210 return 0;
3211 }
3212
3213 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3214 regno, reg_type_str[reg->type], off, size);
3215
3216 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003217}
3218
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003219static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3220{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003221 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003222}
3223
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003224static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3225{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003226 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003227
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003228 return reg->type == PTR_TO_CTX;
3229}
3230
3231static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3232{
3233 const struct bpf_reg_state *reg = reg_state(env, regno);
3234
3235 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003236}
3237
Daniel Borkmannca369602018-02-23 22:29:05 +01003238static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3239{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003240 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003241
3242 return type_is_pkt_pointer(reg->type);
3243}
3244
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003245static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3246{
3247 const struct bpf_reg_state *reg = reg_state(env, regno);
3248
3249 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3250 return reg->type == PTR_TO_FLOW_KEYS;
3251}
3252
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003253static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3254 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003255 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003256{
Edward Creef1174f72017-08-07 15:26:19 +01003257 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003258 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003259
3260 /* Byte size accesses are always allowed. */
3261 if (!strict || size == 1)
3262 return 0;
3263
David S. Millere4eda882017-05-22 12:27:07 -04003264 /* For platforms that do not have a Kconfig enabling
3265 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3266 * NET_IP_ALIGN is universally set to '2'. And on platforms
3267 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3268 * to this code only in strict mode where we want to emulate
3269 * the NET_IP_ALIGN==2 checking. Therefore use an
3270 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003271 */
David S. Millere4eda882017-05-22 12:27:07 -04003272 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003273
3274 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3275 if (!tnum_is_aligned(reg_off, size)) {
3276 char tn_buf[48];
3277
3278 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003279 verbose(env,
3280 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003281 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003282 return -EACCES;
3283 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003284
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003285 return 0;
3286}
3287
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003288static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3289 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003290 const char *pointer_desc,
3291 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003292{
Edward Creef1174f72017-08-07 15:26:19 +01003293 struct tnum reg_off;
3294
3295 /* Byte size accesses are always allowed. */
3296 if (!strict || size == 1)
3297 return 0;
3298
3299 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3300 if (!tnum_is_aligned(reg_off, size)) {
3301 char tn_buf[48];
3302
3303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003304 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003305 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003306 return -EACCES;
3307 }
3308
3309 return 0;
3310}
3311
David S. Millere07b98d2017-05-10 11:38:07 -07003312static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003313 const struct bpf_reg_state *reg, int off,
3314 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003315{
Daniel Borkmannca369602018-02-23 22:29:05 +01003316 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003317 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003318
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003319 switch (reg->type) {
3320 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003321 case PTR_TO_PACKET_META:
3322 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3323 * right in front, treat it the very same way.
3324 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003325 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003326 case PTR_TO_FLOW_KEYS:
3327 pointer_desc = "flow keys ";
3328 break;
Yonghong Song69c087b2021-02-26 12:49:25 -08003329 case PTR_TO_MAP_KEY:
3330 pointer_desc = "key ";
3331 break;
Edward Creef1174f72017-08-07 15:26:19 +01003332 case PTR_TO_MAP_VALUE:
3333 pointer_desc = "value ";
3334 break;
3335 case PTR_TO_CTX:
3336 pointer_desc = "context ";
3337 break;
3338 case PTR_TO_STACK:
3339 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003340 /* The stack spill tracking logic in check_stack_write_fixed_off()
3341 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003342 * aligned.
3343 */
3344 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003345 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003346 case PTR_TO_SOCKET:
3347 pointer_desc = "sock ";
3348 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003349 case PTR_TO_SOCK_COMMON:
3350 pointer_desc = "sock_common ";
3351 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003352 case PTR_TO_TCP_SOCK:
3353 pointer_desc = "tcp_sock ";
3354 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003355 case PTR_TO_XDP_SOCK:
3356 pointer_desc = "xdp_sock ";
3357 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003358 default:
Edward Creef1174f72017-08-07 15:26:19 +01003359 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003360 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003361 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3362 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003363}
3364
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003365static int update_stack_depth(struct bpf_verifier_env *env,
3366 const struct bpf_func_state *func,
3367 int off)
3368{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003369 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003370
3371 if (stack >= -off)
3372 return 0;
3373
3374 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003375 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003376 return 0;
3377}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003378
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003379/* starting from main bpf function walk all instructions of the function
3380 * and recursively walk all callees that given function can call.
3381 * Ignore jump and exit insns.
3382 * Since recursion is prevented by check_cfg() this algorithm
3383 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3384 */
3385static int check_max_stack_depth(struct bpf_verifier_env *env)
3386{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003387 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3388 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003389 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003390 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003391 int ret_insn[MAX_CALL_FRAMES];
3392 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003393 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003394
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003395process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003396 /* protect against potential stack overflow that might happen when
3397 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3398 * depth for such case down to 256 so that the worst case scenario
3399 * would result in 8k stack size (32 which is tailcall limit * 256 =
3400 * 8k).
3401 *
3402 * To get the idea what might happen, see an example:
3403 * func1 -> sub rsp, 128
3404 * subfunc1 -> sub rsp, 256
3405 * tailcall1 -> add rsp, 256
3406 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3407 * subfunc2 -> sub rsp, 64
3408 * subfunc22 -> sub rsp, 128
3409 * tailcall2 -> add rsp, 128
3410 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3411 *
3412 * tailcall will unwind the current stack frame but it will not get rid
3413 * of caller's stack as shown on the example above.
3414 */
3415 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3416 verbose(env,
3417 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3418 depth);
3419 return -EACCES;
3420 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003421 /* round up to 32-bytes, since this is granularity
3422 * of interpreter stack size
3423 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003424 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003425 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003426 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003427 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003428 return -EACCES;
3429 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003430continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003431 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003432 for (; i < subprog_end; i++) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003433 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003434 continue;
3435 /* remember insn and function to return to */
3436 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003437 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003438
3439 /* find the callee */
3440 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003441 idx = find_subprog(env, i);
3442 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003443 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3444 i);
3445 return -EFAULT;
3446 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003447
3448 if (subprog[idx].has_tail_call)
3449 tail_call_reachable = true;
3450
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003451 frame++;
3452 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003453 verbose(env, "the call stack of %d frames is too deep !\n",
3454 frame);
3455 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003456 }
3457 goto process_func;
3458 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003459 /* if tail call got detected across bpf2bpf calls then mark each of the
3460 * currently present subprog frames as tail call reachable subprogs;
3461 * this info will be utilized by JIT so that we will be preserving the
3462 * tail call counter throughout bpf2bpf calls combined with tailcalls
3463 */
3464 if (tail_call_reachable)
3465 for (j = 0; j < frame; j++)
3466 subprog[ret_prog[j]].tail_call_reachable = true;
3467
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003468 /* end of for() loop means the last insn of the 'subprog'
3469 * was reached. Doesn't matter whether it was JA or EXIT
3470 */
3471 if (frame == 0)
3472 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003473 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003474 frame--;
3475 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003476 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003477 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003478}
3479
David S. Miller19d28fb2018-01-11 21:27:54 -05003480#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003481static int get_callee_stack_depth(struct bpf_verifier_env *env,
3482 const struct bpf_insn *insn, int idx)
3483{
3484 int start = idx + insn->imm + 1, subprog;
3485
3486 subprog = find_subprog(env, start);
3487 if (subprog < 0) {
3488 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3489 start);
3490 return -EFAULT;
3491 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003492 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003493}
David S. Miller19d28fb2018-01-11 21:27:54 -05003494#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003495
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003496int check_ctx_reg(struct bpf_verifier_env *env,
3497 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003498{
3499 /* Access to ctx or passing it to a helper is only allowed in
3500 * its original, unmodified form.
3501 */
3502
3503 if (reg->off) {
3504 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3505 regno, reg->off);
3506 return -EACCES;
3507 }
3508
3509 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3510 char tn_buf[48];
3511
3512 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3513 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3514 return -EACCES;
3515 }
3516
3517 return 0;
3518}
3519
Yonghong Songafbf21d2020-07-23 11:41:11 -07003520static int __check_buffer_access(struct bpf_verifier_env *env,
3521 const char *buf_info,
3522 const struct bpf_reg_state *reg,
3523 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003524{
3525 if (off < 0) {
3526 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003527 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003528 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003529 return -EACCES;
3530 }
3531 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3532 char tn_buf[48];
3533
3534 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3535 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003536 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003537 regno, off, tn_buf);
3538 return -EACCES;
3539 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003540
3541 return 0;
3542}
3543
3544static int check_tp_buffer_access(struct bpf_verifier_env *env,
3545 const struct bpf_reg_state *reg,
3546 int regno, int off, int size)
3547{
3548 int err;
3549
3550 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3551 if (err)
3552 return err;
3553
Matt Mullins9df1c282019-04-26 11:49:47 -07003554 if (off + size > env->prog->aux->max_tp_access)
3555 env->prog->aux->max_tp_access = off + size;
3556
3557 return 0;
3558}
3559
Yonghong Songafbf21d2020-07-23 11:41:11 -07003560static int check_buffer_access(struct bpf_verifier_env *env,
3561 const struct bpf_reg_state *reg,
3562 int regno, int off, int size,
3563 bool zero_size_allowed,
3564 const char *buf_info,
3565 u32 *max_access)
3566{
3567 int err;
3568
3569 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3570 if (err)
3571 return err;
3572
3573 if (off + size > *max_access)
3574 *max_access = off + size;
3575
3576 return 0;
3577}
3578
John Fastabend3f50f132020-03-30 14:36:39 -07003579/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3580static void zext_32_to_64(struct bpf_reg_state *reg)
3581{
3582 reg->var_off = tnum_subreg(reg->var_off);
3583 __reg_assign_32_into_64(reg);
3584}
Matt Mullins9df1c282019-04-26 11:49:47 -07003585
Jann Horn0c17d1d2017-12-18 20:11:55 -08003586/* truncate register to smaller size (in bytes)
3587 * must be called with size < BPF_REG_SIZE
3588 */
3589static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3590{
3591 u64 mask;
3592
3593 /* clear high bits in bit representation */
3594 reg->var_off = tnum_cast(reg->var_off, size);
3595
3596 /* fix arithmetic bounds */
3597 mask = ((u64)1 << (size * 8)) - 1;
3598 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3599 reg->umin_value &= mask;
3600 reg->umax_value &= mask;
3601 } else {
3602 reg->umin_value = 0;
3603 reg->umax_value = mask;
3604 }
3605 reg->smin_value = reg->umin_value;
3606 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003607
3608 /* If size is smaller than 32bit register the 32bit register
3609 * values are also truncated so we push 64-bit bounds into
3610 * 32-bit bounds. Above were truncated < 32-bits already.
3611 */
3612 if (size >= 4)
3613 return;
3614 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003615}
3616
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003617static bool bpf_map_is_rdonly(const struct bpf_map *map)
3618{
3619 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3620}
3621
3622static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3623{
3624 void *ptr;
3625 u64 addr;
3626 int err;
3627
3628 err = map->ops->map_direct_value_addr(map, &addr, off);
3629 if (err)
3630 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003631 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003632
3633 switch (size) {
3634 case sizeof(u8):
3635 *val = (u64)*(u8 *)ptr;
3636 break;
3637 case sizeof(u16):
3638 *val = (u64)*(u16 *)ptr;
3639 break;
3640 case sizeof(u32):
3641 *val = (u64)*(u32 *)ptr;
3642 break;
3643 case sizeof(u64):
3644 *val = *(u64 *)ptr;
3645 break;
3646 default:
3647 return -EINVAL;
3648 }
3649 return 0;
3650}
3651
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003652static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3653 struct bpf_reg_state *regs,
3654 int regno, int off, int size,
3655 enum bpf_access_type atype,
3656 int value_regno)
3657{
3658 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003659 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3660 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003661 u32 btf_id;
3662 int ret;
3663
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003664 if (off < 0) {
3665 verbose(env,
3666 "R%d is ptr_%s invalid negative access: off=%d\n",
3667 regno, tname, off);
3668 return -EACCES;
3669 }
3670 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3671 char tn_buf[48];
3672
3673 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3674 verbose(env,
3675 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3676 regno, tname, off, tn_buf);
3677 return -EACCES;
3678 }
3679
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003680 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003681 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3682 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003683 } else {
3684 if (atype != BPF_READ) {
3685 verbose(env, "only read is supported\n");
3686 return -EACCES;
3687 }
3688
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003689 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3690 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003691 }
3692
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003693 if (ret < 0)
3694 return ret;
3695
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003696 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003697 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003698
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003699 return 0;
3700}
3701
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003702static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3703 struct bpf_reg_state *regs,
3704 int regno, int off, int size,
3705 enum bpf_access_type atype,
3706 int value_regno)
3707{
3708 struct bpf_reg_state *reg = regs + regno;
3709 struct bpf_map *map = reg->map_ptr;
3710 const struct btf_type *t;
3711 const char *tname;
3712 u32 btf_id;
3713 int ret;
3714
3715 if (!btf_vmlinux) {
3716 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3717 return -ENOTSUPP;
3718 }
3719
3720 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3721 verbose(env, "map_ptr access not supported for map type %d\n",
3722 map->map_type);
3723 return -ENOTSUPP;
3724 }
3725
3726 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3727 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3728
3729 if (!env->allow_ptr_to_map_access) {
3730 verbose(env,
3731 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3732 tname);
3733 return -EPERM;
3734 }
3735
3736 if (off < 0) {
3737 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3738 regno, tname, off);
3739 return -EACCES;
3740 }
3741
3742 if (atype != BPF_READ) {
3743 verbose(env, "only read from %s is supported\n", tname);
3744 return -EACCES;
3745 }
3746
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003747 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003748 if (ret < 0)
3749 return ret;
3750
3751 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003752 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003753
3754 return 0;
3755}
3756
Andrei Matei01f810a2021-02-06 20:10:24 -05003757/* Check that the stack access at the given offset is within bounds. The
3758 * maximum valid offset is -1.
3759 *
3760 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3761 * -state->allocated_stack for reads.
3762 */
3763static int check_stack_slot_within_bounds(int off,
3764 struct bpf_func_state *state,
3765 enum bpf_access_type t)
3766{
3767 int min_valid_off;
3768
3769 if (t == BPF_WRITE)
3770 min_valid_off = -MAX_BPF_STACK;
3771 else
3772 min_valid_off = -state->allocated_stack;
3773
3774 if (off < min_valid_off || off > -1)
3775 return -EACCES;
3776 return 0;
3777}
3778
3779/* Check that the stack access at 'regno + off' falls within the maximum stack
3780 * bounds.
3781 *
3782 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3783 */
3784static int check_stack_access_within_bounds(
3785 struct bpf_verifier_env *env,
3786 int regno, int off, int access_size,
3787 enum stack_access_src src, enum bpf_access_type type)
3788{
3789 struct bpf_reg_state *regs = cur_regs(env);
3790 struct bpf_reg_state *reg = regs + regno;
3791 struct bpf_func_state *state = func(env, reg);
3792 int min_off, max_off;
3793 int err;
3794 char *err_extra;
3795
3796 if (src == ACCESS_HELPER)
3797 /* We don't know if helpers are reading or writing (or both). */
3798 err_extra = " indirect access to";
3799 else if (type == BPF_READ)
3800 err_extra = " read from";
3801 else
3802 err_extra = " write to";
3803
3804 if (tnum_is_const(reg->var_off)) {
3805 min_off = reg->var_off.value + off;
3806 if (access_size > 0)
3807 max_off = min_off + access_size - 1;
3808 else
3809 max_off = min_off;
3810 } else {
3811 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3812 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3813 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3814 err_extra, regno);
3815 return -EACCES;
3816 }
3817 min_off = reg->smin_value + off;
3818 if (access_size > 0)
3819 max_off = reg->smax_value + off + access_size - 1;
3820 else
3821 max_off = min_off;
3822 }
3823
3824 err = check_stack_slot_within_bounds(min_off, state, type);
3825 if (!err)
3826 err = check_stack_slot_within_bounds(max_off, state, type);
3827
3828 if (err) {
3829 if (tnum_is_const(reg->var_off)) {
3830 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3831 err_extra, regno, off, access_size);
3832 } else {
3833 char tn_buf[48];
3834
3835 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3836 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3837 err_extra, regno, tn_buf, access_size);
3838 }
3839 }
3840 return err;
3841}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003842
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003843/* check whether memory at (regno + off) is accessible for t = (read | write)
3844 * if t==write, value_regno is a register which value is stored into memory
3845 * if t==read, value_regno is a register which will receive the value from memory
3846 * if t==write && value_regno==-1, some unknown value is stored into memory
3847 * if t==read && value_regno==-1, don't care what we read from memory
3848 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003849static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3850 int off, int bpf_size, enum bpf_access_type t,
3851 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003852{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003853 struct bpf_reg_state *regs = cur_regs(env);
3854 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003855 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003856 int size, err = 0;
3857
3858 size = bpf_size_to_bytes(bpf_size);
3859 if (size < 0)
3860 return size;
3861
Edward Creef1174f72017-08-07 15:26:19 +01003862 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003863 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003864 if (err)
3865 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003866
Edward Creef1174f72017-08-07 15:26:19 +01003867 /* for access checks, reg->off is just part of off */
3868 off += reg->off;
3869
Yonghong Song69c087b2021-02-26 12:49:25 -08003870 if (reg->type == PTR_TO_MAP_KEY) {
3871 if (t == BPF_WRITE) {
3872 verbose(env, "write to change key R%d not allowed\n", regno);
3873 return -EACCES;
3874 }
3875
3876 err = check_mem_region_access(env, regno, off, size,
3877 reg->map_ptr->key_size, false);
3878 if (err)
3879 return err;
3880 if (value_regno >= 0)
3881 mark_reg_unknown(env, regs, value_regno);
3882 } else if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003883 if (t == BPF_WRITE && value_regno >= 0 &&
3884 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003885 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003886 return -EACCES;
3887 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003888 err = check_map_access_type(env, regno, off, size, t);
3889 if (err)
3890 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003891 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003892 if (!err && t == BPF_READ && value_regno >= 0) {
3893 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003894
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003895 /* if map is read-only, track its contents as scalars */
3896 if (tnum_is_const(reg->var_off) &&
3897 bpf_map_is_rdonly(map) &&
3898 map->ops->map_direct_value_addr) {
3899 int map_off = off + reg->var_off.value;
3900 u64 val = 0;
3901
3902 err = bpf_map_direct_read(map, map_off, size,
3903 &val);
3904 if (err)
3905 return err;
3906
3907 regs[value_regno].type = SCALAR_VALUE;
3908 __mark_reg_known(&regs[value_regno], val);
3909 } else {
3910 mark_reg_unknown(env, regs, value_regno);
3911 }
3912 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003913 } else if (reg->type == PTR_TO_MEM) {
3914 if (t == BPF_WRITE && value_regno >= 0 &&
3915 is_pointer_value(env, value_regno)) {
3916 verbose(env, "R%d leaks addr into mem\n", value_regno);
3917 return -EACCES;
3918 }
3919 err = check_mem_region_access(env, regno, off, size,
3920 reg->mem_size, false);
3921 if (!err && t == BPF_READ && value_regno >= 0)
3922 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003923 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003924 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003925 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003926 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003927
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003928 if (t == BPF_WRITE && value_regno >= 0 &&
3929 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003930 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003931 return -EACCES;
3932 }
Edward Creef1174f72017-08-07 15:26:19 +01003933
Daniel Borkmann58990d12018-06-07 17:40:03 +02003934 err = check_ctx_reg(env, reg, regno);
3935 if (err < 0)
3936 return err;
3937
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003938 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003939 if (err)
3940 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003941 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003942 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003943 * PTR_TO_PACKET[_META,_END]. In the latter
3944 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003945 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003946 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003947 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003948 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003949 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003950 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003951 if (reg_type_may_be_null(reg_type))
3952 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003953 /* A load of ctx field could have different
3954 * actual load size with the one encoded in the
3955 * insn. When the dst is PTR, it is for sure not
3956 * a sub-register.
3957 */
3958 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003959 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003960 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3961 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003962 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003963 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003964 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003965 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003966 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003967
Edward Creef1174f72017-08-07 15:26:19 +01003968 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05003969 /* Basic bounds checks. */
3970 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003971 if (err)
3972 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003973
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003974 state = func(env, reg);
3975 err = update_stack_depth(env, state, off);
3976 if (err)
3977 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003978
Andrei Matei01f810a2021-02-06 20:10:24 -05003979 if (t == BPF_READ)
3980 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003981 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05003982 else
3983 err = check_stack_write(env, regno, off, size,
3984 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003985 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003986 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003987 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003988 return -EACCES;
3989 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003990 if (t == BPF_WRITE && value_regno >= 0 &&
3991 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003992 verbose(env, "R%d leaks addr into packet\n",
3993 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003994 return -EACCES;
3995 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003996 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003997 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003998 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003999 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4000 if (t == BPF_WRITE && value_regno >= 0 &&
4001 is_pointer_value(env, value_regno)) {
4002 verbose(env, "R%d leaks addr into flow keys\n",
4003 value_regno);
4004 return -EACCES;
4005 }
4006
4007 err = check_flow_keys_access(env, off, size);
4008 if (!err && t == BPF_READ && value_regno >= 0)
4009 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004010 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07004011 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004012 verbose(env, "R%d cannot write into %s\n",
4013 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07004014 return -EACCES;
4015 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08004016 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07004017 if (!err && value_regno >= 0)
4018 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07004019 } else if (reg->type == PTR_TO_TP_BUFFER) {
4020 err = check_tp_buffer_access(env, reg, regno, off, size);
4021 if (!err && t == BPF_READ && value_regno >= 0)
4022 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004023 } else if (reg->type == PTR_TO_BTF_ID) {
4024 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4025 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004026 } else if (reg->type == CONST_PTR_TO_MAP) {
4027 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4028 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004029 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4030 if (t == BPF_WRITE) {
4031 verbose(env, "R%d cannot write into %s\n",
4032 regno, reg_type_str[reg->type]);
4033 return -EACCES;
4034 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004035 err = check_buffer_access(env, reg, regno, off, size, false,
4036 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004037 &env->prog->aux->max_rdonly_access);
4038 if (!err && value_regno >= 0)
4039 mark_reg_unknown(env, regs, value_regno);
4040 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004041 err = check_buffer_access(env, reg, regno, off, size, false,
4042 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004043 &env->prog->aux->max_rdwr_access);
4044 if (!err && t == BPF_READ && value_regno >= 0)
4045 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004046 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004047 verbose(env, "R%d invalid mem access '%s'\n", regno,
4048 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004049 return -EACCES;
4050 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004051
Edward Creef1174f72017-08-07 15:26:19 +01004052 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004053 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004054 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08004055 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004056 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004057 return err;
4058}
4059
Brendan Jackman91c960b2021-01-14 18:17:44 +00004060static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004061{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004062 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004063 int err;
4064
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004065 switch (insn->imm) {
4066 case BPF_ADD:
4067 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004068 case BPF_AND:
4069 case BPF_AND | BPF_FETCH:
4070 case BPF_OR:
4071 case BPF_OR | BPF_FETCH:
4072 case BPF_XOR:
4073 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004074 case BPF_XCHG:
4075 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004076 break;
4077 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004078 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4079 return -EINVAL;
4080 }
4081
4082 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4083 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004084 return -EINVAL;
4085 }
4086
4087 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004088 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004089 if (err)
4090 return err;
4091
4092 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004093 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004094 if (err)
4095 return err;
4096
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004097 if (insn->imm == BPF_CMPXCHG) {
4098 /* Check comparison of R0 with memory location */
4099 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4100 if (err)
4101 return err;
4102 }
4103
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004104 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004105 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004106 return -EACCES;
4107 }
4108
Daniel Borkmannca369602018-02-23 22:29:05 +01004109 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004110 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004111 is_flow_key_reg(env, insn->dst_reg) ||
4112 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004113 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004114 insn->dst_reg,
4115 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004116 return -EACCES;
4117 }
4118
Brendan Jackman37086bf2021-02-02 13:50:02 +00004119 if (insn->imm & BPF_FETCH) {
4120 if (insn->imm == BPF_CMPXCHG)
4121 load_reg = BPF_REG_0;
4122 else
4123 load_reg = insn->src_reg;
4124
4125 /* check and record load of old value */
4126 err = check_reg_arg(env, load_reg, DST_OP);
4127 if (err)
4128 return err;
4129 } else {
4130 /* This instruction accesses a memory location but doesn't
4131 * actually load it into a register.
4132 */
4133 load_reg = -1;
4134 }
4135
Brendan Jackman91c960b2021-01-14 18:17:44 +00004136 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004137 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004138 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004139 if (err)
4140 return err;
4141
Brendan Jackman91c960b2021-01-14 18:17:44 +00004142 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004143 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4144 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4145 if (err)
4146 return err;
4147
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004148 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004149}
4150
Andrei Matei01f810a2021-02-06 20:10:24 -05004151/* When register 'regno' is used to read the stack (either directly or through
4152 * a helper function) make sure that it's within stack boundary and, depending
4153 * on the access type, that all elements of the stack are initialized.
4154 *
4155 * 'off' includes 'regno->off', but not its dynamic part (if any).
4156 *
4157 * All registers that have been spilled on the stack in the slots within the
4158 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004159 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004160static int check_stack_range_initialized(
4161 struct bpf_verifier_env *env, int regno, int off,
4162 int access_size, bool zero_size_allowed,
4163 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004164{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004165 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004166 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004167 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004168 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4169 enum bpf_access_type bounds_check_type;
4170 /* Some accesses can write anything into the stack, others are
4171 * read-only.
4172 */
4173 bool clobber = false;
4174
4175 if (access_size == 0 && !zero_size_allowed) {
4176 verbose(env, "invalid zero-sized read\n");
4177 return -EACCES;
4178 }
4179
4180 if (type == ACCESS_HELPER) {
4181 /* The bounds checks for writes are more permissive than for
4182 * reads. However, if raw_mode is not set, we'll do extra
4183 * checks below.
4184 */
4185 bounds_check_type = BPF_WRITE;
4186 clobber = true;
4187 } else {
4188 bounds_check_type = BPF_READ;
4189 }
4190 err = check_stack_access_within_bounds(env, regno, off, access_size,
4191 type, bounds_check_type);
4192 if (err)
4193 return err;
4194
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004195
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004196 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004197 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004198 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004199 /* Variable offset is prohibited for unprivileged mode for
4200 * simplicity since it requires corresponding support in
4201 * Spectre masking for stack ALU.
4202 * See also retrieve_ptr_limit().
4203 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004204 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004205 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004206
Andrey Ignatov088ec262019-04-03 23:22:39 -07004207 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004208 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4209 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004210 return -EACCES;
4211 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004212 /* Only initialized buffer on stack is allowed to be accessed
4213 * with variable offset. With uninitialized buffer it's hard to
4214 * guarantee that whole memory is marked as initialized on
4215 * helper return since specific bounds are unknown what may
4216 * cause uninitialized stack leaking.
4217 */
4218 if (meta && meta->raw_mode)
4219 meta = NULL;
4220
Andrei Matei01f810a2021-02-06 20:10:24 -05004221 min_off = reg->smin_value + off;
4222 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004223 }
4224
Daniel Borkmann435faee12016-04-13 00:10:51 +02004225 if (meta && meta->raw_mode) {
4226 meta->access_size = access_size;
4227 meta->regno = regno;
4228 return 0;
4229 }
4230
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004231 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004232 u8 *stype;
4233
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004234 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004235 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004236 if (state->allocated_stack <= slot)
4237 goto err;
4238 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4239 if (*stype == STACK_MISC)
4240 goto mark;
4241 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004242 if (clobber) {
4243 /* helper can write anything into the stack */
4244 *stype = STACK_MISC;
4245 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004246 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004247 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004248
4249 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4250 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4251 goto mark;
4252
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004253 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004254 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4255 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004256 if (clobber) {
4257 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4258 for (j = 0; j < BPF_REG_SIZE; j++)
4259 state->stack[spi].slot_type[j] = STACK_MISC;
4260 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004261 goto mark;
4262 }
4263
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004264err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004265 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004266 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4267 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004268 } else {
4269 char tn_buf[48];
4270
4271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004272 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4273 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004274 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004275 return -EACCES;
4276mark:
4277 /* reading any byte out of 8-byte 'spill_slot' will cause
4278 * the whole slot to be marked as 'read'
4279 */
Edward Cree679c7822018-08-22 20:02:19 +01004280 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004281 state->stack[spi].spilled_ptr.parent,
4282 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004283 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004284 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004285}
4286
Gianluca Borello06c1c042017-01-09 10:19:49 -08004287static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4288 int access_size, bool zero_size_allowed,
4289 struct bpf_call_arg_meta *meta)
4290{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004291 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004292
Edward Creef1174f72017-08-07 15:26:19 +01004293 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004294 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004295 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004296 return check_packet_access(env, regno, reg->off, access_size,
4297 zero_size_allowed);
Yonghong Song69c087b2021-02-26 12:49:25 -08004298 case PTR_TO_MAP_KEY:
4299 return check_mem_region_access(env, regno, reg->off, access_size,
4300 reg->map_ptr->key_size, false);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004301 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004302 if (check_map_access_type(env, regno, reg->off, access_size,
4303 meta && meta->raw_mode ? BPF_WRITE :
4304 BPF_READ))
4305 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004306 return check_map_access(env, regno, reg->off, access_size,
4307 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004308 case PTR_TO_MEM:
4309 return check_mem_region_access(env, regno, reg->off,
4310 access_size, reg->mem_size,
4311 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004312 case PTR_TO_RDONLY_BUF:
4313 if (meta && meta->raw_mode)
4314 return -EACCES;
4315 return check_buffer_access(env, reg, regno, reg->off,
4316 access_size, zero_size_allowed,
4317 "rdonly",
4318 &env->prog->aux->max_rdonly_access);
4319 case PTR_TO_RDWR_BUF:
4320 return check_buffer_access(env, reg, regno, reg->off,
4321 access_size, zero_size_allowed,
4322 "rdwr",
4323 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004324 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004325 return check_stack_range_initialized(
4326 env,
4327 regno, reg->off, access_size,
4328 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004329 default: /* scalar_value or invalid ptr */
4330 /* Allow zero-byte read from NULL, regardless of pointer type */
4331 if (zero_size_allowed && access_size == 0 &&
4332 register_is_null(reg))
4333 return 0;
4334
4335 verbose(env, "R%d type=%s expected=%s\n", regno,
4336 reg_type_str[reg->type],
4337 reg_type_str[PTR_TO_STACK]);
4338 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004339 }
4340}
4341
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004342int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4343 u32 regno, u32 mem_size)
4344{
4345 if (register_is_null(reg))
4346 return 0;
4347
4348 if (reg_type_may_be_null(reg->type)) {
4349 /* Assuming that the register contains a value check if the memory
4350 * access is safe. Temporarily save and restore the register's state as
4351 * the conversion shouldn't be visible to a caller.
4352 */
4353 const struct bpf_reg_state saved_reg = *reg;
4354 int rv;
4355
4356 mark_ptr_not_null_reg(reg);
4357 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4358 *reg = saved_reg;
4359 return rv;
4360 }
4361
4362 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4363}
4364
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004365/* Implementation details:
4366 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4367 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4368 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4369 * value_or_null->value transition, since the verifier only cares about
4370 * the range of access to valid map value pointer and doesn't care about actual
4371 * address of the map element.
4372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4373 * reg->id > 0 after value_or_null->value transition. By doing so
4374 * two bpf_map_lookups will be considered two different pointers that
4375 * point to different bpf_spin_locks.
4376 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4377 * dead-locks.
4378 * Since only one bpf_spin_lock is allowed the checks are simpler than
4379 * reg_is_refcounted() logic. The verifier needs to remember only
4380 * one spin_lock instead of array of acquired_refs.
4381 * cur_state->active_spin_lock remembers which map value element got locked
4382 * and clears it after bpf_spin_unlock.
4383 */
4384static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4385 bool is_lock)
4386{
4387 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4388 struct bpf_verifier_state *cur = env->cur_state;
4389 bool is_const = tnum_is_const(reg->var_off);
4390 struct bpf_map *map = reg->map_ptr;
4391 u64 val = reg->var_off.value;
4392
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004393 if (!is_const) {
4394 verbose(env,
4395 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4396 regno);
4397 return -EINVAL;
4398 }
4399 if (!map->btf) {
4400 verbose(env,
4401 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4402 map->name);
4403 return -EINVAL;
4404 }
4405 if (!map_value_has_spin_lock(map)) {
4406 if (map->spin_lock_off == -E2BIG)
4407 verbose(env,
4408 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4409 map->name);
4410 else if (map->spin_lock_off == -ENOENT)
4411 verbose(env,
4412 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4413 map->name);
4414 else
4415 verbose(env,
4416 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4417 map->name);
4418 return -EINVAL;
4419 }
4420 if (map->spin_lock_off != val + reg->off) {
4421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4422 val + reg->off);
4423 return -EINVAL;
4424 }
4425 if (is_lock) {
4426 if (cur->active_spin_lock) {
4427 verbose(env,
4428 "Locking two bpf_spin_locks are not allowed\n");
4429 return -EINVAL;
4430 }
4431 cur->active_spin_lock = reg->id;
4432 } else {
4433 if (!cur->active_spin_lock) {
4434 verbose(env, "bpf_spin_unlock without taking a lock\n");
4435 return -EINVAL;
4436 }
4437 if (cur->active_spin_lock != reg->id) {
4438 verbose(env, "bpf_spin_unlock of different lock\n");
4439 return -EINVAL;
4440 }
4441 cur->active_spin_lock = 0;
4442 }
4443 return 0;
4444}
4445
Daniel Borkmann90133412018-01-20 01:24:29 +01004446static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4447{
4448 return type == ARG_PTR_TO_MEM ||
4449 type == ARG_PTR_TO_MEM_OR_NULL ||
4450 type == ARG_PTR_TO_UNINIT_MEM;
4451}
4452
4453static bool arg_type_is_mem_size(enum bpf_arg_type type)
4454{
4455 return type == ARG_CONST_SIZE ||
4456 type == ARG_CONST_SIZE_OR_ZERO;
4457}
4458
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004459static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4460{
4461 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4462}
4463
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004464static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4465{
4466 return type == ARG_PTR_TO_INT ||
4467 type == ARG_PTR_TO_LONG;
4468}
4469
4470static int int_ptr_type_to_size(enum bpf_arg_type type)
4471{
4472 if (type == ARG_PTR_TO_INT)
4473 return sizeof(u32);
4474 else if (type == ARG_PTR_TO_LONG)
4475 return sizeof(u64);
4476
4477 return -EINVAL;
4478}
4479
Lorenz Bauer912f4422020-08-21 11:29:46 +01004480static int resolve_map_arg_type(struct bpf_verifier_env *env,
4481 const struct bpf_call_arg_meta *meta,
4482 enum bpf_arg_type *arg_type)
4483{
4484 if (!meta->map_ptr) {
4485 /* kernel subsystem misconfigured verifier */
4486 verbose(env, "invalid map_ptr to access map->type\n");
4487 return -EACCES;
4488 }
4489
4490 switch (meta->map_ptr->map_type) {
4491 case BPF_MAP_TYPE_SOCKMAP:
4492 case BPF_MAP_TYPE_SOCKHASH:
4493 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01004494 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01004495 } else {
4496 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4497 return -EINVAL;
4498 }
4499 break;
4500
4501 default:
4502 break;
4503 }
4504 return 0;
4505}
4506
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004507struct bpf_reg_types {
4508 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004509 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004510};
4511
4512static const struct bpf_reg_types map_key_value_types = {
4513 .types = {
4514 PTR_TO_STACK,
4515 PTR_TO_PACKET,
4516 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004517 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004518 PTR_TO_MAP_VALUE,
4519 },
4520};
4521
4522static const struct bpf_reg_types sock_types = {
4523 .types = {
4524 PTR_TO_SOCK_COMMON,
4525 PTR_TO_SOCKET,
4526 PTR_TO_TCP_SOCK,
4527 PTR_TO_XDP_SOCK,
4528 },
4529};
4530
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004531#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004532static const struct bpf_reg_types btf_id_sock_common_types = {
4533 .types = {
4534 PTR_TO_SOCK_COMMON,
4535 PTR_TO_SOCKET,
4536 PTR_TO_TCP_SOCK,
4537 PTR_TO_XDP_SOCK,
4538 PTR_TO_BTF_ID,
4539 },
4540 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4541};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004542#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004543
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004544static const struct bpf_reg_types mem_types = {
4545 .types = {
4546 PTR_TO_STACK,
4547 PTR_TO_PACKET,
4548 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004549 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004550 PTR_TO_MAP_VALUE,
4551 PTR_TO_MEM,
4552 PTR_TO_RDONLY_BUF,
4553 PTR_TO_RDWR_BUF,
4554 },
4555};
4556
4557static const struct bpf_reg_types int_ptr_types = {
4558 .types = {
4559 PTR_TO_STACK,
4560 PTR_TO_PACKET,
4561 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08004562 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004563 PTR_TO_MAP_VALUE,
4564 },
4565};
4566
4567static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4568static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4569static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4570static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4571static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4572static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4573static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004574static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Yonghong Song69c087b2021-02-26 12:49:25 -08004575static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
4576static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004577
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004578static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004579 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4580 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4581 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4582 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4583 [ARG_CONST_SIZE] = &scalar_types,
4584 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4585 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4586 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4587 [ARG_PTR_TO_CTX] = &context_types,
4588 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4589 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004590#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004591 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004592#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004593 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4594 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4595 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4596 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4597 [ARG_PTR_TO_MEM] = &mem_types,
4598 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4599 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4600 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4601 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4602 [ARG_PTR_TO_INT] = &int_ptr_types,
4603 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004604 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Yonghong Song69c087b2021-02-26 12:49:25 -08004605 [ARG_PTR_TO_FUNC] = &func_ptr_types,
4606 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004607};
4608
4609static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004610 enum bpf_arg_type arg_type,
4611 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004612{
4613 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4614 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004615 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004616 int i, j;
4617
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004618 compatible = compatible_reg_types[arg_type];
4619 if (!compatible) {
4620 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4621 return -EFAULT;
4622 }
4623
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004624 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4625 expected = compatible->types[i];
4626 if (expected == NOT_INIT)
4627 break;
4628
4629 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004630 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004631 }
4632
4633 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4634 for (j = 0; j + 1 < i; j++)
4635 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4636 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4637 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004638
4639found:
4640 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004641 if (!arg_btf_id) {
4642 if (!compatible->btf_id) {
4643 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4644 return -EFAULT;
4645 }
4646 arg_btf_id = compatible->btf_id;
4647 }
4648
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004649 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4650 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004651 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004652 regno, kernel_type_name(reg->btf, reg->btf_id),
4653 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004654 return -EACCES;
4655 }
4656
4657 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4658 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4659 regno);
4660 return -EACCES;
4661 }
4662 }
4663
4664 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004665}
4666
Yonghong Songaf7ec132020-06-23 16:08:09 -07004667static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4668 struct bpf_call_arg_meta *meta,
4669 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004670{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004671 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004672 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004673 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004674 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004675 int err = 0;
4676
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004677 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004678 return 0;
4679
Edward Creedc503a82017-08-15 20:34:35 +01004680 err = check_reg_arg(env, regno, SRC_OP);
4681 if (err)
4682 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004683
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004684 if (arg_type == ARG_ANYTHING) {
4685 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004686 verbose(env, "R%d leaks addr into helper function\n",
4687 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004688 return -EACCES;
4689 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004690 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004691 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004692
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004693 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004694 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004695 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004696 return -EACCES;
4697 }
4698
Lorenz Bauer912f4422020-08-21 11:29:46 +01004699 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4700 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4701 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4702 err = resolve_map_arg_type(env, meta, &arg_type);
4703 if (err)
4704 return err;
4705 }
4706
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004707 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4708 /* A NULL register has a SCALAR_VALUE type, so skip
4709 * type checking.
4710 */
4711 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004712
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004713 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004714 if (err)
4715 return err;
4716
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004717 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004718 err = check_ctx_reg(env, reg, regno);
4719 if (err < 0)
4720 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004721 }
4722
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004723skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004724 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004725 if (meta->ref_obj_id) {
4726 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4727 regno, reg->ref_obj_id,
4728 meta->ref_obj_id);
4729 return -EFAULT;
4730 }
4731 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004732 }
4733
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004734 if (arg_type == ARG_CONST_MAP_PTR) {
4735 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004736 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004737 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4738 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4739 * check that [key, key + map->key_size) are within
4740 * stack limits and initialized
4741 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004742 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004743 /* in function declaration map_ptr must come before
4744 * map_key, so that it's verified and known before
4745 * we have to check map_key here. Otherwise it means
4746 * that kernel subsystem misconfigured verifier
4747 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004748 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004749 return -EACCES;
4750 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004751 err = check_helper_mem_access(env, regno,
4752 meta->map_ptr->key_size, false,
4753 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004754 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004755 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4756 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004757 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004758 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4759 * check [value, value + map->value_size) validity
4760 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004761 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004762 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004763 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004764 return -EACCES;
4765 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004766 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004767 err = check_helper_mem_access(env, regno,
4768 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004769 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004770 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4771 if (!reg->btf_id) {
4772 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4773 return -EACCES;
4774 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004775 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004776 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004777 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4778 if (meta->func_id == BPF_FUNC_spin_lock) {
4779 if (process_spin_lock(env, regno, true))
4780 return -EACCES;
4781 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4782 if (process_spin_lock(env, regno, false))
4783 return -EACCES;
4784 } else {
4785 verbose(env, "verifier internal error\n");
4786 return -EFAULT;
4787 }
Yonghong Song69c087b2021-02-26 12:49:25 -08004788 } else if (arg_type == ARG_PTR_TO_FUNC) {
4789 meta->subprogno = reg->subprogno;
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01004790 } else if (arg_type_is_mem_ptr(arg_type)) {
4791 /* The access to this pointer is only checked when we hit the
4792 * next is_mem_size argument below.
4793 */
4794 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01004795 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004796 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004797
John Fastabend10060502020-03-30 14:36:19 -07004798 /* This is used to refine r0 return value bounds for helpers
4799 * that enforce this value as an upper bound on return values.
4800 * See do_refine_retval_range() for helpers that can refine
4801 * the return value. C type of helper is u32 so we pull register
4802 * bound from umax_value however, if negative verifier errors
4803 * out. Only upper bounds can be learned because retval is an
4804 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004805 */
John Fastabend10060502020-03-30 14:36:19 -07004806 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004807
Edward Creef1174f72017-08-07 15:26:19 +01004808 /* The register is SCALAR_VALUE; the access check
4809 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004810 */
Edward Creef1174f72017-08-07 15:26:19 +01004811 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004812 /* For unprivileged variable accesses, disable raw
4813 * mode so that the program is required to
4814 * initialize all the memory that the helper could
4815 * just partially fill up.
4816 */
4817 meta = NULL;
4818
Edward Creeb03c9f92017-08-07 15:26:36 +01004819 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004820 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004821 regno);
4822 return -EACCES;
4823 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004824
Edward Creeb03c9f92017-08-07 15:26:36 +01004825 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004826 err = check_helper_mem_access(env, regno - 1, 0,
4827 zero_size_allowed,
4828 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004829 if (err)
4830 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004831 }
Edward Creef1174f72017-08-07 15:26:19 +01004832
Edward Creeb03c9f92017-08-07 15:26:36 +01004833 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004834 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004835 regno);
4836 return -EACCES;
4837 }
4838 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004839 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004840 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004841 if (!err)
4842 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004843 } else if (arg_type_is_alloc_size(arg_type)) {
4844 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00004845 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004846 regno);
4847 return -EACCES;
4848 }
4849 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004850 } else if (arg_type_is_int_ptr(arg_type)) {
4851 int size = int_ptr_type_to_size(arg_type);
4852
4853 err = check_helper_mem_access(env, regno, size, false, meta);
4854 if (err)
4855 return err;
4856 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004857 }
4858
4859 return err;
4860}
4861
Lorenz Bauer01262402020-08-21 11:29:47 +01004862static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4863{
4864 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004865 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004866
4867 if (func_id != BPF_FUNC_map_update_elem)
4868 return false;
4869
4870 /* It's not possible to get access to a locked struct sock in these
4871 * contexts, so updating is safe.
4872 */
4873 switch (type) {
4874 case BPF_PROG_TYPE_TRACING:
4875 if (eatype == BPF_TRACE_ITER)
4876 return true;
4877 break;
4878 case BPF_PROG_TYPE_SOCKET_FILTER:
4879 case BPF_PROG_TYPE_SCHED_CLS:
4880 case BPF_PROG_TYPE_SCHED_ACT:
4881 case BPF_PROG_TYPE_XDP:
4882 case BPF_PROG_TYPE_SK_REUSEPORT:
4883 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4884 case BPF_PROG_TYPE_SK_LOOKUP:
4885 return true;
4886 default:
4887 break;
4888 }
4889
4890 verbose(env, "cannot update sockmap in this context\n");
4891 return false;
4892}
4893
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004894static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4895{
4896 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4897}
4898
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004899static int check_map_func_compatibility(struct bpf_verifier_env *env,
4900 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004901{
Kaixu Xia35578d72015-08-06 07:02:35 +00004902 if (!map)
4903 return 0;
4904
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004905 /* We need a two way check, first is from map perspective ... */
4906 switch (map->map_type) {
4907 case BPF_MAP_TYPE_PROG_ARRAY:
4908 if (func_id != BPF_FUNC_tail_call)
4909 goto error;
4910 break;
4911 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4912 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004913 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004914 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004915 func_id != BPF_FUNC_perf_event_read_value &&
4916 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004917 goto error;
4918 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004919 case BPF_MAP_TYPE_RINGBUF:
4920 if (func_id != BPF_FUNC_ringbuf_output &&
4921 func_id != BPF_FUNC_ringbuf_reserve &&
4922 func_id != BPF_FUNC_ringbuf_submit &&
4923 func_id != BPF_FUNC_ringbuf_discard &&
4924 func_id != BPF_FUNC_ringbuf_query)
4925 goto error;
4926 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004927 case BPF_MAP_TYPE_STACK_TRACE:
4928 if (func_id != BPF_FUNC_get_stackid)
4929 goto error;
4930 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004931 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004932 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004933 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004934 goto error;
4935 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004936 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004937 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004938 if (func_id != BPF_FUNC_get_local_storage)
4939 goto error;
4940 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004941 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004942 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004943 if (func_id != BPF_FUNC_redirect_map &&
4944 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004945 goto error;
4946 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004947 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4948 * appear.
4949 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004950 case BPF_MAP_TYPE_CPUMAP:
4951 if (func_id != BPF_FUNC_redirect_map)
4952 goto error;
4953 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004954 case BPF_MAP_TYPE_XSKMAP:
4955 if (func_id != BPF_FUNC_redirect_map &&
4956 func_id != BPF_FUNC_map_lookup_elem)
4957 goto error;
4958 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004959 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004960 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004961 if (func_id != BPF_FUNC_map_lookup_elem)
4962 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004963 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004964 case BPF_MAP_TYPE_SOCKMAP:
4965 if (func_id != BPF_FUNC_sk_redirect_map &&
4966 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004967 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004968 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004969 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004970 func_id != BPF_FUNC_map_lookup_elem &&
4971 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004972 goto error;
4973 break;
John Fastabend81110382018-05-14 10:00:17 -07004974 case BPF_MAP_TYPE_SOCKHASH:
4975 if (func_id != BPF_FUNC_sk_redirect_hash &&
4976 func_id != BPF_FUNC_sock_hash_update &&
4977 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004978 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004979 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004980 func_id != BPF_FUNC_map_lookup_elem &&
4981 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004982 goto error;
4983 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004984 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4985 if (func_id != BPF_FUNC_sk_select_reuseport)
4986 goto error;
4987 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004988 case BPF_MAP_TYPE_QUEUE:
4989 case BPF_MAP_TYPE_STACK:
4990 if (func_id != BPF_FUNC_map_peek_elem &&
4991 func_id != BPF_FUNC_map_pop_elem &&
4992 func_id != BPF_FUNC_map_push_elem)
4993 goto error;
4994 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004995 case BPF_MAP_TYPE_SK_STORAGE:
4996 if (func_id != BPF_FUNC_sk_storage_get &&
4997 func_id != BPF_FUNC_sk_storage_delete)
4998 goto error;
4999 break;
KP Singh8ea63682020-08-25 20:29:17 +02005000 case BPF_MAP_TYPE_INODE_STORAGE:
5001 if (func_id != BPF_FUNC_inode_storage_get &&
5002 func_id != BPF_FUNC_inode_storage_delete)
5003 goto error;
5004 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005005 case BPF_MAP_TYPE_TASK_STORAGE:
5006 if (func_id != BPF_FUNC_task_storage_get &&
5007 func_id != BPF_FUNC_task_storage_delete)
5008 goto error;
5009 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005010 default:
5011 break;
5012 }
5013
5014 /* ... and second from the function itself. */
5015 switch (func_id) {
5016 case BPF_FUNC_tail_call:
5017 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5018 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005019 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5020 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005021 return -EINVAL;
5022 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005023 break;
5024 case BPF_FUNC_perf_event_read:
5025 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07005026 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005027 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005028 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005029 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5030 goto error;
5031 break;
5032 case BPF_FUNC_get_stackid:
5033 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5034 goto error;
5035 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005036 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02005037 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005038 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5039 goto error;
5040 break;
John Fastabend97f91a72017-07-17 09:29:18 -07005041 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02005042 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005043 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005044 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5045 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07005046 goto error;
5047 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005048 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07005049 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07005050 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07005051 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5052 goto error;
5053 break;
John Fastabend81110382018-05-14 10:00:17 -07005054 case BPF_FUNC_sk_redirect_hash:
5055 case BPF_FUNC_msg_redirect_hash:
5056 case BPF_FUNC_sock_hash_update:
5057 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07005058 goto error;
5059 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005060 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00005061 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5062 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07005063 goto error;
5064 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005065 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005066 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5067 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5068 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005069 goto error;
5070 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005071 case BPF_FUNC_map_peek_elem:
5072 case BPF_FUNC_map_pop_elem:
5073 case BPF_FUNC_map_push_elem:
5074 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5075 map->map_type != BPF_MAP_TYPE_STACK)
5076 goto error;
5077 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005078 case BPF_FUNC_sk_storage_get:
5079 case BPF_FUNC_sk_storage_delete:
5080 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5081 goto error;
5082 break;
KP Singh8ea63682020-08-25 20:29:17 +02005083 case BPF_FUNC_inode_storage_get:
5084 case BPF_FUNC_inode_storage_delete:
5085 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5086 goto error;
5087 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005088 case BPF_FUNC_task_storage_get:
5089 case BPF_FUNC_task_storage_delete:
5090 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5091 goto error;
5092 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005093 default:
5094 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005095 }
5096
5097 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005098error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005099 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005100 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005101 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005102}
5103
Daniel Borkmann90133412018-01-20 01:24:29 +01005104static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005105{
5106 int count = 0;
5107
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005108 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005109 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005110 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005111 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005112 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005113 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005114 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005115 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005116 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005117 count++;
5118
Daniel Borkmann90133412018-01-20 01:24:29 +01005119 /* We only support one arg being in raw mode at the moment,
5120 * which is sufficient for the helper functions we have
5121 * right now.
5122 */
5123 return count <= 1;
5124}
5125
5126static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5127 enum bpf_arg_type arg_next)
5128{
5129 return (arg_type_is_mem_ptr(arg_curr) &&
5130 !arg_type_is_mem_size(arg_next)) ||
5131 (!arg_type_is_mem_ptr(arg_curr) &&
5132 arg_type_is_mem_size(arg_next));
5133}
5134
5135static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5136{
5137 /* bpf_xxx(..., buf, len) call will access 'len'
5138 * bytes from memory 'buf'. Both arg types need
5139 * to be paired, so make sure there's no buggy
5140 * helper function specification.
5141 */
5142 if (arg_type_is_mem_size(fn->arg1_type) ||
5143 arg_type_is_mem_ptr(fn->arg5_type) ||
5144 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5145 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5146 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5147 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5148 return false;
5149
5150 return true;
5151}
5152
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005153static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005154{
5155 int count = 0;
5156
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005157 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005158 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005159 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005160 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005161 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005162 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005163 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005164 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005165 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005166 count++;
5167
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005168 /* A reference acquiring function cannot acquire
5169 * another refcounted ptr.
5170 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005171 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005172 return false;
5173
Joe Stringerfd978bf72018-10-02 13:35:35 -07005174 /* We only support one arg being unreferenced at the moment,
5175 * which is sufficient for the helper functions we have right now.
5176 */
5177 return count <= 1;
5178}
5179
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005180static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5181{
5182 int i;
5183
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005184 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005185 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5186 return false;
5187
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005188 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5189 return false;
5190 }
5191
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005192 return true;
5193}
5194
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005195static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005196{
5197 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005198 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005199 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005200 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005201}
5202
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005203/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5204 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005205 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005206static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5207 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005208{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005209 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005210 int i;
5211
5212 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005213 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005214 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005215
Joe Stringerf3709f62018-10-02 13:35:29 -07005216 bpf_for_each_spilled_reg(i, state, reg) {
5217 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005218 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005219 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005220 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005221 }
5222}
5223
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005224static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5225{
5226 struct bpf_verifier_state *vstate = env->cur_state;
5227 int i;
5228
5229 for (i = 0; i <= vstate->curframe; i++)
5230 __clear_all_pkt_pointers(env, vstate->frame[i]);
5231}
5232
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005233enum {
5234 AT_PKT_END = -1,
5235 BEYOND_PKT_END = -2,
5236};
5237
5238static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5239{
5240 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5241 struct bpf_reg_state *reg = &state->regs[regn];
5242
5243 if (reg->type != PTR_TO_PACKET)
5244 /* PTR_TO_PACKET_META is not supported yet */
5245 return;
5246
5247 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5248 * How far beyond pkt_end it goes is unknown.
5249 * if (!range_open) it's the case of pkt >= pkt_end
5250 * if (range_open) it's the case of pkt > pkt_end
5251 * hence this pointer is at least 1 byte bigger than pkt_end
5252 */
5253 if (range_open)
5254 reg->range = BEYOND_PKT_END;
5255 else
5256 reg->range = AT_PKT_END;
5257}
5258
Joe Stringerfd978bf72018-10-02 13:35:35 -07005259static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005260 struct bpf_func_state *state,
5261 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005262{
5263 struct bpf_reg_state *regs = state->regs, *reg;
5264 int i;
5265
5266 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005267 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005268 mark_reg_unknown(env, regs, i);
5269
5270 bpf_for_each_spilled_reg(i, state, reg) {
5271 if (!reg)
5272 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005273 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005274 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005275 }
5276}
5277
5278/* The pointer with the specified id has released its reference to kernel
5279 * resources. Identify all copies of the same pointer and clear the reference.
5280 */
5281static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005282 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005283{
5284 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005285 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005286 int i;
5287
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005288 err = release_reference_state(cur_func(env), ref_obj_id);
5289 if (err)
5290 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005291
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005292 for (i = 0; i <= vstate->curframe; i++)
5293 release_reg_references(env, vstate->frame[i], ref_obj_id);
5294
5295 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005296}
5297
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005298static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5299 struct bpf_reg_state *regs)
5300{
5301 int i;
5302
5303 /* after the call registers r0 - r5 were scratched */
5304 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5305 mark_reg_not_init(env, regs, caller_saved[i]);
5306 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5307 }
5308}
5309
Yonghong Song14351372021-02-26 12:49:23 -08005310typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5311 struct bpf_func_state *caller,
5312 struct bpf_func_state *callee,
5313 int insn_idx);
5314
5315static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5316 int *insn_idx, int subprog,
5317 set_callee_state_fn set_callee_state_cb)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005318{
5319 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005320 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005321 struct bpf_func_state *caller, *callee;
Yonghong Song14351372021-02-26 12:49:23 -08005322 int err;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005323 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005324
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005325 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005326 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005327 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005328 return -E2BIG;
5329 }
5330
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005331 caller = state->frame[state->curframe];
5332 if (state->frame[state->curframe + 1]) {
5333 verbose(env, "verifier bug. Frame %d already allocated\n",
5334 state->curframe + 1);
5335 return -EFAULT;
5336 }
5337
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005338 func_info_aux = env->prog->aux->func_info_aux;
5339 if (func_info_aux)
5340 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5341 err = btf_check_func_arg_match(env, subprog, caller->regs);
5342 if (err == -EFAULT)
5343 return err;
5344 if (is_global) {
5345 if (err) {
5346 verbose(env, "Caller passes invalid args into func#%d\n",
5347 subprog);
5348 return err;
5349 } else {
5350 if (env->log.level & BPF_LOG_LEVEL)
5351 verbose(env,
5352 "Func#%d is global and valid. Skipping.\n",
5353 subprog);
5354 clear_caller_saved_regs(env, caller->regs);
5355
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005356 /* All global functions return a 64-bit SCALAR_VALUE */
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005357 mark_reg_unknown(env, caller->regs, BPF_REG_0);
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005358 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005359
5360 /* continue with next insn after call */
5361 return 0;
5362 }
5363 }
5364
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005365 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5366 if (!callee)
5367 return -ENOMEM;
5368 state->frame[state->curframe + 1] = callee;
5369
5370 /* callee cannot access r0, r6 - r9 for reading and has to write
5371 * into its own stack before reading from it.
5372 * callee can read/write into caller's stack
5373 */
5374 init_func_state(env, callee,
5375 /* remember the callsite, it will be used by bpf_exit */
5376 *insn_idx /* callsite */,
5377 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04005378 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005379
Joe Stringerfd978bf72018-10-02 13:35:35 -07005380 /* Transfer references to the callee */
5381 err = transfer_reference_state(callee, caller);
5382 if (err)
5383 return err;
5384
Yonghong Song14351372021-02-26 12:49:23 -08005385 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5386 if (err)
5387 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005388
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005389 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005390
5391 /* only increment it after check_reg_arg() finished */
5392 state->curframe++;
5393
5394 /* and go analyze first insn of the callee */
Yonghong Song14351372021-02-26 12:49:23 -08005395 *insn_idx = env->subprog_info[subprog].start - 1;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005396
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005397 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005398 verbose(env, "caller:\n");
5399 print_verifier_state(env, caller);
5400 verbose(env, "callee:\n");
5401 print_verifier_state(env, callee);
5402 }
5403 return 0;
5404}
5405
Yonghong Song14351372021-02-26 12:49:23 -08005406static int set_callee_state(struct bpf_verifier_env *env,
5407 struct bpf_func_state *caller,
5408 struct bpf_func_state *callee, int insn_idx)
5409{
5410 int i;
5411
5412 /* copy r1 - r5 args that callee can access. The copy includes parent
5413 * pointers, which connects us up to the liveness chain
5414 */
5415 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5416 callee->regs[i] = caller->regs[i];
5417 return 0;
5418}
5419
5420static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5421 int *insn_idx)
5422{
5423 int subprog, target_insn;
5424
5425 target_insn = *insn_idx + insn->imm + 1;
5426 subprog = find_subprog(env, target_insn);
5427 if (subprog < 0) {
5428 verbose(env, "verifier bug. No program starts at insn %d\n",
5429 target_insn);
5430 return -EFAULT;
5431 }
5432
5433 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5434}
5435
Yonghong Song69c087b2021-02-26 12:49:25 -08005436static int set_map_elem_callback_state(struct bpf_verifier_env *env,
5437 struct bpf_func_state *caller,
5438 struct bpf_func_state *callee,
5439 int insn_idx)
5440{
5441 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
5442 struct bpf_map *map;
5443 int err;
5444
5445 if (bpf_map_ptr_poisoned(insn_aux)) {
5446 verbose(env, "tail_call abusing map_ptr\n");
5447 return -EINVAL;
5448 }
5449
5450 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
5451 if (!map->ops->map_set_for_each_callback_args ||
5452 !map->ops->map_for_each_callback) {
5453 verbose(env, "callback function not allowed for map\n");
5454 return -ENOTSUPP;
5455 }
5456
5457 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
5458 if (err)
5459 return err;
5460
5461 callee->in_callback_fn = true;
5462 return 0;
5463}
5464
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005465static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5466{
5467 struct bpf_verifier_state *state = env->cur_state;
5468 struct bpf_func_state *caller, *callee;
5469 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005470 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005471
5472 callee = state->frame[state->curframe];
5473 r0 = &callee->regs[BPF_REG_0];
5474 if (r0->type == PTR_TO_STACK) {
5475 /* technically it's ok to return caller's stack pointer
5476 * (or caller's caller's pointer) back to the caller,
5477 * since these pointers are valid. Only current stack
5478 * pointer will be invalid as soon as function exits,
5479 * but let's be conservative
5480 */
5481 verbose(env, "cannot return stack pointer to the caller\n");
5482 return -EINVAL;
5483 }
5484
5485 state->curframe--;
5486 caller = state->frame[state->curframe];
Yonghong Song69c087b2021-02-26 12:49:25 -08005487 if (callee->in_callback_fn) {
5488 /* enforce R0 return value range [0, 1]. */
5489 struct tnum range = tnum_range(0, 1);
5490
5491 if (r0->type != SCALAR_VALUE) {
5492 verbose(env, "R0 not a scalar value\n");
5493 return -EACCES;
5494 }
5495 if (!tnum_in(range, r0->var_off)) {
5496 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
5497 return -EINVAL;
5498 }
5499 } else {
5500 /* return to the caller whatever r0 had in the callee */
5501 caller->regs[BPF_REG_0] = *r0;
5502 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005503
Joe Stringerfd978bf72018-10-02 13:35:35 -07005504 /* Transfer references to the caller */
5505 err = transfer_reference_state(caller, callee);
5506 if (err)
5507 return err;
5508
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005509 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005510 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005511 verbose(env, "returning from callee:\n");
5512 print_verifier_state(env, callee);
5513 verbose(env, "to caller at %d:\n", *insn_idx);
5514 print_verifier_state(env, caller);
5515 }
5516 /* clear everything in the callee */
5517 free_func_state(callee);
5518 state->frame[state->curframe + 1] = NULL;
5519 return 0;
5520}
5521
Yonghong Song849fa502018-04-28 22:28:09 -07005522static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5523 int func_id,
5524 struct bpf_call_arg_meta *meta)
5525{
5526 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5527
5528 if (ret_type != RET_INTEGER ||
5529 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02005530 func_id != BPF_FUNC_probe_read_str &&
5531 func_id != BPF_FUNC_probe_read_kernel_str &&
5532 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07005533 return;
5534
John Fastabend10060502020-03-30 14:36:19 -07005535 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07005536 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01005537 ret_reg->smin_value = -MAX_ERRNO;
5538 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07005539 __reg_deduce_bounds(ret_reg);
5540 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07005541 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07005542}
5543
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005544static int
5545record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5546 int func_id, int insn_idx)
5547{
5548 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02005549 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005550
5551 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02005552 func_id != BPF_FUNC_map_lookup_elem &&
5553 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005554 func_id != BPF_FUNC_map_delete_elem &&
5555 func_id != BPF_FUNC_map_push_elem &&
5556 func_id != BPF_FUNC_map_pop_elem &&
Yonghong Song69c087b2021-02-26 12:49:25 -08005557 func_id != BPF_FUNC_map_peek_elem &&
5558 func_id != BPF_FUNC_for_each_map_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005559 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02005560
Daniel Borkmann591fe982019-04-09 23:20:05 +02005561 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005562 verbose(env, "kernel subsystem misconfigured verifier\n");
5563 return -EINVAL;
5564 }
5565
Daniel Borkmann591fe982019-04-09 23:20:05 +02005566 /* In case of read-only, some additional restrictions
5567 * need to be applied in order to prevent altering the
5568 * state of the map from program side.
5569 */
5570 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5571 (func_id == BPF_FUNC_map_delete_elem ||
5572 func_id == BPF_FUNC_map_update_elem ||
5573 func_id == BPF_FUNC_map_push_elem ||
5574 func_id == BPF_FUNC_map_pop_elem)) {
5575 verbose(env, "write into map forbidden\n");
5576 return -EACCES;
5577 }
5578
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005579 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005580 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005581 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005582 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005583 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005584 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005585 return 0;
5586}
5587
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005588static int
5589record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5590 int func_id, int insn_idx)
5591{
5592 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5593 struct bpf_reg_state *regs = cur_regs(env), *reg;
5594 struct bpf_map *map = meta->map_ptr;
5595 struct tnum range;
5596 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005597 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005598
5599 if (func_id != BPF_FUNC_tail_call)
5600 return 0;
5601 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5602 verbose(env, "kernel subsystem misconfigured verifier\n");
5603 return -EINVAL;
5604 }
5605
5606 range = tnum_range(0, map->max_entries - 1);
5607 reg = &regs[BPF_REG_3];
5608
5609 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5610 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5611 return 0;
5612 }
5613
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005614 err = mark_chain_precision(env, BPF_REG_3);
5615 if (err)
5616 return err;
5617
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005618 val = reg->var_off.value;
5619 if (bpf_map_key_unseen(aux))
5620 bpf_map_key_store(aux, val);
5621 else if (!bpf_map_key_poisoned(aux) &&
5622 bpf_map_key_immediate(aux) != val)
5623 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5624 return 0;
5625}
5626
Joe Stringerfd978bf72018-10-02 13:35:35 -07005627static int check_reference_leak(struct bpf_verifier_env *env)
5628{
5629 struct bpf_func_state *state = cur_func(env);
5630 int i;
5631
5632 for (i = 0; i < state->acquired_refs; i++) {
5633 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5634 state->refs[i].id, state->refs[i].insn_idx);
5635 }
5636 return state->acquired_refs ? -EINVAL : 0;
5637}
5638
Yonghong Song69c087b2021-02-26 12:49:25 -08005639static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5640 int *insn_idx_p)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005641{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005642 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005643 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005644 struct bpf_call_arg_meta meta;
Yonghong Song69c087b2021-02-26 12:49:25 -08005645 int insn_idx = *insn_idx_p;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005646 bool changes_data;
Yonghong Song69c087b2021-02-26 12:49:25 -08005647 int i, err, func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005648
5649 /* find function prototype */
Yonghong Song69c087b2021-02-26 12:49:25 -08005650 func_id = insn->imm;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005651 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005652 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5653 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005654 return -EINVAL;
5655 }
5656
Jakub Kicinski00176a32017-10-16 16:40:54 -07005657 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07005658 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005659 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005660 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5661 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005662 return -EINVAL;
5663 }
5664
5665 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01005666 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02005667 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005668 return -EINVAL;
5669 }
5670
Jiri Olsaeae2e832020-08-25 21:21:19 +02005671 if (fn->allowed && !fn->allowed(env->prog)) {
5672 verbose(env, "helper call is not allowed in probe\n");
5673 return -EINVAL;
5674 }
5675
Daniel Borkmann04514d12017-12-14 21:07:25 +01005676 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08005677 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01005678 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5679 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5680 func_id_name(func_id), func_id);
5681 return -EINVAL;
5682 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005683
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005684 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02005685 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005686
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005687 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005688 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005689 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005690 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005691 return err;
5692 }
5693
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08005694 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005695 /* check args */
Dmitrii Banshchikov523a4cf2021-02-26 00:26:29 +04005696 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005697 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005698 if (err)
5699 return err;
5700 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005701
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005702 err = record_func_map(env, &meta, func_id, insn_idx);
5703 if (err)
5704 return err;
5705
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005706 err = record_func_key(env, &meta, func_id, insn_idx);
5707 if (err)
5708 return err;
5709
Daniel Borkmann435faee12016-04-13 00:10:51 +02005710 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5711 * is inferred from register state.
5712 */
5713 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01005714 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5715 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005716 if (err)
5717 return err;
5718 }
5719
Joe Stringerfd978bf72018-10-02 13:35:35 -07005720 if (func_id == BPF_FUNC_tail_call) {
5721 err = check_reference_leak(env);
5722 if (err) {
5723 verbose(env, "tail_call would lead to reference leak\n");
5724 return err;
5725 }
5726 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005727 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005728 if (err) {
5729 verbose(env, "func %s#%d reference has not been acquired before\n",
5730 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005731 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005732 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07005733 }
5734
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005735 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07005736
5737 /* check that flags argument in get_local_storage(map, flags) is 0,
5738 * this is required because get_local_storage() can't return an error.
5739 */
5740 if (func_id == BPF_FUNC_get_local_storage &&
5741 !register_is_null(&regs[BPF_REG_2])) {
5742 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5743 return -EINVAL;
5744 }
5745
Yonghong Song69c087b2021-02-26 12:49:25 -08005746 if (func_id == BPF_FUNC_for_each_map_elem) {
5747 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
5748 set_map_elem_callback_state);
5749 if (err < 0)
5750 return -EINVAL;
5751 }
5752
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005753 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01005754 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005755 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01005756 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5757 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005758
Jiong Wang5327ed32019-05-24 23:25:12 +01005759 /* helper call returns 64-bit value. */
5760 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5761
Edward Creedc503a82017-08-15 20:34:35 +01005762 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005763 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01005764 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005765 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005766 } else if (fn->ret_type == RET_VOID) {
5767 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07005768 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5769 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01005770 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005771 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005772 /* remember map_ptr, so that check_map_access()
5773 * can check 'value_size' boundary of memory access
5774 * to map element returned from bpf_map_lookup_elem()
5775 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005776 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005777 verbose(env,
5778 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005779 return -EINVAL;
5780 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005781 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005782 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5783 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08005784 if (map_value_has_spin_lock(meta.map_ptr))
5785 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005786 } else {
5787 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005788 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005789 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5790 mark_reg_known_zero(env, regs, BPF_REG_0);
5791 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08005792 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5793 mark_reg_known_zero(env, regs, BPF_REG_0);
5794 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005795 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5796 mark_reg_known_zero(env, regs, BPF_REG_0);
5797 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005798 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5799 mark_reg_known_zero(env, regs, BPF_REG_0);
5800 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005801 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07005802 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5803 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005804 const struct btf_type *t;
5805
5806 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005807 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005808 if (!btf_type_is_struct(t)) {
5809 u32 tsize;
5810 const struct btf_type *ret;
5811 const char *tname;
5812
5813 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005814 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005815 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005816 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005817 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5818 tname, PTR_ERR(ret));
5819 return -EINVAL;
5820 }
Hao Luo63d9b802020-09-29 16:50:48 -07005821 regs[BPF_REG_0].type =
5822 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5823 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005824 regs[BPF_REG_0].mem_size = tsize;
5825 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07005826 regs[BPF_REG_0].type =
5827 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5828 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005829 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005830 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5831 }
KP Singh3ca10322020-11-06 10:37:43 +00005832 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5833 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005834 int ret_btf_id;
5835
5836 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00005837 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5838 PTR_TO_BTF_ID :
5839 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005840 ret_btf_id = *fn->ret_btf_id;
5841 if (ret_btf_id == 0) {
5842 verbose(env, "invalid return type %d of func %s#%d\n",
5843 fn->ret_type, func_id_name(func_id), func_id);
5844 return -EINVAL;
5845 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005846 /* current BPF helper definitions are only coming from
5847 * built-in code with type IDs from vmlinux BTF
5848 */
5849 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005850 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005851 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005852 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005853 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005854 return -EINVAL;
5855 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005856
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07005857 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5858 regs[BPF_REG_0].id = ++env->id_gen;
5859
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005860 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005861 /* For release_reference() */
5862 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005863 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005864 int id = acquire_reference_state(env, insn_idx);
5865
5866 if (id < 0)
5867 return id;
5868 /* For mark_ptr_or_null_reg() */
5869 regs[BPF_REG_0].id = id;
5870 /* For release_reference() */
5871 regs[BPF_REG_0].ref_obj_id = id;
5872 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005873
Yonghong Song849fa502018-04-28 22:28:09 -07005874 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5875
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005876 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005877 if (err)
5878 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005879
Song Liufa28dcb2020-06-29 23:28:44 -07005880 if ((func_id == BPF_FUNC_get_stack ||
5881 func_id == BPF_FUNC_get_task_stack) &&
5882 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005883 const char *err_str;
5884
5885#ifdef CONFIG_PERF_EVENTS
5886 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5887 err_str = "cannot get callchain buffer for func %s#%d\n";
5888#else
5889 err = -ENOTSUPP;
5890 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5891#endif
5892 if (err) {
5893 verbose(env, err_str, func_id_name(func_id), func_id);
5894 return err;
5895 }
5896
5897 env->prog->has_callchain_buf = true;
5898 }
5899
Song Liu5d99cb2c2020-07-23 11:06:45 -07005900 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5901 env->prog->call_get_stack = true;
5902
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005903 if (changes_data)
5904 clear_all_pkt_pointers(env);
5905 return 0;
5906}
5907
Edward Creeb03c9f92017-08-07 15:26:36 +01005908static bool signed_add_overflows(s64 a, s64 b)
5909{
5910 /* Do the add in u64, where overflow is well-defined */
5911 s64 res = (s64)((u64)a + (u64)b);
5912
5913 if (b < 0)
5914 return res > a;
5915 return res < a;
5916}
5917
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005918static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07005919{
5920 /* Do the add in u32, where overflow is well-defined */
5921 s32 res = (s32)((u32)a + (u32)b);
5922
5923 if (b < 0)
5924 return res > a;
5925 return res < a;
5926}
5927
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005928static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005929{
5930 /* Do the sub in u64, where overflow is well-defined */
5931 s64 res = (s64)((u64)a - (u64)b);
5932
5933 if (b < 0)
5934 return res < a;
5935 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005936}
5937
John Fastabend3f50f132020-03-30 14:36:39 -07005938static bool signed_sub32_overflows(s32 a, s32 b)
5939{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005940 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07005941 s32 res = (s32)((u32)a - (u32)b);
5942
5943 if (b < 0)
5944 return res < a;
5945 return res > a;
5946}
5947
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005948static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5949 const struct bpf_reg_state *reg,
5950 enum bpf_reg_type type)
5951{
5952 bool known = tnum_is_const(reg->var_off);
5953 s64 val = reg->var_off.value;
5954 s64 smin = reg->smin_value;
5955
5956 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5957 verbose(env, "math between %s pointer and %lld is not allowed\n",
5958 reg_type_str[type], val);
5959 return false;
5960 }
5961
5962 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5963 verbose(env, "%s pointer offset %d is not allowed\n",
5964 reg_type_str[type], reg->off);
5965 return false;
5966 }
5967
5968 if (smin == S64_MIN) {
5969 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5970 reg_type_str[type]);
5971 return false;
5972 }
5973
5974 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5975 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5976 smin, reg_type_str[type]);
5977 return false;
5978 }
5979
5980 return true;
5981}
5982
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005983static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5984{
5985 return &env->insn_aux_data[env->insn_idx];
5986}
5987
5988static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5989 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5990{
5991 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5992 (opcode == BPF_SUB && !off_is_neg);
5993 u32 off;
5994
5995 switch (ptr_reg->type) {
5996 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005997 /* Indirect variable offset stack access is prohibited in
5998 * unprivileged mode so it's not handled here.
5999 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006000 off = ptr_reg->off + ptr_reg->var_off.value;
6001 if (mask_to_left)
6002 *ptr_limit = MAX_BPF_STACK + off;
6003 else
6004 *ptr_limit = -off;
6005 return 0;
Yonghong Song69c087b2021-02-26 12:49:25 -08006006 case PTR_TO_MAP_KEY:
6007 /* Currently, this code is not exercised as the only use
6008 * is bpf_for_each_map_elem() helper which requires
6009 * bpf_capble. The code has been tested manually for
6010 * future use.
6011 */
6012 if (mask_to_left) {
6013 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6014 } else {
6015 off = ptr_reg->smin_value + ptr_reg->off;
6016 *ptr_limit = ptr_reg->map_ptr->key_size - off;
6017 }
6018 return 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006019 case PTR_TO_MAP_VALUE:
6020 if (mask_to_left) {
6021 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
6022 } else {
6023 off = ptr_reg->smin_value + ptr_reg->off;
6024 *ptr_limit = ptr_reg->map_ptr->value_size - off;
6025 }
6026 return 0;
6027 default:
6028 return -EINVAL;
6029 }
6030}
6031
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006032static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
6033 const struct bpf_insn *insn)
6034{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006035 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006036}
6037
6038static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
6039 u32 alu_state, u32 alu_limit)
6040{
6041 /* If we arrived here from different branches with different
6042 * state or limits to sanitize, then this won't work.
6043 */
6044 if (aux->alu_state &&
6045 (aux->alu_state != alu_state ||
6046 aux->alu_limit != alu_limit))
6047 return -EACCES;
6048
Brendan Jackmane6ac5932021-02-17 10:45:09 +00006049 /* Corresponding fixup done in do_misc_fixups(). */
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006050 aux->alu_state = alu_state;
6051 aux->alu_limit = alu_limit;
6052 return 0;
6053}
6054
6055static int sanitize_val_alu(struct bpf_verifier_env *env,
6056 struct bpf_insn *insn)
6057{
6058 struct bpf_insn_aux_data *aux = cur_aux(env);
6059
6060 if (can_skip_alu_sanitation(env, insn))
6061 return 0;
6062
6063 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
6064}
6065
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006066static int sanitize_ptr_alu(struct bpf_verifier_env *env,
6067 struct bpf_insn *insn,
6068 const struct bpf_reg_state *ptr_reg,
6069 struct bpf_reg_state *dst_reg,
6070 bool off_is_neg)
6071{
6072 struct bpf_verifier_state *vstate = env->cur_state;
6073 struct bpf_insn_aux_data *aux = cur_aux(env);
6074 bool ptr_is_dst_reg = ptr_reg == dst_reg;
6075 u8 opcode = BPF_OP(insn->code);
6076 u32 alu_state, alu_limit;
6077 struct bpf_reg_state tmp;
6078 bool ret;
6079
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006080 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006081 return 0;
6082
6083 /* We already marked aux for masking from non-speculative
6084 * paths, thus we got here in the first place. We only care
6085 * to explore bad access from here.
6086 */
6087 if (vstate->speculative)
6088 goto do_sim;
6089
6090 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
6091 alu_state |= ptr_is_dst_reg ?
6092 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
6093
6094 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
6095 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006096 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006097 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006098do_sim:
6099 /* Simulate and find potential out-of-bounds access under
6100 * speculative execution from truncation as a result of
6101 * masking when off was not within expected range. If off
6102 * sits in dst, then we temporarily need to move ptr there
6103 * to simulate dst (== 0) +/-= ptr. Needed, for example,
6104 * for cases where we use K-based arithmetic in one direction
6105 * and truncated reg-based in the other in order to explore
6106 * bad access.
6107 */
6108 if (!ptr_is_dst_reg) {
6109 tmp = *dst_reg;
6110 *dst_reg = *ptr_reg;
6111 }
6112 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08006113 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006114 *dst_reg = tmp;
6115 return !ret ? -EFAULT : 0;
6116}
6117
Andrei Matei01f810a2021-02-06 20:10:24 -05006118/* check that stack access falls within stack limits and that 'reg' doesn't
6119 * have a variable offset.
6120 *
6121 * Variable offset is prohibited for unprivileged mode for simplicity since it
6122 * requires corresponding support in Spectre masking for stack ALU. See also
6123 * retrieve_ptr_limit().
6124 *
6125 *
6126 * 'off' includes 'reg->off'.
6127 */
6128static int check_stack_access_for_ptr_arithmetic(
6129 struct bpf_verifier_env *env,
6130 int regno,
6131 const struct bpf_reg_state *reg,
6132 int off)
6133{
6134 if (!tnum_is_const(reg->var_off)) {
6135 char tn_buf[48];
6136
6137 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6138 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6139 regno, tn_buf, off);
6140 return -EACCES;
6141 }
6142
6143 if (off >= 0 || off < -MAX_BPF_STACK) {
6144 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6145 "prohibited for !root; off=%d\n", regno, off);
6146 return -EACCES;
6147 }
6148
6149 return 0;
6150}
6151
6152
Edward Creef1174f72017-08-07 15:26:19 +01006153/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01006154 * Caller should also handle BPF_MOV case separately.
6155 * If we return -EACCES, caller may want to try again treating pointer as a
6156 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6157 */
6158static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6159 struct bpf_insn *insn,
6160 const struct bpf_reg_state *ptr_reg,
6161 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04006162{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006163 struct bpf_verifier_state *vstate = env->cur_state;
6164 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6165 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006166 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01006167 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6168 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6169 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6170 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006171 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04006172 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006173 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04006174
Edward Creef1174f72017-08-07 15:26:19 +01006175 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04006176
Daniel Borkmann6f161012018-01-18 01:15:21 +01006177 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6178 smin_val > smax_val || umin_val > umax_val) {
6179 /* Taint dst register if offset had invalid bounds derived from
6180 * e.g. dead branches.
6181 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006182 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01006183 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04006184 }
6185
Edward Creef1174f72017-08-07 15:26:19 +01006186 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6187 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07006188 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6189 __mark_reg_unknown(env, dst_reg);
6190 return 0;
6191 }
6192
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006193 verbose(env,
6194 "R%d 32-bit pointer arithmetic prohibited\n",
6195 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006196 return -EACCES;
6197 }
David S. Millerd1174412017-05-10 11:22:52 -07006198
Joe Stringeraad2eea2018-10-02 13:35:30 -07006199 switch (ptr_reg->type) {
6200 case PTR_TO_MAP_VALUE_OR_NULL:
6201 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6202 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006203 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006204 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07006205 /* smin_val represents the known value */
6206 if (known && smin_val == 0 && opcode == BPF_ADD)
6207 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05006208 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006209 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07006210 case PTR_TO_SOCKET:
6211 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006212 case PTR_TO_SOCK_COMMON:
6213 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006214 case PTR_TO_TCP_SOCK:
6215 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07006216 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07006217 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6218 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006219 return -EACCES;
Yonghong Song69c087b2021-02-26 12:49:25 -08006220 case PTR_TO_MAP_KEY:
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006221 case PTR_TO_MAP_VALUE:
6222 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6223 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6224 off_reg == dst_reg ? dst : src);
6225 return -EACCES;
6226 }
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05006227 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006228 default:
6229 break;
Edward Creef1174f72017-08-07 15:26:19 +01006230 }
6231
6232 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6233 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04006234 */
Edward Creef1174f72017-08-07 15:26:19 +01006235 dst_reg->type = ptr_reg->type;
6236 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05006237
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006238 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6239 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6240 return -EINVAL;
6241
John Fastabend3f50f132020-03-30 14:36:39 -07006242 /* pointer types do not carry 32-bit bounds at the moment. */
6243 __mark_reg32_unbounded(dst_reg);
6244
Josef Bacik48461132016-09-28 10:54:32 -04006245 switch (opcode) {
6246 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006247 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6248 if (ret < 0) {
6249 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6250 return ret;
6251 }
Edward Creef1174f72017-08-07 15:26:19 +01006252 /* We can take a fixed offset as long as it doesn't overflow
6253 * the s32 'off' field
6254 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006255 if (known && (ptr_reg->off + smin_val ==
6256 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006257 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006258 dst_reg->smin_value = smin_ptr;
6259 dst_reg->smax_value = smax_ptr;
6260 dst_reg->umin_value = umin_ptr;
6261 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006262 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01006263 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006264 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006265 break;
6266 }
Edward Creef1174f72017-08-07 15:26:19 +01006267 /* A new variable offset is created. Note that off_reg->off
6268 * == 0, since it's a scalar.
6269 * dst_reg gets the pointer type and since some positive
6270 * integer value was added to the pointer, give it a new 'id'
6271 * if it's a PTR_TO_PACKET.
6272 * this creates a new 'base' pointer, off_reg (variable) gets
6273 * added into the variable offset, and we copy the fixed offset
6274 * from ptr_reg.
6275 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006276 if (signed_add_overflows(smin_ptr, smin_val) ||
6277 signed_add_overflows(smax_ptr, smax_val)) {
6278 dst_reg->smin_value = S64_MIN;
6279 dst_reg->smax_value = S64_MAX;
6280 } else {
6281 dst_reg->smin_value = smin_ptr + smin_val;
6282 dst_reg->smax_value = smax_ptr + smax_val;
6283 }
6284 if (umin_ptr + umin_val < umin_ptr ||
6285 umax_ptr + umax_val < umax_ptr) {
6286 dst_reg->umin_value = 0;
6287 dst_reg->umax_value = U64_MAX;
6288 } else {
6289 dst_reg->umin_value = umin_ptr + umin_val;
6290 dst_reg->umax_value = umax_ptr + umax_val;
6291 }
Edward Creef1174f72017-08-07 15:26:19 +01006292 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6293 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006294 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006295 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006296 dst_reg->id = ++env->id_gen;
6297 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006298 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006299 }
Josef Bacik48461132016-09-28 10:54:32 -04006300 break;
6301 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006302 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6303 if (ret < 0) {
6304 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6305 return ret;
6306 }
Edward Creef1174f72017-08-07 15:26:19 +01006307 if (dst_reg == off_reg) {
6308 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006309 verbose(env, "R%d tried to subtract pointer from scalar\n",
6310 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006311 return -EACCES;
6312 }
6313 /* We don't allow subtraction from FP, because (according to
6314 * test_verifier.c test "invalid fp arithmetic", JITs might not
6315 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01006316 */
Edward Creef1174f72017-08-07 15:26:19 +01006317 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006318 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6319 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006320 return -EACCES;
6321 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006322 if (known && (ptr_reg->off - smin_val ==
6323 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006324 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006325 dst_reg->smin_value = smin_ptr;
6326 dst_reg->smax_value = smax_ptr;
6327 dst_reg->umin_value = umin_ptr;
6328 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006329 dst_reg->var_off = ptr_reg->var_off;
6330 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01006331 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006332 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006333 break;
6334 }
Edward Creef1174f72017-08-07 15:26:19 +01006335 /* A new variable offset is created. If the subtrahend is known
6336 * nonnegative, then any reg->range we had before is still good.
6337 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006338 if (signed_sub_overflows(smin_ptr, smax_val) ||
6339 signed_sub_overflows(smax_ptr, smin_val)) {
6340 /* Overflow possible, we know nothing */
6341 dst_reg->smin_value = S64_MIN;
6342 dst_reg->smax_value = S64_MAX;
6343 } else {
6344 dst_reg->smin_value = smin_ptr - smax_val;
6345 dst_reg->smax_value = smax_ptr - smin_val;
6346 }
6347 if (umin_ptr < umax_val) {
6348 /* Overflow possible, we know nothing */
6349 dst_reg->umin_value = 0;
6350 dst_reg->umax_value = U64_MAX;
6351 } else {
6352 /* Cannot overflow (as long as bounds are consistent) */
6353 dst_reg->umin_value = umin_ptr - umax_val;
6354 dst_reg->umax_value = umax_ptr - umin_val;
6355 }
Edward Creef1174f72017-08-07 15:26:19 +01006356 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6357 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006358 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006359 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006360 dst_reg->id = ++env->id_gen;
6361 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01006362 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006363 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006364 }
6365 break;
6366 case BPF_AND:
6367 case BPF_OR:
6368 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006369 /* bitwise ops on pointers are troublesome, prohibit. */
6370 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6371 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006372 return -EACCES;
6373 default:
6374 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006375 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6376 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006377 return -EACCES;
6378 }
6379
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006380 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6381 return -EINVAL;
6382
Edward Creeb03c9f92017-08-07 15:26:36 +01006383 __update_reg_bounds(dst_reg);
6384 __reg_deduce_bounds(dst_reg);
6385 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006386
6387 /* For unprivileged we require that resulting offset must be in bounds
6388 * in order to be able to sanitize access later on.
6389 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006390 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006391 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6392 check_map_access(env, dst, dst_reg->off, 1, false)) {
6393 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6394 "prohibited for !root\n", dst);
6395 return -EACCES;
6396 } else if (dst_reg->type == PTR_TO_STACK &&
Andrei Matei01f810a2021-02-06 20:10:24 -05006397 check_stack_access_for_ptr_arithmetic(
6398 env, dst, dst_reg, dst_reg->off +
6399 dst_reg->var_off.value)) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006400 return -EACCES;
6401 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006402 }
6403
Edward Creef1174f72017-08-07 15:26:19 +01006404 return 0;
6405}
6406
John Fastabend3f50f132020-03-30 14:36:39 -07006407static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6408 struct bpf_reg_state *src_reg)
6409{
6410 s32 smin_val = src_reg->s32_min_value;
6411 s32 smax_val = src_reg->s32_max_value;
6412 u32 umin_val = src_reg->u32_min_value;
6413 u32 umax_val = src_reg->u32_max_value;
6414
6415 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6416 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6417 dst_reg->s32_min_value = S32_MIN;
6418 dst_reg->s32_max_value = S32_MAX;
6419 } else {
6420 dst_reg->s32_min_value += smin_val;
6421 dst_reg->s32_max_value += smax_val;
6422 }
6423 if (dst_reg->u32_min_value + umin_val < umin_val ||
6424 dst_reg->u32_max_value + umax_val < umax_val) {
6425 dst_reg->u32_min_value = 0;
6426 dst_reg->u32_max_value = U32_MAX;
6427 } else {
6428 dst_reg->u32_min_value += umin_val;
6429 dst_reg->u32_max_value += umax_val;
6430 }
6431}
6432
John Fastabend07cd2632020-03-24 10:38:15 -07006433static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6434 struct bpf_reg_state *src_reg)
6435{
6436 s64 smin_val = src_reg->smin_value;
6437 s64 smax_val = src_reg->smax_value;
6438 u64 umin_val = src_reg->umin_value;
6439 u64 umax_val = src_reg->umax_value;
6440
6441 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6442 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6443 dst_reg->smin_value = S64_MIN;
6444 dst_reg->smax_value = S64_MAX;
6445 } else {
6446 dst_reg->smin_value += smin_val;
6447 dst_reg->smax_value += smax_val;
6448 }
6449 if (dst_reg->umin_value + umin_val < umin_val ||
6450 dst_reg->umax_value + umax_val < umax_val) {
6451 dst_reg->umin_value = 0;
6452 dst_reg->umax_value = U64_MAX;
6453 } else {
6454 dst_reg->umin_value += umin_val;
6455 dst_reg->umax_value += umax_val;
6456 }
John Fastabend3f50f132020-03-30 14:36:39 -07006457}
6458
6459static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6460 struct bpf_reg_state *src_reg)
6461{
6462 s32 smin_val = src_reg->s32_min_value;
6463 s32 smax_val = src_reg->s32_max_value;
6464 u32 umin_val = src_reg->u32_min_value;
6465 u32 umax_val = src_reg->u32_max_value;
6466
6467 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6468 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6469 /* Overflow possible, we know nothing */
6470 dst_reg->s32_min_value = S32_MIN;
6471 dst_reg->s32_max_value = S32_MAX;
6472 } else {
6473 dst_reg->s32_min_value -= smax_val;
6474 dst_reg->s32_max_value -= smin_val;
6475 }
6476 if (dst_reg->u32_min_value < umax_val) {
6477 /* Overflow possible, we know nothing */
6478 dst_reg->u32_min_value = 0;
6479 dst_reg->u32_max_value = U32_MAX;
6480 } else {
6481 /* Cannot overflow (as long as bounds are consistent) */
6482 dst_reg->u32_min_value -= umax_val;
6483 dst_reg->u32_max_value -= umin_val;
6484 }
John Fastabend07cd2632020-03-24 10:38:15 -07006485}
6486
6487static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6488 struct bpf_reg_state *src_reg)
6489{
6490 s64 smin_val = src_reg->smin_value;
6491 s64 smax_val = src_reg->smax_value;
6492 u64 umin_val = src_reg->umin_value;
6493 u64 umax_val = src_reg->umax_value;
6494
6495 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6496 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6497 /* Overflow possible, we know nothing */
6498 dst_reg->smin_value = S64_MIN;
6499 dst_reg->smax_value = S64_MAX;
6500 } else {
6501 dst_reg->smin_value -= smax_val;
6502 dst_reg->smax_value -= smin_val;
6503 }
6504 if (dst_reg->umin_value < umax_val) {
6505 /* Overflow possible, we know nothing */
6506 dst_reg->umin_value = 0;
6507 dst_reg->umax_value = U64_MAX;
6508 } else {
6509 /* Cannot overflow (as long as bounds are consistent) */
6510 dst_reg->umin_value -= umax_val;
6511 dst_reg->umax_value -= umin_val;
6512 }
John Fastabend3f50f132020-03-30 14:36:39 -07006513}
6514
6515static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6516 struct bpf_reg_state *src_reg)
6517{
6518 s32 smin_val = src_reg->s32_min_value;
6519 u32 umin_val = src_reg->u32_min_value;
6520 u32 umax_val = src_reg->u32_max_value;
6521
6522 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6523 /* Ain't nobody got time to multiply that sign */
6524 __mark_reg32_unbounded(dst_reg);
6525 return;
6526 }
6527 /* Both values are positive, so we can work with unsigned and
6528 * copy the result to signed (unless it exceeds S32_MAX).
6529 */
6530 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6531 /* Potential overflow, we know nothing */
6532 __mark_reg32_unbounded(dst_reg);
6533 return;
6534 }
6535 dst_reg->u32_min_value *= umin_val;
6536 dst_reg->u32_max_value *= umax_val;
6537 if (dst_reg->u32_max_value > S32_MAX) {
6538 /* Overflow possible, we know nothing */
6539 dst_reg->s32_min_value = S32_MIN;
6540 dst_reg->s32_max_value = S32_MAX;
6541 } else {
6542 dst_reg->s32_min_value = dst_reg->u32_min_value;
6543 dst_reg->s32_max_value = dst_reg->u32_max_value;
6544 }
John Fastabend07cd2632020-03-24 10:38:15 -07006545}
6546
6547static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6548 struct bpf_reg_state *src_reg)
6549{
6550 s64 smin_val = src_reg->smin_value;
6551 u64 umin_val = src_reg->umin_value;
6552 u64 umax_val = src_reg->umax_value;
6553
John Fastabend07cd2632020-03-24 10:38:15 -07006554 if (smin_val < 0 || dst_reg->smin_value < 0) {
6555 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07006556 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006557 return;
6558 }
6559 /* Both values are positive, so we can work with unsigned and
6560 * copy the result to signed (unless it exceeds S64_MAX).
6561 */
6562 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6563 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07006564 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006565 return;
6566 }
6567 dst_reg->umin_value *= umin_val;
6568 dst_reg->umax_value *= umax_val;
6569 if (dst_reg->umax_value > S64_MAX) {
6570 /* Overflow possible, we know nothing */
6571 dst_reg->smin_value = S64_MIN;
6572 dst_reg->smax_value = S64_MAX;
6573 } else {
6574 dst_reg->smin_value = dst_reg->umin_value;
6575 dst_reg->smax_value = dst_reg->umax_value;
6576 }
6577}
6578
John Fastabend3f50f132020-03-30 14:36:39 -07006579static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6580 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006581{
John Fastabend3f50f132020-03-30 14:36:39 -07006582 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6583 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6584 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6585 s32 smin_val = src_reg->s32_min_value;
6586 u32 umax_val = src_reg->u32_max_value;
6587
6588 /* Assuming scalar64_min_max_and will be called so its safe
6589 * to skip updating register for known 32-bit case.
6590 */
6591 if (src_known && dst_known)
6592 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006593
6594 /* We get our minimum from the var_off, since that's inherently
6595 * bitwise. Our maximum is the minimum of the operands' maxima.
6596 */
John Fastabend3f50f132020-03-30 14:36:39 -07006597 dst_reg->u32_min_value = var32_off.value;
6598 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6599 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6600 /* Lose signed bounds when ANDing negative numbers,
6601 * ain't nobody got time for that.
6602 */
6603 dst_reg->s32_min_value = S32_MIN;
6604 dst_reg->s32_max_value = S32_MAX;
6605 } else {
6606 /* ANDing two positives gives a positive, so safe to
6607 * cast result into s64.
6608 */
6609 dst_reg->s32_min_value = dst_reg->u32_min_value;
6610 dst_reg->s32_max_value = dst_reg->u32_max_value;
6611 }
6612
6613}
6614
6615static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6616 struct bpf_reg_state *src_reg)
6617{
6618 bool src_known = tnum_is_const(src_reg->var_off);
6619 bool dst_known = tnum_is_const(dst_reg->var_off);
6620 s64 smin_val = src_reg->smin_value;
6621 u64 umax_val = src_reg->umax_value;
6622
6623 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006624 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006625 return;
6626 }
6627
6628 /* We get our minimum from the var_off, since that's inherently
6629 * bitwise. Our maximum is the minimum of the operands' maxima.
6630 */
John Fastabend07cd2632020-03-24 10:38:15 -07006631 dst_reg->umin_value = dst_reg->var_off.value;
6632 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6633 if (dst_reg->smin_value < 0 || smin_val < 0) {
6634 /* Lose signed bounds when ANDing negative numbers,
6635 * ain't nobody got time for that.
6636 */
6637 dst_reg->smin_value = S64_MIN;
6638 dst_reg->smax_value = S64_MAX;
6639 } else {
6640 /* ANDing two positives gives a positive, so safe to
6641 * cast result into s64.
6642 */
6643 dst_reg->smin_value = dst_reg->umin_value;
6644 dst_reg->smax_value = dst_reg->umax_value;
6645 }
6646 /* We may learn something more from the var_off */
6647 __update_reg_bounds(dst_reg);
6648}
6649
John Fastabend3f50f132020-03-30 14:36:39 -07006650static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6651 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006652{
John Fastabend3f50f132020-03-30 14:36:39 -07006653 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6654 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6655 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006656 s32 smin_val = src_reg->s32_min_value;
6657 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006658
6659 /* Assuming scalar64_min_max_or will be called so it is safe
6660 * to skip updating register for known case.
6661 */
6662 if (src_known && dst_known)
6663 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006664
6665 /* We get our maximum from the var_off, and our minimum is the
6666 * maximum of the operands' minima
6667 */
John Fastabend3f50f132020-03-30 14:36:39 -07006668 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6669 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6670 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6671 /* Lose signed bounds when ORing negative numbers,
6672 * ain't nobody got time for that.
6673 */
6674 dst_reg->s32_min_value = S32_MIN;
6675 dst_reg->s32_max_value = S32_MAX;
6676 } else {
6677 /* ORing two positives gives a positive, so safe to
6678 * cast result into s64.
6679 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006680 dst_reg->s32_min_value = dst_reg->u32_min_value;
6681 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006682 }
6683}
6684
6685static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6686 struct bpf_reg_state *src_reg)
6687{
6688 bool src_known = tnum_is_const(src_reg->var_off);
6689 bool dst_known = tnum_is_const(dst_reg->var_off);
6690 s64 smin_val = src_reg->smin_value;
6691 u64 umin_val = src_reg->umin_value;
6692
6693 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006694 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006695 return;
6696 }
6697
6698 /* We get our maximum from the var_off, and our minimum is the
6699 * maximum of the operands' minima
6700 */
John Fastabend07cd2632020-03-24 10:38:15 -07006701 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6702 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6703 if (dst_reg->smin_value < 0 || smin_val < 0) {
6704 /* Lose signed bounds when ORing negative numbers,
6705 * ain't nobody got time for that.
6706 */
6707 dst_reg->smin_value = S64_MIN;
6708 dst_reg->smax_value = S64_MAX;
6709 } else {
6710 /* ORing two positives gives a positive, so safe to
6711 * cast result into s64.
6712 */
6713 dst_reg->smin_value = dst_reg->umin_value;
6714 dst_reg->smax_value = dst_reg->umax_value;
6715 }
6716 /* We may learn something more from the var_off */
6717 __update_reg_bounds(dst_reg);
6718}
6719
Yonghong Song2921c902020-08-24 23:46:08 -07006720static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6721 struct bpf_reg_state *src_reg)
6722{
6723 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6724 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6725 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6726 s32 smin_val = src_reg->s32_min_value;
6727
6728 /* Assuming scalar64_min_max_xor will be called so it is safe
6729 * to skip updating register for known case.
6730 */
6731 if (src_known && dst_known)
6732 return;
6733
6734 /* We get both minimum and maximum from the var32_off. */
6735 dst_reg->u32_min_value = var32_off.value;
6736 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6737
6738 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6739 /* XORing two positive sign numbers gives a positive,
6740 * so safe to cast u32 result into s32.
6741 */
6742 dst_reg->s32_min_value = dst_reg->u32_min_value;
6743 dst_reg->s32_max_value = dst_reg->u32_max_value;
6744 } else {
6745 dst_reg->s32_min_value = S32_MIN;
6746 dst_reg->s32_max_value = S32_MAX;
6747 }
6748}
6749
6750static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6751 struct bpf_reg_state *src_reg)
6752{
6753 bool src_known = tnum_is_const(src_reg->var_off);
6754 bool dst_known = tnum_is_const(dst_reg->var_off);
6755 s64 smin_val = src_reg->smin_value;
6756
6757 if (src_known && dst_known) {
6758 /* dst_reg->var_off.value has been updated earlier */
6759 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6760 return;
6761 }
6762
6763 /* We get both minimum and maximum from the var_off. */
6764 dst_reg->umin_value = dst_reg->var_off.value;
6765 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6766
6767 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6768 /* XORing two positive sign numbers gives a positive,
6769 * so safe to cast u64 result into s64.
6770 */
6771 dst_reg->smin_value = dst_reg->umin_value;
6772 dst_reg->smax_value = dst_reg->umax_value;
6773 } else {
6774 dst_reg->smin_value = S64_MIN;
6775 dst_reg->smax_value = S64_MAX;
6776 }
6777
6778 __update_reg_bounds(dst_reg);
6779}
6780
John Fastabend3f50f132020-03-30 14:36:39 -07006781static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6782 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07006783{
John Fastabend07cd2632020-03-24 10:38:15 -07006784 /* We lose all sign bit information (except what we can pick
6785 * up from var_off)
6786 */
John Fastabend3f50f132020-03-30 14:36:39 -07006787 dst_reg->s32_min_value = S32_MIN;
6788 dst_reg->s32_max_value = S32_MAX;
6789 /* If we might shift our top bit out, then we know nothing */
6790 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6791 dst_reg->u32_min_value = 0;
6792 dst_reg->u32_max_value = U32_MAX;
6793 } else {
6794 dst_reg->u32_min_value <<= umin_val;
6795 dst_reg->u32_max_value <<= umax_val;
6796 }
6797}
6798
6799static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6800 struct bpf_reg_state *src_reg)
6801{
6802 u32 umax_val = src_reg->u32_max_value;
6803 u32 umin_val = src_reg->u32_min_value;
6804 /* u32 alu operation will zext upper bits */
6805 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6806
6807 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6808 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6809 /* Not required but being careful mark reg64 bounds as unknown so
6810 * that we are forced to pick them up from tnum and zext later and
6811 * if some path skips this step we are still safe.
6812 */
6813 __mark_reg64_unbounded(dst_reg);
6814 __update_reg32_bounds(dst_reg);
6815}
6816
6817static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6818 u64 umin_val, u64 umax_val)
6819{
6820 /* Special case <<32 because it is a common compiler pattern to sign
6821 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6822 * positive we know this shift will also be positive so we can track
6823 * bounds correctly. Otherwise we lose all sign bit information except
6824 * what we can pick up from var_off. Perhaps we can generalize this
6825 * later to shifts of any length.
6826 */
6827 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6828 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6829 else
6830 dst_reg->smax_value = S64_MAX;
6831
6832 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6833 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6834 else
6835 dst_reg->smin_value = S64_MIN;
6836
John Fastabend07cd2632020-03-24 10:38:15 -07006837 /* If we might shift our top bit out, then we know nothing */
6838 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6839 dst_reg->umin_value = 0;
6840 dst_reg->umax_value = U64_MAX;
6841 } else {
6842 dst_reg->umin_value <<= umin_val;
6843 dst_reg->umax_value <<= umax_val;
6844 }
John Fastabend3f50f132020-03-30 14:36:39 -07006845}
6846
6847static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6848 struct bpf_reg_state *src_reg)
6849{
6850 u64 umax_val = src_reg->umax_value;
6851 u64 umin_val = src_reg->umin_value;
6852
6853 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6854 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6855 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6856
John Fastabend07cd2632020-03-24 10:38:15 -07006857 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6858 /* We may learn something more from the var_off */
6859 __update_reg_bounds(dst_reg);
6860}
6861
John Fastabend3f50f132020-03-30 14:36:39 -07006862static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6863 struct bpf_reg_state *src_reg)
6864{
6865 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6866 u32 umax_val = src_reg->u32_max_value;
6867 u32 umin_val = src_reg->u32_min_value;
6868
6869 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6870 * be negative, then either:
6871 * 1) src_reg might be zero, so the sign bit of the result is
6872 * unknown, so we lose our signed bounds
6873 * 2) it's known negative, thus the unsigned bounds capture the
6874 * signed bounds
6875 * 3) the signed bounds cross zero, so they tell us nothing
6876 * about the result
6877 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006878 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07006879 * Thus, in all cases it suffices to blow away our signed bounds
6880 * and rely on inferring new ones from the unsigned bounds and
6881 * var_off of the result.
6882 */
6883 dst_reg->s32_min_value = S32_MIN;
6884 dst_reg->s32_max_value = S32_MAX;
6885
6886 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6887 dst_reg->u32_min_value >>= umax_val;
6888 dst_reg->u32_max_value >>= umin_val;
6889
6890 __mark_reg64_unbounded(dst_reg);
6891 __update_reg32_bounds(dst_reg);
6892}
6893
John Fastabend07cd2632020-03-24 10:38:15 -07006894static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6895 struct bpf_reg_state *src_reg)
6896{
6897 u64 umax_val = src_reg->umax_value;
6898 u64 umin_val = src_reg->umin_value;
6899
6900 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6901 * be negative, then either:
6902 * 1) src_reg might be zero, so the sign bit of the result is
6903 * unknown, so we lose our signed bounds
6904 * 2) it's known negative, thus the unsigned bounds capture the
6905 * signed bounds
6906 * 3) the signed bounds cross zero, so they tell us nothing
6907 * about the result
6908 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006909 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07006910 * Thus, in all cases it suffices to blow away our signed bounds
6911 * and rely on inferring new ones from the unsigned bounds and
6912 * var_off of the result.
6913 */
6914 dst_reg->smin_value = S64_MIN;
6915 dst_reg->smax_value = S64_MAX;
6916 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6917 dst_reg->umin_value >>= umax_val;
6918 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006919
6920 /* Its not easy to operate on alu32 bounds here because it depends
6921 * on bits being shifted in. Take easy way out and mark unbounded
6922 * so we can recalculate later from tnum.
6923 */
6924 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006925 __update_reg_bounds(dst_reg);
6926}
6927
John Fastabend3f50f132020-03-30 14:36:39 -07006928static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6929 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006930{
John Fastabend3f50f132020-03-30 14:36:39 -07006931 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006932
6933 /* Upon reaching here, src_known is true and
6934 * umax_val is equal to umin_val.
6935 */
John Fastabend3f50f132020-03-30 14:36:39 -07006936 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6937 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006938
John Fastabend3f50f132020-03-30 14:36:39 -07006939 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6940
6941 /* blow away the dst_reg umin_value/umax_value and rely on
6942 * dst_reg var_off to refine the result.
6943 */
6944 dst_reg->u32_min_value = 0;
6945 dst_reg->u32_max_value = U32_MAX;
6946
6947 __mark_reg64_unbounded(dst_reg);
6948 __update_reg32_bounds(dst_reg);
6949}
6950
6951static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6952 struct bpf_reg_state *src_reg)
6953{
6954 u64 umin_val = src_reg->umin_value;
6955
6956 /* Upon reaching here, src_known is true and umax_val is equal
6957 * to umin_val.
6958 */
6959 dst_reg->smin_value >>= umin_val;
6960 dst_reg->smax_value >>= umin_val;
6961
6962 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006963
6964 /* blow away the dst_reg umin_value/umax_value and rely on
6965 * dst_reg var_off to refine the result.
6966 */
6967 dst_reg->umin_value = 0;
6968 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006969
6970 /* Its not easy to operate on alu32 bounds here because it depends
6971 * on bits being shifted in from upper 32-bits. Take easy way out
6972 * and mark unbounded so we can recalculate later from tnum.
6973 */
6974 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006975 __update_reg_bounds(dst_reg);
6976}
6977
Jann Horn468f6ea2017-12-18 20:11:56 -08006978/* WARNING: This function does calculations on 64-bit values, but the actual
6979 * execution may occur on 32-bit values. Therefore, things like bitshifts
6980 * need extra checks in the 32-bit case.
6981 */
Edward Creef1174f72017-08-07 15:26:19 +01006982static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6983 struct bpf_insn *insn,
6984 struct bpf_reg_state *dst_reg,
6985 struct bpf_reg_state src_reg)
6986{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006987 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006988 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006989 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006990 s64 smin_val, smax_val;
6991 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006992 s32 s32_min_val, s32_max_val;
6993 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006994 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006995 u32 dst = insn->dst_reg;
6996 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006997 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006998
Edward Creeb03c9f92017-08-07 15:26:36 +01006999 smin_val = src_reg.smin_value;
7000 smax_val = src_reg.smax_value;
7001 umin_val = src_reg.umin_value;
7002 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01007003
John Fastabend3f50f132020-03-30 14:36:39 -07007004 s32_min_val = src_reg.s32_min_value;
7005 s32_max_val = src_reg.s32_max_value;
7006 u32_min_val = src_reg.u32_min_value;
7007 u32_max_val = src_reg.u32_max_value;
7008
7009 if (alu32) {
7010 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007011 if ((src_known &&
7012 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
7013 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
7014 /* Taint dst register if offset had invalid bounds
7015 * derived from e.g. dead branches.
7016 */
7017 __mark_reg_unknown(env, dst_reg);
7018 return 0;
7019 }
7020 } else {
7021 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07007022 if ((src_known &&
7023 (smin_val != smax_val || umin_val != umax_val)) ||
7024 smin_val > smax_val || umin_val > umax_val) {
7025 /* Taint dst register if offset had invalid bounds
7026 * derived from e.g. dead branches.
7027 */
7028 __mark_reg_unknown(env, dst_reg);
7029 return 0;
7030 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01007031 }
7032
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007033 if (!src_known &&
7034 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007035 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007036 return 0;
7037 }
7038
John Fastabend3f50f132020-03-30 14:36:39 -07007039 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
7040 * There are two classes of instructions: The first class we track both
7041 * alu32 and alu64 sign/unsigned bounds independently this provides the
7042 * greatest amount of precision when alu operations are mixed with jmp32
7043 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
7044 * and BPF_OR. This is possible because these ops have fairly easy to
7045 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
7046 * See alu32 verifier tests for examples. The second class of
7047 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
7048 * with regards to tracking sign/unsigned bounds because the bits may
7049 * cross subreg boundaries in the alu64 case. When this happens we mark
7050 * the reg unbounded in the subreg bound space and use the resulting
7051 * tnum to calculate an approximation of the sign/unsigned bounds.
7052 */
Edward Creef1174f72017-08-07 15:26:19 +01007053 switch (opcode) {
7054 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007055 ret = sanitize_val_alu(env, insn);
7056 if (ret < 0) {
7057 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
7058 return ret;
7059 }
John Fastabend3f50f132020-03-30 14:36:39 -07007060 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007061 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007062 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01007063 break;
7064 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007065 ret = sanitize_val_alu(env, insn);
7066 if (ret < 0) {
7067 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
7068 return ret;
7069 }
John Fastabend3f50f132020-03-30 14:36:39 -07007070 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007071 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07007072 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04007073 break;
7074 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07007075 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
7076 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007077 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007078 break;
7079 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07007080 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
7081 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007082 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007083 break;
7084 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07007085 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
7086 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007087 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007088 break;
Yonghong Song2921c902020-08-24 23:46:08 -07007089 case BPF_XOR:
7090 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
7091 scalar32_min_max_xor(dst_reg, &src_reg);
7092 scalar_min_max_xor(dst_reg, &src_reg);
7093 break;
Josef Bacik48461132016-09-28 10:54:32 -04007094 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007095 if (umax_val >= insn_bitness) {
7096 /* Shifts greater than 31 or 63 are undefined.
7097 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007098 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007099 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007100 break;
7101 }
John Fastabend3f50f132020-03-30 14:36:39 -07007102 if (alu32)
7103 scalar32_min_max_lsh(dst_reg, &src_reg);
7104 else
7105 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007106 break;
7107 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08007108 if (umax_val >= insn_bitness) {
7109 /* Shifts greater than 31 or 63 are undefined.
7110 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01007111 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007112 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007113 break;
7114 }
John Fastabend3f50f132020-03-30 14:36:39 -07007115 if (alu32)
7116 scalar32_min_max_rsh(dst_reg, &src_reg);
7117 else
7118 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007119 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007120 case BPF_ARSH:
7121 if (umax_val >= insn_bitness) {
7122 /* Shifts greater than 31 or 63 are undefined.
7123 * This includes shifts by a negative number.
7124 */
7125 mark_reg_unknown(env, regs, insn->dst_reg);
7126 break;
7127 }
John Fastabend3f50f132020-03-30 14:36:39 -07007128 if (alu32)
7129 scalar32_min_max_arsh(dst_reg, &src_reg);
7130 else
7131 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007132 break;
Josef Bacik48461132016-09-28 10:54:32 -04007133 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007134 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007135 break;
7136 }
7137
John Fastabend3f50f132020-03-30 14:36:39 -07007138 /* ALU32 ops are zero extended into 64bit register */
7139 if (alu32)
7140 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08007141
John Fastabend294f2fc2020-03-24 10:38:37 -07007142 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01007143 __reg_deduce_bounds(dst_reg);
7144 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007145 return 0;
7146}
7147
7148/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7149 * and var_off.
7150 */
7151static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7152 struct bpf_insn *insn)
7153{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007154 struct bpf_verifier_state *vstate = env->cur_state;
7155 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7156 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01007157 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7158 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007159 int err;
Edward Creef1174f72017-08-07 15:26:19 +01007160
7161 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007162 src_reg = NULL;
7163 if (dst_reg->type != SCALAR_VALUE)
7164 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007165 else
7166 /* Make sure ID is cleared otherwise dst_reg min/max could be
7167 * incorrectly propagated into other registers by find_equal_scalars()
7168 */
7169 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007170 if (BPF_SRC(insn->code) == BPF_X) {
7171 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007172 if (src_reg->type != SCALAR_VALUE) {
7173 if (dst_reg->type != SCALAR_VALUE) {
7174 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007175 * an arbitrary scalar. Disallow all math except
7176 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01007177 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07007178 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007179 mark_reg_unknown(env, regs, insn->dst_reg);
7180 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01007181 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007182 verbose(env, "R%d pointer %s pointer prohibited\n",
7183 insn->dst_reg,
7184 bpf_alu_string[opcode >> 4]);
7185 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01007186 } else {
7187 /* scalar += pointer
7188 * This is legal, but we have to reverse our
7189 * src/dest handling in computing the range
7190 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007191 err = mark_chain_precision(env, insn->dst_reg);
7192 if (err)
7193 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007194 return adjust_ptr_min_max_vals(env, insn,
7195 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007196 }
7197 } else if (ptr_reg) {
7198 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007199 err = mark_chain_precision(env, insn->src_reg);
7200 if (err)
7201 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007202 return adjust_ptr_min_max_vals(env, insn,
7203 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007204 }
7205 } else {
7206 /* Pretend the src is a reg with a known value, since we only
7207 * need to be able to read from this state.
7208 */
7209 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007210 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01007211 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007212 if (ptr_reg) /* pointer += K */
7213 return adjust_ptr_min_max_vals(env, insn,
7214 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007215 }
7216
7217 /* Got here implies adding two SCALAR_VALUEs */
7218 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007219 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007220 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007221 return -EINVAL;
7222 }
7223 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007224 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007225 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007226 return -EINVAL;
7227 }
7228 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007229}
7230
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007231/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007232static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007233{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007234 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007235 u8 opcode = BPF_OP(insn->code);
7236 int err;
7237
7238 if (opcode == BPF_END || opcode == BPF_NEG) {
7239 if (opcode == BPF_NEG) {
7240 if (BPF_SRC(insn->code) != 0 ||
7241 insn->src_reg != BPF_REG_0 ||
7242 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007243 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007244 return -EINVAL;
7245 }
7246 } else {
7247 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01007248 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7249 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007250 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007251 return -EINVAL;
7252 }
7253 }
7254
7255 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007256 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007257 if (err)
7258 return err;
7259
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007260 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007261 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007262 insn->dst_reg);
7263 return -EACCES;
7264 }
7265
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007266 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007267 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007268 if (err)
7269 return err;
7270
7271 } else if (opcode == BPF_MOV) {
7272
7273 if (BPF_SRC(insn->code) == BPF_X) {
7274 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007275 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007276 return -EINVAL;
7277 }
7278
7279 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007280 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007281 if (err)
7282 return err;
7283 } else {
7284 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007285 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007286 return -EINVAL;
7287 }
7288 }
7289
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007290 /* check dest operand, mark as required later */
7291 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007292 if (err)
7293 return err;
7294
7295 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05007296 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7297 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7298
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007299 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7300 /* case: R1 = R2
7301 * copy register state to dest reg
7302 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07007303 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7304 /* Assign src and dst registers the same ID
7305 * that will be used by find_equal_scalars()
7306 * to propagate min/max range.
7307 */
7308 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05007309 *dst_reg = *src_reg;
7310 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007311 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007312 } else {
Edward Creef1174f72017-08-07 15:26:19 +01007313 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007314 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007315 verbose(env,
7316 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007317 insn->src_reg);
7318 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05007319 } else if (src_reg->type == SCALAR_VALUE) {
7320 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007321 /* Make sure ID is cleared otherwise
7322 * dst_reg min/max could be incorrectly
7323 * propagated into src_reg by find_equal_scalars()
7324 */
7325 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05007326 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007327 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05007328 } else {
7329 mark_reg_unknown(env, regs,
7330 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007331 }
John Fastabend3f50f132020-03-30 14:36:39 -07007332 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007333 }
7334 } else {
7335 /* case: R = imm
7336 * remember the value we stored into this reg
7337 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007338 /* clear any state __mark_reg_known doesn't set */
7339 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007340 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08007341 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7342 __mark_reg_known(regs + insn->dst_reg,
7343 insn->imm);
7344 } else {
7345 __mark_reg_known(regs + insn->dst_reg,
7346 (u32)insn->imm);
7347 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007348 }
7349
7350 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007351 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007352 return -EINVAL;
7353
7354 } else { /* all other ALU ops: and, sub, xor, add, ... */
7355
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007356 if (BPF_SRC(insn->code) == BPF_X) {
7357 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007358 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007359 return -EINVAL;
7360 }
7361 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007362 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007363 if (err)
7364 return err;
7365 } else {
7366 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007367 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007368 return -EINVAL;
7369 }
7370 }
7371
7372 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007373 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007374 if (err)
7375 return err;
7376
7377 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7378 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007379 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007380 return -EINVAL;
7381 }
7382
Rabin Vincent229394e82016-01-12 20:17:08 +01007383 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7384 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7385 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7386
7387 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007388 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01007389 return -EINVAL;
7390 }
7391 }
7392
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007393 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007394 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007395 if (err)
7396 return err;
7397
Edward Creef1174f72017-08-07 15:26:19 +01007398 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007399 }
7400
7401 return 0;
7402}
7403
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007404static void __find_good_pkt_pointers(struct bpf_func_state *state,
7405 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007406 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007407{
7408 struct bpf_reg_state *reg;
7409 int i;
7410
7411 for (i = 0; i < MAX_BPF_REG; i++) {
7412 reg = &state->regs[i];
7413 if (reg->type == type && reg->id == dst_reg->id)
7414 /* keep the maximum range already checked */
7415 reg->range = max(reg->range, new_range);
7416 }
7417
7418 bpf_for_each_spilled_reg(i, state, reg) {
7419 if (!reg)
7420 continue;
7421 if (reg->type == type && reg->id == dst_reg->id)
7422 reg->range = max(reg->range, new_range);
7423 }
7424}
7425
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007426static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007427 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01007428 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007429 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007430{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007431 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007432
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007433 if (dst_reg->off < 0 ||
7434 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01007435 /* This doesn't give us any range */
7436 return;
7437
Edward Creeb03c9f92017-08-07 15:26:36 +01007438 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7439 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01007440 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7441 * than pkt_end, but that's because it's also less than pkt.
7442 */
7443 return;
7444
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007445 new_range = dst_reg->off;
7446 if (range_right_open)
7447 new_range--;
7448
7449 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007450 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007451 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007452 *
7453 * r2 = r3;
7454 * r2 += 8;
7455 * if (r2 > pkt_end) goto <handle exception>
7456 * <access okay>
7457 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007458 * r2 = r3;
7459 * r2 += 8;
7460 * if (r2 < pkt_end) goto <access okay>
7461 * <handle exception>
7462 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007463 * Where:
7464 * r2 == dst_reg, pkt_end == src_reg
7465 * r2=pkt(id=n,off=8,r=0)
7466 * r3=pkt(id=n,off=0,r=0)
7467 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007468 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007469 *
7470 * r2 = r3;
7471 * r2 += 8;
7472 * if (pkt_end >= r2) goto <access okay>
7473 * <handle exception>
7474 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007475 * r2 = r3;
7476 * r2 += 8;
7477 * if (pkt_end <= r2) goto <handle exception>
7478 * <access okay>
7479 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007480 * Where:
7481 * pkt_end == dst_reg, r2 == src_reg
7482 * r2=pkt(id=n,off=8,r=0)
7483 * r3=pkt(id=n,off=0,r=0)
7484 *
7485 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007486 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7487 * and [r3, r3 + 8-1) respectively is safe to access depending on
7488 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007489 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007490
Edward Creef1174f72017-08-07 15:26:19 +01007491 /* If our ids match, then we must have the same max_value. And we
7492 * don't care about the other reg's fixed offset, since if it's too big
7493 * the range won't allow anything.
7494 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7495 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007496 for (i = 0; i <= vstate->curframe; i++)
7497 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7498 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007499}
7500
John Fastabend3f50f132020-03-30 14:36:39 -07007501static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007502{
John Fastabend3f50f132020-03-30 14:36:39 -07007503 struct tnum subreg = tnum_subreg(reg->var_off);
7504 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007505
John Fastabend3f50f132020-03-30 14:36:39 -07007506 switch (opcode) {
7507 case BPF_JEQ:
7508 if (tnum_is_const(subreg))
7509 return !!tnum_equals_const(subreg, val);
7510 break;
7511 case BPF_JNE:
7512 if (tnum_is_const(subreg))
7513 return !tnum_equals_const(subreg, val);
7514 break;
7515 case BPF_JSET:
7516 if ((~subreg.mask & subreg.value) & val)
7517 return 1;
7518 if (!((subreg.mask | subreg.value) & val))
7519 return 0;
7520 break;
7521 case BPF_JGT:
7522 if (reg->u32_min_value > val)
7523 return 1;
7524 else if (reg->u32_max_value <= val)
7525 return 0;
7526 break;
7527 case BPF_JSGT:
7528 if (reg->s32_min_value > sval)
7529 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01007530 else if (reg->s32_max_value <= sval)
John Fastabend3f50f132020-03-30 14:36:39 -07007531 return 0;
7532 break;
7533 case BPF_JLT:
7534 if (reg->u32_max_value < val)
7535 return 1;
7536 else if (reg->u32_min_value >= val)
7537 return 0;
7538 break;
7539 case BPF_JSLT:
7540 if (reg->s32_max_value < sval)
7541 return 1;
7542 else if (reg->s32_min_value >= sval)
7543 return 0;
7544 break;
7545 case BPF_JGE:
7546 if (reg->u32_min_value >= val)
7547 return 1;
7548 else if (reg->u32_max_value < val)
7549 return 0;
7550 break;
7551 case BPF_JSGE:
7552 if (reg->s32_min_value >= sval)
7553 return 1;
7554 else if (reg->s32_max_value < sval)
7555 return 0;
7556 break;
7557 case BPF_JLE:
7558 if (reg->u32_max_value <= val)
7559 return 1;
7560 else if (reg->u32_min_value > val)
7561 return 0;
7562 break;
7563 case BPF_JSLE:
7564 if (reg->s32_max_value <= sval)
7565 return 1;
7566 else if (reg->s32_min_value > sval)
7567 return 0;
7568 break;
Jiong Wang092ed092019-01-26 12:26:01 -05007569 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05007570
John Fastabend3f50f132020-03-30 14:36:39 -07007571 return -1;
7572}
7573
7574
7575static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7576{
7577 s64 sval = (s64)val;
7578
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007579 switch (opcode) {
7580 case BPF_JEQ:
7581 if (tnum_is_const(reg->var_off))
7582 return !!tnum_equals_const(reg->var_off, val);
7583 break;
7584 case BPF_JNE:
7585 if (tnum_is_const(reg->var_off))
7586 return !tnum_equals_const(reg->var_off, val);
7587 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08007588 case BPF_JSET:
7589 if ((~reg->var_off.mask & reg->var_off.value) & val)
7590 return 1;
7591 if (!((reg->var_off.mask | reg->var_off.value) & val))
7592 return 0;
7593 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007594 case BPF_JGT:
7595 if (reg->umin_value > val)
7596 return 1;
7597 else if (reg->umax_value <= val)
7598 return 0;
7599 break;
7600 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007601 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007602 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01007603 else if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007604 return 0;
7605 break;
7606 case BPF_JLT:
7607 if (reg->umax_value < val)
7608 return 1;
7609 else if (reg->umin_value >= val)
7610 return 0;
7611 break;
7612 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007613 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007614 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007615 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007616 return 0;
7617 break;
7618 case BPF_JGE:
7619 if (reg->umin_value >= val)
7620 return 1;
7621 else if (reg->umax_value < val)
7622 return 0;
7623 break;
7624 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007625 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007626 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007627 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007628 return 0;
7629 break;
7630 case BPF_JLE:
7631 if (reg->umax_value <= val)
7632 return 1;
7633 else if (reg->umin_value > val)
7634 return 0;
7635 break;
7636 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007637 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007638 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007639 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007640 return 0;
7641 break;
7642 }
7643
7644 return -1;
7645}
7646
John Fastabend3f50f132020-03-30 14:36:39 -07007647/* compute branch direction of the expression "if (reg opcode val) goto target;"
7648 * and return:
7649 * 1 - branch will be taken and "goto target" will be executed
7650 * 0 - branch will not be taken and fall-through to next insn
7651 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7652 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05007653 */
John Fastabend3f50f132020-03-30 14:36:39 -07007654static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7655 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05007656{
John Fastabendcac616d2020-05-21 13:07:26 -07007657 if (__is_pointer_value(false, reg)) {
7658 if (!reg_type_not_null(reg->type))
7659 return -1;
7660
7661 /* If pointer is valid tests against zero will fail so we can
7662 * use this to direct branch taken.
7663 */
7664 if (val != 0)
7665 return -1;
7666
7667 switch (opcode) {
7668 case BPF_JEQ:
7669 return 0;
7670 case BPF_JNE:
7671 return 1;
7672 default:
7673 return -1;
7674 }
7675 }
Jiong Wang092ed092019-01-26 12:26:01 -05007676
John Fastabend3f50f132020-03-30 14:36:39 -07007677 if (is_jmp32)
7678 return is_branch32_taken(reg, val, opcode);
7679 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02007680}
7681
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007682static int flip_opcode(u32 opcode)
7683{
7684 /* How can we transform "a <op> b" into "b <op> a"? */
7685 static const u8 opcode_flip[16] = {
7686 /* these stay the same */
7687 [BPF_JEQ >> 4] = BPF_JEQ,
7688 [BPF_JNE >> 4] = BPF_JNE,
7689 [BPF_JSET >> 4] = BPF_JSET,
7690 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7691 [BPF_JGE >> 4] = BPF_JLE,
7692 [BPF_JGT >> 4] = BPF_JLT,
7693 [BPF_JLE >> 4] = BPF_JGE,
7694 [BPF_JLT >> 4] = BPF_JGT,
7695 [BPF_JSGE >> 4] = BPF_JSLE,
7696 [BPF_JSGT >> 4] = BPF_JSLT,
7697 [BPF_JSLE >> 4] = BPF_JSGE,
7698 [BPF_JSLT >> 4] = BPF_JSGT
7699 };
7700 return opcode_flip[opcode >> 4];
7701}
7702
7703static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7704 struct bpf_reg_state *src_reg,
7705 u8 opcode)
7706{
7707 struct bpf_reg_state *pkt;
7708
7709 if (src_reg->type == PTR_TO_PACKET_END) {
7710 pkt = dst_reg;
7711 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7712 pkt = src_reg;
7713 opcode = flip_opcode(opcode);
7714 } else {
7715 return -1;
7716 }
7717
7718 if (pkt->range >= 0)
7719 return -1;
7720
7721 switch (opcode) {
7722 case BPF_JLE:
7723 /* pkt <= pkt_end */
7724 fallthrough;
7725 case BPF_JGT:
7726 /* pkt > pkt_end */
7727 if (pkt->range == BEYOND_PKT_END)
7728 /* pkt has at last one extra byte beyond pkt_end */
7729 return opcode == BPF_JGT;
7730 break;
7731 case BPF_JLT:
7732 /* pkt < pkt_end */
7733 fallthrough;
7734 case BPF_JGE:
7735 /* pkt >= pkt_end */
7736 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7737 return opcode == BPF_JGE;
7738 break;
7739 }
7740 return -1;
7741}
7742
Josef Bacik48461132016-09-28 10:54:32 -04007743/* Adjusts the register min/max values in the case that the dst_reg is the
7744 * variable register that we are working on, and src_reg is a constant or we're
7745 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01007746 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04007747 */
7748static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007749 struct bpf_reg_state *false_reg,
7750 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007751 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007752{
John Fastabend3f50f132020-03-30 14:36:39 -07007753 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7754 struct tnum false_64off = false_reg->var_off;
7755 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7756 struct tnum true_64off = true_reg->var_off;
7757 s64 sval = (s64)val;
7758 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007759
Edward Creef1174f72017-08-07 15:26:19 +01007760 /* If the dst_reg is a pointer, we can't learn anything about its
7761 * variable offset from the compare (unless src_reg were a pointer into
7762 * the same object, but we don't bother with that.
7763 * Since false_reg and true_reg have the same type by construction, we
7764 * only need to check one of them for pointerness.
7765 */
7766 if (__is_pointer_value(false, false_reg))
7767 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007768
Josef Bacik48461132016-09-28 10:54:32 -04007769 switch (opcode) {
7770 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04007771 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007772 {
7773 struct bpf_reg_state *reg =
7774 opcode == BPF_JEQ ? true_reg : false_reg;
7775
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007776 /* JEQ/JNE comparison doesn't change the register equivalence.
7777 * r1 = r2;
7778 * if (r1 == 42) goto label;
7779 * ...
7780 * label: // here both r1 and r2 are known to be 42.
7781 *
7782 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04007783 */
John Fastabend3f50f132020-03-30 14:36:39 -07007784 if (is_jmp32)
7785 __mark_reg32_known(reg, val32);
7786 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007787 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04007788 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007789 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007790 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07007791 if (is_jmp32) {
7792 false_32off = tnum_and(false_32off, tnum_const(~val32));
7793 if (is_power_of_2(val32))
7794 true_32off = tnum_or(true_32off,
7795 tnum_const(val32));
7796 } else {
7797 false_64off = tnum_and(false_64off, tnum_const(~val));
7798 if (is_power_of_2(val))
7799 true_64off = tnum_or(true_64off,
7800 tnum_const(val));
7801 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007802 break;
Josef Bacik48461132016-09-28 10:54:32 -04007803 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007804 case BPF_JGT:
7805 {
John Fastabend3f50f132020-03-30 14:36:39 -07007806 if (is_jmp32) {
7807 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7808 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7809
7810 false_reg->u32_max_value = min(false_reg->u32_max_value,
7811 false_umax);
7812 true_reg->u32_min_value = max(true_reg->u32_min_value,
7813 true_umin);
7814 } else {
7815 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7816 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7817
7818 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7819 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7820 }
Edward Creeb03c9f92017-08-07 15:26:36 +01007821 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007822 }
Josef Bacik48461132016-09-28 10:54:32 -04007823 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007824 case BPF_JSGT:
7825 {
John Fastabend3f50f132020-03-30 14:36:39 -07007826 if (is_jmp32) {
7827 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7828 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007829
John Fastabend3f50f132020-03-30 14:36:39 -07007830 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7831 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7832 } else {
7833 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7834 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7835
7836 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7837 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7838 }
Josef Bacik48461132016-09-28 10:54:32 -04007839 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007840 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007841 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007842 case BPF_JLT:
7843 {
John Fastabend3f50f132020-03-30 14:36:39 -07007844 if (is_jmp32) {
7845 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7846 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7847
7848 false_reg->u32_min_value = max(false_reg->u32_min_value,
7849 false_umin);
7850 true_reg->u32_max_value = min(true_reg->u32_max_value,
7851 true_umax);
7852 } else {
7853 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7854 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7855
7856 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7857 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7858 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007859 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007860 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007861 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007862 case BPF_JSLT:
7863 {
John Fastabend3f50f132020-03-30 14:36:39 -07007864 if (is_jmp32) {
7865 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7866 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007867
John Fastabend3f50f132020-03-30 14:36:39 -07007868 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7869 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7870 } else {
7871 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7872 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7873
7874 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7875 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7876 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007877 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007878 }
Josef Bacik48461132016-09-28 10:54:32 -04007879 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02007880 return;
Josef Bacik48461132016-09-28 10:54:32 -04007881 }
7882
John Fastabend3f50f132020-03-30 14:36:39 -07007883 if (is_jmp32) {
7884 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7885 tnum_subreg(false_32off));
7886 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7887 tnum_subreg(true_32off));
7888 __reg_combine_32_into_64(false_reg);
7889 __reg_combine_32_into_64(true_reg);
7890 } else {
7891 false_reg->var_off = false_64off;
7892 true_reg->var_off = true_64off;
7893 __reg_combine_64_into_32(false_reg);
7894 __reg_combine_64_into_32(true_reg);
7895 }
Josef Bacik48461132016-09-28 10:54:32 -04007896}
7897
Edward Creef1174f72017-08-07 15:26:19 +01007898/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7899 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04007900 */
7901static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007902 struct bpf_reg_state *false_reg,
7903 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007904 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007905{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007906 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02007907 /* This uses zero as "not present in table"; luckily the zero opcode,
7908 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01007909 */
Jann Horn0fc31b12020-03-30 18:03:24 +02007910 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07007911 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01007912}
7913
7914/* Regs are known to be equal, so intersect their min/max/var_off */
7915static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7916 struct bpf_reg_state *dst_reg)
7917{
Edward Creeb03c9f92017-08-07 15:26:36 +01007918 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7919 dst_reg->umin_value);
7920 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7921 dst_reg->umax_value);
7922 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7923 dst_reg->smin_value);
7924 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7925 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01007926 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7927 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007928 /* We might have learned new bounds from the var_off. */
7929 __update_reg_bounds(src_reg);
7930 __update_reg_bounds(dst_reg);
7931 /* We might have learned something about the sign bit. */
7932 __reg_deduce_bounds(src_reg);
7933 __reg_deduce_bounds(dst_reg);
7934 /* We might have learned some bits from the bounds. */
7935 __reg_bound_offset(src_reg);
7936 __reg_bound_offset(dst_reg);
7937 /* Intersecting with the old var_off might have improved our bounds
7938 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7939 * then new var_off is (0; 0x7f...fc) which improves our umax.
7940 */
7941 __update_reg_bounds(src_reg);
7942 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007943}
7944
7945static void reg_combine_min_max(struct bpf_reg_state *true_src,
7946 struct bpf_reg_state *true_dst,
7947 struct bpf_reg_state *false_src,
7948 struct bpf_reg_state *false_dst,
7949 u8 opcode)
7950{
7951 switch (opcode) {
7952 case BPF_JEQ:
7953 __reg_combine_min_max(true_src, true_dst);
7954 break;
7955 case BPF_JNE:
7956 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007957 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007958 }
Josef Bacik48461132016-09-28 10:54:32 -04007959}
7960
Joe Stringerfd978bf72018-10-02 13:35:35 -07007961static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7962 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007963 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007964{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07007965 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7966 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01007967 /* Old offset (both fixed and variable parts) should
7968 * have been known-zero, because we don't allow pointer
7969 * arithmetic on pointers that might be NULL.
7970 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007971 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7972 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007973 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007974 __mark_reg_known_zero(reg);
7975 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007976 }
7977 if (is_null) {
7978 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007979 /* We don't need id and ref_obj_id from this point
7980 * onwards anymore, thus we should better reset it,
7981 * so that state pruning has chances to take effect.
7982 */
7983 reg->id = 0;
7984 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04007985
7986 return;
7987 }
7988
7989 mark_ptr_not_null_reg(reg);
7990
7991 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007992 /* For not-NULL ptr, reg->ref_obj_id will be reset
7993 * in release_reg_references().
7994 *
7995 * reg->id is still used by spin_lock ptr. Other
7996 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007997 */
7998 reg->id = 0;
7999 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02008000 }
8001}
8002
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008003static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
8004 bool is_null)
8005{
8006 struct bpf_reg_state *reg;
8007 int i;
8008
8009 for (i = 0; i < MAX_BPF_REG; i++)
8010 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
8011
8012 bpf_for_each_spilled_reg(i, state, reg) {
8013 if (!reg)
8014 continue;
8015 mark_ptr_or_null_reg(state, reg, id, is_null);
8016 }
8017}
8018
Thomas Graf57a09bf2016-10-18 19:51:19 +02008019/* The logic is similar to find_good_pkt_pointers(), both could eventually
8020 * be folded together at some point.
8021 */
Joe Stringer840b9612018-10-02 13:35:32 -07008022static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
8023 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02008024{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008025 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008026 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008027 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01008028 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008029 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02008030
Martin KaFai Lau1b986582019-03-12 10:23:02 -07008031 if (ref_obj_id && ref_obj_id == id && is_null)
8032 /* regs[regno] is in the " == NULL" branch.
8033 * No one could have freed the reference state before
8034 * doing the NULL check.
8035 */
8036 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07008037
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008038 for (i = 0; i <= vstate->curframe; i++)
8039 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02008040}
8041
Daniel Borkmann5beca082017-11-01 23:58:10 +01008042static bool try_match_pkt_pointers(const struct bpf_insn *insn,
8043 struct bpf_reg_state *dst_reg,
8044 struct bpf_reg_state *src_reg,
8045 struct bpf_verifier_state *this_branch,
8046 struct bpf_verifier_state *other_branch)
8047{
8048 if (BPF_SRC(insn->code) != BPF_X)
8049 return false;
8050
Jiong Wang092ed092019-01-26 12:26:01 -05008051 /* Pointers are always 64-bit. */
8052 if (BPF_CLASS(insn->code) == BPF_JMP32)
8053 return false;
8054
Daniel Borkmann5beca082017-11-01 23:58:10 +01008055 switch (BPF_OP(insn->code)) {
8056 case BPF_JGT:
8057 if ((dst_reg->type == PTR_TO_PACKET &&
8058 src_reg->type == PTR_TO_PACKET_END) ||
8059 (dst_reg->type == PTR_TO_PACKET_META &&
8060 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8061 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
8062 find_good_pkt_pointers(this_branch, dst_reg,
8063 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008064 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008065 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8066 src_reg->type == PTR_TO_PACKET) ||
8067 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8068 src_reg->type == PTR_TO_PACKET_META)) {
8069 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
8070 find_good_pkt_pointers(other_branch, src_reg,
8071 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008072 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008073 } else {
8074 return false;
8075 }
8076 break;
8077 case BPF_JLT:
8078 if ((dst_reg->type == PTR_TO_PACKET &&
8079 src_reg->type == PTR_TO_PACKET_END) ||
8080 (dst_reg->type == PTR_TO_PACKET_META &&
8081 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8082 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
8083 find_good_pkt_pointers(other_branch, dst_reg,
8084 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008085 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008086 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8087 src_reg->type == PTR_TO_PACKET) ||
8088 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8089 src_reg->type == PTR_TO_PACKET_META)) {
8090 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
8091 find_good_pkt_pointers(this_branch, src_reg,
8092 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008093 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008094 } else {
8095 return false;
8096 }
8097 break;
8098 case BPF_JGE:
8099 if ((dst_reg->type == PTR_TO_PACKET &&
8100 src_reg->type == PTR_TO_PACKET_END) ||
8101 (dst_reg->type == PTR_TO_PACKET_META &&
8102 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8103 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
8104 find_good_pkt_pointers(this_branch, dst_reg,
8105 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008106 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008107 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8108 src_reg->type == PTR_TO_PACKET) ||
8109 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8110 src_reg->type == PTR_TO_PACKET_META)) {
8111 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
8112 find_good_pkt_pointers(other_branch, src_reg,
8113 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008114 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008115 } else {
8116 return false;
8117 }
8118 break;
8119 case BPF_JLE:
8120 if ((dst_reg->type == PTR_TO_PACKET &&
8121 src_reg->type == PTR_TO_PACKET_END) ||
8122 (dst_reg->type == PTR_TO_PACKET_META &&
8123 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
8124 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
8125 find_good_pkt_pointers(other_branch, dst_reg,
8126 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008127 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008128 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8129 src_reg->type == PTR_TO_PACKET) ||
8130 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8131 src_reg->type == PTR_TO_PACKET_META)) {
8132 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8133 find_good_pkt_pointers(this_branch, src_reg,
8134 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008135 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008136 } else {
8137 return false;
8138 }
8139 break;
8140 default:
8141 return false;
8142 }
8143
8144 return true;
8145}
8146
Alexei Starovoitov75748832020-10-08 18:12:37 -07008147static void find_equal_scalars(struct bpf_verifier_state *vstate,
8148 struct bpf_reg_state *known_reg)
8149{
8150 struct bpf_func_state *state;
8151 struct bpf_reg_state *reg;
8152 int i, j;
8153
8154 for (i = 0; i <= vstate->curframe; i++) {
8155 state = vstate->frame[i];
8156 for (j = 0; j < MAX_BPF_REG; j++) {
8157 reg = &state->regs[j];
8158 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8159 *reg = *known_reg;
8160 }
8161
8162 bpf_for_each_spilled_reg(j, state, reg) {
8163 if (!reg)
8164 continue;
8165 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8166 *reg = *known_reg;
8167 }
8168 }
8169}
8170
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008171static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008172 struct bpf_insn *insn, int *insn_idx)
8173{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008174 struct bpf_verifier_state *this_branch = env->cur_state;
8175 struct bpf_verifier_state *other_branch;
8176 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008177 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008178 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05008179 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008180 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008181 int err;
8182
Jiong Wang092ed092019-01-26 12:26:01 -05008183 /* Only conditional jumps are expected to reach here. */
8184 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8185 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008186 return -EINVAL;
8187 }
8188
8189 if (BPF_SRC(insn->code) == BPF_X) {
8190 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008191 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008192 return -EINVAL;
8193 }
8194
8195 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008196 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008197 if (err)
8198 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008199
8200 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008201 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008202 insn->src_reg);
8203 return -EACCES;
8204 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008205 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008206 } else {
8207 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008208 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008209 return -EINVAL;
8210 }
8211 }
8212
8213 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008214 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008215 if (err)
8216 return err;
8217
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008218 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008219 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008220
John Fastabend3f50f132020-03-30 14:36:39 -07008221 if (BPF_SRC(insn->code) == BPF_K) {
8222 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8223 } else if (src_reg->type == SCALAR_VALUE &&
8224 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8225 pred = is_branch_taken(dst_reg,
8226 tnum_subreg(src_reg->var_off).value,
8227 opcode,
8228 is_jmp32);
8229 } else if (src_reg->type == SCALAR_VALUE &&
8230 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8231 pred = is_branch_taken(dst_reg,
8232 src_reg->var_off.value,
8233 opcode,
8234 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008235 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8236 reg_is_pkt_pointer_any(src_reg) &&
8237 !is_jmp32) {
8238 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07008239 }
8240
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008241 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07008242 /* If we get here with a dst_reg pointer type it is because
8243 * above is_branch_taken() special cased the 0 comparison.
8244 */
8245 if (!__is_pointer_value(false, dst_reg))
8246 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008247 if (BPF_SRC(insn->code) == BPF_X && !err &&
8248 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008249 err = mark_chain_precision(env, insn->src_reg);
8250 if (err)
8251 return err;
8252 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008253 if (pred == 1) {
8254 /* only follow the goto, ignore fall-through */
8255 *insn_idx += insn->off;
8256 return 0;
8257 } else if (pred == 0) {
8258 /* only follow fall-through branch, since
8259 * that's where the program will go
8260 */
8261 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008262 }
8263
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008264 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8265 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008266 if (!other_branch)
8267 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008268 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008269
Josef Bacik48461132016-09-28 10:54:32 -04008270 /* detect if we are comparing against a constant value so we can adjust
8271 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01008272 * this is only legit if both are scalars (or pointers to the same
8273 * object, I suppose, but we don't support that right now), because
8274 * otherwise the different base pointers mean the offsets aren't
8275 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04008276 */
8277 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05008278 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008279
Edward Creef1174f72017-08-07 15:26:19 +01008280 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05008281 src_reg->type == SCALAR_VALUE) {
8282 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008283 (is_jmp32 &&
8284 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008285 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008286 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008287 src_reg->var_off.value,
8288 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008289 opcode, is_jmp32);
8290 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008291 (is_jmp32 &&
8292 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008293 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008294 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008295 dst_reg->var_off.value,
8296 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008297 opcode, is_jmp32);
8298 else if (!is_jmp32 &&
8299 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01008300 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008301 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8302 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008303 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008304 if (src_reg->id &&
8305 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008306 find_equal_scalars(this_branch, src_reg);
8307 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8308 }
8309
Edward Creef1174f72017-08-07 15:26:19 +01008310 }
8311 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008312 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07008313 dst_reg, insn->imm, (u32)insn->imm,
8314 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04008315 }
8316
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008317 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8318 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008319 find_equal_scalars(this_branch, dst_reg);
8320 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8321 }
8322
Jiong Wang092ed092019-01-26 12:26:01 -05008323 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8324 * NOTE: these optimizations below are related with pointer comparison
8325 * which will never be JMP32.
8326 */
8327 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008328 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07008329 reg_type_may_be_null(dst_reg->type)) {
8330 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02008331 * safe or unknown depending R == 0 or R != 0 conditional.
8332 */
Joe Stringer840b9612018-10-02 13:35:32 -07008333 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8334 opcode == BPF_JNE);
8335 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8336 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008337 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8338 this_branch, other_branch) &&
8339 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008340 verbose(env, "R%d pointer comparison prohibited\n",
8341 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008342 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008343 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008344 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008345 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008346 return 0;
8347}
8348
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008349/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008350static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008351{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008352 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008353 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07008354 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008355 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008356 int err;
8357
8358 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008359 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008360 return -EINVAL;
8361 }
8362 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008363 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008364 return -EINVAL;
8365 }
8366
Edward Creedc503a82017-08-15 20:34:35 +01008367 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008368 if (err)
8369 return err;
8370
Hao Luo4976b712020-09-29 16:50:44 -07008371 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01008372 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01008373 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8374
Hao Luo4976b712020-09-29 16:50:44 -07008375 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008376 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008377 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01008378 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008379
Hao Luo4976b712020-09-29 16:50:44 -07008380 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8381 mark_reg_known_zero(env, regs, insn->dst_reg);
8382
8383 dst_reg->type = aux->btf_var.reg_type;
8384 switch (dst_reg->type) {
8385 case PTR_TO_MEM:
8386 dst_reg->mem_size = aux->btf_var.mem_size;
8387 break;
8388 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07008389 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08008390 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07008391 dst_reg->btf_id = aux->btf_var.btf_id;
8392 break;
8393 default:
8394 verbose(env, "bpf verifier is misconfigured\n");
8395 return -EFAULT;
8396 }
8397 return 0;
8398 }
8399
Yonghong Song69c087b2021-02-26 12:49:25 -08008400 if (insn->src_reg == BPF_PSEUDO_FUNC) {
8401 struct bpf_prog_aux *aux = env->prog->aux;
8402 u32 subprogno = insn[1].imm;
8403
8404 if (!aux->func_info) {
8405 verbose(env, "missing btf func_info\n");
8406 return -EINVAL;
8407 }
8408 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
8409 verbose(env, "callback function not static\n");
8410 return -EINVAL;
8411 }
8412
8413 dst_reg->type = PTR_TO_FUNC;
8414 dst_reg->subprogno = subprogno;
8415 return 0;
8416 }
8417
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008418 map = env->used_maps[aux->map_index];
8419 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07008420 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008421
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008422 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07008423 dst_reg->type = PTR_TO_MAP_VALUE;
8424 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008425 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07008426 dst_reg->id = ++env->id_gen;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008427 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
Hao Luo4976b712020-09-29 16:50:44 -07008428 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008429 } else {
8430 verbose(env, "bpf verifier is misconfigured\n");
8431 return -EINVAL;
8432 }
8433
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008434 return 0;
8435}
8436
Daniel Borkmann96be4322015-03-01 12:31:46 +01008437static bool may_access_skb(enum bpf_prog_type type)
8438{
8439 switch (type) {
8440 case BPF_PROG_TYPE_SOCKET_FILTER:
8441 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01008442 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01008443 return true;
8444 default:
8445 return false;
8446 }
8447}
8448
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008449/* verify safety of LD_ABS|LD_IND instructions:
8450 * - they can only appear in the programs where ctx == skb
8451 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8452 * preserve R6-R9, and store return value into R0
8453 *
8454 * Implicit input:
8455 * ctx == skb == R6 == CTX
8456 *
8457 * Explicit input:
8458 * SRC == any register
8459 * IMM == 32-bit immediate
8460 *
8461 * Output:
8462 * R0 - 8/16/32-bit skb data converted to cpu endianness
8463 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008464static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008465{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008466 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008467 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008468 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008469 int i, err;
8470
Udip Pant7e407812020-08-25 16:20:00 -07008471 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008472 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008473 return -EINVAL;
8474 }
8475
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02008476 if (!env->ops->gen_ld_abs) {
8477 verbose(env, "bpf verifier is misconfigured\n");
8478 return -EINVAL;
8479 }
8480
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008481 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07008482 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008483 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008484 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008485 return -EINVAL;
8486 }
8487
8488 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008489 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008490 if (err)
8491 return err;
8492
Joe Stringerfd978bf72018-10-02 13:35:35 -07008493 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8494 * gen_ld_abs() may terminate the program at runtime, leading to
8495 * reference leak.
8496 */
8497 err = check_reference_leak(env);
8498 if (err) {
8499 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8500 return err;
8501 }
8502
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008503 if (env->cur_state->active_spin_lock) {
8504 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8505 return -EINVAL;
8506 }
8507
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008508 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008509 verbose(env,
8510 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008511 return -EINVAL;
8512 }
8513
8514 if (mode == BPF_IND) {
8515 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01008516 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008517 if (err)
8518 return err;
8519 }
8520
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008521 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8522 if (err < 0)
8523 return err;
8524
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008525 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01008526 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008527 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008528 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8529 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008530
8531 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01008532 * the value fetched from the packet.
8533 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008534 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008535 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01008536 /* ld_abs load up to 32-bit skb data. */
8537 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008538 return 0;
8539}
8540
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008541static int check_return_code(struct bpf_verifier_env *env)
8542{
brakmo5cf1e912019-05-28 16:59:36 -07008543 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008544 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008545 struct bpf_reg_state *reg;
8546 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07008547 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008548 int err;
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008549 const bool is_subprog = env->cur_state->frame[0]->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008550
KP Singh9e4e01d2020-03-29 01:43:52 +01008551 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008552 if (!is_subprog &&
8553 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07008554 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008555 !prog->aux->attach_func_proto->type)
8556 return 0;
8557
8558 /* eBPF calling convetion is such that R0 is used
8559 * to return the value from eBPF program.
8560 * Make sure that it's readable at this time
8561 * of bpf_exit, which means that program wrote
8562 * something into it earlier
8563 */
8564 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8565 if (err)
8566 return err;
8567
8568 if (is_pointer_value(env, BPF_REG_0)) {
8569 verbose(env, "R0 leaks addr as return value\n");
8570 return -EACCES;
8571 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008572
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008573 reg = cur_regs(env) + BPF_REG_0;
8574 if (is_subprog) {
8575 if (reg->type != SCALAR_VALUE) {
8576 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8577 reg_type_str[reg->type]);
8578 return -EINVAL;
8579 }
8580 return 0;
8581 }
8582
Udip Pant7e407812020-08-25 16:20:00 -07008583 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02008584 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8585 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02008586 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8587 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8588 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8589 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8590 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02008591 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08008592 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8593 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8594 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008595 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008596 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07008597 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8598 range = tnum_range(0, 3);
8599 enforce_attach_type_range = tnum_range(2, 3);
8600 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008601 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008602 case BPF_PROG_TYPE_CGROUP_SOCK:
8603 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05008604 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08008605 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07008606 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008607 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07008608 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8609 if (!env->prog->aux->attach_btf_id)
8610 return 0;
8611 range = tnum_const(0);
8612 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07008613 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07008614 switch (env->prog->expected_attach_type) {
8615 case BPF_TRACE_FENTRY:
8616 case BPF_TRACE_FEXIT:
8617 range = tnum_const(0);
8618 break;
8619 case BPF_TRACE_RAW_TP:
8620 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07008621 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02008622 case BPF_TRACE_ITER:
8623 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008624 default:
8625 return -ENOTSUPP;
8626 }
Yonghong Song15d83c42020-05-09 10:59:00 -07008627 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02008628 case BPF_PROG_TYPE_SK_LOOKUP:
8629 range = tnum_range(SK_DROP, SK_PASS);
8630 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008631 case BPF_PROG_TYPE_EXT:
8632 /* freplace program can return anything as its return value
8633 * depends on the to-be-replaced kernel func or bpf program.
8634 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008635 default:
8636 return 0;
8637 }
8638
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008639 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008640 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008641 reg_type_str[reg->type]);
8642 return -EINVAL;
8643 }
8644
8645 if (!tnum_in(range, reg->var_off)) {
Yonghong Songbc2591d2021-02-26 12:49:22 -08008646 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008647 return -EINVAL;
8648 }
brakmo5cf1e912019-05-28 16:59:36 -07008649
8650 if (!tnum_is_unknown(enforce_attach_type_range) &&
8651 tnum_in(enforce_attach_type_range, reg->var_off))
8652 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008653 return 0;
8654}
8655
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008656/* non-recursive DFS pseudo code
8657 * 1 procedure DFS-iterative(G,v):
8658 * 2 label v as discovered
8659 * 3 let S be a stack
8660 * 4 S.push(v)
8661 * 5 while S is not empty
8662 * 6 t <- S.pop()
8663 * 7 if t is what we're looking for:
8664 * 8 return t
8665 * 9 for all edges e in G.adjacentEdges(t) do
8666 * 10 if edge e is already labelled
8667 * 11 continue with the next edge
8668 * 12 w <- G.adjacentVertex(t,e)
8669 * 13 if vertex w is not discovered and not explored
8670 * 14 label e as tree-edge
8671 * 15 label w as discovered
8672 * 16 S.push(w)
8673 * 17 continue at 5
8674 * 18 else if vertex w is discovered
8675 * 19 label e as back-edge
8676 * 20 else
8677 * 21 // vertex w is explored
8678 * 22 label e as forward- or cross-edge
8679 * 23 label t as explored
8680 * 24 S.pop()
8681 *
8682 * convention:
8683 * 0x10 - discovered
8684 * 0x11 - discovered and fall-through edge labelled
8685 * 0x12 - discovered and fall-through and branch edges labelled
8686 * 0x20 - explored
8687 */
8688
8689enum {
8690 DISCOVERED = 0x10,
8691 EXPLORED = 0x20,
8692 FALLTHROUGH = 1,
8693 BRANCH = 2,
8694};
8695
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008696static u32 state_htab_size(struct bpf_verifier_env *env)
8697{
8698 return env->prog->len;
8699}
8700
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008701static struct bpf_verifier_state_list **explored_state(
8702 struct bpf_verifier_env *env,
8703 int idx)
8704{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008705 struct bpf_verifier_state *cur = env->cur_state;
8706 struct bpf_func_state *state = cur->frame[cur->curframe];
8707
8708 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008709}
8710
8711static void init_explored_state(struct bpf_verifier_env *env, int idx)
8712{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008713 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008714}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008715
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008716enum {
8717 DONE_EXPLORING = 0,
8718 KEEP_EXPLORING = 1,
8719};
8720
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008721/* t, w, e - match pseudo-code above:
8722 * t - index of current instruction
8723 * w - next instruction
8724 * e - edge
8725 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07008726static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8727 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008728{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008729 int *insn_stack = env->cfg.insn_stack;
8730 int *insn_state = env->cfg.insn_state;
8731
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008732 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008733 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008734
8735 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008736 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008737
8738 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008739 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008740 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008741 return -EINVAL;
8742 }
8743
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008744 if (e == BRANCH)
8745 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008746 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008747
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008748 if (insn_state[w] == 0) {
8749 /* tree-edge */
8750 insn_state[t] = DISCOVERED | e;
8751 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008752 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008753 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008754 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008755 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008756 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07008757 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008758 return DONE_EXPLORING;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008759 verbose_linfo(env, t, "%d: ", t);
8760 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008761 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008762 return -EINVAL;
8763 } else if (insn_state[w] == EXPLORED) {
8764 /* forward- or cross-edge */
8765 insn_state[t] = DISCOVERED | e;
8766 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008767 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008768 return -EFAULT;
8769 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008770 return DONE_EXPLORING;
8771}
8772
Yonghong Songefdb22d2021-02-26 12:49:20 -08008773static int visit_func_call_insn(int t, int insn_cnt,
8774 struct bpf_insn *insns,
8775 struct bpf_verifier_env *env,
8776 bool visit_callee)
8777{
8778 int ret;
8779
8780 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8781 if (ret)
8782 return ret;
8783
8784 if (t + 1 < insn_cnt)
8785 init_explored_state(env, t + 1);
8786 if (visit_callee) {
8787 init_explored_state(env, t);
8788 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8789 env, false);
8790 }
8791 return ret;
8792}
8793
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008794/* Visits the instruction at index t and returns one of the following:
8795 * < 0 - an error occurred
8796 * DONE_EXPLORING - the instruction was fully explored
8797 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8798 */
8799static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8800{
8801 struct bpf_insn *insns = env->prog->insnsi;
8802 int ret;
8803
Yonghong Song69c087b2021-02-26 12:49:25 -08008804 if (bpf_pseudo_func(insns + t))
8805 return visit_func_call_insn(t, insn_cnt, insns, env, true);
8806
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008807 /* All non-branch instructions have a single fall-through edge. */
8808 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8809 BPF_CLASS(insns[t].code) != BPF_JMP32)
8810 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8811
8812 switch (BPF_OP(insns[t].code)) {
8813 case BPF_EXIT:
8814 return DONE_EXPLORING;
8815
8816 case BPF_CALL:
Yonghong Songefdb22d2021-02-26 12:49:20 -08008817 return visit_func_call_insn(t, insn_cnt, insns, env,
8818 insns[t].src_reg == BPF_PSEUDO_CALL);
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008819
8820 case BPF_JA:
8821 if (BPF_SRC(insns[t].code) != BPF_K)
8822 return -EINVAL;
8823
8824 /* unconditional jump with single edge */
8825 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8826 true);
8827 if (ret)
8828 return ret;
8829
8830 /* unconditional jmp is not a good pruning point,
8831 * but it's marked, since backtracking needs
8832 * to record jmp history in is_state_visited().
8833 */
8834 init_explored_state(env, t + insns[t].off + 1);
8835 /* tell verifier to check for equivalent states
8836 * after every call and jump
8837 */
8838 if (t + 1 < insn_cnt)
8839 init_explored_state(env, t + 1);
8840
8841 return ret;
8842
8843 default:
8844 /* conditional jump with two edges */
8845 init_explored_state(env, t);
8846 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8847 if (ret)
8848 return ret;
8849
8850 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8851 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008852}
8853
8854/* non-recursive depth-first-search to detect loops in BPF program
8855 * loop == back-edge in directed graph
8856 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008857static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008858{
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008859 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008860 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008861 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008862 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008863
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008864 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008865 if (!insn_state)
8866 return -ENOMEM;
8867
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008868 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008869 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008870 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008871 return -ENOMEM;
8872 }
8873
8874 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8875 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008876 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008877
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008878 while (env->cfg.cur_stack > 0) {
8879 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008880
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008881 ret = visit_insn(t, insn_cnt, env);
8882 switch (ret) {
8883 case DONE_EXPLORING:
8884 insn_state[t] = EXPLORED;
8885 env->cfg.cur_stack--;
8886 break;
8887 case KEEP_EXPLORING:
8888 break;
8889 default:
8890 if (ret > 0) {
8891 verbose(env, "visit_insn internal bug\n");
8892 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008893 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008894 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008895 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008896 }
8897
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008898 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008899 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008900 ret = -EFAULT;
8901 goto err_free;
8902 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008903
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008904 for (i = 0; i < insn_cnt; i++) {
8905 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008906 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008907 ret = -EINVAL;
8908 goto err_free;
8909 }
8910 }
8911 ret = 0; /* cfg looks good */
8912
8913err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008914 kvfree(insn_state);
8915 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008916 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008917 return ret;
8918}
8919
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008920static int check_abnormal_return(struct bpf_verifier_env *env)
8921{
8922 int i;
8923
8924 for (i = 1; i < env->subprog_cnt; i++) {
8925 if (env->subprog_info[i].has_ld_abs) {
8926 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8927 return -EINVAL;
8928 }
8929 if (env->subprog_info[i].has_tail_call) {
8930 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8931 return -EINVAL;
8932 }
8933 }
8934 return 0;
8935}
8936
Yonghong Song838e9692018-11-19 15:29:11 -08008937/* The minimum supported BTF func info size */
8938#define MIN_BPF_FUNCINFO_SIZE 8
8939#define MAX_FUNCINFO_REC_SIZE 252
8940
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008941static int check_btf_func(struct bpf_verifier_env *env,
8942 const union bpf_attr *attr,
8943 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08008944{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008945 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008946 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08008947 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008948 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008949 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008950 struct bpf_prog *prog;
8951 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008952 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008953 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008954 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03008955 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08008956
8957 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008958 if (!nfuncs) {
8959 if (check_abnormal_return(env))
8960 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008961 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008962 }
Yonghong Song838e9692018-11-19 15:29:11 -08008963
8964 if (nfuncs != env->subprog_cnt) {
8965 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8966 return -EINVAL;
8967 }
8968
8969 urec_size = attr->func_info_rec_size;
8970 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8971 urec_size > MAX_FUNCINFO_REC_SIZE ||
8972 urec_size % sizeof(u32)) {
8973 verbose(env, "invalid func info rec size %u\n", urec_size);
8974 return -EINVAL;
8975 }
8976
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008977 prog = env->prog;
8978 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008979
8980 urecord = u64_to_user_ptr(attr->func_info);
8981 min_size = min_t(u32, krec_size, urec_size);
8982
Yonghong Songba64e7d2018-11-24 23:20:44 -08008983 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008984 if (!krecord)
8985 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008986 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8987 if (!info_aux)
8988 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008989
Yonghong Song838e9692018-11-19 15:29:11 -08008990 for (i = 0; i < nfuncs; i++) {
8991 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8992 if (ret) {
8993 if (ret == -E2BIG) {
8994 verbose(env, "nonzero tailing record in func info");
8995 /* set the size kernel expects so loader can zero
8996 * out the rest of the record.
8997 */
8998 if (put_user(min_size, &uattr->func_info_rec_size))
8999 ret = -EFAULT;
9000 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009001 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009002 }
9003
Yonghong Songba64e7d2018-11-24 23:20:44 -08009004 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009005 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009006 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009007 }
9008
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009009 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009010 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08009011 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009012 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009013 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009014 "nonzero insn_off %u for the first func info record",
9015 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009016 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009017 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009018 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08009019 verbose(env,
9020 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009021 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009022 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009023 }
9024
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009025 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08009026 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009027 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009028 }
9029
9030 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08009031 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009032 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08009033 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08009034 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009035 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08009036 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009037 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009038
9039 func_proto = btf_type_by_id(btf, type->type);
9040 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
9041 /* btf_func_check() already verified it during BTF load */
9042 goto err_free;
9043 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
9044 scalar_return =
9045 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
9046 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
9047 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
9048 goto err_free;
9049 }
9050 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
9051 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
9052 goto err_free;
9053 }
9054
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08009055 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08009056 urecord += urec_size;
9057 }
9058
Yonghong Songba64e7d2018-11-24 23:20:44 -08009059 prog->aux->func_info = krecord;
9060 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009061 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08009062 return 0;
9063
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009064err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08009065 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009066 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08009067 return ret;
9068}
9069
Yonghong Songba64e7d2018-11-24 23:20:44 -08009070static void adjust_btf_func(struct bpf_verifier_env *env)
9071{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009072 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009073 int i;
9074
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009075 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08009076 return;
9077
9078 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08009079 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08009080}
9081
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009082#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
9083 sizeof(((struct bpf_line_info *)(0))->line_col))
9084#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
9085
9086static int check_btf_line(struct bpf_verifier_env *env,
9087 const union bpf_attr *attr,
9088 union bpf_attr __user *uattr)
9089{
9090 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
9091 struct bpf_subprog_info *sub;
9092 struct bpf_line_info *linfo;
9093 struct bpf_prog *prog;
9094 const struct btf *btf;
9095 void __user *ulinfo;
9096 int err;
9097
9098 nr_linfo = attr->line_info_cnt;
9099 if (!nr_linfo)
9100 return 0;
9101
9102 rec_size = attr->line_info_rec_size;
9103 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
9104 rec_size > MAX_LINEINFO_REC_SIZE ||
9105 rec_size & (sizeof(u32) - 1))
9106 return -EINVAL;
9107
9108 /* Need to zero it in case the userspace may
9109 * pass in a smaller bpf_line_info object.
9110 */
9111 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
9112 GFP_KERNEL | __GFP_NOWARN);
9113 if (!linfo)
9114 return -ENOMEM;
9115
9116 prog = env->prog;
9117 btf = prog->aux->btf;
9118
9119 s = 0;
9120 sub = env->subprog_info;
9121 ulinfo = u64_to_user_ptr(attr->line_info);
9122 expected_size = sizeof(struct bpf_line_info);
9123 ncopy = min_t(u32, expected_size, rec_size);
9124 for (i = 0; i < nr_linfo; i++) {
9125 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
9126 if (err) {
9127 if (err == -E2BIG) {
9128 verbose(env, "nonzero tailing record in line_info");
9129 if (put_user(expected_size,
9130 &uattr->line_info_rec_size))
9131 err = -EFAULT;
9132 }
9133 goto err_free;
9134 }
9135
9136 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
9137 err = -EFAULT;
9138 goto err_free;
9139 }
9140
9141 /*
9142 * Check insn_off to ensure
9143 * 1) strictly increasing AND
9144 * 2) bounded by prog->len
9145 *
9146 * The linfo[0].insn_off == 0 check logically falls into
9147 * the later "missing bpf_line_info for func..." case
9148 * because the first linfo[0].insn_off must be the
9149 * first sub also and the first sub must have
9150 * subprog_info[0].start == 0.
9151 */
9152 if ((i && linfo[i].insn_off <= prev_offset) ||
9153 linfo[i].insn_off >= prog->len) {
9154 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9155 i, linfo[i].insn_off, prev_offset,
9156 prog->len);
9157 err = -EINVAL;
9158 goto err_free;
9159 }
9160
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08009161 if (!prog->insnsi[linfo[i].insn_off].code) {
9162 verbose(env,
9163 "Invalid insn code at line_info[%u].insn_off\n",
9164 i);
9165 err = -EINVAL;
9166 goto err_free;
9167 }
9168
Martin KaFai Lau23127b32018-12-13 10:41:46 -08009169 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9170 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009171 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9172 err = -EINVAL;
9173 goto err_free;
9174 }
9175
9176 if (s != env->subprog_cnt) {
9177 if (linfo[i].insn_off == sub[s].start) {
9178 sub[s].linfo_idx = i;
9179 s++;
9180 } else if (sub[s].start < linfo[i].insn_off) {
9181 verbose(env, "missing bpf_line_info for func#%u\n", s);
9182 err = -EINVAL;
9183 goto err_free;
9184 }
9185 }
9186
9187 prev_offset = linfo[i].insn_off;
9188 ulinfo += rec_size;
9189 }
9190
9191 if (s != env->subprog_cnt) {
9192 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9193 env->subprog_cnt - s, s);
9194 err = -EINVAL;
9195 goto err_free;
9196 }
9197
9198 prog->aux->linfo = linfo;
9199 prog->aux->nr_linfo = nr_linfo;
9200
9201 return 0;
9202
9203err_free:
9204 kvfree(linfo);
9205 return err;
9206}
9207
9208static int check_btf_info(struct bpf_verifier_env *env,
9209 const union bpf_attr *attr,
9210 union bpf_attr __user *uattr)
9211{
9212 struct btf *btf;
9213 int err;
9214
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009215 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9216 if (check_abnormal_return(env))
9217 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009218 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009219 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009220
9221 btf = btf_get_by_fd(attr->prog_btf_fd);
9222 if (IS_ERR(btf))
9223 return PTR_ERR(btf);
9224 env->prog->aux->btf = btf;
9225
9226 err = check_btf_func(env, attr, uattr);
9227 if (err)
9228 return err;
9229
9230 err = check_btf_line(env, attr, uattr);
9231 if (err)
9232 return err;
9233
9234 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009235}
9236
Edward Creef1174f72017-08-07 15:26:19 +01009237/* check %cur's range satisfies %old's */
9238static bool range_within(struct bpf_reg_state *old,
9239 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009240{
Edward Creeb03c9f92017-08-07 15:26:36 +01009241 return old->umin_value <= cur->umin_value &&
9242 old->umax_value >= cur->umax_value &&
9243 old->smin_value <= cur->smin_value &&
Daniel Borkmannfd675182021-02-05 20:48:21 +01009244 old->smax_value >= cur->smax_value &&
9245 old->u32_min_value <= cur->u32_min_value &&
9246 old->u32_max_value >= cur->u32_max_value &&
9247 old->s32_min_value <= cur->s32_min_value &&
9248 old->s32_max_value >= cur->s32_max_value;
Edward Creef1174f72017-08-07 15:26:19 +01009249}
9250
9251/* Maximum number of register states that can exist at once */
9252#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9253struct idpair {
9254 u32 old;
9255 u32 cur;
9256};
9257
9258/* If in the old state two registers had the same id, then they need to have
9259 * the same id in the new state as well. But that id could be different from
9260 * the old state, so we need to track the mapping from old to new ids.
9261 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9262 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9263 * regs with a different old id could still have new id 9, we don't care about
9264 * that.
9265 * So we look through our idmap to see if this old id has been seen before. If
9266 * so, we require the new id to match; otherwise, we add the id pair to the map.
9267 */
9268static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9269{
9270 unsigned int i;
9271
9272 for (i = 0; i < ID_MAP_SIZE; i++) {
9273 if (!idmap[i].old) {
9274 /* Reached an empty slot; haven't seen this id before */
9275 idmap[i].old = old_id;
9276 idmap[i].cur = cur_id;
9277 return true;
9278 }
9279 if (idmap[i].old == old_id)
9280 return idmap[i].cur == cur_id;
9281 }
9282 /* We ran out of idmap slots, which should be impossible */
9283 WARN_ON_ONCE(1);
9284 return false;
9285}
9286
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009287static void clean_func_state(struct bpf_verifier_env *env,
9288 struct bpf_func_state *st)
9289{
9290 enum bpf_reg_liveness live;
9291 int i, j;
9292
9293 for (i = 0; i < BPF_REG_FP; i++) {
9294 live = st->regs[i].live;
9295 /* liveness must not touch this register anymore */
9296 st->regs[i].live |= REG_LIVE_DONE;
9297 if (!(live & REG_LIVE_READ))
9298 /* since the register is unused, clear its state
9299 * to make further comparison simpler
9300 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009301 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009302 }
9303
9304 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9305 live = st->stack[i].spilled_ptr.live;
9306 /* liveness must not touch this stack slot anymore */
9307 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9308 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009309 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009310 for (j = 0; j < BPF_REG_SIZE; j++)
9311 st->stack[i].slot_type[j] = STACK_INVALID;
9312 }
9313 }
9314}
9315
9316static void clean_verifier_state(struct bpf_verifier_env *env,
9317 struct bpf_verifier_state *st)
9318{
9319 int i;
9320
9321 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9322 /* all regs in this state in all frames were already marked */
9323 return;
9324
9325 for (i = 0; i <= st->curframe; i++)
9326 clean_func_state(env, st->frame[i]);
9327}
9328
9329/* the parentage chains form a tree.
9330 * the verifier states are added to state lists at given insn and
9331 * pushed into state stack for future exploration.
9332 * when the verifier reaches bpf_exit insn some of the verifer states
9333 * stored in the state lists have their final liveness state already,
9334 * but a lot of states will get revised from liveness point of view when
9335 * the verifier explores other branches.
9336 * Example:
9337 * 1: r0 = 1
9338 * 2: if r1 == 100 goto pc+1
9339 * 3: r0 = 2
9340 * 4: exit
9341 * when the verifier reaches exit insn the register r0 in the state list of
9342 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9343 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9344 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9345 *
9346 * Since the verifier pushes the branch states as it sees them while exploring
9347 * the program the condition of walking the branch instruction for the second
9348 * time means that all states below this branch were already explored and
9349 * their final liveness markes are already propagated.
9350 * Hence when the verifier completes the search of state list in is_state_visited()
9351 * we can call this clean_live_states() function to mark all liveness states
9352 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9353 * will not be used.
9354 * This function also clears the registers and stack for states that !READ
9355 * to simplify state merging.
9356 *
9357 * Important note here that walking the same branch instruction in the callee
9358 * doesn't meant that the states are DONE. The verifier has to compare
9359 * the callsites
9360 */
9361static void clean_live_states(struct bpf_verifier_env *env, int insn,
9362 struct bpf_verifier_state *cur)
9363{
9364 struct bpf_verifier_state_list *sl;
9365 int i;
9366
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009367 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009368 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009369 if (sl->state.branches)
9370 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009371 if (sl->state.insn_idx != insn ||
9372 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009373 goto next;
9374 for (i = 0; i <= cur->curframe; i++)
9375 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9376 goto next;
9377 clean_verifier_state(env, &sl->state);
9378next:
9379 sl = sl->next;
9380 }
9381}
9382
Edward Creef1174f72017-08-07 15:26:19 +01009383/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01009384static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9385 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009386{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009387 bool equal;
9388
Edward Creedc503a82017-08-15 20:34:35 +01009389 if (!(rold->live & REG_LIVE_READ))
9390 /* explored state didn't use this */
9391 return true;
9392
Edward Cree679c7822018-08-22 20:02:19 +01009393 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009394
9395 if (rold->type == PTR_TO_STACK)
9396 /* two stack pointers are equal only if they're pointing to
9397 * the same stack frame, since fp-8 in foo != fp-8 in bar
9398 */
9399 return equal && rold->frameno == rcur->frameno;
9400
9401 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01009402 return true;
9403
9404 if (rold->type == NOT_INIT)
9405 /* explored state can't have used this */
9406 return true;
9407 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009408 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009409 switch (rold->type) {
9410 case SCALAR_VALUE:
9411 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009412 if (!rold->precise && !rcur->precise)
9413 return true;
Edward Creef1174f72017-08-07 15:26:19 +01009414 /* new val must satisfy old val knowledge */
9415 return range_within(rold, rcur) &&
9416 tnum_in(rold->var_off, rcur->var_off);
9417 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08009418 /* We're trying to use a pointer in place of a scalar.
9419 * Even if the scalar was unbounded, this could lead to
9420 * pointer leaks because scalars are allowed to leak
9421 * while pointers are not. We could make this safe in
9422 * special cases if root is calling us, but it's
9423 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01009424 */
Jann Horn179d1c52017-12-18 20:11:59 -08009425 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009426 }
Yonghong Song69c087b2021-02-26 12:49:25 -08009427 case PTR_TO_MAP_KEY:
Edward Creef1174f72017-08-07 15:26:19 +01009428 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01009429 /* If the new min/max/var_off satisfy the old ones and
9430 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009431 * 'id' is not compared, since it's only used for maps with
9432 * bpf_spin_lock inside map element and in such cases if
9433 * the rest of the prog is valid for one map element then
9434 * it's valid for all map elements regardless of the key
9435 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01009436 */
9437 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9438 range_within(rold, rcur) &&
9439 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01009440 case PTR_TO_MAP_VALUE_OR_NULL:
9441 /* a PTR_TO_MAP_VALUE could be safe to use as a
9442 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9443 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9444 * checked, doing so could have affected others with the same
9445 * id, and we can't check for that because we lost the id when
9446 * we converted to a PTR_TO_MAP_VALUE.
9447 */
9448 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9449 return false;
9450 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9451 return false;
9452 /* Check our ids match any regs they're supposed to */
9453 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009454 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01009455 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009456 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01009457 return false;
9458 /* We must have at least as much range as the old ptr
9459 * did, so that any accesses which were safe before are
9460 * still safe. This is true even if old range < old off,
9461 * since someone could have accessed through (ptr - k), or
9462 * even done ptr -= k in a register, to get a safe access.
9463 */
9464 if (rold->range > rcur->range)
9465 return false;
9466 /* If the offsets don't match, we can't trust our alignment;
9467 * nor can we be sure that we won't fall out of range.
9468 */
9469 if (rold->off != rcur->off)
9470 return false;
9471 /* id relations must be preserved */
9472 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9473 return false;
9474 /* new val must satisfy old val knowledge */
9475 return range_within(rold, rcur) &&
9476 tnum_in(rold->var_off, rcur->var_off);
9477 case PTR_TO_CTX:
9478 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01009479 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07009480 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07009481 case PTR_TO_SOCKET:
9482 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009483 case PTR_TO_SOCK_COMMON:
9484 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009485 case PTR_TO_TCP_SOCK:
9486 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009487 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01009488 /* Only valid matches are exact, which memcmp() above
9489 * would have accepted
9490 */
9491 default:
9492 /* Don't know what's going on, just say it's not safe */
9493 return false;
9494 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009495
Edward Creef1174f72017-08-07 15:26:19 +01009496 /* Shouldn't get here; if we do, say it's not safe */
9497 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009498 return false;
9499}
9500
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009501static bool stacksafe(struct bpf_func_state *old,
9502 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009503 struct idpair *idmap)
9504{
9505 int i, spi;
9506
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009507 /* walk slots of the explored stack and ignore any additional
9508 * slots in the current stack, since explored(safe) state
9509 * didn't use them
9510 */
9511 for (i = 0; i < old->allocated_stack; i++) {
9512 spi = i / BPF_REG_SIZE;
9513
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009514 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9515 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009516 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00009517 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009518 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009519
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009520 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9521 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08009522
9523 /* explored stack has more populated slots than current stack
9524 * and these slots were used
9525 */
9526 if (i >= cur->allocated_stack)
9527 return false;
9528
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009529 /* if old state was safe with misc data in the stack
9530 * it will be safe with zero-initialized stack.
9531 * The opposite is not true
9532 */
9533 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9534 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9535 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009536 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9537 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9538 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07009539 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009540 * this verifier states are not equivalent,
9541 * return false to continue verification of this path
9542 */
9543 return false;
9544 if (i % BPF_REG_SIZE)
9545 continue;
9546 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9547 continue;
9548 if (!regsafe(&old->stack[spi].spilled_ptr,
9549 &cur->stack[spi].spilled_ptr,
9550 idmap))
9551 /* when explored and current stack slot are both storing
9552 * spilled registers, check that stored pointers types
9553 * are the same as well.
9554 * Ex: explored safe path could have stored
9555 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9556 * but current path has stored:
9557 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9558 * such verifier states are not equivalent.
9559 * return false to continue verification of this path
9560 */
9561 return false;
9562 }
9563 return true;
9564}
9565
Joe Stringerfd978bf72018-10-02 13:35:35 -07009566static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9567{
9568 if (old->acquired_refs != cur->acquired_refs)
9569 return false;
9570 return !memcmp(old->refs, cur->refs,
9571 sizeof(*old->refs) * old->acquired_refs);
9572}
9573
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009574/* compare two verifier states
9575 *
9576 * all states stored in state_list are known to be valid, since
9577 * verifier reached 'bpf_exit' instruction through them
9578 *
9579 * this function is called when verifier exploring different branches of
9580 * execution popped from the state stack. If it sees an old state that has
9581 * more strict register state and more strict stack state then this execution
9582 * branch doesn't need to be explored further, since verifier already
9583 * concluded that more strict state leads to valid finish.
9584 *
9585 * Therefore two states are equivalent if register state is more conservative
9586 * and explored stack state is more conservative than the current one.
9587 * Example:
9588 * explored current
9589 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9590 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9591 *
9592 * In other words if current stack state (one being explored) has more
9593 * valid slots than old one that already passed validation, it means
9594 * the verifier can stop exploring and conclude that current state is valid too
9595 *
9596 * Similarly with registers. If explored state has register type as invalid
9597 * whereas register type in current state is meaningful, it means that
9598 * the current state will reach 'bpf_exit' instruction safely
9599 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009600static bool func_states_equal(struct bpf_func_state *old,
9601 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009602{
Edward Creef1174f72017-08-07 15:26:19 +01009603 struct idpair *idmap;
9604 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009605 int i;
9606
Edward Creef1174f72017-08-07 15:26:19 +01009607 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9608 /* If we failed to allocate the idmap, just say it's not safe */
9609 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009610 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009611
9612 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01009613 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01009614 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009615 }
9616
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009617 if (!stacksafe(old, cur, idmap))
9618 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009619
9620 if (!refsafe(old, cur))
9621 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01009622 ret = true;
9623out_free:
9624 kfree(idmap);
9625 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009626}
9627
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009628static bool states_equal(struct bpf_verifier_env *env,
9629 struct bpf_verifier_state *old,
9630 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01009631{
Edward Creedc503a82017-08-15 20:34:35 +01009632 int i;
9633
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009634 if (old->curframe != cur->curframe)
9635 return false;
9636
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009637 /* Verification state from speculative execution simulation
9638 * must never prune a non-speculative execution one.
9639 */
9640 if (old->speculative && !cur->speculative)
9641 return false;
9642
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009643 if (old->active_spin_lock != cur->active_spin_lock)
9644 return false;
9645
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009646 /* for states to be equal callsites have to be the same
9647 * and all frame states need to be equivalent
9648 */
9649 for (i = 0; i <= old->curframe; i++) {
9650 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9651 return false;
9652 if (!func_states_equal(old->frame[i], cur->frame[i]))
9653 return false;
9654 }
9655 return true;
9656}
9657
Jiong Wang5327ed32019-05-24 23:25:12 +01009658/* Return 0 if no propagation happened. Return negative error code if error
9659 * happened. Otherwise, return the propagated bit.
9660 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009661static int propagate_liveness_reg(struct bpf_verifier_env *env,
9662 struct bpf_reg_state *reg,
9663 struct bpf_reg_state *parent_reg)
9664{
Jiong Wang5327ed32019-05-24 23:25:12 +01009665 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9666 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009667 int err;
9668
Jiong Wang5327ed32019-05-24 23:25:12 +01009669 /* When comes here, read flags of PARENT_REG or REG could be any of
9670 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9671 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9672 */
9673 if (parent_flag == REG_LIVE_READ64 ||
9674 /* Or if there is no read flag from REG. */
9675 !flag ||
9676 /* Or if the read flag from REG is the same as PARENT_REG. */
9677 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009678 return 0;
9679
Jiong Wang5327ed32019-05-24 23:25:12 +01009680 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009681 if (err)
9682 return err;
9683
Jiong Wang5327ed32019-05-24 23:25:12 +01009684 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009685}
9686
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009687/* A write screens off any subsequent reads; but write marks come from the
9688 * straight-line code between a state and its parent. When we arrive at an
9689 * equivalent state (jump target or such) we didn't arrive by the straight-line
9690 * code, so read marks in the state must propagate to the parent regardless
9691 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01009692 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009693 */
9694static int propagate_liveness(struct bpf_verifier_env *env,
9695 const struct bpf_verifier_state *vstate,
9696 struct bpf_verifier_state *vparent)
9697{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009698 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009699 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009700 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009701
9702 if (vparent->curframe != vstate->curframe) {
9703 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9704 vparent->curframe, vstate->curframe);
9705 return -EFAULT;
9706 }
Edward Creedc503a82017-08-15 20:34:35 +01009707 /* Propagate read liveness of registers... */
9708 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07009709 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009710 parent = vparent->frame[frame];
9711 state = vstate->frame[frame];
9712 parent_reg = parent->regs;
9713 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07009714 /* We don't need to worry about FP liveness, it's read-only */
9715 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009716 err = propagate_liveness_reg(env, &state_reg[i],
9717 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01009718 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009719 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01009720 if (err == REG_LIVE_READ64)
9721 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009722 }
Edward Creedc503a82017-08-15 20:34:35 +01009723
Jiong Wang1b04aee2019-04-12 22:59:34 +01009724 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009725 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9726 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009727 parent_reg = &parent->stack[i].spilled_ptr;
9728 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009729 err = propagate_liveness_reg(env, state_reg,
9730 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01009731 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009732 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009733 }
Edward Creedc503a82017-08-15 20:34:35 +01009734 }
Jiong Wang5327ed32019-05-24 23:25:12 +01009735 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01009736}
9737
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009738/* find precise scalars in the previous equivalent state and
9739 * propagate them into the current state
9740 */
9741static int propagate_precision(struct bpf_verifier_env *env,
9742 const struct bpf_verifier_state *old)
9743{
9744 struct bpf_reg_state *state_reg;
9745 struct bpf_func_state *state;
9746 int i, err = 0;
9747
9748 state = old->frame[old->curframe];
9749 state_reg = state->regs;
9750 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9751 if (state_reg->type != SCALAR_VALUE ||
9752 !state_reg->precise)
9753 continue;
9754 if (env->log.level & BPF_LOG_LEVEL2)
9755 verbose(env, "propagating r%d\n", i);
9756 err = mark_chain_precision(env, i);
9757 if (err < 0)
9758 return err;
9759 }
9760
9761 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9762 if (state->stack[i].slot_type[0] != STACK_SPILL)
9763 continue;
9764 state_reg = &state->stack[i].spilled_ptr;
9765 if (state_reg->type != SCALAR_VALUE ||
9766 !state_reg->precise)
9767 continue;
9768 if (env->log.level & BPF_LOG_LEVEL2)
9769 verbose(env, "propagating fp%d\n",
9770 (-i - 1) * BPF_REG_SIZE);
9771 err = mark_chain_precision_stack(env, i);
9772 if (err < 0)
9773 return err;
9774 }
9775 return 0;
9776}
9777
Alexei Starovoitov25897262019-06-15 12:12:20 -07009778static bool states_maybe_looping(struct bpf_verifier_state *old,
9779 struct bpf_verifier_state *cur)
9780{
9781 struct bpf_func_state *fold, *fcur;
9782 int i, fr = cur->curframe;
9783
9784 if (old->curframe != fr)
9785 return false;
9786
9787 fold = old->frame[fr];
9788 fcur = cur->frame[fr];
9789 for (i = 0; i < MAX_BPF_REG; i++)
9790 if (memcmp(&fold->regs[i], &fcur->regs[i],
9791 offsetof(struct bpf_reg_state, parent)))
9792 return false;
9793 return true;
9794}
9795
9796
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009797static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009798{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009799 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009800 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01009801 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009802 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07009803 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009804
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009805 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009806 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009807 /* this 'insn_idx' instruction wasn't marked, so we will not
9808 * be doing state search here
9809 */
9810 return 0;
9811
Alexei Starovoitov25897262019-06-15 12:12:20 -07009812 /* bpf progs typically have pruning point every 4 instructions
9813 * http://vger.kernel.org/bpfconf2019.html#session-1
9814 * Do not add new state for future pruning if the verifier hasn't seen
9815 * at least 2 jumps and at least 8 instructions.
9816 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9817 * In tests that amounts to up to 50% reduction into total verifier
9818 * memory consumption and 20% verifier time speedup.
9819 */
9820 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9821 env->insn_processed - env->prev_insn_processed >= 8)
9822 add_new_state = true;
9823
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009824 pprev = explored_state(env, insn_idx);
9825 sl = *pprev;
9826
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009827 clean_live_states(env, insn_idx, cur);
9828
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009829 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009830 states_cnt++;
9831 if (sl->state.insn_idx != insn_idx)
9832 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009833 if (sl->state.branches) {
9834 if (states_maybe_looping(&sl->state, cur) &&
9835 states_equal(env, &sl->state, cur)) {
9836 verbose_linfo(env, insn_idx, "; ");
9837 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9838 return -EINVAL;
9839 }
9840 /* if the verifier is processing a loop, avoid adding new state
9841 * too often, since different loop iterations have distinct
9842 * states and may not help future pruning.
9843 * This threshold shouldn't be too low to make sure that
9844 * a loop with large bound will be rejected quickly.
9845 * The most abusive loop will be:
9846 * r1 += 1
9847 * if r1 < 1000000 goto pc-2
9848 * 1M insn_procssed limit / 100 == 10k peak states.
9849 * This threshold shouldn't be too high either, since states
9850 * at the end of the loop are likely to be useful in pruning.
9851 */
9852 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9853 env->insn_processed - env->prev_insn_processed < 100)
9854 add_new_state = false;
9855 goto miss;
9856 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009857 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009858 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009859 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01009860 * prune the search.
9861 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009862 * If we have any write marks in env->cur_state, they
9863 * will prevent corresponding reads in the continuation
9864 * from reaching our parent (an explored_state). Our
9865 * own state will get the read marks recorded, but
9866 * they'll be immediately forgotten as we're pruning
9867 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009868 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009869 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009870
9871 /* if previous state reached the exit with precision and
9872 * current state is equivalent to it (except precsion marks)
9873 * the precision needs to be propagated back in
9874 * the current state.
9875 */
9876 err = err ? : push_jmp_history(env, cur);
9877 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009878 if (err)
9879 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009880 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01009881 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07009882miss:
9883 /* when new state is not going to be added do not increase miss count.
9884 * Otherwise several loop iterations will remove the state
9885 * recorded earlier. The goal of these heuristics is to have
9886 * states from some iterations of the loop (some in the beginning
9887 * and some at the end) to help pruning.
9888 */
9889 if (add_new_state)
9890 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009891 /* heuristic to determine whether this state is beneficial
9892 * to keep checking from state equivalence point of view.
9893 * Higher numbers increase max_states_per_insn and verification time,
9894 * but do not meaningfully decrease insn_processed.
9895 */
9896 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9897 /* the state is unlikely to be useful. Remove it to
9898 * speed up verification
9899 */
9900 *pprev = sl->next;
9901 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009902 u32 br = sl->state.branches;
9903
9904 WARN_ONCE(br,
9905 "BUG live_done but branches_to_explore %d\n",
9906 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009907 free_verifier_state(&sl->state, false);
9908 kfree(sl);
9909 env->peak_states--;
9910 } else {
9911 /* cannot free this state, since parentage chain may
9912 * walk it later. Add it for free_list instead to
9913 * be freed at the end of verification
9914 */
9915 sl->next = env->free_list;
9916 env->free_list = sl;
9917 }
9918 sl = *pprev;
9919 continue;
9920 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009921next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009922 pprev = &sl->next;
9923 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009924 }
9925
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009926 if (env->max_states_per_insn < states_cnt)
9927 env->max_states_per_insn = states_cnt;
9928
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009929 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009930 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009931
Alexei Starovoitov25897262019-06-15 12:12:20 -07009932 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009933 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07009934
9935 /* There were no equivalent states, remember the current one.
9936 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009937 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009938 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009939 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009940 * again on the way to bpf_exit.
9941 * When looping the sl->state.branches will be > 0 and this state
9942 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009943 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009944 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009945 if (!new_sl)
9946 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009947 env->total_states++;
9948 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009949 env->prev_jmps_processed = env->jmps_processed;
9950 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009951
9952 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01009953 new = &new_sl->state;
9954 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009955 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01009956 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009957 kfree(new_sl);
9958 return err;
9959 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009960 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009961 WARN_ONCE(new->branches != 1,
9962 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009963
Alexei Starovoitov25897262019-06-15 12:12:20 -07009964 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009965 cur->first_insn_idx = insn_idx;
9966 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009967 new_sl->next = *explored_state(env, insn_idx);
9968 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08009969 /* connect new state to parentage chain. Current frame needs all
9970 * registers connected. Only r6 - r9 of the callers are alive (pushed
9971 * to the stack implicitly by JITs) so in callers' frames connect just
9972 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9973 * the state of the call instruction (with WRITTEN set), and r0 comes
9974 * from callee with its full parentage chain, anyway.
9975 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009976 /* clear write marks in current state: the writes we did are not writes
9977 * our child did, so they don't screen off its reads from us.
9978 * (There are no read marks in current state, because reads always mark
9979 * their parent and current state never has children yet. Only
9980 * explored_states can get read marks.)
9981 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07009982 for (j = 0; j <= cur->curframe; j++) {
9983 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9984 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9985 for (i = 0; i < BPF_REG_FP; i++)
9986 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9987 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009988
9989 /* all stack frames are accessible from callee, clear them all */
9990 for (j = 0; j <= cur->curframe; j++) {
9991 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01009992 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009993
Edward Cree679c7822018-08-22 20:02:19 +01009994 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009995 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01009996 frame->stack[i].spilled_ptr.parent =
9997 &newframe->stack[i].spilled_ptr;
9998 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009999 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010000 return 0;
10001}
10002
Joe Stringerc64b7982018-10-02 13:35:33 -070010003/* Return true if it's OK to have the same insn return a different type. */
10004static bool reg_type_mismatch_ok(enum bpf_reg_type type)
10005{
10006 switch (type) {
10007 case PTR_TO_CTX:
10008 case PTR_TO_SOCKET:
10009 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010010 case PTR_TO_SOCK_COMMON:
10011 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010012 case PTR_TO_TCP_SOCK:
10013 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010014 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -070010015 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -070010016 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -070010017 return false;
10018 default:
10019 return true;
10020 }
10021}
10022
10023/* If an instruction was previously used with particular pointer types, then we
10024 * need to be careful to avoid cases such as the below, where it may be ok
10025 * for one branch accessing the pointer, but not ok for the other branch:
10026 *
10027 * R1 = sock_ptr
10028 * goto X;
10029 * ...
10030 * R1 = some_other_valid_ptr;
10031 * goto X;
10032 * ...
10033 * R2 = *(u32 *)(R1 + 0);
10034 */
10035static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
10036{
10037 return src != prev && (!reg_type_mismatch_ok(src) ||
10038 !reg_type_mismatch_ok(prev));
10039}
10040
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010041static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010042{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010043 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010044 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010045 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010046 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010047 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010048 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010049 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010050
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010051 for (;;) {
10052 struct bpf_insn *insn;
10053 u8 class;
10054 int err;
10055
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010056 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010057 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010058 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010059 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010060 return -EFAULT;
10061 }
10062
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010063 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010064 class = BPF_CLASS(insn->code);
10065
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010066 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010067 verbose(env,
10068 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010069 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010070 return -E2BIG;
10071 }
10072
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010073 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010074 if (err < 0)
10075 return err;
10076 if (err == 1) {
10077 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010078 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010079 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010080 verbose(env, "\nfrom %d to %d%s: safe\n",
10081 env->prev_insn_idx, env->insn_idx,
10082 env->cur_state->speculative ?
10083 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010084 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010085 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010086 }
10087 goto process_bpf_exit;
10088 }
10089
Alexei Starovoitovc3494802018-12-03 22:46:04 -080010090 if (signal_pending(current))
10091 return -EAGAIN;
10092
Daniel Borkmann3c2ce602017-05-18 03:00:06 +020010093 if (need_resched())
10094 cond_resched();
10095
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010096 if (env->log.level & BPF_LOG_LEVEL2 ||
10097 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
10098 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010099 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -070010100 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010101 verbose(env, "\nfrom %d to %d%s:",
10102 env->prev_insn_idx, env->insn_idx,
10103 env->cur_state->speculative ?
10104 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010105 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010106 do_print_state = false;
10107 }
10108
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070010109 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010010110 const struct bpf_insn_cbs cbs = {
10111 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +010010112 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +010010113 };
10114
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010115 verbose_linfo(env, env->insn_idx, "; ");
10116 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +010010117 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010118 }
10119
Jakub Kicinskicae19272017-12-27 18:39:05 -080010120 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010121 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
10122 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -080010123 if (err)
10124 return err;
10125 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +010010126
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010127 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010128 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010129 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -070010130
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010131 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -070010132 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010133 if (err)
10134 return err;
10135
10136 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010137 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010138
10139 /* check for reserved fields is already done */
10140
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010141 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010142 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010143 if (err)
10144 return err;
10145
Edward Creedc503a82017-08-15 20:34:35 +010010146 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010147 if (err)
10148 return err;
10149
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -070010150 src_reg_type = regs[insn->src_reg].type;
10151
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010152 /* check that memory (src_reg + off) is readable,
10153 * the state of dst_reg will be updated by this func
10154 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010155 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10156 insn->off, BPF_SIZE(insn->code),
10157 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010158 if (err)
10159 return err;
10160
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010161 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010162
10163 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010164 /* saw a valid insn
10165 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010166 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010167 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010168 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010169
Joe Stringerc64b7982018-10-02 13:35:33 -070010170 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010171 /* ABuser program is trying to use the same insn
10172 * dst_reg = *(u32*) (src_reg + off)
10173 * with different pointer types:
10174 * src_reg == ctx in one branch and
10175 * src_reg == stack|map in some other branch.
10176 * Reject it.
10177 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010178 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010179 return -EINVAL;
10180 }
10181
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010182 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010183 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010184
Brendan Jackman91c960b2021-01-14 18:17:44 +000010185 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10186 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010187 if (err)
10188 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010189 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010190 continue;
10191 }
10192
Brendan Jackman5ca419f2021-01-14 18:17:46 +000010193 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10194 verbose(env, "BPF_STX uses reserved fields\n");
10195 return -EINVAL;
10196 }
10197
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010198 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010199 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010200 if (err)
10201 return err;
10202 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010203 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010204 if (err)
10205 return err;
10206
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010207 dst_reg_type = regs[insn->dst_reg].type;
10208
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010209 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010210 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10211 insn->off, BPF_SIZE(insn->code),
10212 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010213 if (err)
10214 return err;
10215
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010216 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010217
10218 if (*prev_dst_type == NOT_INIT) {
10219 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070010220 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010221 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010222 return -EINVAL;
10223 }
10224
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010225 } else if (class == BPF_ST) {
10226 if (BPF_MODE(insn->code) != BPF_MEM ||
10227 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010228 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010229 return -EINVAL;
10230 }
10231 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010232 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010233 if (err)
10234 return err;
10235
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010236 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070010237 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020010238 insn->dst_reg,
10239 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010240 return -EACCES;
10241 }
10242
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010243 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010244 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10245 insn->off, BPF_SIZE(insn->code),
10246 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010247 if (err)
10248 return err;
10249
Jiong Wang092ed092019-01-26 12:26:01 -050010250 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010251 u8 opcode = BPF_OP(insn->code);
10252
Alexei Starovoitov25897262019-06-15 12:12:20 -070010253 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010254 if (opcode == BPF_CALL) {
10255 if (BPF_SRC(insn->code) != BPF_K ||
10256 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010257 (insn->src_reg != BPF_REG_0 &&
10258 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050010259 insn->dst_reg != BPF_REG_0 ||
10260 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010261 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010262 return -EINVAL;
10263 }
10264
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010265 if (env->cur_state->active_spin_lock &&
10266 (insn->src_reg == BPF_PSEUDO_CALL ||
10267 insn->imm != BPF_FUNC_spin_unlock)) {
10268 verbose(env, "function calls are not allowed while holding a lock\n");
10269 return -EINVAL;
10270 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010271 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010272 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010273 else
Yonghong Song69c087b2021-02-26 12:49:25 -080010274 err = check_helper_call(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010275 if (err)
10276 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010277 } else if (opcode == BPF_JA) {
10278 if (BPF_SRC(insn->code) != BPF_K ||
10279 insn->imm != 0 ||
10280 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010281 insn->dst_reg != BPF_REG_0 ||
10282 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010283 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010284 return -EINVAL;
10285 }
10286
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010287 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010288 continue;
10289
10290 } else if (opcode == BPF_EXIT) {
10291 if (BPF_SRC(insn->code) != BPF_K ||
10292 insn->imm != 0 ||
10293 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010294 insn->dst_reg != BPF_REG_0 ||
10295 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010296 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010297 return -EINVAL;
10298 }
10299
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010300 if (env->cur_state->active_spin_lock) {
10301 verbose(env, "bpf_spin_unlock is missing\n");
10302 return -EINVAL;
10303 }
10304
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010305 if (state->curframe) {
10306 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010307 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010308 if (err)
10309 return err;
10310 do_print_state = true;
10311 continue;
10312 }
10313
Joe Stringerfd978bf72018-10-02 13:35:35 -070010314 err = check_reference_leak(env);
10315 if (err)
10316 return err;
10317
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070010318 err = check_return_code(env);
10319 if (err)
10320 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010321process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -070010322 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010323 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010324 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010325 if (err < 0) {
10326 if (err != -ENOENT)
10327 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010328 break;
10329 } else {
10330 do_print_state = true;
10331 continue;
10332 }
10333 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010334 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010335 if (err)
10336 return err;
10337 }
10338 } else if (class == BPF_LD) {
10339 u8 mode = BPF_MODE(insn->code);
10340
10341 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080010342 err = check_ld_abs(env, insn);
10343 if (err)
10344 return err;
10345
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010346 } else if (mode == BPF_IMM) {
10347 err = check_ld_imm(env, insn);
10348 if (err)
10349 return err;
10350
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010351 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010352 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010353 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010354 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010355 return -EINVAL;
10356 }
10357 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010358 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010359 return -EINVAL;
10360 }
10361
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010362 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010363 }
10364
10365 return 0;
10366}
10367
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010368static int find_btf_percpu_datasec(struct btf *btf)
10369{
10370 const struct btf_type *t;
10371 const char *tname;
10372 int i, n;
10373
10374 /*
10375 * Both vmlinux and module each have their own ".data..percpu"
10376 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10377 * types to look at only module's own BTF types.
10378 */
10379 n = btf_nr_types(btf);
10380 if (btf_is_module(btf))
10381 i = btf_nr_types(btf_vmlinux);
10382 else
10383 i = 1;
10384
10385 for(; i < n; i++) {
10386 t = btf_type_by_id(btf, i);
10387 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10388 continue;
10389
10390 tname = btf_name_by_offset(btf, t->name_off);
10391 if (!strcmp(tname, ".data..percpu"))
10392 return i;
10393 }
10394
10395 return -ENOENT;
10396}
10397
Hao Luo4976b712020-09-29 16:50:44 -070010398/* replace pseudo btf_id with kernel symbol address */
10399static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10400 struct bpf_insn *insn,
10401 struct bpf_insn_aux_data *aux)
10402{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010403 const struct btf_var_secinfo *vsi;
10404 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010405 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070010406 const struct btf_type *t;
10407 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010408 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010409 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010410 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010411 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070010412 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010413 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070010414
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010415 btf_fd = insn[1].imm;
10416 if (btf_fd) {
10417 btf = btf_get_by_fd(btf_fd);
10418 if (IS_ERR(btf)) {
10419 verbose(env, "invalid module BTF object FD specified.\n");
10420 return -EINVAL;
10421 }
10422 } else {
10423 if (!btf_vmlinux) {
10424 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10425 return -EINVAL;
10426 }
10427 btf = btf_vmlinux;
10428 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070010429 }
10430
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010431 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070010432 if (!t) {
10433 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010434 err = -ENOENT;
10435 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010436 }
10437
10438 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010439 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10440 err = -EINVAL;
10441 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010442 }
10443
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010444 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010445 addr = kallsyms_lookup_name(sym_name);
10446 if (!addr) {
10447 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10448 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010449 err = -ENOENT;
10450 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010451 }
10452
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010453 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010454 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010455 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010456 for_each_vsi(i, datasec, vsi) {
10457 if (vsi->type == id) {
10458 percpu = true;
10459 break;
10460 }
10461 }
10462 }
10463
Hao Luo4976b712020-09-29 16:50:44 -070010464 insn[0].imm = (u32)addr;
10465 insn[1].imm = addr >> 32;
10466
10467 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010468 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010469 if (percpu) {
10470 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010471 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010472 aux->btf_var.btf_id = type;
10473 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070010474 const struct btf_type *ret;
10475 const char *tname;
10476 u32 tsize;
10477
10478 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010479 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070010480 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010481 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010482 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10483 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010484 err = -EINVAL;
10485 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010486 }
10487 aux->btf_var.reg_type = PTR_TO_MEM;
10488 aux->btf_var.mem_size = tsize;
10489 } else {
10490 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010491 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070010492 aux->btf_var.btf_id = type;
10493 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010494
10495 /* check whether we recorded this BTF (and maybe module) already */
10496 for (i = 0; i < env->used_btf_cnt; i++) {
10497 if (env->used_btfs[i].btf == btf) {
10498 btf_put(btf);
10499 return 0;
10500 }
10501 }
10502
10503 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10504 err = -E2BIG;
10505 goto err_put;
10506 }
10507
10508 btf_mod = &env->used_btfs[env->used_btf_cnt];
10509 btf_mod->btf = btf;
10510 btf_mod->module = NULL;
10511
10512 /* if we reference variables from kernel module, bump its refcount */
10513 if (btf_is_module(btf)) {
10514 btf_mod->module = btf_try_get_module(btf);
10515 if (!btf_mod->module) {
10516 err = -ENXIO;
10517 goto err_put;
10518 }
10519 }
10520
10521 env->used_btf_cnt++;
10522
Hao Luo4976b712020-09-29 16:50:44 -070010523 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010524err_put:
10525 btf_put(btf);
10526 return err;
Hao Luo4976b712020-09-29 16:50:44 -070010527}
10528
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010529static int check_map_prealloc(struct bpf_map *map)
10530{
10531 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070010532 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10533 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010534 !(map->map_flags & BPF_F_NO_PREALLOC);
10535}
10536
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010537static bool is_tracing_prog_type(enum bpf_prog_type type)
10538{
10539 switch (type) {
10540 case BPF_PROG_TYPE_KPROBE:
10541 case BPF_PROG_TYPE_TRACEPOINT:
10542 case BPF_PROG_TYPE_PERF_EVENT:
10543 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10544 return true;
10545 default:
10546 return false;
10547 }
10548}
10549
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010550static bool is_preallocated_map(struct bpf_map *map)
10551{
10552 if (!check_map_prealloc(map))
10553 return false;
10554 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10555 return false;
10556 return true;
10557}
10558
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010559static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10560 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010561 struct bpf_prog *prog)
10562
10563{
Udip Pant7e407812020-08-25 16:20:00 -070010564 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010565 /*
10566 * Validate that trace type programs use preallocated hash maps.
10567 *
10568 * For programs attached to PERF events this is mandatory as the
10569 * perf NMI can hit any arbitrary code sequence.
10570 *
10571 * All other trace types using preallocated hash maps are unsafe as
10572 * well because tracepoint or kprobes can be inside locked regions
10573 * of the memory allocator or at a place where a recursion into the
10574 * memory allocator would see inconsistent state.
10575 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010576 * On RT enabled kernels run-time allocation of all trace type
10577 * programs is strictly prohibited due to lock type constraints. On
10578 * !RT kernels it is allowed for backwards compatibility reasons for
10579 * now, but warnings are emitted so developers are made aware of
10580 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010581 */
Udip Pant7e407812020-08-25 16:20:00 -070010582 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10583 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010584 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010585 return -EINVAL;
10586 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010587 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10588 verbose(env, "trace type programs can only use preallocated hash map\n");
10589 return -EINVAL;
10590 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010591 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10592 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 -070010593 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080010594
KP Singh9e7a4d92020-11-06 10:37:39 +000010595 if (map_value_has_spin_lock(map)) {
10596 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10597 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10598 return -EINVAL;
10599 }
10600
10601 if (is_tracing_prog_type(prog_type)) {
10602 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10603 return -EINVAL;
10604 }
10605
10606 if (prog->aux->sleepable) {
10607 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10608 return -EINVAL;
10609 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010610 }
10611
Jakub Kicinskia3884572018-01-11 20:29:09 -080010612 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070010613 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080010614 verbose(env, "offload device mismatch between prog and map\n");
10615 return -EINVAL;
10616 }
10617
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080010618 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10619 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10620 return -EINVAL;
10621 }
10622
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010623 if (prog->aux->sleepable)
10624 switch (map->map_type) {
10625 case BPF_MAP_TYPE_HASH:
10626 case BPF_MAP_TYPE_LRU_HASH:
10627 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010628 case BPF_MAP_TYPE_PERCPU_HASH:
10629 case BPF_MAP_TYPE_PERCPU_ARRAY:
10630 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10631 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10632 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010633 if (!is_preallocated_map(map)) {
10634 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010635 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010636 return -EINVAL;
10637 }
10638 break;
KP Singhba90c2c2021-02-04 19:36:21 +000010639 case BPF_MAP_TYPE_RINGBUF:
10640 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010641 default:
10642 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000010643 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010644 return -EINVAL;
10645 }
10646
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010647 return 0;
10648}
10649
Roman Gushchinb741f162018-09-28 14:45:43 +000010650static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10651{
10652 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10653 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10654}
10655
Hao Luo4976b712020-09-29 16:50:44 -070010656/* find and rewrite pseudo imm in ld_imm64 instructions:
10657 *
10658 * 1. if it accesses map FD, replace it with actual map pointer.
10659 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10660 *
10661 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010662 */
Hao Luo4976b712020-09-29 16:50:44 -070010663static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010664{
10665 struct bpf_insn *insn = env->prog->insnsi;
10666 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010667 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010668
Daniel Borkmannf1f77142017-01-13 23:38:15 +010010669 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010010670 if (err)
10671 return err;
10672
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010673 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010674 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010675 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010676 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010677 return -EINVAL;
10678 }
10679
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010680 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010681 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010682 struct bpf_map *map;
10683 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010684 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010685
10686 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10687 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10688 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010689 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010690 return -EINVAL;
10691 }
10692
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010693 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010694 /* valid generic load 64-bit imm */
10695 goto next_insn;
10696
Hao Luo4976b712020-09-29 16:50:44 -070010697 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10698 aux = &env->insn_aux_data[i];
10699 err = check_pseudo_btf_id(env, insn, aux);
10700 if (err)
10701 return err;
10702 goto next_insn;
10703 }
10704
Yonghong Song69c087b2021-02-26 12:49:25 -080010705 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
10706 aux = &env->insn_aux_data[i];
10707 aux->ptr_type = PTR_TO_FUNC;
10708 goto next_insn;
10709 }
10710
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010711 /* In final convert_pseudo_ld_imm64() step, this is
10712 * converted into regular 64-bit imm load insn.
10713 */
10714 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10715 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10716 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10717 insn[1].imm != 0)) {
10718 verbose(env,
10719 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010720 return -EINVAL;
10721 }
10722
Daniel Borkmann20182392019-03-04 21:08:53 +010010723 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +010010724 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010725 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010726 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010010727 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010728 return PTR_ERR(map);
10729 }
10730
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010731 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010732 if (err) {
10733 fdput(f);
10734 return err;
10735 }
10736
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010737 aux = &env->insn_aux_data[i];
10738 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10739 addr = (unsigned long)map;
10740 } else {
10741 u32 off = insn[1].imm;
10742
10743 if (off >= BPF_MAX_VAR_OFF) {
10744 verbose(env, "direct value offset of %u is not allowed\n", off);
10745 fdput(f);
10746 return -EINVAL;
10747 }
10748
10749 if (!map->ops->map_direct_value_addr) {
10750 verbose(env, "no direct value access support for this map type\n");
10751 fdput(f);
10752 return -EINVAL;
10753 }
10754
10755 err = map->ops->map_direct_value_addr(map, &addr, off);
10756 if (err) {
10757 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10758 map->value_size, off);
10759 fdput(f);
10760 return err;
10761 }
10762
10763 aux->map_off = off;
10764 addr += off;
10765 }
10766
10767 insn[0].imm = (u32)addr;
10768 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010769
10770 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010771 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010772 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010773 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010774 fdput(f);
10775 goto next_insn;
10776 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010777 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010778
10779 if (env->used_map_cnt >= MAX_USED_MAPS) {
10780 fdput(f);
10781 return -E2BIG;
10782 }
10783
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010784 /* hold the map. If the program is rejected by verifier,
10785 * the map will be released by release_maps() or it
10786 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070010787 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010788 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080010789 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010790
10791 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070010792 env->used_maps[env->used_map_cnt++] = map;
10793
Roman Gushchinb741f162018-09-28 14:45:43 +000010794 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010010795 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000010796 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070010797 fdput(f);
10798 return -EBUSY;
10799 }
10800
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010801 fdput(f);
10802next_insn:
10803 insn++;
10804 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010010805 continue;
10806 }
10807
10808 /* Basic sanity check before we invest more work here. */
10809 if (!bpf_opcode_in_insntable(insn->code)) {
10810 verbose(env, "unknown opcode %02x\n", insn->code);
10811 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010812 }
10813 }
10814
10815 /* now all pseudo BPF_LD_IMM64 instructions load valid
10816 * 'struct bpf_map *' into a register instead of user map_fd.
10817 * These pointers will be used later by verifier to validate map access.
10818 */
10819 return 0;
10820}
10821
10822/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010823static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010824{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010010825 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10826 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010827}
10828
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010829/* drop refcnt of maps used by the rejected program */
10830static void release_btfs(struct bpf_verifier_env *env)
10831{
10832 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10833 env->used_btf_cnt);
10834}
10835
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010836/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010837static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010838{
10839 struct bpf_insn *insn = env->prog->insnsi;
10840 int insn_cnt = env->prog->len;
10841 int i;
10842
Yonghong Song69c087b2021-02-26 12:49:25 -080010843 for (i = 0; i < insn_cnt; i++, insn++) {
10844 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
10845 continue;
10846 if (insn->src_reg == BPF_PSEUDO_FUNC)
10847 continue;
10848 insn->src_reg = 0;
10849 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010850}
10851
Alexei Starovoitov80419022017-03-15 18:26:41 -070010852/* single env->prog->insni[off] instruction was replaced with the range
10853 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10854 * [0, off) and [off, end) to new locations, so the patched range stays zero
10855 */
Jiong Wangb325fbc2019-05-24 23:25:13 +010010856static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10857 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070010858{
10859 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010860 struct bpf_insn *insn = new_prog->insnsi;
10861 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010862 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010863
Jiong Wangb325fbc2019-05-24 23:25:13 +010010864 /* aux info at OFF always needs adjustment, no matter fast path
10865 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10866 * original insn at old prog.
10867 */
10868 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10869
Alexei Starovoitov80419022017-03-15 18:26:41 -070010870 if (cnt == 1)
10871 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010872 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -070010873 new_data = vzalloc(array_size(prog_len,
10874 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -070010875 if (!new_data)
10876 return -ENOMEM;
10877 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10878 memcpy(new_data + off + cnt - 1, old_data + off,
10879 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010010880 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010881 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010882 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10883 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070010884 env->insn_aux_data = new_data;
10885 vfree(old_data);
10886 return 0;
10887}
10888
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010889static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10890{
10891 int i;
10892
10893 if (len == 1)
10894 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010895 /* NOTE: fake 'exit' subprog should be updated as well. */
10896 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000010897 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010898 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040010899 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010900 }
10901}
10902
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010903static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10904{
10905 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10906 int i, sz = prog->aux->size_poke_tab;
10907 struct bpf_jit_poke_descriptor *desc;
10908
10909 for (i = 0; i < sz; i++) {
10910 desc = &tab[i];
10911 desc->insn_idx += len - 1;
10912 }
10913}
10914
Alexei Starovoitov80419022017-03-15 18:26:41 -070010915static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10916 const struct bpf_insn *patch, u32 len)
10917{
10918 struct bpf_prog *new_prog;
10919
10920 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010921 if (IS_ERR(new_prog)) {
10922 if (PTR_ERR(new_prog) == -ERANGE)
10923 verbose(env,
10924 "insn %d cannot be patched due to 16-bit range\n",
10925 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010926 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010927 }
Jiong Wangb325fbc2019-05-24 23:25:13 +010010928 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -070010929 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010930 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010931 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010932 return new_prog;
10933}
10934
Jakub Kicinski52875a02019-01-22 22:45:20 -080010935static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10936 u32 off, u32 cnt)
10937{
10938 int i, j;
10939
10940 /* find first prog starting at or after off (first to remove) */
10941 for (i = 0; i < env->subprog_cnt; i++)
10942 if (env->subprog_info[i].start >= off)
10943 break;
10944 /* find first prog starting at or after off + cnt (first to stay) */
10945 for (j = i; j < env->subprog_cnt; j++)
10946 if (env->subprog_info[j].start >= off + cnt)
10947 break;
10948 /* if j doesn't start exactly at off + cnt, we are just removing
10949 * the front of previous prog
10950 */
10951 if (env->subprog_info[j].start != off + cnt)
10952 j--;
10953
10954 if (j > i) {
10955 struct bpf_prog_aux *aux = env->prog->aux;
10956 int move;
10957
10958 /* move fake 'exit' subprog as well */
10959 move = env->subprog_cnt + 1 - j;
10960
10961 memmove(env->subprog_info + i,
10962 env->subprog_info + j,
10963 sizeof(*env->subprog_info) * move);
10964 env->subprog_cnt -= j - i;
10965
10966 /* remove func_info */
10967 if (aux->func_info) {
10968 move = aux->func_info_cnt - j;
10969
10970 memmove(aux->func_info + i,
10971 aux->func_info + j,
10972 sizeof(*aux->func_info) * move);
10973 aux->func_info_cnt -= j - i;
10974 /* func_info->insn_off is set after all code rewrites,
10975 * in adjust_btf_func() - no need to adjust
10976 */
10977 }
10978 } else {
10979 /* convert i from "first prog to remove" to "first to adjust" */
10980 if (env->subprog_info[i].start == off)
10981 i++;
10982 }
10983
10984 /* update fake 'exit' subprog as well */
10985 for (; i <= env->subprog_cnt; i++)
10986 env->subprog_info[i].start -= cnt;
10987
10988 return 0;
10989}
10990
10991static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10992 u32 cnt)
10993{
10994 struct bpf_prog *prog = env->prog;
10995 u32 i, l_off, l_cnt, nr_linfo;
10996 struct bpf_line_info *linfo;
10997
10998 nr_linfo = prog->aux->nr_linfo;
10999 if (!nr_linfo)
11000 return 0;
11001
11002 linfo = prog->aux->linfo;
11003
11004 /* find first line info to remove, count lines to be removed */
11005 for (i = 0; i < nr_linfo; i++)
11006 if (linfo[i].insn_off >= off)
11007 break;
11008
11009 l_off = i;
11010 l_cnt = 0;
11011 for (; i < nr_linfo; i++)
11012 if (linfo[i].insn_off < off + cnt)
11013 l_cnt++;
11014 else
11015 break;
11016
11017 /* First live insn doesn't match first live linfo, it needs to "inherit"
11018 * last removed linfo. prog is already modified, so prog->len == off
11019 * means no live instructions after (tail of the program was removed).
11020 */
11021 if (prog->len != off && l_cnt &&
11022 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
11023 l_cnt--;
11024 linfo[--i].insn_off = off + cnt;
11025 }
11026
11027 /* remove the line info which refer to the removed instructions */
11028 if (l_cnt) {
11029 memmove(linfo + l_off, linfo + i,
11030 sizeof(*linfo) * (nr_linfo - i));
11031
11032 prog->aux->nr_linfo -= l_cnt;
11033 nr_linfo = prog->aux->nr_linfo;
11034 }
11035
11036 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
11037 for (i = l_off; i < nr_linfo; i++)
11038 linfo[i].insn_off -= cnt;
11039
11040 /* fix up all subprogs (incl. 'exit') which start >= off */
11041 for (i = 0; i <= env->subprog_cnt; i++)
11042 if (env->subprog_info[i].linfo_idx > l_off) {
11043 /* program may have started in the removed region but
11044 * may not be fully removed
11045 */
11046 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
11047 env->subprog_info[i].linfo_idx -= l_cnt;
11048 else
11049 env->subprog_info[i].linfo_idx = l_off;
11050 }
11051
11052 return 0;
11053}
11054
11055static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
11056{
11057 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11058 unsigned int orig_prog_len = env->prog->len;
11059 int err;
11060
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011061 if (bpf_prog_is_dev_bound(env->prog->aux))
11062 bpf_prog_offload_remove_insns(env, off, cnt);
11063
Jakub Kicinski52875a02019-01-22 22:45:20 -080011064 err = bpf_remove_insns(env->prog, off, cnt);
11065 if (err)
11066 return err;
11067
11068 err = adjust_subprog_starts_after_remove(env, off, cnt);
11069 if (err)
11070 return err;
11071
11072 err = bpf_adj_linfo_after_remove(env, off, cnt);
11073 if (err)
11074 return err;
11075
11076 memmove(aux_data + off, aux_data + off + cnt,
11077 sizeof(*aux_data) * (orig_prog_len - off - cnt));
11078
11079 return 0;
11080}
11081
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011082/* The verifier does more data flow analysis than llvm and will not
11083 * explore branches that are dead at run time. Malicious programs can
11084 * have dead code too. Therefore replace all dead at-run-time code
11085 * with 'ja -1'.
11086 *
11087 * Just nops are not optimal, e.g. if they would sit at the end of the
11088 * program and through another bug we would manage to jump there, then
11089 * we'd execute beyond program memory otherwise. Returning exception
11090 * code also wouldn't work since we can have subprogs where the dead
11091 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011092 */
11093static void sanitize_dead_code(struct bpf_verifier_env *env)
11094{
11095 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011096 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011097 struct bpf_insn *insn = env->prog->insnsi;
11098 const int insn_cnt = env->prog->len;
11099 int i;
11100
11101 for (i = 0; i < insn_cnt; i++) {
11102 if (aux_data[i].seen)
11103 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010011104 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080011105 }
11106}
11107
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011108static bool insn_is_cond_jump(u8 code)
11109{
11110 u8 op;
11111
Jiong Wang092ed092019-01-26 12:26:01 -050011112 if (BPF_CLASS(code) == BPF_JMP32)
11113 return true;
11114
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011115 if (BPF_CLASS(code) != BPF_JMP)
11116 return false;
11117
11118 op = BPF_OP(code);
11119 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
11120}
11121
11122static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
11123{
11124 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11125 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11126 struct bpf_insn *insn = env->prog->insnsi;
11127 const int insn_cnt = env->prog->len;
11128 int i;
11129
11130 for (i = 0; i < insn_cnt; i++, insn++) {
11131 if (!insn_is_cond_jump(insn->code))
11132 continue;
11133
11134 if (!aux_data[i + 1].seen)
11135 ja.off = insn->off;
11136 else if (!aux_data[i + 1 + insn->off].seen)
11137 ja.off = 0;
11138 else
11139 continue;
11140
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080011141 if (bpf_prog_is_dev_bound(env->prog->aux))
11142 bpf_prog_offload_replace_insn(env, i, &ja);
11143
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080011144 memcpy(insn, &ja, sizeof(ja));
11145 }
11146}
11147
Jakub Kicinski52875a02019-01-22 22:45:20 -080011148static int opt_remove_dead_code(struct bpf_verifier_env *env)
11149{
11150 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
11151 int insn_cnt = env->prog->len;
11152 int i, err;
11153
11154 for (i = 0; i < insn_cnt; i++) {
11155 int j;
11156
11157 j = 0;
11158 while (i + j < insn_cnt && !aux_data[i + j].seen)
11159 j++;
11160 if (!j)
11161 continue;
11162
11163 err = verifier_remove_insns(env, i, j);
11164 if (err)
11165 return err;
11166 insn_cnt = env->prog->len;
11167 }
11168
11169 return 0;
11170}
11171
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011172static int opt_remove_nops(struct bpf_verifier_env *env)
11173{
11174 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11175 struct bpf_insn *insn = env->prog->insnsi;
11176 int insn_cnt = env->prog->len;
11177 int i, err;
11178
11179 for (i = 0; i < insn_cnt; i++) {
11180 if (memcmp(&insn[i], &ja, sizeof(ja)))
11181 continue;
11182
11183 err = verifier_remove_insns(env, i, 1);
11184 if (err)
11185 return err;
11186 insn_cnt--;
11187 i--;
11188 }
11189
11190 return 0;
11191}
11192
Jiong Wangd6c23082019-05-24 23:25:18 +010011193static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11194 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011195{
Jiong Wangd6c23082019-05-24 23:25:18 +010011196 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011197 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011198 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011199 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011200 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010011201 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011202
Jiong Wangd6c23082019-05-24 23:25:18 +010011203 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011204 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010011205 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11206 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11207 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011208 for (i = 0; i < len; i++) {
11209 int adj_idx = i + delta;
11210 struct bpf_insn insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011211 u8 load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011212
Jiong Wangd6c23082019-05-24 23:25:18 +010011213 insn = insns[adj_idx];
11214 if (!aux[adj_idx].zext_dst) {
11215 u8 code, class;
11216 u32 imm_rnd;
11217
11218 if (!rnd_hi32)
11219 continue;
11220
11221 code = insn.code;
11222 class = BPF_CLASS(code);
11223 if (insn_no_def(&insn))
11224 continue;
11225
11226 /* NOTE: arg "reg" (the fourth one) is only used for
11227 * BPF_STX which has been ruled out in above
11228 * check, it is safe to pass NULL here.
11229 */
11230 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11231 if (class == BPF_LD &&
11232 BPF_MODE(code) == BPF_IMM)
11233 i++;
11234 continue;
11235 }
11236
11237 /* ctx load could be transformed into wider load. */
11238 if (class == BPF_LDX &&
11239 aux[adj_idx].ptr_type == PTR_TO_CTX)
11240 continue;
11241
11242 imm_rnd = get_random_int();
11243 rnd_hi32_patch[0] = insn;
11244 rnd_hi32_patch[1].imm = imm_rnd;
11245 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11246 patch = rnd_hi32_patch;
11247 patch_len = 4;
11248 goto apply_patch_buffer;
11249 }
11250
11251 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011252 continue;
11253
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011254 /* zext_dst means that we want to zero-extend whatever register
11255 * the insn defines, which is dst_reg most of the time, with
11256 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11257 */
11258 if (BPF_CLASS(insn.code) == BPF_STX &&
11259 BPF_MODE(insn.code) == BPF_ATOMIC) {
11260 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11261 * define any registers, therefore zext_dst cannot be
11262 * set.
11263 */
11264 if (WARN_ON(!(insn.imm & BPF_FETCH)))
11265 return -EINVAL;
11266 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11267 : insn.src_reg;
11268 } else {
11269 load_reg = insn.dst_reg;
11270 }
11271
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011272 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011273 zext_patch[1].dst_reg = load_reg;
11274 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010011275 patch = zext_patch;
11276 patch_len = 2;
11277apply_patch_buffer:
11278 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011279 if (!new_prog)
11280 return -ENOMEM;
11281 env->prog = new_prog;
11282 insns = new_prog->insnsi;
11283 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011284 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011285 }
11286
11287 return 0;
11288}
11289
Joe Stringerc64b7982018-10-02 13:35:33 -070011290/* convert load instructions that access fields of a context type into a
11291 * sequence of instructions that access fields of the underlying structure:
11292 * struct __sk_buff -> struct sk_buff
11293 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011294 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011295static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011296{
Jakub Kicinski00176a32017-10-16 16:40:54 -070011297 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011298 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011299 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011300 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011301 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011302 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011303 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011304 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011305
Daniel Borkmannb09928b2018-10-24 22:05:49 +020011306 if (ops->gen_prologue || env->seen_direct_write) {
11307 if (!ops->gen_prologue) {
11308 verbose(env, "bpf verifier is misconfigured\n");
11309 return -EINVAL;
11310 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011311 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11312 env->prog);
11313 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011314 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011315 return -EINVAL;
11316 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070011317 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011318 if (!new_prog)
11319 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011320
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011321 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011322 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011323 }
11324 }
11325
Joe Stringerc64b7982018-10-02 13:35:33 -070011326 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011327 return 0;
11328
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011329 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011330
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011331 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070011332 bpf_convert_ctx_access_t convert_ctx_access;
11333
Daniel Borkmann62c79892017-01-12 11:51:33 +010011334 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11335 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11336 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011337 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011338 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010011339 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11340 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11341 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011342 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011343 type = BPF_WRITE;
11344 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011345 continue;
11346
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011347 if (type == BPF_WRITE &&
11348 env->insn_aux_data[i + delta].sanitize_stack_off) {
11349 struct bpf_insn patch[] = {
11350 /* Sanitize suspicious stack slot with zero.
11351 * There are no memory dependencies for this store,
11352 * since it's only using frame pointer and immediate
11353 * constant of zero
11354 */
11355 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11356 env->insn_aux_data[i + delta].sanitize_stack_off,
11357 0),
11358 /* the original STX instruction will immediately
11359 * overwrite the same stack slot with appropriate value
11360 */
11361 *insn,
11362 };
11363
11364 cnt = ARRAY_SIZE(patch);
11365 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11366 if (!new_prog)
11367 return -ENOMEM;
11368
11369 delta += cnt - 1;
11370 env->prog = new_prog;
11371 insn = new_prog->insnsi + i + delta;
11372 continue;
11373 }
11374
Joe Stringerc64b7982018-10-02 13:35:33 -070011375 switch (env->insn_aux_data[i + delta].ptr_type) {
11376 case PTR_TO_CTX:
11377 if (!ops->convert_ctx_access)
11378 continue;
11379 convert_ctx_access = ops->convert_ctx_access;
11380 break;
11381 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011382 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070011383 convert_ctx_access = bpf_sock_convert_ctx_access;
11384 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011385 case PTR_TO_TCP_SOCK:
11386 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11387 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011388 case PTR_TO_XDP_SOCK:
11389 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11390 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011391 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011392 if (type == BPF_READ) {
11393 insn->code = BPF_LDX | BPF_PROBE_MEM |
11394 BPF_SIZE((insn)->code);
11395 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070011396 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011397 verbose(env, "Writes through BTF pointers are not allowed\n");
11398 return -EINVAL;
11399 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011400 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011401 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011402 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011403 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011404
Yonghong Song31fd8582017-06-13 15:52:13 -070011405 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011406 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070011407
11408 /* If the read access is a narrower load of the field,
11409 * convert to a 4/8-byte load, to minimum program type specific
11410 * convert_ctx_access changes. If conversion is successful,
11411 * we will apply proper mask to the result.
11412 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020011413 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011414 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11415 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070011416 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020011417 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070011418
Daniel Borkmannf96da092017-07-02 02:13:27 +020011419 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011420 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020011421 return -EINVAL;
11422 }
11423
11424 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070011425 if (ctx_field_size == 4)
11426 size_code = BPF_W;
11427 else if (ctx_field_size == 8)
11428 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011429
Daniel Borkmannbc231052018-06-02 23:06:39 +020011430 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070011431 insn->code = BPF_LDX | BPF_MEM | size_code;
11432 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011433
11434 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070011435 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11436 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020011437 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11438 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011439 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011440 return -EINVAL;
11441 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011442
11443 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020011444 u8 shift = bpf_ctx_narrow_access_offset(
11445 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011446 if (ctx_field_size <= 4) {
11447 if (shift)
11448 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11449 insn->dst_reg,
11450 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011451 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020011452 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011453 } else {
11454 if (shift)
11455 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11456 insn->dst_reg,
11457 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011458 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020011459 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011460 }
Yonghong Song31fd8582017-06-13 15:52:13 -070011461 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011462
Alexei Starovoitov80419022017-03-15 18:26:41 -070011463 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011464 if (!new_prog)
11465 return -ENOMEM;
11466
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011467 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011468
11469 /* keep walking new program and skip insns we just inserted */
11470 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011471 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011472 }
11473
11474 return 0;
11475}
11476
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011477static int jit_subprogs(struct bpf_verifier_env *env)
11478{
11479 struct bpf_prog *prog = env->prog, **func, *tmp;
11480 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011481 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011482 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011483 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011484 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011485
Jiong Wangf910cef2018-05-02 16:17:17 -040011486 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011487 return 0;
11488
Daniel Borkmann7105e822017-12-20 13:42:57 +010011489 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080011490 if (bpf_pseudo_func(insn)) {
11491 env->insn_aux_data[i].call_imm = insn->imm;
11492 /* subprog is encoded in insn[1].imm */
11493 continue;
11494 }
11495
Yonghong Song23a2d702021-02-04 15:48:27 -080011496 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011497 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011498 /* Upon error here we cannot fall back to interpreter but
11499 * need a hard reject of the program. Thus -EFAULT is
11500 * propagated in any case.
11501 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011502 subprog = find_subprog(env, i + insn->imm + 1);
11503 if (subprog < 0) {
11504 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11505 i + insn->imm + 1);
11506 return -EFAULT;
11507 }
11508 /* temporarily remember subprog id inside insn instead of
11509 * aux_data, since next loop will split up all insns into funcs
11510 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011511 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011512 /* remember original imm in case JIT fails and fallback
11513 * to interpreter will be needed
11514 */
11515 env->insn_aux_data[i].call_imm = insn->imm;
11516 /* point imm to __bpf_call_base+1 from JITs point of view */
11517 insn->imm = 1;
11518 }
11519
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011520 err = bpf_prog_alloc_jited_linfo(prog);
11521 if (err)
11522 goto out_undo_insn;
11523
11524 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070011525 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011526 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011527 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011528
Jiong Wangf910cef2018-05-02 16:17:17 -040011529 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011530 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040011531 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011532
11533 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011534 /* BPF_PROG_RUN doesn't call subprogs directly,
11535 * hence main prog stats include the runtime of subprogs.
11536 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080011537 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011538 */
11539 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011540 if (!func[i])
11541 goto out_free;
11542 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11543 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011544 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011545 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011546 if (bpf_prog_calc_tag(func[i]))
11547 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011548 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080011549 func[i]->aux->func_idx = i;
11550 /* the btf and func_info will be freed only at prog->aux */
11551 func[i]->aux->btf = prog->aux->btf;
11552 func[i]->aux->func_info = prog->aux->func_info;
11553
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011554 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11555 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11556 int ret;
11557
11558 if (!(insn_idx >= subprog_start &&
11559 insn_idx <= subprog_end))
11560 continue;
11561
11562 ret = bpf_jit_add_poke_descriptor(func[i],
11563 &prog->aux->poke_tab[j]);
11564 if (ret < 0) {
11565 verbose(env, "adding tail call poke descriptor failed\n");
11566 goto out_free;
11567 }
11568
11569 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11570
11571 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11572 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11573 if (ret < 0) {
11574 verbose(env, "tracking tail call prog failed\n");
11575 goto out_free;
11576 }
11577 }
11578
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011579 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11580 * Long term would need debug info to populate names
11581 */
11582 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040011583 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011584 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011585 func[i]->aux->linfo = prog->aux->linfo;
11586 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11587 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11588 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011589 num_exentries = 0;
11590 insn = func[i]->insnsi;
11591 for (j = 0; j < func[i]->len; j++, insn++) {
11592 if (BPF_CLASS(insn->code) == BPF_LDX &&
11593 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11594 num_exentries++;
11595 }
11596 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020011597 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011598 func[i] = bpf_int_jit_compile(func[i]);
11599 if (!func[i]->jited) {
11600 err = -ENOTSUPP;
11601 goto out_free;
11602 }
11603 cond_resched();
11604 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011605
11606 /* Untrack main program's aux structs so that during map_poke_run()
11607 * we will not stumble upon the unfilled poke descriptors; each
11608 * of the main program's poke descs got distributed across subprogs
11609 * and got tracked onto map, so we are sure that none of them will
11610 * be missed after the operation below
11611 */
11612 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11613 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11614
11615 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11616 }
11617
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011618 /* at this point all bpf functions were successfully JITed
11619 * now populate all bpf_calls with correct addresses and
11620 * run last pass of JIT
11621 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011622 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011623 insn = func[i]->insnsi;
11624 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080011625 if (bpf_pseudo_func(insn)) {
11626 subprog = insn[1].imm;
11627 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
11628 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
11629 continue;
11630 }
Yonghong Song23a2d702021-02-04 15:48:27 -080011631 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011632 continue;
11633 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090011634 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11635 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011636 }
Sandipan Das2162fed2018-05-24 12:26:45 +053011637
11638 /* we use the aux data to keep a list of the start addresses
11639 * of the JITed images for each function in the program
11640 *
11641 * for some architectures, such as powerpc64, the imm field
11642 * might not be large enough to hold the offset of the start
11643 * address of the callee's JITed image from __bpf_call_base
11644 *
11645 * in such cases, we can lookup the start address of a callee
11646 * by using its subprog id, available from the off field of
11647 * the call instruction, as an index for this list
11648 */
11649 func[i]->aux->func = func;
11650 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011651 }
Jiong Wangf910cef2018-05-02 16:17:17 -040011652 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011653 old_bpf_func = func[i]->bpf_func;
11654 tmp = bpf_int_jit_compile(func[i]);
11655 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11656 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011657 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011658 goto out_free;
11659 }
11660 cond_resched();
11661 }
11662
11663 /* finally lock prog and jit images for all functions and
11664 * populate kallsysm
11665 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011666 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011667 bpf_prog_lock_ro(func[i]);
11668 bpf_prog_kallsyms_add(func[i]);
11669 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010011670
11671 /* Last step: make now unused interpreter insns from main
11672 * prog consistent for later dump requests, so they can
11673 * later look the same as if they were interpreted only.
11674 */
11675 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080011676 if (bpf_pseudo_func(insn)) {
11677 insn[0].imm = env->insn_aux_data[i].call_imm;
11678 insn[1].imm = find_subprog(env, i + insn[0].imm + 1);
11679 continue;
11680 }
Yonghong Song23a2d702021-02-04 15:48:27 -080011681 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010011682 continue;
11683 insn->off = env->insn_aux_data[i].call_imm;
11684 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053011685 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011686 }
11687
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011688 prog->jited = 1;
11689 prog->bpf_func = func[0]->bpf_func;
11690 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040011691 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011692 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011693 return 0;
11694out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011695 for (i = 0; i < env->subprog_cnt; i++) {
11696 if (!func[i])
11697 continue;
11698
11699 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11700 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11701 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11702 }
11703 bpf_jit_free(func[i]);
11704 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011705 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011706out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011707 /* cleanup main prog to be interpreted */
11708 prog->jit_requested = 0;
11709 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011710 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011711 continue;
11712 insn->off = 0;
11713 insn->imm = env->insn_aux_data[i].call_imm;
11714 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011715 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011716 return err;
11717}
11718
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011719static int fixup_call_args(struct bpf_verifier_env *env)
11720{
David S. Miller19d28fb2018-01-11 21:27:54 -050011721#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011722 struct bpf_prog *prog = env->prog;
11723 struct bpf_insn *insn = prog->insnsi;
11724 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050011725#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010011726 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011727
Quentin Monnete4052d02018-10-07 12:56:58 +010011728 if (env->prog->jit_requested &&
11729 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050011730 err = jit_subprogs(env);
11731 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011732 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011733 if (err == -EFAULT)
11734 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050011735 }
11736#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011737 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11738 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11739 * have to be rejected, since interpreter doesn't support them yet.
11740 */
11741 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11742 return -EINVAL;
11743 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011744 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080011745 if (bpf_pseudo_func(insn)) {
11746 /* When JIT fails the progs with callback calls
11747 * have to be rejected, since interpreter doesn't support them yet.
11748 */
11749 verbose(env, "callbacks are not allowed in non-JITed programs\n");
11750 return -EINVAL;
11751 }
11752
Yonghong Song23a2d702021-02-04 15:48:27 -080011753 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011754 continue;
11755 depth = get_callee_stack_depth(env, insn, i);
11756 if (depth < 0)
11757 return depth;
11758 bpf_patch_call_args(insn, depth);
11759 }
David S. Miller19d28fb2018-01-11 21:27:54 -050011760 err = 0;
11761#endif
11762 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011763}
11764
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011765/* Do various post-verification rewrites in a single program pass.
11766 * These rewrites simplify JIT and interpreter implementations.
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011767 */
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011768static int do_misc_fixups(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011769{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011770 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011771 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011772 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011773 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011774 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020011775 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011776 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011777 struct bpf_insn insn_buf[16];
11778 struct bpf_prog *new_prog;
11779 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011780 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011781
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011782 for (i = 0; i < insn_cnt; i++, insn++) {
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011783 /* Make divide-by-zero exceptions impossible. */
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011784 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11785 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11786 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011787 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011788 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011789 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11790 struct bpf_insn *patchlet;
11791 struct bpf_insn chk_and_div[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011792 /* [R,W]x div 0 -> 0 */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011793 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11794 BPF_JNE | BPF_K, insn->src_reg,
11795 0, 2, 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011796 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11797 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11798 *insn,
11799 };
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011800 struct bpf_insn chk_and_mod[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011801 /* [R,W]x mod 0 -> [R,W]x */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011802 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11803 BPF_JEQ | BPF_K, insn->src_reg,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011804 0, 1 + (is64 ? 0 : 1), 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011805 *insn,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011806 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11807 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011808 };
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011809
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011810 patchlet = isdiv ? chk_and_div : chk_and_mod;
11811 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011812 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011813
11814 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011815 if (!new_prog)
11816 return -ENOMEM;
11817
11818 delta += cnt - 1;
11819 env->prog = prog = new_prog;
11820 insn = new_prog->insnsi + i + delta;
11821 continue;
11822 }
11823
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011824 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020011825 if (BPF_CLASS(insn->code) == BPF_LD &&
11826 (BPF_MODE(insn->code) == BPF_ABS ||
11827 BPF_MODE(insn->code) == BPF_IND)) {
11828 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11829 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11830 verbose(env, "bpf verifier is misconfigured\n");
11831 return -EINVAL;
11832 }
11833
11834 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11835 if (!new_prog)
11836 return -ENOMEM;
11837
11838 delta += cnt - 1;
11839 env->prog = prog = new_prog;
11840 insn = new_prog->insnsi + i + delta;
11841 continue;
11842 }
11843
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011844 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011845 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11846 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11847 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11848 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11849 struct bpf_insn insn_buf[16];
11850 struct bpf_insn *patch = &insn_buf[0];
11851 bool issrc, isneg;
11852 u32 off_reg;
11853
11854 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010011855 if (!aux->alu_state ||
11856 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011857 continue;
11858
11859 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11860 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11861 BPF_ALU_SANITIZE_SRC;
11862
11863 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11864 if (isneg)
11865 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11866 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11867 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11868 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11869 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11870 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11871 if (issrc) {
11872 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11873 off_reg);
11874 insn->src_reg = BPF_REG_AX;
11875 } else {
11876 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11877 BPF_REG_AX);
11878 }
11879 if (isneg)
11880 insn->code = insn->code == code_add ?
11881 code_sub : code_add;
11882 *patch++ = *insn;
11883 if (issrc && isneg)
11884 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11885 cnt = patch - insn_buf;
11886
11887 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11888 if (!new_prog)
11889 return -ENOMEM;
11890
11891 delta += cnt - 1;
11892 env->prog = prog = new_prog;
11893 insn = new_prog->insnsi + i + delta;
11894 continue;
11895 }
11896
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011897 if (insn->code != (BPF_JMP | BPF_CALL))
11898 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011899 if (insn->src_reg == BPF_PSEUDO_CALL)
11900 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011901
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011902 if (insn->imm == BPF_FUNC_get_route_realm)
11903 prog->dst_needed = 1;
11904 if (insn->imm == BPF_FUNC_get_prandom_u32)
11905 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050011906 if (insn->imm == BPF_FUNC_override_return)
11907 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011908 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040011909 /* If we tail call into other programs, we
11910 * cannot make any assumptions since they can
11911 * be replaced dynamically during runtime in
11912 * the program array.
11913 */
11914 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011915 if (!allow_tail_call_in_subprogs(env))
11916 prog->aux->stack_depth = MAX_BPF_STACK;
11917 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040011918
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011919 /* mark bpf_tail_call as different opcode to avoid
11920 * conditional branch in the interpeter for every normal
11921 * call and to prevent accidental JITing by JIT compiler
11922 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011923 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011924 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070011925 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011926
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011927 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011928 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010011929 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011930 !bpf_map_key_poisoned(aux) &&
11931 !bpf_map_ptr_poisoned(aux) &&
11932 !bpf_map_ptr_unpriv(aux)) {
11933 struct bpf_jit_poke_descriptor desc = {
11934 .reason = BPF_POKE_REASON_TAIL_CALL,
11935 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11936 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011937 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011938 };
11939
11940 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11941 if (ret < 0) {
11942 verbose(env, "adding tail call poke descriptor failed\n");
11943 return ret;
11944 }
11945
11946 insn->imm = ret + 1;
11947 continue;
11948 }
11949
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011950 if (!bpf_map_ptr_unpriv(aux))
11951 continue;
11952
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011953 /* instead of changing every JIT dealing with tail_call
11954 * emit two extra insns:
11955 * if (index >= max_entries) goto out;
11956 * index &= array->index_mask;
11957 * to avoid out-of-bounds cpu speculation
11958 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011959 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000011960 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011961 return -EINVAL;
11962 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011963
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011964 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011965 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11966 map_ptr->max_entries, 2);
11967 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11968 container_of(map_ptr,
11969 struct bpf_array,
11970 map)->index_mask);
11971 insn_buf[2] = *insn;
11972 cnt = 3;
11973 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11974 if (!new_prog)
11975 return -ENOMEM;
11976
11977 delta += cnt - 1;
11978 env->prog = prog = new_prog;
11979 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011980 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011981 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011982
Daniel Borkmann89c63072017-08-19 03:12:45 +020011983 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020011984 * and other inlining handlers are currently limited to 64 bit
11985 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020011986 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080011987 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020011988 (insn->imm == BPF_FUNC_map_lookup_elem ||
11989 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020011990 insn->imm == BPF_FUNC_map_delete_elem ||
11991 insn->imm == BPF_FUNC_map_push_elem ||
11992 insn->imm == BPF_FUNC_map_pop_elem ||
11993 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011994 aux = &env->insn_aux_data[i + delta];
11995 if (bpf_map_ptr_poisoned(aux))
11996 goto patch_call_imm;
11997
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011998 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020011999 ops = map_ptr->ops;
12000 if (insn->imm == BPF_FUNC_map_lookup_elem &&
12001 ops->map_gen_lookup) {
12002 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012003 if (cnt == -EOPNOTSUPP)
12004 goto patch_map_ops_generic;
12005 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020012006 verbose(env, "bpf verifier is misconfigured\n");
12007 return -EINVAL;
12008 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012009
Daniel Borkmann09772d92018-06-02 23:06:35 +020012010 new_prog = bpf_patch_insn_data(env, i + delta,
12011 insn_buf, cnt);
12012 if (!new_prog)
12013 return -ENOMEM;
12014
12015 delta += cnt - 1;
12016 env->prog = prog = new_prog;
12017 insn = new_prog->insnsi + i + delta;
12018 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012019 }
12020
Daniel Borkmann09772d92018-06-02 23:06:35 +020012021 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
12022 (void *(*)(struct bpf_map *map, void *key))NULL));
12023 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
12024 (int (*)(struct bpf_map *map, void *key))NULL));
12025 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
12026 (int (*)(struct bpf_map *map, void *key, void *value,
12027 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020012028 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
12029 (int (*)(struct bpf_map *map, void *value,
12030 u64 flags))NULL));
12031 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
12032 (int (*)(struct bpf_map *map, void *value))NULL));
12033 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
12034 (int (*)(struct bpf_map *map, void *value))NULL));
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020012035patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020012036 switch (insn->imm) {
12037 case BPF_FUNC_map_lookup_elem:
12038 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
12039 __bpf_call_base;
12040 continue;
12041 case BPF_FUNC_map_update_elem:
12042 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
12043 __bpf_call_base;
12044 continue;
12045 case BPF_FUNC_map_delete_elem:
12046 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
12047 __bpf_call_base;
12048 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020012049 case BPF_FUNC_map_push_elem:
12050 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
12051 __bpf_call_base;
12052 continue;
12053 case BPF_FUNC_map_pop_elem:
12054 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
12055 __bpf_call_base;
12056 continue;
12057 case BPF_FUNC_map_peek_elem:
12058 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
12059 __bpf_call_base;
12060 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020012061 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012062
Daniel Borkmann09772d92018-06-02 23:06:35 +020012063 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012064 }
12065
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012066 /* Implement bpf_jiffies64 inline. */
Martin KaFai Lau5576b992020-01-22 15:36:46 -080012067 if (prog->jit_requested && BITS_PER_LONG == 64 &&
12068 insn->imm == BPF_FUNC_jiffies64) {
12069 struct bpf_insn ld_jiffies_addr[2] = {
12070 BPF_LD_IMM64(BPF_REG_0,
12071 (unsigned long)&jiffies),
12072 };
12073
12074 insn_buf[0] = ld_jiffies_addr[0];
12075 insn_buf[1] = ld_jiffies_addr[1];
12076 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
12077 BPF_REG_0, 0);
12078 cnt = 3;
12079
12080 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
12081 cnt);
12082 if (!new_prog)
12083 return -ENOMEM;
12084
12085 delta += cnt - 1;
12086 env->prog = prog = new_prog;
12087 insn = new_prog->insnsi + i + delta;
12088 continue;
12089 }
12090
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070012091patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070012092 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012093 /* all functions that have prototype and verifier allowed
12094 * programs to call them, must be real in-kernel functions
12095 */
12096 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012097 verbose(env,
12098 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012099 func_id_name(insn->imm), insn->imm);
12100 return -EFAULT;
12101 }
12102 insn->imm = fn->func - __bpf_call_base;
12103 }
12104
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010012105 /* Since poke tab is now finalized, publish aux to tracker. */
12106 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12107 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12108 if (!map_ptr->ops->map_poke_track ||
12109 !map_ptr->ops->map_poke_untrack ||
12110 !map_ptr->ops->map_poke_run) {
12111 verbose(env, "bpf verifier is misconfigured\n");
12112 return -EINVAL;
12113 }
12114
12115 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
12116 if (ret < 0) {
12117 verbose(env, "tracking tail call prog failed\n");
12118 return ret;
12119 }
12120 }
12121
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012122 return 0;
12123}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012124
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012125static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012126{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012127 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012128 int i;
12129
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012130 sl = env->free_list;
12131 while (sl) {
12132 sln = sl->next;
12133 free_verifier_state(&sl->state, false);
12134 kfree(sl);
12135 sl = sln;
12136 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012137 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070012138
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012139 if (!env->explored_states)
12140 return;
12141
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012142 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012143 sl = env->explored_states[i];
12144
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070012145 while (sl) {
12146 sln = sl->next;
12147 free_verifier_state(&sl->state, false);
12148 kfree(sl);
12149 sl = sln;
12150 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012151 env->explored_states[i] = NULL;
12152 }
12153}
12154
12155/* The verifier is using insn_aux_data[] to store temporary data during
12156 * verification and to store information for passes that run after the
12157 * verification like dead code sanitization. do_check_common() for subprogram N
12158 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
12159 * temporary data after do_check_common() finds that subprogram N cannot be
12160 * verified independently. pass_cnt counts the number of times
12161 * do_check_common() was run and insn->aux->seen tells the pass number
12162 * insn_aux_data was touched. These variables are compared to clear temporary
12163 * data from failed pass. For testing and experiments do_check_common() can be
12164 * run multiple times even when prior attempt to verify is unsuccessful.
12165 */
12166static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
12167{
12168 struct bpf_insn *insn = env->prog->insnsi;
12169 struct bpf_insn_aux_data *aux;
12170 int i, class;
12171
12172 for (i = 0; i < env->prog->len; i++) {
12173 class = BPF_CLASS(insn[i].code);
12174 if (class != BPF_LDX && class != BPF_STX)
12175 continue;
12176 aux = &env->insn_aux_data[i];
12177 if (aux->seen != env->pass_cnt)
12178 continue;
12179 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
12180 }
12181}
12182
12183static int do_check_common(struct bpf_verifier_env *env, int subprog)
12184{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012185 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012186 struct bpf_verifier_state *state;
12187 struct bpf_reg_state *regs;
12188 int ret, i;
12189
12190 env->prev_linfo = NULL;
12191 env->pass_cnt++;
12192
12193 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12194 if (!state)
12195 return -ENOMEM;
12196 state->curframe = 0;
12197 state->speculative = false;
12198 state->branches = 1;
12199 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12200 if (!state->frame[0]) {
12201 kfree(state);
12202 return -ENOMEM;
12203 }
12204 env->cur_state = state;
12205 init_func_state(env, state->frame[0],
12206 BPF_MAIN_FUNC /* callsite */,
12207 0 /* frameno */,
12208 subprog);
12209
12210 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012211 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012212 ret = btf_prepare_func_args(env, subprog, regs);
12213 if (ret)
12214 goto out;
12215 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12216 if (regs[i].type == PTR_TO_CTX)
12217 mark_reg_known_zero(env, regs, i);
12218 else if (regs[i].type == SCALAR_VALUE)
12219 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040012220 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12221 const u32 mem_size = regs[i].mem_size;
12222
12223 mark_reg_known_zero(env, regs, i);
12224 regs[i].mem_size = mem_size;
12225 regs[i].id = ++env->id_gen;
12226 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012227 }
12228 } else {
12229 /* 1st arg to a function */
12230 regs[BPF_REG_1].type = PTR_TO_CTX;
12231 mark_reg_known_zero(env, regs, BPF_REG_1);
12232 ret = btf_check_func_arg_match(env, subprog, regs);
12233 if (ret == -EFAULT)
12234 /* unlikely verifier bug. abort.
12235 * ret == 0 and ret < 0 are sadly acceptable for
12236 * main() function due to backward compatibility.
12237 * Like socket filter program may be written as:
12238 * int bpf_prog(struct pt_regs *ctx)
12239 * and never dereference that ctx in the program.
12240 * 'struct pt_regs' is a type mismatch for socket
12241 * filter that should be using 'struct __sk_buff'.
12242 */
12243 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012244 }
12245
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012246 ret = do_check(env);
12247out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080012248 /* check for NULL is necessary, since cur_state can be freed inside
12249 * do_check() under memory pressure.
12250 */
12251 if (env->cur_state) {
12252 free_verifier_state(env->cur_state, true);
12253 env->cur_state = NULL;
12254 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012255 while (!pop_stack(env, NULL, NULL, false));
12256 if (!ret && pop_log)
12257 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012258 free_states(env);
12259 if (ret)
12260 /* clean aux data in case subprog was rejected */
12261 sanitize_insn_aux_data(env);
12262 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012263}
12264
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012265/* Verify all global functions in a BPF program one by one based on their BTF.
12266 * All global functions must pass verification. Otherwise the whole program is rejected.
12267 * Consider:
12268 * int bar(int);
12269 * int foo(int f)
12270 * {
12271 * return bar(f);
12272 * }
12273 * int bar(int b)
12274 * {
12275 * ...
12276 * }
12277 * foo() will be verified first for R1=any_scalar_value. During verification it
12278 * will be assumed that bar() already verified successfully and call to bar()
12279 * from foo() will be checked for type match only. Later bar() will be verified
12280 * independently to check that it's safe for R1=any_scalar_value.
12281 */
12282static int do_check_subprogs(struct bpf_verifier_env *env)
12283{
12284 struct bpf_prog_aux *aux = env->prog->aux;
12285 int i, ret;
12286
12287 if (!aux->func_info)
12288 return 0;
12289
12290 for (i = 1; i < env->subprog_cnt; i++) {
12291 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12292 continue;
12293 env->insn_idx = env->subprog_info[i].start;
12294 WARN_ON_ONCE(env->insn_idx == 0);
12295 ret = do_check_common(env, i);
12296 if (ret) {
12297 return ret;
12298 } else if (env->log.level & BPF_LOG_LEVEL) {
12299 verbose(env,
12300 "Func#%d is safe for any args that match its prototype\n",
12301 i);
12302 }
12303 }
12304 return 0;
12305}
12306
12307static int do_check_main(struct bpf_verifier_env *env)
12308{
12309 int ret;
12310
12311 env->insn_idx = 0;
12312 ret = do_check_common(env, 0);
12313 if (!ret)
12314 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12315 return ret;
12316}
12317
12318
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012319static void print_verification_stats(struct bpf_verifier_env *env)
12320{
12321 int i;
12322
12323 if (env->log.level & BPF_LOG_STATS) {
12324 verbose(env, "verification time %lld usec\n",
12325 div_u64(env->verification_time, 1000));
12326 verbose(env, "stack depth ");
12327 for (i = 0; i < env->subprog_cnt; i++) {
12328 u32 depth = env->subprog_info[i].stack_depth;
12329
12330 verbose(env, "%d", depth);
12331 if (i + 1 < env->subprog_cnt)
12332 verbose(env, "+");
12333 }
12334 verbose(env, "\n");
12335 }
12336 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12337 "total_states %d peak_states %d mark_read %d\n",
12338 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12339 env->max_states_per_insn, env->total_states,
12340 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012341}
12342
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012343static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12344{
12345 const struct btf_type *t, *func_proto;
12346 const struct bpf_struct_ops *st_ops;
12347 const struct btf_member *member;
12348 struct bpf_prog *prog = env->prog;
12349 u32 btf_id, member_idx;
12350 const char *mname;
12351
12352 btf_id = prog->aux->attach_btf_id;
12353 st_ops = bpf_struct_ops_find(btf_id);
12354 if (!st_ops) {
12355 verbose(env, "attach_btf_id %u is not a supported struct\n",
12356 btf_id);
12357 return -ENOTSUPP;
12358 }
12359
12360 t = st_ops->type;
12361 member_idx = prog->expected_attach_type;
12362 if (member_idx >= btf_type_vlen(t)) {
12363 verbose(env, "attach to invalid member idx %u of struct %s\n",
12364 member_idx, st_ops->name);
12365 return -EINVAL;
12366 }
12367
12368 member = &btf_type_member(t)[member_idx];
12369 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12370 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12371 NULL);
12372 if (!func_proto) {
12373 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12374 mname, member_idx, st_ops->name);
12375 return -EINVAL;
12376 }
12377
12378 if (st_ops->check_member) {
12379 int err = st_ops->check_member(t, member);
12380
12381 if (err) {
12382 verbose(env, "attach to unsupported member %s of struct %s\n",
12383 mname, st_ops->name);
12384 return err;
12385 }
12386 }
12387
12388 prog->aux->attach_func_proto = func_proto;
12389 prog->aux->attach_func_name = mname;
12390 env->ops = st_ops->verifier_ops;
12391
12392 return 0;
12393}
KP Singh6ba43b72020-03-04 20:18:50 +010012394#define SECURITY_PREFIX "security_"
12395
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012396static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010012397{
KP Singh69191752020-03-05 21:49:55 +010012398 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012399 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010012400 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010012401
KP Singh6ba43b72020-03-04 20:18:50 +010012402 return -EINVAL;
12403}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012404
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012405/* list of non-sleepable functions that are otherwise on
12406 * ALLOW_ERROR_INJECTION list
12407 */
12408BTF_SET_START(btf_non_sleepable_error_inject)
12409/* Three functions below can be called from sleepable and non-sleepable context.
12410 * Assume non-sleepable from bpf safety point of view.
12411 */
12412BTF_ID(func, __add_to_page_cache_locked)
12413BTF_ID(func, should_fail_alloc_page)
12414BTF_ID(func, should_failslab)
12415BTF_SET_END(btf_non_sleepable_error_inject)
12416
12417static int check_non_sleepable_error_inject(u32 btf_id)
12418{
12419 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12420}
12421
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012422int bpf_check_attach_target(struct bpf_verifier_log *log,
12423 const struct bpf_prog *prog,
12424 const struct bpf_prog *tgt_prog,
12425 u32 btf_id,
12426 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070012427{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012428 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012429 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012430 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012431 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012432 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012433 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012434 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012435 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012436
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012437 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012438 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012439 return -EINVAL;
12440 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012441 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012442 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012443 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012444 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12445 return -EINVAL;
12446 }
12447 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012448 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012449 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012450 return -EINVAL;
12451 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012452 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012453 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012454 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012455 return -EINVAL;
12456 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012457 if (tgt_prog) {
12458 struct bpf_prog_aux *aux = tgt_prog->aux;
12459
12460 for (i = 0; i < aux->func_info_cnt; i++)
12461 if (aux->func_info[i].type_id == btf_id) {
12462 subprog = i;
12463 break;
12464 }
12465 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012466 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012467 return -EINVAL;
12468 }
12469 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012470 if (prog_extension) {
12471 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012472 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012473 "Cannot replace static functions\n");
12474 return -EINVAL;
12475 }
12476 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012477 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012478 "Extension programs should be JITed\n");
12479 return -EINVAL;
12480 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012481 }
12482 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012483 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012484 return -EINVAL;
12485 }
12486 if (tgt_prog->type == prog->type) {
12487 /* Cannot fentry/fexit another fentry/fexit program.
12488 * Cannot attach program extension to another extension.
12489 * It's ok to attach fentry/fexit to extension program.
12490 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012491 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012492 return -EINVAL;
12493 }
12494 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12495 prog_extension &&
12496 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12497 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12498 /* Program extensions can extend all program types
12499 * except fentry/fexit. The reason is the following.
12500 * The fentry/fexit programs are used for performance
12501 * analysis, stats and can be attached to any program
12502 * type except themselves. When extension program is
12503 * replacing XDP function it is necessary to allow
12504 * performance analysis of all functions. Both original
12505 * XDP program and its program extension. Hence
12506 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12507 * allowed. If extending of fentry/fexit was allowed it
12508 * would be possible to create long call chain
12509 * fentry->extension->fentry->extension beyond
12510 * reasonable stack size. Hence extending fentry is not
12511 * allowed.
12512 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012513 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012514 return -EINVAL;
12515 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012516 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012517 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012518 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012519 return -EINVAL;
12520 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012521 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012522
12523 switch (prog->expected_attach_type) {
12524 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012525 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012526 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012527 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12528 return -EINVAL;
12529 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070012530 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012531 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012532 btf_id);
12533 return -EINVAL;
12534 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012535 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012536 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012537 btf_id, tname);
12538 return -EINVAL;
12539 }
12540 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012541 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012542 if (!btf_type_is_ptr(t))
12543 /* should never happen in valid vmlinux build */
12544 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012545 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012546 if (!btf_type_is_func_proto(t))
12547 /* should never happen in valid vmlinux build */
12548 return -EINVAL;
12549
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012550 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070012551 case BPF_TRACE_ITER:
12552 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012553 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070012554 btf_id);
12555 return -EINVAL;
12556 }
12557 t = btf_type_by_id(btf, t->type);
12558 if (!btf_type_is_func_proto(t))
12559 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012560 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12561 if (ret)
12562 return ret;
12563 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012564 default:
12565 if (!prog_extension)
12566 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050012567 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010012568 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010012569 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012570 case BPF_TRACE_FENTRY:
12571 case BPF_TRACE_FEXIT:
12572 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012573 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012574 btf_id);
12575 return -EINVAL;
12576 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012577 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012578 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012579 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012580 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012581 if (!btf_type_is_func_proto(t))
12582 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012583
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012584 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12585 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12586 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12587 return -EINVAL;
12588
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012589 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012590 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012591
12592 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012593 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012594 return ret;
12595
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012596 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080012597 if (subprog == 0)
12598 addr = (long) tgt_prog->bpf_func;
12599 else
12600 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012601 } else {
12602 addr = kallsyms_lookup_name(tname);
12603 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012604 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012605 "The address of function %s cannot be found\n",
12606 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012607 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012608 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012609 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012610
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012611 if (prog->aux->sleepable) {
12612 ret = -EINVAL;
12613 switch (prog->type) {
12614 case BPF_PROG_TYPE_TRACING:
12615 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12616 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12617 */
12618 if (!check_non_sleepable_error_inject(btf_id) &&
12619 within_error_injection_list(addr))
12620 ret = 0;
12621 break;
12622 case BPF_PROG_TYPE_LSM:
12623 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12624 * Only some of them are sleepable.
12625 */
KP Singh423f1612020-11-13 00:59:29 +000012626 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012627 ret = 0;
12628 break;
12629 default:
12630 break;
12631 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012632 if (ret) {
12633 bpf_log(log, "%s is not sleepable\n", tname);
12634 return ret;
12635 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012636 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012637 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012638 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012639 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012640 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012641 ret = check_attach_modify_return(addr, tname);
12642 if (ret) {
12643 bpf_log(log, "%s() is not modifiable\n", tname);
12644 return ret;
12645 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012646 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012647
12648 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012649 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012650 tgt_info->tgt_addr = addr;
12651 tgt_info->tgt_name = tname;
12652 tgt_info->tgt_type = t;
12653 return 0;
12654}
12655
12656static int check_attach_btf_id(struct bpf_verifier_env *env)
12657{
12658 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012659 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012660 struct bpf_attach_target_info tgt_info = {};
12661 u32 btf_id = prog->aux->attach_btf_id;
12662 struct bpf_trampoline *tr;
12663 int ret;
12664 u64 key;
12665
12666 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12667 prog->type != BPF_PROG_TYPE_LSM) {
12668 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12669 return -EINVAL;
12670 }
12671
12672 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12673 return check_struct_ops_btf_id(env);
12674
12675 if (prog->type != BPF_PROG_TYPE_TRACING &&
12676 prog->type != BPF_PROG_TYPE_LSM &&
12677 prog->type != BPF_PROG_TYPE_EXT)
12678 return 0;
12679
12680 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12681 if (ret)
12682 return ret;
12683
12684 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012685 /* to make freplace equivalent to their targets, they need to
12686 * inherit env->ops and expected_attach_type for the rest of the
12687 * verification
12688 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012689 env->ops = bpf_verifier_ops[tgt_prog->type];
12690 prog->expected_attach_type = tgt_prog->expected_attach_type;
12691 }
12692
12693 /* store info about the attachment target that will be used later */
12694 prog->aux->attach_func_proto = tgt_info.tgt_type;
12695 prog->aux->attach_func_name = tgt_info.tgt_name;
12696
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012697 if (tgt_prog) {
12698 prog->aux->saved_dst_prog_type = tgt_prog->type;
12699 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12700 }
12701
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012702 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12703 prog->aux->attach_btf_trace = true;
12704 return 0;
12705 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12706 if (!bpf_iter_prog_supported(prog))
12707 return -EINVAL;
12708 return 0;
12709 }
12710
12711 if (prog->type == BPF_PROG_TYPE_LSM) {
12712 ret = bpf_lsm_verify_prog(&env->log, prog);
12713 if (ret < 0)
12714 return ret;
12715 }
12716
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012717 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012718 tr = bpf_trampoline_get(key, &tgt_info);
12719 if (!tr)
12720 return -ENOMEM;
12721
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012722 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012723 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012724}
12725
Alan Maguire76654e62020-09-28 12:31:03 +010012726struct btf *bpf_get_btf_vmlinux(void)
12727{
12728 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12729 mutex_lock(&bpf_verifier_lock);
12730 if (!btf_vmlinux)
12731 btf_vmlinux = btf_parse_vmlinux();
12732 mutex_unlock(&bpf_verifier_lock);
12733 }
12734 return btf_vmlinux;
12735}
12736
Yonghong Song838e9692018-11-19 15:29:11 -080012737int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12738 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012739{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012740 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012741 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070012742 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012743 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012744 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012745
Arnd Bergmanneba0c922017-11-02 12:05:52 +010012746 /* no program is valid */
12747 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12748 return -EINVAL;
12749
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012750 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012751 * allocate/free it every time bpf_check() is called
12752 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012753 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012754 if (!env)
12755 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012756 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012757
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012758 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070012759 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012760 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012761 ret = -ENOMEM;
12762 if (!env->insn_aux_data)
12763 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012764 for (i = 0; i < len; i++)
12765 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012766 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070012767 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012768 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012769
Alan Maguire76654e62020-09-28 12:31:03 +010012770 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012771
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012772 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012773 if (!is_priv)
12774 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012775
12776 if (attr->log_level || attr->log_buf || attr->log_size) {
12777 /* user requested verbose verifier output
12778 * and supplied buffer to store the verification trace
12779 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012780 log->level = attr->log_level;
12781 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12782 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012783
12784 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012785 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070012786 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012787 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012788 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012789 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012790
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012791 if (IS_ERR(btf_vmlinux)) {
12792 /* Either gcc or pahole or kernel are broken. */
12793 verbose(env, "in-kernel BTF is malformed\n");
12794 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012795 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012796 }
12797
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012798 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12799 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070012800 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080012801 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12802 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012803
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012804 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050012805 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070012806 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012807 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12808 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12809 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012810
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070012811 if (is_priv)
12812 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12813
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012814 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000012815 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012816 if (ret)
12817 goto skip_full_check;
12818 }
12819
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012820 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012821 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012822 GFP_USER);
12823 ret = -ENOMEM;
12824 if (!env->explored_states)
12825 goto skip_full_check;
12826
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012827 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070012828 if (ret < 0)
12829 goto skip_full_check;
12830
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012831 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080012832 if (ret < 0)
12833 goto skip_full_check;
12834
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012835 ret = check_attach_btf_id(env);
12836 if (ret)
12837 goto skip_full_check;
12838
Hao Luo4976b712020-09-29 16:50:44 -070012839 ret = resolve_pseudo_ldimm64(env);
12840 if (ret < 0)
12841 goto skip_full_check;
12842
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012843 ret = check_cfg(env);
12844 if (ret < 0)
12845 goto skip_full_check;
12846
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012847 ret = do_check_subprogs(env);
12848 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012849
Quentin Monnetc941ce92018-10-07 12:56:47 +010012850 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12851 ret = bpf_prog_offload_finalize(env);
12852
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012853skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012854 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012855
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012856 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080012857 ret = check_max_stack_depth(env);
12858
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012859 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012860 if (is_priv) {
12861 if (ret == 0)
12862 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012863 if (ret == 0)
12864 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080012865 if (ret == 0)
12866 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012867 } else {
12868 if (ret == 0)
12869 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012870 }
12871
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012872 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012873 /* program is valid, convert *(u32*)(ctx + off) accesses */
12874 ret = convert_ctx_accesses(env);
12875
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012876 if (ret == 0)
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012877 ret = do_misc_fixups(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012878
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012879 /* do 32-bit optimization after insn patching has done so those patched
12880 * insns could be handled correctly.
12881 */
Jiong Wangd6c23082019-05-24 23:25:18 +010012882 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12883 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12884 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12885 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012886 }
12887
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012888 if (ret == 0)
12889 ret = fixup_call_args(env);
12890
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012891 env->verification_time = ktime_get_ns() - start_time;
12892 print_verification_stats(env);
12893
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012894 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012895 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012896 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012897 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012898 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012899 }
12900
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012901 if (ret)
12902 goto err_release_maps;
12903
12904 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012905 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012906 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12907 sizeof(env->used_maps[0]),
12908 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012909
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012910 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012911 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012912 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012913 }
12914
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012915 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012916 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012917 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012918 }
12919 if (env->used_btf_cnt) {
12920 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12921 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12922 sizeof(env->used_btfs[0]),
12923 GFP_KERNEL);
12924 if (!env->prog->aux->used_btfs) {
12925 ret = -ENOMEM;
12926 goto err_release_maps;
12927 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012928
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012929 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12930 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12931 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12932 }
12933 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012934 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12935 * bpf_ld_imm64 instructions
12936 */
12937 convert_pseudo_ld_imm64(env);
12938 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012939
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012940 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080012941
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012942err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012943 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012944 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070012945 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012946 */
12947 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012948 if (!env->prog->aux->used_btfs)
12949 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020012950
12951 /* extension progs temporarily inherit the attach_type of their targets
12952 for verification purposes, so set it back to zero before returning
12953 */
12954 if (env->prog->type == BPF_PROG_TYPE_EXT)
12955 env->prog->expected_attach_type = 0;
12956
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012957 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012958err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012959 if (!is_priv)
12960 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012961 vfree(env->insn_aux_data);
12962err_free_env:
12963 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012964 return ret;
12965}