blob: 97e772f44cd77839ef7a99c4e869d555a657692b [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
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200237struct bpf_call_arg_meta {
238 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200239 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200240 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200241 int regno;
242 int access_size;
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700243 int mem_size;
John Fastabend10060502020-03-30 14:36:19 -0700244 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700245 int ref_obj_id;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800246 int func_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800247 struct btf *btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700248 u32 btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800249 struct btf *ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700250 u32 ret_btf_id;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200251};
252
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700253struct btf *btf_vmlinux;
254
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700255static DEFINE_MUTEX(bpf_verifier_lock);
256
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800257static const struct bpf_line_info *
258find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
259{
260 const struct bpf_line_info *linfo;
261 const struct bpf_prog *prog;
262 u32 i, nr_linfo;
263
264 prog = env->prog;
265 nr_linfo = prog->aux->nr_linfo;
266
267 if (!nr_linfo || insn_off >= prog->len)
268 return NULL;
269
270 linfo = prog->aux->linfo;
271 for (i = 1; i < nr_linfo; i++)
272 if (insn_off < linfo[i].insn_off)
273 break;
274
275 return &linfo[i - 1];
276}
277
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700278void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
279 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700280{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700281 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700282
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700283 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700284
285 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
286 "verifier log line truncated - local buffer too short\n");
287
288 n = min(log->len_total - log->len_used - 1, n);
289 log->kbuf[n] = '\0';
290
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700291 if (log->level == BPF_LOG_KERNEL) {
292 pr_err("BPF:%s\n", log->kbuf);
293 return;
294 }
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700295 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
296 log->len_used += n;
297 else
298 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700299}
Jiri Olsaabe08842018-03-23 11:41:28 +0100300
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700301static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
302{
303 char zero = 0;
304
305 if (!bpf_verifier_log_needed(log))
306 return;
307
308 log->len_used = new_pos;
309 if (put_user(zero, log->ubuf + new_pos))
310 log->ubuf = NULL;
311}
312
Jiri Olsaabe08842018-03-23 11:41:28 +0100313/* log_level controls verbosity level of eBPF verifier.
314 * bpf_verifier_log_write() is used to dump the verification trace to the log,
315 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000316 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100317__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
318 const char *fmt, ...)
319{
320 va_list args;
321
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700322 if (!bpf_verifier_log_needed(&env->log))
323 return;
324
Jiri Olsaabe08842018-03-23 11:41:28 +0100325 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700326 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100327 va_end(args);
328}
329EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
330
331__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
332{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700333 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100334 va_list args;
335
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700336 if (!bpf_verifier_log_needed(&env->log))
337 return;
338
Jiri Olsaabe08842018-03-23 11:41:28 +0100339 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700340 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100341 va_end(args);
342}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700343
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700344__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
345 const char *fmt, ...)
346{
347 va_list args;
348
349 if (!bpf_verifier_log_needed(log))
350 return;
351
352 va_start(args, fmt);
353 bpf_verifier_vlog(log, fmt, args);
354 va_end(args);
355}
356
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800357static const char *ltrim(const char *s)
358{
359 while (isspace(*s))
360 s++;
361
362 return s;
363}
364
365__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
366 u32 insn_off,
367 const char *prefix_fmt, ...)
368{
369 const struct bpf_line_info *linfo;
370
371 if (!bpf_verifier_log_needed(&env->log))
372 return;
373
374 linfo = find_linfo(env, insn_off);
375 if (!linfo || linfo == env->prev_linfo)
376 return;
377
378 if (prefix_fmt) {
379 va_list args;
380
381 va_start(args, prefix_fmt);
382 bpf_verifier_vlog(&env->log, prefix_fmt, args);
383 va_end(args);
384 }
385
386 verbose(env, "%s\n",
387 ltrim(btf_name_by_offset(env->prog->aux->btf,
388 linfo->line_off)));
389
390 env->prev_linfo = linfo;
391}
392
Yonghong Songbc2591d2021-02-26 12:49:22 -0800393static void verbose_invalid_scalar(struct bpf_verifier_env *env,
394 struct bpf_reg_state *reg,
395 struct tnum *range, const char *ctx,
396 const char *reg_name)
397{
398 char tn_buf[48];
399
400 verbose(env, "At %s the register %s ", ctx, reg_name);
401 if (!tnum_is_unknown(reg->var_off)) {
402 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
403 verbose(env, "has value %s", tn_buf);
404 } else {
405 verbose(env, "has unknown scalar value");
406 }
407 tnum_strn(tn_buf, sizeof(tn_buf), *range);
408 verbose(env, " should have been in %s\n", tn_buf);
409}
410
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200411static bool type_is_pkt_pointer(enum bpf_reg_type type)
412{
413 return type == PTR_TO_PACKET ||
414 type == PTR_TO_PACKET_META;
415}
416
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800417static bool type_is_sk_pointer(enum bpf_reg_type type)
418{
419 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800420 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700421 type == PTR_TO_TCP_SOCK ||
422 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800423}
424
John Fastabendcac616d2020-05-21 13:07:26 -0700425static bool reg_type_not_null(enum bpf_reg_type type)
426{
427 return type == PTR_TO_SOCKET ||
428 type == PTR_TO_TCP_SOCK ||
429 type == PTR_TO_MAP_VALUE ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700430 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700431}
432
Joe Stringer840b9612018-10-02 13:35:32 -0700433static bool reg_type_may_be_null(enum bpf_reg_type type)
434{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700435 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800436 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800437 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700438 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700439 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700440 type == PTR_TO_MEM_OR_NULL ||
441 type == PTR_TO_RDONLY_BUF_OR_NULL ||
442 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700443}
444
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800445static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
446{
447 return reg->type == PTR_TO_MAP_VALUE &&
448 map_value_has_spin_lock(reg->map_ptr);
449}
450
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700451static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
452{
453 return type == PTR_TO_SOCKET ||
454 type == PTR_TO_SOCKET_OR_NULL ||
455 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700456 type == PTR_TO_TCP_SOCK_OR_NULL ||
457 type == PTR_TO_MEM ||
458 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700459}
460
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700461static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700462{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700463 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700464}
465
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100466static bool arg_type_may_be_null(enum bpf_arg_type type)
467{
468 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
469 type == ARG_PTR_TO_MEM_OR_NULL ||
470 type == ARG_PTR_TO_CTX_OR_NULL ||
471 type == ARG_PTR_TO_SOCKET_OR_NULL ||
472 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
473}
474
Joe Stringerfd978bf72018-10-02 13:35:35 -0700475/* Determine whether the function releases some resources allocated by another
476 * function call. The first reference type argument will be assumed to be
477 * released by release_reference().
478 */
479static bool is_release_function(enum bpf_func_id func_id)
480{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700481 return func_id == BPF_FUNC_sk_release ||
482 func_id == BPF_FUNC_ringbuf_submit ||
483 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700484}
485
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200486static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800487{
488 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800489 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200490 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700491 func_id == BPF_FUNC_map_lookup_elem ||
492 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200493}
494
495static bool is_acquire_function(enum bpf_func_id func_id,
496 const struct bpf_map *map)
497{
498 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
499
500 if (func_id == BPF_FUNC_sk_lookup_tcp ||
501 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700502 func_id == BPF_FUNC_skc_lookup_tcp ||
503 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200504 return true;
505
506 if (func_id == BPF_FUNC_map_lookup_elem &&
507 (map_type == BPF_MAP_TYPE_SOCKMAP ||
508 map_type == BPF_MAP_TYPE_SOCKHASH))
509 return true;
510
511 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800512}
513
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700514static bool is_ptr_cast_function(enum bpf_func_id func_id)
515{
516 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700517 func_id == BPF_FUNC_sk_fullsock ||
518 func_id == BPF_FUNC_skc_to_tcp_sock ||
519 func_id == BPF_FUNC_skc_to_tcp6_sock ||
520 func_id == BPF_FUNC_skc_to_udp6_sock ||
521 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
522 func_id == BPF_FUNC_skc_to_tcp_request_sock;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700523}
524
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700525/* string representation of 'enum bpf_reg_type' */
526static const char * const reg_type_str[] = {
527 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100528 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700529 [PTR_TO_CTX] = "ctx",
530 [CONST_PTR_TO_MAP] = "map_ptr",
531 [PTR_TO_MAP_VALUE] = "map_value",
532 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700533 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700534 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200535 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700536 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700537 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700538 [PTR_TO_SOCKET] = "sock",
539 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800540 [PTR_TO_SOCK_COMMON] = "sock_common",
541 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800542 [PTR_TO_TCP_SOCK] = "tcp_sock",
543 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700544 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700545 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700546 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700547 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700548 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700549 [PTR_TO_MEM] = "mem",
550 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700551 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
552 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
553 [PTR_TO_RDWR_BUF] = "rdwr_buf",
554 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700555};
556
Edward Cree8efea212018-08-22 20:02:44 +0100557static char slot_type_char[] = {
558 [STACK_INVALID] = '?',
559 [STACK_SPILL] = 'r',
560 [STACK_MISC] = 'm',
561 [STACK_ZERO] = '0',
562};
563
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800564static void print_liveness(struct bpf_verifier_env *env,
565 enum bpf_reg_liveness live)
566{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800567 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800568 verbose(env, "_");
569 if (live & REG_LIVE_READ)
570 verbose(env, "r");
571 if (live & REG_LIVE_WRITTEN)
572 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800573 if (live & REG_LIVE_DONE)
574 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800575}
576
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800577static struct bpf_func_state *func(struct bpf_verifier_env *env,
578 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700579{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800580 struct bpf_verifier_state *cur = env->cur_state;
581
582 return cur->frame[reg->frameno];
583}
584
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800585static const char *kernel_type_name(const struct btf* btf, u32 id)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700586{
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800587 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700588}
589
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800590static void print_verifier_state(struct bpf_verifier_env *env,
591 const struct bpf_func_state *state)
592{
593 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700594 enum bpf_reg_type t;
595 int i;
596
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800597 if (state->frameno)
598 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700599 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700600 reg = &state->regs[i];
601 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700602 if (t == NOT_INIT)
603 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800604 verbose(env, " R%d", i);
605 print_liveness(env, reg->live);
606 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700607 if (t == SCALAR_VALUE && reg->precise)
608 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100609 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
610 tnum_is_const(reg->var_off)) {
611 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700612 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100613 } else {
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700614 if (t == PTR_TO_BTF_ID ||
615 t == PTR_TO_BTF_ID_OR_NULL ||
616 t == PTR_TO_PERCPU_BTF_ID)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800617 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700618 verbose(env, "(id=%d", reg->id);
619 if (reg_type_may_be_refcounted_or_null(t))
620 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100621 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700622 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200623 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700624 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100625 else if (t == CONST_PTR_TO_MAP ||
626 t == PTR_TO_MAP_VALUE ||
627 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700628 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100629 reg->map_ptr->key_size,
630 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100631 if (tnum_is_const(reg->var_off)) {
632 /* Typically an immediate SCALAR_VALUE, but
633 * could be a pointer whose offset is too big
634 * for reg->off
635 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700636 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100637 } else {
638 if (reg->smin_value != reg->umin_value &&
639 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700640 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100641 (long long)reg->smin_value);
642 if (reg->smax_value != reg->umax_value &&
643 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700644 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100645 (long long)reg->smax_value);
646 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700647 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100648 (unsigned long long)reg->umin_value);
649 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700650 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100651 (unsigned long long)reg->umax_value);
652 if (!tnum_is_unknown(reg->var_off)) {
653 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100654
Edward Cree7d1238f2017-08-07 15:26:56 +0100655 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700656 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100657 }
John Fastabend3f50f132020-03-30 14:36:39 -0700658 if (reg->s32_min_value != reg->smin_value &&
659 reg->s32_min_value != S32_MIN)
660 verbose(env, ",s32_min_value=%d",
661 (int)(reg->s32_min_value));
662 if (reg->s32_max_value != reg->smax_value &&
663 reg->s32_max_value != S32_MAX)
664 verbose(env, ",s32_max_value=%d",
665 (int)(reg->s32_max_value));
666 if (reg->u32_min_value != reg->umin_value &&
667 reg->u32_min_value != U32_MIN)
668 verbose(env, ",u32_min_value=%d",
669 (int)(reg->u32_min_value));
670 if (reg->u32_max_value != reg->umax_value &&
671 reg->u32_max_value != U32_MAX)
672 verbose(env, ",u32_max_value=%d",
673 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100674 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700675 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100676 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700677 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700678 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100679 char types_buf[BPF_REG_SIZE + 1];
680 bool valid = false;
681 int j;
682
683 for (j = 0; j < BPF_REG_SIZE; j++) {
684 if (state->stack[i].slot_type[j] != STACK_INVALID)
685 valid = true;
686 types_buf[j] = slot_type_char[
687 state->stack[i].slot_type[j]];
688 }
689 types_buf[BPF_REG_SIZE] = 0;
690 if (!valid)
691 continue;
692 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
693 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700694 if (state->stack[i].slot_type[0] == STACK_SPILL) {
695 reg = &state->stack[i].spilled_ptr;
696 t = reg->type;
697 verbose(env, "=%s", reg_type_str[t]);
698 if (t == SCALAR_VALUE && reg->precise)
699 verbose(env, "P");
700 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
701 verbose(env, "%lld", reg->var_off.value + reg->off);
702 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100703 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700704 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700705 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700706 if (state->acquired_refs && state->refs[0].id) {
707 verbose(env, " refs=%d", state->refs[0].id);
708 for (i = 1; i < state->acquired_refs; i++)
709 if (state->refs[i].id)
710 verbose(env, ",%d", state->refs[i].id);
711 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700712 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700713}
714
Joe Stringer84dbf352018-10-02 13:35:34 -0700715#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
716static int copy_##NAME##_state(struct bpf_func_state *dst, \
717 const struct bpf_func_state *src) \
718{ \
719 if (!src->FIELD) \
720 return 0; \
721 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
722 /* internal bug, make state invalid to reject the program */ \
723 memset(dst, 0, sizeof(*dst)); \
724 return -EFAULT; \
725 } \
726 memcpy(dst->FIELD, src->FIELD, \
727 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
728 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700729}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700730/* copy_reference_state() */
731COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700732/* copy_stack_state() */
733COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
734#undef COPY_STATE_FN
735
736#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
737static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
738 bool copy_old) \
739{ \
740 u32 old_size = state->COUNT; \
741 struct bpf_##NAME##_state *new_##FIELD; \
742 int slot = size / SIZE; \
743 \
744 if (size <= old_size || !size) { \
745 if (copy_old) \
746 return 0; \
747 state->COUNT = slot * SIZE; \
748 if (!size && old_size) { \
749 kfree(state->FIELD); \
750 state->FIELD = NULL; \
751 } \
752 return 0; \
753 } \
754 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
755 GFP_KERNEL); \
756 if (!new_##FIELD) \
757 return -ENOMEM; \
758 if (copy_old) { \
759 if (state->FIELD) \
760 memcpy(new_##FIELD, state->FIELD, \
761 sizeof(*new_##FIELD) * (old_size / SIZE)); \
762 memset(new_##FIELD + old_size / SIZE, 0, \
763 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
764 } \
765 state->COUNT = slot * SIZE; \
766 kfree(state->FIELD); \
767 state->FIELD = new_##FIELD; \
768 return 0; \
769}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700770/* realloc_reference_state() */
771REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700772/* realloc_stack_state() */
773REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
774#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700775
776/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
777 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800778 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700779 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
780 * which realloc_stack_state() copies over. It points to previous
781 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700782 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700783static int realloc_func_state(struct bpf_func_state *state, int stack_size,
784 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700785{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700786 int err = realloc_reference_state(state, refs_size, copy_old);
787 if (err)
788 return err;
789 return realloc_stack_state(state, stack_size, copy_old);
790}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700791
Joe Stringerfd978bf72018-10-02 13:35:35 -0700792/* Acquire a pointer id from the env and update the state->refs to include
793 * this new pointer reference.
794 * On success, returns a valid pointer id to associate with the register
795 * On failure, returns a negative errno.
796 */
797static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
798{
799 struct bpf_func_state *state = cur_func(env);
800 int new_ofs = state->acquired_refs;
801 int id, err;
802
803 err = realloc_reference_state(state, state->acquired_refs + 1, true);
804 if (err)
805 return err;
806 id = ++env->id_gen;
807 state->refs[new_ofs].id = id;
808 state->refs[new_ofs].insn_idx = insn_idx;
809
810 return id;
811}
812
813/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800814static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700815{
816 int i, last_idx;
817
Joe Stringerfd978bf72018-10-02 13:35:35 -0700818 last_idx = state->acquired_refs - 1;
819 for (i = 0; i < state->acquired_refs; i++) {
820 if (state->refs[i].id == ptr_id) {
821 if (last_idx && i != last_idx)
822 memcpy(&state->refs[i], &state->refs[last_idx],
823 sizeof(*state->refs));
824 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
825 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700826 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700827 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700828 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800829 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700830}
831
832static int transfer_reference_state(struct bpf_func_state *dst,
833 struct bpf_func_state *src)
834{
835 int err = realloc_reference_state(dst, src->acquired_refs, false);
836 if (err)
837 return err;
838 err = copy_reference_state(dst, src);
839 if (err)
840 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700841 return 0;
842}
843
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800844static void free_func_state(struct bpf_func_state *state)
845{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800846 if (!state)
847 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700848 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800849 kfree(state->stack);
850 kfree(state);
851}
852
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700853static void clear_jmp_history(struct bpf_verifier_state *state)
854{
855 kfree(state->jmp_history);
856 state->jmp_history = NULL;
857 state->jmp_history_cnt = 0;
858}
859
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700860static void free_verifier_state(struct bpf_verifier_state *state,
861 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700862{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800863 int i;
864
865 for (i = 0; i <= state->curframe; i++) {
866 free_func_state(state->frame[i]);
867 state->frame[i] = NULL;
868 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700869 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700870 if (free_self)
871 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700872}
873
874/* copy verifier state from src to dst growing dst stack space
875 * when necessary to accommodate larger src stack
876 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800877static int copy_func_state(struct bpf_func_state *dst,
878 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700879{
880 int err;
881
Joe Stringerfd978bf72018-10-02 13:35:35 -0700882 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
883 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700884 if (err)
885 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700886 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
887 err = copy_reference_state(dst, src);
888 if (err)
889 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700890 return copy_stack_state(dst, src);
891}
892
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800893static int copy_verifier_state(struct bpf_verifier_state *dst_state,
894 const struct bpf_verifier_state *src)
895{
896 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700897 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800898 int i, err;
899
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700900 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
901 kfree(dst_state->jmp_history);
902 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
903 if (!dst_state->jmp_history)
904 return -ENOMEM;
905 }
906 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
907 dst_state->jmp_history_cnt = src->jmp_history_cnt;
908
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800909 /* if dst has more stack frames then src frame, free them */
910 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
911 free_func_state(dst_state->frame[i]);
912 dst_state->frame[i] = NULL;
913 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100914 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800915 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800916 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700917 dst_state->branches = src->branches;
918 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700919 dst_state->first_insn_idx = src->first_insn_idx;
920 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800921 for (i = 0; i <= src->curframe; i++) {
922 dst = dst_state->frame[i];
923 if (!dst) {
924 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
925 if (!dst)
926 return -ENOMEM;
927 dst_state->frame[i] = dst;
928 }
929 err = copy_func_state(dst, src->frame[i]);
930 if (err)
931 return err;
932 }
933 return 0;
934}
935
Alexei Starovoitov25897262019-06-15 12:12:20 -0700936static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
937{
938 while (st) {
939 u32 br = --st->branches;
940
941 /* WARN_ON(br > 1) technically makes sense here,
942 * but see comment in push_stack(), hence:
943 */
944 WARN_ONCE((int)br < 0,
945 "BUG update_branch_counts:branches_to_explore=%d\n",
946 br);
947 if (br)
948 break;
949 st = st->parent;
950 }
951}
952
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700953static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700954 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700955{
956 struct bpf_verifier_state *cur = env->cur_state;
957 struct bpf_verifier_stack_elem *elem, *head = env->head;
958 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700959
960 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700961 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700962
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700963 if (cur) {
964 err = copy_verifier_state(cur, &head->st);
965 if (err)
966 return err;
967 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700968 if (pop_log)
969 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700970 if (insn_idx)
971 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700972 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700973 *prev_insn_idx = head->prev_insn_idx;
974 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700975 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700976 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700977 env->head = elem;
978 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700979 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700980}
981
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100982static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100983 int insn_idx, int prev_insn_idx,
984 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700985{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700986 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100987 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700988 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700989
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700990 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700991 if (!elem)
992 goto err;
993
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700994 elem->insn_idx = insn_idx;
995 elem->prev_insn_idx = prev_insn_idx;
996 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700997 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700998 env->head = elem;
999 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001000 err = copy_verifier_state(&elem->st, cur);
1001 if (err)
1002 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001003 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -07001004 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1005 verbose(env, "The sequence of %d jumps is too complex.\n",
1006 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001007 goto err;
1008 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07001009 if (elem->st.parent) {
1010 ++elem->st.parent->branches;
1011 /* WARN_ON(branches > 2) technically makes sense here,
1012 * but
1013 * 1. speculative states will bump 'branches' for non-branch
1014 * instructions
1015 * 2. is_state_visited() heuristics may decide not to create
1016 * a new state for a sequence of branches and all such current
1017 * and cloned states will be pointing to a single parent state
1018 * which might have large 'branches' count.
1019 */
1020 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001021 return &elem->st;
1022err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001023 free_verifier_state(env->cur_state, true);
1024 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001025 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001026 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001027 return NULL;
1028}
1029
1030#define CALLER_SAVED_REGS 6
1031static const int caller_saved[CALLER_SAVED_REGS] = {
1032 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1033};
1034
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001035static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1036 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001037
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001038/* This helper doesn't clear reg->id */
1039static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001040{
Edward Creeb03c9f92017-08-07 15:26:36 +01001041 reg->var_off = tnum_const(imm);
1042 reg->smin_value = (s64)imm;
1043 reg->smax_value = (s64)imm;
1044 reg->umin_value = imm;
1045 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001046
1047 reg->s32_min_value = (s32)imm;
1048 reg->s32_max_value = (s32)imm;
1049 reg->u32_min_value = (u32)imm;
1050 reg->u32_max_value = (u32)imm;
1051}
1052
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001053/* Mark the unknown part of a register (variable offset or scalar value) as
1054 * known to have the value @imm.
1055 */
1056static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1057{
1058 /* Clear id, off, and union(map_ptr, range) */
1059 memset(((u8 *)reg) + sizeof(reg->type), 0,
1060 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1061 ___mark_reg_known(reg, imm);
1062}
1063
John Fastabend3f50f132020-03-30 14:36:39 -07001064static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1065{
1066 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1067 reg->s32_min_value = (s32)imm;
1068 reg->s32_max_value = (s32)imm;
1069 reg->u32_min_value = (u32)imm;
1070 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001071}
1072
Edward Creef1174f72017-08-07 15:26:19 +01001073/* Mark the 'variable offset' part of a register as zero. This should be
1074 * used only on registers holding a pointer type.
1075 */
1076static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1077{
Edward Creeb03c9f92017-08-07 15:26:36 +01001078 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001079}
1080
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001081static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1082{
1083 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001084 reg->type = SCALAR_VALUE;
1085}
1086
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001087static void mark_reg_known_zero(struct bpf_verifier_env *env,
1088 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001089{
1090 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001091 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001092 /* Something bad happened, let's kill all regs */
1093 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001094 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001095 return;
1096 }
1097 __mark_reg_known_zero(regs + regno);
1098}
1099
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001100static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1101{
1102 switch (reg->type) {
1103 case PTR_TO_MAP_VALUE_OR_NULL: {
1104 const struct bpf_map *map = reg->map_ptr;
1105
1106 if (map->inner_map_meta) {
1107 reg->type = CONST_PTR_TO_MAP;
1108 reg->map_ptr = map->inner_map_meta;
1109 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1110 reg->type = PTR_TO_XDP_SOCK;
1111 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1112 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1113 reg->type = PTR_TO_SOCKET;
1114 } else {
1115 reg->type = PTR_TO_MAP_VALUE;
1116 }
1117 break;
1118 }
1119 case PTR_TO_SOCKET_OR_NULL:
1120 reg->type = PTR_TO_SOCKET;
1121 break;
1122 case PTR_TO_SOCK_COMMON_OR_NULL:
1123 reg->type = PTR_TO_SOCK_COMMON;
1124 break;
1125 case PTR_TO_TCP_SOCK_OR_NULL:
1126 reg->type = PTR_TO_TCP_SOCK;
1127 break;
1128 case PTR_TO_BTF_ID_OR_NULL:
1129 reg->type = PTR_TO_BTF_ID;
1130 break;
1131 case PTR_TO_MEM_OR_NULL:
1132 reg->type = PTR_TO_MEM;
1133 break;
1134 case PTR_TO_RDONLY_BUF_OR_NULL:
1135 reg->type = PTR_TO_RDONLY_BUF;
1136 break;
1137 case PTR_TO_RDWR_BUF_OR_NULL:
1138 reg->type = PTR_TO_RDWR_BUF;
1139 break;
1140 default:
1141 WARN_ON("unknown nullable register type");
1142 }
1143}
1144
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001145static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1146{
1147 return type_is_pkt_pointer(reg->type);
1148}
1149
1150static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1151{
1152 return reg_is_pkt_pointer(reg) ||
1153 reg->type == PTR_TO_PACKET_END;
1154}
1155
1156/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1157static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1158 enum bpf_reg_type which)
1159{
1160 /* The register can already have a range from prior markings.
1161 * This is fine as long as it hasn't been advanced from its
1162 * origin.
1163 */
1164 return reg->type == which &&
1165 reg->id == 0 &&
1166 reg->off == 0 &&
1167 tnum_equals_const(reg->var_off, 0);
1168}
1169
John Fastabend3f50f132020-03-30 14:36:39 -07001170/* Reset the min/max bounds of a register */
1171static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1172{
1173 reg->smin_value = S64_MIN;
1174 reg->smax_value = S64_MAX;
1175 reg->umin_value = 0;
1176 reg->umax_value = U64_MAX;
1177
1178 reg->s32_min_value = S32_MIN;
1179 reg->s32_max_value = S32_MAX;
1180 reg->u32_min_value = 0;
1181 reg->u32_max_value = U32_MAX;
1182}
1183
1184static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1185{
1186 reg->smin_value = S64_MIN;
1187 reg->smax_value = S64_MAX;
1188 reg->umin_value = 0;
1189 reg->umax_value = U64_MAX;
1190}
1191
1192static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1193{
1194 reg->s32_min_value = S32_MIN;
1195 reg->s32_max_value = S32_MAX;
1196 reg->u32_min_value = 0;
1197 reg->u32_max_value = U32_MAX;
1198}
1199
1200static void __update_reg32_bounds(struct bpf_reg_state *reg)
1201{
1202 struct tnum var32_off = tnum_subreg(reg->var_off);
1203
1204 /* min signed is max(sign bit) | min(other bits) */
1205 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1206 var32_off.value | (var32_off.mask & S32_MIN));
1207 /* max signed is min(sign bit) | max(other bits) */
1208 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1209 var32_off.value | (var32_off.mask & S32_MAX));
1210 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1211 reg->u32_max_value = min(reg->u32_max_value,
1212 (u32)(var32_off.value | var32_off.mask));
1213}
1214
1215static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001216{
1217 /* min signed is max(sign bit) | min(other bits) */
1218 reg->smin_value = max_t(s64, reg->smin_value,
1219 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1220 /* max signed is min(sign bit) | max(other bits) */
1221 reg->smax_value = min_t(s64, reg->smax_value,
1222 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1223 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1224 reg->umax_value = min(reg->umax_value,
1225 reg->var_off.value | reg->var_off.mask);
1226}
1227
John Fastabend3f50f132020-03-30 14:36:39 -07001228static void __update_reg_bounds(struct bpf_reg_state *reg)
1229{
1230 __update_reg32_bounds(reg);
1231 __update_reg64_bounds(reg);
1232}
1233
Edward Creeb03c9f92017-08-07 15:26:36 +01001234/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001235static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1236{
1237 /* Learn sign from signed bounds.
1238 * If we cannot cross the sign boundary, then signed and unsigned bounds
1239 * are the same, so combine. This works even in the negative case, e.g.
1240 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1241 */
1242 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1243 reg->s32_min_value = reg->u32_min_value =
1244 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1245 reg->s32_max_value = reg->u32_max_value =
1246 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1247 return;
1248 }
1249 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1250 * boundary, so we must be careful.
1251 */
1252 if ((s32)reg->u32_max_value >= 0) {
1253 /* Positive. We can't learn anything from the smin, but smax
1254 * is positive, hence safe.
1255 */
1256 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 } else if ((s32)reg->u32_min_value < 0) {
1260 /* Negative. We can't learn anything from the smax, but smin
1261 * is negative, hence safe.
1262 */
1263 reg->s32_min_value = reg->u32_min_value =
1264 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1265 reg->s32_max_value = reg->u32_max_value;
1266 }
1267}
1268
1269static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001270{
1271 /* Learn sign from signed bounds.
1272 * If we cannot cross the sign boundary, then signed and unsigned bounds
1273 * are the same, so combine. This works even in the negative case, e.g.
1274 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1275 */
1276 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1277 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1278 reg->umin_value);
1279 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1280 reg->umax_value);
1281 return;
1282 }
1283 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1284 * boundary, so we must be careful.
1285 */
1286 if ((s64)reg->umax_value >= 0) {
1287 /* Positive. We can't learn anything from the smin, but smax
1288 * is positive, hence safe.
1289 */
1290 reg->smin_value = reg->umin_value;
1291 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1292 reg->umax_value);
1293 } else if ((s64)reg->umin_value < 0) {
1294 /* Negative. We can't learn anything from the smax, but smin
1295 * is negative, hence safe.
1296 */
1297 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1298 reg->umin_value);
1299 reg->smax_value = reg->umax_value;
1300 }
1301}
1302
John Fastabend3f50f132020-03-30 14:36:39 -07001303static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1304{
1305 __reg32_deduce_bounds(reg);
1306 __reg64_deduce_bounds(reg);
1307}
1308
Edward Creeb03c9f92017-08-07 15:26:36 +01001309/* Attempts to improve var_off based on unsigned min/max information */
1310static void __reg_bound_offset(struct bpf_reg_state *reg)
1311{
John Fastabend3f50f132020-03-30 14:36:39 -07001312 struct tnum var64_off = tnum_intersect(reg->var_off,
1313 tnum_range(reg->umin_value,
1314 reg->umax_value));
1315 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1316 tnum_range(reg->u32_min_value,
1317 reg->u32_max_value));
1318
1319 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001320}
1321
John Fastabend3f50f132020-03-30 14:36:39 -07001322static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001323{
John Fastabend3f50f132020-03-30 14:36:39 -07001324 reg->umin_value = reg->u32_min_value;
1325 reg->umax_value = reg->u32_max_value;
1326 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1327 * but must be positive otherwise set to worse case bounds
1328 * and refine later from tnum.
1329 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001330 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001331 reg->smax_value = reg->s32_max_value;
1332 else
1333 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001334 if (reg->s32_min_value >= 0)
1335 reg->smin_value = reg->s32_min_value;
1336 else
1337 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001338}
1339
1340static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1341{
1342 /* special case when 64-bit register has upper 32-bit register
1343 * zeroed. Typically happens after zext or <<32, >>32 sequence
1344 * allowing us to use 32-bit bounds directly,
1345 */
1346 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1347 __reg_assign_32_into_64(reg);
1348 } else {
1349 /* Otherwise the best we can do is push lower 32bit known and
1350 * unknown bits into register (var_off set from jmp logic)
1351 * then learn as much as possible from the 64-bit tnum
1352 * known and unknown bits. The previous smin/smax bounds are
1353 * invalid here because of jmp32 compare so mark them unknown
1354 * so they do not impact tnum bounds calculation.
1355 */
1356 __mark_reg64_unbounded(reg);
1357 __update_reg_bounds(reg);
1358 }
1359
1360 /* Intersecting with the old var_off might have improved our bounds
1361 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1362 * then new var_off is (0; 0x7f...fc) which improves our umax.
1363 */
1364 __reg_deduce_bounds(reg);
1365 __reg_bound_offset(reg);
1366 __update_reg_bounds(reg);
1367}
1368
1369static bool __reg64_bound_s32(s64 a)
1370{
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001371 return a > S32_MIN && a < S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001372}
1373
1374static bool __reg64_bound_u32(u64 a)
1375{
1376 if (a > U32_MIN && a < U32_MAX)
1377 return true;
1378 return false;
1379}
1380
1381static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1382{
1383 __mark_reg32_unbounded(reg);
1384
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001385 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001386 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001387 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001388 }
John Fastabend3f50f132020-03-30 14:36:39 -07001389 if (__reg64_bound_u32(reg->umin_value))
1390 reg->u32_min_value = (u32)reg->umin_value;
1391 if (__reg64_bound_u32(reg->umax_value))
1392 reg->u32_max_value = (u32)reg->umax_value;
1393
1394 /* Intersecting with the old var_off might have improved our bounds
1395 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1396 * then new var_off is (0; 0x7f...fc) which improves our umax.
1397 */
1398 __reg_deduce_bounds(reg);
1399 __reg_bound_offset(reg);
1400 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001401}
1402
Edward Creef1174f72017-08-07 15:26:19 +01001403/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001404static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1405 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001406{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001407 /*
1408 * Clear type, id, off, and union(map_ptr, range) and
1409 * padding between 'type' and union
1410 */
1411 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001412 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001413 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001414 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001415 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001416 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001417}
1418
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001419static void mark_reg_unknown(struct bpf_verifier_env *env,
1420 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001421{
1422 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001423 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001424 /* Something bad happened, let's kill all regs except FP */
1425 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001426 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001427 return;
1428 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001429 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001430}
1431
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001432static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1433 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001434{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001435 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001436 reg->type = NOT_INIT;
1437}
1438
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001439static void mark_reg_not_init(struct bpf_verifier_env *env,
1440 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001441{
Edward Creef1174f72017-08-07 15:26:19 +01001442 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001443 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001444 /* Something bad happened, let's kill all regs except FP */
1445 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001446 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001447 return;
1448 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001449 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001450}
1451
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001452static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1453 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001454 enum bpf_reg_type reg_type,
1455 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001456{
1457 if (reg_type == SCALAR_VALUE) {
1458 mark_reg_unknown(env, regs, regno);
1459 return;
1460 }
1461 mark_reg_known_zero(env, regs, regno);
1462 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001463 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001464 regs[regno].btf_id = btf_id;
1465}
1466
Jiong Wang5327ed32019-05-24 23:25:12 +01001467#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001468static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001469 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001470{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001471 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001472 int i;
1473
Edward Creedc503a82017-08-15 20:34:35 +01001474 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001475 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001476 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001477 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001478 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001479 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001480
1481 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001482 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001483 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001484 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001485}
1486
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001487#define BPF_MAIN_FUNC (-1)
1488static void init_func_state(struct bpf_verifier_env *env,
1489 struct bpf_func_state *state,
1490 int callsite, int frameno, int subprogno)
1491{
1492 state->callsite = callsite;
1493 state->frameno = frameno;
1494 state->subprogno = subprogno;
1495 init_reg_state(env, state);
1496}
1497
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001498enum reg_arg_type {
1499 SRC_OP, /* register is used as source operand */
1500 DST_OP, /* register is used as destination operand */
1501 DST_OP_NO_MARK /* same as above, check only, don't mark */
1502};
1503
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001504static int cmp_subprogs(const void *a, const void *b)
1505{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001506 return ((struct bpf_subprog_info *)a)->start -
1507 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001508}
1509
1510static int find_subprog(struct bpf_verifier_env *env, int off)
1511{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001512 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001513
Jiong Wang9c8105b2018-05-02 16:17:18 -04001514 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1515 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001516 if (!p)
1517 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001518 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001519
1520}
1521
1522static int add_subprog(struct bpf_verifier_env *env, int off)
1523{
1524 int insn_cnt = env->prog->len;
1525 int ret;
1526
1527 if (off >= insn_cnt || off < 0) {
1528 verbose(env, "call to invalid destination\n");
1529 return -EINVAL;
1530 }
1531 ret = find_subprog(env, off);
1532 if (ret >= 0)
1533 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001534 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001535 verbose(env, "too many subprograms\n");
1536 return -E2BIG;
1537 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001538 env->subprog_info[env->subprog_cnt++].start = off;
1539 sort(env->subprog_info, env->subprog_cnt,
1540 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001541 return 0;
1542}
1543
1544static int check_subprogs(struct bpf_verifier_env *env)
1545{
1546 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001547 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001548 struct bpf_insn *insn = env->prog->insnsi;
1549 int insn_cnt = env->prog->len;
1550
Jiong Wangf910cef2018-05-02 16:17:17 -04001551 /* Add entry function. */
1552 ret = add_subprog(env, 0);
1553 if (ret < 0)
1554 return ret;
1555
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001556 /* determine subprog starts. The end is one before the next starts */
1557 for (i = 0; i < insn_cnt; i++) {
Yonghong Song23a2d702021-02-04 15:48:27 -08001558 if (!bpf_pseudo_call(insn + i))
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001559 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001560 if (!env->bpf_capable) {
1561 verbose(env,
1562 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001563 return -EPERM;
1564 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001565 ret = add_subprog(env, i + insn[i].imm + 1);
1566 if (ret < 0)
1567 return ret;
1568 }
1569
Jiong Wang4cb3d992018-05-02 16:17:19 -04001570 /* Add a fake 'exit' subprog which could simplify subprog iteration
1571 * logic. 'subprog_cnt' should not be increased.
1572 */
1573 subprog[env->subprog_cnt].start = insn_cnt;
1574
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001575 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001576 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001577 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001578
1579 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001580 subprog_start = subprog[cur_subprog].start;
1581 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001582 for (i = 0; i < insn_cnt; i++) {
1583 u8 code = insn[i].code;
1584
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001585 if (code == (BPF_JMP | BPF_CALL) &&
1586 insn[i].imm == BPF_FUNC_tail_call &&
1587 insn[i].src_reg != BPF_PSEUDO_CALL)
1588 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001589 if (BPF_CLASS(code) == BPF_LD &&
1590 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1591 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001592 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001593 goto next;
1594 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1595 goto next;
1596 off = i + insn[i].off + 1;
1597 if (off < subprog_start || off >= subprog_end) {
1598 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1599 return -EINVAL;
1600 }
1601next:
1602 if (i == subprog_end - 1) {
1603 /* to avoid fall-through from one subprog into another
1604 * the last insn of the subprog should be either exit
1605 * or unconditional jump back
1606 */
1607 if (code != (BPF_JMP | BPF_EXIT) &&
1608 code != (BPF_JMP | BPF_JA)) {
1609 verbose(env, "last insn is not an exit or jmp\n");
1610 return -EINVAL;
1611 }
1612 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001613 cur_subprog++;
1614 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001615 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001616 }
1617 }
1618 return 0;
1619}
1620
Edward Cree679c7822018-08-22 20:02:19 +01001621/* Parentage chain of this register (or stack slot) should take care of all
1622 * issues like callee-saved registers, stack slot allocation time, etc.
1623 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001624static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001625 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001626 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001627{
1628 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001629 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001630
1631 while (parent) {
1632 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001633 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001634 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001635 if (parent->live & REG_LIVE_DONE) {
1636 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1637 reg_type_str[parent->type],
1638 parent->var_off.value, parent->off);
1639 return -EFAULT;
1640 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001641 /* The first condition is more likely to be true than the
1642 * second, checked it first.
1643 */
1644 if ((parent->live & REG_LIVE_READ) == flag ||
1645 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001646 /* The parentage chain never changes and
1647 * this parent was already marked as LIVE_READ.
1648 * There is no need to keep walking the chain again and
1649 * keep re-marking all parents as LIVE_READ.
1650 * This case happens when the same register is read
1651 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001652 * Also, if parent has the stronger REG_LIVE_READ64 set,
1653 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001654 */
1655 break;
Edward Creedc503a82017-08-15 20:34:35 +01001656 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001657 parent->live |= flag;
1658 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1659 if (flag == REG_LIVE_READ64)
1660 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001661 state = parent;
1662 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001663 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001664 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001665 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001666
1667 if (env->longest_mark_read_walk < cnt)
1668 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001669 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001670}
1671
Jiong Wang5327ed32019-05-24 23:25:12 +01001672/* This function is supposed to be used by the following 32-bit optimization
1673 * code only. It returns TRUE if the source or destination register operates
1674 * on 64-bit, otherwise return FALSE.
1675 */
1676static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1677 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1678{
1679 u8 code, class, op;
1680
1681 code = insn->code;
1682 class = BPF_CLASS(code);
1683 op = BPF_OP(code);
1684 if (class == BPF_JMP) {
1685 /* BPF_EXIT for "main" will reach here. Return TRUE
1686 * conservatively.
1687 */
1688 if (op == BPF_EXIT)
1689 return true;
1690 if (op == BPF_CALL) {
1691 /* BPF to BPF call will reach here because of marking
1692 * caller saved clobber with DST_OP_NO_MARK for which we
1693 * don't care the register def because they are anyway
1694 * marked as NOT_INIT already.
1695 */
1696 if (insn->src_reg == BPF_PSEUDO_CALL)
1697 return false;
1698 /* Helper call will reach here because of arg type
1699 * check, conservatively return TRUE.
1700 */
1701 if (t == SRC_OP)
1702 return true;
1703
1704 return false;
1705 }
1706 }
1707
1708 if (class == BPF_ALU64 || class == BPF_JMP ||
1709 /* BPF_END always use BPF_ALU class. */
1710 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1711 return true;
1712
1713 if (class == BPF_ALU || class == BPF_JMP32)
1714 return false;
1715
1716 if (class == BPF_LDX) {
1717 if (t != SRC_OP)
1718 return BPF_SIZE(code) == BPF_DW;
1719 /* LDX source must be ptr. */
1720 return true;
1721 }
1722
1723 if (class == BPF_STX) {
1724 if (reg->type != SCALAR_VALUE)
1725 return true;
1726 return BPF_SIZE(code) == BPF_DW;
1727 }
1728
1729 if (class == BPF_LD) {
1730 u8 mode = BPF_MODE(code);
1731
1732 /* LD_IMM64 */
1733 if (mode == BPF_IMM)
1734 return true;
1735
1736 /* Both LD_IND and LD_ABS return 32-bit data. */
1737 if (t != SRC_OP)
1738 return false;
1739
1740 /* Implicit ctx ptr. */
1741 if (regno == BPF_REG_6)
1742 return true;
1743
1744 /* Explicit source could be any width. */
1745 return true;
1746 }
1747
1748 if (class == BPF_ST)
1749 /* The only source register for BPF_ST is a ptr. */
1750 return true;
1751
1752 /* Conservatively return true at default. */
1753 return true;
1754}
1755
Jiong Wangb325fbc2019-05-24 23:25:13 +01001756/* Return TRUE if INSN doesn't have explicit value define. */
1757static bool insn_no_def(struct bpf_insn *insn)
1758{
1759 u8 class = BPF_CLASS(insn->code);
1760
1761 return (class == BPF_JMP || class == BPF_JMP32 ||
1762 class == BPF_STX || class == BPF_ST);
1763}
1764
1765/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1766static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1767{
1768 if (insn_no_def(insn))
1769 return false;
1770
1771 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1772}
1773
Jiong Wang5327ed32019-05-24 23:25:12 +01001774static void mark_insn_zext(struct bpf_verifier_env *env,
1775 struct bpf_reg_state *reg)
1776{
1777 s32 def_idx = reg->subreg_def;
1778
1779 if (def_idx == DEF_NOT_SUBREG)
1780 return;
1781
1782 env->insn_aux_data[def_idx - 1].zext_dst = true;
1783 /* The dst will be zero extended, so won't be sub-register anymore. */
1784 reg->subreg_def = DEF_NOT_SUBREG;
1785}
1786
Edward Creedc503a82017-08-15 20:34:35 +01001787static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001788 enum reg_arg_type t)
1789{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001790 struct bpf_verifier_state *vstate = env->cur_state;
1791 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001792 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001793 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001794 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001795
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001796 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001797 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001798 return -EINVAL;
1799 }
1800
Jiong Wangc342dc12019-04-12 22:59:37 +01001801 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001802 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001803 if (t == SRC_OP) {
1804 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001805 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001806 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001807 return -EACCES;
1808 }
Edward Cree679c7822018-08-22 20:02:19 +01001809 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001810 if (regno == BPF_REG_FP)
1811 return 0;
1812
Jiong Wang5327ed32019-05-24 23:25:12 +01001813 if (rw64)
1814 mark_insn_zext(env, reg);
1815
1816 return mark_reg_read(env, reg, reg->parent,
1817 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001818 } else {
1819 /* check whether register used as dest operand can be written to */
1820 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001821 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001822 return -EACCES;
1823 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001824 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001825 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001826 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001827 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001828 }
1829 return 0;
1830}
1831
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001832/* for any branch, call, exit record the history of jmps in the given state */
1833static int push_jmp_history(struct bpf_verifier_env *env,
1834 struct bpf_verifier_state *cur)
1835{
1836 u32 cnt = cur->jmp_history_cnt;
1837 struct bpf_idx_pair *p;
1838
1839 cnt++;
1840 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1841 if (!p)
1842 return -ENOMEM;
1843 p[cnt - 1].idx = env->insn_idx;
1844 p[cnt - 1].prev_idx = env->prev_insn_idx;
1845 cur->jmp_history = p;
1846 cur->jmp_history_cnt = cnt;
1847 return 0;
1848}
1849
1850/* Backtrack one insn at a time. If idx is not at the top of recorded
1851 * history then previous instruction came from straight line execution.
1852 */
1853static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1854 u32 *history)
1855{
1856 u32 cnt = *history;
1857
1858 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1859 i = st->jmp_history[cnt - 1].prev_idx;
1860 (*history)--;
1861 } else {
1862 i--;
1863 }
1864 return i;
1865}
1866
1867/* For given verifier state backtrack_insn() is called from the last insn to
1868 * the first insn. Its purpose is to compute a bitmask of registers and
1869 * stack slots that needs precision in the parent verifier state.
1870 */
1871static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1872 u32 *reg_mask, u64 *stack_mask)
1873{
1874 const struct bpf_insn_cbs cbs = {
1875 .cb_print = verbose,
1876 .private_data = env,
1877 };
1878 struct bpf_insn *insn = env->prog->insnsi + idx;
1879 u8 class = BPF_CLASS(insn->code);
1880 u8 opcode = BPF_OP(insn->code);
1881 u8 mode = BPF_MODE(insn->code);
1882 u32 dreg = 1u << insn->dst_reg;
1883 u32 sreg = 1u << insn->src_reg;
1884 u32 spi;
1885
1886 if (insn->code == 0)
1887 return 0;
1888 if (env->log.level & BPF_LOG_LEVEL) {
1889 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1890 verbose(env, "%d: ", idx);
1891 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1892 }
1893
1894 if (class == BPF_ALU || class == BPF_ALU64) {
1895 if (!(*reg_mask & dreg))
1896 return 0;
1897 if (opcode == BPF_MOV) {
1898 if (BPF_SRC(insn->code) == BPF_X) {
1899 /* dreg = sreg
1900 * dreg needs precision after this insn
1901 * sreg needs precision before this insn
1902 */
1903 *reg_mask &= ~dreg;
1904 *reg_mask |= sreg;
1905 } else {
1906 /* dreg = K
1907 * dreg needs precision after this insn.
1908 * Corresponding register is already marked
1909 * as precise=true in this verifier state.
1910 * No further markings in parent are necessary
1911 */
1912 *reg_mask &= ~dreg;
1913 }
1914 } else {
1915 if (BPF_SRC(insn->code) == BPF_X) {
1916 /* dreg += sreg
1917 * both dreg and sreg need precision
1918 * before this insn
1919 */
1920 *reg_mask |= sreg;
1921 } /* else dreg += K
1922 * dreg still needs precision before this insn
1923 */
1924 }
1925 } else if (class == BPF_LDX) {
1926 if (!(*reg_mask & dreg))
1927 return 0;
1928 *reg_mask &= ~dreg;
1929
1930 /* scalars can only be spilled into stack w/o losing precision.
1931 * Load from any other memory can be zero extended.
1932 * The desire to keep that precision is already indicated
1933 * by 'precise' mark in corresponding register of this state.
1934 * No further tracking necessary.
1935 */
1936 if (insn->src_reg != BPF_REG_FP)
1937 return 0;
1938 if (BPF_SIZE(insn->code) != BPF_DW)
1939 return 0;
1940
1941 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1942 * that [fp - off] slot contains scalar that needs to be
1943 * tracked with precision
1944 */
1945 spi = (-insn->off - 1) / BPF_REG_SIZE;
1946 if (spi >= 64) {
1947 verbose(env, "BUG spi %d\n", spi);
1948 WARN_ONCE(1, "verifier backtracking bug");
1949 return -EFAULT;
1950 }
1951 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001952 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001953 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001954 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001955 * to access memory. It means backtracking
1956 * encountered a case of pointer subtraction.
1957 */
1958 return -ENOTSUPP;
1959 /* scalars can only be spilled into stack */
1960 if (insn->dst_reg != BPF_REG_FP)
1961 return 0;
1962 if (BPF_SIZE(insn->code) != BPF_DW)
1963 return 0;
1964 spi = (-insn->off - 1) / BPF_REG_SIZE;
1965 if (spi >= 64) {
1966 verbose(env, "BUG spi %d\n", spi);
1967 WARN_ONCE(1, "verifier backtracking bug");
1968 return -EFAULT;
1969 }
1970 if (!(*stack_mask & (1ull << spi)))
1971 return 0;
1972 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001973 if (class == BPF_STX)
1974 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001975 } else if (class == BPF_JMP || class == BPF_JMP32) {
1976 if (opcode == BPF_CALL) {
1977 if (insn->src_reg == BPF_PSEUDO_CALL)
1978 return -ENOTSUPP;
1979 /* regular helper call sets R0 */
1980 *reg_mask &= ~1;
1981 if (*reg_mask & 0x3f) {
1982 /* if backtracing was looking for registers R1-R5
1983 * they should have been found already.
1984 */
1985 verbose(env, "BUG regs %x\n", *reg_mask);
1986 WARN_ONCE(1, "verifier backtracking bug");
1987 return -EFAULT;
1988 }
1989 } else if (opcode == BPF_EXIT) {
1990 return -ENOTSUPP;
1991 }
1992 } else if (class == BPF_LD) {
1993 if (!(*reg_mask & dreg))
1994 return 0;
1995 *reg_mask &= ~dreg;
1996 /* It's ld_imm64 or ld_abs or ld_ind.
1997 * For ld_imm64 no further tracking of precision
1998 * into parent is necessary
1999 */
2000 if (mode == BPF_IND || mode == BPF_ABS)
2001 /* to be analyzed */
2002 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002003 }
2004 return 0;
2005}
2006
2007/* the scalar precision tracking algorithm:
2008 * . at the start all registers have precise=false.
2009 * . scalar ranges are tracked as normal through alu and jmp insns.
2010 * . once precise value of the scalar register is used in:
2011 * . ptr + scalar alu
2012 * . if (scalar cond K|scalar)
2013 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2014 * backtrack through the verifier states and mark all registers and
2015 * stack slots with spilled constants that these scalar regisers
2016 * should be precise.
2017 * . during state pruning two registers (or spilled stack slots)
2018 * are equivalent if both are not precise.
2019 *
2020 * Note the verifier cannot simply walk register parentage chain,
2021 * since many different registers and stack slots could have been
2022 * used to compute single precise scalar.
2023 *
2024 * The approach of starting with precise=true for all registers and then
2025 * backtrack to mark a register as not precise when the verifier detects
2026 * that program doesn't care about specific value (e.g., when helper
2027 * takes register as ARG_ANYTHING parameter) is not safe.
2028 *
2029 * It's ok to walk single parentage chain of the verifier states.
2030 * It's possible that this backtracking will go all the way till 1st insn.
2031 * All other branches will be explored for needing precision later.
2032 *
2033 * The backtracking needs to deal with cases like:
2034 * 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)
2035 * r9 -= r8
2036 * r5 = r9
2037 * if r5 > 0x79f goto pc+7
2038 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2039 * r5 += 1
2040 * ...
2041 * call bpf_perf_event_output#25
2042 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2043 *
2044 * and this case:
2045 * r6 = 1
2046 * call foo // uses callee's r6 inside to compute r0
2047 * r0 += r6
2048 * if r0 == 0 goto
2049 *
2050 * to track above reg_mask/stack_mask needs to be independent for each frame.
2051 *
2052 * Also if parent's curframe > frame where backtracking started,
2053 * the verifier need to mark registers in both frames, otherwise callees
2054 * may incorrectly prune callers. This is similar to
2055 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2056 *
2057 * For now backtracking falls back into conservative marking.
2058 */
2059static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2060 struct bpf_verifier_state *st)
2061{
2062 struct bpf_func_state *func;
2063 struct bpf_reg_state *reg;
2064 int i, j;
2065
2066 /* big hammer: mark all scalars precise in this path.
2067 * pop_stack may still get !precise scalars.
2068 */
2069 for (; st; st = st->parent)
2070 for (i = 0; i <= st->curframe; i++) {
2071 func = st->frame[i];
2072 for (j = 0; j < BPF_REG_FP; j++) {
2073 reg = &func->regs[j];
2074 if (reg->type != SCALAR_VALUE)
2075 continue;
2076 reg->precise = true;
2077 }
2078 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2079 if (func->stack[j].slot_type[0] != STACK_SPILL)
2080 continue;
2081 reg = &func->stack[j].spilled_ptr;
2082 if (reg->type != SCALAR_VALUE)
2083 continue;
2084 reg->precise = true;
2085 }
2086 }
2087}
2088
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002089static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2090 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002091{
2092 struct bpf_verifier_state *st = env->cur_state;
2093 int first_idx = st->first_insn_idx;
2094 int last_idx = env->insn_idx;
2095 struct bpf_func_state *func;
2096 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002097 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2098 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002099 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002100 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002101 int i, err;
2102
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002103 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002104 return 0;
2105
2106 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002107 if (regno >= 0) {
2108 reg = &func->regs[regno];
2109 if (reg->type != SCALAR_VALUE) {
2110 WARN_ONCE(1, "backtracing misuse");
2111 return -EFAULT;
2112 }
2113 if (!reg->precise)
2114 new_marks = true;
2115 else
2116 reg_mask = 0;
2117 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002118 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002119
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002120 while (spi >= 0) {
2121 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2122 stack_mask = 0;
2123 break;
2124 }
2125 reg = &func->stack[spi].spilled_ptr;
2126 if (reg->type != SCALAR_VALUE) {
2127 stack_mask = 0;
2128 break;
2129 }
2130 if (!reg->precise)
2131 new_marks = true;
2132 else
2133 stack_mask = 0;
2134 reg->precise = true;
2135 break;
2136 }
2137
2138 if (!new_marks)
2139 return 0;
2140 if (!reg_mask && !stack_mask)
2141 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002142 for (;;) {
2143 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002144 u32 history = st->jmp_history_cnt;
2145
2146 if (env->log.level & BPF_LOG_LEVEL)
2147 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2148 for (i = last_idx;;) {
2149 if (skip_first) {
2150 err = 0;
2151 skip_first = false;
2152 } else {
2153 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2154 }
2155 if (err == -ENOTSUPP) {
2156 mark_all_scalars_precise(env, st);
2157 return 0;
2158 } else if (err) {
2159 return err;
2160 }
2161 if (!reg_mask && !stack_mask)
2162 /* Found assignment(s) into tracked register in this state.
2163 * Since this state is already marked, just return.
2164 * Nothing to be tracked further in the parent state.
2165 */
2166 return 0;
2167 if (i == first_idx)
2168 break;
2169 i = get_prev_insn_idx(st, i, &history);
2170 if (i >= env->prog->len) {
2171 /* This can happen if backtracking reached insn 0
2172 * and there are still reg_mask or stack_mask
2173 * to backtrack.
2174 * It means the backtracking missed the spot where
2175 * particular register was initialized with a constant.
2176 */
2177 verbose(env, "BUG backtracking idx %d\n", i);
2178 WARN_ONCE(1, "verifier backtracking bug");
2179 return -EFAULT;
2180 }
2181 }
2182 st = st->parent;
2183 if (!st)
2184 break;
2185
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002186 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002187 func = st->frame[st->curframe];
2188 bitmap_from_u64(mask, reg_mask);
2189 for_each_set_bit(i, mask, 32) {
2190 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002191 if (reg->type != SCALAR_VALUE) {
2192 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002193 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002194 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002195 if (!reg->precise)
2196 new_marks = true;
2197 reg->precise = true;
2198 }
2199
2200 bitmap_from_u64(mask, stack_mask);
2201 for_each_set_bit(i, mask, 64) {
2202 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002203 /* the sequence of instructions:
2204 * 2: (bf) r3 = r10
2205 * 3: (7b) *(u64 *)(r3 -8) = r0
2206 * 4: (79) r4 = *(u64 *)(r10 -8)
2207 * doesn't contain jmps. It's backtracked
2208 * as a single block.
2209 * During backtracking insn 3 is not recognized as
2210 * stack access, so at the end of backtracking
2211 * stack slot fp-8 is still marked in stack_mask.
2212 * However the parent state may not have accessed
2213 * fp-8 and it's "unallocated" stack space.
2214 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002215 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002216 mark_all_scalars_precise(env, st);
2217 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002218 }
2219
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002220 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2221 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002222 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002223 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002224 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002225 if (reg->type != SCALAR_VALUE) {
2226 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002227 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002228 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002229 if (!reg->precise)
2230 new_marks = true;
2231 reg->precise = true;
2232 }
2233 if (env->log.level & BPF_LOG_LEVEL) {
2234 print_verifier_state(env, func);
2235 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2236 new_marks ? "didn't have" : "already had",
2237 reg_mask, stack_mask);
2238 }
2239
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002240 if (!reg_mask && !stack_mask)
2241 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002242 if (!new_marks)
2243 break;
2244
2245 last_idx = st->last_insn_idx;
2246 first_idx = st->first_insn_idx;
2247 }
2248 return 0;
2249}
2250
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002251static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2252{
2253 return __mark_chain_precision(env, regno, -1);
2254}
2255
2256static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2257{
2258 return __mark_chain_precision(env, -1, spi);
2259}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002260
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002261static bool is_spillable_regtype(enum bpf_reg_type type)
2262{
2263 switch (type) {
2264 case PTR_TO_MAP_VALUE:
2265 case PTR_TO_MAP_VALUE_OR_NULL:
2266 case PTR_TO_STACK:
2267 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002268 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002269 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002270 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002271 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002272 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002273 case PTR_TO_SOCKET:
2274 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002275 case PTR_TO_SOCK_COMMON:
2276 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002277 case PTR_TO_TCP_SOCK:
2278 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002279 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002280 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002281 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002282 case PTR_TO_RDONLY_BUF:
2283 case PTR_TO_RDONLY_BUF_OR_NULL:
2284 case PTR_TO_RDWR_BUF:
2285 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002286 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002287 case PTR_TO_MEM:
2288 case PTR_TO_MEM_OR_NULL:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002289 return true;
2290 default:
2291 return false;
2292 }
2293}
2294
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002295/* Does this register contain a constant zero? */
2296static bool register_is_null(struct bpf_reg_state *reg)
2297{
2298 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2299}
2300
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002301static bool register_is_const(struct bpf_reg_state *reg)
2302{
2303 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2304}
2305
Yonghong Song5689d492020-10-08 18:12:38 -07002306static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2307{
2308 return tnum_is_unknown(reg->var_off) &&
2309 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2310 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2311 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2312 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2313}
2314
2315static bool register_is_bounded(struct bpf_reg_state *reg)
2316{
2317 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2318}
2319
Jann Horn6e7e63c2020-04-17 02:00:06 +02002320static bool __is_pointer_value(bool allow_ptr_leaks,
2321 const struct bpf_reg_state *reg)
2322{
2323 if (allow_ptr_leaks)
2324 return false;
2325
2326 return reg->type != SCALAR_VALUE;
2327}
2328
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002329static void save_register_state(struct bpf_func_state *state,
2330 int spi, struct bpf_reg_state *reg)
2331{
2332 int i;
2333
2334 state->stack[spi].spilled_ptr = *reg;
2335 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2336
2337 for (i = 0; i < BPF_REG_SIZE; i++)
2338 state->stack[spi].slot_type[i] = STACK_SPILL;
2339}
2340
Andrei Matei01f810a2021-02-06 20:10:24 -05002341/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002342 * stack boundary and alignment are checked in check_mem_access()
2343 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002344static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2345 /* stack frame we're writing to */
2346 struct bpf_func_state *state,
2347 int off, int size, int value_regno,
2348 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002349{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002350 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002351 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002352 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002353 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002354
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002355 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002356 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002357 if (err)
2358 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002359 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2360 * so it's aligned access and [off, off + size) are within stack limits
2361 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002362 if (!env->allow_ptr_leaks &&
2363 state->stack[spi].slot_type[0] == STACK_SPILL &&
2364 size != BPF_REG_SIZE) {
2365 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2366 return -EACCES;
2367 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002368
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002369 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002370 if (value_regno >= 0)
2371 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002372
Yonghong Song5689d492020-10-08 18:12:38 -07002373 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002374 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002375 if (dst_reg != BPF_REG_FP) {
2376 /* The backtracking logic can only recognize explicit
2377 * stack slot address like [fp - 8]. Other spill of
2378 * scalar via different register has to be conervative.
2379 * Backtrack from here and mark all registers as precise
2380 * that contributed into 'reg' being a constant.
2381 */
2382 err = mark_chain_precision(env, value_regno);
2383 if (err)
2384 return err;
2385 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002386 save_register_state(state, spi, reg);
2387 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002388 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002389 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002390 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002391 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002392 return -EACCES;
2393 }
2394
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002395 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002396 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2397 return -EINVAL;
2398 }
2399
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002400 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002401 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002402
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002403 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2404 register_is_const(&state->stack[spi].spilled_ptr))
2405 sanitize = true;
2406 for (i = 0; i < BPF_REG_SIZE; i++)
2407 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2408 sanitize = true;
2409 break;
2410 }
2411 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002412 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2413 int soff = (-spi - 1) * BPF_REG_SIZE;
2414
2415 /* detected reuse of integer stack slot with a pointer
2416 * which means either llvm is reusing stack slot or
2417 * an attacker is trying to exploit CVE-2018-3639
2418 * (speculative store bypass)
2419 * Have to sanitize that slot with preemptive
2420 * store of zero.
2421 */
2422 if (*poff && *poff != soff) {
2423 /* disallow programs where single insn stores
2424 * into two different stack slots, since verifier
2425 * cannot sanitize them
2426 */
2427 verbose(env,
2428 "insn %d cannot access two stack slots fp%d and fp%d",
2429 insn_idx, *poff, soff);
2430 return -EINVAL;
2431 }
2432 *poff = soff;
2433 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002434 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002435 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002436 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002437 u8 type = STACK_MISC;
2438
Edward Cree679c7822018-08-22 20:02:19 +01002439 /* regular write of data into stack destroys any spilled ptr */
2440 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002441 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2442 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2443 for (i = 0; i < BPF_REG_SIZE; i++)
2444 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002445
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002446 /* only mark the slot as written if all 8 bytes were written
2447 * otherwise read propagation may incorrectly stop too soon
2448 * when stack slots are partially written.
2449 * This heuristic means that read propagation will be
2450 * conservative, since it will add reg_live_read marks
2451 * to stack slots all the way to first state when programs
2452 * writes+reads less than 8 bytes
2453 */
2454 if (size == BPF_REG_SIZE)
2455 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2456
2457 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002458 if (reg && register_is_null(reg)) {
2459 /* backtracking doesn't work for STACK_ZERO yet. */
2460 err = mark_chain_precision(env, value_regno);
2461 if (err)
2462 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002463 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002464 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002465
Jiong Wang0bae2d42018-12-15 03:34:40 -05002466 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002467 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002468 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002469 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002470 }
2471 return 0;
2472}
2473
Andrei Matei01f810a2021-02-06 20:10:24 -05002474/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2475 * known to contain a variable offset.
2476 * This function checks whether the write is permitted and conservatively
2477 * tracks the effects of the write, considering that each stack slot in the
2478 * dynamic range is potentially written to.
2479 *
2480 * 'off' includes 'regno->off'.
2481 * 'value_regno' can be -1, meaning that an unknown value is being written to
2482 * the stack.
2483 *
2484 * Spilled pointers in range are not marked as written because we don't know
2485 * what's going to be actually written. This means that read propagation for
2486 * future reads cannot be terminated by this write.
2487 *
2488 * For privileged programs, uninitialized stack slots are considered
2489 * initialized by this write (even though we don't know exactly what offsets
2490 * are going to be written to). The idea is that we don't want the verifier to
2491 * reject future reads that access slots written to through variable offsets.
2492 */
2493static int check_stack_write_var_off(struct bpf_verifier_env *env,
2494 /* func where register points to */
2495 struct bpf_func_state *state,
2496 int ptr_regno, int off, int size,
2497 int value_regno, int insn_idx)
2498{
2499 struct bpf_func_state *cur; /* state of the current function */
2500 int min_off, max_off;
2501 int i, err;
2502 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2503 bool writing_zero = false;
2504 /* set if the fact that we're writing a zero is used to let any
2505 * stack slots remain STACK_ZERO
2506 */
2507 bool zero_used = false;
2508
2509 cur = env->cur_state->frame[env->cur_state->curframe];
2510 ptr_reg = &cur->regs[ptr_regno];
2511 min_off = ptr_reg->smin_value + off;
2512 max_off = ptr_reg->smax_value + off + size;
2513 if (value_regno >= 0)
2514 value_reg = &cur->regs[value_regno];
2515 if (value_reg && register_is_null(value_reg))
2516 writing_zero = true;
2517
2518 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2519 state->acquired_refs, true);
2520 if (err)
2521 return err;
2522
2523
2524 /* Variable offset writes destroy any spilled pointers in range. */
2525 for (i = min_off; i < max_off; i++) {
2526 u8 new_type, *stype;
2527 int slot, spi;
2528
2529 slot = -i - 1;
2530 spi = slot / BPF_REG_SIZE;
2531 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2532
2533 if (!env->allow_ptr_leaks
2534 && *stype != NOT_INIT
2535 && *stype != SCALAR_VALUE) {
2536 /* Reject the write if there's are spilled pointers in
2537 * range. If we didn't reject here, the ptr status
2538 * would be erased below (even though not all slots are
2539 * actually overwritten), possibly opening the door to
2540 * leaks.
2541 */
2542 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2543 insn_idx, i);
2544 return -EINVAL;
2545 }
2546
2547 /* Erase all spilled pointers. */
2548 state->stack[spi].spilled_ptr.type = NOT_INIT;
2549
2550 /* Update the slot type. */
2551 new_type = STACK_MISC;
2552 if (writing_zero && *stype == STACK_ZERO) {
2553 new_type = STACK_ZERO;
2554 zero_used = true;
2555 }
2556 /* If the slot is STACK_INVALID, we check whether it's OK to
2557 * pretend that it will be initialized by this write. The slot
2558 * might not actually be written to, and so if we mark it as
2559 * initialized future reads might leak uninitialized memory.
2560 * For privileged programs, we will accept such reads to slots
2561 * that may or may not be written because, if we're reject
2562 * them, the error would be too confusing.
2563 */
2564 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2565 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2566 insn_idx, i);
2567 return -EINVAL;
2568 }
2569 *stype = new_type;
2570 }
2571 if (zero_used) {
2572 /* backtracking doesn't work for STACK_ZERO yet. */
2573 err = mark_chain_precision(env, value_regno);
2574 if (err)
2575 return err;
2576 }
2577 return 0;
2578}
2579
2580/* When register 'dst_regno' is assigned some values from stack[min_off,
2581 * max_off), we set the register's type according to the types of the
2582 * respective stack slots. If all the stack values are known to be zeros, then
2583 * so is the destination reg. Otherwise, the register is considered to be
2584 * SCALAR. This function does not deal with register filling; the caller must
2585 * ensure that all spilled registers in the stack range have been marked as
2586 * read.
2587 */
2588static void mark_reg_stack_read(struct bpf_verifier_env *env,
2589 /* func where src register points to */
2590 struct bpf_func_state *ptr_state,
2591 int min_off, int max_off, int dst_regno)
2592{
2593 struct bpf_verifier_state *vstate = env->cur_state;
2594 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2595 int i, slot, spi;
2596 u8 *stype;
2597 int zeros = 0;
2598
2599 for (i = min_off; i < max_off; i++) {
2600 slot = -i - 1;
2601 spi = slot / BPF_REG_SIZE;
2602 stype = ptr_state->stack[spi].slot_type;
2603 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2604 break;
2605 zeros++;
2606 }
2607 if (zeros == max_off - min_off) {
2608 /* any access_size read into register is zero extended,
2609 * so the whole register == const_zero
2610 */
2611 __mark_reg_const_zero(&state->regs[dst_regno]);
2612 /* backtracking doesn't support STACK_ZERO yet,
2613 * so mark it precise here, so that later
2614 * backtracking can stop here.
2615 * Backtracking may not need this if this register
2616 * doesn't participate in pointer adjustment.
2617 * Forward propagation of precise flag is not
2618 * necessary either. This mark is only to stop
2619 * backtracking. Any register that contributed
2620 * to const 0 was marked precise before spill.
2621 */
2622 state->regs[dst_regno].precise = true;
2623 } else {
2624 /* have read misc data from the stack */
2625 mark_reg_unknown(env, state->regs, dst_regno);
2626 }
2627 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2628}
2629
2630/* Read the stack at 'off' and put the results into the register indicated by
2631 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2632 * spilled reg.
2633 *
2634 * 'dst_regno' can be -1, meaning that the read value is not going to a
2635 * register.
2636 *
2637 * The access is assumed to be within the current stack bounds.
2638 */
2639static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2640 /* func where src register points to */
2641 struct bpf_func_state *reg_state,
2642 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002643{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002644 struct bpf_verifier_state *vstate = env->cur_state;
2645 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002646 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002647 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002648 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002649
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002650 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002651 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002652
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002653 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002654 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002655 if (reg->type != SCALAR_VALUE) {
2656 verbose_linfo(env, env->insn_idx, "; ");
2657 verbose(env, "invalid size of register fill\n");
2658 return -EACCES;
2659 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002660 if (dst_regno >= 0) {
2661 mark_reg_unknown(env, state->regs, dst_regno);
2662 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002663 }
2664 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2665 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002666 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002667 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002668 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002669 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002670 return -EACCES;
2671 }
2672 }
2673
Andrei Matei01f810a2021-02-06 20:10:24 -05002674 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002675 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05002676 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002677 /* mark reg as written since spilled pointer state likely
2678 * has its liveness marks cleared by is_state_visited()
2679 * which resets stack/reg liveness for state transitions
2680 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002681 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002682 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002683 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02002684 * it is acceptable to use this value as a SCALAR_VALUE
2685 * (e.g. for XADD).
2686 * We must not allow unprivileged callers to do that
2687 * with spilled pointers.
2688 */
2689 verbose(env, "leaking pointer from stack off %d\n",
2690 off);
2691 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002692 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002693 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002694 } else {
Andrei Matei01f810a2021-02-06 20:10:24 -05002695 u8 type;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002696
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002697 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002698 type = stype[(slot - i) % BPF_REG_SIZE];
2699 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002700 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05002701 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002702 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002703 verbose(env, "invalid read from stack off %d+%d size %d\n",
2704 off, i, size);
2705 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002706 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002707 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05002708 if (dst_regno >= 0)
2709 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002710 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002711 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002712}
2713
Andrei Matei01f810a2021-02-06 20:10:24 -05002714enum stack_access_src {
2715 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2716 ACCESS_HELPER = 2, /* the access is performed by a helper */
2717};
2718
2719static int check_stack_range_initialized(struct bpf_verifier_env *env,
2720 int regno, int off, int access_size,
2721 bool zero_size_allowed,
2722 enum stack_access_src type,
2723 struct bpf_call_arg_meta *meta);
2724
2725static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002726{
Andrei Matei01f810a2021-02-06 20:10:24 -05002727 return cur_regs(env) + regno;
2728}
2729
2730/* Read the stack at 'ptr_regno + off' and put the result into the register
2731 * 'dst_regno'.
2732 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2733 * but not its variable offset.
2734 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2735 *
2736 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2737 * filling registers (i.e. reads of spilled register cannot be detected when
2738 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2739 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2740 * offset; for a fixed offset check_stack_read_fixed_off should be used
2741 * instead.
2742 */
2743static int check_stack_read_var_off(struct bpf_verifier_env *env,
2744 int ptr_regno, int off, int size, int dst_regno)
2745{
2746 /* The state of the source register. */
2747 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2748 struct bpf_func_state *ptr_state = func(env, reg);
2749 int err;
2750 int min_off, max_off;
2751
2752 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002753 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002754 err = check_stack_range_initialized(env, ptr_regno, off, size,
2755 false, ACCESS_DIRECT, NULL);
2756 if (err)
2757 return err;
2758
2759 min_off = reg->smin_value + off;
2760 max_off = reg->smax_value + off;
2761 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2762 return 0;
2763}
2764
2765/* check_stack_read dispatches to check_stack_read_fixed_off or
2766 * check_stack_read_var_off.
2767 *
2768 * The caller must ensure that the offset falls within the allocated stack
2769 * bounds.
2770 *
2771 * 'dst_regno' is a register which will receive the value from the stack. It
2772 * can be -1, meaning that the read value is not going to a register.
2773 */
2774static int check_stack_read(struct bpf_verifier_env *env,
2775 int ptr_regno, int off, int size,
2776 int dst_regno)
2777{
2778 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2779 struct bpf_func_state *state = func(env, reg);
2780 int err;
2781 /* Some accesses are only permitted with a static offset. */
2782 bool var_off = !tnum_is_const(reg->var_off);
2783
2784 /* The offset is required to be static when reads don't go to a
2785 * register, in order to not leak pointers (see
2786 * check_stack_read_fixed_off).
2787 */
2788 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002789 char tn_buf[48];
2790
2791 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05002792 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 +01002793 tn_buf, off, size);
2794 return -EACCES;
2795 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002796 /* Variable offset is prohibited for unprivileged mode for simplicity
2797 * since it requires corresponding support in Spectre masking for stack
2798 * ALU. See also retrieve_ptr_limit().
2799 */
2800 if (!env->bypass_spec_v1 && var_off) {
2801 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002802
Andrei Matei01f810a2021-02-06 20:10:24 -05002803 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2804 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2805 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002806 return -EACCES;
2807 }
2808
Andrei Matei01f810a2021-02-06 20:10:24 -05002809 if (!var_off) {
2810 off += reg->var_off.value;
2811 err = check_stack_read_fixed_off(env, state, off, size,
2812 dst_regno);
2813 } else {
2814 /* Variable offset stack reads need more conservative handling
2815 * than fixed offset ones. Note that dst_regno >= 0 on this
2816 * branch.
2817 */
2818 err = check_stack_read_var_off(env, ptr_regno, off, size,
2819 dst_regno);
2820 }
2821 return err;
2822}
2823
2824
2825/* check_stack_write dispatches to check_stack_write_fixed_off or
2826 * check_stack_write_var_off.
2827 *
2828 * 'ptr_regno' is the register used as a pointer into the stack.
2829 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2830 * 'value_regno' is the register whose value we're writing to the stack. It can
2831 * be -1, meaning that we're not writing from a register.
2832 *
2833 * The caller must ensure that the offset falls within the maximum stack size.
2834 */
2835static int check_stack_write(struct bpf_verifier_env *env,
2836 int ptr_regno, int off, int size,
2837 int value_regno, int insn_idx)
2838{
2839 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2840 struct bpf_func_state *state = func(env, reg);
2841 int err;
2842
2843 if (tnum_is_const(reg->var_off)) {
2844 off += reg->var_off.value;
2845 err = check_stack_write_fixed_off(env, state, off, size,
2846 value_regno, insn_idx);
2847 } else {
2848 /* Variable offset stack reads need more conservative handling
2849 * than fixed offset ones.
2850 */
2851 err = check_stack_write_var_off(env, state,
2852 ptr_regno, off, size,
2853 value_regno, insn_idx);
2854 }
2855 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002856}
2857
Daniel Borkmann591fe982019-04-09 23:20:05 +02002858static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2859 int off, int size, enum bpf_access_type type)
2860{
2861 struct bpf_reg_state *regs = cur_regs(env);
2862 struct bpf_map *map = regs[regno].map_ptr;
2863 u32 cap = bpf_map_flags_to_cap(map);
2864
2865 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2866 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2867 map->value_size, off, size);
2868 return -EACCES;
2869 }
2870
2871 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2872 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2873 map->value_size, off, size);
2874 return -EACCES;
2875 }
2876
2877 return 0;
2878}
2879
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002880/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2881static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2882 int off, int size, u32 mem_size,
2883 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002884{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002885 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2886 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002887
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002888 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2889 return 0;
2890
2891 reg = &cur_regs(env)[regno];
2892 switch (reg->type) {
2893 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002894 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002895 mem_size, off, size);
2896 break;
2897 case PTR_TO_PACKET:
2898 case PTR_TO_PACKET_META:
2899 case PTR_TO_PACKET_END:
2900 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2901 off, size, regno, reg->id, off, mem_size);
2902 break;
2903 case PTR_TO_MEM:
2904 default:
2905 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2906 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002907 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002908
2909 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002910}
2911
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002912/* check read/write into a memory region with possible variable offset */
2913static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2914 int off, int size, u32 mem_size,
2915 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002916{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002917 struct bpf_verifier_state *vstate = env->cur_state;
2918 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002919 struct bpf_reg_state *reg = &state->regs[regno];
2920 int err;
2921
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002922 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002923 * need to try adding each of min_value and max_value to off
2924 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002925 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002926 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002927 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002928
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002929 /* The minimum value is only important with signed
2930 * comparisons where we can't assume the floor of a
2931 * value is 0. If we are using signed variables for our
2932 * index'es we need to make sure that whatever we use
2933 * will have a set floor within our range.
2934 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002935 if (reg->smin_value < 0 &&
2936 (reg->smin_value == S64_MIN ||
2937 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2938 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002939 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 -08002940 regno);
2941 return -EACCES;
2942 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002943 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2944 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002945 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002946 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002947 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002948 return err;
2949 }
2950
Edward Creeb03c9f92017-08-07 15:26:36 +01002951 /* If we haven't set a max value then we need to bail since we can't be
2952 * sure we won't do bad things.
2953 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002954 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002955 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002956 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002957 regno);
2958 return -EACCES;
2959 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002960 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2961 mem_size, zero_size_allowed);
2962 if (err) {
2963 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002964 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002965 return err;
2966 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002967
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002968 return 0;
2969}
2970
2971/* check read/write into a map element with possible variable offset */
2972static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2973 int off, int size, bool zero_size_allowed)
2974{
2975 struct bpf_verifier_state *vstate = env->cur_state;
2976 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2977 struct bpf_reg_state *reg = &state->regs[regno];
2978 struct bpf_map *map = reg->map_ptr;
2979 int err;
2980
2981 err = check_mem_region_access(env, regno, off, size, map->value_size,
2982 zero_size_allowed);
2983 if (err)
2984 return err;
2985
2986 if (map_value_has_spin_lock(map)) {
2987 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002988
2989 /* if any part of struct bpf_spin_lock can be touched by
2990 * load/store reject this program.
2991 * To check that [x1, x2) overlaps with [y1, y2)
2992 * it is sufficient to check x1 < y2 && y1 < x2.
2993 */
2994 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2995 lock < reg->umax_value + off + size) {
2996 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2997 return -EACCES;
2998 }
2999 }
Edward Creef1174f72017-08-07 15:26:19 +01003000 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003001}
3002
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003003#define MAX_PACKET_OFF 0xffff
3004
Udip Pant7e407812020-08-25 16:20:00 -07003005static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3006{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02003007 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07003008}
3009
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003010static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003011 const struct bpf_call_arg_meta *meta,
3012 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003013{
Udip Pant7e407812020-08-25 16:20:00 -07003014 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3015
3016 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003017 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003018 case BPF_PROG_TYPE_LWT_IN:
3019 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003020 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003021 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003022 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003023 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003024 if (t == BPF_WRITE)
3025 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003026 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003027
3028 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003029 case BPF_PROG_TYPE_SCHED_CLS:
3030 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003031 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003032 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003033 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003034 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003035 if (meta)
3036 return meta->pkt_access;
3037
3038 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003039 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003040
3041 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3042 if (t == BPF_WRITE)
3043 env->seen_direct_write = true;
3044
3045 return true;
3046
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003047 default:
3048 return false;
3049 }
3050}
3051
Edward Creef1174f72017-08-07 15:26:19 +01003052static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003053 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003054{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003055 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003056 struct bpf_reg_state *reg = &regs[regno];
3057 int err;
3058
3059 /* We may have added a variable offset to the packet pointer; but any
3060 * reg->range we have comes after that. We are only checking the fixed
3061 * offset.
3062 */
3063
3064 /* We don't allow negative numbers, because we aren't tracking enough
3065 * detail to prove they're safe.
3066 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003067 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003068 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 +01003069 regno);
3070 return -EACCES;
3071 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003072
3073 err = reg->range < 0 ? -EINVAL :
3074 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003075 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003076 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003077 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003078 return err;
3079 }
Jiong Wange6478152018-11-08 04:08:42 -05003080
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003081 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003082 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3083 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003084 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003085 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3086 */
3087 env->prog->aux->max_pkt_offset =
3088 max_t(u32, env->prog->aux->max_pkt_offset,
3089 off + reg->umax_value + size - 1);
3090
Edward Creef1174f72017-08-07 15:26:19 +01003091 return err;
3092}
3093
3094/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003095static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003096 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003097 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003098{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003099 struct bpf_insn_access_aux info = {
3100 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003101 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003102 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003103
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003104 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003105 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003106 /* A non zero info.ctx_field_size indicates that this field is a
3107 * candidate for later verifier transformation to load the whole
3108 * field and then apply a mask when accessed with a narrower
3109 * access than actual ctx access size. A zero info.ctx_field_size
3110 * will only allow for whole field access and rejects any other
3111 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003112 */
Yonghong Song23994632017-06-22 15:07:39 -07003113 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003114
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003115 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3116 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003117 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003118 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003119 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003120 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003121 /* remember the offset of last byte accessed in ctx */
3122 if (env->prog->aux->max_ctx_offset < off + size)
3123 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003124 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003125 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003126
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003127 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003128 return -EACCES;
3129}
3130
Petar Penkovd58e4682018-09-14 07:46:18 -07003131static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3132 int size)
3133{
3134 if (size < 0 || off < 0 ||
3135 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3136 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3137 off, size);
3138 return -EACCES;
3139 }
3140 return 0;
3141}
3142
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003143static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3144 u32 regno, int off, int size,
3145 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003146{
3147 struct bpf_reg_state *regs = cur_regs(env);
3148 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003149 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003150 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003151
3152 if (reg->smin_value < 0) {
3153 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3154 regno);
3155 return -EACCES;
3156 }
3157
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003158 switch (reg->type) {
3159 case PTR_TO_SOCK_COMMON:
3160 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3161 break;
3162 case PTR_TO_SOCKET:
3163 valid = bpf_sock_is_valid_access(off, size, t, &info);
3164 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003165 case PTR_TO_TCP_SOCK:
3166 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3167 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003168 case PTR_TO_XDP_SOCK:
3169 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3170 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003171 default:
3172 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003173 }
3174
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003175
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003176 if (valid) {
3177 env->insn_aux_data[insn_idx].ctx_field_size =
3178 info.ctx_field_size;
3179 return 0;
3180 }
3181
3182 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3183 regno, reg_type_str[reg->type], off, size);
3184
3185 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003186}
3187
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003188static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3189{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003190 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003191}
3192
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003193static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3194{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003195 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003196
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003197 return reg->type == PTR_TO_CTX;
3198}
3199
3200static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3201{
3202 const struct bpf_reg_state *reg = reg_state(env, regno);
3203
3204 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003205}
3206
Daniel Borkmannca369602018-02-23 22:29:05 +01003207static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3208{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003209 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003210
3211 return type_is_pkt_pointer(reg->type);
3212}
3213
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003214static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3215{
3216 const struct bpf_reg_state *reg = reg_state(env, regno);
3217
3218 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3219 return reg->type == PTR_TO_FLOW_KEYS;
3220}
3221
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003222static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3223 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003224 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003225{
Edward Creef1174f72017-08-07 15:26:19 +01003226 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003227 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003228
3229 /* Byte size accesses are always allowed. */
3230 if (!strict || size == 1)
3231 return 0;
3232
David S. Millere4eda882017-05-22 12:27:07 -04003233 /* For platforms that do not have a Kconfig enabling
3234 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3235 * NET_IP_ALIGN is universally set to '2'. And on platforms
3236 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3237 * to this code only in strict mode where we want to emulate
3238 * the NET_IP_ALIGN==2 checking. Therefore use an
3239 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003240 */
David S. Millere4eda882017-05-22 12:27:07 -04003241 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003242
3243 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3244 if (!tnum_is_aligned(reg_off, size)) {
3245 char tn_buf[48];
3246
3247 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003248 verbose(env,
3249 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003250 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003251 return -EACCES;
3252 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003253
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003254 return 0;
3255}
3256
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003257static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3258 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003259 const char *pointer_desc,
3260 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003261{
Edward Creef1174f72017-08-07 15:26:19 +01003262 struct tnum reg_off;
3263
3264 /* Byte size accesses are always allowed. */
3265 if (!strict || size == 1)
3266 return 0;
3267
3268 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3269 if (!tnum_is_aligned(reg_off, size)) {
3270 char tn_buf[48];
3271
3272 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003273 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003274 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003275 return -EACCES;
3276 }
3277
3278 return 0;
3279}
3280
David S. Millere07b98d2017-05-10 11:38:07 -07003281static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003282 const struct bpf_reg_state *reg, int off,
3283 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003284{
Daniel Borkmannca369602018-02-23 22:29:05 +01003285 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003286 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003287
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003288 switch (reg->type) {
3289 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003290 case PTR_TO_PACKET_META:
3291 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3292 * right in front, treat it the very same way.
3293 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003294 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003295 case PTR_TO_FLOW_KEYS:
3296 pointer_desc = "flow keys ";
3297 break;
Edward Creef1174f72017-08-07 15:26:19 +01003298 case PTR_TO_MAP_VALUE:
3299 pointer_desc = "value ";
3300 break;
3301 case PTR_TO_CTX:
3302 pointer_desc = "context ";
3303 break;
3304 case PTR_TO_STACK:
3305 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003306 /* The stack spill tracking logic in check_stack_write_fixed_off()
3307 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003308 * aligned.
3309 */
3310 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003311 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003312 case PTR_TO_SOCKET:
3313 pointer_desc = "sock ";
3314 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003315 case PTR_TO_SOCK_COMMON:
3316 pointer_desc = "sock_common ";
3317 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003318 case PTR_TO_TCP_SOCK:
3319 pointer_desc = "tcp_sock ";
3320 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003321 case PTR_TO_XDP_SOCK:
3322 pointer_desc = "xdp_sock ";
3323 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003324 default:
Edward Creef1174f72017-08-07 15:26:19 +01003325 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003326 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003327 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3328 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003329}
3330
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003331static int update_stack_depth(struct bpf_verifier_env *env,
3332 const struct bpf_func_state *func,
3333 int off)
3334{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003335 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003336
3337 if (stack >= -off)
3338 return 0;
3339
3340 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003341 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003342 return 0;
3343}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003344
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003345/* starting from main bpf function walk all instructions of the function
3346 * and recursively walk all callees that given function can call.
3347 * Ignore jump and exit insns.
3348 * Since recursion is prevented by check_cfg() this algorithm
3349 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3350 */
3351static int check_max_stack_depth(struct bpf_verifier_env *env)
3352{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003353 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3354 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003355 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003356 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003357 int ret_insn[MAX_CALL_FRAMES];
3358 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003359 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003360
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003361process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003362 /* protect against potential stack overflow that might happen when
3363 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3364 * depth for such case down to 256 so that the worst case scenario
3365 * would result in 8k stack size (32 which is tailcall limit * 256 =
3366 * 8k).
3367 *
3368 * To get the idea what might happen, see an example:
3369 * func1 -> sub rsp, 128
3370 * subfunc1 -> sub rsp, 256
3371 * tailcall1 -> add rsp, 256
3372 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3373 * subfunc2 -> sub rsp, 64
3374 * subfunc22 -> sub rsp, 128
3375 * tailcall2 -> add rsp, 128
3376 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3377 *
3378 * tailcall will unwind the current stack frame but it will not get rid
3379 * of caller's stack as shown on the example above.
3380 */
3381 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3382 verbose(env,
3383 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3384 depth);
3385 return -EACCES;
3386 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003387 /* round up to 32-bytes, since this is granularity
3388 * of interpreter stack size
3389 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003390 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003391 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003392 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003393 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003394 return -EACCES;
3395 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003396continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003397 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003398 for (; i < subprog_end; i++) {
Yonghong Song23a2d702021-02-04 15:48:27 -08003399 if (!bpf_pseudo_call(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003400 continue;
3401 /* remember insn and function to return to */
3402 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003403 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003404
3405 /* find the callee */
3406 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003407 idx = find_subprog(env, i);
3408 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003409 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3410 i);
3411 return -EFAULT;
3412 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003413
3414 if (subprog[idx].has_tail_call)
3415 tail_call_reachable = true;
3416
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003417 frame++;
3418 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003419 verbose(env, "the call stack of %d frames is too deep !\n",
3420 frame);
3421 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003422 }
3423 goto process_func;
3424 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003425 /* if tail call got detected across bpf2bpf calls then mark each of the
3426 * currently present subprog frames as tail call reachable subprogs;
3427 * this info will be utilized by JIT so that we will be preserving the
3428 * tail call counter throughout bpf2bpf calls combined with tailcalls
3429 */
3430 if (tail_call_reachable)
3431 for (j = 0; j < frame; j++)
3432 subprog[ret_prog[j]].tail_call_reachable = true;
3433
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003434 /* end of for() loop means the last insn of the 'subprog'
3435 * was reached. Doesn't matter whether it was JA or EXIT
3436 */
3437 if (frame == 0)
3438 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003439 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003440 frame--;
3441 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003442 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003443 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003444}
3445
David S. Miller19d28fb2018-01-11 21:27:54 -05003446#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003447static int get_callee_stack_depth(struct bpf_verifier_env *env,
3448 const struct bpf_insn *insn, int idx)
3449{
3450 int start = idx + insn->imm + 1, subprog;
3451
3452 subprog = find_subprog(env, start);
3453 if (subprog < 0) {
3454 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3455 start);
3456 return -EFAULT;
3457 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003458 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003459}
David S. Miller19d28fb2018-01-11 21:27:54 -05003460#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003461
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003462int check_ctx_reg(struct bpf_verifier_env *env,
3463 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003464{
3465 /* Access to ctx or passing it to a helper is only allowed in
3466 * its original, unmodified form.
3467 */
3468
3469 if (reg->off) {
3470 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3471 regno, reg->off);
3472 return -EACCES;
3473 }
3474
3475 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3476 char tn_buf[48];
3477
3478 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3479 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3480 return -EACCES;
3481 }
3482
3483 return 0;
3484}
3485
Yonghong Songafbf21d2020-07-23 11:41:11 -07003486static int __check_buffer_access(struct bpf_verifier_env *env,
3487 const char *buf_info,
3488 const struct bpf_reg_state *reg,
3489 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003490{
3491 if (off < 0) {
3492 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003493 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003494 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003495 return -EACCES;
3496 }
3497 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3498 char tn_buf[48];
3499
3500 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3501 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003502 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003503 regno, off, tn_buf);
3504 return -EACCES;
3505 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003506
3507 return 0;
3508}
3509
3510static int check_tp_buffer_access(struct bpf_verifier_env *env,
3511 const struct bpf_reg_state *reg,
3512 int regno, int off, int size)
3513{
3514 int err;
3515
3516 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3517 if (err)
3518 return err;
3519
Matt Mullins9df1c282019-04-26 11:49:47 -07003520 if (off + size > env->prog->aux->max_tp_access)
3521 env->prog->aux->max_tp_access = off + size;
3522
3523 return 0;
3524}
3525
Yonghong Songafbf21d2020-07-23 11:41:11 -07003526static int check_buffer_access(struct bpf_verifier_env *env,
3527 const struct bpf_reg_state *reg,
3528 int regno, int off, int size,
3529 bool zero_size_allowed,
3530 const char *buf_info,
3531 u32 *max_access)
3532{
3533 int err;
3534
3535 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3536 if (err)
3537 return err;
3538
3539 if (off + size > *max_access)
3540 *max_access = off + size;
3541
3542 return 0;
3543}
3544
John Fastabend3f50f132020-03-30 14:36:39 -07003545/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3546static void zext_32_to_64(struct bpf_reg_state *reg)
3547{
3548 reg->var_off = tnum_subreg(reg->var_off);
3549 __reg_assign_32_into_64(reg);
3550}
Matt Mullins9df1c282019-04-26 11:49:47 -07003551
Jann Horn0c17d1d2017-12-18 20:11:55 -08003552/* truncate register to smaller size (in bytes)
3553 * must be called with size < BPF_REG_SIZE
3554 */
3555static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3556{
3557 u64 mask;
3558
3559 /* clear high bits in bit representation */
3560 reg->var_off = tnum_cast(reg->var_off, size);
3561
3562 /* fix arithmetic bounds */
3563 mask = ((u64)1 << (size * 8)) - 1;
3564 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3565 reg->umin_value &= mask;
3566 reg->umax_value &= mask;
3567 } else {
3568 reg->umin_value = 0;
3569 reg->umax_value = mask;
3570 }
3571 reg->smin_value = reg->umin_value;
3572 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003573
3574 /* If size is smaller than 32bit register the 32bit register
3575 * values are also truncated so we push 64-bit bounds into
3576 * 32-bit bounds. Above were truncated < 32-bits already.
3577 */
3578 if (size >= 4)
3579 return;
3580 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003581}
3582
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003583static bool bpf_map_is_rdonly(const struct bpf_map *map)
3584{
3585 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3586}
3587
3588static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3589{
3590 void *ptr;
3591 u64 addr;
3592 int err;
3593
3594 err = map->ops->map_direct_value_addr(map, &addr, off);
3595 if (err)
3596 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003597 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003598
3599 switch (size) {
3600 case sizeof(u8):
3601 *val = (u64)*(u8 *)ptr;
3602 break;
3603 case sizeof(u16):
3604 *val = (u64)*(u16 *)ptr;
3605 break;
3606 case sizeof(u32):
3607 *val = (u64)*(u32 *)ptr;
3608 break;
3609 case sizeof(u64):
3610 *val = *(u64 *)ptr;
3611 break;
3612 default:
3613 return -EINVAL;
3614 }
3615 return 0;
3616}
3617
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003618static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3619 struct bpf_reg_state *regs,
3620 int regno, int off, int size,
3621 enum bpf_access_type atype,
3622 int value_regno)
3623{
3624 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003625 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3626 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003627 u32 btf_id;
3628 int ret;
3629
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003630 if (off < 0) {
3631 verbose(env,
3632 "R%d is ptr_%s invalid negative access: off=%d\n",
3633 regno, tname, off);
3634 return -EACCES;
3635 }
3636 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3637 char tn_buf[48];
3638
3639 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3640 verbose(env,
3641 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3642 regno, tname, off, tn_buf);
3643 return -EACCES;
3644 }
3645
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003646 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003647 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3648 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003649 } else {
3650 if (atype != BPF_READ) {
3651 verbose(env, "only read is supported\n");
3652 return -EACCES;
3653 }
3654
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003655 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3656 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003657 }
3658
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003659 if (ret < 0)
3660 return ret;
3661
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003662 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003663 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003664
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003665 return 0;
3666}
3667
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003668static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3669 struct bpf_reg_state *regs,
3670 int regno, int off, int size,
3671 enum bpf_access_type atype,
3672 int value_regno)
3673{
3674 struct bpf_reg_state *reg = regs + regno;
3675 struct bpf_map *map = reg->map_ptr;
3676 const struct btf_type *t;
3677 const char *tname;
3678 u32 btf_id;
3679 int ret;
3680
3681 if (!btf_vmlinux) {
3682 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3683 return -ENOTSUPP;
3684 }
3685
3686 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3687 verbose(env, "map_ptr access not supported for map type %d\n",
3688 map->map_type);
3689 return -ENOTSUPP;
3690 }
3691
3692 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3693 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3694
3695 if (!env->allow_ptr_to_map_access) {
3696 verbose(env,
3697 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3698 tname);
3699 return -EPERM;
3700 }
3701
3702 if (off < 0) {
3703 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3704 regno, tname, off);
3705 return -EACCES;
3706 }
3707
3708 if (atype != BPF_READ) {
3709 verbose(env, "only read from %s is supported\n", tname);
3710 return -EACCES;
3711 }
3712
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003713 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003714 if (ret < 0)
3715 return ret;
3716
3717 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003718 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003719
3720 return 0;
3721}
3722
Andrei Matei01f810a2021-02-06 20:10:24 -05003723/* Check that the stack access at the given offset is within bounds. The
3724 * maximum valid offset is -1.
3725 *
3726 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3727 * -state->allocated_stack for reads.
3728 */
3729static int check_stack_slot_within_bounds(int off,
3730 struct bpf_func_state *state,
3731 enum bpf_access_type t)
3732{
3733 int min_valid_off;
3734
3735 if (t == BPF_WRITE)
3736 min_valid_off = -MAX_BPF_STACK;
3737 else
3738 min_valid_off = -state->allocated_stack;
3739
3740 if (off < min_valid_off || off > -1)
3741 return -EACCES;
3742 return 0;
3743}
3744
3745/* Check that the stack access at 'regno + off' falls within the maximum stack
3746 * bounds.
3747 *
3748 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3749 */
3750static int check_stack_access_within_bounds(
3751 struct bpf_verifier_env *env,
3752 int regno, int off, int access_size,
3753 enum stack_access_src src, enum bpf_access_type type)
3754{
3755 struct bpf_reg_state *regs = cur_regs(env);
3756 struct bpf_reg_state *reg = regs + regno;
3757 struct bpf_func_state *state = func(env, reg);
3758 int min_off, max_off;
3759 int err;
3760 char *err_extra;
3761
3762 if (src == ACCESS_HELPER)
3763 /* We don't know if helpers are reading or writing (or both). */
3764 err_extra = " indirect access to";
3765 else if (type == BPF_READ)
3766 err_extra = " read from";
3767 else
3768 err_extra = " write to";
3769
3770 if (tnum_is_const(reg->var_off)) {
3771 min_off = reg->var_off.value + off;
3772 if (access_size > 0)
3773 max_off = min_off + access_size - 1;
3774 else
3775 max_off = min_off;
3776 } else {
3777 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3778 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3779 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3780 err_extra, regno);
3781 return -EACCES;
3782 }
3783 min_off = reg->smin_value + off;
3784 if (access_size > 0)
3785 max_off = reg->smax_value + off + access_size - 1;
3786 else
3787 max_off = min_off;
3788 }
3789
3790 err = check_stack_slot_within_bounds(min_off, state, type);
3791 if (!err)
3792 err = check_stack_slot_within_bounds(max_off, state, type);
3793
3794 if (err) {
3795 if (tnum_is_const(reg->var_off)) {
3796 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3797 err_extra, regno, off, access_size);
3798 } else {
3799 char tn_buf[48];
3800
3801 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3802 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3803 err_extra, regno, tn_buf, access_size);
3804 }
3805 }
3806 return err;
3807}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003808
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003809/* check whether memory at (regno + off) is accessible for t = (read | write)
3810 * if t==write, value_regno is a register which value is stored into memory
3811 * if t==read, value_regno is a register which will receive the value from memory
3812 * if t==write && value_regno==-1, some unknown value is stored into memory
3813 * if t==read && value_regno==-1, don't care what we read from memory
3814 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003815static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3816 int off, int bpf_size, enum bpf_access_type t,
3817 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003818{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003819 struct bpf_reg_state *regs = cur_regs(env);
3820 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003821 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003822 int size, err = 0;
3823
3824 size = bpf_size_to_bytes(bpf_size);
3825 if (size < 0)
3826 return size;
3827
Edward Creef1174f72017-08-07 15:26:19 +01003828 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003829 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003830 if (err)
3831 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003832
Edward Creef1174f72017-08-07 15:26:19 +01003833 /* for access checks, reg->off is just part of off */
3834 off += reg->off;
3835
3836 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003837 if (t == BPF_WRITE && value_regno >= 0 &&
3838 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003839 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003840 return -EACCES;
3841 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003842 err = check_map_access_type(env, regno, off, size, t);
3843 if (err)
3844 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003845 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003846 if (!err && t == BPF_READ && value_regno >= 0) {
3847 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003848
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003849 /* if map is read-only, track its contents as scalars */
3850 if (tnum_is_const(reg->var_off) &&
3851 bpf_map_is_rdonly(map) &&
3852 map->ops->map_direct_value_addr) {
3853 int map_off = off + reg->var_off.value;
3854 u64 val = 0;
3855
3856 err = bpf_map_direct_read(map, map_off, size,
3857 &val);
3858 if (err)
3859 return err;
3860
3861 regs[value_regno].type = SCALAR_VALUE;
3862 __mark_reg_known(&regs[value_regno], val);
3863 } else {
3864 mark_reg_unknown(env, regs, value_regno);
3865 }
3866 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003867 } else if (reg->type == PTR_TO_MEM) {
3868 if (t == BPF_WRITE && value_regno >= 0 &&
3869 is_pointer_value(env, value_regno)) {
3870 verbose(env, "R%d leaks addr into mem\n", value_regno);
3871 return -EACCES;
3872 }
3873 err = check_mem_region_access(env, regno, off, size,
3874 reg->mem_size, false);
3875 if (!err && t == BPF_READ && value_regno >= 0)
3876 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003877 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003878 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003879 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003880 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003881
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003882 if (t == BPF_WRITE && value_regno >= 0 &&
3883 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003884 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003885 return -EACCES;
3886 }
Edward Creef1174f72017-08-07 15:26:19 +01003887
Daniel Borkmann58990d12018-06-07 17:40:03 +02003888 err = check_ctx_reg(env, reg, regno);
3889 if (err < 0)
3890 return err;
3891
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003892 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003893 if (err)
3894 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003895 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003896 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003897 * PTR_TO_PACKET[_META,_END]. In the latter
3898 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003899 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003900 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003901 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003902 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003903 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003904 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003905 if (reg_type_may_be_null(reg_type))
3906 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003907 /* A load of ctx field could have different
3908 * actual load size with the one encoded in the
3909 * insn. When the dst is PTR, it is for sure not
3910 * a sub-register.
3911 */
3912 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003913 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003914 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3915 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003916 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003917 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003918 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003919 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003920 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003921
Edward Creef1174f72017-08-07 15:26:19 +01003922 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05003923 /* Basic bounds checks. */
3924 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003925 if (err)
3926 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003927
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003928 state = func(env, reg);
3929 err = update_stack_depth(env, state, off);
3930 if (err)
3931 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003932
Andrei Matei01f810a2021-02-06 20:10:24 -05003933 if (t == BPF_READ)
3934 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003935 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05003936 else
3937 err = check_stack_write(env, regno, off, size,
3938 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003939 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003940 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003941 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003942 return -EACCES;
3943 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003944 if (t == BPF_WRITE && value_regno >= 0 &&
3945 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003946 verbose(env, "R%d leaks addr into packet\n",
3947 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003948 return -EACCES;
3949 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003950 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003951 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003952 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003953 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3954 if (t == BPF_WRITE && value_regno >= 0 &&
3955 is_pointer_value(env, value_regno)) {
3956 verbose(env, "R%d leaks addr into flow keys\n",
3957 value_regno);
3958 return -EACCES;
3959 }
3960
3961 err = check_flow_keys_access(env, off, size);
3962 if (!err && t == BPF_READ && value_regno >= 0)
3963 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003964 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003965 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003966 verbose(env, "R%d cannot write into %s\n",
3967 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003968 return -EACCES;
3969 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003970 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003971 if (!err && value_regno >= 0)
3972 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003973 } else if (reg->type == PTR_TO_TP_BUFFER) {
3974 err = check_tp_buffer_access(env, reg, regno, off, size);
3975 if (!err && t == BPF_READ && value_regno >= 0)
3976 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003977 } else if (reg->type == PTR_TO_BTF_ID) {
3978 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3979 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003980 } else if (reg->type == CONST_PTR_TO_MAP) {
3981 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3982 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003983 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3984 if (t == BPF_WRITE) {
3985 verbose(env, "R%d cannot write into %s\n",
3986 regno, reg_type_str[reg->type]);
3987 return -EACCES;
3988 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003989 err = check_buffer_access(env, reg, regno, off, size, false,
3990 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003991 &env->prog->aux->max_rdonly_access);
3992 if (!err && value_regno >= 0)
3993 mark_reg_unknown(env, regs, value_regno);
3994 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003995 err = check_buffer_access(env, reg, regno, off, size, false,
3996 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003997 &env->prog->aux->max_rdwr_access);
3998 if (!err && t == BPF_READ && value_regno >= 0)
3999 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004000 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004001 verbose(env, "R%d invalid mem access '%s'\n", regno,
4002 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004003 return -EACCES;
4004 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004005
Edward Creef1174f72017-08-07 15:26:19 +01004006 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004007 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004008 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08004009 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004010 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004011 return err;
4012}
4013
Brendan Jackman91c960b2021-01-14 18:17:44 +00004014static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004015{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004016 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004017 int err;
4018
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004019 switch (insn->imm) {
4020 case BPF_ADD:
4021 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004022 case BPF_AND:
4023 case BPF_AND | BPF_FETCH:
4024 case BPF_OR:
4025 case BPF_OR | BPF_FETCH:
4026 case BPF_XOR:
4027 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004028 case BPF_XCHG:
4029 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004030 break;
4031 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004032 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4033 return -EINVAL;
4034 }
4035
4036 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4037 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004038 return -EINVAL;
4039 }
4040
4041 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004042 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004043 if (err)
4044 return err;
4045
4046 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004047 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004048 if (err)
4049 return err;
4050
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004051 if (insn->imm == BPF_CMPXCHG) {
4052 /* Check comparison of R0 with memory location */
4053 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4054 if (err)
4055 return err;
4056 }
4057
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004058 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004059 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004060 return -EACCES;
4061 }
4062
Daniel Borkmannca369602018-02-23 22:29:05 +01004063 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004064 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004065 is_flow_key_reg(env, insn->dst_reg) ||
4066 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004067 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004068 insn->dst_reg,
4069 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004070 return -EACCES;
4071 }
4072
Brendan Jackman37086bf2021-02-02 13:50:02 +00004073 if (insn->imm & BPF_FETCH) {
4074 if (insn->imm == BPF_CMPXCHG)
4075 load_reg = BPF_REG_0;
4076 else
4077 load_reg = insn->src_reg;
4078
4079 /* check and record load of old value */
4080 err = check_reg_arg(env, load_reg, DST_OP);
4081 if (err)
4082 return err;
4083 } else {
4084 /* This instruction accesses a memory location but doesn't
4085 * actually load it into a register.
4086 */
4087 load_reg = -1;
4088 }
4089
Brendan Jackman91c960b2021-01-14 18:17:44 +00004090 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004091 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004092 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004093 if (err)
4094 return err;
4095
Brendan Jackman91c960b2021-01-14 18:17:44 +00004096 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004097 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4098 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4099 if (err)
4100 return err;
4101
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004102 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004103}
4104
Andrei Matei01f810a2021-02-06 20:10:24 -05004105/* When register 'regno' is used to read the stack (either directly or through
4106 * a helper function) make sure that it's within stack boundary and, depending
4107 * on the access type, that all elements of the stack are initialized.
4108 *
4109 * 'off' includes 'regno->off', but not its dynamic part (if any).
4110 *
4111 * All registers that have been spilled on the stack in the slots within the
4112 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004113 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004114static int check_stack_range_initialized(
4115 struct bpf_verifier_env *env, int regno, int off,
4116 int access_size, bool zero_size_allowed,
4117 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004118{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004119 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004120 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004121 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004122 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4123 enum bpf_access_type bounds_check_type;
4124 /* Some accesses can write anything into the stack, others are
4125 * read-only.
4126 */
4127 bool clobber = false;
4128
4129 if (access_size == 0 && !zero_size_allowed) {
4130 verbose(env, "invalid zero-sized read\n");
4131 return -EACCES;
4132 }
4133
4134 if (type == ACCESS_HELPER) {
4135 /* The bounds checks for writes are more permissive than for
4136 * reads. However, if raw_mode is not set, we'll do extra
4137 * checks below.
4138 */
4139 bounds_check_type = BPF_WRITE;
4140 clobber = true;
4141 } else {
4142 bounds_check_type = BPF_READ;
4143 }
4144 err = check_stack_access_within_bounds(env, regno, off, access_size,
4145 type, bounds_check_type);
4146 if (err)
4147 return err;
4148
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004149
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004150 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004151 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004152 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004153 /* Variable offset is prohibited for unprivileged mode for
4154 * simplicity since it requires corresponding support in
4155 * Spectre masking for stack ALU.
4156 * See also retrieve_ptr_limit().
4157 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004158 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004159 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004160
Andrey Ignatov088ec262019-04-03 23:22:39 -07004161 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004162 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4163 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004164 return -EACCES;
4165 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004166 /* Only initialized buffer on stack is allowed to be accessed
4167 * with variable offset. With uninitialized buffer it's hard to
4168 * guarantee that whole memory is marked as initialized on
4169 * helper return since specific bounds are unknown what may
4170 * cause uninitialized stack leaking.
4171 */
4172 if (meta && meta->raw_mode)
4173 meta = NULL;
4174
Andrei Matei01f810a2021-02-06 20:10:24 -05004175 min_off = reg->smin_value + off;
4176 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004177 }
4178
Daniel Borkmann435faee12016-04-13 00:10:51 +02004179 if (meta && meta->raw_mode) {
4180 meta->access_size = access_size;
4181 meta->regno = regno;
4182 return 0;
4183 }
4184
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004185 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004186 u8 *stype;
4187
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004188 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004189 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004190 if (state->allocated_stack <= slot)
4191 goto err;
4192 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4193 if (*stype == STACK_MISC)
4194 goto mark;
4195 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004196 if (clobber) {
4197 /* helper can write anything into the stack */
4198 *stype = STACK_MISC;
4199 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004200 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004201 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004202
4203 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4204 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4205 goto mark;
4206
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004207 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004208 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4209 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004210 if (clobber) {
4211 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4212 for (j = 0; j < BPF_REG_SIZE; j++)
4213 state->stack[spi].slot_type[j] = STACK_MISC;
4214 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004215 goto mark;
4216 }
4217
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004218err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004219 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004220 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4221 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004222 } else {
4223 char tn_buf[48];
4224
4225 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004226 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4227 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004228 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004229 return -EACCES;
4230mark:
4231 /* reading any byte out of 8-byte 'spill_slot' will cause
4232 * the whole slot to be marked as 'read'
4233 */
Edward Cree679c7822018-08-22 20:02:19 +01004234 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004235 state->stack[spi].spilled_ptr.parent,
4236 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004237 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004238 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004239}
4240
Gianluca Borello06c1c042017-01-09 10:19:49 -08004241static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4242 int access_size, bool zero_size_allowed,
4243 struct bpf_call_arg_meta *meta)
4244{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004245 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004246
Edward Creef1174f72017-08-07 15:26:19 +01004247 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004248 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004249 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004250 return check_packet_access(env, regno, reg->off, access_size,
4251 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004252 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004253 if (check_map_access_type(env, regno, reg->off, access_size,
4254 meta && meta->raw_mode ? BPF_WRITE :
4255 BPF_READ))
4256 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004257 return check_map_access(env, regno, reg->off, access_size,
4258 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004259 case PTR_TO_MEM:
4260 return check_mem_region_access(env, regno, reg->off,
4261 access_size, reg->mem_size,
4262 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004263 case PTR_TO_RDONLY_BUF:
4264 if (meta && meta->raw_mode)
4265 return -EACCES;
4266 return check_buffer_access(env, reg, regno, reg->off,
4267 access_size, zero_size_allowed,
4268 "rdonly",
4269 &env->prog->aux->max_rdonly_access);
4270 case PTR_TO_RDWR_BUF:
4271 return check_buffer_access(env, reg, regno, reg->off,
4272 access_size, zero_size_allowed,
4273 "rdwr",
4274 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004275 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004276 return check_stack_range_initialized(
4277 env,
4278 regno, reg->off, access_size,
4279 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004280 default: /* scalar_value or invalid ptr */
4281 /* Allow zero-byte read from NULL, regardless of pointer type */
4282 if (zero_size_allowed && access_size == 0 &&
4283 register_is_null(reg))
4284 return 0;
4285
4286 verbose(env, "R%d type=%s expected=%s\n", regno,
4287 reg_type_str[reg->type],
4288 reg_type_str[PTR_TO_STACK]);
4289 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004290 }
4291}
4292
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004293int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4294 u32 regno, u32 mem_size)
4295{
4296 if (register_is_null(reg))
4297 return 0;
4298
4299 if (reg_type_may_be_null(reg->type)) {
4300 /* Assuming that the register contains a value check if the memory
4301 * access is safe. Temporarily save and restore the register's state as
4302 * the conversion shouldn't be visible to a caller.
4303 */
4304 const struct bpf_reg_state saved_reg = *reg;
4305 int rv;
4306
4307 mark_ptr_not_null_reg(reg);
4308 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4309 *reg = saved_reg;
4310 return rv;
4311 }
4312
4313 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4314}
4315
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004316/* Implementation details:
4317 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4318 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4319 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4320 * value_or_null->value transition, since the verifier only cares about
4321 * the range of access to valid map value pointer and doesn't care about actual
4322 * address of the map element.
4323 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4324 * reg->id > 0 after value_or_null->value transition. By doing so
4325 * two bpf_map_lookups will be considered two different pointers that
4326 * point to different bpf_spin_locks.
4327 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4328 * dead-locks.
4329 * Since only one bpf_spin_lock is allowed the checks are simpler than
4330 * reg_is_refcounted() logic. The verifier needs to remember only
4331 * one spin_lock instead of array of acquired_refs.
4332 * cur_state->active_spin_lock remembers which map value element got locked
4333 * and clears it after bpf_spin_unlock.
4334 */
4335static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4336 bool is_lock)
4337{
4338 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4339 struct bpf_verifier_state *cur = env->cur_state;
4340 bool is_const = tnum_is_const(reg->var_off);
4341 struct bpf_map *map = reg->map_ptr;
4342 u64 val = reg->var_off.value;
4343
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004344 if (!is_const) {
4345 verbose(env,
4346 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4347 regno);
4348 return -EINVAL;
4349 }
4350 if (!map->btf) {
4351 verbose(env,
4352 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4353 map->name);
4354 return -EINVAL;
4355 }
4356 if (!map_value_has_spin_lock(map)) {
4357 if (map->spin_lock_off == -E2BIG)
4358 verbose(env,
4359 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4360 map->name);
4361 else if (map->spin_lock_off == -ENOENT)
4362 verbose(env,
4363 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4364 map->name);
4365 else
4366 verbose(env,
4367 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4368 map->name);
4369 return -EINVAL;
4370 }
4371 if (map->spin_lock_off != val + reg->off) {
4372 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4373 val + reg->off);
4374 return -EINVAL;
4375 }
4376 if (is_lock) {
4377 if (cur->active_spin_lock) {
4378 verbose(env,
4379 "Locking two bpf_spin_locks are not allowed\n");
4380 return -EINVAL;
4381 }
4382 cur->active_spin_lock = reg->id;
4383 } else {
4384 if (!cur->active_spin_lock) {
4385 verbose(env, "bpf_spin_unlock without taking a lock\n");
4386 return -EINVAL;
4387 }
4388 if (cur->active_spin_lock != reg->id) {
4389 verbose(env, "bpf_spin_unlock of different lock\n");
4390 return -EINVAL;
4391 }
4392 cur->active_spin_lock = 0;
4393 }
4394 return 0;
4395}
4396
Daniel Borkmann90133412018-01-20 01:24:29 +01004397static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4398{
4399 return type == ARG_PTR_TO_MEM ||
4400 type == ARG_PTR_TO_MEM_OR_NULL ||
4401 type == ARG_PTR_TO_UNINIT_MEM;
4402}
4403
4404static bool arg_type_is_mem_size(enum bpf_arg_type type)
4405{
4406 return type == ARG_CONST_SIZE ||
4407 type == ARG_CONST_SIZE_OR_ZERO;
4408}
4409
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004410static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4411{
4412 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4413}
4414
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004415static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4416{
4417 return type == ARG_PTR_TO_INT ||
4418 type == ARG_PTR_TO_LONG;
4419}
4420
4421static int int_ptr_type_to_size(enum bpf_arg_type type)
4422{
4423 if (type == ARG_PTR_TO_INT)
4424 return sizeof(u32);
4425 else if (type == ARG_PTR_TO_LONG)
4426 return sizeof(u64);
4427
4428 return -EINVAL;
4429}
4430
Lorenz Bauer912f4422020-08-21 11:29:46 +01004431static int resolve_map_arg_type(struct bpf_verifier_env *env,
4432 const struct bpf_call_arg_meta *meta,
4433 enum bpf_arg_type *arg_type)
4434{
4435 if (!meta->map_ptr) {
4436 /* kernel subsystem misconfigured verifier */
4437 verbose(env, "invalid map_ptr to access map->type\n");
4438 return -EACCES;
4439 }
4440
4441 switch (meta->map_ptr->map_type) {
4442 case BPF_MAP_TYPE_SOCKMAP:
4443 case BPF_MAP_TYPE_SOCKHASH:
4444 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01004445 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01004446 } else {
4447 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4448 return -EINVAL;
4449 }
4450 break;
4451
4452 default:
4453 break;
4454 }
4455 return 0;
4456}
4457
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004458struct bpf_reg_types {
4459 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004460 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004461};
4462
4463static const struct bpf_reg_types map_key_value_types = {
4464 .types = {
4465 PTR_TO_STACK,
4466 PTR_TO_PACKET,
4467 PTR_TO_PACKET_META,
4468 PTR_TO_MAP_VALUE,
4469 },
4470};
4471
4472static const struct bpf_reg_types sock_types = {
4473 .types = {
4474 PTR_TO_SOCK_COMMON,
4475 PTR_TO_SOCKET,
4476 PTR_TO_TCP_SOCK,
4477 PTR_TO_XDP_SOCK,
4478 },
4479};
4480
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004481#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004482static const struct bpf_reg_types btf_id_sock_common_types = {
4483 .types = {
4484 PTR_TO_SOCK_COMMON,
4485 PTR_TO_SOCKET,
4486 PTR_TO_TCP_SOCK,
4487 PTR_TO_XDP_SOCK,
4488 PTR_TO_BTF_ID,
4489 },
4490 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4491};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004492#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004493
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004494static const struct bpf_reg_types mem_types = {
4495 .types = {
4496 PTR_TO_STACK,
4497 PTR_TO_PACKET,
4498 PTR_TO_PACKET_META,
4499 PTR_TO_MAP_VALUE,
4500 PTR_TO_MEM,
4501 PTR_TO_RDONLY_BUF,
4502 PTR_TO_RDWR_BUF,
4503 },
4504};
4505
4506static const struct bpf_reg_types int_ptr_types = {
4507 .types = {
4508 PTR_TO_STACK,
4509 PTR_TO_PACKET,
4510 PTR_TO_PACKET_META,
4511 PTR_TO_MAP_VALUE,
4512 },
4513};
4514
4515static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4516static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4517static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4518static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4519static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4520static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4521static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004522static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004523
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004524static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004525 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4526 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4527 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4528 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4529 [ARG_CONST_SIZE] = &scalar_types,
4530 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4531 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4532 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4533 [ARG_PTR_TO_CTX] = &context_types,
4534 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4535 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004536#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004537 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004538#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004539 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4540 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4541 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4542 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4543 [ARG_PTR_TO_MEM] = &mem_types,
4544 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4545 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4546 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4547 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4548 [ARG_PTR_TO_INT] = &int_ptr_types,
4549 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004550 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004551};
4552
4553static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004554 enum bpf_arg_type arg_type,
4555 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004556{
4557 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4558 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004559 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004560 int i, j;
4561
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004562 compatible = compatible_reg_types[arg_type];
4563 if (!compatible) {
4564 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4565 return -EFAULT;
4566 }
4567
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004568 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4569 expected = compatible->types[i];
4570 if (expected == NOT_INIT)
4571 break;
4572
4573 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004574 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004575 }
4576
4577 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4578 for (j = 0; j + 1 < i; j++)
4579 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4580 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4581 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004582
4583found:
4584 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004585 if (!arg_btf_id) {
4586 if (!compatible->btf_id) {
4587 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4588 return -EFAULT;
4589 }
4590 arg_btf_id = compatible->btf_id;
4591 }
4592
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004593 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4594 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004595 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004596 regno, kernel_type_name(reg->btf, reg->btf_id),
4597 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004598 return -EACCES;
4599 }
4600
4601 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4602 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4603 regno);
4604 return -EACCES;
4605 }
4606 }
4607
4608 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004609}
4610
Yonghong Songaf7ec132020-06-23 16:08:09 -07004611static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4612 struct bpf_call_arg_meta *meta,
4613 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004614{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004615 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004616 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004617 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004618 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004619 int err = 0;
4620
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004621 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004622 return 0;
4623
Edward Creedc503a82017-08-15 20:34:35 +01004624 err = check_reg_arg(env, regno, SRC_OP);
4625 if (err)
4626 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004627
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004628 if (arg_type == ARG_ANYTHING) {
4629 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004630 verbose(env, "R%d leaks addr into helper function\n",
4631 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004632 return -EACCES;
4633 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004634 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004635 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004636
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004637 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004638 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004639 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004640 return -EACCES;
4641 }
4642
Lorenz Bauer912f4422020-08-21 11:29:46 +01004643 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4644 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4645 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4646 err = resolve_map_arg_type(env, meta, &arg_type);
4647 if (err)
4648 return err;
4649 }
4650
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004651 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4652 /* A NULL register has a SCALAR_VALUE type, so skip
4653 * type checking.
4654 */
4655 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004656
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004657 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004658 if (err)
4659 return err;
4660
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004661 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004662 err = check_ctx_reg(env, reg, regno);
4663 if (err < 0)
4664 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004665 }
4666
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004667skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004668 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004669 if (meta->ref_obj_id) {
4670 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4671 regno, reg->ref_obj_id,
4672 meta->ref_obj_id);
4673 return -EFAULT;
4674 }
4675 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004676 }
4677
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004678 if (arg_type == ARG_CONST_MAP_PTR) {
4679 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004680 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004681 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4682 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4683 * check that [key, key + map->key_size) are within
4684 * stack limits and initialized
4685 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004686 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004687 /* in function declaration map_ptr must come before
4688 * map_key, so that it's verified and known before
4689 * we have to check map_key here. Otherwise it means
4690 * that kernel subsystem misconfigured verifier
4691 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004692 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004693 return -EACCES;
4694 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004695 err = check_helper_mem_access(env, regno,
4696 meta->map_ptr->key_size, false,
4697 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004698 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004699 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4700 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004701 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004702 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4703 * check [value, value + map->value_size) validity
4704 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004705 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004706 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004707 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004708 return -EACCES;
4709 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004710 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004711 err = check_helper_mem_access(env, regno,
4712 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004713 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004714 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4715 if (!reg->btf_id) {
4716 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4717 return -EACCES;
4718 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004719 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004720 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004721 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4722 if (meta->func_id == BPF_FUNC_spin_lock) {
4723 if (process_spin_lock(env, regno, true))
4724 return -EACCES;
4725 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4726 if (process_spin_lock(env, regno, false))
4727 return -EACCES;
4728 } else {
4729 verbose(env, "verifier internal error\n");
4730 return -EFAULT;
4731 }
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01004732 } else if (arg_type_is_mem_ptr(arg_type)) {
4733 /* The access to this pointer is only checked when we hit the
4734 * next is_mem_size argument below.
4735 */
4736 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01004737 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004738 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004739
John Fastabend10060502020-03-30 14:36:19 -07004740 /* This is used to refine r0 return value bounds for helpers
4741 * that enforce this value as an upper bound on return values.
4742 * See do_refine_retval_range() for helpers that can refine
4743 * the return value. C type of helper is u32 so we pull register
4744 * bound from umax_value however, if negative verifier errors
4745 * out. Only upper bounds can be learned because retval is an
4746 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004747 */
John Fastabend10060502020-03-30 14:36:19 -07004748 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004749
Edward Creef1174f72017-08-07 15:26:19 +01004750 /* The register is SCALAR_VALUE; the access check
4751 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004752 */
Edward Creef1174f72017-08-07 15:26:19 +01004753 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004754 /* For unprivileged variable accesses, disable raw
4755 * mode so that the program is required to
4756 * initialize all the memory that the helper could
4757 * just partially fill up.
4758 */
4759 meta = NULL;
4760
Edward Creeb03c9f92017-08-07 15:26:36 +01004761 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004762 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004763 regno);
4764 return -EACCES;
4765 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004766
Edward Creeb03c9f92017-08-07 15:26:36 +01004767 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004768 err = check_helper_mem_access(env, regno - 1, 0,
4769 zero_size_allowed,
4770 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004771 if (err)
4772 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004773 }
Edward Creef1174f72017-08-07 15:26:19 +01004774
Edward Creeb03c9f92017-08-07 15:26:36 +01004775 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004776 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004777 regno);
4778 return -EACCES;
4779 }
4780 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004781 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004782 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004783 if (!err)
4784 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004785 } else if (arg_type_is_alloc_size(arg_type)) {
4786 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00004787 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004788 regno);
4789 return -EACCES;
4790 }
4791 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004792 } else if (arg_type_is_int_ptr(arg_type)) {
4793 int size = int_ptr_type_to_size(arg_type);
4794
4795 err = check_helper_mem_access(env, regno, size, false, meta);
4796 if (err)
4797 return err;
4798 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004799 }
4800
4801 return err;
4802}
4803
Lorenz Bauer01262402020-08-21 11:29:47 +01004804static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4805{
4806 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004807 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004808
4809 if (func_id != BPF_FUNC_map_update_elem)
4810 return false;
4811
4812 /* It's not possible to get access to a locked struct sock in these
4813 * contexts, so updating is safe.
4814 */
4815 switch (type) {
4816 case BPF_PROG_TYPE_TRACING:
4817 if (eatype == BPF_TRACE_ITER)
4818 return true;
4819 break;
4820 case BPF_PROG_TYPE_SOCKET_FILTER:
4821 case BPF_PROG_TYPE_SCHED_CLS:
4822 case BPF_PROG_TYPE_SCHED_ACT:
4823 case BPF_PROG_TYPE_XDP:
4824 case BPF_PROG_TYPE_SK_REUSEPORT:
4825 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4826 case BPF_PROG_TYPE_SK_LOOKUP:
4827 return true;
4828 default:
4829 break;
4830 }
4831
4832 verbose(env, "cannot update sockmap in this context\n");
4833 return false;
4834}
4835
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004836static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4837{
4838 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4839}
4840
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004841static int check_map_func_compatibility(struct bpf_verifier_env *env,
4842 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004843{
Kaixu Xia35578d72015-08-06 07:02:35 +00004844 if (!map)
4845 return 0;
4846
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004847 /* We need a two way check, first is from map perspective ... */
4848 switch (map->map_type) {
4849 case BPF_MAP_TYPE_PROG_ARRAY:
4850 if (func_id != BPF_FUNC_tail_call)
4851 goto error;
4852 break;
4853 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4854 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004855 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004856 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004857 func_id != BPF_FUNC_perf_event_read_value &&
4858 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004859 goto error;
4860 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004861 case BPF_MAP_TYPE_RINGBUF:
4862 if (func_id != BPF_FUNC_ringbuf_output &&
4863 func_id != BPF_FUNC_ringbuf_reserve &&
4864 func_id != BPF_FUNC_ringbuf_submit &&
4865 func_id != BPF_FUNC_ringbuf_discard &&
4866 func_id != BPF_FUNC_ringbuf_query)
4867 goto error;
4868 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004869 case BPF_MAP_TYPE_STACK_TRACE:
4870 if (func_id != BPF_FUNC_get_stackid)
4871 goto error;
4872 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004873 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004874 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004875 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004876 goto error;
4877 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004878 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004879 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004880 if (func_id != BPF_FUNC_get_local_storage)
4881 goto error;
4882 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004883 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004884 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004885 if (func_id != BPF_FUNC_redirect_map &&
4886 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004887 goto error;
4888 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004889 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4890 * appear.
4891 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004892 case BPF_MAP_TYPE_CPUMAP:
4893 if (func_id != BPF_FUNC_redirect_map)
4894 goto error;
4895 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004896 case BPF_MAP_TYPE_XSKMAP:
4897 if (func_id != BPF_FUNC_redirect_map &&
4898 func_id != BPF_FUNC_map_lookup_elem)
4899 goto error;
4900 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004901 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004902 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004903 if (func_id != BPF_FUNC_map_lookup_elem)
4904 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004905 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004906 case BPF_MAP_TYPE_SOCKMAP:
4907 if (func_id != BPF_FUNC_sk_redirect_map &&
4908 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004909 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004910 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004911 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004912 func_id != BPF_FUNC_map_lookup_elem &&
4913 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004914 goto error;
4915 break;
John Fastabend81110382018-05-14 10:00:17 -07004916 case BPF_MAP_TYPE_SOCKHASH:
4917 if (func_id != BPF_FUNC_sk_redirect_hash &&
4918 func_id != BPF_FUNC_sock_hash_update &&
4919 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004920 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004921 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004922 func_id != BPF_FUNC_map_lookup_elem &&
4923 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004924 goto error;
4925 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004926 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4927 if (func_id != BPF_FUNC_sk_select_reuseport)
4928 goto error;
4929 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004930 case BPF_MAP_TYPE_QUEUE:
4931 case BPF_MAP_TYPE_STACK:
4932 if (func_id != BPF_FUNC_map_peek_elem &&
4933 func_id != BPF_FUNC_map_pop_elem &&
4934 func_id != BPF_FUNC_map_push_elem)
4935 goto error;
4936 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004937 case BPF_MAP_TYPE_SK_STORAGE:
4938 if (func_id != BPF_FUNC_sk_storage_get &&
4939 func_id != BPF_FUNC_sk_storage_delete)
4940 goto error;
4941 break;
KP Singh8ea63682020-08-25 20:29:17 +02004942 case BPF_MAP_TYPE_INODE_STORAGE:
4943 if (func_id != BPF_FUNC_inode_storage_get &&
4944 func_id != BPF_FUNC_inode_storage_delete)
4945 goto error;
4946 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00004947 case BPF_MAP_TYPE_TASK_STORAGE:
4948 if (func_id != BPF_FUNC_task_storage_get &&
4949 func_id != BPF_FUNC_task_storage_delete)
4950 goto error;
4951 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004952 default:
4953 break;
4954 }
4955
4956 /* ... and second from the function itself. */
4957 switch (func_id) {
4958 case BPF_FUNC_tail_call:
4959 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4960 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004961 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4962 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004963 return -EINVAL;
4964 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004965 break;
4966 case BPF_FUNC_perf_event_read:
4967 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07004968 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004969 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004970 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004971 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4972 goto error;
4973 break;
4974 case BPF_FUNC_get_stackid:
4975 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4976 goto error;
4977 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004978 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02004979 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004980 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4981 goto error;
4982 break;
John Fastabend97f91a72017-07-17 09:29:18 -07004983 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02004984 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004985 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004986 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4987 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07004988 goto error;
4989 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004990 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07004991 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07004992 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07004993 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4994 goto error;
4995 break;
John Fastabend81110382018-05-14 10:00:17 -07004996 case BPF_FUNC_sk_redirect_hash:
4997 case BPF_FUNC_msg_redirect_hash:
4998 case BPF_FUNC_sock_hash_update:
4999 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07005000 goto error;
5001 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005002 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00005003 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5004 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07005005 goto error;
5006 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005007 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005008 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5009 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5010 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005011 goto error;
5012 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005013 case BPF_FUNC_map_peek_elem:
5014 case BPF_FUNC_map_pop_elem:
5015 case BPF_FUNC_map_push_elem:
5016 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5017 map->map_type != BPF_MAP_TYPE_STACK)
5018 goto error;
5019 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005020 case BPF_FUNC_sk_storage_get:
5021 case BPF_FUNC_sk_storage_delete:
5022 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5023 goto error;
5024 break;
KP Singh8ea63682020-08-25 20:29:17 +02005025 case BPF_FUNC_inode_storage_get:
5026 case BPF_FUNC_inode_storage_delete:
5027 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5028 goto error;
5029 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005030 case BPF_FUNC_task_storage_get:
5031 case BPF_FUNC_task_storage_delete:
5032 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5033 goto error;
5034 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005035 default:
5036 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005037 }
5038
5039 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005040error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005041 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005042 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005043 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005044}
5045
Daniel Borkmann90133412018-01-20 01:24:29 +01005046static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005047{
5048 int count = 0;
5049
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005050 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005051 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005052 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005053 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005054 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005055 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005056 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005057 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005058 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005059 count++;
5060
Daniel Borkmann90133412018-01-20 01:24:29 +01005061 /* We only support one arg being in raw mode at the moment,
5062 * which is sufficient for the helper functions we have
5063 * right now.
5064 */
5065 return count <= 1;
5066}
5067
5068static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5069 enum bpf_arg_type arg_next)
5070{
5071 return (arg_type_is_mem_ptr(arg_curr) &&
5072 !arg_type_is_mem_size(arg_next)) ||
5073 (!arg_type_is_mem_ptr(arg_curr) &&
5074 arg_type_is_mem_size(arg_next));
5075}
5076
5077static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5078{
5079 /* bpf_xxx(..., buf, len) call will access 'len'
5080 * bytes from memory 'buf'. Both arg types need
5081 * to be paired, so make sure there's no buggy
5082 * helper function specification.
5083 */
5084 if (arg_type_is_mem_size(fn->arg1_type) ||
5085 arg_type_is_mem_ptr(fn->arg5_type) ||
5086 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5087 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5088 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5089 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5090 return false;
5091
5092 return true;
5093}
5094
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005095static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005096{
5097 int count = 0;
5098
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005099 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005100 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005101 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005102 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005103 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005104 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005105 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005106 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005107 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005108 count++;
5109
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005110 /* A reference acquiring function cannot acquire
5111 * another refcounted ptr.
5112 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005113 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005114 return false;
5115
Joe Stringerfd978bf72018-10-02 13:35:35 -07005116 /* We only support one arg being unreferenced at the moment,
5117 * which is sufficient for the helper functions we have right now.
5118 */
5119 return count <= 1;
5120}
5121
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005122static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5123{
5124 int i;
5125
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005126 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005127 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5128 return false;
5129
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005130 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5131 return false;
5132 }
5133
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005134 return true;
5135}
5136
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005137static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005138{
5139 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005140 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005141 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005142 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005143}
5144
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005145/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5146 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005147 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005148static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5149 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005150{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005151 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005152 int i;
5153
5154 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005155 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005156 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005157
Joe Stringerf3709f62018-10-02 13:35:29 -07005158 bpf_for_each_spilled_reg(i, state, reg) {
5159 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005160 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005161 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005162 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005163 }
5164}
5165
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005166static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5167{
5168 struct bpf_verifier_state *vstate = env->cur_state;
5169 int i;
5170
5171 for (i = 0; i <= vstate->curframe; i++)
5172 __clear_all_pkt_pointers(env, vstate->frame[i]);
5173}
5174
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005175enum {
5176 AT_PKT_END = -1,
5177 BEYOND_PKT_END = -2,
5178};
5179
5180static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5181{
5182 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5183 struct bpf_reg_state *reg = &state->regs[regn];
5184
5185 if (reg->type != PTR_TO_PACKET)
5186 /* PTR_TO_PACKET_META is not supported yet */
5187 return;
5188
5189 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5190 * How far beyond pkt_end it goes is unknown.
5191 * if (!range_open) it's the case of pkt >= pkt_end
5192 * if (range_open) it's the case of pkt > pkt_end
5193 * hence this pointer is at least 1 byte bigger than pkt_end
5194 */
5195 if (range_open)
5196 reg->range = BEYOND_PKT_END;
5197 else
5198 reg->range = AT_PKT_END;
5199}
5200
Joe Stringerfd978bf72018-10-02 13:35:35 -07005201static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005202 struct bpf_func_state *state,
5203 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005204{
5205 struct bpf_reg_state *regs = state->regs, *reg;
5206 int i;
5207
5208 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005209 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005210 mark_reg_unknown(env, regs, i);
5211
5212 bpf_for_each_spilled_reg(i, state, reg) {
5213 if (!reg)
5214 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005215 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005216 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005217 }
5218}
5219
5220/* The pointer with the specified id has released its reference to kernel
5221 * resources. Identify all copies of the same pointer and clear the reference.
5222 */
5223static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005224 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005225{
5226 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005227 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005228 int i;
5229
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005230 err = release_reference_state(cur_func(env), ref_obj_id);
5231 if (err)
5232 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005233
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005234 for (i = 0; i <= vstate->curframe; i++)
5235 release_reg_references(env, vstate->frame[i], ref_obj_id);
5236
5237 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005238}
5239
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005240static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5241 struct bpf_reg_state *regs)
5242{
5243 int i;
5244
5245 /* after the call registers r0 - r5 were scratched */
5246 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5247 mark_reg_not_init(env, regs, caller_saved[i]);
5248 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5249 }
5250}
5251
Yonghong Song14351372021-02-26 12:49:23 -08005252typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5253 struct bpf_func_state *caller,
5254 struct bpf_func_state *callee,
5255 int insn_idx);
5256
5257static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5258 int *insn_idx, int subprog,
5259 set_callee_state_fn set_callee_state_cb)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005260{
5261 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005262 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005263 struct bpf_func_state *caller, *callee;
Yonghong Song14351372021-02-26 12:49:23 -08005264 int err;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005265 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005266
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005267 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005268 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005269 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005270 return -E2BIG;
5271 }
5272
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005273 caller = state->frame[state->curframe];
5274 if (state->frame[state->curframe + 1]) {
5275 verbose(env, "verifier bug. Frame %d already allocated\n",
5276 state->curframe + 1);
5277 return -EFAULT;
5278 }
5279
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005280 func_info_aux = env->prog->aux->func_info_aux;
5281 if (func_info_aux)
5282 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5283 err = btf_check_func_arg_match(env, subprog, caller->regs);
5284 if (err == -EFAULT)
5285 return err;
5286 if (is_global) {
5287 if (err) {
5288 verbose(env, "Caller passes invalid args into func#%d\n",
5289 subprog);
5290 return err;
5291 } else {
5292 if (env->log.level & BPF_LOG_LEVEL)
5293 verbose(env,
5294 "Func#%d is global and valid. Skipping.\n",
5295 subprog);
5296 clear_caller_saved_regs(env, caller->regs);
5297
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005298 /* All global functions return a 64-bit SCALAR_VALUE */
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005299 mark_reg_unknown(env, caller->regs, BPF_REG_0);
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01005300 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005301
5302 /* continue with next insn after call */
5303 return 0;
5304 }
5305 }
5306
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005307 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5308 if (!callee)
5309 return -ENOMEM;
5310 state->frame[state->curframe + 1] = callee;
5311
5312 /* callee cannot access r0, r6 - r9 for reading and has to write
5313 * into its own stack before reading from it.
5314 * callee can read/write into caller's stack
5315 */
5316 init_func_state(env, callee,
5317 /* remember the callsite, it will be used by bpf_exit */
5318 *insn_idx /* callsite */,
5319 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04005320 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005321
Joe Stringerfd978bf72018-10-02 13:35:35 -07005322 /* Transfer references to the callee */
5323 err = transfer_reference_state(callee, caller);
5324 if (err)
5325 return err;
5326
Yonghong Song14351372021-02-26 12:49:23 -08005327 err = set_callee_state_cb(env, caller, callee, *insn_idx);
5328 if (err)
5329 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005330
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005331 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005332
5333 /* only increment it after check_reg_arg() finished */
5334 state->curframe++;
5335
5336 /* and go analyze first insn of the callee */
Yonghong Song14351372021-02-26 12:49:23 -08005337 *insn_idx = env->subprog_info[subprog].start - 1;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005338
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005339 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005340 verbose(env, "caller:\n");
5341 print_verifier_state(env, caller);
5342 verbose(env, "callee:\n");
5343 print_verifier_state(env, callee);
5344 }
5345 return 0;
5346}
5347
Yonghong Song14351372021-02-26 12:49:23 -08005348static int set_callee_state(struct bpf_verifier_env *env,
5349 struct bpf_func_state *caller,
5350 struct bpf_func_state *callee, int insn_idx)
5351{
5352 int i;
5353
5354 /* copy r1 - r5 args that callee can access. The copy includes parent
5355 * pointers, which connects us up to the liveness chain
5356 */
5357 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5358 callee->regs[i] = caller->regs[i];
5359 return 0;
5360}
5361
5362static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5363 int *insn_idx)
5364{
5365 int subprog, target_insn;
5366
5367 target_insn = *insn_idx + insn->imm + 1;
5368 subprog = find_subprog(env, target_insn);
5369 if (subprog < 0) {
5370 verbose(env, "verifier bug. No program starts at insn %d\n",
5371 target_insn);
5372 return -EFAULT;
5373 }
5374
5375 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
5376}
5377
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005378static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5379{
5380 struct bpf_verifier_state *state = env->cur_state;
5381 struct bpf_func_state *caller, *callee;
5382 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005383 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005384
5385 callee = state->frame[state->curframe];
5386 r0 = &callee->regs[BPF_REG_0];
5387 if (r0->type == PTR_TO_STACK) {
5388 /* technically it's ok to return caller's stack pointer
5389 * (or caller's caller's pointer) back to the caller,
5390 * since these pointers are valid. Only current stack
5391 * pointer will be invalid as soon as function exits,
5392 * but let's be conservative
5393 */
5394 verbose(env, "cannot return stack pointer to the caller\n");
5395 return -EINVAL;
5396 }
5397
5398 state->curframe--;
5399 caller = state->frame[state->curframe];
5400 /* return to the caller whatever r0 had in the callee */
5401 caller->regs[BPF_REG_0] = *r0;
5402
Joe Stringerfd978bf72018-10-02 13:35:35 -07005403 /* Transfer references to the caller */
5404 err = transfer_reference_state(caller, callee);
5405 if (err)
5406 return err;
5407
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005408 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005409 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005410 verbose(env, "returning from callee:\n");
5411 print_verifier_state(env, callee);
5412 verbose(env, "to caller at %d:\n", *insn_idx);
5413 print_verifier_state(env, caller);
5414 }
5415 /* clear everything in the callee */
5416 free_func_state(callee);
5417 state->frame[state->curframe + 1] = NULL;
5418 return 0;
5419}
5420
Yonghong Song849fa502018-04-28 22:28:09 -07005421static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5422 int func_id,
5423 struct bpf_call_arg_meta *meta)
5424{
5425 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5426
5427 if (ret_type != RET_INTEGER ||
5428 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02005429 func_id != BPF_FUNC_probe_read_str &&
5430 func_id != BPF_FUNC_probe_read_kernel_str &&
5431 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07005432 return;
5433
John Fastabend10060502020-03-30 14:36:19 -07005434 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07005435 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01005436 ret_reg->smin_value = -MAX_ERRNO;
5437 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07005438 __reg_deduce_bounds(ret_reg);
5439 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07005440 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07005441}
5442
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005443static int
5444record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5445 int func_id, int insn_idx)
5446{
5447 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02005448 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005449
5450 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02005451 func_id != BPF_FUNC_map_lookup_elem &&
5452 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005453 func_id != BPF_FUNC_map_delete_elem &&
5454 func_id != BPF_FUNC_map_push_elem &&
5455 func_id != BPF_FUNC_map_pop_elem &&
5456 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005457 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02005458
Daniel Borkmann591fe982019-04-09 23:20:05 +02005459 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005460 verbose(env, "kernel subsystem misconfigured verifier\n");
5461 return -EINVAL;
5462 }
5463
Daniel Borkmann591fe982019-04-09 23:20:05 +02005464 /* In case of read-only, some additional restrictions
5465 * need to be applied in order to prevent altering the
5466 * state of the map from program side.
5467 */
5468 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5469 (func_id == BPF_FUNC_map_delete_elem ||
5470 func_id == BPF_FUNC_map_update_elem ||
5471 func_id == BPF_FUNC_map_push_elem ||
5472 func_id == BPF_FUNC_map_pop_elem)) {
5473 verbose(env, "write into map forbidden\n");
5474 return -EACCES;
5475 }
5476
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005477 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005478 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005479 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005480 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005481 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005482 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005483 return 0;
5484}
5485
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005486static int
5487record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5488 int func_id, int insn_idx)
5489{
5490 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5491 struct bpf_reg_state *regs = cur_regs(env), *reg;
5492 struct bpf_map *map = meta->map_ptr;
5493 struct tnum range;
5494 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005495 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005496
5497 if (func_id != BPF_FUNC_tail_call)
5498 return 0;
5499 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5500 verbose(env, "kernel subsystem misconfigured verifier\n");
5501 return -EINVAL;
5502 }
5503
5504 range = tnum_range(0, map->max_entries - 1);
5505 reg = &regs[BPF_REG_3];
5506
5507 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5508 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5509 return 0;
5510 }
5511
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005512 err = mark_chain_precision(env, BPF_REG_3);
5513 if (err)
5514 return err;
5515
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005516 val = reg->var_off.value;
5517 if (bpf_map_key_unseen(aux))
5518 bpf_map_key_store(aux, val);
5519 else if (!bpf_map_key_poisoned(aux) &&
5520 bpf_map_key_immediate(aux) != val)
5521 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5522 return 0;
5523}
5524
Joe Stringerfd978bf72018-10-02 13:35:35 -07005525static int check_reference_leak(struct bpf_verifier_env *env)
5526{
5527 struct bpf_func_state *state = cur_func(env);
5528 int i;
5529
5530 for (i = 0; i < state->acquired_refs; i++) {
5531 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5532 state->refs[i].id, state->refs[i].insn_idx);
5533 }
5534 return state->acquired_refs ? -EINVAL : 0;
5535}
5536
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005537static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005538{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005539 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005540 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005541 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005542 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005543 int i, err;
5544
5545 /* find function prototype */
5546 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005547 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5548 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005549 return -EINVAL;
5550 }
5551
Jakub Kicinski00176a32017-10-16 16:40:54 -07005552 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07005553 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005554 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005555 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5556 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005557 return -EINVAL;
5558 }
5559
5560 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01005561 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02005562 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005563 return -EINVAL;
5564 }
5565
Jiri Olsaeae2e832020-08-25 21:21:19 +02005566 if (fn->allowed && !fn->allowed(env->prog)) {
5567 verbose(env, "helper call is not allowed in probe\n");
5568 return -EINVAL;
5569 }
5570
Daniel Borkmann04514d12017-12-14 21:07:25 +01005571 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08005572 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01005573 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5574 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5575 func_id_name(func_id), func_id);
5576 return -EINVAL;
5577 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005578
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005579 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02005580 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005581
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005582 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005583 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005584 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005585 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005586 return err;
5587 }
5588
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08005589 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005590 /* check args */
Dmitrii Banshchikov523a4cf2021-02-26 00:26:29 +04005591 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005592 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005593 if (err)
5594 return err;
5595 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005596
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005597 err = record_func_map(env, &meta, func_id, insn_idx);
5598 if (err)
5599 return err;
5600
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005601 err = record_func_key(env, &meta, func_id, insn_idx);
5602 if (err)
5603 return err;
5604
Daniel Borkmann435faee12016-04-13 00:10:51 +02005605 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5606 * is inferred from register state.
5607 */
5608 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01005609 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5610 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005611 if (err)
5612 return err;
5613 }
5614
Joe Stringerfd978bf72018-10-02 13:35:35 -07005615 if (func_id == BPF_FUNC_tail_call) {
5616 err = check_reference_leak(env);
5617 if (err) {
5618 verbose(env, "tail_call would lead to reference leak\n");
5619 return err;
5620 }
5621 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005622 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005623 if (err) {
5624 verbose(env, "func %s#%d reference has not been acquired before\n",
5625 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005626 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005627 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07005628 }
5629
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005630 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07005631
5632 /* check that flags argument in get_local_storage(map, flags) is 0,
5633 * this is required because get_local_storage() can't return an error.
5634 */
5635 if (func_id == BPF_FUNC_get_local_storage &&
5636 !register_is_null(&regs[BPF_REG_2])) {
5637 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5638 return -EINVAL;
5639 }
5640
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005641 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01005642 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005643 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01005644 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5645 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005646
Jiong Wang5327ed32019-05-24 23:25:12 +01005647 /* helper call returns 64-bit value. */
5648 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5649
Edward Creedc503a82017-08-15 20:34:35 +01005650 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005651 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01005652 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005653 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005654 } else if (fn->ret_type == RET_VOID) {
5655 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07005656 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5657 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01005658 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005659 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005660 /* remember map_ptr, so that check_map_access()
5661 * can check 'value_size' boundary of memory access
5662 * to map element returned from bpf_map_lookup_elem()
5663 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005664 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005665 verbose(env,
5666 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005667 return -EINVAL;
5668 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005669 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005670 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5671 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08005672 if (map_value_has_spin_lock(meta.map_ptr))
5673 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005674 } else {
5675 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005676 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005677 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5678 mark_reg_known_zero(env, regs, BPF_REG_0);
5679 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08005680 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5681 mark_reg_known_zero(env, regs, BPF_REG_0);
5682 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005683 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5684 mark_reg_known_zero(env, regs, BPF_REG_0);
5685 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005686 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5687 mark_reg_known_zero(env, regs, BPF_REG_0);
5688 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005689 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07005690 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5691 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005692 const struct btf_type *t;
5693
5694 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005695 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005696 if (!btf_type_is_struct(t)) {
5697 u32 tsize;
5698 const struct btf_type *ret;
5699 const char *tname;
5700
5701 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005702 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005703 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005704 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005705 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5706 tname, PTR_ERR(ret));
5707 return -EINVAL;
5708 }
Hao Luo63d9b802020-09-29 16:50:48 -07005709 regs[BPF_REG_0].type =
5710 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5711 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005712 regs[BPF_REG_0].mem_size = tsize;
5713 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07005714 regs[BPF_REG_0].type =
5715 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5716 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005717 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005718 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5719 }
KP Singh3ca10322020-11-06 10:37:43 +00005720 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5721 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005722 int ret_btf_id;
5723
5724 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00005725 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5726 PTR_TO_BTF_ID :
5727 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005728 ret_btf_id = *fn->ret_btf_id;
5729 if (ret_btf_id == 0) {
5730 verbose(env, "invalid return type %d of func %s#%d\n",
5731 fn->ret_type, func_id_name(func_id), func_id);
5732 return -EINVAL;
5733 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005734 /* current BPF helper definitions are only coming from
5735 * built-in code with type IDs from vmlinux BTF
5736 */
5737 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005738 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005739 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005740 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005741 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005742 return -EINVAL;
5743 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005744
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07005745 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5746 regs[BPF_REG_0].id = ++env->id_gen;
5747
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005748 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005749 /* For release_reference() */
5750 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005751 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005752 int id = acquire_reference_state(env, insn_idx);
5753
5754 if (id < 0)
5755 return id;
5756 /* For mark_ptr_or_null_reg() */
5757 regs[BPF_REG_0].id = id;
5758 /* For release_reference() */
5759 regs[BPF_REG_0].ref_obj_id = id;
5760 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005761
Yonghong Song849fa502018-04-28 22:28:09 -07005762 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5763
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005764 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005765 if (err)
5766 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005767
Song Liufa28dcb2020-06-29 23:28:44 -07005768 if ((func_id == BPF_FUNC_get_stack ||
5769 func_id == BPF_FUNC_get_task_stack) &&
5770 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005771 const char *err_str;
5772
5773#ifdef CONFIG_PERF_EVENTS
5774 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5775 err_str = "cannot get callchain buffer for func %s#%d\n";
5776#else
5777 err = -ENOTSUPP;
5778 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5779#endif
5780 if (err) {
5781 verbose(env, err_str, func_id_name(func_id), func_id);
5782 return err;
5783 }
5784
5785 env->prog->has_callchain_buf = true;
5786 }
5787
Song Liu5d99cb2c2020-07-23 11:06:45 -07005788 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5789 env->prog->call_get_stack = true;
5790
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005791 if (changes_data)
5792 clear_all_pkt_pointers(env);
5793 return 0;
5794}
5795
Edward Creeb03c9f92017-08-07 15:26:36 +01005796static bool signed_add_overflows(s64 a, s64 b)
5797{
5798 /* Do the add in u64, where overflow is well-defined */
5799 s64 res = (s64)((u64)a + (u64)b);
5800
5801 if (b < 0)
5802 return res > a;
5803 return res < a;
5804}
5805
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005806static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07005807{
5808 /* Do the add in u32, where overflow is well-defined */
5809 s32 res = (s32)((u32)a + (u32)b);
5810
5811 if (b < 0)
5812 return res > a;
5813 return res < a;
5814}
5815
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005816static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005817{
5818 /* Do the sub in u64, where overflow is well-defined */
5819 s64 res = (s64)((u64)a - (u64)b);
5820
5821 if (b < 0)
5822 return res < a;
5823 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005824}
5825
John Fastabend3f50f132020-03-30 14:36:39 -07005826static bool signed_sub32_overflows(s32 a, s32 b)
5827{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005828 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07005829 s32 res = (s32)((u32)a - (u32)b);
5830
5831 if (b < 0)
5832 return res < a;
5833 return res > a;
5834}
5835
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005836static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5837 const struct bpf_reg_state *reg,
5838 enum bpf_reg_type type)
5839{
5840 bool known = tnum_is_const(reg->var_off);
5841 s64 val = reg->var_off.value;
5842 s64 smin = reg->smin_value;
5843
5844 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5845 verbose(env, "math between %s pointer and %lld is not allowed\n",
5846 reg_type_str[type], val);
5847 return false;
5848 }
5849
5850 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5851 verbose(env, "%s pointer offset %d is not allowed\n",
5852 reg_type_str[type], reg->off);
5853 return false;
5854 }
5855
5856 if (smin == S64_MIN) {
5857 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5858 reg_type_str[type]);
5859 return false;
5860 }
5861
5862 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5863 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5864 smin, reg_type_str[type]);
5865 return false;
5866 }
5867
5868 return true;
5869}
5870
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005871static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5872{
5873 return &env->insn_aux_data[env->insn_idx];
5874}
5875
5876static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5877 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5878{
5879 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5880 (opcode == BPF_SUB && !off_is_neg);
5881 u32 off;
5882
5883 switch (ptr_reg->type) {
5884 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005885 /* Indirect variable offset stack access is prohibited in
5886 * unprivileged mode so it's not handled here.
5887 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005888 off = ptr_reg->off + ptr_reg->var_off.value;
5889 if (mask_to_left)
5890 *ptr_limit = MAX_BPF_STACK + off;
5891 else
5892 *ptr_limit = -off;
5893 return 0;
5894 case PTR_TO_MAP_VALUE:
5895 if (mask_to_left) {
5896 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5897 } else {
5898 off = ptr_reg->smin_value + ptr_reg->off;
5899 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5900 }
5901 return 0;
5902 default:
5903 return -EINVAL;
5904 }
5905}
5906
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005907static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5908 const struct bpf_insn *insn)
5909{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005910 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005911}
5912
5913static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5914 u32 alu_state, u32 alu_limit)
5915{
5916 /* If we arrived here from different branches with different
5917 * state or limits to sanitize, then this won't work.
5918 */
5919 if (aux->alu_state &&
5920 (aux->alu_state != alu_state ||
5921 aux->alu_limit != alu_limit))
5922 return -EACCES;
5923
Brendan Jackmane6ac5932021-02-17 10:45:09 +00005924 /* Corresponding fixup done in do_misc_fixups(). */
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005925 aux->alu_state = alu_state;
5926 aux->alu_limit = alu_limit;
5927 return 0;
5928}
5929
5930static int sanitize_val_alu(struct bpf_verifier_env *env,
5931 struct bpf_insn *insn)
5932{
5933 struct bpf_insn_aux_data *aux = cur_aux(env);
5934
5935 if (can_skip_alu_sanitation(env, insn))
5936 return 0;
5937
5938 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5939}
5940
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005941static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5942 struct bpf_insn *insn,
5943 const struct bpf_reg_state *ptr_reg,
5944 struct bpf_reg_state *dst_reg,
5945 bool off_is_neg)
5946{
5947 struct bpf_verifier_state *vstate = env->cur_state;
5948 struct bpf_insn_aux_data *aux = cur_aux(env);
5949 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5950 u8 opcode = BPF_OP(insn->code);
5951 u32 alu_state, alu_limit;
5952 struct bpf_reg_state tmp;
5953 bool ret;
5954
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005955 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005956 return 0;
5957
5958 /* We already marked aux for masking from non-speculative
5959 * paths, thus we got here in the first place. We only care
5960 * to explore bad access from here.
5961 */
5962 if (vstate->speculative)
5963 goto do_sim;
5964
5965 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5966 alu_state |= ptr_is_dst_reg ?
5967 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5968
5969 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5970 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005971 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005972 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005973do_sim:
5974 /* Simulate and find potential out-of-bounds access under
5975 * speculative execution from truncation as a result of
5976 * masking when off was not within expected range. If off
5977 * sits in dst, then we temporarily need to move ptr there
5978 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5979 * for cases where we use K-based arithmetic in one direction
5980 * and truncated reg-based in the other in order to explore
5981 * bad access.
5982 */
5983 if (!ptr_is_dst_reg) {
5984 tmp = *dst_reg;
5985 *dst_reg = *ptr_reg;
5986 }
5987 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08005988 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005989 *dst_reg = tmp;
5990 return !ret ? -EFAULT : 0;
5991}
5992
Andrei Matei01f810a2021-02-06 20:10:24 -05005993/* check that stack access falls within stack limits and that 'reg' doesn't
5994 * have a variable offset.
5995 *
5996 * Variable offset is prohibited for unprivileged mode for simplicity since it
5997 * requires corresponding support in Spectre masking for stack ALU. See also
5998 * retrieve_ptr_limit().
5999 *
6000 *
6001 * 'off' includes 'reg->off'.
6002 */
6003static int check_stack_access_for_ptr_arithmetic(
6004 struct bpf_verifier_env *env,
6005 int regno,
6006 const struct bpf_reg_state *reg,
6007 int off)
6008{
6009 if (!tnum_is_const(reg->var_off)) {
6010 char tn_buf[48];
6011
6012 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6013 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
6014 regno, tn_buf, off);
6015 return -EACCES;
6016 }
6017
6018 if (off >= 0 || off < -MAX_BPF_STACK) {
6019 verbose(env, "R%d stack pointer arithmetic goes out of range, "
6020 "prohibited for !root; off=%d\n", regno, off);
6021 return -EACCES;
6022 }
6023
6024 return 0;
6025}
6026
6027
Edward Creef1174f72017-08-07 15:26:19 +01006028/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01006029 * Caller should also handle BPF_MOV case separately.
6030 * If we return -EACCES, caller may want to try again treating pointer as a
6031 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
6032 */
6033static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
6034 struct bpf_insn *insn,
6035 const struct bpf_reg_state *ptr_reg,
6036 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04006037{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006038 struct bpf_verifier_state *vstate = env->cur_state;
6039 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6040 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006041 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01006042 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
6043 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
6044 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6045 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006046 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04006047 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006048 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04006049
Edward Creef1174f72017-08-07 15:26:19 +01006050 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04006051
Daniel Borkmann6f161012018-01-18 01:15:21 +01006052 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6053 smin_val > smax_val || umin_val > umax_val) {
6054 /* Taint dst register if offset had invalid bounds derived from
6055 * e.g. dead branches.
6056 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006057 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01006058 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04006059 }
6060
Edward Creef1174f72017-08-07 15:26:19 +01006061 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6062 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07006063 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6064 __mark_reg_unknown(env, dst_reg);
6065 return 0;
6066 }
6067
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006068 verbose(env,
6069 "R%d 32-bit pointer arithmetic prohibited\n",
6070 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006071 return -EACCES;
6072 }
David S. Millerd1174412017-05-10 11:22:52 -07006073
Joe Stringeraad2eea2018-10-02 13:35:30 -07006074 switch (ptr_reg->type) {
6075 case PTR_TO_MAP_VALUE_OR_NULL:
6076 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6077 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006078 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006079 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07006080 /* smin_val represents the known value */
6081 if (known && smin_val == 0 && opcode == BPF_ADD)
6082 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05006083 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006084 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07006085 case PTR_TO_SOCKET:
6086 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006087 case PTR_TO_SOCK_COMMON:
6088 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006089 case PTR_TO_TCP_SOCK:
6090 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07006091 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07006092 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6093 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006094 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006095 case PTR_TO_MAP_VALUE:
6096 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6097 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6098 off_reg == dst_reg ? dst : src);
6099 return -EACCES;
6100 }
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05006101 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006102 default:
6103 break;
Edward Creef1174f72017-08-07 15:26:19 +01006104 }
6105
6106 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6107 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04006108 */
Edward Creef1174f72017-08-07 15:26:19 +01006109 dst_reg->type = ptr_reg->type;
6110 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05006111
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006112 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6113 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6114 return -EINVAL;
6115
John Fastabend3f50f132020-03-30 14:36:39 -07006116 /* pointer types do not carry 32-bit bounds at the moment. */
6117 __mark_reg32_unbounded(dst_reg);
6118
Josef Bacik48461132016-09-28 10:54:32 -04006119 switch (opcode) {
6120 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006121 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6122 if (ret < 0) {
6123 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6124 return ret;
6125 }
Edward Creef1174f72017-08-07 15:26:19 +01006126 /* We can take a fixed offset as long as it doesn't overflow
6127 * the s32 'off' field
6128 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006129 if (known && (ptr_reg->off + smin_val ==
6130 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006131 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006132 dst_reg->smin_value = smin_ptr;
6133 dst_reg->smax_value = smax_ptr;
6134 dst_reg->umin_value = umin_ptr;
6135 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006136 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01006137 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006138 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006139 break;
6140 }
Edward Creef1174f72017-08-07 15:26:19 +01006141 /* A new variable offset is created. Note that off_reg->off
6142 * == 0, since it's a scalar.
6143 * dst_reg gets the pointer type and since some positive
6144 * integer value was added to the pointer, give it a new 'id'
6145 * if it's a PTR_TO_PACKET.
6146 * this creates a new 'base' pointer, off_reg (variable) gets
6147 * added into the variable offset, and we copy the fixed offset
6148 * from ptr_reg.
6149 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006150 if (signed_add_overflows(smin_ptr, smin_val) ||
6151 signed_add_overflows(smax_ptr, smax_val)) {
6152 dst_reg->smin_value = S64_MIN;
6153 dst_reg->smax_value = S64_MAX;
6154 } else {
6155 dst_reg->smin_value = smin_ptr + smin_val;
6156 dst_reg->smax_value = smax_ptr + smax_val;
6157 }
6158 if (umin_ptr + umin_val < umin_ptr ||
6159 umax_ptr + umax_val < umax_ptr) {
6160 dst_reg->umin_value = 0;
6161 dst_reg->umax_value = U64_MAX;
6162 } else {
6163 dst_reg->umin_value = umin_ptr + umin_val;
6164 dst_reg->umax_value = umax_ptr + umax_val;
6165 }
Edward Creef1174f72017-08-07 15:26:19 +01006166 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6167 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006168 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006169 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006170 dst_reg->id = ++env->id_gen;
6171 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006172 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006173 }
Josef Bacik48461132016-09-28 10:54:32 -04006174 break;
6175 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006176 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6177 if (ret < 0) {
6178 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6179 return ret;
6180 }
Edward Creef1174f72017-08-07 15:26:19 +01006181 if (dst_reg == off_reg) {
6182 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006183 verbose(env, "R%d tried to subtract pointer from scalar\n",
6184 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006185 return -EACCES;
6186 }
6187 /* We don't allow subtraction from FP, because (according to
6188 * test_verifier.c test "invalid fp arithmetic", JITs might not
6189 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01006190 */
Edward Creef1174f72017-08-07 15:26:19 +01006191 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006192 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6193 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006194 return -EACCES;
6195 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006196 if (known && (ptr_reg->off - smin_val ==
6197 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006198 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006199 dst_reg->smin_value = smin_ptr;
6200 dst_reg->smax_value = smax_ptr;
6201 dst_reg->umin_value = umin_ptr;
6202 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006203 dst_reg->var_off = ptr_reg->var_off;
6204 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01006205 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006206 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006207 break;
6208 }
Edward Creef1174f72017-08-07 15:26:19 +01006209 /* A new variable offset is created. If the subtrahend is known
6210 * nonnegative, then any reg->range we had before is still good.
6211 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006212 if (signed_sub_overflows(smin_ptr, smax_val) ||
6213 signed_sub_overflows(smax_ptr, smin_val)) {
6214 /* Overflow possible, we know nothing */
6215 dst_reg->smin_value = S64_MIN;
6216 dst_reg->smax_value = S64_MAX;
6217 } else {
6218 dst_reg->smin_value = smin_ptr - smax_val;
6219 dst_reg->smax_value = smax_ptr - smin_val;
6220 }
6221 if (umin_ptr < umax_val) {
6222 /* Overflow possible, we know nothing */
6223 dst_reg->umin_value = 0;
6224 dst_reg->umax_value = U64_MAX;
6225 } else {
6226 /* Cannot overflow (as long as bounds are consistent) */
6227 dst_reg->umin_value = umin_ptr - umax_val;
6228 dst_reg->umax_value = umax_ptr - umin_val;
6229 }
Edward Creef1174f72017-08-07 15:26:19 +01006230 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6231 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006232 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006233 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006234 dst_reg->id = ++env->id_gen;
6235 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01006236 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006237 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006238 }
6239 break;
6240 case BPF_AND:
6241 case BPF_OR:
6242 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006243 /* bitwise ops on pointers are troublesome, prohibit. */
6244 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6245 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006246 return -EACCES;
6247 default:
6248 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006249 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6250 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006251 return -EACCES;
6252 }
6253
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006254 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6255 return -EINVAL;
6256
Edward Creeb03c9f92017-08-07 15:26:36 +01006257 __update_reg_bounds(dst_reg);
6258 __reg_deduce_bounds(dst_reg);
6259 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006260
6261 /* For unprivileged we require that resulting offset must be in bounds
6262 * in order to be able to sanitize access later on.
6263 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006264 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006265 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6266 check_map_access(env, dst, dst_reg->off, 1, false)) {
6267 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6268 "prohibited for !root\n", dst);
6269 return -EACCES;
6270 } else if (dst_reg->type == PTR_TO_STACK &&
Andrei Matei01f810a2021-02-06 20:10:24 -05006271 check_stack_access_for_ptr_arithmetic(
6272 env, dst, dst_reg, dst_reg->off +
6273 dst_reg->var_off.value)) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006274 return -EACCES;
6275 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006276 }
6277
Edward Creef1174f72017-08-07 15:26:19 +01006278 return 0;
6279}
6280
John Fastabend3f50f132020-03-30 14:36:39 -07006281static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6282 struct bpf_reg_state *src_reg)
6283{
6284 s32 smin_val = src_reg->s32_min_value;
6285 s32 smax_val = src_reg->s32_max_value;
6286 u32 umin_val = src_reg->u32_min_value;
6287 u32 umax_val = src_reg->u32_max_value;
6288
6289 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6290 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6291 dst_reg->s32_min_value = S32_MIN;
6292 dst_reg->s32_max_value = S32_MAX;
6293 } else {
6294 dst_reg->s32_min_value += smin_val;
6295 dst_reg->s32_max_value += smax_val;
6296 }
6297 if (dst_reg->u32_min_value + umin_val < umin_val ||
6298 dst_reg->u32_max_value + umax_val < umax_val) {
6299 dst_reg->u32_min_value = 0;
6300 dst_reg->u32_max_value = U32_MAX;
6301 } else {
6302 dst_reg->u32_min_value += umin_val;
6303 dst_reg->u32_max_value += umax_val;
6304 }
6305}
6306
John Fastabend07cd2632020-03-24 10:38:15 -07006307static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6308 struct bpf_reg_state *src_reg)
6309{
6310 s64 smin_val = src_reg->smin_value;
6311 s64 smax_val = src_reg->smax_value;
6312 u64 umin_val = src_reg->umin_value;
6313 u64 umax_val = src_reg->umax_value;
6314
6315 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6316 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6317 dst_reg->smin_value = S64_MIN;
6318 dst_reg->smax_value = S64_MAX;
6319 } else {
6320 dst_reg->smin_value += smin_val;
6321 dst_reg->smax_value += smax_val;
6322 }
6323 if (dst_reg->umin_value + umin_val < umin_val ||
6324 dst_reg->umax_value + umax_val < umax_val) {
6325 dst_reg->umin_value = 0;
6326 dst_reg->umax_value = U64_MAX;
6327 } else {
6328 dst_reg->umin_value += umin_val;
6329 dst_reg->umax_value += umax_val;
6330 }
John Fastabend3f50f132020-03-30 14:36:39 -07006331}
6332
6333static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6334 struct bpf_reg_state *src_reg)
6335{
6336 s32 smin_val = src_reg->s32_min_value;
6337 s32 smax_val = src_reg->s32_max_value;
6338 u32 umin_val = src_reg->u32_min_value;
6339 u32 umax_val = src_reg->u32_max_value;
6340
6341 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6342 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6343 /* Overflow possible, we know nothing */
6344 dst_reg->s32_min_value = S32_MIN;
6345 dst_reg->s32_max_value = S32_MAX;
6346 } else {
6347 dst_reg->s32_min_value -= smax_val;
6348 dst_reg->s32_max_value -= smin_val;
6349 }
6350 if (dst_reg->u32_min_value < umax_val) {
6351 /* Overflow possible, we know nothing */
6352 dst_reg->u32_min_value = 0;
6353 dst_reg->u32_max_value = U32_MAX;
6354 } else {
6355 /* Cannot overflow (as long as bounds are consistent) */
6356 dst_reg->u32_min_value -= umax_val;
6357 dst_reg->u32_max_value -= umin_val;
6358 }
John Fastabend07cd2632020-03-24 10:38:15 -07006359}
6360
6361static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6362 struct bpf_reg_state *src_reg)
6363{
6364 s64 smin_val = src_reg->smin_value;
6365 s64 smax_val = src_reg->smax_value;
6366 u64 umin_val = src_reg->umin_value;
6367 u64 umax_val = src_reg->umax_value;
6368
6369 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6370 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6371 /* Overflow possible, we know nothing */
6372 dst_reg->smin_value = S64_MIN;
6373 dst_reg->smax_value = S64_MAX;
6374 } else {
6375 dst_reg->smin_value -= smax_val;
6376 dst_reg->smax_value -= smin_val;
6377 }
6378 if (dst_reg->umin_value < umax_val) {
6379 /* Overflow possible, we know nothing */
6380 dst_reg->umin_value = 0;
6381 dst_reg->umax_value = U64_MAX;
6382 } else {
6383 /* Cannot overflow (as long as bounds are consistent) */
6384 dst_reg->umin_value -= umax_val;
6385 dst_reg->umax_value -= umin_val;
6386 }
John Fastabend3f50f132020-03-30 14:36:39 -07006387}
6388
6389static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6390 struct bpf_reg_state *src_reg)
6391{
6392 s32 smin_val = src_reg->s32_min_value;
6393 u32 umin_val = src_reg->u32_min_value;
6394 u32 umax_val = src_reg->u32_max_value;
6395
6396 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6397 /* Ain't nobody got time to multiply that sign */
6398 __mark_reg32_unbounded(dst_reg);
6399 return;
6400 }
6401 /* Both values are positive, so we can work with unsigned and
6402 * copy the result to signed (unless it exceeds S32_MAX).
6403 */
6404 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6405 /* Potential overflow, we know nothing */
6406 __mark_reg32_unbounded(dst_reg);
6407 return;
6408 }
6409 dst_reg->u32_min_value *= umin_val;
6410 dst_reg->u32_max_value *= umax_val;
6411 if (dst_reg->u32_max_value > S32_MAX) {
6412 /* Overflow possible, we know nothing */
6413 dst_reg->s32_min_value = S32_MIN;
6414 dst_reg->s32_max_value = S32_MAX;
6415 } else {
6416 dst_reg->s32_min_value = dst_reg->u32_min_value;
6417 dst_reg->s32_max_value = dst_reg->u32_max_value;
6418 }
John Fastabend07cd2632020-03-24 10:38:15 -07006419}
6420
6421static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6422 struct bpf_reg_state *src_reg)
6423{
6424 s64 smin_val = src_reg->smin_value;
6425 u64 umin_val = src_reg->umin_value;
6426 u64 umax_val = src_reg->umax_value;
6427
John Fastabend07cd2632020-03-24 10:38:15 -07006428 if (smin_val < 0 || dst_reg->smin_value < 0) {
6429 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07006430 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006431 return;
6432 }
6433 /* Both values are positive, so we can work with unsigned and
6434 * copy the result to signed (unless it exceeds S64_MAX).
6435 */
6436 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6437 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07006438 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006439 return;
6440 }
6441 dst_reg->umin_value *= umin_val;
6442 dst_reg->umax_value *= umax_val;
6443 if (dst_reg->umax_value > S64_MAX) {
6444 /* Overflow possible, we know nothing */
6445 dst_reg->smin_value = S64_MIN;
6446 dst_reg->smax_value = S64_MAX;
6447 } else {
6448 dst_reg->smin_value = dst_reg->umin_value;
6449 dst_reg->smax_value = dst_reg->umax_value;
6450 }
6451}
6452
John Fastabend3f50f132020-03-30 14:36:39 -07006453static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6454 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006455{
John Fastabend3f50f132020-03-30 14:36:39 -07006456 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6457 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6458 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6459 s32 smin_val = src_reg->s32_min_value;
6460 u32 umax_val = src_reg->u32_max_value;
6461
6462 /* Assuming scalar64_min_max_and will be called so its safe
6463 * to skip updating register for known 32-bit case.
6464 */
6465 if (src_known && dst_known)
6466 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006467
6468 /* We get our minimum from the var_off, since that's inherently
6469 * bitwise. Our maximum is the minimum of the operands' maxima.
6470 */
John Fastabend3f50f132020-03-30 14:36:39 -07006471 dst_reg->u32_min_value = var32_off.value;
6472 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6473 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6474 /* Lose signed bounds when ANDing negative numbers,
6475 * ain't nobody got time for that.
6476 */
6477 dst_reg->s32_min_value = S32_MIN;
6478 dst_reg->s32_max_value = S32_MAX;
6479 } else {
6480 /* ANDing two positives gives a positive, so safe to
6481 * cast result into s64.
6482 */
6483 dst_reg->s32_min_value = dst_reg->u32_min_value;
6484 dst_reg->s32_max_value = dst_reg->u32_max_value;
6485 }
6486
6487}
6488
6489static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6490 struct bpf_reg_state *src_reg)
6491{
6492 bool src_known = tnum_is_const(src_reg->var_off);
6493 bool dst_known = tnum_is_const(dst_reg->var_off);
6494 s64 smin_val = src_reg->smin_value;
6495 u64 umax_val = src_reg->umax_value;
6496
6497 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006498 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006499 return;
6500 }
6501
6502 /* We get our minimum from the var_off, since that's inherently
6503 * bitwise. Our maximum is the minimum of the operands' maxima.
6504 */
John Fastabend07cd2632020-03-24 10:38:15 -07006505 dst_reg->umin_value = dst_reg->var_off.value;
6506 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6507 if (dst_reg->smin_value < 0 || smin_val < 0) {
6508 /* Lose signed bounds when ANDing negative numbers,
6509 * ain't nobody got time for that.
6510 */
6511 dst_reg->smin_value = S64_MIN;
6512 dst_reg->smax_value = S64_MAX;
6513 } else {
6514 /* ANDing two positives gives a positive, so safe to
6515 * cast result into s64.
6516 */
6517 dst_reg->smin_value = dst_reg->umin_value;
6518 dst_reg->smax_value = dst_reg->umax_value;
6519 }
6520 /* We may learn something more from the var_off */
6521 __update_reg_bounds(dst_reg);
6522}
6523
John Fastabend3f50f132020-03-30 14:36:39 -07006524static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6525 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006526{
John Fastabend3f50f132020-03-30 14:36:39 -07006527 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6528 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6529 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006530 s32 smin_val = src_reg->s32_min_value;
6531 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006532
6533 /* Assuming scalar64_min_max_or will be called so it is safe
6534 * to skip updating register for known case.
6535 */
6536 if (src_known && dst_known)
6537 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006538
6539 /* We get our maximum from the var_off, and our minimum is the
6540 * maximum of the operands' minima
6541 */
John Fastabend3f50f132020-03-30 14:36:39 -07006542 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6543 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6544 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6545 /* Lose signed bounds when ORing negative numbers,
6546 * ain't nobody got time for that.
6547 */
6548 dst_reg->s32_min_value = S32_MIN;
6549 dst_reg->s32_max_value = S32_MAX;
6550 } else {
6551 /* ORing two positives gives a positive, so safe to
6552 * cast result into s64.
6553 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006554 dst_reg->s32_min_value = dst_reg->u32_min_value;
6555 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006556 }
6557}
6558
6559static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6560 struct bpf_reg_state *src_reg)
6561{
6562 bool src_known = tnum_is_const(src_reg->var_off);
6563 bool dst_known = tnum_is_const(dst_reg->var_off);
6564 s64 smin_val = src_reg->smin_value;
6565 u64 umin_val = src_reg->umin_value;
6566
6567 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006568 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006569 return;
6570 }
6571
6572 /* We get our maximum from the var_off, and our minimum is the
6573 * maximum of the operands' minima
6574 */
John Fastabend07cd2632020-03-24 10:38:15 -07006575 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6576 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6577 if (dst_reg->smin_value < 0 || smin_val < 0) {
6578 /* Lose signed bounds when ORing negative numbers,
6579 * ain't nobody got time for that.
6580 */
6581 dst_reg->smin_value = S64_MIN;
6582 dst_reg->smax_value = S64_MAX;
6583 } else {
6584 /* ORing two positives gives a positive, so safe to
6585 * cast result into s64.
6586 */
6587 dst_reg->smin_value = dst_reg->umin_value;
6588 dst_reg->smax_value = dst_reg->umax_value;
6589 }
6590 /* We may learn something more from the var_off */
6591 __update_reg_bounds(dst_reg);
6592}
6593
Yonghong Song2921c902020-08-24 23:46:08 -07006594static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6595 struct bpf_reg_state *src_reg)
6596{
6597 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6598 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6599 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6600 s32 smin_val = src_reg->s32_min_value;
6601
6602 /* Assuming scalar64_min_max_xor will be called so it is safe
6603 * to skip updating register for known case.
6604 */
6605 if (src_known && dst_known)
6606 return;
6607
6608 /* We get both minimum and maximum from the var32_off. */
6609 dst_reg->u32_min_value = var32_off.value;
6610 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6611
6612 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6613 /* XORing two positive sign numbers gives a positive,
6614 * so safe to cast u32 result into s32.
6615 */
6616 dst_reg->s32_min_value = dst_reg->u32_min_value;
6617 dst_reg->s32_max_value = dst_reg->u32_max_value;
6618 } else {
6619 dst_reg->s32_min_value = S32_MIN;
6620 dst_reg->s32_max_value = S32_MAX;
6621 }
6622}
6623
6624static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6625 struct bpf_reg_state *src_reg)
6626{
6627 bool src_known = tnum_is_const(src_reg->var_off);
6628 bool dst_known = tnum_is_const(dst_reg->var_off);
6629 s64 smin_val = src_reg->smin_value;
6630
6631 if (src_known && dst_known) {
6632 /* dst_reg->var_off.value has been updated earlier */
6633 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6634 return;
6635 }
6636
6637 /* We get both minimum and maximum from the var_off. */
6638 dst_reg->umin_value = dst_reg->var_off.value;
6639 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6640
6641 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6642 /* XORing two positive sign numbers gives a positive,
6643 * so safe to cast u64 result into s64.
6644 */
6645 dst_reg->smin_value = dst_reg->umin_value;
6646 dst_reg->smax_value = dst_reg->umax_value;
6647 } else {
6648 dst_reg->smin_value = S64_MIN;
6649 dst_reg->smax_value = S64_MAX;
6650 }
6651
6652 __update_reg_bounds(dst_reg);
6653}
6654
John Fastabend3f50f132020-03-30 14:36:39 -07006655static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6656 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07006657{
John Fastabend07cd2632020-03-24 10:38:15 -07006658 /* We lose all sign bit information (except what we can pick
6659 * up from var_off)
6660 */
John Fastabend3f50f132020-03-30 14:36:39 -07006661 dst_reg->s32_min_value = S32_MIN;
6662 dst_reg->s32_max_value = S32_MAX;
6663 /* If we might shift our top bit out, then we know nothing */
6664 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6665 dst_reg->u32_min_value = 0;
6666 dst_reg->u32_max_value = U32_MAX;
6667 } else {
6668 dst_reg->u32_min_value <<= umin_val;
6669 dst_reg->u32_max_value <<= umax_val;
6670 }
6671}
6672
6673static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6674 struct bpf_reg_state *src_reg)
6675{
6676 u32 umax_val = src_reg->u32_max_value;
6677 u32 umin_val = src_reg->u32_min_value;
6678 /* u32 alu operation will zext upper bits */
6679 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6680
6681 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6682 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6683 /* Not required but being careful mark reg64 bounds as unknown so
6684 * that we are forced to pick them up from tnum and zext later and
6685 * if some path skips this step we are still safe.
6686 */
6687 __mark_reg64_unbounded(dst_reg);
6688 __update_reg32_bounds(dst_reg);
6689}
6690
6691static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6692 u64 umin_val, u64 umax_val)
6693{
6694 /* Special case <<32 because it is a common compiler pattern to sign
6695 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6696 * positive we know this shift will also be positive so we can track
6697 * bounds correctly. Otherwise we lose all sign bit information except
6698 * what we can pick up from var_off. Perhaps we can generalize this
6699 * later to shifts of any length.
6700 */
6701 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6702 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6703 else
6704 dst_reg->smax_value = S64_MAX;
6705
6706 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6707 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6708 else
6709 dst_reg->smin_value = S64_MIN;
6710
John Fastabend07cd2632020-03-24 10:38:15 -07006711 /* If we might shift our top bit out, then we know nothing */
6712 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6713 dst_reg->umin_value = 0;
6714 dst_reg->umax_value = U64_MAX;
6715 } else {
6716 dst_reg->umin_value <<= umin_val;
6717 dst_reg->umax_value <<= umax_val;
6718 }
John Fastabend3f50f132020-03-30 14:36:39 -07006719}
6720
6721static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6722 struct bpf_reg_state *src_reg)
6723{
6724 u64 umax_val = src_reg->umax_value;
6725 u64 umin_val = src_reg->umin_value;
6726
6727 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6728 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6729 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6730
John Fastabend07cd2632020-03-24 10:38:15 -07006731 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6732 /* We may learn something more from the var_off */
6733 __update_reg_bounds(dst_reg);
6734}
6735
John Fastabend3f50f132020-03-30 14:36:39 -07006736static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6737 struct bpf_reg_state *src_reg)
6738{
6739 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6740 u32 umax_val = src_reg->u32_max_value;
6741 u32 umin_val = src_reg->u32_min_value;
6742
6743 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6744 * be negative, then either:
6745 * 1) src_reg might be zero, so the sign bit of the result is
6746 * unknown, so we lose our signed bounds
6747 * 2) it's known negative, thus the unsigned bounds capture the
6748 * signed bounds
6749 * 3) the signed bounds cross zero, so they tell us nothing
6750 * about the result
6751 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006752 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07006753 * Thus, in all cases it suffices to blow away our signed bounds
6754 * and rely on inferring new ones from the unsigned bounds and
6755 * var_off of the result.
6756 */
6757 dst_reg->s32_min_value = S32_MIN;
6758 dst_reg->s32_max_value = S32_MAX;
6759
6760 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6761 dst_reg->u32_min_value >>= umax_val;
6762 dst_reg->u32_max_value >>= umin_val;
6763
6764 __mark_reg64_unbounded(dst_reg);
6765 __update_reg32_bounds(dst_reg);
6766}
6767
John Fastabend07cd2632020-03-24 10:38:15 -07006768static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6769 struct bpf_reg_state *src_reg)
6770{
6771 u64 umax_val = src_reg->umax_value;
6772 u64 umin_val = src_reg->umin_value;
6773
6774 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6775 * be negative, then either:
6776 * 1) src_reg might be zero, so the sign bit of the result is
6777 * unknown, so we lose our signed bounds
6778 * 2) it's known negative, thus the unsigned bounds capture the
6779 * signed bounds
6780 * 3) the signed bounds cross zero, so they tell us nothing
6781 * about the result
6782 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006783 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07006784 * Thus, in all cases it suffices to blow away our signed bounds
6785 * and rely on inferring new ones from the unsigned bounds and
6786 * var_off of the result.
6787 */
6788 dst_reg->smin_value = S64_MIN;
6789 dst_reg->smax_value = S64_MAX;
6790 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6791 dst_reg->umin_value >>= umax_val;
6792 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006793
6794 /* Its not easy to operate on alu32 bounds here because it depends
6795 * on bits being shifted in. Take easy way out and mark unbounded
6796 * so we can recalculate later from tnum.
6797 */
6798 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006799 __update_reg_bounds(dst_reg);
6800}
6801
John Fastabend3f50f132020-03-30 14:36:39 -07006802static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6803 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006804{
John Fastabend3f50f132020-03-30 14:36:39 -07006805 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006806
6807 /* Upon reaching here, src_known is true and
6808 * umax_val is equal to umin_val.
6809 */
John Fastabend3f50f132020-03-30 14:36:39 -07006810 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6811 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006812
John Fastabend3f50f132020-03-30 14:36:39 -07006813 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6814
6815 /* blow away the dst_reg umin_value/umax_value and rely on
6816 * dst_reg var_off to refine the result.
6817 */
6818 dst_reg->u32_min_value = 0;
6819 dst_reg->u32_max_value = U32_MAX;
6820
6821 __mark_reg64_unbounded(dst_reg);
6822 __update_reg32_bounds(dst_reg);
6823}
6824
6825static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6826 struct bpf_reg_state *src_reg)
6827{
6828 u64 umin_val = src_reg->umin_value;
6829
6830 /* Upon reaching here, src_known is true and umax_val is equal
6831 * to umin_val.
6832 */
6833 dst_reg->smin_value >>= umin_val;
6834 dst_reg->smax_value >>= umin_val;
6835
6836 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006837
6838 /* blow away the dst_reg umin_value/umax_value and rely on
6839 * dst_reg var_off to refine the result.
6840 */
6841 dst_reg->umin_value = 0;
6842 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006843
6844 /* Its not easy to operate on alu32 bounds here because it depends
6845 * on bits being shifted in from upper 32-bits. Take easy way out
6846 * and mark unbounded so we can recalculate later from tnum.
6847 */
6848 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006849 __update_reg_bounds(dst_reg);
6850}
6851
Jann Horn468f6ea2017-12-18 20:11:56 -08006852/* WARNING: This function does calculations on 64-bit values, but the actual
6853 * execution may occur on 32-bit values. Therefore, things like bitshifts
6854 * need extra checks in the 32-bit case.
6855 */
Edward Creef1174f72017-08-07 15:26:19 +01006856static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6857 struct bpf_insn *insn,
6858 struct bpf_reg_state *dst_reg,
6859 struct bpf_reg_state src_reg)
6860{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006861 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006862 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006863 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006864 s64 smin_val, smax_val;
6865 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006866 s32 s32_min_val, s32_max_val;
6867 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006868 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006869 u32 dst = insn->dst_reg;
6870 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006871 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006872
Edward Creeb03c9f92017-08-07 15:26:36 +01006873 smin_val = src_reg.smin_value;
6874 smax_val = src_reg.smax_value;
6875 umin_val = src_reg.umin_value;
6876 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01006877
John Fastabend3f50f132020-03-30 14:36:39 -07006878 s32_min_val = src_reg.s32_min_value;
6879 s32_max_val = src_reg.s32_max_value;
6880 u32_min_val = src_reg.u32_min_value;
6881 u32_max_val = src_reg.u32_max_value;
6882
6883 if (alu32) {
6884 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006885 if ((src_known &&
6886 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6887 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6888 /* Taint dst register if offset had invalid bounds
6889 * derived from e.g. dead branches.
6890 */
6891 __mark_reg_unknown(env, dst_reg);
6892 return 0;
6893 }
6894 } else {
6895 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006896 if ((src_known &&
6897 (smin_val != smax_val || umin_val != umax_val)) ||
6898 smin_val > smax_val || umin_val > umax_val) {
6899 /* Taint dst register if offset had invalid bounds
6900 * derived from e.g. dead branches.
6901 */
6902 __mark_reg_unknown(env, dst_reg);
6903 return 0;
6904 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01006905 }
6906
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006907 if (!src_known &&
6908 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006909 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006910 return 0;
6911 }
6912
John Fastabend3f50f132020-03-30 14:36:39 -07006913 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6914 * There are two classes of instructions: The first class we track both
6915 * alu32 and alu64 sign/unsigned bounds independently this provides the
6916 * greatest amount of precision when alu operations are mixed with jmp32
6917 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6918 * and BPF_OR. This is possible because these ops have fairly easy to
6919 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6920 * See alu32 verifier tests for examples. The second class of
6921 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6922 * with regards to tracking sign/unsigned bounds because the bits may
6923 * cross subreg boundaries in the alu64 case. When this happens we mark
6924 * the reg unbounded in the subreg bound space and use the resulting
6925 * tnum to calculate an approximation of the sign/unsigned bounds.
6926 */
Edward Creef1174f72017-08-07 15:26:19 +01006927 switch (opcode) {
6928 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006929 ret = sanitize_val_alu(env, insn);
6930 if (ret < 0) {
6931 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6932 return ret;
6933 }
John Fastabend3f50f132020-03-30 14:36:39 -07006934 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006935 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006936 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01006937 break;
6938 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006939 ret = sanitize_val_alu(env, insn);
6940 if (ret < 0) {
6941 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6942 return ret;
6943 }
John Fastabend3f50f132020-03-30 14:36:39 -07006944 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006945 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006946 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04006947 break;
6948 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07006949 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6950 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006951 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006952 break;
6953 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07006954 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6955 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006956 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006957 break;
6958 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07006959 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6960 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006961 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006962 break;
Yonghong Song2921c902020-08-24 23:46:08 -07006963 case BPF_XOR:
6964 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6965 scalar32_min_max_xor(dst_reg, &src_reg);
6966 scalar_min_max_xor(dst_reg, &src_reg);
6967 break;
Josef Bacik48461132016-09-28 10:54:32 -04006968 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006969 if (umax_val >= insn_bitness) {
6970 /* Shifts greater than 31 or 63 are undefined.
6971 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006972 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006973 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006974 break;
6975 }
John Fastabend3f50f132020-03-30 14:36:39 -07006976 if (alu32)
6977 scalar32_min_max_lsh(dst_reg, &src_reg);
6978 else
6979 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006980 break;
6981 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006982 if (umax_val >= insn_bitness) {
6983 /* Shifts greater than 31 or 63 are undefined.
6984 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006985 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006986 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006987 break;
6988 }
John Fastabend3f50f132020-03-30 14:36:39 -07006989 if (alu32)
6990 scalar32_min_max_rsh(dst_reg, &src_reg);
6991 else
6992 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006993 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006994 case BPF_ARSH:
6995 if (umax_val >= insn_bitness) {
6996 /* Shifts greater than 31 or 63 are undefined.
6997 * This includes shifts by a negative number.
6998 */
6999 mark_reg_unknown(env, regs, insn->dst_reg);
7000 break;
7001 }
John Fastabend3f50f132020-03-30 14:36:39 -07007002 if (alu32)
7003 scalar32_min_max_arsh(dst_reg, &src_reg);
7004 else
7005 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07007006 break;
Josef Bacik48461132016-09-28 10:54:32 -04007007 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007008 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007009 break;
7010 }
7011
John Fastabend3f50f132020-03-30 14:36:39 -07007012 /* ALU32 ops are zero extended into 64bit register */
7013 if (alu32)
7014 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08007015
John Fastabend294f2fc2020-03-24 10:38:37 -07007016 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01007017 __reg_deduce_bounds(dst_reg);
7018 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007019 return 0;
7020}
7021
7022/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
7023 * and var_off.
7024 */
7025static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
7026 struct bpf_insn *insn)
7027{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007028 struct bpf_verifier_state *vstate = env->cur_state;
7029 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7030 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01007031 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
7032 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007033 int err;
Edward Creef1174f72017-08-07 15:26:19 +01007034
7035 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007036 src_reg = NULL;
7037 if (dst_reg->type != SCALAR_VALUE)
7038 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007039 else
7040 /* Make sure ID is cleared otherwise dst_reg min/max could be
7041 * incorrectly propagated into other registers by find_equal_scalars()
7042 */
7043 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007044 if (BPF_SRC(insn->code) == BPF_X) {
7045 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007046 if (src_reg->type != SCALAR_VALUE) {
7047 if (dst_reg->type != SCALAR_VALUE) {
7048 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007049 * an arbitrary scalar. Disallow all math except
7050 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01007051 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07007052 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007053 mark_reg_unknown(env, regs, insn->dst_reg);
7054 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01007055 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007056 verbose(env, "R%d pointer %s pointer prohibited\n",
7057 insn->dst_reg,
7058 bpf_alu_string[opcode >> 4]);
7059 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01007060 } else {
7061 /* scalar += pointer
7062 * This is legal, but we have to reverse our
7063 * src/dest handling in computing the range
7064 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007065 err = mark_chain_precision(env, insn->dst_reg);
7066 if (err)
7067 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007068 return adjust_ptr_min_max_vals(env, insn,
7069 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007070 }
7071 } else if (ptr_reg) {
7072 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007073 err = mark_chain_precision(env, insn->src_reg);
7074 if (err)
7075 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007076 return adjust_ptr_min_max_vals(env, insn,
7077 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007078 }
7079 } else {
7080 /* Pretend the src is a reg with a known value, since we only
7081 * need to be able to read from this state.
7082 */
7083 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007084 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01007085 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007086 if (ptr_reg) /* pointer += K */
7087 return adjust_ptr_min_max_vals(env, insn,
7088 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007089 }
7090
7091 /* Got here implies adding two SCALAR_VALUEs */
7092 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007093 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007094 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007095 return -EINVAL;
7096 }
7097 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007098 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007099 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007100 return -EINVAL;
7101 }
7102 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007103}
7104
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007105/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007106static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007107{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007108 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007109 u8 opcode = BPF_OP(insn->code);
7110 int err;
7111
7112 if (opcode == BPF_END || opcode == BPF_NEG) {
7113 if (opcode == BPF_NEG) {
7114 if (BPF_SRC(insn->code) != 0 ||
7115 insn->src_reg != BPF_REG_0 ||
7116 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007117 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007118 return -EINVAL;
7119 }
7120 } else {
7121 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01007122 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7123 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007124 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007125 return -EINVAL;
7126 }
7127 }
7128
7129 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007130 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007131 if (err)
7132 return err;
7133
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007134 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007135 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007136 insn->dst_reg);
7137 return -EACCES;
7138 }
7139
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007140 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007141 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007142 if (err)
7143 return err;
7144
7145 } else if (opcode == BPF_MOV) {
7146
7147 if (BPF_SRC(insn->code) == BPF_X) {
7148 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007149 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007150 return -EINVAL;
7151 }
7152
7153 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007154 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007155 if (err)
7156 return err;
7157 } else {
7158 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007159 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007160 return -EINVAL;
7161 }
7162 }
7163
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007164 /* check dest operand, mark as required later */
7165 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007166 if (err)
7167 return err;
7168
7169 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05007170 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7171 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7172
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007173 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7174 /* case: R1 = R2
7175 * copy register state to dest reg
7176 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07007177 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7178 /* Assign src and dst registers the same ID
7179 * that will be used by find_equal_scalars()
7180 * to propagate min/max range.
7181 */
7182 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05007183 *dst_reg = *src_reg;
7184 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007185 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007186 } else {
Edward Creef1174f72017-08-07 15:26:19 +01007187 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007188 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007189 verbose(env,
7190 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007191 insn->src_reg);
7192 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05007193 } else if (src_reg->type == SCALAR_VALUE) {
7194 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007195 /* Make sure ID is cleared otherwise
7196 * dst_reg min/max could be incorrectly
7197 * propagated into src_reg by find_equal_scalars()
7198 */
7199 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05007200 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007201 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05007202 } else {
7203 mark_reg_unknown(env, regs,
7204 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007205 }
John Fastabend3f50f132020-03-30 14:36:39 -07007206 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007207 }
7208 } else {
7209 /* case: R = imm
7210 * remember the value we stored into this reg
7211 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007212 /* clear any state __mark_reg_known doesn't set */
7213 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007214 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08007215 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7216 __mark_reg_known(regs + insn->dst_reg,
7217 insn->imm);
7218 } else {
7219 __mark_reg_known(regs + insn->dst_reg,
7220 (u32)insn->imm);
7221 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007222 }
7223
7224 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007225 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007226 return -EINVAL;
7227
7228 } else { /* all other ALU ops: and, sub, xor, add, ... */
7229
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007230 if (BPF_SRC(insn->code) == BPF_X) {
7231 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007232 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007233 return -EINVAL;
7234 }
7235 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007236 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007237 if (err)
7238 return err;
7239 } else {
7240 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007241 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007242 return -EINVAL;
7243 }
7244 }
7245
7246 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007247 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007248 if (err)
7249 return err;
7250
7251 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7252 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007253 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007254 return -EINVAL;
7255 }
7256
Rabin Vincent229394e82016-01-12 20:17:08 +01007257 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7258 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7259 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7260
7261 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007262 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01007263 return -EINVAL;
7264 }
7265 }
7266
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007267 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007268 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007269 if (err)
7270 return err;
7271
Edward Creef1174f72017-08-07 15:26:19 +01007272 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007273 }
7274
7275 return 0;
7276}
7277
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007278static void __find_good_pkt_pointers(struct bpf_func_state *state,
7279 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007280 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007281{
7282 struct bpf_reg_state *reg;
7283 int i;
7284
7285 for (i = 0; i < MAX_BPF_REG; i++) {
7286 reg = &state->regs[i];
7287 if (reg->type == type && reg->id == dst_reg->id)
7288 /* keep the maximum range already checked */
7289 reg->range = max(reg->range, new_range);
7290 }
7291
7292 bpf_for_each_spilled_reg(i, state, reg) {
7293 if (!reg)
7294 continue;
7295 if (reg->type == type && reg->id == dst_reg->id)
7296 reg->range = max(reg->range, new_range);
7297 }
7298}
7299
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007300static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007301 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01007302 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007303 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007304{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007305 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007306
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007307 if (dst_reg->off < 0 ||
7308 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01007309 /* This doesn't give us any range */
7310 return;
7311
Edward Creeb03c9f92017-08-07 15:26:36 +01007312 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7313 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01007314 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7315 * than pkt_end, but that's because it's also less than pkt.
7316 */
7317 return;
7318
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007319 new_range = dst_reg->off;
7320 if (range_right_open)
7321 new_range--;
7322
7323 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007324 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007325 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007326 *
7327 * r2 = r3;
7328 * r2 += 8;
7329 * if (r2 > pkt_end) goto <handle exception>
7330 * <access okay>
7331 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007332 * r2 = r3;
7333 * r2 += 8;
7334 * if (r2 < pkt_end) goto <access okay>
7335 * <handle exception>
7336 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007337 * Where:
7338 * r2 == dst_reg, pkt_end == src_reg
7339 * r2=pkt(id=n,off=8,r=0)
7340 * r3=pkt(id=n,off=0,r=0)
7341 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007342 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007343 *
7344 * r2 = r3;
7345 * r2 += 8;
7346 * if (pkt_end >= r2) goto <access okay>
7347 * <handle exception>
7348 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007349 * r2 = r3;
7350 * r2 += 8;
7351 * if (pkt_end <= r2) goto <handle exception>
7352 * <access okay>
7353 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007354 * Where:
7355 * pkt_end == dst_reg, r2 == src_reg
7356 * r2=pkt(id=n,off=8,r=0)
7357 * r3=pkt(id=n,off=0,r=0)
7358 *
7359 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007360 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7361 * and [r3, r3 + 8-1) respectively is safe to access depending on
7362 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007363 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007364
Edward Creef1174f72017-08-07 15:26:19 +01007365 /* If our ids match, then we must have the same max_value. And we
7366 * don't care about the other reg's fixed offset, since if it's too big
7367 * the range won't allow anything.
7368 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7369 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007370 for (i = 0; i <= vstate->curframe; i++)
7371 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7372 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007373}
7374
John Fastabend3f50f132020-03-30 14:36:39 -07007375static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007376{
John Fastabend3f50f132020-03-30 14:36:39 -07007377 struct tnum subreg = tnum_subreg(reg->var_off);
7378 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007379
John Fastabend3f50f132020-03-30 14:36:39 -07007380 switch (opcode) {
7381 case BPF_JEQ:
7382 if (tnum_is_const(subreg))
7383 return !!tnum_equals_const(subreg, val);
7384 break;
7385 case BPF_JNE:
7386 if (tnum_is_const(subreg))
7387 return !tnum_equals_const(subreg, val);
7388 break;
7389 case BPF_JSET:
7390 if ((~subreg.mask & subreg.value) & val)
7391 return 1;
7392 if (!((subreg.mask | subreg.value) & val))
7393 return 0;
7394 break;
7395 case BPF_JGT:
7396 if (reg->u32_min_value > val)
7397 return 1;
7398 else if (reg->u32_max_value <= val)
7399 return 0;
7400 break;
7401 case BPF_JSGT:
7402 if (reg->s32_min_value > sval)
7403 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01007404 else if (reg->s32_max_value <= sval)
John Fastabend3f50f132020-03-30 14:36:39 -07007405 return 0;
7406 break;
7407 case BPF_JLT:
7408 if (reg->u32_max_value < val)
7409 return 1;
7410 else if (reg->u32_min_value >= val)
7411 return 0;
7412 break;
7413 case BPF_JSLT:
7414 if (reg->s32_max_value < sval)
7415 return 1;
7416 else if (reg->s32_min_value >= sval)
7417 return 0;
7418 break;
7419 case BPF_JGE:
7420 if (reg->u32_min_value >= val)
7421 return 1;
7422 else if (reg->u32_max_value < val)
7423 return 0;
7424 break;
7425 case BPF_JSGE:
7426 if (reg->s32_min_value >= sval)
7427 return 1;
7428 else if (reg->s32_max_value < sval)
7429 return 0;
7430 break;
7431 case BPF_JLE:
7432 if (reg->u32_max_value <= val)
7433 return 1;
7434 else if (reg->u32_min_value > val)
7435 return 0;
7436 break;
7437 case BPF_JSLE:
7438 if (reg->s32_max_value <= sval)
7439 return 1;
7440 else if (reg->s32_min_value > sval)
7441 return 0;
7442 break;
Jiong Wang092ed092019-01-26 12:26:01 -05007443 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05007444
John Fastabend3f50f132020-03-30 14:36:39 -07007445 return -1;
7446}
7447
7448
7449static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7450{
7451 s64 sval = (s64)val;
7452
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007453 switch (opcode) {
7454 case BPF_JEQ:
7455 if (tnum_is_const(reg->var_off))
7456 return !!tnum_equals_const(reg->var_off, val);
7457 break;
7458 case BPF_JNE:
7459 if (tnum_is_const(reg->var_off))
7460 return !tnum_equals_const(reg->var_off, val);
7461 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08007462 case BPF_JSET:
7463 if ((~reg->var_off.mask & reg->var_off.value) & val)
7464 return 1;
7465 if (!((reg->var_off.mask | reg->var_off.value) & val))
7466 return 0;
7467 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007468 case BPF_JGT:
7469 if (reg->umin_value > val)
7470 return 1;
7471 else if (reg->umax_value <= val)
7472 return 0;
7473 break;
7474 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007475 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007476 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01007477 else if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007478 return 0;
7479 break;
7480 case BPF_JLT:
7481 if (reg->umax_value < val)
7482 return 1;
7483 else if (reg->umin_value >= val)
7484 return 0;
7485 break;
7486 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007487 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007488 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007489 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007490 return 0;
7491 break;
7492 case BPF_JGE:
7493 if (reg->umin_value >= val)
7494 return 1;
7495 else if (reg->umax_value < val)
7496 return 0;
7497 break;
7498 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007499 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007500 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007501 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007502 return 0;
7503 break;
7504 case BPF_JLE:
7505 if (reg->umax_value <= val)
7506 return 1;
7507 else if (reg->umin_value > val)
7508 return 0;
7509 break;
7510 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007511 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007512 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007513 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007514 return 0;
7515 break;
7516 }
7517
7518 return -1;
7519}
7520
John Fastabend3f50f132020-03-30 14:36:39 -07007521/* compute branch direction of the expression "if (reg opcode val) goto target;"
7522 * and return:
7523 * 1 - branch will be taken and "goto target" will be executed
7524 * 0 - branch will not be taken and fall-through to next insn
7525 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7526 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05007527 */
John Fastabend3f50f132020-03-30 14:36:39 -07007528static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7529 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05007530{
John Fastabendcac616d2020-05-21 13:07:26 -07007531 if (__is_pointer_value(false, reg)) {
7532 if (!reg_type_not_null(reg->type))
7533 return -1;
7534
7535 /* If pointer is valid tests against zero will fail so we can
7536 * use this to direct branch taken.
7537 */
7538 if (val != 0)
7539 return -1;
7540
7541 switch (opcode) {
7542 case BPF_JEQ:
7543 return 0;
7544 case BPF_JNE:
7545 return 1;
7546 default:
7547 return -1;
7548 }
7549 }
Jiong Wang092ed092019-01-26 12:26:01 -05007550
John Fastabend3f50f132020-03-30 14:36:39 -07007551 if (is_jmp32)
7552 return is_branch32_taken(reg, val, opcode);
7553 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02007554}
7555
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007556static int flip_opcode(u32 opcode)
7557{
7558 /* How can we transform "a <op> b" into "b <op> a"? */
7559 static const u8 opcode_flip[16] = {
7560 /* these stay the same */
7561 [BPF_JEQ >> 4] = BPF_JEQ,
7562 [BPF_JNE >> 4] = BPF_JNE,
7563 [BPF_JSET >> 4] = BPF_JSET,
7564 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7565 [BPF_JGE >> 4] = BPF_JLE,
7566 [BPF_JGT >> 4] = BPF_JLT,
7567 [BPF_JLE >> 4] = BPF_JGE,
7568 [BPF_JLT >> 4] = BPF_JGT,
7569 [BPF_JSGE >> 4] = BPF_JSLE,
7570 [BPF_JSGT >> 4] = BPF_JSLT,
7571 [BPF_JSLE >> 4] = BPF_JSGE,
7572 [BPF_JSLT >> 4] = BPF_JSGT
7573 };
7574 return opcode_flip[opcode >> 4];
7575}
7576
7577static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7578 struct bpf_reg_state *src_reg,
7579 u8 opcode)
7580{
7581 struct bpf_reg_state *pkt;
7582
7583 if (src_reg->type == PTR_TO_PACKET_END) {
7584 pkt = dst_reg;
7585 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7586 pkt = src_reg;
7587 opcode = flip_opcode(opcode);
7588 } else {
7589 return -1;
7590 }
7591
7592 if (pkt->range >= 0)
7593 return -1;
7594
7595 switch (opcode) {
7596 case BPF_JLE:
7597 /* pkt <= pkt_end */
7598 fallthrough;
7599 case BPF_JGT:
7600 /* pkt > pkt_end */
7601 if (pkt->range == BEYOND_PKT_END)
7602 /* pkt has at last one extra byte beyond pkt_end */
7603 return opcode == BPF_JGT;
7604 break;
7605 case BPF_JLT:
7606 /* pkt < pkt_end */
7607 fallthrough;
7608 case BPF_JGE:
7609 /* pkt >= pkt_end */
7610 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7611 return opcode == BPF_JGE;
7612 break;
7613 }
7614 return -1;
7615}
7616
Josef Bacik48461132016-09-28 10:54:32 -04007617/* Adjusts the register min/max values in the case that the dst_reg is the
7618 * variable register that we are working on, and src_reg is a constant or we're
7619 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01007620 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04007621 */
7622static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007623 struct bpf_reg_state *false_reg,
7624 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007625 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007626{
John Fastabend3f50f132020-03-30 14:36:39 -07007627 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7628 struct tnum false_64off = false_reg->var_off;
7629 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7630 struct tnum true_64off = true_reg->var_off;
7631 s64 sval = (s64)val;
7632 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007633
Edward Creef1174f72017-08-07 15:26:19 +01007634 /* If the dst_reg is a pointer, we can't learn anything about its
7635 * variable offset from the compare (unless src_reg were a pointer into
7636 * the same object, but we don't bother with that.
7637 * Since false_reg and true_reg have the same type by construction, we
7638 * only need to check one of them for pointerness.
7639 */
7640 if (__is_pointer_value(false, false_reg))
7641 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007642
Josef Bacik48461132016-09-28 10:54:32 -04007643 switch (opcode) {
7644 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04007645 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007646 {
7647 struct bpf_reg_state *reg =
7648 opcode == BPF_JEQ ? true_reg : false_reg;
7649
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007650 /* JEQ/JNE comparison doesn't change the register equivalence.
7651 * r1 = r2;
7652 * if (r1 == 42) goto label;
7653 * ...
7654 * label: // here both r1 and r2 are known to be 42.
7655 *
7656 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04007657 */
John Fastabend3f50f132020-03-30 14:36:39 -07007658 if (is_jmp32)
7659 __mark_reg32_known(reg, val32);
7660 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007661 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04007662 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007663 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007664 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07007665 if (is_jmp32) {
7666 false_32off = tnum_and(false_32off, tnum_const(~val32));
7667 if (is_power_of_2(val32))
7668 true_32off = tnum_or(true_32off,
7669 tnum_const(val32));
7670 } else {
7671 false_64off = tnum_and(false_64off, tnum_const(~val));
7672 if (is_power_of_2(val))
7673 true_64off = tnum_or(true_64off,
7674 tnum_const(val));
7675 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007676 break;
Josef Bacik48461132016-09-28 10:54:32 -04007677 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007678 case BPF_JGT:
7679 {
John Fastabend3f50f132020-03-30 14:36:39 -07007680 if (is_jmp32) {
7681 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7682 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7683
7684 false_reg->u32_max_value = min(false_reg->u32_max_value,
7685 false_umax);
7686 true_reg->u32_min_value = max(true_reg->u32_min_value,
7687 true_umin);
7688 } else {
7689 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7690 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7691
7692 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7693 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7694 }
Edward Creeb03c9f92017-08-07 15:26:36 +01007695 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007696 }
Josef Bacik48461132016-09-28 10:54:32 -04007697 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007698 case BPF_JSGT:
7699 {
John Fastabend3f50f132020-03-30 14:36:39 -07007700 if (is_jmp32) {
7701 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7702 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007703
John Fastabend3f50f132020-03-30 14:36:39 -07007704 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7705 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7706 } else {
7707 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7708 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7709
7710 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7711 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7712 }
Josef Bacik48461132016-09-28 10:54:32 -04007713 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007714 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007715 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007716 case BPF_JLT:
7717 {
John Fastabend3f50f132020-03-30 14:36:39 -07007718 if (is_jmp32) {
7719 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7720 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7721
7722 false_reg->u32_min_value = max(false_reg->u32_min_value,
7723 false_umin);
7724 true_reg->u32_max_value = min(true_reg->u32_max_value,
7725 true_umax);
7726 } else {
7727 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7728 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7729
7730 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7731 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7732 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007733 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007734 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007735 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007736 case BPF_JSLT:
7737 {
John Fastabend3f50f132020-03-30 14:36:39 -07007738 if (is_jmp32) {
7739 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7740 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007741
John Fastabend3f50f132020-03-30 14:36:39 -07007742 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7743 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7744 } else {
7745 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7746 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7747
7748 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7749 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7750 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007751 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007752 }
Josef Bacik48461132016-09-28 10:54:32 -04007753 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02007754 return;
Josef Bacik48461132016-09-28 10:54:32 -04007755 }
7756
John Fastabend3f50f132020-03-30 14:36:39 -07007757 if (is_jmp32) {
7758 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7759 tnum_subreg(false_32off));
7760 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7761 tnum_subreg(true_32off));
7762 __reg_combine_32_into_64(false_reg);
7763 __reg_combine_32_into_64(true_reg);
7764 } else {
7765 false_reg->var_off = false_64off;
7766 true_reg->var_off = true_64off;
7767 __reg_combine_64_into_32(false_reg);
7768 __reg_combine_64_into_32(true_reg);
7769 }
Josef Bacik48461132016-09-28 10:54:32 -04007770}
7771
Edward Creef1174f72017-08-07 15:26:19 +01007772/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7773 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04007774 */
7775static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007776 struct bpf_reg_state *false_reg,
7777 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007778 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007779{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007780 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02007781 /* This uses zero as "not present in table"; luckily the zero opcode,
7782 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01007783 */
Jann Horn0fc31b12020-03-30 18:03:24 +02007784 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07007785 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01007786}
7787
7788/* Regs are known to be equal, so intersect their min/max/var_off */
7789static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7790 struct bpf_reg_state *dst_reg)
7791{
Edward Creeb03c9f92017-08-07 15:26:36 +01007792 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7793 dst_reg->umin_value);
7794 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7795 dst_reg->umax_value);
7796 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7797 dst_reg->smin_value);
7798 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7799 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01007800 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7801 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007802 /* We might have learned new bounds from the var_off. */
7803 __update_reg_bounds(src_reg);
7804 __update_reg_bounds(dst_reg);
7805 /* We might have learned something about the sign bit. */
7806 __reg_deduce_bounds(src_reg);
7807 __reg_deduce_bounds(dst_reg);
7808 /* We might have learned some bits from the bounds. */
7809 __reg_bound_offset(src_reg);
7810 __reg_bound_offset(dst_reg);
7811 /* Intersecting with the old var_off might have improved our bounds
7812 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7813 * then new var_off is (0; 0x7f...fc) which improves our umax.
7814 */
7815 __update_reg_bounds(src_reg);
7816 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007817}
7818
7819static void reg_combine_min_max(struct bpf_reg_state *true_src,
7820 struct bpf_reg_state *true_dst,
7821 struct bpf_reg_state *false_src,
7822 struct bpf_reg_state *false_dst,
7823 u8 opcode)
7824{
7825 switch (opcode) {
7826 case BPF_JEQ:
7827 __reg_combine_min_max(true_src, true_dst);
7828 break;
7829 case BPF_JNE:
7830 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007831 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007832 }
Josef Bacik48461132016-09-28 10:54:32 -04007833}
7834
Joe Stringerfd978bf72018-10-02 13:35:35 -07007835static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7836 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007837 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007838{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07007839 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7840 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01007841 /* Old offset (both fixed and variable parts) should
7842 * have been known-zero, because we don't allow pointer
7843 * arithmetic on pointers that might be NULL.
7844 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007845 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7846 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007847 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007848 __mark_reg_known_zero(reg);
7849 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007850 }
7851 if (is_null) {
7852 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007853 /* We don't need id and ref_obj_id from this point
7854 * onwards anymore, thus we should better reset it,
7855 * so that state pruning has chances to take effect.
7856 */
7857 reg->id = 0;
7858 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04007859
7860 return;
7861 }
7862
7863 mark_ptr_not_null_reg(reg);
7864
7865 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007866 /* For not-NULL ptr, reg->ref_obj_id will be reset
7867 * in release_reg_references().
7868 *
7869 * reg->id is still used by spin_lock ptr. Other
7870 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007871 */
7872 reg->id = 0;
7873 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02007874 }
7875}
7876
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007877static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7878 bool is_null)
7879{
7880 struct bpf_reg_state *reg;
7881 int i;
7882
7883 for (i = 0; i < MAX_BPF_REG; i++)
7884 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7885
7886 bpf_for_each_spilled_reg(i, state, reg) {
7887 if (!reg)
7888 continue;
7889 mark_ptr_or_null_reg(state, reg, id, is_null);
7890 }
7891}
7892
Thomas Graf57a09bf2016-10-18 19:51:19 +02007893/* The logic is similar to find_good_pkt_pointers(), both could eventually
7894 * be folded together at some point.
7895 */
Joe Stringer840b9612018-10-02 13:35:32 -07007896static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7897 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007898{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007899 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007900 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007901 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01007902 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007903 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02007904
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007905 if (ref_obj_id && ref_obj_id == id && is_null)
7906 /* regs[regno] is in the " == NULL" branch.
7907 * No one could have freed the reference state before
7908 * doing the NULL check.
7909 */
7910 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07007911
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007912 for (i = 0; i <= vstate->curframe; i++)
7913 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02007914}
7915
Daniel Borkmann5beca082017-11-01 23:58:10 +01007916static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7917 struct bpf_reg_state *dst_reg,
7918 struct bpf_reg_state *src_reg,
7919 struct bpf_verifier_state *this_branch,
7920 struct bpf_verifier_state *other_branch)
7921{
7922 if (BPF_SRC(insn->code) != BPF_X)
7923 return false;
7924
Jiong Wang092ed092019-01-26 12:26:01 -05007925 /* Pointers are always 64-bit. */
7926 if (BPF_CLASS(insn->code) == BPF_JMP32)
7927 return false;
7928
Daniel Borkmann5beca082017-11-01 23:58:10 +01007929 switch (BPF_OP(insn->code)) {
7930 case BPF_JGT:
7931 if ((dst_reg->type == PTR_TO_PACKET &&
7932 src_reg->type == PTR_TO_PACKET_END) ||
7933 (dst_reg->type == PTR_TO_PACKET_META &&
7934 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7935 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7936 find_good_pkt_pointers(this_branch, dst_reg,
7937 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007938 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007939 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7940 src_reg->type == PTR_TO_PACKET) ||
7941 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7942 src_reg->type == PTR_TO_PACKET_META)) {
7943 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7944 find_good_pkt_pointers(other_branch, src_reg,
7945 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007946 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007947 } else {
7948 return false;
7949 }
7950 break;
7951 case BPF_JLT:
7952 if ((dst_reg->type == PTR_TO_PACKET &&
7953 src_reg->type == PTR_TO_PACKET_END) ||
7954 (dst_reg->type == PTR_TO_PACKET_META &&
7955 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7956 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7957 find_good_pkt_pointers(other_branch, dst_reg,
7958 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007959 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007960 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7961 src_reg->type == PTR_TO_PACKET) ||
7962 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7963 src_reg->type == PTR_TO_PACKET_META)) {
7964 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7965 find_good_pkt_pointers(this_branch, src_reg,
7966 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007967 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007968 } else {
7969 return false;
7970 }
7971 break;
7972 case BPF_JGE:
7973 if ((dst_reg->type == PTR_TO_PACKET &&
7974 src_reg->type == PTR_TO_PACKET_END) ||
7975 (dst_reg->type == PTR_TO_PACKET_META &&
7976 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7977 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7978 find_good_pkt_pointers(this_branch, dst_reg,
7979 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007980 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007981 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7982 src_reg->type == PTR_TO_PACKET) ||
7983 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7984 src_reg->type == PTR_TO_PACKET_META)) {
7985 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7986 find_good_pkt_pointers(other_branch, src_reg,
7987 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007988 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007989 } else {
7990 return false;
7991 }
7992 break;
7993 case BPF_JLE:
7994 if ((dst_reg->type == PTR_TO_PACKET &&
7995 src_reg->type == PTR_TO_PACKET_END) ||
7996 (dst_reg->type == PTR_TO_PACKET_META &&
7997 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7998 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7999 find_good_pkt_pointers(other_branch, dst_reg,
8000 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008001 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008002 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
8003 src_reg->type == PTR_TO_PACKET) ||
8004 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
8005 src_reg->type == PTR_TO_PACKET_META)) {
8006 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
8007 find_good_pkt_pointers(this_branch, src_reg,
8008 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008009 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008010 } else {
8011 return false;
8012 }
8013 break;
8014 default:
8015 return false;
8016 }
8017
8018 return true;
8019}
8020
Alexei Starovoitov75748832020-10-08 18:12:37 -07008021static void find_equal_scalars(struct bpf_verifier_state *vstate,
8022 struct bpf_reg_state *known_reg)
8023{
8024 struct bpf_func_state *state;
8025 struct bpf_reg_state *reg;
8026 int i, j;
8027
8028 for (i = 0; i <= vstate->curframe; i++) {
8029 state = vstate->frame[i];
8030 for (j = 0; j < MAX_BPF_REG; j++) {
8031 reg = &state->regs[j];
8032 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8033 *reg = *known_reg;
8034 }
8035
8036 bpf_for_each_spilled_reg(j, state, reg) {
8037 if (!reg)
8038 continue;
8039 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
8040 *reg = *known_reg;
8041 }
8042 }
8043}
8044
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008045static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008046 struct bpf_insn *insn, int *insn_idx)
8047{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008048 struct bpf_verifier_state *this_branch = env->cur_state;
8049 struct bpf_verifier_state *other_branch;
8050 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008051 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008052 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05008053 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008054 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008055 int err;
8056
Jiong Wang092ed092019-01-26 12:26:01 -05008057 /* Only conditional jumps are expected to reach here. */
8058 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8059 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008060 return -EINVAL;
8061 }
8062
8063 if (BPF_SRC(insn->code) == BPF_X) {
8064 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008065 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008066 return -EINVAL;
8067 }
8068
8069 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008070 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008071 if (err)
8072 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008073
8074 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008075 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008076 insn->src_reg);
8077 return -EACCES;
8078 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008079 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008080 } else {
8081 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008082 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008083 return -EINVAL;
8084 }
8085 }
8086
8087 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008088 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008089 if (err)
8090 return err;
8091
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008092 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008093 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008094
John Fastabend3f50f132020-03-30 14:36:39 -07008095 if (BPF_SRC(insn->code) == BPF_K) {
8096 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8097 } else if (src_reg->type == SCALAR_VALUE &&
8098 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8099 pred = is_branch_taken(dst_reg,
8100 tnum_subreg(src_reg->var_off).value,
8101 opcode,
8102 is_jmp32);
8103 } else if (src_reg->type == SCALAR_VALUE &&
8104 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8105 pred = is_branch_taken(dst_reg,
8106 src_reg->var_off.value,
8107 opcode,
8108 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008109 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8110 reg_is_pkt_pointer_any(src_reg) &&
8111 !is_jmp32) {
8112 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07008113 }
8114
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008115 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07008116 /* If we get here with a dst_reg pointer type it is because
8117 * above is_branch_taken() special cased the 0 comparison.
8118 */
8119 if (!__is_pointer_value(false, dst_reg))
8120 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008121 if (BPF_SRC(insn->code) == BPF_X && !err &&
8122 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008123 err = mark_chain_precision(env, insn->src_reg);
8124 if (err)
8125 return err;
8126 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008127 if (pred == 1) {
8128 /* only follow the goto, ignore fall-through */
8129 *insn_idx += insn->off;
8130 return 0;
8131 } else if (pred == 0) {
8132 /* only follow fall-through branch, since
8133 * that's where the program will go
8134 */
8135 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008136 }
8137
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008138 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8139 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008140 if (!other_branch)
8141 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008142 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008143
Josef Bacik48461132016-09-28 10:54:32 -04008144 /* detect if we are comparing against a constant value so we can adjust
8145 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01008146 * this is only legit if both are scalars (or pointers to the same
8147 * object, I suppose, but we don't support that right now), because
8148 * otherwise the different base pointers mean the offsets aren't
8149 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04008150 */
8151 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05008152 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008153
Edward Creef1174f72017-08-07 15:26:19 +01008154 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05008155 src_reg->type == SCALAR_VALUE) {
8156 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008157 (is_jmp32 &&
8158 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008159 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008160 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008161 src_reg->var_off.value,
8162 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008163 opcode, is_jmp32);
8164 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008165 (is_jmp32 &&
8166 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008167 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008168 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008169 dst_reg->var_off.value,
8170 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008171 opcode, is_jmp32);
8172 else if (!is_jmp32 &&
8173 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01008174 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008175 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8176 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008177 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008178 if (src_reg->id &&
8179 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008180 find_equal_scalars(this_branch, src_reg);
8181 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8182 }
8183
Edward Creef1174f72017-08-07 15:26:19 +01008184 }
8185 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008186 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07008187 dst_reg, insn->imm, (u32)insn->imm,
8188 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04008189 }
8190
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008191 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8192 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008193 find_equal_scalars(this_branch, dst_reg);
8194 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8195 }
8196
Jiong Wang092ed092019-01-26 12:26:01 -05008197 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8198 * NOTE: these optimizations below are related with pointer comparison
8199 * which will never be JMP32.
8200 */
8201 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008202 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07008203 reg_type_may_be_null(dst_reg->type)) {
8204 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02008205 * safe or unknown depending R == 0 or R != 0 conditional.
8206 */
Joe Stringer840b9612018-10-02 13:35:32 -07008207 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8208 opcode == BPF_JNE);
8209 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8210 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008211 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8212 this_branch, other_branch) &&
8213 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008214 verbose(env, "R%d pointer comparison prohibited\n",
8215 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008216 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008217 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008218 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008219 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008220 return 0;
8221}
8222
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008223/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008224static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008225{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008226 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008227 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07008228 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008229 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008230 int err;
8231
8232 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008233 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008234 return -EINVAL;
8235 }
8236 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008237 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008238 return -EINVAL;
8239 }
8240
Edward Creedc503a82017-08-15 20:34:35 +01008241 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008242 if (err)
8243 return err;
8244
Hao Luo4976b712020-09-29 16:50:44 -07008245 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01008246 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01008247 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8248
Hao Luo4976b712020-09-29 16:50:44 -07008249 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008250 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008251 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01008252 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008253
Hao Luo4976b712020-09-29 16:50:44 -07008254 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8255 mark_reg_known_zero(env, regs, insn->dst_reg);
8256
8257 dst_reg->type = aux->btf_var.reg_type;
8258 switch (dst_reg->type) {
8259 case PTR_TO_MEM:
8260 dst_reg->mem_size = aux->btf_var.mem_size;
8261 break;
8262 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07008263 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08008264 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07008265 dst_reg->btf_id = aux->btf_var.btf_id;
8266 break;
8267 default:
8268 verbose(env, "bpf verifier is misconfigured\n");
8269 return -EFAULT;
8270 }
8271 return 0;
8272 }
8273
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008274 map = env->used_maps[aux->map_index];
8275 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07008276 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008277
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008278 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07008279 dst_reg->type = PTR_TO_MAP_VALUE;
8280 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008281 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07008282 dst_reg->id = ++env->id_gen;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008283 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
Hao Luo4976b712020-09-29 16:50:44 -07008284 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008285 } else {
8286 verbose(env, "bpf verifier is misconfigured\n");
8287 return -EINVAL;
8288 }
8289
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008290 return 0;
8291}
8292
Daniel Borkmann96be4322015-03-01 12:31:46 +01008293static bool may_access_skb(enum bpf_prog_type type)
8294{
8295 switch (type) {
8296 case BPF_PROG_TYPE_SOCKET_FILTER:
8297 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01008298 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01008299 return true;
8300 default:
8301 return false;
8302 }
8303}
8304
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008305/* verify safety of LD_ABS|LD_IND instructions:
8306 * - they can only appear in the programs where ctx == skb
8307 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8308 * preserve R6-R9, and store return value into R0
8309 *
8310 * Implicit input:
8311 * ctx == skb == R6 == CTX
8312 *
8313 * Explicit input:
8314 * SRC == any register
8315 * IMM == 32-bit immediate
8316 *
8317 * Output:
8318 * R0 - 8/16/32-bit skb data converted to cpu endianness
8319 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008320static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008321{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008322 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008323 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008324 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008325 int i, err;
8326
Udip Pant7e407812020-08-25 16:20:00 -07008327 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008328 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008329 return -EINVAL;
8330 }
8331
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02008332 if (!env->ops->gen_ld_abs) {
8333 verbose(env, "bpf verifier is misconfigured\n");
8334 return -EINVAL;
8335 }
8336
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008337 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07008338 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008339 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008340 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008341 return -EINVAL;
8342 }
8343
8344 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008345 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008346 if (err)
8347 return err;
8348
Joe Stringerfd978bf72018-10-02 13:35:35 -07008349 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8350 * gen_ld_abs() may terminate the program at runtime, leading to
8351 * reference leak.
8352 */
8353 err = check_reference_leak(env);
8354 if (err) {
8355 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8356 return err;
8357 }
8358
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008359 if (env->cur_state->active_spin_lock) {
8360 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8361 return -EINVAL;
8362 }
8363
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008364 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008365 verbose(env,
8366 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008367 return -EINVAL;
8368 }
8369
8370 if (mode == BPF_IND) {
8371 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01008372 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008373 if (err)
8374 return err;
8375 }
8376
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008377 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8378 if (err < 0)
8379 return err;
8380
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008381 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01008382 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008383 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008384 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8385 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008386
8387 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01008388 * the value fetched from the packet.
8389 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008390 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008391 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01008392 /* ld_abs load up to 32-bit skb data. */
8393 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008394 return 0;
8395}
8396
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008397static int check_return_code(struct bpf_verifier_env *env)
8398{
brakmo5cf1e912019-05-28 16:59:36 -07008399 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008400 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008401 struct bpf_reg_state *reg;
8402 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07008403 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008404 int err;
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008405 const bool is_subprog = env->cur_state->frame[0]->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008406
KP Singh9e4e01d2020-03-29 01:43:52 +01008407 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008408 if (!is_subprog &&
8409 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07008410 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008411 !prog->aux->attach_func_proto->type)
8412 return 0;
8413
8414 /* eBPF calling convetion is such that R0 is used
8415 * to return the value from eBPF program.
8416 * Make sure that it's readable at this time
8417 * of bpf_exit, which means that program wrote
8418 * something into it earlier
8419 */
8420 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8421 if (err)
8422 return err;
8423
8424 if (is_pointer_value(env, BPF_REG_0)) {
8425 verbose(env, "R0 leaks addr as return value\n");
8426 return -EACCES;
8427 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008428
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008429 reg = cur_regs(env) + BPF_REG_0;
8430 if (is_subprog) {
8431 if (reg->type != SCALAR_VALUE) {
8432 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8433 reg_type_str[reg->type]);
8434 return -EINVAL;
8435 }
8436 return 0;
8437 }
8438
Udip Pant7e407812020-08-25 16:20:00 -07008439 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02008440 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8441 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02008442 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8443 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8444 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8445 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8446 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02008447 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08008448 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8449 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8450 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008451 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008452 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07008453 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8454 range = tnum_range(0, 3);
8455 enforce_attach_type_range = tnum_range(2, 3);
8456 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008457 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008458 case BPF_PROG_TYPE_CGROUP_SOCK:
8459 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05008460 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08008461 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07008462 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008463 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07008464 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8465 if (!env->prog->aux->attach_btf_id)
8466 return 0;
8467 range = tnum_const(0);
8468 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07008469 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07008470 switch (env->prog->expected_attach_type) {
8471 case BPF_TRACE_FENTRY:
8472 case BPF_TRACE_FEXIT:
8473 range = tnum_const(0);
8474 break;
8475 case BPF_TRACE_RAW_TP:
8476 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07008477 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02008478 case BPF_TRACE_ITER:
8479 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008480 default:
8481 return -ENOTSUPP;
8482 }
Yonghong Song15d83c42020-05-09 10:59:00 -07008483 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02008484 case BPF_PROG_TYPE_SK_LOOKUP:
8485 range = tnum_range(SK_DROP, SK_PASS);
8486 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008487 case BPF_PROG_TYPE_EXT:
8488 /* freplace program can return anything as its return value
8489 * depends on the to-be-replaced kernel func or bpf program.
8490 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008491 default:
8492 return 0;
8493 }
8494
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008495 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008496 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008497 reg_type_str[reg->type]);
8498 return -EINVAL;
8499 }
8500
8501 if (!tnum_in(range, reg->var_off)) {
Yonghong Songbc2591d2021-02-26 12:49:22 -08008502 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008503 return -EINVAL;
8504 }
brakmo5cf1e912019-05-28 16:59:36 -07008505
8506 if (!tnum_is_unknown(enforce_attach_type_range) &&
8507 tnum_in(enforce_attach_type_range, reg->var_off))
8508 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008509 return 0;
8510}
8511
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008512/* non-recursive DFS pseudo code
8513 * 1 procedure DFS-iterative(G,v):
8514 * 2 label v as discovered
8515 * 3 let S be a stack
8516 * 4 S.push(v)
8517 * 5 while S is not empty
8518 * 6 t <- S.pop()
8519 * 7 if t is what we're looking for:
8520 * 8 return t
8521 * 9 for all edges e in G.adjacentEdges(t) do
8522 * 10 if edge e is already labelled
8523 * 11 continue with the next edge
8524 * 12 w <- G.adjacentVertex(t,e)
8525 * 13 if vertex w is not discovered and not explored
8526 * 14 label e as tree-edge
8527 * 15 label w as discovered
8528 * 16 S.push(w)
8529 * 17 continue at 5
8530 * 18 else if vertex w is discovered
8531 * 19 label e as back-edge
8532 * 20 else
8533 * 21 // vertex w is explored
8534 * 22 label e as forward- or cross-edge
8535 * 23 label t as explored
8536 * 24 S.pop()
8537 *
8538 * convention:
8539 * 0x10 - discovered
8540 * 0x11 - discovered and fall-through edge labelled
8541 * 0x12 - discovered and fall-through and branch edges labelled
8542 * 0x20 - explored
8543 */
8544
8545enum {
8546 DISCOVERED = 0x10,
8547 EXPLORED = 0x20,
8548 FALLTHROUGH = 1,
8549 BRANCH = 2,
8550};
8551
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008552static u32 state_htab_size(struct bpf_verifier_env *env)
8553{
8554 return env->prog->len;
8555}
8556
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008557static struct bpf_verifier_state_list **explored_state(
8558 struct bpf_verifier_env *env,
8559 int idx)
8560{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008561 struct bpf_verifier_state *cur = env->cur_state;
8562 struct bpf_func_state *state = cur->frame[cur->curframe];
8563
8564 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008565}
8566
8567static void init_explored_state(struct bpf_verifier_env *env, int idx)
8568{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008569 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008570}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008571
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008572enum {
8573 DONE_EXPLORING = 0,
8574 KEEP_EXPLORING = 1,
8575};
8576
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008577/* t, w, e - match pseudo-code above:
8578 * t - index of current instruction
8579 * w - next instruction
8580 * e - edge
8581 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07008582static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8583 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008584{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008585 int *insn_stack = env->cfg.insn_stack;
8586 int *insn_state = env->cfg.insn_state;
8587
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008588 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008589 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008590
8591 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008592 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008593
8594 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008595 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008596 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008597 return -EINVAL;
8598 }
8599
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008600 if (e == BRANCH)
8601 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008602 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008603
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008604 if (insn_state[w] == 0) {
8605 /* tree-edge */
8606 insn_state[t] = DISCOVERED | e;
8607 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008608 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008609 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008610 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008611 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008612 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07008613 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008614 return DONE_EXPLORING;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008615 verbose_linfo(env, t, "%d: ", t);
8616 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008617 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008618 return -EINVAL;
8619 } else if (insn_state[w] == EXPLORED) {
8620 /* forward- or cross-edge */
8621 insn_state[t] = DISCOVERED | e;
8622 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008623 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008624 return -EFAULT;
8625 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008626 return DONE_EXPLORING;
8627}
8628
Yonghong Songefdb22d2021-02-26 12:49:20 -08008629static int visit_func_call_insn(int t, int insn_cnt,
8630 struct bpf_insn *insns,
8631 struct bpf_verifier_env *env,
8632 bool visit_callee)
8633{
8634 int ret;
8635
8636 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8637 if (ret)
8638 return ret;
8639
8640 if (t + 1 < insn_cnt)
8641 init_explored_state(env, t + 1);
8642 if (visit_callee) {
8643 init_explored_state(env, t);
8644 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8645 env, false);
8646 }
8647 return ret;
8648}
8649
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008650/* Visits the instruction at index t and returns one of the following:
8651 * < 0 - an error occurred
8652 * DONE_EXPLORING - the instruction was fully explored
8653 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8654 */
8655static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8656{
8657 struct bpf_insn *insns = env->prog->insnsi;
8658 int ret;
8659
8660 /* All non-branch instructions have a single fall-through edge. */
8661 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8662 BPF_CLASS(insns[t].code) != BPF_JMP32)
8663 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8664
8665 switch (BPF_OP(insns[t].code)) {
8666 case BPF_EXIT:
8667 return DONE_EXPLORING;
8668
8669 case BPF_CALL:
Yonghong Songefdb22d2021-02-26 12:49:20 -08008670 return visit_func_call_insn(t, insn_cnt, insns, env,
8671 insns[t].src_reg == BPF_PSEUDO_CALL);
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008672
8673 case BPF_JA:
8674 if (BPF_SRC(insns[t].code) != BPF_K)
8675 return -EINVAL;
8676
8677 /* unconditional jump with single edge */
8678 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8679 true);
8680 if (ret)
8681 return ret;
8682
8683 /* unconditional jmp is not a good pruning point,
8684 * but it's marked, since backtracking needs
8685 * to record jmp history in is_state_visited().
8686 */
8687 init_explored_state(env, t + insns[t].off + 1);
8688 /* tell verifier to check for equivalent states
8689 * after every call and jump
8690 */
8691 if (t + 1 < insn_cnt)
8692 init_explored_state(env, t + 1);
8693
8694 return ret;
8695
8696 default:
8697 /* conditional jump with two edges */
8698 init_explored_state(env, t);
8699 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8700 if (ret)
8701 return ret;
8702
8703 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8704 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008705}
8706
8707/* non-recursive depth-first-search to detect loops in BPF program
8708 * loop == back-edge in directed graph
8709 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008710static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008711{
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008712 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008713 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008714 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008715 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008716
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008717 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008718 if (!insn_state)
8719 return -ENOMEM;
8720
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008721 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008722 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008723 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008724 return -ENOMEM;
8725 }
8726
8727 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8728 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008729 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008730
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008731 while (env->cfg.cur_stack > 0) {
8732 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008733
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008734 ret = visit_insn(t, insn_cnt, env);
8735 switch (ret) {
8736 case DONE_EXPLORING:
8737 insn_state[t] = EXPLORED;
8738 env->cfg.cur_stack--;
8739 break;
8740 case KEEP_EXPLORING:
8741 break;
8742 default:
8743 if (ret > 0) {
8744 verbose(env, "visit_insn internal bug\n");
8745 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008746 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008747 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008748 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008749 }
8750
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008751 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008752 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008753 ret = -EFAULT;
8754 goto err_free;
8755 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008756
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008757 for (i = 0; i < insn_cnt; i++) {
8758 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008759 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008760 ret = -EINVAL;
8761 goto err_free;
8762 }
8763 }
8764 ret = 0; /* cfg looks good */
8765
8766err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008767 kvfree(insn_state);
8768 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008769 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008770 return ret;
8771}
8772
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008773static int check_abnormal_return(struct bpf_verifier_env *env)
8774{
8775 int i;
8776
8777 for (i = 1; i < env->subprog_cnt; i++) {
8778 if (env->subprog_info[i].has_ld_abs) {
8779 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8780 return -EINVAL;
8781 }
8782 if (env->subprog_info[i].has_tail_call) {
8783 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8784 return -EINVAL;
8785 }
8786 }
8787 return 0;
8788}
8789
Yonghong Song838e9692018-11-19 15:29:11 -08008790/* The minimum supported BTF func info size */
8791#define MIN_BPF_FUNCINFO_SIZE 8
8792#define MAX_FUNCINFO_REC_SIZE 252
8793
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008794static int check_btf_func(struct bpf_verifier_env *env,
8795 const union bpf_attr *attr,
8796 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08008797{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008798 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008799 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08008800 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008801 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008802 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008803 struct bpf_prog *prog;
8804 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008805 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008806 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008807 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03008808 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08008809
8810 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008811 if (!nfuncs) {
8812 if (check_abnormal_return(env))
8813 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008814 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008815 }
Yonghong Song838e9692018-11-19 15:29:11 -08008816
8817 if (nfuncs != env->subprog_cnt) {
8818 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8819 return -EINVAL;
8820 }
8821
8822 urec_size = attr->func_info_rec_size;
8823 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8824 urec_size > MAX_FUNCINFO_REC_SIZE ||
8825 urec_size % sizeof(u32)) {
8826 verbose(env, "invalid func info rec size %u\n", urec_size);
8827 return -EINVAL;
8828 }
8829
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008830 prog = env->prog;
8831 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008832
8833 urecord = u64_to_user_ptr(attr->func_info);
8834 min_size = min_t(u32, krec_size, urec_size);
8835
Yonghong Songba64e7d2018-11-24 23:20:44 -08008836 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008837 if (!krecord)
8838 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008839 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8840 if (!info_aux)
8841 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008842
Yonghong Song838e9692018-11-19 15:29:11 -08008843 for (i = 0; i < nfuncs; i++) {
8844 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8845 if (ret) {
8846 if (ret == -E2BIG) {
8847 verbose(env, "nonzero tailing record in func info");
8848 /* set the size kernel expects so loader can zero
8849 * out the rest of the record.
8850 */
8851 if (put_user(min_size, &uattr->func_info_rec_size))
8852 ret = -EFAULT;
8853 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008854 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008855 }
8856
Yonghong Songba64e7d2018-11-24 23:20:44 -08008857 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008858 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008859 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008860 }
8861
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008862 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008863 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008864 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008865 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008866 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008867 "nonzero insn_off %u for the first func info record",
8868 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008869 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008870 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008871 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08008872 verbose(env,
8873 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008874 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008875 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008876 }
8877
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008878 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008879 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008880 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008881 }
8882
8883 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08008884 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008885 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008886 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08008887 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008888 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008889 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008890 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008891
8892 func_proto = btf_type_by_id(btf, type->type);
8893 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8894 /* btf_func_check() already verified it during BTF load */
8895 goto err_free;
8896 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8897 scalar_return =
8898 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8899 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8900 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8901 goto err_free;
8902 }
8903 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8904 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8905 goto err_free;
8906 }
8907
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008908 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08008909 urecord += urec_size;
8910 }
8911
Yonghong Songba64e7d2018-11-24 23:20:44 -08008912 prog->aux->func_info = krecord;
8913 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008914 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08008915 return 0;
8916
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008917err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08008918 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008919 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08008920 return ret;
8921}
8922
Yonghong Songba64e7d2018-11-24 23:20:44 -08008923static void adjust_btf_func(struct bpf_verifier_env *env)
8924{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008925 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008926 int i;
8927
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008928 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08008929 return;
8930
8931 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008932 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008933}
8934
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008935#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8936 sizeof(((struct bpf_line_info *)(0))->line_col))
8937#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8938
8939static int check_btf_line(struct bpf_verifier_env *env,
8940 const union bpf_attr *attr,
8941 union bpf_attr __user *uattr)
8942{
8943 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8944 struct bpf_subprog_info *sub;
8945 struct bpf_line_info *linfo;
8946 struct bpf_prog *prog;
8947 const struct btf *btf;
8948 void __user *ulinfo;
8949 int err;
8950
8951 nr_linfo = attr->line_info_cnt;
8952 if (!nr_linfo)
8953 return 0;
8954
8955 rec_size = attr->line_info_rec_size;
8956 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8957 rec_size > MAX_LINEINFO_REC_SIZE ||
8958 rec_size & (sizeof(u32) - 1))
8959 return -EINVAL;
8960
8961 /* Need to zero it in case the userspace may
8962 * pass in a smaller bpf_line_info object.
8963 */
8964 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8965 GFP_KERNEL | __GFP_NOWARN);
8966 if (!linfo)
8967 return -ENOMEM;
8968
8969 prog = env->prog;
8970 btf = prog->aux->btf;
8971
8972 s = 0;
8973 sub = env->subprog_info;
8974 ulinfo = u64_to_user_ptr(attr->line_info);
8975 expected_size = sizeof(struct bpf_line_info);
8976 ncopy = min_t(u32, expected_size, rec_size);
8977 for (i = 0; i < nr_linfo; i++) {
8978 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8979 if (err) {
8980 if (err == -E2BIG) {
8981 verbose(env, "nonzero tailing record in line_info");
8982 if (put_user(expected_size,
8983 &uattr->line_info_rec_size))
8984 err = -EFAULT;
8985 }
8986 goto err_free;
8987 }
8988
8989 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8990 err = -EFAULT;
8991 goto err_free;
8992 }
8993
8994 /*
8995 * Check insn_off to ensure
8996 * 1) strictly increasing AND
8997 * 2) bounded by prog->len
8998 *
8999 * The linfo[0].insn_off == 0 check logically falls into
9000 * the later "missing bpf_line_info for func..." case
9001 * because the first linfo[0].insn_off must be the
9002 * first sub also and the first sub must have
9003 * subprog_info[0].start == 0.
9004 */
9005 if ((i && linfo[i].insn_off <= prev_offset) ||
9006 linfo[i].insn_off >= prog->len) {
9007 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
9008 i, linfo[i].insn_off, prev_offset,
9009 prog->len);
9010 err = -EINVAL;
9011 goto err_free;
9012 }
9013
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08009014 if (!prog->insnsi[linfo[i].insn_off].code) {
9015 verbose(env,
9016 "Invalid insn code at line_info[%u].insn_off\n",
9017 i);
9018 err = -EINVAL;
9019 goto err_free;
9020 }
9021
Martin KaFai Lau23127b32018-12-13 10:41:46 -08009022 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
9023 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009024 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
9025 err = -EINVAL;
9026 goto err_free;
9027 }
9028
9029 if (s != env->subprog_cnt) {
9030 if (linfo[i].insn_off == sub[s].start) {
9031 sub[s].linfo_idx = i;
9032 s++;
9033 } else if (sub[s].start < linfo[i].insn_off) {
9034 verbose(env, "missing bpf_line_info for func#%u\n", s);
9035 err = -EINVAL;
9036 goto err_free;
9037 }
9038 }
9039
9040 prev_offset = linfo[i].insn_off;
9041 ulinfo += rec_size;
9042 }
9043
9044 if (s != env->subprog_cnt) {
9045 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9046 env->subprog_cnt - s, s);
9047 err = -EINVAL;
9048 goto err_free;
9049 }
9050
9051 prog->aux->linfo = linfo;
9052 prog->aux->nr_linfo = nr_linfo;
9053
9054 return 0;
9055
9056err_free:
9057 kvfree(linfo);
9058 return err;
9059}
9060
9061static int check_btf_info(struct bpf_verifier_env *env,
9062 const union bpf_attr *attr,
9063 union bpf_attr __user *uattr)
9064{
9065 struct btf *btf;
9066 int err;
9067
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009068 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9069 if (check_abnormal_return(env))
9070 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009071 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009072 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009073
9074 btf = btf_get_by_fd(attr->prog_btf_fd);
9075 if (IS_ERR(btf))
9076 return PTR_ERR(btf);
9077 env->prog->aux->btf = btf;
9078
9079 err = check_btf_func(env, attr, uattr);
9080 if (err)
9081 return err;
9082
9083 err = check_btf_line(env, attr, uattr);
9084 if (err)
9085 return err;
9086
9087 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009088}
9089
Edward Creef1174f72017-08-07 15:26:19 +01009090/* check %cur's range satisfies %old's */
9091static bool range_within(struct bpf_reg_state *old,
9092 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009093{
Edward Creeb03c9f92017-08-07 15:26:36 +01009094 return old->umin_value <= cur->umin_value &&
9095 old->umax_value >= cur->umax_value &&
9096 old->smin_value <= cur->smin_value &&
Daniel Borkmannfd675182021-02-05 20:48:21 +01009097 old->smax_value >= cur->smax_value &&
9098 old->u32_min_value <= cur->u32_min_value &&
9099 old->u32_max_value >= cur->u32_max_value &&
9100 old->s32_min_value <= cur->s32_min_value &&
9101 old->s32_max_value >= cur->s32_max_value;
Edward Creef1174f72017-08-07 15:26:19 +01009102}
9103
9104/* Maximum number of register states that can exist at once */
9105#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9106struct idpair {
9107 u32 old;
9108 u32 cur;
9109};
9110
9111/* If in the old state two registers had the same id, then they need to have
9112 * the same id in the new state as well. But that id could be different from
9113 * the old state, so we need to track the mapping from old to new ids.
9114 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9115 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9116 * regs with a different old id could still have new id 9, we don't care about
9117 * that.
9118 * So we look through our idmap to see if this old id has been seen before. If
9119 * so, we require the new id to match; otherwise, we add the id pair to the map.
9120 */
9121static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9122{
9123 unsigned int i;
9124
9125 for (i = 0; i < ID_MAP_SIZE; i++) {
9126 if (!idmap[i].old) {
9127 /* Reached an empty slot; haven't seen this id before */
9128 idmap[i].old = old_id;
9129 idmap[i].cur = cur_id;
9130 return true;
9131 }
9132 if (idmap[i].old == old_id)
9133 return idmap[i].cur == cur_id;
9134 }
9135 /* We ran out of idmap slots, which should be impossible */
9136 WARN_ON_ONCE(1);
9137 return false;
9138}
9139
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009140static void clean_func_state(struct bpf_verifier_env *env,
9141 struct bpf_func_state *st)
9142{
9143 enum bpf_reg_liveness live;
9144 int i, j;
9145
9146 for (i = 0; i < BPF_REG_FP; i++) {
9147 live = st->regs[i].live;
9148 /* liveness must not touch this register anymore */
9149 st->regs[i].live |= REG_LIVE_DONE;
9150 if (!(live & REG_LIVE_READ))
9151 /* since the register is unused, clear its state
9152 * to make further comparison simpler
9153 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009154 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009155 }
9156
9157 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9158 live = st->stack[i].spilled_ptr.live;
9159 /* liveness must not touch this stack slot anymore */
9160 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9161 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009162 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009163 for (j = 0; j < BPF_REG_SIZE; j++)
9164 st->stack[i].slot_type[j] = STACK_INVALID;
9165 }
9166 }
9167}
9168
9169static void clean_verifier_state(struct bpf_verifier_env *env,
9170 struct bpf_verifier_state *st)
9171{
9172 int i;
9173
9174 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9175 /* all regs in this state in all frames were already marked */
9176 return;
9177
9178 for (i = 0; i <= st->curframe; i++)
9179 clean_func_state(env, st->frame[i]);
9180}
9181
9182/* the parentage chains form a tree.
9183 * the verifier states are added to state lists at given insn and
9184 * pushed into state stack for future exploration.
9185 * when the verifier reaches bpf_exit insn some of the verifer states
9186 * stored in the state lists have their final liveness state already,
9187 * but a lot of states will get revised from liveness point of view when
9188 * the verifier explores other branches.
9189 * Example:
9190 * 1: r0 = 1
9191 * 2: if r1 == 100 goto pc+1
9192 * 3: r0 = 2
9193 * 4: exit
9194 * when the verifier reaches exit insn the register r0 in the state list of
9195 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9196 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9197 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9198 *
9199 * Since the verifier pushes the branch states as it sees them while exploring
9200 * the program the condition of walking the branch instruction for the second
9201 * time means that all states below this branch were already explored and
9202 * their final liveness markes are already propagated.
9203 * Hence when the verifier completes the search of state list in is_state_visited()
9204 * we can call this clean_live_states() function to mark all liveness states
9205 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9206 * will not be used.
9207 * This function also clears the registers and stack for states that !READ
9208 * to simplify state merging.
9209 *
9210 * Important note here that walking the same branch instruction in the callee
9211 * doesn't meant that the states are DONE. The verifier has to compare
9212 * the callsites
9213 */
9214static void clean_live_states(struct bpf_verifier_env *env, int insn,
9215 struct bpf_verifier_state *cur)
9216{
9217 struct bpf_verifier_state_list *sl;
9218 int i;
9219
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009220 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009221 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009222 if (sl->state.branches)
9223 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009224 if (sl->state.insn_idx != insn ||
9225 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009226 goto next;
9227 for (i = 0; i <= cur->curframe; i++)
9228 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9229 goto next;
9230 clean_verifier_state(env, &sl->state);
9231next:
9232 sl = sl->next;
9233 }
9234}
9235
Edward Creef1174f72017-08-07 15:26:19 +01009236/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01009237static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9238 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009239{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009240 bool equal;
9241
Edward Creedc503a82017-08-15 20:34:35 +01009242 if (!(rold->live & REG_LIVE_READ))
9243 /* explored state didn't use this */
9244 return true;
9245
Edward Cree679c7822018-08-22 20:02:19 +01009246 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009247
9248 if (rold->type == PTR_TO_STACK)
9249 /* two stack pointers are equal only if they're pointing to
9250 * the same stack frame, since fp-8 in foo != fp-8 in bar
9251 */
9252 return equal && rold->frameno == rcur->frameno;
9253
9254 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01009255 return true;
9256
9257 if (rold->type == NOT_INIT)
9258 /* explored state can't have used this */
9259 return true;
9260 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009261 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009262 switch (rold->type) {
9263 case SCALAR_VALUE:
9264 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009265 if (!rold->precise && !rcur->precise)
9266 return true;
Edward Creef1174f72017-08-07 15:26:19 +01009267 /* new val must satisfy old val knowledge */
9268 return range_within(rold, rcur) &&
9269 tnum_in(rold->var_off, rcur->var_off);
9270 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08009271 /* We're trying to use a pointer in place of a scalar.
9272 * Even if the scalar was unbounded, this could lead to
9273 * pointer leaks because scalars are allowed to leak
9274 * while pointers are not. We could make this safe in
9275 * special cases if root is calling us, but it's
9276 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01009277 */
Jann Horn179d1c52017-12-18 20:11:59 -08009278 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009279 }
9280 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01009281 /* If the new min/max/var_off satisfy the old ones and
9282 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009283 * 'id' is not compared, since it's only used for maps with
9284 * bpf_spin_lock inside map element and in such cases if
9285 * the rest of the prog is valid for one map element then
9286 * it's valid for all map elements regardless of the key
9287 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01009288 */
9289 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9290 range_within(rold, rcur) &&
9291 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01009292 case PTR_TO_MAP_VALUE_OR_NULL:
9293 /* a PTR_TO_MAP_VALUE could be safe to use as a
9294 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9295 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9296 * checked, doing so could have affected others with the same
9297 * id, and we can't check for that because we lost the id when
9298 * we converted to a PTR_TO_MAP_VALUE.
9299 */
9300 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9301 return false;
9302 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9303 return false;
9304 /* Check our ids match any regs they're supposed to */
9305 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009306 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01009307 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009308 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01009309 return false;
9310 /* We must have at least as much range as the old ptr
9311 * did, so that any accesses which were safe before are
9312 * still safe. This is true even if old range < old off,
9313 * since someone could have accessed through (ptr - k), or
9314 * even done ptr -= k in a register, to get a safe access.
9315 */
9316 if (rold->range > rcur->range)
9317 return false;
9318 /* If the offsets don't match, we can't trust our alignment;
9319 * nor can we be sure that we won't fall out of range.
9320 */
9321 if (rold->off != rcur->off)
9322 return false;
9323 /* id relations must be preserved */
9324 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9325 return false;
9326 /* new val must satisfy old val knowledge */
9327 return range_within(rold, rcur) &&
9328 tnum_in(rold->var_off, rcur->var_off);
9329 case PTR_TO_CTX:
9330 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01009331 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07009332 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07009333 case PTR_TO_SOCKET:
9334 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009335 case PTR_TO_SOCK_COMMON:
9336 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009337 case PTR_TO_TCP_SOCK:
9338 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009339 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01009340 /* Only valid matches are exact, which memcmp() above
9341 * would have accepted
9342 */
9343 default:
9344 /* Don't know what's going on, just say it's not safe */
9345 return false;
9346 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009347
Edward Creef1174f72017-08-07 15:26:19 +01009348 /* Shouldn't get here; if we do, say it's not safe */
9349 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009350 return false;
9351}
9352
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009353static bool stacksafe(struct bpf_func_state *old,
9354 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009355 struct idpair *idmap)
9356{
9357 int i, spi;
9358
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009359 /* walk slots of the explored stack and ignore any additional
9360 * slots in the current stack, since explored(safe) state
9361 * didn't use them
9362 */
9363 for (i = 0; i < old->allocated_stack; i++) {
9364 spi = i / BPF_REG_SIZE;
9365
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009366 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9367 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009368 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00009369 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009370 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009371
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009372 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9373 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08009374
9375 /* explored stack has more populated slots than current stack
9376 * and these slots were used
9377 */
9378 if (i >= cur->allocated_stack)
9379 return false;
9380
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009381 /* if old state was safe with misc data in the stack
9382 * it will be safe with zero-initialized stack.
9383 * The opposite is not true
9384 */
9385 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9386 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9387 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009388 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9389 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9390 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07009391 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009392 * this verifier states are not equivalent,
9393 * return false to continue verification of this path
9394 */
9395 return false;
9396 if (i % BPF_REG_SIZE)
9397 continue;
9398 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9399 continue;
9400 if (!regsafe(&old->stack[spi].spilled_ptr,
9401 &cur->stack[spi].spilled_ptr,
9402 idmap))
9403 /* when explored and current stack slot are both storing
9404 * spilled registers, check that stored pointers types
9405 * are the same as well.
9406 * Ex: explored safe path could have stored
9407 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9408 * but current path has stored:
9409 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9410 * such verifier states are not equivalent.
9411 * return false to continue verification of this path
9412 */
9413 return false;
9414 }
9415 return true;
9416}
9417
Joe Stringerfd978bf72018-10-02 13:35:35 -07009418static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9419{
9420 if (old->acquired_refs != cur->acquired_refs)
9421 return false;
9422 return !memcmp(old->refs, cur->refs,
9423 sizeof(*old->refs) * old->acquired_refs);
9424}
9425
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009426/* compare two verifier states
9427 *
9428 * all states stored in state_list are known to be valid, since
9429 * verifier reached 'bpf_exit' instruction through them
9430 *
9431 * this function is called when verifier exploring different branches of
9432 * execution popped from the state stack. If it sees an old state that has
9433 * more strict register state and more strict stack state then this execution
9434 * branch doesn't need to be explored further, since verifier already
9435 * concluded that more strict state leads to valid finish.
9436 *
9437 * Therefore two states are equivalent if register state is more conservative
9438 * and explored stack state is more conservative than the current one.
9439 * Example:
9440 * explored current
9441 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9442 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9443 *
9444 * In other words if current stack state (one being explored) has more
9445 * valid slots than old one that already passed validation, it means
9446 * the verifier can stop exploring and conclude that current state is valid too
9447 *
9448 * Similarly with registers. If explored state has register type as invalid
9449 * whereas register type in current state is meaningful, it means that
9450 * the current state will reach 'bpf_exit' instruction safely
9451 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009452static bool func_states_equal(struct bpf_func_state *old,
9453 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009454{
Edward Creef1174f72017-08-07 15:26:19 +01009455 struct idpair *idmap;
9456 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009457 int i;
9458
Edward Creef1174f72017-08-07 15:26:19 +01009459 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9460 /* If we failed to allocate the idmap, just say it's not safe */
9461 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009462 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009463
9464 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01009465 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01009466 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009467 }
9468
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009469 if (!stacksafe(old, cur, idmap))
9470 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009471
9472 if (!refsafe(old, cur))
9473 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01009474 ret = true;
9475out_free:
9476 kfree(idmap);
9477 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009478}
9479
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009480static bool states_equal(struct bpf_verifier_env *env,
9481 struct bpf_verifier_state *old,
9482 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01009483{
Edward Creedc503a82017-08-15 20:34:35 +01009484 int i;
9485
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009486 if (old->curframe != cur->curframe)
9487 return false;
9488
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009489 /* Verification state from speculative execution simulation
9490 * must never prune a non-speculative execution one.
9491 */
9492 if (old->speculative && !cur->speculative)
9493 return false;
9494
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009495 if (old->active_spin_lock != cur->active_spin_lock)
9496 return false;
9497
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009498 /* for states to be equal callsites have to be the same
9499 * and all frame states need to be equivalent
9500 */
9501 for (i = 0; i <= old->curframe; i++) {
9502 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9503 return false;
9504 if (!func_states_equal(old->frame[i], cur->frame[i]))
9505 return false;
9506 }
9507 return true;
9508}
9509
Jiong Wang5327ed32019-05-24 23:25:12 +01009510/* Return 0 if no propagation happened. Return negative error code if error
9511 * happened. Otherwise, return the propagated bit.
9512 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009513static int propagate_liveness_reg(struct bpf_verifier_env *env,
9514 struct bpf_reg_state *reg,
9515 struct bpf_reg_state *parent_reg)
9516{
Jiong Wang5327ed32019-05-24 23:25:12 +01009517 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9518 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009519 int err;
9520
Jiong Wang5327ed32019-05-24 23:25:12 +01009521 /* When comes here, read flags of PARENT_REG or REG could be any of
9522 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9523 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9524 */
9525 if (parent_flag == REG_LIVE_READ64 ||
9526 /* Or if there is no read flag from REG. */
9527 !flag ||
9528 /* Or if the read flag from REG is the same as PARENT_REG. */
9529 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009530 return 0;
9531
Jiong Wang5327ed32019-05-24 23:25:12 +01009532 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009533 if (err)
9534 return err;
9535
Jiong Wang5327ed32019-05-24 23:25:12 +01009536 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009537}
9538
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009539/* A write screens off any subsequent reads; but write marks come from the
9540 * straight-line code between a state and its parent. When we arrive at an
9541 * equivalent state (jump target or such) we didn't arrive by the straight-line
9542 * code, so read marks in the state must propagate to the parent regardless
9543 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01009544 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009545 */
9546static int propagate_liveness(struct bpf_verifier_env *env,
9547 const struct bpf_verifier_state *vstate,
9548 struct bpf_verifier_state *vparent)
9549{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009550 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009551 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009552 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009553
9554 if (vparent->curframe != vstate->curframe) {
9555 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9556 vparent->curframe, vstate->curframe);
9557 return -EFAULT;
9558 }
Edward Creedc503a82017-08-15 20:34:35 +01009559 /* Propagate read liveness of registers... */
9560 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07009561 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009562 parent = vparent->frame[frame];
9563 state = vstate->frame[frame];
9564 parent_reg = parent->regs;
9565 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07009566 /* We don't need to worry about FP liveness, it's read-only */
9567 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009568 err = propagate_liveness_reg(env, &state_reg[i],
9569 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01009570 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009571 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01009572 if (err == REG_LIVE_READ64)
9573 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009574 }
Edward Creedc503a82017-08-15 20:34:35 +01009575
Jiong Wang1b04aee2019-04-12 22:59:34 +01009576 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009577 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9578 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009579 parent_reg = &parent->stack[i].spilled_ptr;
9580 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009581 err = propagate_liveness_reg(env, state_reg,
9582 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01009583 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009584 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009585 }
Edward Creedc503a82017-08-15 20:34:35 +01009586 }
Jiong Wang5327ed32019-05-24 23:25:12 +01009587 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01009588}
9589
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009590/* find precise scalars in the previous equivalent state and
9591 * propagate them into the current state
9592 */
9593static int propagate_precision(struct bpf_verifier_env *env,
9594 const struct bpf_verifier_state *old)
9595{
9596 struct bpf_reg_state *state_reg;
9597 struct bpf_func_state *state;
9598 int i, err = 0;
9599
9600 state = old->frame[old->curframe];
9601 state_reg = state->regs;
9602 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9603 if (state_reg->type != SCALAR_VALUE ||
9604 !state_reg->precise)
9605 continue;
9606 if (env->log.level & BPF_LOG_LEVEL2)
9607 verbose(env, "propagating r%d\n", i);
9608 err = mark_chain_precision(env, i);
9609 if (err < 0)
9610 return err;
9611 }
9612
9613 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9614 if (state->stack[i].slot_type[0] != STACK_SPILL)
9615 continue;
9616 state_reg = &state->stack[i].spilled_ptr;
9617 if (state_reg->type != SCALAR_VALUE ||
9618 !state_reg->precise)
9619 continue;
9620 if (env->log.level & BPF_LOG_LEVEL2)
9621 verbose(env, "propagating fp%d\n",
9622 (-i - 1) * BPF_REG_SIZE);
9623 err = mark_chain_precision_stack(env, i);
9624 if (err < 0)
9625 return err;
9626 }
9627 return 0;
9628}
9629
Alexei Starovoitov25897262019-06-15 12:12:20 -07009630static bool states_maybe_looping(struct bpf_verifier_state *old,
9631 struct bpf_verifier_state *cur)
9632{
9633 struct bpf_func_state *fold, *fcur;
9634 int i, fr = cur->curframe;
9635
9636 if (old->curframe != fr)
9637 return false;
9638
9639 fold = old->frame[fr];
9640 fcur = cur->frame[fr];
9641 for (i = 0; i < MAX_BPF_REG; i++)
9642 if (memcmp(&fold->regs[i], &fcur->regs[i],
9643 offsetof(struct bpf_reg_state, parent)))
9644 return false;
9645 return true;
9646}
9647
9648
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009649static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009650{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009651 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009652 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01009653 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009654 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07009655 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009656
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009657 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009658 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009659 /* this 'insn_idx' instruction wasn't marked, so we will not
9660 * be doing state search here
9661 */
9662 return 0;
9663
Alexei Starovoitov25897262019-06-15 12:12:20 -07009664 /* bpf progs typically have pruning point every 4 instructions
9665 * http://vger.kernel.org/bpfconf2019.html#session-1
9666 * Do not add new state for future pruning if the verifier hasn't seen
9667 * at least 2 jumps and at least 8 instructions.
9668 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9669 * In tests that amounts to up to 50% reduction into total verifier
9670 * memory consumption and 20% verifier time speedup.
9671 */
9672 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9673 env->insn_processed - env->prev_insn_processed >= 8)
9674 add_new_state = true;
9675
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009676 pprev = explored_state(env, insn_idx);
9677 sl = *pprev;
9678
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009679 clean_live_states(env, insn_idx, cur);
9680
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009681 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009682 states_cnt++;
9683 if (sl->state.insn_idx != insn_idx)
9684 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009685 if (sl->state.branches) {
9686 if (states_maybe_looping(&sl->state, cur) &&
9687 states_equal(env, &sl->state, cur)) {
9688 verbose_linfo(env, insn_idx, "; ");
9689 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9690 return -EINVAL;
9691 }
9692 /* if the verifier is processing a loop, avoid adding new state
9693 * too often, since different loop iterations have distinct
9694 * states and may not help future pruning.
9695 * This threshold shouldn't be too low to make sure that
9696 * a loop with large bound will be rejected quickly.
9697 * The most abusive loop will be:
9698 * r1 += 1
9699 * if r1 < 1000000 goto pc-2
9700 * 1M insn_procssed limit / 100 == 10k peak states.
9701 * This threshold shouldn't be too high either, since states
9702 * at the end of the loop are likely to be useful in pruning.
9703 */
9704 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9705 env->insn_processed - env->prev_insn_processed < 100)
9706 add_new_state = false;
9707 goto miss;
9708 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009709 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009710 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009711 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01009712 * prune the search.
9713 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009714 * If we have any write marks in env->cur_state, they
9715 * will prevent corresponding reads in the continuation
9716 * from reaching our parent (an explored_state). Our
9717 * own state will get the read marks recorded, but
9718 * they'll be immediately forgotten as we're pruning
9719 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009720 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009721 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009722
9723 /* if previous state reached the exit with precision and
9724 * current state is equivalent to it (except precsion marks)
9725 * the precision needs to be propagated back in
9726 * the current state.
9727 */
9728 err = err ? : push_jmp_history(env, cur);
9729 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009730 if (err)
9731 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009732 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01009733 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07009734miss:
9735 /* when new state is not going to be added do not increase miss count.
9736 * Otherwise several loop iterations will remove the state
9737 * recorded earlier. The goal of these heuristics is to have
9738 * states from some iterations of the loop (some in the beginning
9739 * and some at the end) to help pruning.
9740 */
9741 if (add_new_state)
9742 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009743 /* heuristic to determine whether this state is beneficial
9744 * to keep checking from state equivalence point of view.
9745 * Higher numbers increase max_states_per_insn and verification time,
9746 * but do not meaningfully decrease insn_processed.
9747 */
9748 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9749 /* the state is unlikely to be useful. Remove it to
9750 * speed up verification
9751 */
9752 *pprev = sl->next;
9753 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009754 u32 br = sl->state.branches;
9755
9756 WARN_ONCE(br,
9757 "BUG live_done but branches_to_explore %d\n",
9758 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009759 free_verifier_state(&sl->state, false);
9760 kfree(sl);
9761 env->peak_states--;
9762 } else {
9763 /* cannot free this state, since parentage chain may
9764 * walk it later. Add it for free_list instead to
9765 * be freed at the end of verification
9766 */
9767 sl->next = env->free_list;
9768 env->free_list = sl;
9769 }
9770 sl = *pprev;
9771 continue;
9772 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009773next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009774 pprev = &sl->next;
9775 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009776 }
9777
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009778 if (env->max_states_per_insn < states_cnt)
9779 env->max_states_per_insn = states_cnt;
9780
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009781 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009782 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009783
Alexei Starovoitov25897262019-06-15 12:12:20 -07009784 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009785 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07009786
9787 /* There were no equivalent states, remember the current one.
9788 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009789 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009790 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009791 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009792 * again on the way to bpf_exit.
9793 * When looping the sl->state.branches will be > 0 and this state
9794 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009795 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009796 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009797 if (!new_sl)
9798 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009799 env->total_states++;
9800 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009801 env->prev_jmps_processed = env->jmps_processed;
9802 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009803
9804 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01009805 new = &new_sl->state;
9806 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009807 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01009808 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009809 kfree(new_sl);
9810 return err;
9811 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009812 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009813 WARN_ONCE(new->branches != 1,
9814 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009815
Alexei Starovoitov25897262019-06-15 12:12:20 -07009816 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009817 cur->first_insn_idx = insn_idx;
9818 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009819 new_sl->next = *explored_state(env, insn_idx);
9820 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08009821 /* connect new state to parentage chain. Current frame needs all
9822 * registers connected. Only r6 - r9 of the callers are alive (pushed
9823 * to the stack implicitly by JITs) so in callers' frames connect just
9824 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9825 * the state of the call instruction (with WRITTEN set), and r0 comes
9826 * from callee with its full parentage chain, anyway.
9827 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009828 /* clear write marks in current state: the writes we did are not writes
9829 * our child did, so they don't screen off its reads from us.
9830 * (There are no read marks in current state, because reads always mark
9831 * their parent and current state never has children yet. Only
9832 * explored_states can get read marks.)
9833 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07009834 for (j = 0; j <= cur->curframe; j++) {
9835 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9836 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9837 for (i = 0; i < BPF_REG_FP; i++)
9838 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9839 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009840
9841 /* all stack frames are accessible from callee, clear them all */
9842 for (j = 0; j <= cur->curframe; j++) {
9843 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01009844 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009845
Edward Cree679c7822018-08-22 20:02:19 +01009846 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009847 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01009848 frame->stack[i].spilled_ptr.parent =
9849 &newframe->stack[i].spilled_ptr;
9850 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009851 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009852 return 0;
9853}
9854
Joe Stringerc64b7982018-10-02 13:35:33 -07009855/* Return true if it's OK to have the same insn return a different type. */
9856static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9857{
9858 switch (type) {
9859 case PTR_TO_CTX:
9860 case PTR_TO_SOCKET:
9861 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009862 case PTR_TO_SOCK_COMMON:
9863 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009864 case PTR_TO_TCP_SOCK:
9865 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009866 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07009867 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07009868 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -07009869 return false;
9870 default:
9871 return true;
9872 }
9873}
9874
9875/* If an instruction was previously used with particular pointer types, then we
9876 * need to be careful to avoid cases such as the below, where it may be ok
9877 * for one branch accessing the pointer, but not ok for the other branch:
9878 *
9879 * R1 = sock_ptr
9880 * goto X;
9881 * ...
9882 * R1 = some_other_valid_ptr;
9883 * goto X;
9884 * ...
9885 * R2 = *(u32 *)(R1 + 0);
9886 */
9887static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9888{
9889 return src != prev && (!reg_type_mismatch_ok(src) ||
9890 !reg_type_mismatch_ok(prev));
9891}
9892
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009893static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009894{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009895 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009896 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009897 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009898 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009899 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009900 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009901 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009902
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009903 for (;;) {
9904 struct bpf_insn *insn;
9905 u8 class;
9906 int err;
9907
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009908 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009909 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009910 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009911 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009912 return -EFAULT;
9913 }
9914
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009915 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009916 class = BPF_CLASS(insn->code);
9917
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009918 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009919 verbose(env,
9920 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009921 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009922 return -E2BIG;
9923 }
9924
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009925 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009926 if (err < 0)
9927 return err;
9928 if (err == 1) {
9929 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009930 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009931 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009932 verbose(env, "\nfrom %d to %d%s: safe\n",
9933 env->prev_insn_idx, env->insn_idx,
9934 env->cur_state->speculative ?
9935 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009936 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009937 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009938 }
9939 goto process_bpf_exit;
9940 }
9941
Alexei Starovoitovc3494802018-12-03 22:46:04 -08009942 if (signal_pending(current))
9943 return -EAGAIN;
9944
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02009945 if (need_resched())
9946 cond_resched();
9947
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009948 if (env->log.level & BPF_LOG_LEVEL2 ||
9949 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9950 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009951 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07009952 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009953 verbose(env, "\nfrom %d to %d%s:",
9954 env->prev_insn_idx, env->insn_idx,
9955 env->cur_state->speculative ?
9956 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009957 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009958 do_print_state = false;
9959 }
9960
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009961 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009962 const struct bpf_insn_cbs cbs = {
9963 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01009964 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01009965 };
9966
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009967 verbose_linfo(env, env->insn_idx, "; ");
9968 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01009969 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009970 }
9971
Jakub Kicinskicae19272017-12-27 18:39:05 -08009972 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009973 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9974 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08009975 if (err)
9976 return err;
9977 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01009978
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009979 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009980 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009981 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009982
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009983 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009984 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009985 if (err)
9986 return err;
9987
9988 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009989 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009990
9991 /* check for reserved fields is already done */
9992
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009993 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009994 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009995 if (err)
9996 return err;
9997
Edward Creedc503a82017-08-15 20:34:35 +01009998 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009999 if (err)
10000 return err;
10001
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -070010002 src_reg_type = regs[insn->src_reg].type;
10003
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010004 /* check that memory (src_reg + off) is readable,
10005 * the state of dst_reg will be updated by this func
10006 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010007 err = check_mem_access(env, env->insn_idx, insn->src_reg,
10008 insn->off, BPF_SIZE(insn->code),
10009 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010010 if (err)
10011 return err;
10012
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010013 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010014
10015 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010016 /* saw a valid insn
10017 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010018 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010019 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010020 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010021
Joe Stringerc64b7982018-10-02 13:35:33 -070010022 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010023 /* ABuser program is trying to use the same insn
10024 * dst_reg = *(u32*) (src_reg + off)
10025 * with different pointer types:
10026 * src_reg == ctx in one branch and
10027 * src_reg == stack|map in some other branch.
10028 * Reject it.
10029 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010030 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010031 return -EINVAL;
10032 }
10033
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010034 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010035 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010036
Brendan Jackman91c960b2021-01-14 18:17:44 +000010037 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
10038 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010039 if (err)
10040 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010041 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010042 continue;
10043 }
10044
Brendan Jackman5ca419f2021-01-14 18:17:46 +000010045 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
10046 verbose(env, "BPF_STX uses reserved fields\n");
10047 return -EINVAL;
10048 }
10049
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010050 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010051 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010052 if (err)
10053 return err;
10054 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010055 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010056 if (err)
10057 return err;
10058
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010059 dst_reg_type = regs[insn->dst_reg].type;
10060
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010061 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010062 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10063 insn->off, BPF_SIZE(insn->code),
10064 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010065 if (err)
10066 return err;
10067
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010068 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010069
10070 if (*prev_dst_type == NOT_INIT) {
10071 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070010072 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010073 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010074 return -EINVAL;
10075 }
10076
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010077 } else if (class == BPF_ST) {
10078 if (BPF_MODE(insn->code) != BPF_MEM ||
10079 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010080 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010081 return -EINVAL;
10082 }
10083 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010084 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010085 if (err)
10086 return err;
10087
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010088 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070010089 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020010090 insn->dst_reg,
10091 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010092 return -EACCES;
10093 }
10094
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010095 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010096 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10097 insn->off, BPF_SIZE(insn->code),
10098 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010099 if (err)
10100 return err;
10101
Jiong Wang092ed092019-01-26 12:26:01 -050010102 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010103 u8 opcode = BPF_OP(insn->code);
10104
Alexei Starovoitov25897262019-06-15 12:12:20 -070010105 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010106 if (opcode == BPF_CALL) {
10107 if (BPF_SRC(insn->code) != BPF_K ||
10108 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010109 (insn->src_reg != BPF_REG_0 &&
10110 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050010111 insn->dst_reg != BPF_REG_0 ||
10112 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010113 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010114 return -EINVAL;
10115 }
10116
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010117 if (env->cur_state->active_spin_lock &&
10118 (insn->src_reg == BPF_PSEUDO_CALL ||
10119 insn->imm != BPF_FUNC_spin_unlock)) {
10120 verbose(env, "function calls are not allowed while holding a lock\n");
10121 return -EINVAL;
10122 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010123 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010124 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010125 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010126 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010127 if (err)
10128 return err;
10129
10130 } else if (opcode == BPF_JA) {
10131 if (BPF_SRC(insn->code) != BPF_K ||
10132 insn->imm != 0 ||
10133 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010134 insn->dst_reg != BPF_REG_0 ||
10135 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010136 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010137 return -EINVAL;
10138 }
10139
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010140 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010141 continue;
10142
10143 } else if (opcode == BPF_EXIT) {
10144 if (BPF_SRC(insn->code) != BPF_K ||
10145 insn->imm != 0 ||
10146 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010147 insn->dst_reg != BPF_REG_0 ||
10148 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010149 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010150 return -EINVAL;
10151 }
10152
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010153 if (env->cur_state->active_spin_lock) {
10154 verbose(env, "bpf_spin_unlock is missing\n");
10155 return -EINVAL;
10156 }
10157
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010158 if (state->curframe) {
10159 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010160 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010161 if (err)
10162 return err;
10163 do_print_state = true;
10164 continue;
10165 }
10166
Joe Stringerfd978bf72018-10-02 13:35:35 -070010167 err = check_reference_leak(env);
10168 if (err)
10169 return err;
10170
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070010171 err = check_return_code(env);
10172 if (err)
10173 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010174process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -070010175 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010176 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010177 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010178 if (err < 0) {
10179 if (err != -ENOENT)
10180 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010181 break;
10182 } else {
10183 do_print_state = true;
10184 continue;
10185 }
10186 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010187 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010188 if (err)
10189 return err;
10190 }
10191 } else if (class == BPF_LD) {
10192 u8 mode = BPF_MODE(insn->code);
10193
10194 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080010195 err = check_ld_abs(env, insn);
10196 if (err)
10197 return err;
10198
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010199 } else if (mode == BPF_IMM) {
10200 err = check_ld_imm(env, insn);
10201 if (err)
10202 return err;
10203
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010204 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010205 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010206 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010207 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010208 return -EINVAL;
10209 }
10210 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010211 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010212 return -EINVAL;
10213 }
10214
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010215 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010216 }
10217
10218 return 0;
10219}
10220
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010221static int find_btf_percpu_datasec(struct btf *btf)
10222{
10223 const struct btf_type *t;
10224 const char *tname;
10225 int i, n;
10226
10227 /*
10228 * Both vmlinux and module each have their own ".data..percpu"
10229 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10230 * types to look at only module's own BTF types.
10231 */
10232 n = btf_nr_types(btf);
10233 if (btf_is_module(btf))
10234 i = btf_nr_types(btf_vmlinux);
10235 else
10236 i = 1;
10237
10238 for(; i < n; i++) {
10239 t = btf_type_by_id(btf, i);
10240 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10241 continue;
10242
10243 tname = btf_name_by_offset(btf, t->name_off);
10244 if (!strcmp(tname, ".data..percpu"))
10245 return i;
10246 }
10247
10248 return -ENOENT;
10249}
10250
Hao Luo4976b712020-09-29 16:50:44 -070010251/* replace pseudo btf_id with kernel symbol address */
10252static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10253 struct bpf_insn *insn,
10254 struct bpf_insn_aux_data *aux)
10255{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010256 const struct btf_var_secinfo *vsi;
10257 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010258 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070010259 const struct btf_type *t;
10260 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010261 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010262 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010263 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010264 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070010265 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010266 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070010267
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010268 btf_fd = insn[1].imm;
10269 if (btf_fd) {
10270 btf = btf_get_by_fd(btf_fd);
10271 if (IS_ERR(btf)) {
10272 verbose(env, "invalid module BTF object FD specified.\n");
10273 return -EINVAL;
10274 }
10275 } else {
10276 if (!btf_vmlinux) {
10277 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10278 return -EINVAL;
10279 }
10280 btf = btf_vmlinux;
10281 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070010282 }
10283
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010284 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070010285 if (!t) {
10286 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010287 err = -ENOENT;
10288 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010289 }
10290
10291 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010292 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10293 err = -EINVAL;
10294 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010295 }
10296
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010297 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010298 addr = kallsyms_lookup_name(sym_name);
10299 if (!addr) {
10300 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10301 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010302 err = -ENOENT;
10303 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010304 }
10305
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010306 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010307 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010308 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010309 for_each_vsi(i, datasec, vsi) {
10310 if (vsi->type == id) {
10311 percpu = true;
10312 break;
10313 }
10314 }
10315 }
10316
Hao Luo4976b712020-09-29 16:50:44 -070010317 insn[0].imm = (u32)addr;
10318 insn[1].imm = addr >> 32;
10319
10320 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010321 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010322 if (percpu) {
10323 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010324 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010325 aux->btf_var.btf_id = type;
10326 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070010327 const struct btf_type *ret;
10328 const char *tname;
10329 u32 tsize;
10330
10331 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010332 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070010333 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010334 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010335 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10336 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010337 err = -EINVAL;
10338 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010339 }
10340 aux->btf_var.reg_type = PTR_TO_MEM;
10341 aux->btf_var.mem_size = tsize;
10342 } else {
10343 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010344 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070010345 aux->btf_var.btf_id = type;
10346 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010347
10348 /* check whether we recorded this BTF (and maybe module) already */
10349 for (i = 0; i < env->used_btf_cnt; i++) {
10350 if (env->used_btfs[i].btf == btf) {
10351 btf_put(btf);
10352 return 0;
10353 }
10354 }
10355
10356 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10357 err = -E2BIG;
10358 goto err_put;
10359 }
10360
10361 btf_mod = &env->used_btfs[env->used_btf_cnt];
10362 btf_mod->btf = btf;
10363 btf_mod->module = NULL;
10364
10365 /* if we reference variables from kernel module, bump its refcount */
10366 if (btf_is_module(btf)) {
10367 btf_mod->module = btf_try_get_module(btf);
10368 if (!btf_mod->module) {
10369 err = -ENXIO;
10370 goto err_put;
10371 }
10372 }
10373
10374 env->used_btf_cnt++;
10375
Hao Luo4976b712020-09-29 16:50:44 -070010376 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010377err_put:
10378 btf_put(btf);
10379 return err;
Hao Luo4976b712020-09-29 16:50:44 -070010380}
10381
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010382static int check_map_prealloc(struct bpf_map *map)
10383{
10384 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070010385 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10386 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010387 !(map->map_flags & BPF_F_NO_PREALLOC);
10388}
10389
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010390static bool is_tracing_prog_type(enum bpf_prog_type type)
10391{
10392 switch (type) {
10393 case BPF_PROG_TYPE_KPROBE:
10394 case BPF_PROG_TYPE_TRACEPOINT:
10395 case BPF_PROG_TYPE_PERF_EVENT:
10396 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10397 return true;
10398 default:
10399 return false;
10400 }
10401}
10402
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010403static bool is_preallocated_map(struct bpf_map *map)
10404{
10405 if (!check_map_prealloc(map))
10406 return false;
10407 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10408 return false;
10409 return true;
10410}
10411
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010412static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10413 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010414 struct bpf_prog *prog)
10415
10416{
Udip Pant7e407812020-08-25 16:20:00 -070010417 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010418 /*
10419 * Validate that trace type programs use preallocated hash maps.
10420 *
10421 * For programs attached to PERF events this is mandatory as the
10422 * perf NMI can hit any arbitrary code sequence.
10423 *
10424 * All other trace types using preallocated hash maps are unsafe as
10425 * well because tracepoint or kprobes can be inside locked regions
10426 * of the memory allocator or at a place where a recursion into the
10427 * memory allocator would see inconsistent state.
10428 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010429 * On RT enabled kernels run-time allocation of all trace type
10430 * programs is strictly prohibited due to lock type constraints. On
10431 * !RT kernels it is allowed for backwards compatibility reasons for
10432 * now, but warnings are emitted so developers are made aware of
10433 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010434 */
Udip Pant7e407812020-08-25 16:20:00 -070010435 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10436 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010437 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010438 return -EINVAL;
10439 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010440 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10441 verbose(env, "trace type programs can only use preallocated hash map\n");
10442 return -EINVAL;
10443 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010444 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10445 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 -070010446 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080010447
KP Singh9e7a4d92020-11-06 10:37:39 +000010448 if (map_value_has_spin_lock(map)) {
10449 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10450 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10451 return -EINVAL;
10452 }
10453
10454 if (is_tracing_prog_type(prog_type)) {
10455 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10456 return -EINVAL;
10457 }
10458
10459 if (prog->aux->sleepable) {
10460 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10461 return -EINVAL;
10462 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010463 }
10464
Jakub Kicinskia3884572018-01-11 20:29:09 -080010465 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070010466 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080010467 verbose(env, "offload device mismatch between prog and map\n");
10468 return -EINVAL;
10469 }
10470
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080010471 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10472 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10473 return -EINVAL;
10474 }
10475
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010476 if (prog->aux->sleepable)
10477 switch (map->map_type) {
10478 case BPF_MAP_TYPE_HASH:
10479 case BPF_MAP_TYPE_LRU_HASH:
10480 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010481 case BPF_MAP_TYPE_PERCPU_HASH:
10482 case BPF_MAP_TYPE_PERCPU_ARRAY:
10483 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10484 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10485 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010486 if (!is_preallocated_map(map)) {
10487 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010488 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010489 return -EINVAL;
10490 }
10491 break;
KP Singhba90c2c2021-02-04 19:36:21 +000010492 case BPF_MAP_TYPE_RINGBUF:
10493 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010494 default:
10495 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000010496 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010497 return -EINVAL;
10498 }
10499
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010500 return 0;
10501}
10502
Roman Gushchinb741f162018-09-28 14:45:43 +000010503static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10504{
10505 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10506 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10507}
10508
Hao Luo4976b712020-09-29 16:50:44 -070010509/* find and rewrite pseudo imm in ld_imm64 instructions:
10510 *
10511 * 1. if it accesses map FD, replace it with actual map pointer.
10512 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10513 *
10514 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010515 */
Hao Luo4976b712020-09-29 16:50:44 -070010516static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010517{
10518 struct bpf_insn *insn = env->prog->insnsi;
10519 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010520 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010521
Daniel Borkmannf1f77142017-01-13 23:38:15 +010010522 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010010523 if (err)
10524 return err;
10525
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010526 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010527 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010528 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010529 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010530 return -EINVAL;
10531 }
10532
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010533 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010534 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010535 struct bpf_map *map;
10536 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010537 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010538
10539 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10540 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10541 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010542 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010543 return -EINVAL;
10544 }
10545
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010546 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010547 /* valid generic load 64-bit imm */
10548 goto next_insn;
10549
Hao Luo4976b712020-09-29 16:50:44 -070010550 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10551 aux = &env->insn_aux_data[i];
10552 err = check_pseudo_btf_id(env, insn, aux);
10553 if (err)
10554 return err;
10555 goto next_insn;
10556 }
10557
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010558 /* In final convert_pseudo_ld_imm64() step, this is
10559 * converted into regular 64-bit imm load insn.
10560 */
10561 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10562 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10563 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10564 insn[1].imm != 0)) {
10565 verbose(env,
10566 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010567 return -EINVAL;
10568 }
10569
Daniel Borkmann20182392019-03-04 21:08:53 +010010570 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +010010571 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010572 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010573 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010010574 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010575 return PTR_ERR(map);
10576 }
10577
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010578 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010579 if (err) {
10580 fdput(f);
10581 return err;
10582 }
10583
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010584 aux = &env->insn_aux_data[i];
10585 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10586 addr = (unsigned long)map;
10587 } else {
10588 u32 off = insn[1].imm;
10589
10590 if (off >= BPF_MAX_VAR_OFF) {
10591 verbose(env, "direct value offset of %u is not allowed\n", off);
10592 fdput(f);
10593 return -EINVAL;
10594 }
10595
10596 if (!map->ops->map_direct_value_addr) {
10597 verbose(env, "no direct value access support for this map type\n");
10598 fdput(f);
10599 return -EINVAL;
10600 }
10601
10602 err = map->ops->map_direct_value_addr(map, &addr, off);
10603 if (err) {
10604 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10605 map->value_size, off);
10606 fdput(f);
10607 return err;
10608 }
10609
10610 aux->map_off = off;
10611 addr += off;
10612 }
10613
10614 insn[0].imm = (u32)addr;
10615 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010616
10617 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010618 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010619 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010620 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010621 fdput(f);
10622 goto next_insn;
10623 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010624 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010625
10626 if (env->used_map_cnt >= MAX_USED_MAPS) {
10627 fdput(f);
10628 return -E2BIG;
10629 }
10630
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010631 /* hold the map. If the program is rejected by verifier,
10632 * the map will be released by release_maps() or it
10633 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070010634 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010635 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080010636 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010637
10638 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070010639 env->used_maps[env->used_map_cnt++] = map;
10640
Roman Gushchinb741f162018-09-28 14:45:43 +000010641 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010010642 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000010643 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070010644 fdput(f);
10645 return -EBUSY;
10646 }
10647
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010648 fdput(f);
10649next_insn:
10650 insn++;
10651 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010010652 continue;
10653 }
10654
10655 /* Basic sanity check before we invest more work here. */
10656 if (!bpf_opcode_in_insntable(insn->code)) {
10657 verbose(env, "unknown opcode %02x\n", insn->code);
10658 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010659 }
10660 }
10661
10662 /* now all pseudo BPF_LD_IMM64 instructions load valid
10663 * 'struct bpf_map *' into a register instead of user map_fd.
10664 * These pointers will be used later by verifier to validate map access.
10665 */
10666 return 0;
10667}
10668
10669/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010670static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010671{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010010672 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10673 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010674}
10675
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010676/* drop refcnt of maps used by the rejected program */
10677static void release_btfs(struct bpf_verifier_env *env)
10678{
10679 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10680 env->used_btf_cnt);
10681}
10682
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010683/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010684static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010685{
10686 struct bpf_insn *insn = env->prog->insnsi;
10687 int insn_cnt = env->prog->len;
10688 int i;
10689
10690 for (i = 0; i < insn_cnt; i++, insn++)
10691 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10692 insn->src_reg = 0;
10693}
10694
Alexei Starovoitov80419022017-03-15 18:26:41 -070010695/* single env->prog->insni[off] instruction was replaced with the range
10696 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10697 * [0, off) and [off, end) to new locations, so the patched range stays zero
10698 */
Jiong Wangb325fbc2019-05-24 23:25:13 +010010699static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10700 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070010701{
10702 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010703 struct bpf_insn *insn = new_prog->insnsi;
10704 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010705 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010706
Jiong Wangb325fbc2019-05-24 23:25:13 +010010707 /* aux info at OFF always needs adjustment, no matter fast path
10708 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10709 * original insn at old prog.
10710 */
10711 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10712
Alexei Starovoitov80419022017-03-15 18:26:41 -070010713 if (cnt == 1)
10714 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010715 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -070010716 new_data = vzalloc(array_size(prog_len,
10717 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -070010718 if (!new_data)
10719 return -ENOMEM;
10720 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10721 memcpy(new_data + off + cnt - 1, old_data + off,
10722 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010010723 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010724 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010725 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10726 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070010727 env->insn_aux_data = new_data;
10728 vfree(old_data);
10729 return 0;
10730}
10731
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010732static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10733{
10734 int i;
10735
10736 if (len == 1)
10737 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010738 /* NOTE: fake 'exit' subprog should be updated as well. */
10739 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000010740 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010741 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040010742 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010743 }
10744}
10745
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010746static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10747{
10748 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10749 int i, sz = prog->aux->size_poke_tab;
10750 struct bpf_jit_poke_descriptor *desc;
10751
10752 for (i = 0; i < sz; i++) {
10753 desc = &tab[i];
10754 desc->insn_idx += len - 1;
10755 }
10756}
10757
Alexei Starovoitov80419022017-03-15 18:26:41 -070010758static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10759 const struct bpf_insn *patch, u32 len)
10760{
10761 struct bpf_prog *new_prog;
10762
10763 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010764 if (IS_ERR(new_prog)) {
10765 if (PTR_ERR(new_prog) == -ERANGE)
10766 verbose(env,
10767 "insn %d cannot be patched due to 16-bit range\n",
10768 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010769 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010770 }
Jiong Wangb325fbc2019-05-24 23:25:13 +010010771 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -070010772 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010773 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010774 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010775 return new_prog;
10776}
10777
Jakub Kicinski52875a02019-01-22 22:45:20 -080010778static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10779 u32 off, u32 cnt)
10780{
10781 int i, j;
10782
10783 /* find first prog starting at or after off (first to remove) */
10784 for (i = 0; i < env->subprog_cnt; i++)
10785 if (env->subprog_info[i].start >= off)
10786 break;
10787 /* find first prog starting at or after off + cnt (first to stay) */
10788 for (j = i; j < env->subprog_cnt; j++)
10789 if (env->subprog_info[j].start >= off + cnt)
10790 break;
10791 /* if j doesn't start exactly at off + cnt, we are just removing
10792 * the front of previous prog
10793 */
10794 if (env->subprog_info[j].start != off + cnt)
10795 j--;
10796
10797 if (j > i) {
10798 struct bpf_prog_aux *aux = env->prog->aux;
10799 int move;
10800
10801 /* move fake 'exit' subprog as well */
10802 move = env->subprog_cnt + 1 - j;
10803
10804 memmove(env->subprog_info + i,
10805 env->subprog_info + j,
10806 sizeof(*env->subprog_info) * move);
10807 env->subprog_cnt -= j - i;
10808
10809 /* remove func_info */
10810 if (aux->func_info) {
10811 move = aux->func_info_cnt - j;
10812
10813 memmove(aux->func_info + i,
10814 aux->func_info + j,
10815 sizeof(*aux->func_info) * move);
10816 aux->func_info_cnt -= j - i;
10817 /* func_info->insn_off is set after all code rewrites,
10818 * in adjust_btf_func() - no need to adjust
10819 */
10820 }
10821 } else {
10822 /* convert i from "first prog to remove" to "first to adjust" */
10823 if (env->subprog_info[i].start == off)
10824 i++;
10825 }
10826
10827 /* update fake 'exit' subprog as well */
10828 for (; i <= env->subprog_cnt; i++)
10829 env->subprog_info[i].start -= cnt;
10830
10831 return 0;
10832}
10833
10834static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10835 u32 cnt)
10836{
10837 struct bpf_prog *prog = env->prog;
10838 u32 i, l_off, l_cnt, nr_linfo;
10839 struct bpf_line_info *linfo;
10840
10841 nr_linfo = prog->aux->nr_linfo;
10842 if (!nr_linfo)
10843 return 0;
10844
10845 linfo = prog->aux->linfo;
10846
10847 /* find first line info to remove, count lines to be removed */
10848 for (i = 0; i < nr_linfo; i++)
10849 if (linfo[i].insn_off >= off)
10850 break;
10851
10852 l_off = i;
10853 l_cnt = 0;
10854 for (; i < nr_linfo; i++)
10855 if (linfo[i].insn_off < off + cnt)
10856 l_cnt++;
10857 else
10858 break;
10859
10860 /* First live insn doesn't match first live linfo, it needs to "inherit"
10861 * last removed linfo. prog is already modified, so prog->len == off
10862 * means no live instructions after (tail of the program was removed).
10863 */
10864 if (prog->len != off && l_cnt &&
10865 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10866 l_cnt--;
10867 linfo[--i].insn_off = off + cnt;
10868 }
10869
10870 /* remove the line info which refer to the removed instructions */
10871 if (l_cnt) {
10872 memmove(linfo + l_off, linfo + i,
10873 sizeof(*linfo) * (nr_linfo - i));
10874
10875 prog->aux->nr_linfo -= l_cnt;
10876 nr_linfo = prog->aux->nr_linfo;
10877 }
10878
10879 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10880 for (i = l_off; i < nr_linfo; i++)
10881 linfo[i].insn_off -= cnt;
10882
10883 /* fix up all subprogs (incl. 'exit') which start >= off */
10884 for (i = 0; i <= env->subprog_cnt; i++)
10885 if (env->subprog_info[i].linfo_idx > l_off) {
10886 /* program may have started in the removed region but
10887 * may not be fully removed
10888 */
10889 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10890 env->subprog_info[i].linfo_idx -= l_cnt;
10891 else
10892 env->subprog_info[i].linfo_idx = l_off;
10893 }
10894
10895 return 0;
10896}
10897
10898static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10899{
10900 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10901 unsigned int orig_prog_len = env->prog->len;
10902 int err;
10903
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010904 if (bpf_prog_is_dev_bound(env->prog->aux))
10905 bpf_prog_offload_remove_insns(env, off, cnt);
10906
Jakub Kicinski52875a02019-01-22 22:45:20 -080010907 err = bpf_remove_insns(env->prog, off, cnt);
10908 if (err)
10909 return err;
10910
10911 err = adjust_subprog_starts_after_remove(env, off, cnt);
10912 if (err)
10913 return err;
10914
10915 err = bpf_adj_linfo_after_remove(env, off, cnt);
10916 if (err)
10917 return err;
10918
10919 memmove(aux_data + off, aux_data + off + cnt,
10920 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10921
10922 return 0;
10923}
10924
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010925/* The verifier does more data flow analysis than llvm and will not
10926 * explore branches that are dead at run time. Malicious programs can
10927 * have dead code too. Therefore replace all dead at-run-time code
10928 * with 'ja -1'.
10929 *
10930 * Just nops are not optimal, e.g. if they would sit at the end of the
10931 * program and through another bug we would manage to jump there, then
10932 * we'd execute beyond program memory otherwise. Returning exception
10933 * code also wouldn't work since we can have subprogs where the dead
10934 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010935 */
10936static void sanitize_dead_code(struct bpf_verifier_env *env)
10937{
10938 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010939 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010940 struct bpf_insn *insn = env->prog->insnsi;
10941 const int insn_cnt = env->prog->len;
10942 int i;
10943
10944 for (i = 0; i < insn_cnt; i++) {
10945 if (aux_data[i].seen)
10946 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010947 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010948 }
10949}
10950
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010951static bool insn_is_cond_jump(u8 code)
10952{
10953 u8 op;
10954
Jiong Wang092ed092019-01-26 12:26:01 -050010955 if (BPF_CLASS(code) == BPF_JMP32)
10956 return true;
10957
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010958 if (BPF_CLASS(code) != BPF_JMP)
10959 return false;
10960
10961 op = BPF_OP(code);
10962 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10963}
10964
10965static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10966{
10967 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10968 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10969 struct bpf_insn *insn = env->prog->insnsi;
10970 const int insn_cnt = env->prog->len;
10971 int i;
10972
10973 for (i = 0; i < insn_cnt; i++, insn++) {
10974 if (!insn_is_cond_jump(insn->code))
10975 continue;
10976
10977 if (!aux_data[i + 1].seen)
10978 ja.off = insn->off;
10979 else if (!aux_data[i + 1 + insn->off].seen)
10980 ja.off = 0;
10981 else
10982 continue;
10983
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010984 if (bpf_prog_is_dev_bound(env->prog->aux))
10985 bpf_prog_offload_replace_insn(env, i, &ja);
10986
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010987 memcpy(insn, &ja, sizeof(ja));
10988 }
10989}
10990
Jakub Kicinski52875a02019-01-22 22:45:20 -080010991static int opt_remove_dead_code(struct bpf_verifier_env *env)
10992{
10993 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10994 int insn_cnt = env->prog->len;
10995 int i, err;
10996
10997 for (i = 0; i < insn_cnt; i++) {
10998 int j;
10999
11000 j = 0;
11001 while (i + j < insn_cnt && !aux_data[i + j].seen)
11002 j++;
11003 if (!j)
11004 continue;
11005
11006 err = verifier_remove_insns(env, i, j);
11007 if (err)
11008 return err;
11009 insn_cnt = env->prog->len;
11010 }
11011
11012 return 0;
11013}
11014
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080011015static int opt_remove_nops(struct bpf_verifier_env *env)
11016{
11017 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
11018 struct bpf_insn *insn = env->prog->insnsi;
11019 int insn_cnt = env->prog->len;
11020 int i, err;
11021
11022 for (i = 0; i < insn_cnt; i++) {
11023 if (memcmp(&insn[i], &ja, sizeof(ja)))
11024 continue;
11025
11026 err = verifier_remove_insns(env, i, 1);
11027 if (err)
11028 return err;
11029 insn_cnt--;
11030 i--;
11031 }
11032
11033 return 0;
11034}
11035
Jiong Wangd6c23082019-05-24 23:25:18 +010011036static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
11037 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011038{
Jiong Wangd6c23082019-05-24 23:25:18 +010011039 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011040 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011041 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011042 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011043 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010011044 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011045
Jiong Wangd6c23082019-05-24 23:25:18 +010011046 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011047 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010011048 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
11049 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11050 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011051 for (i = 0; i < len; i++) {
11052 int adj_idx = i + delta;
11053 struct bpf_insn insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011054 u8 load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011055
Jiong Wangd6c23082019-05-24 23:25:18 +010011056 insn = insns[adj_idx];
11057 if (!aux[adj_idx].zext_dst) {
11058 u8 code, class;
11059 u32 imm_rnd;
11060
11061 if (!rnd_hi32)
11062 continue;
11063
11064 code = insn.code;
11065 class = BPF_CLASS(code);
11066 if (insn_no_def(&insn))
11067 continue;
11068
11069 /* NOTE: arg "reg" (the fourth one) is only used for
11070 * BPF_STX which has been ruled out in above
11071 * check, it is safe to pass NULL here.
11072 */
11073 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11074 if (class == BPF_LD &&
11075 BPF_MODE(code) == BPF_IMM)
11076 i++;
11077 continue;
11078 }
11079
11080 /* ctx load could be transformed into wider load. */
11081 if (class == BPF_LDX &&
11082 aux[adj_idx].ptr_type == PTR_TO_CTX)
11083 continue;
11084
11085 imm_rnd = get_random_int();
11086 rnd_hi32_patch[0] = insn;
11087 rnd_hi32_patch[1].imm = imm_rnd;
11088 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11089 patch = rnd_hi32_patch;
11090 patch_len = 4;
11091 goto apply_patch_buffer;
11092 }
11093
11094 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011095 continue;
11096
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011097 /* zext_dst means that we want to zero-extend whatever register
11098 * the insn defines, which is dst_reg most of the time, with
11099 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11100 */
11101 if (BPF_CLASS(insn.code) == BPF_STX &&
11102 BPF_MODE(insn.code) == BPF_ATOMIC) {
11103 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11104 * define any registers, therefore zext_dst cannot be
11105 * set.
11106 */
11107 if (WARN_ON(!(insn.imm & BPF_FETCH)))
11108 return -EINVAL;
11109 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11110 : insn.src_reg;
11111 } else {
11112 load_reg = insn.dst_reg;
11113 }
11114
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011115 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011116 zext_patch[1].dst_reg = load_reg;
11117 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010011118 patch = zext_patch;
11119 patch_len = 2;
11120apply_patch_buffer:
11121 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011122 if (!new_prog)
11123 return -ENOMEM;
11124 env->prog = new_prog;
11125 insns = new_prog->insnsi;
11126 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011127 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011128 }
11129
11130 return 0;
11131}
11132
Joe Stringerc64b7982018-10-02 13:35:33 -070011133/* convert load instructions that access fields of a context type into a
11134 * sequence of instructions that access fields of the underlying structure:
11135 * struct __sk_buff -> struct sk_buff
11136 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011137 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011138static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011139{
Jakub Kicinski00176a32017-10-16 16:40:54 -070011140 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011141 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011142 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011143 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011144 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011145 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011146 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011147 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011148
Daniel Borkmannb09928b2018-10-24 22:05:49 +020011149 if (ops->gen_prologue || env->seen_direct_write) {
11150 if (!ops->gen_prologue) {
11151 verbose(env, "bpf verifier is misconfigured\n");
11152 return -EINVAL;
11153 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011154 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11155 env->prog);
11156 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011157 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011158 return -EINVAL;
11159 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070011160 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011161 if (!new_prog)
11162 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011163
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011164 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011165 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011166 }
11167 }
11168
Joe Stringerc64b7982018-10-02 13:35:33 -070011169 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011170 return 0;
11171
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011172 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011173
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011174 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070011175 bpf_convert_ctx_access_t convert_ctx_access;
11176
Daniel Borkmann62c79892017-01-12 11:51:33 +010011177 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11178 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11179 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011180 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011181 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010011182 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11183 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11184 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011185 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011186 type = BPF_WRITE;
11187 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011188 continue;
11189
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011190 if (type == BPF_WRITE &&
11191 env->insn_aux_data[i + delta].sanitize_stack_off) {
11192 struct bpf_insn patch[] = {
11193 /* Sanitize suspicious stack slot with zero.
11194 * There are no memory dependencies for this store,
11195 * since it's only using frame pointer and immediate
11196 * constant of zero
11197 */
11198 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11199 env->insn_aux_data[i + delta].sanitize_stack_off,
11200 0),
11201 /* the original STX instruction will immediately
11202 * overwrite the same stack slot with appropriate value
11203 */
11204 *insn,
11205 };
11206
11207 cnt = ARRAY_SIZE(patch);
11208 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11209 if (!new_prog)
11210 return -ENOMEM;
11211
11212 delta += cnt - 1;
11213 env->prog = new_prog;
11214 insn = new_prog->insnsi + i + delta;
11215 continue;
11216 }
11217
Joe Stringerc64b7982018-10-02 13:35:33 -070011218 switch (env->insn_aux_data[i + delta].ptr_type) {
11219 case PTR_TO_CTX:
11220 if (!ops->convert_ctx_access)
11221 continue;
11222 convert_ctx_access = ops->convert_ctx_access;
11223 break;
11224 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011225 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070011226 convert_ctx_access = bpf_sock_convert_ctx_access;
11227 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011228 case PTR_TO_TCP_SOCK:
11229 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11230 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011231 case PTR_TO_XDP_SOCK:
11232 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11233 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011234 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011235 if (type == BPF_READ) {
11236 insn->code = BPF_LDX | BPF_PROBE_MEM |
11237 BPF_SIZE((insn)->code);
11238 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070011239 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011240 verbose(env, "Writes through BTF pointers are not allowed\n");
11241 return -EINVAL;
11242 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011243 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011244 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011245 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011246 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011247
Yonghong Song31fd8582017-06-13 15:52:13 -070011248 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011249 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070011250
11251 /* If the read access is a narrower load of the field,
11252 * convert to a 4/8-byte load, to minimum program type specific
11253 * convert_ctx_access changes. If conversion is successful,
11254 * we will apply proper mask to the result.
11255 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020011256 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011257 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11258 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070011259 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020011260 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070011261
Daniel Borkmannf96da092017-07-02 02:13:27 +020011262 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011263 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020011264 return -EINVAL;
11265 }
11266
11267 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070011268 if (ctx_field_size == 4)
11269 size_code = BPF_W;
11270 else if (ctx_field_size == 8)
11271 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011272
Daniel Borkmannbc231052018-06-02 23:06:39 +020011273 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070011274 insn->code = BPF_LDX | BPF_MEM | size_code;
11275 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011276
11277 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070011278 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11279 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020011280 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11281 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011282 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011283 return -EINVAL;
11284 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011285
11286 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020011287 u8 shift = bpf_ctx_narrow_access_offset(
11288 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011289 if (ctx_field_size <= 4) {
11290 if (shift)
11291 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11292 insn->dst_reg,
11293 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011294 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020011295 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011296 } else {
11297 if (shift)
11298 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11299 insn->dst_reg,
11300 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011301 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020011302 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011303 }
Yonghong Song31fd8582017-06-13 15:52:13 -070011304 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011305
Alexei Starovoitov80419022017-03-15 18:26:41 -070011306 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011307 if (!new_prog)
11308 return -ENOMEM;
11309
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011310 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011311
11312 /* keep walking new program and skip insns we just inserted */
11313 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011314 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011315 }
11316
11317 return 0;
11318}
11319
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011320static int jit_subprogs(struct bpf_verifier_env *env)
11321{
11322 struct bpf_prog *prog = env->prog, **func, *tmp;
11323 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011324 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011325 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011326 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011327 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011328
Jiong Wangf910cef2018-05-02 16:17:17 -040011329 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011330 return 0;
11331
Daniel Borkmann7105e822017-12-20 13:42:57 +010011332 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011333 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011334 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011335 /* Upon error here we cannot fall back to interpreter but
11336 * need a hard reject of the program. Thus -EFAULT is
11337 * propagated in any case.
11338 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011339 subprog = find_subprog(env, i + insn->imm + 1);
11340 if (subprog < 0) {
11341 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11342 i + insn->imm + 1);
11343 return -EFAULT;
11344 }
11345 /* temporarily remember subprog id inside insn instead of
11346 * aux_data, since next loop will split up all insns into funcs
11347 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011348 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011349 /* remember original imm in case JIT fails and fallback
11350 * to interpreter will be needed
11351 */
11352 env->insn_aux_data[i].call_imm = insn->imm;
11353 /* point imm to __bpf_call_base+1 from JITs point of view */
11354 insn->imm = 1;
11355 }
11356
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011357 err = bpf_prog_alloc_jited_linfo(prog);
11358 if (err)
11359 goto out_undo_insn;
11360
11361 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070011362 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011363 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011364 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011365
Jiong Wangf910cef2018-05-02 16:17:17 -040011366 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011367 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040011368 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011369
11370 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011371 /* BPF_PROG_RUN doesn't call subprogs directly,
11372 * hence main prog stats include the runtime of subprogs.
11373 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080011374 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011375 */
11376 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011377 if (!func[i])
11378 goto out_free;
11379 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11380 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011381 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011382 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011383 if (bpf_prog_calc_tag(func[i]))
11384 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011385 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080011386 func[i]->aux->func_idx = i;
11387 /* the btf and func_info will be freed only at prog->aux */
11388 func[i]->aux->btf = prog->aux->btf;
11389 func[i]->aux->func_info = prog->aux->func_info;
11390
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011391 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11392 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11393 int ret;
11394
11395 if (!(insn_idx >= subprog_start &&
11396 insn_idx <= subprog_end))
11397 continue;
11398
11399 ret = bpf_jit_add_poke_descriptor(func[i],
11400 &prog->aux->poke_tab[j]);
11401 if (ret < 0) {
11402 verbose(env, "adding tail call poke descriptor failed\n");
11403 goto out_free;
11404 }
11405
11406 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11407
11408 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11409 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11410 if (ret < 0) {
11411 verbose(env, "tracking tail call prog failed\n");
11412 goto out_free;
11413 }
11414 }
11415
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011416 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11417 * Long term would need debug info to populate names
11418 */
11419 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040011420 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011421 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011422 func[i]->aux->linfo = prog->aux->linfo;
11423 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11424 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11425 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011426 num_exentries = 0;
11427 insn = func[i]->insnsi;
11428 for (j = 0; j < func[i]->len; j++, insn++) {
11429 if (BPF_CLASS(insn->code) == BPF_LDX &&
11430 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11431 num_exentries++;
11432 }
11433 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020011434 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011435 func[i] = bpf_int_jit_compile(func[i]);
11436 if (!func[i]->jited) {
11437 err = -ENOTSUPP;
11438 goto out_free;
11439 }
11440 cond_resched();
11441 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011442
11443 /* Untrack main program's aux structs so that during map_poke_run()
11444 * we will not stumble upon the unfilled poke descriptors; each
11445 * of the main program's poke descs got distributed across subprogs
11446 * and got tracked onto map, so we are sure that none of them will
11447 * be missed after the operation below
11448 */
11449 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11450 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11451
11452 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11453 }
11454
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011455 /* at this point all bpf functions were successfully JITed
11456 * now populate all bpf_calls with correct addresses and
11457 * run last pass of JIT
11458 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011459 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011460 insn = func[i]->insnsi;
11461 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011462 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011463 continue;
11464 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090011465 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11466 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011467 }
Sandipan Das2162fed2018-05-24 12:26:45 +053011468
11469 /* we use the aux data to keep a list of the start addresses
11470 * of the JITed images for each function in the program
11471 *
11472 * for some architectures, such as powerpc64, the imm field
11473 * might not be large enough to hold the offset of the start
11474 * address of the callee's JITed image from __bpf_call_base
11475 *
11476 * in such cases, we can lookup the start address of a callee
11477 * by using its subprog id, available from the off field of
11478 * the call instruction, as an index for this list
11479 */
11480 func[i]->aux->func = func;
11481 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011482 }
Jiong Wangf910cef2018-05-02 16:17:17 -040011483 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011484 old_bpf_func = func[i]->bpf_func;
11485 tmp = bpf_int_jit_compile(func[i]);
11486 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11487 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011488 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011489 goto out_free;
11490 }
11491 cond_resched();
11492 }
11493
11494 /* finally lock prog and jit images for all functions and
11495 * populate kallsysm
11496 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011497 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011498 bpf_prog_lock_ro(func[i]);
11499 bpf_prog_kallsyms_add(func[i]);
11500 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010011501
11502 /* Last step: make now unused interpreter insns from main
11503 * prog consistent for later dump requests, so they can
11504 * later look the same as if they were interpreted only.
11505 */
11506 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011507 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010011508 continue;
11509 insn->off = env->insn_aux_data[i].call_imm;
11510 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053011511 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011512 }
11513
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011514 prog->jited = 1;
11515 prog->bpf_func = func[0]->bpf_func;
11516 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040011517 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011518 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011519 return 0;
11520out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011521 for (i = 0; i < env->subprog_cnt; i++) {
11522 if (!func[i])
11523 continue;
11524
11525 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11526 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11527 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11528 }
11529 bpf_jit_free(func[i]);
11530 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011531 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011532out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011533 /* cleanup main prog to be interpreted */
11534 prog->jit_requested = 0;
11535 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011536 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011537 continue;
11538 insn->off = 0;
11539 insn->imm = env->insn_aux_data[i].call_imm;
11540 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011541 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011542 return err;
11543}
11544
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011545static int fixup_call_args(struct bpf_verifier_env *env)
11546{
David S. Miller19d28fb2018-01-11 21:27:54 -050011547#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011548 struct bpf_prog *prog = env->prog;
11549 struct bpf_insn *insn = prog->insnsi;
11550 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050011551#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010011552 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011553
Quentin Monnete4052d02018-10-07 12:56:58 +010011554 if (env->prog->jit_requested &&
11555 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050011556 err = jit_subprogs(env);
11557 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011558 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011559 if (err == -EFAULT)
11560 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050011561 }
11562#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011563 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11564 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11565 * have to be rejected, since interpreter doesn't support them yet.
11566 */
11567 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11568 return -EINVAL;
11569 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011570 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011571 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011572 continue;
11573 depth = get_callee_stack_depth(env, insn, i);
11574 if (depth < 0)
11575 return depth;
11576 bpf_patch_call_args(insn, depth);
11577 }
David S. Miller19d28fb2018-01-11 21:27:54 -050011578 err = 0;
11579#endif
11580 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011581}
11582
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011583/* Do various post-verification rewrites in a single program pass.
11584 * These rewrites simplify JIT and interpreter implementations.
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011585 */
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011586static int do_misc_fixups(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011587{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011588 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011589 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011590 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011591 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011592 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020011593 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011594 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011595 struct bpf_insn insn_buf[16];
11596 struct bpf_prog *new_prog;
11597 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011598 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011599
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011600 for (i = 0; i < insn_cnt; i++, insn++) {
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011601 /* Make divide-by-zero exceptions impossible. */
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011602 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11603 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11604 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011605 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011606 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011607 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
11608 struct bpf_insn *patchlet;
11609 struct bpf_insn chk_and_div[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011610 /* [R,W]x div 0 -> 0 */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011611 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11612 BPF_JNE | BPF_K, insn->src_reg,
11613 0, 2, 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011614 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11615 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11616 *insn,
11617 };
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011618 struct bpf_insn chk_and_mod[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011619 /* [R,W]x mod 0 -> [R,W]x */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011620 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
11621 BPF_JEQ | BPF_K, insn->src_reg,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011622 0, 1 + (is64 ? 0 : 1), 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011623 *insn,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011624 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11625 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011626 };
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011627
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000011628 patchlet = isdiv ? chk_and_div : chk_and_mod;
11629 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010011630 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011631
11632 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011633 if (!new_prog)
11634 return -ENOMEM;
11635
11636 delta += cnt - 1;
11637 env->prog = prog = new_prog;
11638 insn = new_prog->insnsi + i + delta;
11639 continue;
11640 }
11641
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011642 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020011643 if (BPF_CLASS(insn->code) == BPF_LD &&
11644 (BPF_MODE(insn->code) == BPF_ABS ||
11645 BPF_MODE(insn->code) == BPF_IND)) {
11646 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11647 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11648 verbose(env, "bpf verifier is misconfigured\n");
11649 return -EINVAL;
11650 }
11651
11652 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11653 if (!new_prog)
11654 return -ENOMEM;
11655
11656 delta += cnt - 1;
11657 env->prog = prog = new_prog;
11658 insn = new_prog->insnsi + i + delta;
11659 continue;
11660 }
11661
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011662 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011663 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11664 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11665 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11666 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11667 struct bpf_insn insn_buf[16];
11668 struct bpf_insn *patch = &insn_buf[0];
11669 bool issrc, isneg;
11670 u32 off_reg;
11671
11672 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010011673 if (!aux->alu_state ||
11674 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011675 continue;
11676
11677 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11678 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11679 BPF_ALU_SANITIZE_SRC;
11680
11681 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11682 if (isneg)
11683 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11684 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11685 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11686 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11687 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11688 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11689 if (issrc) {
11690 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11691 off_reg);
11692 insn->src_reg = BPF_REG_AX;
11693 } else {
11694 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11695 BPF_REG_AX);
11696 }
11697 if (isneg)
11698 insn->code = insn->code == code_add ?
11699 code_sub : code_add;
11700 *patch++ = *insn;
11701 if (issrc && isneg)
11702 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11703 cnt = patch - insn_buf;
11704
11705 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11706 if (!new_prog)
11707 return -ENOMEM;
11708
11709 delta += cnt - 1;
11710 env->prog = prog = new_prog;
11711 insn = new_prog->insnsi + i + delta;
11712 continue;
11713 }
11714
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011715 if (insn->code != (BPF_JMP | BPF_CALL))
11716 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011717 if (insn->src_reg == BPF_PSEUDO_CALL)
11718 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011719
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011720 if (insn->imm == BPF_FUNC_get_route_realm)
11721 prog->dst_needed = 1;
11722 if (insn->imm == BPF_FUNC_get_prandom_u32)
11723 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050011724 if (insn->imm == BPF_FUNC_override_return)
11725 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011726 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040011727 /* If we tail call into other programs, we
11728 * cannot make any assumptions since they can
11729 * be replaced dynamically during runtime in
11730 * the program array.
11731 */
11732 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011733 if (!allow_tail_call_in_subprogs(env))
11734 prog->aux->stack_depth = MAX_BPF_STACK;
11735 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040011736
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011737 /* mark bpf_tail_call as different opcode to avoid
11738 * conditional branch in the interpeter for every normal
11739 * call and to prevent accidental JITing by JIT compiler
11740 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011741 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011742 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070011743 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011744
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011745 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011746 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010011747 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011748 !bpf_map_key_poisoned(aux) &&
11749 !bpf_map_ptr_poisoned(aux) &&
11750 !bpf_map_ptr_unpriv(aux)) {
11751 struct bpf_jit_poke_descriptor desc = {
11752 .reason = BPF_POKE_REASON_TAIL_CALL,
11753 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11754 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011755 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011756 };
11757
11758 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11759 if (ret < 0) {
11760 verbose(env, "adding tail call poke descriptor failed\n");
11761 return ret;
11762 }
11763
11764 insn->imm = ret + 1;
11765 continue;
11766 }
11767
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011768 if (!bpf_map_ptr_unpriv(aux))
11769 continue;
11770
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011771 /* instead of changing every JIT dealing with tail_call
11772 * emit two extra insns:
11773 * if (index >= max_entries) goto out;
11774 * index &= array->index_mask;
11775 * to avoid out-of-bounds cpu speculation
11776 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011777 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000011778 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011779 return -EINVAL;
11780 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011781
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011782 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011783 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11784 map_ptr->max_entries, 2);
11785 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11786 container_of(map_ptr,
11787 struct bpf_array,
11788 map)->index_mask);
11789 insn_buf[2] = *insn;
11790 cnt = 3;
11791 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11792 if (!new_prog)
11793 return -ENOMEM;
11794
11795 delta += cnt - 1;
11796 env->prog = prog = new_prog;
11797 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011798 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011799 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011800
Daniel Borkmann89c63072017-08-19 03:12:45 +020011801 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020011802 * and other inlining handlers are currently limited to 64 bit
11803 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020011804 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080011805 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020011806 (insn->imm == BPF_FUNC_map_lookup_elem ||
11807 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020011808 insn->imm == BPF_FUNC_map_delete_elem ||
11809 insn->imm == BPF_FUNC_map_push_elem ||
11810 insn->imm == BPF_FUNC_map_pop_elem ||
11811 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011812 aux = &env->insn_aux_data[i + delta];
11813 if (bpf_map_ptr_poisoned(aux))
11814 goto patch_call_imm;
11815
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011816 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020011817 ops = map_ptr->ops;
11818 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11819 ops->map_gen_lookup) {
11820 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020011821 if (cnt == -EOPNOTSUPP)
11822 goto patch_map_ops_generic;
11823 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020011824 verbose(env, "bpf verifier is misconfigured\n");
11825 return -EINVAL;
11826 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011827
Daniel Borkmann09772d92018-06-02 23:06:35 +020011828 new_prog = bpf_patch_insn_data(env, i + delta,
11829 insn_buf, cnt);
11830 if (!new_prog)
11831 return -ENOMEM;
11832
11833 delta += cnt - 1;
11834 env->prog = prog = new_prog;
11835 insn = new_prog->insnsi + i + delta;
11836 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011837 }
11838
Daniel Borkmann09772d92018-06-02 23:06:35 +020011839 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11840 (void *(*)(struct bpf_map *map, void *key))NULL));
11841 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11842 (int (*)(struct bpf_map *map, void *key))NULL));
11843 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11844 (int (*)(struct bpf_map *map, void *key, void *value,
11845 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020011846 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11847 (int (*)(struct bpf_map *map, void *value,
11848 u64 flags))NULL));
11849 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11850 (int (*)(struct bpf_map *map, void *value))NULL));
11851 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11852 (int (*)(struct bpf_map *map, void *value))NULL));
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020011853patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020011854 switch (insn->imm) {
11855 case BPF_FUNC_map_lookup_elem:
11856 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11857 __bpf_call_base;
11858 continue;
11859 case BPF_FUNC_map_update_elem:
11860 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11861 __bpf_call_base;
11862 continue;
11863 case BPF_FUNC_map_delete_elem:
11864 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11865 __bpf_call_base;
11866 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020011867 case BPF_FUNC_map_push_elem:
11868 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11869 __bpf_call_base;
11870 continue;
11871 case BPF_FUNC_map_pop_elem:
11872 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11873 __bpf_call_base;
11874 continue;
11875 case BPF_FUNC_map_peek_elem:
11876 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11877 __bpf_call_base;
11878 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020011879 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011880
Daniel Borkmann09772d92018-06-02 23:06:35 +020011881 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011882 }
11883
Brendan Jackmane6ac5932021-02-17 10:45:09 +000011884 /* Implement bpf_jiffies64 inline. */
Martin KaFai Lau5576b992020-01-22 15:36:46 -080011885 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11886 insn->imm == BPF_FUNC_jiffies64) {
11887 struct bpf_insn ld_jiffies_addr[2] = {
11888 BPF_LD_IMM64(BPF_REG_0,
11889 (unsigned long)&jiffies),
11890 };
11891
11892 insn_buf[0] = ld_jiffies_addr[0];
11893 insn_buf[1] = ld_jiffies_addr[1];
11894 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11895 BPF_REG_0, 0);
11896 cnt = 3;
11897
11898 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11899 cnt);
11900 if (!new_prog)
11901 return -ENOMEM;
11902
11903 delta += cnt - 1;
11904 env->prog = prog = new_prog;
11905 insn = new_prog->insnsi + i + delta;
11906 continue;
11907 }
11908
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011909patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070011910 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011911 /* all functions that have prototype and verifier allowed
11912 * programs to call them, must be real in-kernel functions
11913 */
11914 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011915 verbose(env,
11916 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011917 func_id_name(insn->imm), insn->imm);
11918 return -EFAULT;
11919 }
11920 insn->imm = fn->func - __bpf_call_base;
11921 }
11922
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011923 /* Since poke tab is now finalized, publish aux to tracker. */
11924 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11925 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11926 if (!map_ptr->ops->map_poke_track ||
11927 !map_ptr->ops->map_poke_untrack ||
11928 !map_ptr->ops->map_poke_run) {
11929 verbose(env, "bpf verifier is misconfigured\n");
11930 return -EINVAL;
11931 }
11932
11933 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11934 if (ret < 0) {
11935 verbose(env, "tracking tail call prog failed\n");
11936 return ret;
11937 }
11938 }
11939
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011940 return 0;
11941}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011942
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011943static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011944{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011945 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011946 int i;
11947
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011948 sl = env->free_list;
11949 while (sl) {
11950 sln = sl->next;
11951 free_verifier_state(&sl->state, false);
11952 kfree(sl);
11953 sl = sln;
11954 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011955 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011956
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011957 if (!env->explored_states)
11958 return;
11959
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011960 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011961 sl = env->explored_states[i];
11962
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011963 while (sl) {
11964 sln = sl->next;
11965 free_verifier_state(&sl->state, false);
11966 kfree(sl);
11967 sl = sln;
11968 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011969 env->explored_states[i] = NULL;
11970 }
11971}
11972
11973/* The verifier is using insn_aux_data[] to store temporary data during
11974 * verification and to store information for passes that run after the
11975 * verification like dead code sanitization. do_check_common() for subprogram N
11976 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11977 * temporary data after do_check_common() finds that subprogram N cannot be
11978 * verified independently. pass_cnt counts the number of times
11979 * do_check_common() was run and insn->aux->seen tells the pass number
11980 * insn_aux_data was touched. These variables are compared to clear temporary
11981 * data from failed pass. For testing and experiments do_check_common() can be
11982 * run multiple times even when prior attempt to verify is unsuccessful.
11983 */
11984static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11985{
11986 struct bpf_insn *insn = env->prog->insnsi;
11987 struct bpf_insn_aux_data *aux;
11988 int i, class;
11989
11990 for (i = 0; i < env->prog->len; i++) {
11991 class = BPF_CLASS(insn[i].code);
11992 if (class != BPF_LDX && class != BPF_STX)
11993 continue;
11994 aux = &env->insn_aux_data[i];
11995 if (aux->seen != env->pass_cnt)
11996 continue;
11997 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11998 }
11999}
12000
12001static int do_check_common(struct bpf_verifier_env *env, int subprog)
12002{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012003 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012004 struct bpf_verifier_state *state;
12005 struct bpf_reg_state *regs;
12006 int ret, i;
12007
12008 env->prev_linfo = NULL;
12009 env->pass_cnt++;
12010
12011 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
12012 if (!state)
12013 return -ENOMEM;
12014 state->curframe = 0;
12015 state->speculative = false;
12016 state->branches = 1;
12017 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
12018 if (!state->frame[0]) {
12019 kfree(state);
12020 return -ENOMEM;
12021 }
12022 env->cur_state = state;
12023 init_func_state(env, state->frame[0],
12024 BPF_MAIN_FUNC /* callsite */,
12025 0 /* frameno */,
12026 subprog);
12027
12028 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012029 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012030 ret = btf_prepare_func_args(env, subprog, regs);
12031 if (ret)
12032 goto out;
12033 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
12034 if (regs[i].type == PTR_TO_CTX)
12035 mark_reg_known_zero(env, regs, i);
12036 else if (regs[i].type == SCALAR_VALUE)
12037 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040012038 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
12039 const u32 mem_size = regs[i].mem_size;
12040
12041 mark_reg_known_zero(env, regs, i);
12042 regs[i].mem_size = mem_size;
12043 regs[i].id = ++env->id_gen;
12044 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012045 }
12046 } else {
12047 /* 1st arg to a function */
12048 regs[BPF_REG_1].type = PTR_TO_CTX;
12049 mark_reg_known_zero(env, regs, BPF_REG_1);
12050 ret = btf_check_func_arg_match(env, subprog, regs);
12051 if (ret == -EFAULT)
12052 /* unlikely verifier bug. abort.
12053 * ret == 0 and ret < 0 are sadly acceptable for
12054 * main() function due to backward compatibility.
12055 * Like socket filter program may be written as:
12056 * int bpf_prog(struct pt_regs *ctx)
12057 * and never dereference that ctx in the program.
12058 * 'struct pt_regs' is a type mismatch for socket
12059 * filter that should be using 'struct __sk_buff'.
12060 */
12061 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012062 }
12063
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012064 ret = do_check(env);
12065out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080012066 /* check for NULL is necessary, since cur_state can be freed inside
12067 * do_check() under memory pressure.
12068 */
12069 if (env->cur_state) {
12070 free_verifier_state(env->cur_state, true);
12071 env->cur_state = NULL;
12072 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012073 while (!pop_stack(env, NULL, NULL, false));
12074 if (!ret && pop_log)
12075 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012076 free_states(env);
12077 if (ret)
12078 /* clean aux data in case subprog was rejected */
12079 sanitize_insn_aux_data(env);
12080 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012081}
12082
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012083/* Verify all global functions in a BPF program one by one based on their BTF.
12084 * All global functions must pass verification. Otherwise the whole program is rejected.
12085 * Consider:
12086 * int bar(int);
12087 * int foo(int f)
12088 * {
12089 * return bar(f);
12090 * }
12091 * int bar(int b)
12092 * {
12093 * ...
12094 * }
12095 * foo() will be verified first for R1=any_scalar_value. During verification it
12096 * will be assumed that bar() already verified successfully and call to bar()
12097 * from foo() will be checked for type match only. Later bar() will be verified
12098 * independently to check that it's safe for R1=any_scalar_value.
12099 */
12100static int do_check_subprogs(struct bpf_verifier_env *env)
12101{
12102 struct bpf_prog_aux *aux = env->prog->aux;
12103 int i, ret;
12104
12105 if (!aux->func_info)
12106 return 0;
12107
12108 for (i = 1; i < env->subprog_cnt; i++) {
12109 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12110 continue;
12111 env->insn_idx = env->subprog_info[i].start;
12112 WARN_ON_ONCE(env->insn_idx == 0);
12113 ret = do_check_common(env, i);
12114 if (ret) {
12115 return ret;
12116 } else if (env->log.level & BPF_LOG_LEVEL) {
12117 verbose(env,
12118 "Func#%d is safe for any args that match its prototype\n",
12119 i);
12120 }
12121 }
12122 return 0;
12123}
12124
12125static int do_check_main(struct bpf_verifier_env *env)
12126{
12127 int ret;
12128
12129 env->insn_idx = 0;
12130 ret = do_check_common(env, 0);
12131 if (!ret)
12132 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12133 return ret;
12134}
12135
12136
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012137static void print_verification_stats(struct bpf_verifier_env *env)
12138{
12139 int i;
12140
12141 if (env->log.level & BPF_LOG_STATS) {
12142 verbose(env, "verification time %lld usec\n",
12143 div_u64(env->verification_time, 1000));
12144 verbose(env, "stack depth ");
12145 for (i = 0; i < env->subprog_cnt; i++) {
12146 u32 depth = env->subprog_info[i].stack_depth;
12147
12148 verbose(env, "%d", depth);
12149 if (i + 1 < env->subprog_cnt)
12150 verbose(env, "+");
12151 }
12152 verbose(env, "\n");
12153 }
12154 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12155 "total_states %d peak_states %d mark_read %d\n",
12156 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12157 env->max_states_per_insn, env->total_states,
12158 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012159}
12160
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012161static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12162{
12163 const struct btf_type *t, *func_proto;
12164 const struct bpf_struct_ops *st_ops;
12165 const struct btf_member *member;
12166 struct bpf_prog *prog = env->prog;
12167 u32 btf_id, member_idx;
12168 const char *mname;
12169
12170 btf_id = prog->aux->attach_btf_id;
12171 st_ops = bpf_struct_ops_find(btf_id);
12172 if (!st_ops) {
12173 verbose(env, "attach_btf_id %u is not a supported struct\n",
12174 btf_id);
12175 return -ENOTSUPP;
12176 }
12177
12178 t = st_ops->type;
12179 member_idx = prog->expected_attach_type;
12180 if (member_idx >= btf_type_vlen(t)) {
12181 verbose(env, "attach to invalid member idx %u of struct %s\n",
12182 member_idx, st_ops->name);
12183 return -EINVAL;
12184 }
12185
12186 member = &btf_type_member(t)[member_idx];
12187 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12188 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12189 NULL);
12190 if (!func_proto) {
12191 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12192 mname, member_idx, st_ops->name);
12193 return -EINVAL;
12194 }
12195
12196 if (st_ops->check_member) {
12197 int err = st_ops->check_member(t, member);
12198
12199 if (err) {
12200 verbose(env, "attach to unsupported member %s of struct %s\n",
12201 mname, st_ops->name);
12202 return err;
12203 }
12204 }
12205
12206 prog->aux->attach_func_proto = func_proto;
12207 prog->aux->attach_func_name = mname;
12208 env->ops = st_ops->verifier_ops;
12209
12210 return 0;
12211}
KP Singh6ba43b72020-03-04 20:18:50 +010012212#define SECURITY_PREFIX "security_"
12213
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012214static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010012215{
KP Singh69191752020-03-05 21:49:55 +010012216 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012217 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010012218 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010012219
KP Singh6ba43b72020-03-04 20:18:50 +010012220 return -EINVAL;
12221}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012222
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012223/* list of non-sleepable functions that are otherwise on
12224 * ALLOW_ERROR_INJECTION list
12225 */
12226BTF_SET_START(btf_non_sleepable_error_inject)
12227/* Three functions below can be called from sleepable and non-sleepable context.
12228 * Assume non-sleepable from bpf safety point of view.
12229 */
12230BTF_ID(func, __add_to_page_cache_locked)
12231BTF_ID(func, should_fail_alloc_page)
12232BTF_ID(func, should_failslab)
12233BTF_SET_END(btf_non_sleepable_error_inject)
12234
12235static int check_non_sleepable_error_inject(u32 btf_id)
12236{
12237 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12238}
12239
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012240int bpf_check_attach_target(struct bpf_verifier_log *log,
12241 const struct bpf_prog *prog,
12242 const struct bpf_prog *tgt_prog,
12243 u32 btf_id,
12244 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070012245{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012246 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012247 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012248 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012249 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012250 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012251 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012252 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012253 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012254
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012255 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012256 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012257 return -EINVAL;
12258 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012259 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012260 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012261 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012262 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12263 return -EINVAL;
12264 }
12265 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012266 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012267 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012268 return -EINVAL;
12269 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012270 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012271 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012272 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012273 return -EINVAL;
12274 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012275 if (tgt_prog) {
12276 struct bpf_prog_aux *aux = tgt_prog->aux;
12277
12278 for (i = 0; i < aux->func_info_cnt; i++)
12279 if (aux->func_info[i].type_id == btf_id) {
12280 subprog = i;
12281 break;
12282 }
12283 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012284 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012285 return -EINVAL;
12286 }
12287 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012288 if (prog_extension) {
12289 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012290 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012291 "Cannot replace static functions\n");
12292 return -EINVAL;
12293 }
12294 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012295 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012296 "Extension programs should be JITed\n");
12297 return -EINVAL;
12298 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012299 }
12300 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012301 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012302 return -EINVAL;
12303 }
12304 if (tgt_prog->type == prog->type) {
12305 /* Cannot fentry/fexit another fentry/fexit program.
12306 * Cannot attach program extension to another extension.
12307 * It's ok to attach fentry/fexit to extension program.
12308 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012309 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012310 return -EINVAL;
12311 }
12312 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12313 prog_extension &&
12314 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12315 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12316 /* Program extensions can extend all program types
12317 * except fentry/fexit. The reason is the following.
12318 * The fentry/fexit programs are used for performance
12319 * analysis, stats and can be attached to any program
12320 * type except themselves. When extension program is
12321 * replacing XDP function it is necessary to allow
12322 * performance analysis of all functions. Both original
12323 * XDP program and its program extension. Hence
12324 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12325 * allowed. If extending of fentry/fexit was allowed it
12326 * would be possible to create long call chain
12327 * fentry->extension->fentry->extension beyond
12328 * reasonable stack size. Hence extending fentry is not
12329 * allowed.
12330 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012331 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012332 return -EINVAL;
12333 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012334 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012335 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012336 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012337 return -EINVAL;
12338 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012339 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012340
12341 switch (prog->expected_attach_type) {
12342 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012343 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012344 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012345 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12346 return -EINVAL;
12347 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070012348 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012349 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012350 btf_id);
12351 return -EINVAL;
12352 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012353 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012354 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012355 btf_id, tname);
12356 return -EINVAL;
12357 }
12358 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012359 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012360 if (!btf_type_is_ptr(t))
12361 /* should never happen in valid vmlinux build */
12362 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012363 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012364 if (!btf_type_is_func_proto(t))
12365 /* should never happen in valid vmlinux build */
12366 return -EINVAL;
12367
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012368 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070012369 case BPF_TRACE_ITER:
12370 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012371 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070012372 btf_id);
12373 return -EINVAL;
12374 }
12375 t = btf_type_by_id(btf, t->type);
12376 if (!btf_type_is_func_proto(t))
12377 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012378 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12379 if (ret)
12380 return ret;
12381 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012382 default:
12383 if (!prog_extension)
12384 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050012385 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010012386 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010012387 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012388 case BPF_TRACE_FENTRY:
12389 case BPF_TRACE_FEXIT:
12390 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012391 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012392 btf_id);
12393 return -EINVAL;
12394 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012395 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012396 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012397 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012398 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012399 if (!btf_type_is_func_proto(t))
12400 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012401
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012402 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12403 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12404 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12405 return -EINVAL;
12406
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012407 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012408 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012409
12410 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012411 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012412 return ret;
12413
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012414 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080012415 if (subprog == 0)
12416 addr = (long) tgt_prog->bpf_func;
12417 else
12418 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012419 } else {
12420 addr = kallsyms_lookup_name(tname);
12421 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012422 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012423 "The address of function %s cannot be found\n",
12424 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012425 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012426 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012427 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012428
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012429 if (prog->aux->sleepable) {
12430 ret = -EINVAL;
12431 switch (prog->type) {
12432 case BPF_PROG_TYPE_TRACING:
12433 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12434 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12435 */
12436 if (!check_non_sleepable_error_inject(btf_id) &&
12437 within_error_injection_list(addr))
12438 ret = 0;
12439 break;
12440 case BPF_PROG_TYPE_LSM:
12441 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12442 * Only some of them are sleepable.
12443 */
KP Singh423f1612020-11-13 00:59:29 +000012444 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012445 ret = 0;
12446 break;
12447 default:
12448 break;
12449 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012450 if (ret) {
12451 bpf_log(log, "%s is not sleepable\n", tname);
12452 return ret;
12453 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012454 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012455 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012456 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012457 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012458 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012459 ret = check_attach_modify_return(addr, tname);
12460 if (ret) {
12461 bpf_log(log, "%s() is not modifiable\n", tname);
12462 return ret;
12463 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012464 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012465
12466 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012467 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012468 tgt_info->tgt_addr = addr;
12469 tgt_info->tgt_name = tname;
12470 tgt_info->tgt_type = t;
12471 return 0;
12472}
12473
12474static int check_attach_btf_id(struct bpf_verifier_env *env)
12475{
12476 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012477 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012478 struct bpf_attach_target_info tgt_info = {};
12479 u32 btf_id = prog->aux->attach_btf_id;
12480 struct bpf_trampoline *tr;
12481 int ret;
12482 u64 key;
12483
12484 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12485 prog->type != BPF_PROG_TYPE_LSM) {
12486 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12487 return -EINVAL;
12488 }
12489
12490 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12491 return check_struct_ops_btf_id(env);
12492
12493 if (prog->type != BPF_PROG_TYPE_TRACING &&
12494 prog->type != BPF_PROG_TYPE_LSM &&
12495 prog->type != BPF_PROG_TYPE_EXT)
12496 return 0;
12497
12498 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12499 if (ret)
12500 return ret;
12501
12502 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012503 /* to make freplace equivalent to their targets, they need to
12504 * inherit env->ops and expected_attach_type for the rest of the
12505 * verification
12506 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012507 env->ops = bpf_verifier_ops[tgt_prog->type];
12508 prog->expected_attach_type = tgt_prog->expected_attach_type;
12509 }
12510
12511 /* store info about the attachment target that will be used later */
12512 prog->aux->attach_func_proto = tgt_info.tgt_type;
12513 prog->aux->attach_func_name = tgt_info.tgt_name;
12514
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012515 if (tgt_prog) {
12516 prog->aux->saved_dst_prog_type = tgt_prog->type;
12517 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12518 }
12519
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012520 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12521 prog->aux->attach_btf_trace = true;
12522 return 0;
12523 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12524 if (!bpf_iter_prog_supported(prog))
12525 return -EINVAL;
12526 return 0;
12527 }
12528
12529 if (prog->type == BPF_PROG_TYPE_LSM) {
12530 ret = bpf_lsm_verify_prog(&env->log, prog);
12531 if (ret < 0)
12532 return ret;
12533 }
12534
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012535 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012536 tr = bpf_trampoline_get(key, &tgt_info);
12537 if (!tr)
12538 return -ENOMEM;
12539
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012540 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012541 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012542}
12543
Alan Maguire76654e62020-09-28 12:31:03 +010012544struct btf *bpf_get_btf_vmlinux(void)
12545{
12546 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12547 mutex_lock(&bpf_verifier_lock);
12548 if (!btf_vmlinux)
12549 btf_vmlinux = btf_parse_vmlinux();
12550 mutex_unlock(&bpf_verifier_lock);
12551 }
12552 return btf_vmlinux;
12553}
12554
Yonghong Song838e9692018-11-19 15:29:11 -080012555int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12556 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012557{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012558 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012559 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070012560 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012561 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012562 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012563
Arnd Bergmanneba0c922017-11-02 12:05:52 +010012564 /* no program is valid */
12565 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12566 return -EINVAL;
12567
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012568 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012569 * allocate/free it every time bpf_check() is called
12570 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012571 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012572 if (!env)
12573 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012574 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012575
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012576 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070012577 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012578 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012579 ret = -ENOMEM;
12580 if (!env->insn_aux_data)
12581 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012582 for (i = 0; i < len; i++)
12583 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012584 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070012585 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012586 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012587
Alan Maguire76654e62020-09-28 12:31:03 +010012588 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012589
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012590 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012591 if (!is_priv)
12592 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012593
12594 if (attr->log_level || attr->log_buf || attr->log_size) {
12595 /* user requested verbose verifier output
12596 * and supplied buffer to store the verification trace
12597 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012598 log->level = attr->log_level;
12599 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12600 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012601
12602 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012603 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070012604 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012605 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012606 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012607 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012608
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012609 if (IS_ERR(btf_vmlinux)) {
12610 /* Either gcc or pahole or kernel are broken. */
12611 verbose(env, "in-kernel BTF is malformed\n");
12612 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012613 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012614 }
12615
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012616 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12617 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070012618 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080012619 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12620 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012621
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012622 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050012623 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070012624 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012625 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12626 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12627 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012628
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070012629 if (is_priv)
12630 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12631
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012632 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000012633 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012634 if (ret)
12635 goto skip_full_check;
12636 }
12637
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012638 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012639 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012640 GFP_USER);
12641 ret = -ENOMEM;
12642 if (!env->explored_states)
12643 goto skip_full_check;
12644
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012645 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070012646 if (ret < 0)
12647 goto skip_full_check;
12648
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012649 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080012650 if (ret < 0)
12651 goto skip_full_check;
12652
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012653 ret = check_attach_btf_id(env);
12654 if (ret)
12655 goto skip_full_check;
12656
Hao Luo4976b712020-09-29 16:50:44 -070012657 ret = resolve_pseudo_ldimm64(env);
12658 if (ret < 0)
12659 goto skip_full_check;
12660
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012661 ret = check_cfg(env);
12662 if (ret < 0)
12663 goto skip_full_check;
12664
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012665 ret = do_check_subprogs(env);
12666 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012667
Quentin Monnetc941ce92018-10-07 12:56:47 +010012668 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12669 ret = bpf_prog_offload_finalize(env);
12670
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012671skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012672 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012673
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012674 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080012675 ret = check_max_stack_depth(env);
12676
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012677 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012678 if (is_priv) {
12679 if (ret == 0)
12680 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012681 if (ret == 0)
12682 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080012683 if (ret == 0)
12684 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012685 } else {
12686 if (ret == 0)
12687 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012688 }
12689
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012690 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012691 /* program is valid, convert *(u32*)(ctx + off) accesses */
12692 ret = convert_ctx_accesses(env);
12693
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012694 if (ret == 0)
Brendan Jackmane6ac5932021-02-17 10:45:09 +000012695 ret = do_misc_fixups(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012696
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012697 /* do 32-bit optimization after insn patching has done so those patched
12698 * insns could be handled correctly.
12699 */
Jiong Wangd6c23082019-05-24 23:25:18 +010012700 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12701 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12702 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12703 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012704 }
12705
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012706 if (ret == 0)
12707 ret = fixup_call_args(env);
12708
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012709 env->verification_time = ktime_get_ns() - start_time;
12710 print_verification_stats(env);
12711
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012712 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012713 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012714 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012715 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012716 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012717 }
12718
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012719 if (ret)
12720 goto err_release_maps;
12721
12722 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012723 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012724 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12725 sizeof(env->used_maps[0]),
12726 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012727
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012728 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012729 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012730 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012731 }
12732
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012733 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012734 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012735 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012736 }
12737 if (env->used_btf_cnt) {
12738 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12739 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12740 sizeof(env->used_btfs[0]),
12741 GFP_KERNEL);
12742 if (!env->prog->aux->used_btfs) {
12743 ret = -ENOMEM;
12744 goto err_release_maps;
12745 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012746
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012747 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12748 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12749 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12750 }
12751 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012752 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12753 * bpf_ld_imm64 instructions
12754 */
12755 convert_pseudo_ld_imm64(env);
12756 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012757
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012758 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080012759
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012760err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012761 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012762 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070012763 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012764 */
12765 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012766 if (!env->prog->aux->used_btfs)
12767 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020012768
12769 /* extension progs temporarily inherit the attach_type of their targets
12770 for verification purposes, so set it back to zero before returning
12771 */
12772 if (env->prog->type == BPF_PROG_TYPE_EXT)
12773 env->prog->expected_attach_type = 0;
12774
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012775 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012776err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012777 if (!is_priv)
12778 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012779 vfree(env->insn_aux_data);
12780err_free_env:
12781 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012782 return ret;
12783}