blob: 11a242932a2c6b623ff947edd05a60849b8717d2 [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
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200393static bool type_is_pkt_pointer(enum bpf_reg_type type)
394{
395 return type == PTR_TO_PACKET ||
396 type == PTR_TO_PACKET_META;
397}
398
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800399static bool type_is_sk_pointer(enum bpf_reg_type type)
400{
401 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800402 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700403 type == PTR_TO_TCP_SOCK ||
404 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800405}
406
John Fastabendcac616d2020-05-21 13:07:26 -0700407static bool reg_type_not_null(enum bpf_reg_type type)
408{
409 return type == PTR_TO_SOCKET ||
410 type == PTR_TO_TCP_SOCK ||
411 type == PTR_TO_MAP_VALUE ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700412 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700413}
414
Joe Stringer840b9612018-10-02 13:35:32 -0700415static bool reg_type_may_be_null(enum bpf_reg_type type)
416{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700417 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800418 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800419 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700420 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700421 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700422 type == PTR_TO_MEM_OR_NULL ||
423 type == PTR_TO_RDONLY_BUF_OR_NULL ||
424 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700425}
426
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800427static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
428{
429 return reg->type == PTR_TO_MAP_VALUE &&
430 map_value_has_spin_lock(reg->map_ptr);
431}
432
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700433static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
434{
435 return type == PTR_TO_SOCKET ||
436 type == PTR_TO_SOCKET_OR_NULL ||
437 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700438 type == PTR_TO_TCP_SOCK_OR_NULL ||
439 type == PTR_TO_MEM ||
440 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700441}
442
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700443static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700444{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700445 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700446}
447
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100448static bool arg_type_may_be_null(enum bpf_arg_type type)
449{
450 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
451 type == ARG_PTR_TO_MEM_OR_NULL ||
452 type == ARG_PTR_TO_CTX_OR_NULL ||
453 type == ARG_PTR_TO_SOCKET_OR_NULL ||
454 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL;
455}
456
Joe Stringerfd978bf72018-10-02 13:35:35 -0700457/* Determine whether the function releases some resources allocated by another
458 * function call. The first reference type argument will be assumed to be
459 * released by release_reference().
460 */
461static bool is_release_function(enum bpf_func_id func_id)
462{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700463 return func_id == BPF_FUNC_sk_release ||
464 func_id == BPF_FUNC_ringbuf_submit ||
465 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700466}
467
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200468static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800469{
470 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800471 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200472 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700473 func_id == BPF_FUNC_map_lookup_elem ||
474 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200475}
476
477static bool is_acquire_function(enum bpf_func_id func_id,
478 const struct bpf_map *map)
479{
480 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
481
482 if (func_id == BPF_FUNC_sk_lookup_tcp ||
483 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700484 func_id == BPF_FUNC_skc_lookup_tcp ||
485 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200486 return true;
487
488 if (func_id == BPF_FUNC_map_lookup_elem &&
489 (map_type == BPF_MAP_TYPE_SOCKMAP ||
490 map_type == BPF_MAP_TYPE_SOCKHASH))
491 return true;
492
493 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800494}
495
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700496static bool is_ptr_cast_function(enum bpf_func_id func_id)
497{
498 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700499 func_id == BPF_FUNC_sk_fullsock ||
500 func_id == BPF_FUNC_skc_to_tcp_sock ||
501 func_id == BPF_FUNC_skc_to_tcp6_sock ||
502 func_id == BPF_FUNC_skc_to_udp6_sock ||
503 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
504 func_id == BPF_FUNC_skc_to_tcp_request_sock;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700505}
506
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700507/* string representation of 'enum bpf_reg_type' */
508static const char * const reg_type_str[] = {
509 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100510 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700511 [PTR_TO_CTX] = "ctx",
512 [CONST_PTR_TO_MAP] = "map_ptr",
513 [PTR_TO_MAP_VALUE] = "map_value",
514 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700515 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700516 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200517 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700518 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700519 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700520 [PTR_TO_SOCKET] = "sock",
521 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800522 [PTR_TO_SOCK_COMMON] = "sock_common",
523 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800524 [PTR_TO_TCP_SOCK] = "tcp_sock",
525 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700526 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700527 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700528 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700529 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700530 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700531 [PTR_TO_MEM] = "mem",
532 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700533 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
534 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
535 [PTR_TO_RDWR_BUF] = "rdwr_buf",
536 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700537};
538
Edward Cree8efea212018-08-22 20:02:44 +0100539static char slot_type_char[] = {
540 [STACK_INVALID] = '?',
541 [STACK_SPILL] = 'r',
542 [STACK_MISC] = 'm',
543 [STACK_ZERO] = '0',
544};
545
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800546static void print_liveness(struct bpf_verifier_env *env,
547 enum bpf_reg_liveness live)
548{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800549 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800550 verbose(env, "_");
551 if (live & REG_LIVE_READ)
552 verbose(env, "r");
553 if (live & REG_LIVE_WRITTEN)
554 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800555 if (live & REG_LIVE_DONE)
556 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800557}
558
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800559static struct bpf_func_state *func(struct bpf_verifier_env *env,
560 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700561{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800562 struct bpf_verifier_state *cur = env->cur_state;
563
564 return cur->frame[reg->frameno];
565}
566
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800567static const char *kernel_type_name(const struct btf* btf, u32 id)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700568{
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800569 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700570}
571
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800572static void print_verifier_state(struct bpf_verifier_env *env,
573 const struct bpf_func_state *state)
574{
575 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700576 enum bpf_reg_type t;
577 int i;
578
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800579 if (state->frameno)
580 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700581 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700582 reg = &state->regs[i];
583 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700584 if (t == NOT_INIT)
585 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800586 verbose(env, " R%d", i);
587 print_liveness(env, reg->live);
588 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700589 if (t == SCALAR_VALUE && reg->precise)
590 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100591 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
592 tnum_is_const(reg->var_off)) {
593 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700594 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100595 } else {
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700596 if (t == PTR_TO_BTF_ID ||
597 t == PTR_TO_BTF_ID_OR_NULL ||
598 t == PTR_TO_PERCPU_BTF_ID)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800599 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700600 verbose(env, "(id=%d", reg->id);
601 if (reg_type_may_be_refcounted_or_null(t))
602 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100603 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700604 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200605 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700606 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100607 else if (t == CONST_PTR_TO_MAP ||
608 t == PTR_TO_MAP_VALUE ||
609 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700610 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100611 reg->map_ptr->key_size,
612 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100613 if (tnum_is_const(reg->var_off)) {
614 /* Typically an immediate SCALAR_VALUE, but
615 * could be a pointer whose offset is too big
616 * for reg->off
617 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700618 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100619 } else {
620 if (reg->smin_value != reg->umin_value &&
621 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700622 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100623 (long long)reg->smin_value);
624 if (reg->smax_value != reg->umax_value &&
625 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700626 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100627 (long long)reg->smax_value);
628 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700629 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100630 (unsigned long long)reg->umin_value);
631 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700632 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100633 (unsigned long long)reg->umax_value);
634 if (!tnum_is_unknown(reg->var_off)) {
635 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100636
Edward Cree7d1238f2017-08-07 15:26:56 +0100637 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700638 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100639 }
John Fastabend3f50f132020-03-30 14:36:39 -0700640 if (reg->s32_min_value != reg->smin_value &&
641 reg->s32_min_value != S32_MIN)
642 verbose(env, ",s32_min_value=%d",
643 (int)(reg->s32_min_value));
644 if (reg->s32_max_value != reg->smax_value &&
645 reg->s32_max_value != S32_MAX)
646 verbose(env, ",s32_max_value=%d",
647 (int)(reg->s32_max_value));
648 if (reg->u32_min_value != reg->umin_value &&
649 reg->u32_min_value != U32_MIN)
650 verbose(env, ",u32_min_value=%d",
651 (int)(reg->u32_min_value));
652 if (reg->u32_max_value != reg->umax_value &&
653 reg->u32_max_value != U32_MAX)
654 verbose(env, ",u32_max_value=%d",
655 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100656 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700657 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100658 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700659 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700660 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100661 char types_buf[BPF_REG_SIZE + 1];
662 bool valid = false;
663 int j;
664
665 for (j = 0; j < BPF_REG_SIZE; j++) {
666 if (state->stack[i].slot_type[j] != STACK_INVALID)
667 valid = true;
668 types_buf[j] = slot_type_char[
669 state->stack[i].slot_type[j]];
670 }
671 types_buf[BPF_REG_SIZE] = 0;
672 if (!valid)
673 continue;
674 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
675 print_liveness(env, state->stack[i].spilled_ptr.live);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700676 if (state->stack[i].slot_type[0] == STACK_SPILL) {
677 reg = &state->stack[i].spilled_ptr;
678 t = reg->type;
679 verbose(env, "=%s", reg_type_str[t]);
680 if (t == SCALAR_VALUE && reg->precise)
681 verbose(env, "P");
682 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
683 verbose(env, "%lld", reg->var_off.value + reg->off);
684 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100685 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700686 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700687 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700688 if (state->acquired_refs && state->refs[0].id) {
689 verbose(env, " refs=%d", state->refs[0].id);
690 for (i = 1; i < state->acquired_refs; i++)
691 if (state->refs[i].id)
692 verbose(env, ",%d", state->refs[i].id);
693 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700694 verbose(env, "\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700695}
696
Joe Stringer84dbf352018-10-02 13:35:34 -0700697#define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \
698static int copy_##NAME##_state(struct bpf_func_state *dst, \
699 const struct bpf_func_state *src) \
700{ \
701 if (!src->FIELD) \
702 return 0; \
703 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \
704 /* internal bug, make state invalid to reject the program */ \
705 memset(dst, 0, sizeof(*dst)); \
706 return -EFAULT; \
707 } \
708 memcpy(dst->FIELD, src->FIELD, \
709 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \
710 return 0; \
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700711}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700712/* copy_reference_state() */
713COPY_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700714/* copy_stack_state() */
715COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
716#undef COPY_STATE_FN
717
718#define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \
719static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \
720 bool copy_old) \
721{ \
722 u32 old_size = state->COUNT; \
723 struct bpf_##NAME##_state *new_##FIELD; \
724 int slot = size / SIZE; \
725 \
726 if (size <= old_size || !size) { \
727 if (copy_old) \
728 return 0; \
729 state->COUNT = slot * SIZE; \
730 if (!size && old_size) { \
731 kfree(state->FIELD); \
732 state->FIELD = NULL; \
733 } \
734 return 0; \
735 } \
736 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \
737 GFP_KERNEL); \
738 if (!new_##FIELD) \
739 return -ENOMEM; \
740 if (copy_old) { \
741 if (state->FIELD) \
742 memcpy(new_##FIELD, state->FIELD, \
743 sizeof(*new_##FIELD) * (old_size / SIZE)); \
744 memset(new_##FIELD + old_size / SIZE, 0, \
745 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \
746 } \
747 state->COUNT = slot * SIZE; \
748 kfree(state->FIELD); \
749 state->FIELD = new_##FIELD; \
750 return 0; \
751}
Joe Stringerfd978bf72018-10-02 13:35:35 -0700752/* realloc_reference_state() */
753REALLOC_STATE_FN(reference, acquired_refs, refs, 1)
Joe Stringer84dbf352018-10-02 13:35:34 -0700754/* realloc_stack_state() */
755REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE)
756#undef REALLOC_STATE_FN
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700757
758/* do_check() starts with zero-sized stack in struct bpf_verifier_state to
759 * make it consume minimal amount of memory. check_stack_write() access from
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800760 * the program calls into realloc_func_state() to grow the stack size.
Joe Stringer84dbf352018-10-02 13:35:34 -0700761 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state
762 * which realloc_stack_state() copies over. It points to previous
763 * bpf_verifier_state which is never reallocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700764 */
Joe Stringerfd978bf72018-10-02 13:35:35 -0700765static int realloc_func_state(struct bpf_func_state *state, int stack_size,
766 int refs_size, bool copy_old)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700767{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700768 int err = realloc_reference_state(state, refs_size, copy_old);
769 if (err)
770 return err;
771 return realloc_stack_state(state, stack_size, copy_old);
772}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700773
Joe Stringerfd978bf72018-10-02 13:35:35 -0700774/* Acquire a pointer id from the env and update the state->refs to include
775 * this new pointer reference.
776 * On success, returns a valid pointer id to associate with the register
777 * On failure, returns a negative errno.
778 */
779static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
780{
781 struct bpf_func_state *state = cur_func(env);
782 int new_ofs = state->acquired_refs;
783 int id, err;
784
785 err = realloc_reference_state(state, state->acquired_refs + 1, true);
786 if (err)
787 return err;
788 id = ++env->id_gen;
789 state->refs[new_ofs].id = id;
790 state->refs[new_ofs].insn_idx = insn_idx;
791
792 return id;
793}
794
795/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800796static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700797{
798 int i, last_idx;
799
Joe Stringerfd978bf72018-10-02 13:35:35 -0700800 last_idx = state->acquired_refs - 1;
801 for (i = 0; i < state->acquired_refs; i++) {
802 if (state->refs[i].id == ptr_id) {
803 if (last_idx && i != last_idx)
804 memcpy(&state->refs[i], &state->refs[last_idx],
805 sizeof(*state->refs));
806 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
807 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700808 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700809 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700810 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800811 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700812}
813
814static int transfer_reference_state(struct bpf_func_state *dst,
815 struct bpf_func_state *src)
816{
817 int err = realloc_reference_state(dst, src->acquired_refs, false);
818 if (err)
819 return err;
820 err = copy_reference_state(dst, src);
821 if (err)
822 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700823 return 0;
824}
825
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800826static void free_func_state(struct bpf_func_state *state)
827{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800828 if (!state)
829 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700830 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800831 kfree(state->stack);
832 kfree(state);
833}
834
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700835static void clear_jmp_history(struct bpf_verifier_state *state)
836{
837 kfree(state->jmp_history);
838 state->jmp_history = NULL;
839 state->jmp_history_cnt = 0;
840}
841
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700842static void free_verifier_state(struct bpf_verifier_state *state,
843 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700844{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800845 int i;
846
847 for (i = 0; i <= state->curframe; i++) {
848 free_func_state(state->frame[i]);
849 state->frame[i] = NULL;
850 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700851 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700852 if (free_self)
853 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700854}
855
856/* copy verifier state from src to dst growing dst stack space
857 * when necessary to accommodate larger src stack
858 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800859static int copy_func_state(struct bpf_func_state *dst,
860 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700861{
862 int err;
863
Joe Stringerfd978bf72018-10-02 13:35:35 -0700864 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs,
865 false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700866 if (err)
867 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700868 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
869 err = copy_reference_state(dst, src);
870 if (err)
871 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700872 return copy_stack_state(dst, src);
873}
874
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800875static int copy_verifier_state(struct bpf_verifier_state *dst_state,
876 const struct bpf_verifier_state *src)
877{
878 struct bpf_func_state *dst;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700879 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800880 int i, err;
881
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700882 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) {
883 kfree(dst_state->jmp_history);
884 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER);
885 if (!dst_state->jmp_history)
886 return -ENOMEM;
887 }
888 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz);
889 dst_state->jmp_history_cnt = src->jmp_history_cnt;
890
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800891 /* if dst has more stack frames then src frame, free them */
892 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
893 free_func_state(dst_state->frame[i]);
894 dst_state->frame[i] = NULL;
895 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100896 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800897 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800898 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -0700899 dst_state->branches = src->branches;
900 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700901 dst_state->first_insn_idx = src->first_insn_idx;
902 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800903 for (i = 0; i <= src->curframe; i++) {
904 dst = dst_state->frame[i];
905 if (!dst) {
906 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
907 if (!dst)
908 return -ENOMEM;
909 dst_state->frame[i] = dst;
910 }
911 err = copy_func_state(dst, src->frame[i]);
912 if (err)
913 return err;
914 }
915 return 0;
916}
917
Alexei Starovoitov25897262019-06-15 12:12:20 -0700918static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
919{
920 while (st) {
921 u32 br = --st->branches;
922
923 /* WARN_ON(br > 1) technically makes sense here,
924 * but see comment in push_stack(), hence:
925 */
926 WARN_ONCE((int)br < 0,
927 "BUG update_branch_counts:branches_to_explore=%d\n",
928 br);
929 if (br)
930 break;
931 st = st->parent;
932 }
933}
934
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700935static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700936 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700937{
938 struct bpf_verifier_state *cur = env->cur_state;
939 struct bpf_verifier_stack_elem *elem, *head = env->head;
940 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700941
942 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700943 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700944
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700945 if (cur) {
946 err = copy_verifier_state(cur, &head->st);
947 if (err)
948 return err;
949 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700950 if (pop_log)
951 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700952 if (insn_idx)
953 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700954 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700955 *prev_insn_idx = head->prev_insn_idx;
956 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700957 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700958 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700959 env->head = elem;
960 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700961 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700962}
963
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100964static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100965 int insn_idx, int prev_insn_idx,
966 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700967{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700968 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100969 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700970 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700971
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700972 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700973 if (!elem)
974 goto err;
975
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700976 elem->insn_idx = insn_idx;
977 elem->prev_insn_idx = prev_insn_idx;
978 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700979 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700980 env->head = elem;
981 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700982 err = copy_verifier_state(&elem->st, cur);
983 if (err)
984 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +0100985 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700986 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
987 verbose(env, "The sequence of %d jumps is too complex.\n",
988 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700989 goto err;
990 }
Alexei Starovoitov25897262019-06-15 12:12:20 -0700991 if (elem->st.parent) {
992 ++elem->st.parent->branches;
993 /* WARN_ON(branches > 2) technically makes sense here,
994 * but
995 * 1. speculative states will bump 'branches' for non-branch
996 * instructions
997 * 2. is_state_visited() heuristics may decide not to create
998 * a new state for a sequence of branches and all such current
999 * and cloned states will be pointing to a single parent state
1000 * which might have large 'branches' count.
1001 */
1002 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001003 return &elem->st;
1004err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001005 free_verifier_state(env->cur_state, true);
1006 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001007 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001008 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001009 return NULL;
1010}
1011
1012#define CALLER_SAVED_REGS 6
1013static const int caller_saved[CALLER_SAVED_REGS] = {
1014 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1015};
1016
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001017static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1018 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001019
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001020/* This helper doesn't clear reg->id */
1021static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001022{
Edward Creeb03c9f92017-08-07 15:26:36 +01001023 reg->var_off = tnum_const(imm);
1024 reg->smin_value = (s64)imm;
1025 reg->smax_value = (s64)imm;
1026 reg->umin_value = imm;
1027 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001028
1029 reg->s32_min_value = (s32)imm;
1030 reg->s32_max_value = (s32)imm;
1031 reg->u32_min_value = (u32)imm;
1032 reg->u32_max_value = (u32)imm;
1033}
1034
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001035/* Mark the unknown part of a register (variable offset or scalar value) as
1036 * known to have the value @imm.
1037 */
1038static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1039{
1040 /* Clear id, off, and union(map_ptr, range) */
1041 memset(((u8 *)reg) + sizeof(reg->type), 0,
1042 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1043 ___mark_reg_known(reg, imm);
1044}
1045
John Fastabend3f50f132020-03-30 14:36:39 -07001046static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1047{
1048 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1049 reg->s32_min_value = (s32)imm;
1050 reg->s32_max_value = (s32)imm;
1051 reg->u32_min_value = (u32)imm;
1052 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001053}
1054
Edward Creef1174f72017-08-07 15:26:19 +01001055/* Mark the 'variable offset' part of a register as zero. This should be
1056 * used only on registers holding a pointer type.
1057 */
1058static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1059{
Edward Creeb03c9f92017-08-07 15:26:36 +01001060 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001061}
1062
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001063static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1064{
1065 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001066 reg->type = SCALAR_VALUE;
1067}
1068
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001069static void mark_reg_known_zero(struct bpf_verifier_env *env,
1070 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001071{
1072 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001073 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001074 /* Something bad happened, let's kill all regs */
1075 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001076 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001077 return;
1078 }
1079 __mark_reg_known_zero(regs + regno);
1080}
1081
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001082static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1083{
1084 switch (reg->type) {
1085 case PTR_TO_MAP_VALUE_OR_NULL: {
1086 const struct bpf_map *map = reg->map_ptr;
1087
1088 if (map->inner_map_meta) {
1089 reg->type = CONST_PTR_TO_MAP;
1090 reg->map_ptr = map->inner_map_meta;
1091 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1092 reg->type = PTR_TO_XDP_SOCK;
1093 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1094 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1095 reg->type = PTR_TO_SOCKET;
1096 } else {
1097 reg->type = PTR_TO_MAP_VALUE;
1098 }
1099 break;
1100 }
1101 case PTR_TO_SOCKET_OR_NULL:
1102 reg->type = PTR_TO_SOCKET;
1103 break;
1104 case PTR_TO_SOCK_COMMON_OR_NULL:
1105 reg->type = PTR_TO_SOCK_COMMON;
1106 break;
1107 case PTR_TO_TCP_SOCK_OR_NULL:
1108 reg->type = PTR_TO_TCP_SOCK;
1109 break;
1110 case PTR_TO_BTF_ID_OR_NULL:
1111 reg->type = PTR_TO_BTF_ID;
1112 break;
1113 case PTR_TO_MEM_OR_NULL:
1114 reg->type = PTR_TO_MEM;
1115 break;
1116 case PTR_TO_RDONLY_BUF_OR_NULL:
1117 reg->type = PTR_TO_RDONLY_BUF;
1118 break;
1119 case PTR_TO_RDWR_BUF_OR_NULL:
1120 reg->type = PTR_TO_RDWR_BUF;
1121 break;
1122 default:
1123 WARN_ON("unknown nullable register type");
1124 }
1125}
1126
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001127static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1128{
1129 return type_is_pkt_pointer(reg->type);
1130}
1131
1132static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1133{
1134 return reg_is_pkt_pointer(reg) ||
1135 reg->type == PTR_TO_PACKET_END;
1136}
1137
1138/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1139static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1140 enum bpf_reg_type which)
1141{
1142 /* The register can already have a range from prior markings.
1143 * This is fine as long as it hasn't been advanced from its
1144 * origin.
1145 */
1146 return reg->type == which &&
1147 reg->id == 0 &&
1148 reg->off == 0 &&
1149 tnum_equals_const(reg->var_off, 0);
1150}
1151
John Fastabend3f50f132020-03-30 14:36:39 -07001152/* Reset the min/max bounds of a register */
1153static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1154{
1155 reg->smin_value = S64_MIN;
1156 reg->smax_value = S64_MAX;
1157 reg->umin_value = 0;
1158 reg->umax_value = U64_MAX;
1159
1160 reg->s32_min_value = S32_MIN;
1161 reg->s32_max_value = S32_MAX;
1162 reg->u32_min_value = 0;
1163 reg->u32_max_value = U32_MAX;
1164}
1165
1166static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1167{
1168 reg->smin_value = S64_MIN;
1169 reg->smax_value = S64_MAX;
1170 reg->umin_value = 0;
1171 reg->umax_value = U64_MAX;
1172}
1173
1174static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1175{
1176 reg->s32_min_value = S32_MIN;
1177 reg->s32_max_value = S32_MAX;
1178 reg->u32_min_value = 0;
1179 reg->u32_max_value = U32_MAX;
1180}
1181
1182static void __update_reg32_bounds(struct bpf_reg_state *reg)
1183{
1184 struct tnum var32_off = tnum_subreg(reg->var_off);
1185
1186 /* min signed is max(sign bit) | min(other bits) */
1187 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1188 var32_off.value | (var32_off.mask & S32_MIN));
1189 /* max signed is min(sign bit) | max(other bits) */
1190 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1191 var32_off.value | (var32_off.mask & S32_MAX));
1192 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1193 reg->u32_max_value = min(reg->u32_max_value,
1194 (u32)(var32_off.value | var32_off.mask));
1195}
1196
1197static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001198{
1199 /* min signed is max(sign bit) | min(other bits) */
1200 reg->smin_value = max_t(s64, reg->smin_value,
1201 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1202 /* max signed is min(sign bit) | max(other bits) */
1203 reg->smax_value = min_t(s64, reg->smax_value,
1204 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1205 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1206 reg->umax_value = min(reg->umax_value,
1207 reg->var_off.value | reg->var_off.mask);
1208}
1209
John Fastabend3f50f132020-03-30 14:36:39 -07001210static void __update_reg_bounds(struct bpf_reg_state *reg)
1211{
1212 __update_reg32_bounds(reg);
1213 __update_reg64_bounds(reg);
1214}
1215
Edward Creeb03c9f92017-08-07 15:26:36 +01001216/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001217static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1218{
1219 /* Learn sign from signed bounds.
1220 * If we cannot cross the sign boundary, then signed and unsigned bounds
1221 * are the same, so combine. This works even in the negative case, e.g.
1222 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1223 */
1224 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1225 reg->s32_min_value = reg->u32_min_value =
1226 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1227 reg->s32_max_value = reg->u32_max_value =
1228 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1229 return;
1230 }
1231 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1232 * boundary, so we must be careful.
1233 */
1234 if ((s32)reg->u32_max_value >= 0) {
1235 /* Positive. We can't learn anything from the smin, but smax
1236 * is positive, hence safe.
1237 */
1238 reg->s32_min_value = reg->u32_min_value;
1239 reg->s32_max_value = reg->u32_max_value =
1240 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1241 } else if ((s32)reg->u32_min_value < 0) {
1242 /* Negative. We can't learn anything from the smax, but smin
1243 * is negative, hence safe.
1244 */
1245 reg->s32_min_value = reg->u32_min_value =
1246 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1247 reg->s32_max_value = reg->u32_max_value;
1248 }
1249}
1250
1251static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001252{
1253 /* Learn sign from signed bounds.
1254 * If we cannot cross the sign boundary, then signed and unsigned bounds
1255 * are the same, so combine. This works even in the negative case, e.g.
1256 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1257 */
1258 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1259 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1260 reg->umin_value);
1261 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1262 reg->umax_value);
1263 return;
1264 }
1265 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1266 * boundary, so we must be careful.
1267 */
1268 if ((s64)reg->umax_value >= 0) {
1269 /* Positive. We can't learn anything from the smin, but smax
1270 * is positive, hence safe.
1271 */
1272 reg->smin_value = reg->umin_value;
1273 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1274 reg->umax_value);
1275 } else if ((s64)reg->umin_value < 0) {
1276 /* Negative. We can't learn anything from the smax, but smin
1277 * is negative, hence safe.
1278 */
1279 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1280 reg->umin_value);
1281 reg->smax_value = reg->umax_value;
1282 }
1283}
1284
John Fastabend3f50f132020-03-30 14:36:39 -07001285static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1286{
1287 __reg32_deduce_bounds(reg);
1288 __reg64_deduce_bounds(reg);
1289}
1290
Edward Creeb03c9f92017-08-07 15:26:36 +01001291/* Attempts to improve var_off based on unsigned min/max information */
1292static void __reg_bound_offset(struct bpf_reg_state *reg)
1293{
John Fastabend3f50f132020-03-30 14:36:39 -07001294 struct tnum var64_off = tnum_intersect(reg->var_off,
1295 tnum_range(reg->umin_value,
1296 reg->umax_value));
1297 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1298 tnum_range(reg->u32_min_value,
1299 reg->u32_max_value));
1300
1301 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001302}
1303
John Fastabend3f50f132020-03-30 14:36:39 -07001304static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001305{
John Fastabend3f50f132020-03-30 14:36:39 -07001306 reg->umin_value = reg->u32_min_value;
1307 reg->umax_value = reg->u32_max_value;
1308 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1309 * but must be positive otherwise set to worse case bounds
1310 * and refine later from tnum.
1311 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001312 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001313 reg->smax_value = reg->s32_max_value;
1314 else
1315 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001316 if (reg->s32_min_value >= 0)
1317 reg->smin_value = reg->s32_min_value;
1318 else
1319 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001320}
1321
1322static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1323{
1324 /* special case when 64-bit register has upper 32-bit register
1325 * zeroed. Typically happens after zext or <<32, >>32 sequence
1326 * allowing us to use 32-bit bounds directly,
1327 */
1328 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1329 __reg_assign_32_into_64(reg);
1330 } else {
1331 /* Otherwise the best we can do is push lower 32bit known and
1332 * unknown bits into register (var_off set from jmp logic)
1333 * then learn as much as possible from the 64-bit tnum
1334 * known and unknown bits. The previous smin/smax bounds are
1335 * invalid here because of jmp32 compare so mark them unknown
1336 * so they do not impact tnum bounds calculation.
1337 */
1338 __mark_reg64_unbounded(reg);
1339 __update_reg_bounds(reg);
1340 }
1341
1342 /* Intersecting with the old var_off might have improved our bounds
1343 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1344 * then new var_off is (0; 0x7f...fc) which improves our umax.
1345 */
1346 __reg_deduce_bounds(reg);
1347 __reg_bound_offset(reg);
1348 __update_reg_bounds(reg);
1349}
1350
1351static bool __reg64_bound_s32(s64 a)
1352{
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001353 return a > S32_MIN && a < S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001354}
1355
1356static bool __reg64_bound_u32(u64 a)
1357{
1358 if (a > U32_MIN && a < U32_MAX)
1359 return true;
1360 return false;
1361}
1362
1363static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1364{
1365 __mark_reg32_unbounded(reg);
1366
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001367 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001368 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001369 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001370 }
John Fastabend3f50f132020-03-30 14:36:39 -07001371 if (__reg64_bound_u32(reg->umin_value))
1372 reg->u32_min_value = (u32)reg->umin_value;
1373 if (__reg64_bound_u32(reg->umax_value))
1374 reg->u32_max_value = (u32)reg->umax_value;
1375
1376 /* Intersecting with the old var_off might have improved our bounds
1377 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1378 * then new var_off is (0; 0x7f...fc) which improves our umax.
1379 */
1380 __reg_deduce_bounds(reg);
1381 __reg_bound_offset(reg);
1382 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001383}
1384
Edward Creef1174f72017-08-07 15:26:19 +01001385/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001386static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1387 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001388{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001389 /*
1390 * Clear type, id, off, and union(map_ptr, range) and
1391 * padding between 'type' and union
1392 */
1393 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001394 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001395 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001396 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001397 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001398 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001399}
1400
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001401static void mark_reg_unknown(struct bpf_verifier_env *env,
1402 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001403{
1404 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001405 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001406 /* Something bad happened, let's kill all regs except FP */
1407 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001408 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001409 return;
1410 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001411 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001412}
1413
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001414static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1415 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001416{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001417 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001418 reg->type = NOT_INIT;
1419}
1420
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001421static void mark_reg_not_init(struct bpf_verifier_env *env,
1422 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001423{
Edward Creef1174f72017-08-07 15:26:19 +01001424 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001425 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001426 /* Something bad happened, let's kill all regs except FP */
1427 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001428 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001429 return;
1430 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001431 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001432}
1433
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001434static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1435 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001436 enum bpf_reg_type reg_type,
1437 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001438{
1439 if (reg_type == SCALAR_VALUE) {
1440 mark_reg_unknown(env, regs, regno);
1441 return;
1442 }
1443 mark_reg_known_zero(env, regs, regno);
1444 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001445 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001446 regs[regno].btf_id = btf_id;
1447}
1448
Jiong Wang5327ed32019-05-24 23:25:12 +01001449#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001450static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001451 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001452{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001453 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001454 int i;
1455
Edward Creedc503a82017-08-15 20:34:35 +01001456 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001457 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001458 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001459 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001460 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001461 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001462
1463 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001464 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001465 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001466 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001467}
1468
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001469#define BPF_MAIN_FUNC (-1)
1470static void init_func_state(struct bpf_verifier_env *env,
1471 struct bpf_func_state *state,
1472 int callsite, int frameno, int subprogno)
1473{
1474 state->callsite = callsite;
1475 state->frameno = frameno;
1476 state->subprogno = subprogno;
1477 init_reg_state(env, state);
1478}
1479
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001480enum reg_arg_type {
1481 SRC_OP, /* register is used as source operand */
1482 DST_OP, /* register is used as destination operand */
1483 DST_OP_NO_MARK /* same as above, check only, don't mark */
1484};
1485
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001486static int cmp_subprogs(const void *a, const void *b)
1487{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001488 return ((struct bpf_subprog_info *)a)->start -
1489 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001490}
1491
1492static int find_subprog(struct bpf_verifier_env *env, int off)
1493{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001494 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001495
Jiong Wang9c8105b2018-05-02 16:17:18 -04001496 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1497 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001498 if (!p)
1499 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001500 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001501
1502}
1503
1504static int add_subprog(struct bpf_verifier_env *env, int off)
1505{
1506 int insn_cnt = env->prog->len;
1507 int ret;
1508
1509 if (off >= insn_cnt || off < 0) {
1510 verbose(env, "call to invalid destination\n");
1511 return -EINVAL;
1512 }
1513 ret = find_subprog(env, off);
1514 if (ret >= 0)
1515 return 0;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001516 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001517 verbose(env, "too many subprograms\n");
1518 return -E2BIG;
1519 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04001520 env->subprog_info[env->subprog_cnt++].start = off;
1521 sort(env->subprog_info, env->subprog_cnt,
1522 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001523 return 0;
1524}
1525
1526static int check_subprogs(struct bpf_verifier_env *env)
1527{
1528 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001529 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001530 struct bpf_insn *insn = env->prog->insnsi;
1531 int insn_cnt = env->prog->len;
1532
Jiong Wangf910cef2018-05-02 16:17:17 -04001533 /* Add entry function. */
1534 ret = add_subprog(env, 0);
1535 if (ret < 0)
1536 return ret;
1537
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001538 /* determine subprog starts. The end is one before the next starts */
1539 for (i = 0; i < insn_cnt; i++) {
Yonghong Song23a2d702021-02-04 15:48:27 -08001540 if (!bpf_pseudo_call(insn + i))
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001541 continue;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001542 if (!env->bpf_capable) {
1543 verbose(env,
1544 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001545 return -EPERM;
1546 }
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001547 ret = add_subprog(env, i + insn[i].imm + 1);
1548 if (ret < 0)
1549 return ret;
1550 }
1551
Jiong Wang4cb3d992018-05-02 16:17:19 -04001552 /* Add a fake 'exit' subprog which could simplify subprog iteration
1553 * logic. 'subprog_cnt' should not be increased.
1554 */
1555 subprog[env->subprog_cnt].start = insn_cnt;
1556
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001557 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001558 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001559 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001560
1561 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04001562 subprog_start = subprog[cur_subprog].start;
1563 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001564 for (i = 0; i < insn_cnt; i++) {
1565 u8 code = insn[i].code;
1566
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02001567 if (code == (BPF_JMP | BPF_CALL) &&
1568 insn[i].imm == BPF_FUNC_tail_call &&
1569 insn[i].src_reg != BPF_PSEUDO_CALL)
1570 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07001571 if (BPF_CLASS(code) == BPF_LD &&
1572 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
1573 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05001574 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001575 goto next;
1576 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
1577 goto next;
1578 off = i + insn[i].off + 1;
1579 if (off < subprog_start || off >= subprog_end) {
1580 verbose(env, "jump out of range from insn %d to %d\n", i, off);
1581 return -EINVAL;
1582 }
1583next:
1584 if (i == subprog_end - 1) {
1585 /* to avoid fall-through from one subprog into another
1586 * the last insn of the subprog should be either exit
1587 * or unconditional jump back
1588 */
1589 if (code != (BPF_JMP | BPF_EXIT) &&
1590 code != (BPF_JMP | BPF_JA)) {
1591 verbose(env, "last insn is not an exit or jmp\n");
1592 return -EINVAL;
1593 }
1594 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001595 cur_subprog++;
1596 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04001597 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001598 }
1599 }
1600 return 0;
1601}
1602
Edward Cree679c7822018-08-22 20:02:19 +01001603/* Parentage chain of this register (or stack slot) should take care of all
1604 * issues like callee-saved registers, stack slot allocation time, etc.
1605 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001606static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01001607 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01001608 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001609{
1610 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001611 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01001612
1613 while (parent) {
1614 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01001615 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01001616 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08001617 if (parent->live & REG_LIVE_DONE) {
1618 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
1619 reg_type_str[parent->type],
1620 parent->var_off.value, parent->off);
1621 return -EFAULT;
1622 }
Jiong Wang5327ed32019-05-24 23:25:12 +01001623 /* The first condition is more likely to be true than the
1624 * second, checked it first.
1625 */
1626 if ((parent->live & REG_LIVE_READ) == flag ||
1627 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001628 /* The parentage chain never changes and
1629 * this parent was already marked as LIVE_READ.
1630 * There is no need to keep walking the chain again and
1631 * keep re-marking all parents as LIVE_READ.
1632 * This case happens when the same register is read
1633 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01001634 * Also, if parent has the stronger REG_LIVE_READ64 set,
1635 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07001636 */
1637 break;
Edward Creedc503a82017-08-15 20:34:35 +01001638 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01001639 parent->live |= flag;
1640 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
1641 if (flag == REG_LIVE_READ64)
1642 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01001643 state = parent;
1644 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001645 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001646 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01001647 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07001648
1649 if (env->longest_mark_read_walk < cnt)
1650 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001651 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01001652}
1653
Jiong Wang5327ed32019-05-24 23:25:12 +01001654/* This function is supposed to be used by the following 32-bit optimization
1655 * code only. It returns TRUE if the source or destination register operates
1656 * on 64-bit, otherwise return FALSE.
1657 */
1658static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
1659 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
1660{
1661 u8 code, class, op;
1662
1663 code = insn->code;
1664 class = BPF_CLASS(code);
1665 op = BPF_OP(code);
1666 if (class == BPF_JMP) {
1667 /* BPF_EXIT for "main" will reach here. Return TRUE
1668 * conservatively.
1669 */
1670 if (op == BPF_EXIT)
1671 return true;
1672 if (op == BPF_CALL) {
1673 /* BPF to BPF call will reach here because of marking
1674 * caller saved clobber with DST_OP_NO_MARK for which we
1675 * don't care the register def because they are anyway
1676 * marked as NOT_INIT already.
1677 */
1678 if (insn->src_reg == BPF_PSEUDO_CALL)
1679 return false;
1680 /* Helper call will reach here because of arg type
1681 * check, conservatively return TRUE.
1682 */
1683 if (t == SRC_OP)
1684 return true;
1685
1686 return false;
1687 }
1688 }
1689
1690 if (class == BPF_ALU64 || class == BPF_JMP ||
1691 /* BPF_END always use BPF_ALU class. */
1692 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
1693 return true;
1694
1695 if (class == BPF_ALU || class == BPF_JMP32)
1696 return false;
1697
1698 if (class == BPF_LDX) {
1699 if (t != SRC_OP)
1700 return BPF_SIZE(code) == BPF_DW;
1701 /* LDX source must be ptr. */
1702 return true;
1703 }
1704
1705 if (class == BPF_STX) {
1706 if (reg->type != SCALAR_VALUE)
1707 return true;
1708 return BPF_SIZE(code) == BPF_DW;
1709 }
1710
1711 if (class == BPF_LD) {
1712 u8 mode = BPF_MODE(code);
1713
1714 /* LD_IMM64 */
1715 if (mode == BPF_IMM)
1716 return true;
1717
1718 /* Both LD_IND and LD_ABS return 32-bit data. */
1719 if (t != SRC_OP)
1720 return false;
1721
1722 /* Implicit ctx ptr. */
1723 if (regno == BPF_REG_6)
1724 return true;
1725
1726 /* Explicit source could be any width. */
1727 return true;
1728 }
1729
1730 if (class == BPF_ST)
1731 /* The only source register for BPF_ST is a ptr. */
1732 return true;
1733
1734 /* Conservatively return true at default. */
1735 return true;
1736}
1737
Jiong Wangb325fbc2019-05-24 23:25:13 +01001738/* Return TRUE if INSN doesn't have explicit value define. */
1739static bool insn_no_def(struct bpf_insn *insn)
1740{
1741 u8 class = BPF_CLASS(insn->code);
1742
1743 return (class == BPF_JMP || class == BPF_JMP32 ||
1744 class == BPF_STX || class == BPF_ST);
1745}
1746
1747/* Return TRUE if INSN has defined any 32-bit value explicitly. */
1748static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
1749{
1750 if (insn_no_def(insn))
1751 return false;
1752
1753 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP);
1754}
1755
Jiong Wang5327ed32019-05-24 23:25:12 +01001756static void mark_insn_zext(struct bpf_verifier_env *env,
1757 struct bpf_reg_state *reg)
1758{
1759 s32 def_idx = reg->subreg_def;
1760
1761 if (def_idx == DEF_NOT_SUBREG)
1762 return;
1763
1764 env->insn_aux_data[def_idx - 1].zext_dst = true;
1765 /* The dst will be zero extended, so won't be sub-register anymore. */
1766 reg->subreg_def = DEF_NOT_SUBREG;
1767}
1768
Edward Creedc503a82017-08-15 20:34:35 +01001769static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001770 enum reg_arg_type t)
1771{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001772 struct bpf_verifier_state *vstate = env->cur_state;
1773 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01001774 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01001775 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01001776 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01001777
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001778 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001779 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001780 return -EINVAL;
1781 }
1782
Jiong Wangc342dc12019-04-12 22:59:37 +01001783 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01001784 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001785 if (t == SRC_OP) {
1786 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01001787 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001788 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001789 return -EACCES;
1790 }
Edward Cree679c7822018-08-22 20:02:19 +01001791 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01001792 if (regno == BPF_REG_FP)
1793 return 0;
1794
Jiong Wang5327ed32019-05-24 23:25:12 +01001795 if (rw64)
1796 mark_insn_zext(env, reg);
1797
1798 return mark_reg_read(env, reg, reg->parent,
1799 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001800 } else {
1801 /* check whether register used as dest operand can be written to */
1802 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001803 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001804 return -EACCES;
1805 }
Jiong Wangc342dc12019-04-12 22:59:37 +01001806 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01001807 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001808 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001809 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001810 }
1811 return 0;
1812}
1813
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001814/* for any branch, call, exit record the history of jmps in the given state */
1815static int push_jmp_history(struct bpf_verifier_env *env,
1816 struct bpf_verifier_state *cur)
1817{
1818 u32 cnt = cur->jmp_history_cnt;
1819 struct bpf_idx_pair *p;
1820
1821 cnt++;
1822 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
1823 if (!p)
1824 return -ENOMEM;
1825 p[cnt - 1].idx = env->insn_idx;
1826 p[cnt - 1].prev_idx = env->prev_insn_idx;
1827 cur->jmp_history = p;
1828 cur->jmp_history_cnt = cnt;
1829 return 0;
1830}
1831
1832/* Backtrack one insn at a time. If idx is not at the top of recorded
1833 * history then previous instruction came from straight line execution.
1834 */
1835static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
1836 u32 *history)
1837{
1838 u32 cnt = *history;
1839
1840 if (cnt && st->jmp_history[cnt - 1].idx == i) {
1841 i = st->jmp_history[cnt - 1].prev_idx;
1842 (*history)--;
1843 } else {
1844 i--;
1845 }
1846 return i;
1847}
1848
1849/* For given verifier state backtrack_insn() is called from the last insn to
1850 * the first insn. Its purpose is to compute a bitmask of registers and
1851 * stack slots that needs precision in the parent verifier state.
1852 */
1853static int backtrack_insn(struct bpf_verifier_env *env, int idx,
1854 u32 *reg_mask, u64 *stack_mask)
1855{
1856 const struct bpf_insn_cbs cbs = {
1857 .cb_print = verbose,
1858 .private_data = env,
1859 };
1860 struct bpf_insn *insn = env->prog->insnsi + idx;
1861 u8 class = BPF_CLASS(insn->code);
1862 u8 opcode = BPF_OP(insn->code);
1863 u8 mode = BPF_MODE(insn->code);
1864 u32 dreg = 1u << insn->dst_reg;
1865 u32 sreg = 1u << insn->src_reg;
1866 u32 spi;
1867
1868 if (insn->code == 0)
1869 return 0;
1870 if (env->log.level & BPF_LOG_LEVEL) {
1871 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
1872 verbose(env, "%d: ", idx);
1873 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
1874 }
1875
1876 if (class == BPF_ALU || class == BPF_ALU64) {
1877 if (!(*reg_mask & dreg))
1878 return 0;
1879 if (opcode == BPF_MOV) {
1880 if (BPF_SRC(insn->code) == BPF_X) {
1881 /* dreg = sreg
1882 * dreg needs precision after this insn
1883 * sreg needs precision before this insn
1884 */
1885 *reg_mask &= ~dreg;
1886 *reg_mask |= sreg;
1887 } else {
1888 /* dreg = K
1889 * dreg needs precision after this insn.
1890 * Corresponding register is already marked
1891 * as precise=true in this verifier state.
1892 * No further markings in parent are necessary
1893 */
1894 *reg_mask &= ~dreg;
1895 }
1896 } else {
1897 if (BPF_SRC(insn->code) == BPF_X) {
1898 /* dreg += sreg
1899 * both dreg and sreg need precision
1900 * before this insn
1901 */
1902 *reg_mask |= sreg;
1903 } /* else dreg += K
1904 * dreg still needs precision before this insn
1905 */
1906 }
1907 } else if (class == BPF_LDX) {
1908 if (!(*reg_mask & dreg))
1909 return 0;
1910 *reg_mask &= ~dreg;
1911
1912 /* scalars can only be spilled into stack w/o losing precision.
1913 * Load from any other memory can be zero extended.
1914 * The desire to keep that precision is already indicated
1915 * by 'precise' mark in corresponding register of this state.
1916 * No further tracking necessary.
1917 */
1918 if (insn->src_reg != BPF_REG_FP)
1919 return 0;
1920 if (BPF_SIZE(insn->code) != BPF_DW)
1921 return 0;
1922
1923 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
1924 * that [fp - off] slot contains scalar that needs to be
1925 * tracked with precision
1926 */
1927 spi = (-insn->off - 1) / BPF_REG_SIZE;
1928 if (spi >= 64) {
1929 verbose(env, "BUG spi %d\n", spi);
1930 WARN_ONCE(1, "verifier backtracking bug");
1931 return -EFAULT;
1932 }
1933 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001934 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001935 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001936 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001937 * to access memory. It means backtracking
1938 * encountered a case of pointer subtraction.
1939 */
1940 return -ENOTSUPP;
1941 /* scalars can only be spilled into stack */
1942 if (insn->dst_reg != BPF_REG_FP)
1943 return 0;
1944 if (BPF_SIZE(insn->code) != BPF_DW)
1945 return 0;
1946 spi = (-insn->off - 1) / BPF_REG_SIZE;
1947 if (spi >= 64) {
1948 verbose(env, "BUG spi %d\n", spi);
1949 WARN_ONCE(1, "verifier backtracking bug");
1950 return -EFAULT;
1951 }
1952 if (!(*stack_mask & (1ull << spi)))
1953 return 0;
1954 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07001955 if (class == BPF_STX)
1956 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001957 } else if (class == BPF_JMP || class == BPF_JMP32) {
1958 if (opcode == BPF_CALL) {
1959 if (insn->src_reg == BPF_PSEUDO_CALL)
1960 return -ENOTSUPP;
1961 /* regular helper call sets R0 */
1962 *reg_mask &= ~1;
1963 if (*reg_mask & 0x3f) {
1964 /* if backtracing was looking for registers R1-R5
1965 * they should have been found already.
1966 */
1967 verbose(env, "BUG regs %x\n", *reg_mask);
1968 WARN_ONCE(1, "verifier backtracking bug");
1969 return -EFAULT;
1970 }
1971 } else if (opcode == BPF_EXIT) {
1972 return -ENOTSUPP;
1973 }
1974 } else if (class == BPF_LD) {
1975 if (!(*reg_mask & dreg))
1976 return 0;
1977 *reg_mask &= ~dreg;
1978 /* It's ld_imm64 or ld_abs or ld_ind.
1979 * For ld_imm64 no further tracking of precision
1980 * into parent is necessary
1981 */
1982 if (mode == BPF_IND || mode == BPF_ABS)
1983 /* to be analyzed */
1984 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001985 }
1986 return 0;
1987}
1988
1989/* the scalar precision tracking algorithm:
1990 * . at the start all registers have precise=false.
1991 * . scalar ranges are tracked as normal through alu and jmp insns.
1992 * . once precise value of the scalar register is used in:
1993 * . ptr + scalar alu
1994 * . if (scalar cond K|scalar)
1995 * . helper_call(.., scalar, ...) where ARG_CONST is expected
1996 * backtrack through the verifier states and mark all registers and
1997 * stack slots with spilled constants that these scalar regisers
1998 * should be precise.
1999 * . during state pruning two registers (or spilled stack slots)
2000 * are equivalent if both are not precise.
2001 *
2002 * Note the verifier cannot simply walk register parentage chain,
2003 * since many different registers and stack slots could have been
2004 * used to compute single precise scalar.
2005 *
2006 * The approach of starting with precise=true for all registers and then
2007 * backtrack to mark a register as not precise when the verifier detects
2008 * that program doesn't care about specific value (e.g., when helper
2009 * takes register as ARG_ANYTHING parameter) is not safe.
2010 *
2011 * It's ok to walk single parentage chain of the verifier states.
2012 * It's possible that this backtracking will go all the way till 1st insn.
2013 * All other branches will be explored for needing precision later.
2014 *
2015 * The backtracking needs to deal with cases like:
2016 * 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)
2017 * r9 -= r8
2018 * r5 = r9
2019 * if r5 > 0x79f goto pc+7
2020 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2021 * r5 += 1
2022 * ...
2023 * call bpf_perf_event_output#25
2024 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2025 *
2026 * and this case:
2027 * r6 = 1
2028 * call foo // uses callee's r6 inside to compute r0
2029 * r0 += r6
2030 * if r0 == 0 goto
2031 *
2032 * to track above reg_mask/stack_mask needs to be independent for each frame.
2033 *
2034 * Also if parent's curframe > frame where backtracking started,
2035 * the verifier need to mark registers in both frames, otherwise callees
2036 * may incorrectly prune callers. This is similar to
2037 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2038 *
2039 * For now backtracking falls back into conservative marking.
2040 */
2041static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2042 struct bpf_verifier_state *st)
2043{
2044 struct bpf_func_state *func;
2045 struct bpf_reg_state *reg;
2046 int i, j;
2047
2048 /* big hammer: mark all scalars precise in this path.
2049 * pop_stack may still get !precise scalars.
2050 */
2051 for (; st; st = st->parent)
2052 for (i = 0; i <= st->curframe; i++) {
2053 func = st->frame[i];
2054 for (j = 0; j < BPF_REG_FP; j++) {
2055 reg = &func->regs[j];
2056 if (reg->type != SCALAR_VALUE)
2057 continue;
2058 reg->precise = true;
2059 }
2060 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
2061 if (func->stack[j].slot_type[0] != STACK_SPILL)
2062 continue;
2063 reg = &func->stack[j].spilled_ptr;
2064 if (reg->type != SCALAR_VALUE)
2065 continue;
2066 reg->precise = true;
2067 }
2068 }
2069}
2070
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002071static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2072 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002073{
2074 struct bpf_verifier_state *st = env->cur_state;
2075 int first_idx = st->first_insn_idx;
2076 int last_idx = env->insn_idx;
2077 struct bpf_func_state *func;
2078 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002079 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2080 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002081 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002082 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002083 int i, err;
2084
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002085 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002086 return 0;
2087
2088 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002089 if (regno >= 0) {
2090 reg = &func->regs[regno];
2091 if (reg->type != SCALAR_VALUE) {
2092 WARN_ONCE(1, "backtracing misuse");
2093 return -EFAULT;
2094 }
2095 if (!reg->precise)
2096 new_marks = true;
2097 else
2098 reg_mask = 0;
2099 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002100 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002101
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002102 while (spi >= 0) {
2103 if (func->stack[spi].slot_type[0] != STACK_SPILL) {
2104 stack_mask = 0;
2105 break;
2106 }
2107 reg = &func->stack[spi].spilled_ptr;
2108 if (reg->type != SCALAR_VALUE) {
2109 stack_mask = 0;
2110 break;
2111 }
2112 if (!reg->precise)
2113 new_marks = true;
2114 else
2115 stack_mask = 0;
2116 reg->precise = true;
2117 break;
2118 }
2119
2120 if (!new_marks)
2121 return 0;
2122 if (!reg_mask && !stack_mask)
2123 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002124 for (;;) {
2125 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002126 u32 history = st->jmp_history_cnt;
2127
2128 if (env->log.level & BPF_LOG_LEVEL)
2129 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2130 for (i = last_idx;;) {
2131 if (skip_first) {
2132 err = 0;
2133 skip_first = false;
2134 } else {
2135 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2136 }
2137 if (err == -ENOTSUPP) {
2138 mark_all_scalars_precise(env, st);
2139 return 0;
2140 } else if (err) {
2141 return err;
2142 }
2143 if (!reg_mask && !stack_mask)
2144 /* Found assignment(s) into tracked register in this state.
2145 * Since this state is already marked, just return.
2146 * Nothing to be tracked further in the parent state.
2147 */
2148 return 0;
2149 if (i == first_idx)
2150 break;
2151 i = get_prev_insn_idx(st, i, &history);
2152 if (i >= env->prog->len) {
2153 /* This can happen if backtracking reached insn 0
2154 * and there are still reg_mask or stack_mask
2155 * to backtrack.
2156 * It means the backtracking missed the spot where
2157 * particular register was initialized with a constant.
2158 */
2159 verbose(env, "BUG backtracking idx %d\n", i);
2160 WARN_ONCE(1, "verifier backtracking bug");
2161 return -EFAULT;
2162 }
2163 }
2164 st = st->parent;
2165 if (!st)
2166 break;
2167
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002168 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002169 func = st->frame[st->curframe];
2170 bitmap_from_u64(mask, reg_mask);
2171 for_each_set_bit(i, mask, 32) {
2172 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002173 if (reg->type != SCALAR_VALUE) {
2174 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002175 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002176 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002177 if (!reg->precise)
2178 new_marks = true;
2179 reg->precise = true;
2180 }
2181
2182 bitmap_from_u64(mask, stack_mask);
2183 for_each_set_bit(i, mask, 64) {
2184 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002185 /* the sequence of instructions:
2186 * 2: (bf) r3 = r10
2187 * 3: (7b) *(u64 *)(r3 -8) = r0
2188 * 4: (79) r4 = *(u64 *)(r10 -8)
2189 * doesn't contain jmps. It's backtracked
2190 * as a single block.
2191 * During backtracking insn 3 is not recognized as
2192 * stack access, so at the end of backtracking
2193 * stack slot fp-8 is still marked in stack_mask.
2194 * However the parent state may not have accessed
2195 * fp-8 and it's "unallocated" stack space.
2196 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002197 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002198 mark_all_scalars_precise(env, st);
2199 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002200 }
2201
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002202 if (func->stack[i].slot_type[0] != STACK_SPILL) {
2203 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002204 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002205 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002206 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002207 if (reg->type != SCALAR_VALUE) {
2208 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002209 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002210 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002211 if (!reg->precise)
2212 new_marks = true;
2213 reg->precise = true;
2214 }
2215 if (env->log.level & BPF_LOG_LEVEL) {
2216 print_verifier_state(env, func);
2217 verbose(env, "parent %s regs=%x stack=%llx marks\n",
2218 new_marks ? "didn't have" : "already had",
2219 reg_mask, stack_mask);
2220 }
2221
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002222 if (!reg_mask && !stack_mask)
2223 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002224 if (!new_marks)
2225 break;
2226
2227 last_idx = st->last_insn_idx;
2228 first_idx = st->first_insn_idx;
2229 }
2230 return 0;
2231}
2232
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002233static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2234{
2235 return __mark_chain_precision(env, regno, -1);
2236}
2237
2238static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2239{
2240 return __mark_chain_precision(env, -1, spi);
2241}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002242
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002243static bool is_spillable_regtype(enum bpf_reg_type type)
2244{
2245 switch (type) {
2246 case PTR_TO_MAP_VALUE:
2247 case PTR_TO_MAP_VALUE_OR_NULL:
2248 case PTR_TO_STACK:
2249 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002250 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002251 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002252 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002253 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002254 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002255 case PTR_TO_SOCKET:
2256 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002257 case PTR_TO_SOCK_COMMON:
2258 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002259 case PTR_TO_TCP_SOCK:
2260 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002261 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002262 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002263 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002264 case PTR_TO_RDONLY_BUF:
2265 case PTR_TO_RDONLY_BUF_OR_NULL:
2266 case PTR_TO_RDWR_BUF:
2267 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002268 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002269 case PTR_TO_MEM:
2270 case PTR_TO_MEM_OR_NULL:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002271 return true;
2272 default:
2273 return false;
2274 }
2275}
2276
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002277/* Does this register contain a constant zero? */
2278static bool register_is_null(struct bpf_reg_state *reg)
2279{
2280 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2281}
2282
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002283static bool register_is_const(struct bpf_reg_state *reg)
2284{
2285 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2286}
2287
Yonghong Song5689d492020-10-08 18:12:38 -07002288static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2289{
2290 return tnum_is_unknown(reg->var_off) &&
2291 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2292 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2293 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2294 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2295}
2296
2297static bool register_is_bounded(struct bpf_reg_state *reg)
2298{
2299 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2300}
2301
Jann Horn6e7e63c2020-04-17 02:00:06 +02002302static bool __is_pointer_value(bool allow_ptr_leaks,
2303 const struct bpf_reg_state *reg)
2304{
2305 if (allow_ptr_leaks)
2306 return false;
2307
2308 return reg->type != SCALAR_VALUE;
2309}
2310
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002311static void save_register_state(struct bpf_func_state *state,
2312 int spi, struct bpf_reg_state *reg)
2313{
2314 int i;
2315
2316 state->stack[spi].spilled_ptr = *reg;
2317 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2318
2319 for (i = 0; i < BPF_REG_SIZE; i++)
2320 state->stack[spi].slot_type[i] = STACK_SPILL;
2321}
2322
Andrei Matei01f810a2021-02-06 20:10:24 -05002323/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002324 * stack boundary and alignment are checked in check_mem_access()
2325 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002326static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2327 /* stack frame we're writing to */
2328 struct bpf_func_state *state,
2329 int off, int size, int value_regno,
2330 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002331{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002332 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002333 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002334 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002335 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002336
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002337 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE),
Joe Stringerfd978bf72018-10-02 13:35:35 -07002338 state->acquired_refs, true);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002339 if (err)
2340 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002341 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2342 * so it's aligned access and [off, off + size) are within stack limits
2343 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002344 if (!env->allow_ptr_leaks &&
2345 state->stack[spi].slot_type[0] == STACK_SPILL &&
2346 size != BPF_REG_SIZE) {
2347 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2348 return -EACCES;
2349 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002350
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002351 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002352 if (value_regno >= 0)
2353 reg = &cur->regs[value_regno];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002354
Yonghong Song5689d492020-10-08 18:12:38 -07002355 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002356 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002357 if (dst_reg != BPF_REG_FP) {
2358 /* The backtracking logic can only recognize explicit
2359 * stack slot address like [fp - 8]. Other spill of
2360 * scalar via different register has to be conervative.
2361 * Backtrack from here and mark all registers as precise
2362 * that contributed into 'reg' being a constant.
2363 */
2364 err = mark_chain_precision(env, value_regno);
2365 if (err)
2366 return err;
2367 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002368 save_register_state(state, spi, reg);
2369 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002370 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002371 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002372 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002373 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002374 return -EACCES;
2375 }
2376
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002377 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002378 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2379 return -EINVAL;
2380 }
2381
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002382 if (!env->bypass_spec_v4) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002383 bool sanitize = false;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002384
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002385 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
2386 register_is_const(&state->stack[spi].spilled_ptr))
2387 sanitize = true;
2388 for (i = 0; i < BPF_REG_SIZE; i++)
2389 if (state->stack[spi].slot_type[i] == STACK_MISC) {
2390 sanitize = true;
2391 break;
2392 }
2393 if (sanitize) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002394 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off;
2395 int soff = (-spi - 1) * BPF_REG_SIZE;
2396
2397 /* detected reuse of integer stack slot with a pointer
2398 * which means either llvm is reusing stack slot or
2399 * an attacker is trying to exploit CVE-2018-3639
2400 * (speculative store bypass)
2401 * Have to sanitize that slot with preemptive
2402 * store of zero.
2403 */
2404 if (*poff && *poff != soff) {
2405 /* disallow programs where single insn stores
2406 * into two different stack slots, since verifier
2407 * cannot sanitize them
2408 */
2409 verbose(env,
2410 "insn %d cannot access two stack slots fp%d and fp%d",
2411 insn_idx, *poff, soff);
2412 return -EINVAL;
2413 }
2414 *poff = soff;
2415 }
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -07002416 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002417 save_register_state(state, spi, reg);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002418 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002419 u8 type = STACK_MISC;
2420
Edward Cree679c7822018-08-22 20:02:19 +01002421 /* regular write of data into stack destroys any spilled ptr */
2422 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002423 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
2424 if (state->stack[spi].slot_type[0] == STACK_SPILL)
2425 for (i = 0; i < BPF_REG_SIZE; i++)
2426 state->stack[spi].slot_type[i] = STACK_MISC;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002427
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002428 /* only mark the slot as written if all 8 bytes were written
2429 * otherwise read propagation may incorrectly stop too soon
2430 * when stack slots are partially written.
2431 * This heuristic means that read propagation will be
2432 * conservative, since it will add reg_live_read marks
2433 * to stack slots all the way to first state when programs
2434 * writes+reads less than 8 bytes
2435 */
2436 if (size == BPF_REG_SIZE)
2437 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2438
2439 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002440 if (reg && register_is_null(reg)) {
2441 /* backtracking doesn't work for STACK_ZERO yet. */
2442 err = mark_chain_precision(env, value_regno);
2443 if (err)
2444 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002445 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002446 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002447
Jiong Wang0bae2d42018-12-15 03:34:40 -05002448 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002449 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002450 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002451 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002452 }
2453 return 0;
2454}
2455
Andrei Matei01f810a2021-02-06 20:10:24 -05002456/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2457 * known to contain a variable offset.
2458 * This function checks whether the write is permitted and conservatively
2459 * tracks the effects of the write, considering that each stack slot in the
2460 * dynamic range is potentially written to.
2461 *
2462 * 'off' includes 'regno->off'.
2463 * 'value_regno' can be -1, meaning that an unknown value is being written to
2464 * the stack.
2465 *
2466 * Spilled pointers in range are not marked as written because we don't know
2467 * what's going to be actually written. This means that read propagation for
2468 * future reads cannot be terminated by this write.
2469 *
2470 * For privileged programs, uninitialized stack slots are considered
2471 * initialized by this write (even though we don't know exactly what offsets
2472 * are going to be written to). The idea is that we don't want the verifier to
2473 * reject future reads that access slots written to through variable offsets.
2474 */
2475static int check_stack_write_var_off(struct bpf_verifier_env *env,
2476 /* func where register points to */
2477 struct bpf_func_state *state,
2478 int ptr_regno, int off, int size,
2479 int value_regno, int insn_idx)
2480{
2481 struct bpf_func_state *cur; /* state of the current function */
2482 int min_off, max_off;
2483 int i, err;
2484 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
2485 bool writing_zero = false;
2486 /* set if the fact that we're writing a zero is used to let any
2487 * stack slots remain STACK_ZERO
2488 */
2489 bool zero_used = false;
2490
2491 cur = env->cur_state->frame[env->cur_state->curframe];
2492 ptr_reg = &cur->regs[ptr_regno];
2493 min_off = ptr_reg->smin_value + off;
2494 max_off = ptr_reg->smax_value + off + size;
2495 if (value_regno >= 0)
2496 value_reg = &cur->regs[value_regno];
2497 if (value_reg && register_is_null(value_reg))
2498 writing_zero = true;
2499
2500 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE),
2501 state->acquired_refs, true);
2502 if (err)
2503 return err;
2504
2505
2506 /* Variable offset writes destroy any spilled pointers in range. */
2507 for (i = min_off; i < max_off; i++) {
2508 u8 new_type, *stype;
2509 int slot, spi;
2510
2511 slot = -i - 1;
2512 spi = slot / BPF_REG_SIZE;
2513 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
2514
2515 if (!env->allow_ptr_leaks
2516 && *stype != NOT_INIT
2517 && *stype != SCALAR_VALUE) {
2518 /* Reject the write if there's are spilled pointers in
2519 * range. If we didn't reject here, the ptr status
2520 * would be erased below (even though not all slots are
2521 * actually overwritten), possibly opening the door to
2522 * leaks.
2523 */
2524 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
2525 insn_idx, i);
2526 return -EINVAL;
2527 }
2528
2529 /* Erase all spilled pointers. */
2530 state->stack[spi].spilled_ptr.type = NOT_INIT;
2531
2532 /* Update the slot type. */
2533 new_type = STACK_MISC;
2534 if (writing_zero && *stype == STACK_ZERO) {
2535 new_type = STACK_ZERO;
2536 zero_used = true;
2537 }
2538 /* If the slot is STACK_INVALID, we check whether it's OK to
2539 * pretend that it will be initialized by this write. The slot
2540 * might not actually be written to, and so if we mark it as
2541 * initialized future reads might leak uninitialized memory.
2542 * For privileged programs, we will accept such reads to slots
2543 * that may or may not be written because, if we're reject
2544 * them, the error would be too confusing.
2545 */
2546 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
2547 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
2548 insn_idx, i);
2549 return -EINVAL;
2550 }
2551 *stype = new_type;
2552 }
2553 if (zero_used) {
2554 /* backtracking doesn't work for STACK_ZERO yet. */
2555 err = mark_chain_precision(env, value_regno);
2556 if (err)
2557 return err;
2558 }
2559 return 0;
2560}
2561
2562/* When register 'dst_regno' is assigned some values from stack[min_off,
2563 * max_off), we set the register's type according to the types of the
2564 * respective stack slots. If all the stack values are known to be zeros, then
2565 * so is the destination reg. Otherwise, the register is considered to be
2566 * SCALAR. This function does not deal with register filling; the caller must
2567 * ensure that all spilled registers in the stack range have been marked as
2568 * read.
2569 */
2570static void mark_reg_stack_read(struct bpf_verifier_env *env,
2571 /* func where src register points to */
2572 struct bpf_func_state *ptr_state,
2573 int min_off, int max_off, int dst_regno)
2574{
2575 struct bpf_verifier_state *vstate = env->cur_state;
2576 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2577 int i, slot, spi;
2578 u8 *stype;
2579 int zeros = 0;
2580
2581 for (i = min_off; i < max_off; i++) {
2582 slot = -i - 1;
2583 spi = slot / BPF_REG_SIZE;
2584 stype = ptr_state->stack[spi].slot_type;
2585 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
2586 break;
2587 zeros++;
2588 }
2589 if (zeros == max_off - min_off) {
2590 /* any access_size read into register is zero extended,
2591 * so the whole register == const_zero
2592 */
2593 __mark_reg_const_zero(&state->regs[dst_regno]);
2594 /* backtracking doesn't support STACK_ZERO yet,
2595 * so mark it precise here, so that later
2596 * backtracking can stop here.
2597 * Backtracking may not need this if this register
2598 * doesn't participate in pointer adjustment.
2599 * Forward propagation of precise flag is not
2600 * necessary either. This mark is only to stop
2601 * backtracking. Any register that contributed
2602 * to const 0 was marked precise before spill.
2603 */
2604 state->regs[dst_regno].precise = true;
2605 } else {
2606 /* have read misc data from the stack */
2607 mark_reg_unknown(env, state->regs, dst_regno);
2608 }
2609 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
2610}
2611
2612/* Read the stack at 'off' and put the results into the register indicated by
2613 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
2614 * spilled reg.
2615 *
2616 * 'dst_regno' can be -1, meaning that the read value is not going to a
2617 * register.
2618 *
2619 * The access is assumed to be within the current stack bounds.
2620 */
2621static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
2622 /* func where src register points to */
2623 struct bpf_func_state *reg_state,
2624 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002625{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002626 struct bpf_verifier_state *vstate = env->cur_state;
2627 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002628 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002629 struct bpf_reg_state *reg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002630 u8 *stype;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002631
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002632 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002633 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002634
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002635 if (stype[0] == STACK_SPILL) {
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002636 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002637 if (reg->type != SCALAR_VALUE) {
2638 verbose_linfo(env, env->insn_idx, "; ");
2639 verbose(env, "invalid size of register fill\n");
2640 return -EACCES;
2641 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002642 if (dst_regno >= 0) {
2643 mark_reg_unknown(env, state->regs, dst_regno);
2644 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002645 }
2646 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
2647 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002648 }
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002649 for (i = 1; i < BPF_REG_SIZE; i++) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002650 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002651 verbose(env, "corrupted spill memory\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002652 return -EACCES;
2653 }
2654 }
2655
Andrei Matei01f810a2021-02-06 20:10:24 -05002656 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002657 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05002658 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08002659 /* mark reg as written since spilled pointer state likely
2660 * has its liveness marks cleared by is_state_visited()
2661 * which resets stack/reg liveness for state transitions
2662 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002663 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02002664 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002665 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02002666 * it is acceptable to use this value as a SCALAR_VALUE
2667 * (e.g. for XADD).
2668 * We must not allow unprivileged callers to do that
2669 * with spilled pointers.
2670 */
2671 verbose(env, "leaking pointer from stack off %d\n",
2672 off);
2673 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01002674 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002675 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002676 } else {
Andrei Matei01f810a2021-02-06 20:10:24 -05002677 u8 type;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002678
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002679 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05002680 type = stype[(slot - i) % BPF_REG_SIZE];
2681 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002682 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05002683 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002684 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002685 verbose(env, "invalid read from stack off %d+%d size %d\n",
2686 off, i, size);
2687 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002688 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002689 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05002690 if (dst_regno >= 0)
2691 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002692 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002693 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002694}
2695
Andrei Matei01f810a2021-02-06 20:10:24 -05002696enum stack_access_src {
2697 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
2698 ACCESS_HELPER = 2, /* the access is performed by a helper */
2699};
2700
2701static int check_stack_range_initialized(struct bpf_verifier_env *env,
2702 int regno, int off, int access_size,
2703 bool zero_size_allowed,
2704 enum stack_access_src type,
2705 struct bpf_call_arg_meta *meta);
2706
2707static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002708{
Andrei Matei01f810a2021-02-06 20:10:24 -05002709 return cur_regs(env) + regno;
2710}
2711
2712/* Read the stack at 'ptr_regno + off' and put the result into the register
2713 * 'dst_regno'.
2714 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
2715 * but not its variable offset.
2716 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
2717 *
2718 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
2719 * filling registers (i.e. reads of spilled register cannot be detected when
2720 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
2721 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
2722 * offset; for a fixed offset check_stack_read_fixed_off should be used
2723 * instead.
2724 */
2725static int check_stack_read_var_off(struct bpf_verifier_env *env,
2726 int ptr_regno, int off, int size, int dst_regno)
2727{
2728 /* The state of the source register. */
2729 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2730 struct bpf_func_state *ptr_state = func(env, reg);
2731 int err;
2732 int min_off, max_off;
2733
2734 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002735 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002736 err = check_stack_range_initialized(env, ptr_regno, off, size,
2737 false, ACCESS_DIRECT, NULL);
2738 if (err)
2739 return err;
2740
2741 min_off = reg->smin_value + off;
2742 max_off = reg->smax_value + off;
2743 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
2744 return 0;
2745}
2746
2747/* check_stack_read dispatches to check_stack_read_fixed_off or
2748 * check_stack_read_var_off.
2749 *
2750 * The caller must ensure that the offset falls within the allocated stack
2751 * bounds.
2752 *
2753 * 'dst_regno' is a register which will receive the value from the stack. It
2754 * can be -1, meaning that the read value is not going to a register.
2755 */
2756static int check_stack_read(struct bpf_verifier_env *env,
2757 int ptr_regno, int off, int size,
2758 int dst_regno)
2759{
2760 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2761 struct bpf_func_state *state = func(env, reg);
2762 int err;
2763 /* Some accesses are only permitted with a static offset. */
2764 bool var_off = !tnum_is_const(reg->var_off);
2765
2766 /* The offset is required to be static when reads don't go to a
2767 * register, in order to not leak pointers (see
2768 * check_stack_read_fixed_off).
2769 */
2770 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002771 char tn_buf[48];
2772
2773 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05002774 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 +01002775 tn_buf, off, size);
2776 return -EACCES;
2777 }
Andrei Matei01f810a2021-02-06 20:10:24 -05002778 /* Variable offset is prohibited for unprivileged mode for simplicity
2779 * since it requires corresponding support in Spectre masking for stack
2780 * ALU. See also retrieve_ptr_limit().
2781 */
2782 if (!env->bypass_spec_v1 && var_off) {
2783 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002784
Andrei Matei01f810a2021-02-06 20:10:24 -05002785 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
2786 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
2787 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002788 return -EACCES;
2789 }
2790
Andrei Matei01f810a2021-02-06 20:10:24 -05002791 if (!var_off) {
2792 off += reg->var_off.value;
2793 err = check_stack_read_fixed_off(env, state, off, size,
2794 dst_regno);
2795 } else {
2796 /* Variable offset stack reads need more conservative handling
2797 * than fixed offset ones. Note that dst_regno >= 0 on this
2798 * branch.
2799 */
2800 err = check_stack_read_var_off(env, ptr_regno, off, size,
2801 dst_regno);
2802 }
2803 return err;
2804}
2805
2806
2807/* check_stack_write dispatches to check_stack_write_fixed_off or
2808 * check_stack_write_var_off.
2809 *
2810 * 'ptr_regno' is the register used as a pointer into the stack.
2811 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
2812 * 'value_regno' is the register whose value we're writing to the stack. It can
2813 * be -1, meaning that we're not writing from a register.
2814 *
2815 * The caller must ensure that the offset falls within the maximum stack size.
2816 */
2817static int check_stack_write(struct bpf_verifier_env *env,
2818 int ptr_regno, int off, int size,
2819 int value_regno, int insn_idx)
2820{
2821 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
2822 struct bpf_func_state *state = func(env, reg);
2823 int err;
2824
2825 if (tnum_is_const(reg->var_off)) {
2826 off += reg->var_off.value;
2827 err = check_stack_write_fixed_off(env, state, off, size,
2828 value_regno, insn_idx);
2829 } else {
2830 /* Variable offset stack reads need more conservative handling
2831 * than fixed offset ones.
2832 */
2833 err = check_stack_write_var_off(env, state,
2834 ptr_regno, off, size,
2835 value_regno, insn_idx);
2836 }
2837 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01002838}
2839
Daniel Borkmann591fe982019-04-09 23:20:05 +02002840static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
2841 int off, int size, enum bpf_access_type type)
2842{
2843 struct bpf_reg_state *regs = cur_regs(env);
2844 struct bpf_map *map = regs[regno].map_ptr;
2845 u32 cap = bpf_map_flags_to_cap(map);
2846
2847 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
2848 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
2849 map->value_size, off, size);
2850 return -EACCES;
2851 }
2852
2853 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
2854 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
2855 map->value_size, off, size);
2856 return -EACCES;
2857 }
2858
2859 return 0;
2860}
2861
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002862/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
2863static int __check_mem_access(struct bpf_verifier_env *env, int regno,
2864 int off, int size, u32 mem_size,
2865 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002866{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002867 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
2868 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002869
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002870 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
2871 return 0;
2872
2873 reg = &cur_regs(env)[regno];
2874 switch (reg->type) {
2875 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002876 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002877 mem_size, off, size);
2878 break;
2879 case PTR_TO_PACKET:
2880 case PTR_TO_PACKET_META:
2881 case PTR_TO_PACKET_END:
2882 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
2883 off, size, regno, reg->id, off, mem_size);
2884 break;
2885 case PTR_TO_MEM:
2886 default:
2887 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
2888 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002889 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002890
2891 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002892}
2893
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002894/* check read/write into a memory region with possible variable offset */
2895static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
2896 int off, int size, u32 mem_size,
2897 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002898{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002899 struct bpf_verifier_state *vstate = env->cur_state;
2900 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002901 struct bpf_reg_state *reg = &state->regs[regno];
2902 int err;
2903
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002904 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01002905 * need to try adding each of min_value and max_value to off
2906 * to make sure our theoretical access will be safe.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002907 */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002908 if (env->log.level & BPF_LOG_LEVEL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002909 print_verifier_state(env, state);
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002910
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002911 /* The minimum value is only important with signed
2912 * comparisons where we can't assume the floor of a
2913 * value is 0. If we are using signed variables for our
2914 * index'es we need to make sure that whatever we use
2915 * will have a set floor within our range.
2916 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01002917 if (reg->smin_value < 0 &&
2918 (reg->smin_value == S64_MIN ||
2919 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
2920 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002921 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 -08002922 regno);
2923 return -EACCES;
2924 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002925 err = __check_mem_access(env, regno, reg->smin_value + off, size,
2926 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002927 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002928 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002929 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002930 return err;
2931 }
2932
Edward Creeb03c9f92017-08-07 15:26:36 +01002933 /* If we haven't set a max value then we need to bail since we can't be
2934 * sure we won't do bad things.
2935 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002936 */
Edward Creeb03c9f92017-08-07 15:26:36 +01002937 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002938 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002939 regno);
2940 return -EACCES;
2941 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002942 err = __check_mem_access(env, regno, reg->umax_value + off, size,
2943 mem_size, zero_size_allowed);
2944 if (err) {
2945 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002946 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002947 return err;
2948 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002949
Andrii Nakryiko457f4432020-05-29 00:54:20 -07002950 return 0;
2951}
2952
2953/* check read/write into a map element with possible variable offset */
2954static int check_map_access(struct bpf_verifier_env *env, u32 regno,
2955 int off, int size, bool zero_size_allowed)
2956{
2957 struct bpf_verifier_state *vstate = env->cur_state;
2958 struct bpf_func_state *state = vstate->frame[vstate->curframe];
2959 struct bpf_reg_state *reg = &state->regs[regno];
2960 struct bpf_map *map = reg->map_ptr;
2961 int err;
2962
2963 err = check_mem_region_access(env, regno, off, size, map->value_size,
2964 zero_size_allowed);
2965 if (err)
2966 return err;
2967
2968 if (map_value_has_spin_lock(map)) {
2969 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08002970
2971 /* if any part of struct bpf_spin_lock can be touched by
2972 * load/store reject this program.
2973 * To check that [x1, x2) overlaps with [y1, y2)
2974 * it is sufficient to check x1 < y2 && y1 < x2.
2975 */
2976 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
2977 lock < reg->umax_value + off + size) {
2978 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
2979 return -EACCES;
2980 }
2981 }
Edward Creef1174f72017-08-07 15:26:19 +01002982 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08002983}
2984
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002985#define MAX_PACKET_OFF 0xffff
2986
Udip Pant7e407812020-08-25 16:20:00 -07002987static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
2988{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02002989 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07002990}
2991
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01002992static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01002993 const struct bpf_call_arg_meta *meta,
2994 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07002995{
Udip Pant7e407812020-08-25 16:20:00 -07002996 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
2997
2998 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02002999 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003000 case BPF_PROG_TYPE_LWT_IN:
3001 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003002 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003003 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003004 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003005 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003006 if (t == BPF_WRITE)
3007 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003008 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003009
3010 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003011 case BPF_PROG_TYPE_SCHED_CLS:
3012 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003013 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003014 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003015 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003016 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003017 if (meta)
3018 return meta->pkt_access;
3019
3020 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003021 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003022
3023 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3024 if (t == BPF_WRITE)
3025 env->seen_direct_write = true;
3026
3027 return true;
3028
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003029 default:
3030 return false;
3031 }
3032}
3033
Edward Creef1174f72017-08-07 15:26:19 +01003034static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003035 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003036{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003037 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003038 struct bpf_reg_state *reg = &regs[regno];
3039 int err;
3040
3041 /* We may have added a variable offset to the packet pointer; but any
3042 * reg->range we have comes after that. We are only checking the fixed
3043 * offset.
3044 */
3045
3046 /* We don't allow negative numbers, because we aren't tracking enough
3047 * detail to prove they're safe.
3048 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003049 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003050 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 +01003051 regno);
3052 return -EACCES;
3053 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003054
3055 err = reg->range < 0 ? -EINVAL :
3056 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003057 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003058 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003059 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003060 return err;
3061 }
Jiong Wange6478152018-11-08 04:08:42 -05003062
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003063 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003064 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3065 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003066 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003067 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3068 */
3069 env->prog->aux->max_pkt_offset =
3070 max_t(u32, env->prog->aux->max_pkt_offset,
3071 off + reg->umax_value + size - 1);
3072
Edward Creef1174f72017-08-07 15:26:19 +01003073 return err;
3074}
3075
3076/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003077static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003078 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003079 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003080{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003081 struct bpf_insn_access_aux info = {
3082 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003083 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003084 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003085
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003086 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003087 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003088 /* A non zero info.ctx_field_size indicates that this field is a
3089 * candidate for later verifier transformation to load the whole
3090 * field and then apply a mask when accessed with a narrower
3091 * access than actual ctx access size. A zero info.ctx_field_size
3092 * will only allow for whole field access and rejects any other
3093 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003094 */
Yonghong Song23994632017-06-22 15:07:39 -07003095 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003096
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003097 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3098 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003099 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003100 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003101 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003102 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003103 /* remember the offset of last byte accessed in ctx */
3104 if (env->prog->aux->max_ctx_offset < off + size)
3105 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003106 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003107 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003108
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003109 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003110 return -EACCES;
3111}
3112
Petar Penkovd58e4682018-09-14 07:46:18 -07003113static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3114 int size)
3115{
3116 if (size < 0 || off < 0 ||
3117 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3118 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3119 off, size);
3120 return -EACCES;
3121 }
3122 return 0;
3123}
3124
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003125static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3126 u32 regno, int off, int size,
3127 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003128{
3129 struct bpf_reg_state *regs = cur_regs(env);
3130 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003131 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003132 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003133
3134 if (reg->smin_value < 0) {
3135 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3136 regno);
3137 return -EACCES;
3138 }
3139
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003140 switch (reg->type) {
3141 case PTR_TO_SOCK_COMMON:
3142 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3143 break;
3144 case PTR_TO_SOCKET:
3145 valid = bpf_sock_is_valid_access(off, size, t, &info);
3146 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003147 case PTR_TO_TCP_SOCK:
3148 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3149 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003150 case PTR_TO_XDP_SOCK:
3151 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3152 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003153 default:
3154 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003155 }
3156
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003157
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003158 if (valid) {
3159 env->insn_aux_data[insn_idx].ctx_field_size =
3160 info.ctx_field_size;
3161 return 0;
3162 }
3163
3164 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3165 regno, reg_type_str[reg->type], off, size);
3166
3167 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003168}
3169
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003170static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3171{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003172 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003173}
3174
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003175static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3176{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003177 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003178
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003179 return reg->type == PTR_TO_CTX;
3180}
3181
3182static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3183{
3184 const struct bpf_reg_state *reg = reg_state(env, regno);
3185
3186 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003187}
3188
Daniel Borkmannca369602018-02-23 22:29:05 +01003189static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3190{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003191 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003192
3193 return type_is_pkt_pointer(reg->type);
3194}
3195
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003196static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3197{
3198 const struct bpf_reg_state *reg = reg_state(env, regno);
3199
3200 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3201 return reg->type == PTR_TO_FLOW_KEYS;
3202}
3203
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003204static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3205 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003206 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003207{
Edward Creef1174f72017-08-07 15:26:19 +01003208 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003209 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003210
3211 /* Byte size accesses are always allowed. */
3212 if (!strict || size == 1)
3213 return 0;
3214
David S. Millere4eda882017-05-22 12:27:07 -04003215 /* For platforms that do not have a Kconfig enabling
3216 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3217 * NET_IP_ALIGN is universally set to '2'. And on platforms
3218 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3219 * to this code only in strict mode where we want to emulate
3220 * the NET_IP_ALIGN==2 checking. Therefore use an
3221 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003222 */
David S. Millere4eda882017-05-22 12:27:07 -04003223 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003224
3225 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3226 if (!tnum_is_aligned(reg_off, size)) {
3227 char tn_buf[48];
3228
3229 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003230 verbose(env,
3231 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003232 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003233 return -EACCES;
3234 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003235
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003236 return 0;
3237}
3238
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003239static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3240 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003241 const char *pointer_desc,
3242 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003243{
Edward Creef1174f72017-08-07 15:26:19 +01003244 struct tnum reg_off;
3245
3246 /* Byte size accesses are always allowed. */
3247 if (!strict || size == 1)
3248 return 0;
3249
3250 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3251 if (!tnum_is_aligned(reg_off, size)) {
3252 char tn_buf[48];
3253
3254 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003255 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003256 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003257 return -EACCES;
3258 }
3259
3260 return 0;
3261}
3262
David S. Millere07b98d2017-05-10 11:38:07 -07003263static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003264 const struct bpf_reg_state *reg, int off,
3265 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003266{
Daniel Borkmannca369602018-02-23 22:29:05 +01003267 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003268 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003269
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003270 switch (reg->type) {
3271 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003272 case PTR_TO_PACKET_META:
3273 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3274 * right in front, treat it the very same way.
3275 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003276 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003277 case PTR_TO_FLOW_KEYS:
3278 pointer_desc = "flow keys ";
3279 break;
Edward Creef1174f72017-08-07 15:26:19 +01003280 case PTR_TO_MAP_VALUE:
3281 pointer_desc = "value ";
3282 break;
3283 case PTR_TO_CTX:
3284 pointer_desc = "context ";
3285 break;
3286 case PTR_TO_STACK:
3287 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003288 /* The stack spill tracking logic in check_stack_write_fixed_off()
3289 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003290 * aligned.
3291 */
3292 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003293 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003294 case PTR_TO_SOCKET:
3295 pointer_desc = "sock ";
3296 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003297 case PTR_TO_SOCK_COMMON:
3298 pointer_desc = "sock_common ";
3299 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003300 case PTR_TO_TCP_SOCK:
3301 pointer_desc = "tcp_sock ";
3302 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003303 case PTR_TO_XDP_SOCK:
3304 pointer_desc = "xdp_sock ";
3305 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003306 default:
Edward Creef1174f72017-08-07 15:26:19 +01003307 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003308 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003309 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3310 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003311}
3312
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003313static int update_stack_depth(struct bpf_verifier_env *env,
3314 const struct bpf_func_state *func,
3315 int off)
3316{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003317 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003318
3319 if (stack >= -off)
3320 return 0;
3321
3322 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003323 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003324 return 0;
3325}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003326
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003327/* starting from main bpf function walk all instructions of the function
3328 * and recursively walk all callees that given function can call.
3329 * Ignore jump and exit insns.
3330 * Since recursion is prevented by check_cfg() this algorithm
3331 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3332 */
3333static int check_max_stack_depth(struct bpf_verifier_env *env)
3334{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003335 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3336 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003337 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003338 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003339 int ret_insn[MAX_CALL_FRAMES];
3340 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003341 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003342
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003343process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003344 /* protect against potential stack overflow that might happen when
3345 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3346 * depth for such case down to 256 so that the worst case scenario
3347 * would result in 8k stack size (32 which is tailcall limit * 256 =
3348 * 8k).
3349 *
3350 * To get the idea what might happen, see an example:
3351 * func1 -> sub rsp, 128
3352 * subfunc1 -> sub rsp, 256
3353 * tailcall1 -> add rsp, 256
3354 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3355 * subfunc2 -> sub rsp, 64
3356 * subfunc22 -> sub rsp, 128
3357 * tailcall2 -> add rsp, 128
3358 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3359 *
3360 * tailcall will unwind the current stack frame but it will not get rid
3361 * of caller's stack as shown on the example above.
3362 */
3363 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3364 verbose(env,
3365 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3366 depth);
3367 return -EACCES;
3368 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003369 /* round up to 32-bytes, since this is granularity
3370 * of interpreter stack size
3371 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003372 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003373 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003374 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003375 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003376 return -EACCES;
3377 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003378continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003379 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003380 for (; i < subprog_end; i++) {
Yonghong Song23a2d702021-02-04 15:48:27 -08003381 if (!bpf_pseudo_call(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003382 continue;
3383 /* remember insn and function to return to */
3384 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003385 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003386
3387 /* find the callee */
3388 i = i + insn[i].imm + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003389 idx = find_subprog(env, i);
3390 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003391 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3392 i);
3393 return -EFAULT;
3394 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003395
3396 if (subprog[idx].has_tail_call)
3397 tail_call_reachable = true;
3398
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003399 frame++;
3400 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003401 verbose(env, "the call stack of %d frames is too deep !\n",
3402 frame);
3403 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003404 }
3405 goto process_func;
3406 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003407 /* if tail call got detected across bpf2bpf calls then mark each of the
3408 * currently present subprog frames as tail call reachable subprogs;
3409 * this info will be utilized by JIT so that we will be preserving the
3410 * tail call counter throughout bpf2bpf calls combined with tailcalls
3411 */
3412 if (tail_call_reachable)
3413 for (j = 0; j < frame; j++)
3414 subprog[ret_prog[j]].tail_call_reachable = true;
3415
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003416 /* end of for() loop means the last insn of the 'subprog'
3417 * was reached. Doesn't matter whether it was JA or EXIT
3418 */
3419 if (frame == 0)
3420 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003421 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003422 frame--;
3423 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003424 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003425 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003426}
3427
David S. Miller19d28fb2018-01-11 21:27:54 -05003428#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003429static int get_callee_stack_depth(struct bpf_verifier_env *env,
3430 const struct bpf_insn *insn, int idx)
3431{
3432 int start = idx + insn->imm + 1, subprog;
3433
3434 subprog = find_subprog(env, start);
3435 if (subprog < 0) {
3436 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3437 start);
3438 return -EFAULT;
3439 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04003440 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003441}
David S. Miller19d28fb2018-01-11 21:27:54 -05003442#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003443
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08003444int check_ctx_reg(struct bpf_verifier_env *env,
3445 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02003446{
3447 /* Access to ctx or passing it to a helper is only allowed in
3448 * its original, unmodified form.
3449 */
3450
3451 if (reg->off) {
3452 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
3453 regno, reg->off);
3454 return -EACCES;
3455 }
3456
3457 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3458 char tn_buf[48];
3459
3460 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3461 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
3462 return -EACCES;
3463 }
3464
3465 return 0;
3466}
3467
Yonghong Songafbf21d2020-07-23 11:41:11 -07003468static int __check_buffer_access(struct bpf_verifier_env *env,
3469 const char *buf_info,
3470 const struct bpf_reg_state *reg,
3471 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07003472{
3473 if (off < 0) {
3474 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003475 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003476 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07003477 return -EACCES;
3478 }
3479 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3480 char tn_buf[48];
3481
3482 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3483 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07003484 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07003485 regno, off, tn_buf);
3486 return -EACCES;
3487 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07003488
3489 return 0;
3490}
3491
3492static int check_tp_buffer_access(struct bpf_verifier_env *env,
3493 const struct bpf_reg_state *reg,
3494 int regno, int off, int size)
3495{
3496 int err;
3497
3498 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
3499 if (err)
3500 return err;
3501
Matt Mullins9df1c282019-04-26 11:49:47 -07003502 if (off + size > env->prog->aux->max_tp_access)
3503 env->prog->aux->max_tp_access = off + size;
3504
3505 return 0;
3506}
3507
Yonghong Songafbf21d2020-07-23 11:41:11 -07003508static int check_buffer_access(struct bpf_verifier_env *env,
3509 const struct bpf_reg_state *reg,
3510 int regno, int off, int size,
3511 bool zero_size_allowed,
3512 const char *buf_info,
3513 u32 *max_access)
3514{
3515 int err;
3516
3517 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
3518 if (err)
3519 return err;
3520
3521 if (off + size > *max_access)
3522 *max_access = off + size;
3523
3524 return 0;
3525}
3526
John Fastabend3f50f132020-03-30 14:36:39 -07003527/* BPF architecture zero extends alu32 ops into 64-bit registesr */
3528static void zext_32_to_64(struct bpf_reg_state *reg)
3529{
3530 reg->var_off = tnum_subreg(reg->var_off);
3531 __reg_assign_32_into_64(reg);
3532}
Matt Mullins9df1c282019-04-26 11:49:47 -07003533
Jann Horn0c17d1d2017-12-18 20:11:55 -08003534/* truncate register to smaller size (in bytes)
3535 * must be called with size < BPF_REG_SIZE
3536 */
3537static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
3538{
3539 u64 mask;
3540
3541 /* clear high bits in bit representation */
3542 reg->var_off = tnum_cast(reg->var_off, size);
3543
3544 /* fix arithmetic bounds */
3545 mask = ((u64)1 << (size * 8)) - 1;
3546 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
3547 reg->umin_value &= mask;
3548 reg->umax_value &= mask;
3549 } else {
3550 reg->umin_value = 0;
3551 reg->umax_value = mask;
3552 }
3553 reg->smin_value = reg->umin_value;
3554 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07003555
3556 /* If size is smaller than 32bit register the 32bit register
3557 * values are also truncated so we push 64-bit bounds into
3558 * 32-bit bounds. Above were truncated < 32-bits already.
3559 */
3560 if (size >= 4)
3561 return;
3562 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08003563}
3564
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003565static bool bpf_map_is_rdonly(const struct bpf_map *map)
3566{
3567 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen;
3568}
3569
3570static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
3571{
3572 void *ptr;
3573 u64 addr;
3574 int err;
3575
3576 err = map->ops->map_direct_value_addr(map, &addr, off);
3577 if (err)
3578 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07003579 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003580
3581 switch (size) {
3582 case sizeof(u8):
3583 *val = (u64)*(u8 *)ptr;
3584 break;
3585 case sizeof(u16):
3586 *val = (u64)*(u16 *)ptr;
3587 break;
3588 case sizeof(u32):
3589 *val = (u64)*(u32 *)ptr;
3590 break;
3591 case sizeof(u64):
3592 *val = *(u64 *)ptr;
3593 break;
3594 default:
3595 return -EINVAL;
3596 }
3597 return 0;
3598}
3599
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003600static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
3601 struct bpf_reg_state *regs,
3602 int regno, int off, int size,
3603 enum bpf_access_type atype,
3604 int value_regno)
3605{
3606 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003607 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
3608 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003609 u32 btf_id;
3610 int ret;
3611
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003612 if (off < 0) {
3613 verbose(env,
3614 "R%d is ptr_%s invalid negative access: off=%d\n",
3615 regno, tname, off);
3616 return -EACCES;
3617 }
3618 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
3619 char tn_buf[48];
3620
3621 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3622 verbose(env,
3623 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
3624 regno, tname, off, tn_buf);
3625 return -EACCES;
3626 }
3627
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003628 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003629 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
3630 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003631 } else {
3632 if (atype != BPF_READ) {
3633 verbose(env, "only read is supported\n");
3634 return -EACCES;
3635 }
3636
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003637 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
3638 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003639 }
3640
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003641 if (ret < 0)
3642 return ret;
3643
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003644 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003645 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08003646
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003647 return 0;
3648}
3649
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003650static int check_ptr_to_map_access(struct bpf_verifier_env *env,
3651 struct bpf_reg_state *regs,
3652 int regno, int off, int size,
3653 enum bpf_access_type atype,
3654 int value_regno)
3655{
3656 struct bpf_reg_state *reg = regs + regno;
3657 struct bpf_map *map = reg->map_ptr;
3658 const struct btf_type *t;
3659 const char *tname;
3660 u32 btf_id;
3661 int ret;
3662
3663 if (!btf_vmlinux) {
3664 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
3665 return -ENOTSUPP;
3666 }
3667
3668 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
3669 verbose(env, "map_ptr access not supported for map type %d\n",
3670 map->map_type);
3671 return -ENOTSUPP;
3672 }
3673
3674 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
3675 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
3676
3677 if (!env->allow_ptr_to_map_access) {
3678 verbose(env,
3679 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
3680 tname);
3681 return -EPERM;
3682 }
3683
3684 if (off < 0) {
3685 verbose(env, "R%d is %s invalid negative access: off=%d\n",
3686 regno, tname, off);
3687 return -EACCES;
3688 }
3689
3690 if (atype != BPF_READ) {
3691 verbose(env, "only read from %s is supported\n", tname);
3692 return -EACCES;
3693 }
3694
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003695 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003696 if (ret < 0)
3697 return ret;
3698
3699 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003700 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003701
3702 return 0;
3703}
3704
Andrei Matei01f810a2021-02-06 20:10:24 -05003705/* Check that the stack access at the given offset is within bounds. The
3706 * maximum valid offset is -1.
3707 *
3708 * The minimum valid offset is -MAX_BPF_STACK for writes, and
3709 * -state->allocated_stack for reads.
3710 */
3711static int check_stack_slot_within_bounds(int off,
3712 struct bpf_func_state *state,
3713 enum bpf_access_type t)
3714{
3715 int min_valid_off;
3716
3717 if (t == BPF_WRITE)
3718 min_valid_off = -MAX_BPF_STACK;
3719 else
3720 min_valid_off = -state->allocated_stack;
3721
3722 if (off < min_valid_off || off > -1)
3723 return -EACCES;
3724 return 0;
3725}
3726
3727/* Check that the stack access at 'regno + off' falls within the maximum stack
3728 * bounds.
3729 *
3730 * 'off' includes `regno->offset`, but not its dynamic part (if any).
3731 */
3732static int check_stack_access_within_bounds(
3733 struct bpf_verifier_env *env,
3734 int regno, int off, int access_size,
3735 enum stack_access_src src, enum bpf_access_type type)
3736{
3737 struct bpf_reg_state *regs = cur_regs(env);
3738 struct bpf_reg_state *reg = regs + regno;
3739 struct bpf_func_state *state = func(env, reg);
3740 int min_off, max_off;
3741 int err;
3742 char *err_extra;
3743
3744 if (src == ACCESS_HELPER)
3745 /* We don't know if helpers are reading or writing (or both). */
3746 err_extra = " indirect access to";
3747 else if (type == BPF_READ)
3748 err_extra = " read from";
3749 else
3750 err_extra = " write to";
3751
3752 if (tnum_is_const(reg->var_off)) {
3753 min_off = reg->var_off.value + off;
3754 if (access_size > 0)
3755 max_off = min_off + access_size - 1;
3756 else
3757 max_off = min_off;
3758 } else {
3759 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
3760 reg->smin_value <= -BPF_MAX_VAR_OFF) {
3761 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
3762 err_extra, regno);
3763 return -EACCES;
3764 }
3765 min_off = reg->smin_value + off;
3766 if (access_size > 0)
3767 max_off = reg->smax_value + off + access_size - 1;
3768 else
3769 max_off = min_off;
3770 }
3771
3772 err = check_stack_slot_within_bounds(min_off, state, type);
3773 if (!err)
3774 err = check_stack_slot_within_bounds(max_off, state, type);
3775
3776 if (err) {
3777 if (tnum_is_const(reg->var_off)) {
3778 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
3779 err_extra, regno, off, access_size);
3780 } else {
3781 char tn_buf[48];
3782
3783 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3784 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
3785 err_extra, regno, tn_buf, access_size);
3786 }
3787 }
3788 return err;
3789}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003790
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003791/* check whether memory at (regno + off) is accessible for t = (read | write)
3792 * if t==write, value_regno is a register which value is stored into memory
3793 * if t==read, value_regno is a register which will receive the value from memory
3794 * if t==write && value_regno==-1, some unknown value is stored into memory
3795 * if t==read && value_regno==-1, don't care what we read from memory
3796 */
Daniel Borkmannca369602018-02-23 22:29:05 +01003797static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
3798 int off, int bpf_size, enum bpf_access_type t,
3799 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003800{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003801 struct bpf_reg_state *regs = cur_regs(env);
3802 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003803 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003804 int size, err = 0;
3805
3806 size = bpf_size_to_bytes(bpf_size);
3807 if (size < 0)
3808 return size;
3809
Edward Creef1174f72017-08-07 15:26:19 +01003810 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01003811 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003812 if (err)
3813 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003814
Edward Creef1174f72017-08-07 15:26:19 +01003815 /* for access checks, reg->off is just part of off */
3816 off += reg->off;
3817
3818 if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003819 if (t == BPF_WRITE && value_regno >= 0 &&
3820 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003821 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003822 return -EACCES;
3823 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02003824 err = check_map_access_type(env, regno, off, size, t);
3825 if (err)
3826 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08003827 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003828 if (!err && t == BPF_READ && value_regno >= 0) {
3829 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003830
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07003831 /* if map is read-only, track its contents as scalars */
3832 if (tnum_is_const(reg->var_off) &&
3833 bpf_map_is_rdonly(map) &&
3834 map->ops->map_direct_value_addr) {
3835 int map_off = off + reg->var_off.value;
3836 u64 val = 0;
3837
3838 err = bpf_map_direct_read(map, map_off, size,
3839 &val);
3840 if (err)
3841 return err;
3842
3843 regs[value_regno].type = SCALAR_VALUE;
3844 __mark_reg_known(&regs[value_regno], val);
3845 } else {
3846 mark_reg_unknown(env, regs, value_regno);
3847 }
3848 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003849 } else if (reg->type == PTR_TO_MEM) {
3850 if (t == BPF_WRITE && value_regno >= 0 &&
3851 is_pointer_value(env, value_regno)) {
3852 verbose(env, "R%d leaks addr into mem\n", value_regno);
3853 return -EACCES;
3854 }
3855 err = check_mem_region_access(env, regno, off, size,
3856 reg->mem_size, false);
3857 if (!err && t == BPF_READ && value_regno >= 0)
3858 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07003859 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01003860 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003861 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003862 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07003863
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003864 if (t == BPF_WRITE && value_regno >= 0 &&
3865 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003866 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07003867 return -EACCES;
3868 }
Edward Creef1174f72017-08-07 15:26:19 +01003869
Daniel Borkmann58990d12018-06-07 17:40:03 +02003870 err = check_ctx_reg(env, reg, regno);
3871 if (err < 0)
3872 return err;
3873
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003874 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003875 if (err)
3876 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003877 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01003878 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003879 * PTR_TO_PACKET[_META,_END]. In the latter
3880 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01003881 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003882 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003883 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003884 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003885 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003886 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003887 if (reg_type_may_be_null(reg_type))
3888 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01003889 /* A load of ctx field could have different
3890 * actual load size with the one encoded in the
3891 * insn. When the dst is PTR, it is for sure not
3892 * a sub-register.
3893 */
3894 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07003895 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003896 reg_type == PTR_TO_BTF_ID_OR_NULL) {
3897 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003898 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003899 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003900 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003901 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003902 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003903
Edward Creef1174f72017-08-07 15:26:19 +01003904 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05003905 /* Basic bounds checks. */
3906 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003907 if (err)
3908 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003909
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003910 state = func(env, reg);
3911 err = update_stack_depth(env, state, off);
3912 if (err)
3913 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07003914
Andrei Matei01f810a2021-02-06 20:10:24 -05003915 if (t == BPF_READ)
3916 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003917 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05003918 else
3919 err = check_stack_write(env, regno, off, size,
3920 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003921 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003922 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003923 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003924 return -EACCES;
3925 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003926 if (t == BPF_WRITE && value_regno >= 0 &&
3927 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003928 verbose(env, "R%d leaks addr into packet\n",
3929 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003930 return -EACCES;
3931 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08003932 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003933 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003934 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07003935 } else if (reg->type == PTR_TO_FLOW_KEYS) {
3936 if (t == BPF_WRITE && value_regno >= 0 &&
3937 is_pointer_value(env, value_regno)) {
3938 verbose(env, "R%d leaks addr into flow keys\n",
3939 value_regno);
3940 return -EACCES;
3941 }
3942
3943 err = check_flow_keys_access(env, off, size);
3944 if (!err && t == BPF_READ && value_regno >= 0)
3945 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003946 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07003947 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003948 verbose(env, "R%d cannot write into %s\n",
3949 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07003950 return -EACCES;
3951 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003952 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07003953 if (!err && value_regno >= 0)
3954 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07003955 } else if (reg->type == PTR_TO_TP_BUFFER) {
3956 err = check_tp_buffer_access(env, reg, regno, off, size);
3957 if (!err && t == BPF_READ && value_regno >= 0)
3958 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003959 } else if (reg->type == PTR_TO_BTF_ID) {
3960 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
3961 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07003962 } else if (reg->type == CONST_PTR_TO_MAP) {
3963 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
3964 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07003965 } else if (reg->type == PTR_TO_RDONLY_BUF) {
3966 if (t == BPF_WRITE) {
3967 verbose(env, "R%d cannot write into %s\n",
3968 regno, reg_type_str[reg->type]);
3969 return -EACCES;
3970 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003971 err = check_buffer_access(env, reg, regno, off, size, false,
3972 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003973 &env->prog->aux->max_rdonly_access);
3974 if (!err && value_regno >= 0)
3975 mark_reg_unknown(env, regs, value_regno);
3976 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01003977 err = check_buffer_access(env, reg, regno, off, size, false,
3978 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07003979 &env->prog->aux->max_rdwr_access);
3980 if (!err && t == BPF_READ && value_regno >= 0)
3981 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003982 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003983 verbose(env, "R%d invalid mem access '%s'\n", regno,
3984 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003985 return -EACCES;
3986 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003987
Edward Creef1174f72017-08-07 15:26:19 +01003988 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003989 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01003990 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08003991 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003992 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003993 return err;
3994}
3995
Brendan Jackman91c960b2021-01-14 18:17:44 +00003996static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003997{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00003998 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003999 int err;
4000
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004001 switch (insn->imm) {
4002 case BPF_ADD:
4003 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004004 case BPF_AND:
4005 case BPF_AND | BPF_FETCH:
4006 case BPF_OR:
4007 case BPF_OR | BPF_FETCH:
4008 case BPF_XOR:
4009 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004010 case BPF_XCHG:
4011 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004012 break;
4013 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004014 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4015 return -EINVAL;
4016 }
4017
4018 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4019 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004020 return -EINVAL;
4021 }
4022
4023 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004024 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004025 if (err)
4026 return err;
4027
4028 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004029 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004030 if (err)
4031 return err;
4032
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004033 if (insn->imm == BPF_CMPXCHG) {
4034 /* Check comparison of R0 with memory location */
4035 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4036 if (err)
4037 return err;
4038 }
4039
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004040 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004041 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004042 return -EACCES;
4043 }
4044
Daniel Borkmannca369602018-02-23 22:29:05 +01004045 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004046 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004047 is_flow_key_reg(env, insn->dst_reg) ||
4048 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004049 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004050 insn->dst_reg,
4051 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004052 return -EACCES;
4053 }
4054
Brendan Jackman37086bf2021-02-02 13:50:02 +00004055 if (insn->imm & BPF_FETCH) {
4056 if (insn->imm == BPF_CMPXCHG)
4057 load_reg = BPF_REG_0;
4058 else
4059 load_reg = insn->src_reg;
4060
4061 /* check and record load of old value */
4062 err = check_reg_arg(env, load_reg, DST_OP);
4063 if (err)
4064 return err;
4065 } else {
4066 /* This instruction accesses a memory location but doesn't
4067 * actually load it into a register.
4068 */
4069 load_reg = -1;
4070 }
4071
Brendan Jackman91c960b2021-01-14 18:17:44 +00004072 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004073 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004074 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004075 if (err)
4076 return err;
4077
Brendan Jackman91c960b2021-01-14 18:17:44 +00004078 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004079 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4080 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4081 if (err)
4082 return err;
4083
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004084 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004085}
4086
Andrei Matei01f810a2021-02-06 20:10:24 -05004087/* When register 'regno' is used to read the stack (either directly or through
4088 * a helper function) make sure that it's within stack boundary and, depending
4089 * on the access type, that all elements of the stack are initialized.
4090 *
4091 * 'off' includes 'regno->off', but not its dynamic part (if any).
4092 *
4093 * All registers that have been spilled on the stack in the slots within the
4094 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004095 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004096static int check_stack_range_initialized(
4097 struct bpf_verifier_env *env, int regno, int off,
4098 int access_size, bool zero_size_allowed,
4099 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004100{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004101 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004102 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004103 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004104 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4105 enum bpf_access_type bounds_check_type;
4106 /* Some accesses can write anything into the stack, others are
4107 * read-only.
4108 */
4109 bool clobber = false;
4110
4111 if (access_size == 0 && !zero_size_allowed) {
4112 verbose(env, "invalid zero-sized read\n");
4113 return -EACCES;
4114 }
4115
4116 if (type == ACCESS_HELPER) {
4117 /* The bounds checks for writes are more permissive than for
4118 * reads. However, if raw_mode is not set, we'll do extra
4119 * checks below.
4120 */
4121 bounds_check_type = BPF_WRITE;
4122 clobber = true;
4123 } else {
4124 bounds_check_type = BPF_READ;
4125 }
4126 err = check_stack_access_within_bounds(env, regno, off, access_size,
4127 type, bounds_check_type);
4128 if (err)
4129 return err;
4130
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004131
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004132 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004133 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004134 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004135 /* Variable offset is prohibited for unprivileged mode for
4136 * simplicity since it requires corresponding support in
4137 * Spectre masking for stack ALU.
4138 * See also retrieve_ptr_limit().
4139 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004140 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004141 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004142
Andrey Ignatov088ec262019-04-03 23:22:39 -07004143 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004144 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4145 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004146 return -EACCES;
4147 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004148 /* Only initialized buffer on stack is allowed to be accessed
4149 * with variable offset. With uninitialized buffer it's hard to
4150 * guarantee that whole memory is marked as initialized on
4151 * helper return since specific bounds are unknown what may
4152 * cause uninitialized stack leaking.
4153 */
4154 if (meta && meta->raw_mode)
4155 meta = NULL;
4156
Andrei Matei01f810a2021-02-06 20:10:24 -05004157 min_off = reg->smin_value + off;
4158 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004159 }
4160
Daniel Borkmann435faee12016-04-13 00:10:51 +02004161 if (meta && meta->raw_mode) {
4162 meta->access_size = access_size;
4163 meta->regno = regno;
4164 return 0;
4165 }
4166
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004167 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004168 u8 *stype;
4169
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004170 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004171 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004172 if (state->allocated_stack <= slot)
4173 goto err;
4174 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4175 if (*stype == STACK_MISC)
4176 goto mark;
4177 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004178 if (clobber) {
4179 /* helper can write anything into the stack */
4180 *stype = STACK_MISC;
4181 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004182 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004183 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004184
4185 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
4186 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4187 goto mark;
4188
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004189 if (state->stack[spi].slot_type[0] == STACK_SPILL &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004190 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4191 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004192 if (clobber) {
4193 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4194 for (j = 0; j < BPF_REG_SIZE; j++)
4195 state->stack[spi].slot_type[j] = STACK_MISC;
4196 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004197 goto mark;
4198 }
4199
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004200err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004201 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004202 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4203 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004204 } else {
4205 char tn_buf[48];
4206
4207 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004208 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4209 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004210 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004211 return -EACCES;
4212mark:
4213 /* reading any byte out of 8-byte 'spill_slot' will cause
4214 * the whole slot to be marked as 'read'
4215 */
Edward Cree679c7822018-08-22 20:02:19 +01004216 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004217 state->stack[spi].spilled_ptr.parent,
4218 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004219 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004220 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004221}
4222
Gianluca Borello06c1c042017-01-09 10:19:49 -08004223static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4224 int access_size, bool zero_size_allowed,
4225 struct bpf_call_arg_meta *meta)
4226{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004227 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004228
Edward Creef1174f72017-08-07 15:26:19 +01004229 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004230 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004231 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004232 return check_packet_access(env, regno, reg->off, access_size,
4233 zero_size_allowed);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004234 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004235 if (check_map_access_type(env, regno, reg->off, access_size,
4236 meta && meta->raw_mode ? BPF_WRITE :
4237 BPF_READ))
4238 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004239 return check_map_access(env, regno, reg->off, access_size,
4240 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004241 case PTR_TO_MEM:
4242 return check_mem_region_access(env, regno, reg->off,
4243 access_size, reg->mem_size,
4244 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004245 case PTR_TO_RDONLY_BUF:
4246 if (meta && meta->raw_mode)
4247 return -EACCES;
4248 return check_buffer_access(env, reg, regno, reg->off,
4249 access_size, zero_size_allowed,
4250 "rdonly",
4251 &env->prog->aux->max_rdonly_access);
4252 case PTR_TO_RDWR_BUF:
4253 return check_buffer_access(env, reg, regno, reg->off,
4254 access_size, zero_size_allowed,
4255 "rdwr",
4256 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004257 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004258 return check_stack_range_initialized(
4259 env,
4260 regno, reg->off, access_size,
4261 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004262 default: /* scalar_value or invalid ptr */
4263 /* Allow zero-byte read from NULL, regardless of pointer type */
4264 if (zero_size_allowed && access_size == 0 &&
4265 register_is_null(reg))
4266 return 0;
4267
4268 verbose(env, "R%d type=%s expected=%s\n", regno,
4269 reg_type_str[reg->type],
4270 reg_type_str[PTR_TO_STACK]);
4271 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004272 }
4273}
4274
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004275int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4276 u32 regno, u32 mem_size)
4277{
4278 if (register_is_null(reg))
4279 return 0;
4280
4281 if (reg_type_may_be_null(reg->type)) {
4282 /* Assuming that the register contains a value check if the memory
4283 * access is safe. Temporarily save and restore the register's state as
4284 * the conversion shouldn't be visible to a caller.
4285 */
4286 const struct bpf_reg_state saved_reg = *reg;
4287 int rv;
4288
4289 mark_ptr_not_null_reg(reg);
4290 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4291 *reg = saved_reg;
4292 return rv;
4293 }
4294
4295 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4296}
4297
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004298/* Implementation details:
4299 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4300 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4301 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4302 * value_or_null->value transition, since the verifier only cares about
4303 * the range of access to valid map value pointer and doesn't care about actual
4304 * address of the map element.
4305 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4306 * reg->id > 0 after value_or_null->value transition. By doing so
4307 * two bpf_map_lookups will be considered two different pointers that
4308 * point to different bpf_spin_locks.
4309 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4310 * dead-locks.
4311 * Since only one bpf_spin_lock is allowed the checks are simpler than
4312 * reg_is_refcounted() logic. The verifier needs to remember only
4313 * one spin_lock instead of array of acquired_refs.
4314 * cur_state->active_spin_lock remembers which map value element got locked
4315 * and clears it after bpf_spin_unlock.
4316 */
4317static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4318 bool is_lock)
4319{
4320 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4321 struct bpf_verifier_state *cur = env->cur_state;
4322 bool is_const = tnum_is_const(reg->var_off);
4323 struct bpf_map *map = reg->map_ptr;
4324 u64 val = reg->var_off.value;
4325
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004326 if (!is_const) {
4327 verbose(env,
4328 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4329 regno);
4330 return -EINVAL;
4331 }
4332 if (!map->btf) {
4333 verbose(env,
4334 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4335 map->name);
4336 return -EINVAL;
4337 }
4338 if (!map_value_has_spin_lock(map)) {
4339 if (map->spin_lock_off == -E2BIG)
4340 verbose(env,
4341 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4342 map->name);
4343 else if (map->spin_lock_off == -ENOENT)
4344 verbose(env,
4345 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4346 map->name);
4347 else
4348 verbose(env,
4349 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4350 map->name);
4351 return -EINVAL;
4352 }
4353 if (map->spin_lock_off != val + reg->off) {
4354 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4355 val + reg->off);
4356 return -EINVAL;
4357 }
4358 if (is_lock) {
4359 if (cur->active_spin_lock) {
4360 verbose(env,
4361 "Locking two bpf_spin_locks are not allowed\n");
4362 return -EINVAL;
4363 }
4364 cur->active_spin_lock = reg->id;
4365 } else {
4366 if (!cur->active_spin_lock) {
4367 verbose(env, "bpf_spin_unlock without taking a lock\n");
4368 return -EINVAL;
4369 }
4370 if (cur->active_spin_lock != reg->id) {
4371 verbose(env, "bpf_spin_unlock of different lock\n");
4372 return -EINVAL;
4373 }
4374 cur->active_spin_lock = 0;
4375 }
4376 return 0;
4377}
4378
Daniel Borkmann90133412018-01-20 01:24:29 +01004379static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
4380{
4381 return type == ARG_PTR_TO_MEM ||
4382 type == ARG_PTR_TO_MEM_OR_NULL ||
4383 type == ARG_PTR_TO_UNINIT_MEM;
4384}
4385
4386static bool arg_type_is_mem_size(enum bpf_arg_type type)
4387{
4388 return type == ARG_CONST_SIZE ||
4389 type == ARG_CONST_SIZE_OR_ZERO;
4390}
4391
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004392static bool arg_type_is_alloc_size(enum bpf_arg_type type)
4393{
4394 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
4395}
4396
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004397static bool arg_type_is_int_ptr(enum bpf_arg_type type)
4398{
4399 return type == ARG_PTR_TO_INT ||
4400 type == ARG_PTR_TO_LONG;
4401}
4402
4403static int int_ptr_type_to_size(enum bpf_arg_type type)
4404{
4405 if (type == ARG_PTR_TO_INT)
4406 return sizeof(u32);
4407 else if (type == ARG_PTR_TO_LONG)
4408 return sizeof(u64);
4409
4410 return -EINVAL;
4411}
4412
Lorenz Bauer912f4422020-08-21 11:29:46 +01004413static int resolve_map_arg_type(struct bpf_verifier_env *env,
4414 const struct bpf_call_arg_meta *meta,
4415 enum bpf_arg_type *arg_type)
4416{
4417 if (!meta->map_ptr) {
4418 /* kernel subsystem misconfigured verifier */
4419 verbose(env, "invalid map_ptr to access map->type\n");
4420 return -EACCES;
4421 }
4422
4423 switch (meta->map_ptr->map_type) {
4424 case BPF_MAP_TYPE_SOCKMAP:
4425 case BPF_MAP_TYPE_SOCKHASH:
4426 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01004427 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01004428 } else {
4429 verbose(env, "invalid arg_type for sockmap/sockhash\n");
4430 return -EINVAL;
4431 }
4432 break;
4433
4434 default:
4435 break;
4436 }
4437 return 0;
4438}
4439
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004440struct bpf_reg_types {
4441 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004442 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004443};
4444
4445static const struct bpf_reg_types map_key_value_types = {
4446 .types = {
4447 PTR_TO_STACK,
4448 PTR_TO_PACKET,
4449 PTR_TO_PACKET_META,
4450 PTR_TO_MAP_VALUE,
4451 },
4452};
4453
4454static const struct bpf_reg_types sock_types = {
4455 .types = {
4456 PTR_TO_SOCK_COMMON,
4457 PTR_TO_SOCKET,
4458 PTR_TO_TCP_SOCK,
4459 PTR_TO_XDP_SOCK,
4460 },
4461};
4462
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004463#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004464static const struct bpf_reg_types btf_id_sock_common_types = {
4465 .types = {
4466 PTR_TO_SOCK_COMMON,
4467 PTR_TO_SOCKET,
4468 PTR_TO_TCP_SOCK,
4469 PTR_TO_XDP_SOCK,
4470 PTR_TO_BTF_ID,
4471 },
4472 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
4473};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004474#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004475
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004476static const struct bpf_reg_types mem_types = {
4477 .types = {
4478 PTR_TO_STACK,
4479 PTR_TO_PACKET,
4480 PTR_TO_PACKET_META,
4481 PTR_TO_MAP_VALUE,
4482 PTR_TO_MEM,
4483 PTR_TO_RDONLY_BUF,
4484 PTR_TO_RDWR_BUF,
4485 },
4486};
4487
4488static const struct bpf_reg_types int_ptr_types = {
4489 .types = {
4490 PTR_TO_STACK,
4491 PTR_TO_PACKET,
4492 PTR_TO_PACKET_META,
4493 PTR_TO_MAP_VALUE,
4494 },
4495};
4496
4497static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
4498static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
4499static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
4500static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
4501static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
4502static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
4503static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004504static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004505
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01004506static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004507 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
4508 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
4509 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
4510 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
4511 [ARG_CONST_SIZE] = &scalar_types,
4512 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
4513 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
4514 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
4515 [ARG_PTR_TO_CTX] = &context_types,
4516 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
4517 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004518#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004519 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07004520#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004521 [ARG_PTR_TO_SOCKET] = &fullsock_types,
4522 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
4523 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
4524 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
4525 [ARG_PTR_TO_MEM] = &mem_types,
4526 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
4527 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
4528 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
4529 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
4530 [ARG_PTR_TO_INT] = &int_ptr_types,
4531 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004532 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004533};
4534
4535static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004536 enum bpf_arg_type arg_type,
4537 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004538{
4539 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4540 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004541 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004542 int i, j;
4543
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004544 compatible = compatible_reg_types[arg_type];
4545 if (!compatible) {
4546 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
4547 return -EFAULT;
4548 }
4549
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004550 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
4551 expected = compatible->types[i];
4552 if (expected == NOT_INIT)
4553 break;
4554
4555 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004556 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004557 }
4558
4559 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
4560 for (j = 0; j + 1 < i; j++)
4561 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
4562 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
4563 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004564
4565found:
4566 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07004567 if (!arg_btf_id) {
4568 if (!compatible->btf_id) {
4569 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
4570 return -EFAULT;
4571 }
4572 arg_btf_id = compatible->btf_id;
4573 }
4574
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004575 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
4576 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004577 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004578 regno, kernel_type_name(reg->btf, reg->btf_id),
4579 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004580 return -EACCES;
4581 }
4582
4583 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4584 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
4585 regno);
4586 return -EACCES;
4587 }
4588 }
4589
4590 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004591}
4592
Yonghong Songaf7ec132020-06-23 16:08:09 -07004593static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
4594 struct bpf_call_arg_meta *meta,
4595 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004596{
Yonghong Songaf7ec132020-06-23 16:08:09 -07004597 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004598 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07004599 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004600 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004601 int err = 0;
4602
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004603 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004604 return 0;
4605
Edward Creedc503a82017-08-15 20:34:35 +01004606 err = check_reg_arg(env, regno, SRC_OP);
4607 if (err)
4608 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004609
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004610 if (arg_type == ARG_ANYTHING) {
4611 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004612 verbose(env, "R%d leaks addr into helper function\n",
4613 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004614 return -EACCES;
4615 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004616 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004617 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01004618
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004619 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004620 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004621 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07004622 return -EACCES;
4623 }
4624
Lorenz Bauer912f4422020-08-21 11:29:46 +01004625 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
4626 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
4627 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
4628 err = resolve_map_arg_type(env, meta, &arg_type);
4629 if (err)
4630 return err;
4631 }
4632
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004633 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
4634 /* A NULL register has a SCALAR_VALUE type, so skip
4635 * type checking.
4636 */
4637 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02004638
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004639 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01004640 if (err)
4641 return err;
4642
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07004643 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01004644 err = check_ctx_reg(env, reg, regno);
4645 if (err < 0)
4646 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01004647 }
4648
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01004649skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01004650 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004651 if (meta->ref_obj_id) {
4652 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
4653 regno, reg->ref_obj_id,
4654 meta->ref_obj_id);
4655 return -EFAULT;
4656 }
4657 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004658 }
4659
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004660 if (arg_type == ARG_CONST_MAP_PTR) {
4661 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004662 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004663 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
4664 /* bpf_map_xxx(..., map_ptr, ..., key) call:
4665 * check that [key, key + map->key_size) are within
4666 * stack limits and initialized
4667 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004668 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004669 /* in function declaration map_ptr must come before
4670 * map_key, so that it's verified and known before
4671 * we have to check map_key here. Otherwise it means
4672 * that kernel subsystem misconfigured verifier
4673 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004674 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004675 return -EACCES;
4676 }
Paul Chaignond71962f2018-04-24 15:07:54 +02004677 err = check_helper_mem_access(env, regno,
4678 meta->map_ptr->key_size, false,
4679 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004680 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004681 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
4682 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004683 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004684 /* bpf_map_xxx(..., map_ptr, ..., value) call:
4685 * check [value, value + map->value_size) validity
4686 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02004687 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004688 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004689 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004690 return -EACCES;
4691 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004692 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02004693 err = check_helper_mem_access(env, regno,
4694 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02004695 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004696 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
4697 if (!reg->btf_id) {
4698 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
4699 return -EACCES;
4700 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004701 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07004702 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01004703 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
4704 if (meta->func_id == BPF_FUNC_spin_lock) {
4705 if (process_spin_lock(env, regno, true))
4706 return -EACCES;
4707 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
4708 if (process_spin_lock(env, regno, false))
4709 return -EACCES;
4710 } else {
4711 verbose(env, "verifier internal error\n");
4712 return -EFAULT;
4713 }
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01004714 } else if (arg_type_is_mem_ptr(arg_type)) {
4715 /* The access to this pointer is only checked when we hit the
4716 * next is_mem_size argument below.
4717 */
4718 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01004719 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08004720 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004721
John Fastabend10060502020-03-30 14:36:19 -07004722 /* This is used to refine r0 return value bounds for helpers
4723 * that enforce this value as an upper bound on return values.
4724 * See do_refine_retval_range() for helpers that can refine
4725 * the return value. C type of helper is u32 so we pull register
4726 * bound from umax_value however, if negative verifier errors
4727 * out. Only upper bounds can be learned because retval is an
4728 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07004729 */
John Fastabend10060502020-03-30 14:36:19 -07004730 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07004731
Edward Creef1174f72017-08-07 15:26:19 +01004732 /* The register is SCALAR_VALUE; the access check
4733 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08004734 */
Edward Creef1174f72017-08-07 15:26:19 +01004735 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08004736 /* For unprivileged variable accesses, disable raw
4737 * mode so that the program is required to
4738 * initialize all the memory that the helper could
4739 * just partially fill up.
4740 */
4741 meta = NULL;
4742
Edward Creeb03c9f92017-08-07 15:26:36 +01004743 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004744 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004745 regno);
4746 return -EACCES;
4747 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08004748
Edward Creeb03c9f92017-08-07 15:26:36 +01004749 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004750 err = check_helper_mem_access(env, regno - 1, 0,
4751 zero_size_allowed,
4752 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004753 if (err)
4754 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004755 }
Edward Creef1174f72017-08-07 15:26:19 +01004756
Edward Creeb03c9f92017-08-07 15:26:36 +01004757 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004758 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01004759 regno);
4760 return -EACCES;
4761 }
4762 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01004763 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01004764 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07004765 if (!err)
4766 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004767 } else if (arg_type_is_alloc_size(arg_type)) {
4768 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00004769 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004770 regno);
4771 return -EACCES;
4772 }
4773 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07004774 } else if (arg_type_is_int_ptr(arg_type)) {
4775 int size = int_ptr_type_to_size(arg_type);
4776
4777 err = check_helper_mem_access(env, regno, size, false, meta);
4778 if (err)
4779 return err;
4780 err = check_ptr_alignment(env, reg, 0, size, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004781 }
4782
4783 return err;
4784}
4785
Lorenz Bauer01262402020-08-21 11:29:47 +01004786static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
4787{
4788 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07004789 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01004790
4791 if (func_id != BPF_FUNC_map_update_elem)
4792 return false;
4793
4794 /* It's not possible to get access to a locked struct sock in these
4795 * contexts, so updating is safe.
4796 */
4797 switch (type) {
4798 case BPF_PROG_TYPE_TRACING:
4799 if (eatype == BPF_TRACE_ITER)
4800 return true;
4801 break;
4802 case BPF_PROG_TYPE_SOCKET_FILTER:
4803 case BPF_PROG_TYPE_SCHED_CLS:
4804 case BPF_PROG_TYPE_SCHED_ACT:
4805 case BPF_PROG_TYPE_XDP:
4806 case BPF_PROG_TYPE_SK_REUSEPORT:
4807 case BPF_PROG_TYPE_FLOW_DISSECTOR:
4808 case BPF_PROG_TYPE_SK_LOOKUP:
4809 return true;
4810 default:
4811 break;
4812 }
4813
4814 verbose(env, "cannot update sockmap in this context\n");
4815 return false;
4816}
4817
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004818static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
4819{
4820 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
4821}
4822
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004823static int check_map_func_compatibility(struct bpf_verifier_env *env,
4824 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00004825{
Kaixu Xia35578d72015-08-06 07:02:35 +00004826 if (!map)
4827 return 0;
4828
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004829 /* We need a two way check, first is from map perspective ... */
4830 switch (map->map_type) {
4831 case BPF_MAP_TYPE_PROG_ARRAY:
4832 if (func_id != BPF_FUNC_tail_call)
4833 goto error;
4834 break;
4835 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
4836 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07004837 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004838 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004839 func_id != BPF_FUNC_perf_event_read_value &&
4840 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004841 goto error;
4842 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004843 case BPF_MAP_TYPE_RINGBUF:
4844 if (func_id != BPF_FUNC_ringbuf_output &&
4845 func_id != BPF_FUNC_ringbuf_reserve &&
4846 func_id != BPF_FUNC_ringbuf_submit &&
4847 func_id != BPF_FUNC_ringbuf_discard &&
4848 func_id != BPF_FUNC_ringbuf_query)
4849 goto error;
4850 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004851 case BPF_MAP_TYPE_STACK_TRACE:
4852 if (func_id != BPF_FUNC_get_stackid)
4853 goto error;
4854 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07004855 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04004856 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004857 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004858 goto error;
4859 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004860 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00004861 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07004862 if (func_id != BPF_FUNC_get_local_storage)
4863 goto error;
4864 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07004865 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004866 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02004867 if (func_id != BPF_FUNC_redirect_map &&
4868 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07004869 goto error;
4870 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004871 /* Restrict bpf side of cpumap and xskmap, open when use-cases
4872 * appear.
4873 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02004874 case BPF_MAP_TYPE_CPUMAP:
4875 if (func_id != BPF_FUNC_redirect_map)
4876 goto error;
4877 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07004878 case BPF_MAP_TYPE_XSKMAP:
4879 if (func_id != BPF_FUNC_redirect_map &&
4880 func_id != BPF_FUNC_map_lookup_elem)
4881 goto error;
4882 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004883 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07004884 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07004885 if (func_id != BPF_FUNC_map_lookup_elem)
4886 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07004887 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004888 case BPF_MAP_TYPE_SOCKMAP:
4889 if (func_id != BPF_FUNC_sk_redirect_map &&
4890 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07004891 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004892 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004893 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004894 func_id != BPF_FUNC_map_lookup_elem &&
4895 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07004896 goto error;
4897 break;
John Fastabend81110382018-05-14 10:00:17 -07004898 case BPF_MAP_TYPE_SOCKHASH:
4899 if (func_id != BPF_FUNC_sk_redirect_hash &&
4900 func_id != BPF_FUNC_sock_hash_update &&
4901 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004902 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02004903 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01004904 func_id != BPF_FUNC_map_lookup_elem &&
4905 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07004906 goto error;
4907 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004908 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
4909 if (func_id != BPF_FUNC_sk_select_reuseport)
4910 goto error;
4911 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004912 case BPF_MAP_TYPE_QUEUE:
4913 case BPF_MAP_TYPE_STACK:
4914 if (func_id != BPF_FUNC_map_peek_elem &&
4915 func_id != BPF_FUNC_map_pop_elem &&
4916 func_id != BPF_FUNC_map_push_elem)
4917 goto error;
4918 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07004919 case BPF_MAP_TYPE_SK_STORAGE:
4920 if (func_id != BPF_FUNC_sk_storage_get &&
4921 func_id != BPF_FUNC_sk_storage_delete)
4922 goto error;
4923 break;
KP Singh8ea63682020-08-25 20:29:17 +02004924 case BPF_MAP_TYPE_INODE_STORAGE:
4925 if (func_id != BPF_FUNC_inode_storage_get &&
4926 func_id != BPF_FUNC_inode_storage_delete)
4927 goto error;
4928 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00004929 case BPF_MAP_TYPE_TASK_STORAGE:
4930 if (func_id != BPF_FUNC_task_storage_get &&
4931 func_id != BPF_FUNC_task_storage_delete)
4932 goto error;
4933 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004934 default:
4935 break;
4936 }
4937
4938 /* ... and second from the function itself. */
4939 switch (func_id) {
4940 case BPF_FUNC_tail_call:
4941 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
4942 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02004943 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
4944 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004945 return -EINVAL;
4946 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004947 break;
4948 case BPF_FUNC_perf_event_read:
4949 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07004950 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07004951 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00004952 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07004953 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
4954 goto error;
4955 break;
4956 case BPF_FUNC_get_stackid:
4957 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
4958 goto error;
4959 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07004960 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02004961 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07004962 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
4963 goto error;
4964 break;
John Fastabend97f91a72017-07-17 09:29:18 -07004965 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02004966 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02004967 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02004968 map->map_type != BPF_MAP_TYPE_CPUMAP &&
4969 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07004970 goto error;
4971 break;
John Fastabend174a79f2017-08-15 22:32:47 -07004972 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07004973 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07004974 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07004975 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
4976 goto error;
4977 break;
John Fastabend81110382018-05-14 10:00:17 -07004978 case BPF_FUNC_sk_redirect_hash:
4979 case BPF_FUNC_msg_redirect_hash:
4980 case BPF_FUNC_sock_hash_update:
4981 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07004982 goto error;
4983 break;
Roman Gushchincd339432018-08-02 14:27:24 -07004984 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00004985 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
4986 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07004987 goto error;
4988 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004989 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00004990 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
4991 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
4992 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07004993 goto error;
4994 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02004995 case BPF_FUNC_map_peek_elem:
4996 case BPF_FUNC_map_pop_elem:
4997 case BPF_FUNC_map_push_elem:
4998 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
4999 map->map_type != BPF_MAP_TYPE_STACK)
5000 goto error;
5001 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005002 case BPF_FUNC_sk_storage_get:
5003 case BPF_FUNC_sk_storage_delete:
5004 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5005 goto error;
5006 break;
KP Singh8ea63682020-08-25 20:29:17 +02005007 case BPF_FUNC_inode_storage_get:
5008 case BPF_FUNC_inode_storage_delete:
5009 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5010 goto error;
5011 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005012 case BPF_FUNC_task_storage_get:
5013 case BPF_FUNC_task_storage_delete:
5014 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5015 goto error;
5016 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005017 default:
5018 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005019 }
5020
5021 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005022error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005023 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005024 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005025 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005026}
5027
Daniel Borkmann90133412018-01-20 01:24:29 +01005028static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005029{
5030 int count = 0;
5031
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005032 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005033 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005034 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005035 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005036 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005037 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005038 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005039 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005040 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005041 count++;
5042
Daniel Borkmann90133412018-01-20 01:24:29 +01005043 /* We only support one arg being in raw mode at the moment,
5044 * which is sufficient for the helper functions we have
5045 * right now.
5046 */
5047 return count <= 1;
5048}
5049
5050static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5051 enum bpf_arg_type arg_next)
5052{
5053 return (arg_type_is_mem_ptr(arg_curr) &&
5054 !arg_type_is_mem_size(arg_next)) ||
5055 (!arg_type_is_mem_ptr(arg_curr) &&
5056 arg_type_is_mem_size(arg_next));
5057}
5058
5059static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5060{
5061 /* bpf_xxx(..., buf, len) call will access 'len'
5062 * bytes from memory 'buf'. Both arg types need
5063 * to be paired, so make sure there's no buggy
5064 * helper function specification.
5065 */
5066 if (arg_type_is_mem_size(fn->arg1_type) ||
5067 arg_type_is_mem_ptr(fn->arg5_type) ||
5068 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5069 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5070 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5071 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5072 return false;
5073
5074 return true;
5075}
5076
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005077static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005078{
5079 int count = 0;
5080
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005081 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005082 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005083 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005084 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005085 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005086 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005087 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005088 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005089 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005090 count++;
5091
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005092 /* A reference acquiring function cannot acquire
5093 * another refcounted ptr.
5094 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005095 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005096 return false;
5097
Joe Stringerfd978bf72018-10-02 13:35:35 -07005098 /* We only support one arg being unreferenced at the moment,
5099 * which is sufficient for the helper functions we have right now.
5100 */
5101 return count <= 1;
5102}
5103
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005104static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5105{
5106 int i;
5107
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005108 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005109 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5110 return false;
5111
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005112 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5113 return false;
5114 }
5115
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005116 return true;
5117}
5118
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005119static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005120{
5121 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005122 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005123 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005124 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005125}
5126
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005127/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5128 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005129 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005130static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5131 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005132{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005133 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005134 int i;
5135
5136 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005137 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005138 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005139
Joe Stringerf3709f62018-10-02 13:35:29 -07005140 bpf_for_each_spilled_reg(i, state, reg) {
5141 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005142 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005143 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005144 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005145 }
5146}
5147
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005148static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5149{
5150 struct bpf_verifier_state *vstate = env->cur_state;
5151 int i;
5152
5153 for (i = 0; i <= vstate->curframe; i++)
5154 __clear_all_pkt_pointers(env, vstate->frame[i]);
5155}
5156
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005157enum {
5158 AT_PKT_END = -1,
5159 BEYOND_PKT_END = -2,
5160};
5161
5162static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5163{
5164 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5165 struct bpf_reg_state *reg = &state->regs[regn];
5166
5167 if (reg->type != PTR_TO_PACKET)
5168 /* PTR_TO_PACKET_META is not supported yet */
5169 return;
5170
5171 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5172 * How far beyond pkt_end it goes is unknown.
5173 * if (!range_open) it's the case of pkt >= pkt_end
5174 * if (range_open) it's the case of pkt > pkt_end
5175 * hence this pointer is at least 1 byte bigger than pkt_end
5176 */
5177 if (range_open)
5178 reg->range = BEYOND_PKT_END;
5179 else
5180 reg->range = AT_PKT_END;
5181}
5182
Joe Stringerfd978bf72018-10-02 13:35:35 -07005183static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005184 struct bpf_func_state *state,
5185 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005186{
5187 struct bpf_reg_state *regs = state->regs, *reg;
5188 int i;
5189
5190 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005191 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005192 mark_reg_unknown(env, regs, i);
5193
5194 bpf_for_each_spilled_reg(i, state, reg) {
5195 if (!reg)
5196 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005197 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005198 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005199 }
5200}
5201
5202/* The pointer with the specified id has released its reference to kernel
5203 * resources. Identify all copies of the same pointer and clear the reference.
5204 */
5205static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005206 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005207{
5208 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005209 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005210 int i;
5211
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005212 err = release_reference_state(cur_func(env), ref_obj_id);
5213 if (err)
5214 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005215
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005216 for (i = 0; i <= vstate->curframe; i++)
5217 release_reg_references(env, vstate->frame[i], ref_obj_id);
5218
5219 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005220}
5221
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005222static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5223 struct bpf_reg_state *regs)
5224{
5225 int i;
5226
5227 /* after the call registers r0 - r5 were scratched */
5228 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5229 mark_reg_not_init(env, regs, caller_saved[i]);
5230 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5231 }
5232}
5233
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005234static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5235 int *insn_idx)
5236{
5237 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005238 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005239 struct bpf_func_state *caller, *callee;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005240 int i, err, subprog, target_insn;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005241 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005242
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005243 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005244 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005245 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005246 return -E2BIG;
5247 }
5248
5249 target_insn = *insn_idx + insn->imm;
5250 subprog = find_subprog(env, target_insn + 1);
5251 if (subprog < 0) {
5252 verbose(env, "verifier bug. No program starts at insn %d\n",
5253 target_insn + 1);
5254 return -EFAULT;
5255 }
5256
5257 caller = state->frame[state->curframe];
5258 if (state->frame[state->curframe + 1]) {
5259 verbose(env, "verifier bug. Frame %d already allocated\n",
5260 state->curframe + 1);
5261 return -EFAULT;
5262 }
5263
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005264 func_info_aux = env->prog->aux->func_info_aux;
5265 if (func_info_aux)
5266 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
5267 err = btf_check_func_arg_match(env, subprog, caller->regs);
5268 if (err == -EFAULT)
5269 return err;
5270 if (is_global) {
5271 if (err) {
5272 verbose(env, "Caller passes invalid args into func#%d\n",
5273 subprog);
5274 return err;
5275 } else {
5276 if (env->log.level & BPF_LOG_LEVEL)
5277 verbose(env,
5278 "Func#%d is global and valid. Skipping.\n",
5279 subprog);
5280 clear_caller_saved_regs(env, caller->regs);
5281
5282 /* All global functions return SCALAR_VALUE */
5283 mark_reg_unknown(env, caller->regs, BPF_REG_0);
5284
5285 /* continue with next insn after call */
5286 return 0;
5287 }
5288 }
5289
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005290 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
5291 if (!callee)
5292 return -ENOMEM;
5293 state->frame[state->curframe + 1] = callee;
5294
5295 /* callee cannot access r0, r6 - r9 for reading and has to write
5296 * into its own stack before reading from it.
5297 * callee can read/write into caller's stack
5298 */
5299 init_func_state(env, callee,
5300 /* remember the callsite, it will be used by bpf_exit */
5301 *insn_idx /* callsite */,
5302 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04005303 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005304
Joe Stringerfd978bf72018-10-02 13:35:35 -07005305 /* Transfer references to the callee */
5306 err = transfer_reference_state(callee, caller);
5307 if (err)
5308 return err;
5309
Edward Cree679c7822018-08-22 20:02:19 +01005310 /* copy r1 - r5 args that callee can access. The copy includes parent
5311 * pointers, which connects us up to the liveness chain
5312 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005313 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
5314 callee->regs[i] = caller->regs[i];
5315
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005316 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005317
5318 /* only increment it after check_reg_arg() finished */
5319 state->curframe++;
5320
5321 /* and go analyze first insn of the callee */
5322 *insn_idx = target_insn;
5323
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005324 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005325 verbose(env, "caller:\n");
5326 print_verifier_state(env, caller);
5327 verbose(env, "callee:\n");
5328 print_verifier_state(env, callee);
5329 }
5330 return 0;
5331}
5332
5333static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
5334{
5335 struct bpf_verifier_state *state = env->cur_state;
5336 struct bpf_func_state *caller, *callee;
5337 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005338 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005339
5340 callee = state->frame[state->curframe];
5341 r0 = &callee->regs[BPF_REG_0];
5342 if (r0->type == PTR_TO_STACK) {
5343 /* technically it's ok to return caller's stack pointer
5344 * (or caller's caller's pointer) back to the caller,
5345 * since these pointers are valid. Only current stack
5346 * pointer will be invalid as soon as function exits,
5347 * but let's be conservative
5348 */
5349 verbose(env, "cannot return stack pointer to the caller\n");
5350 return -EINVAL;
5351 }
5352
5353 state->curframe--;
5354 caller = state->frame[state->curframe];
5355 /* return to the caller whatever r0 had in the callee */
5356 caller->regs[BPF_REG_0] = *r0;
5357
Joe Stringerfd978bf72018-10-02 13:35:35 -07005358 /* Transfer references to the caller */
5359 err = transfer_reference_state(caller, callee);
5360 if (err)
5361 return err;
5362
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005363 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07005364 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005365 verbose(env, "returning from callee:\n");
5366 print_verifier_state(env, callee);
5367 verbose(env, "to caller at %d:\n", *insn_idx);
5368 print_verifier_state(env, caller);
5369 }
5370 /* clear everything in the callee */
5371 free_func_state(callee);
5372 state->frame[state->curframe + 1] = NULL;
5373 return 0;
5374}
5375
Yonghong Song849fa502018-04-28 22:28:09 -07005376static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
5377 int func_id,
5378 struct bpf_call_arg_meta *meta)
5379{
5380 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
5381
5382 if (ret_type != RET_INTEGER ||
5383 (func_id != BPF_FUNC_get_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02005384 func_id != BPF_FUNC_probe_read_str &&
5385 func_id != BPF_FUNC_probe_read_kernel_str &&
5386 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07005387 return;
5388
John Fastabend10060502020-03-30 14:36:19 -07005389 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07005390 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01005391 ret_reg->smin_value = -MAX_ERRNO;
5392 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07005393 __reg_deduce_bounds(ret_reg);
5394 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07005395 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07005396}
5397
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005398static int
5399record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5400 int func_id, int insn_idx)
5401{
5402 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02005403 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005404
5405 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02005406 func_id != BPF_FUNC_map_lookup_elem &&
5407 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005408 func_id != BPF_FUNC_map_delete_elem &&
5409 func_id != BPF_FUNC_map_push_elem &&
5410 func_id != BPF_FUNC_map_pop_elem &&
5411 func_id != BPF_FUNC_map_peek_elem)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005412 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02005413
Daniel Borkmann591fe982019-04-09 23:20:05 +02005414 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005415 verbose(env, "kernel subsystem misconfigured verifier\n");
5416 return -EINVAL;
5417 }
5418
Daniel Borkmann591fe982019-04-09 23:20:05 +02005419 /* In case of read-only, some additional restrictions
5420 * need to be applied in order to prevent altering the
5421 * state of the map from program side.
5422 */
5423 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
5424 (func_id == BPF_FUNC_map_delete_elem ||
5425 func_id == BPF_FUNC_map_update_elem ||
5426 func_id == BPF_FUNC_map_push_elem ||
5427 func_id == BPF_FUNC_map_pop_elem)) {
5428 verbose(env, "write into map forbidden\n");
5429 return -EACCES;
5430 }
5431
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005432 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005433 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005434 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005435 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005436 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005437 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005438 return 0;
5439}
5440
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005441static int
5442record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
5443 int func_id, int insn_idx)
5444{
5445 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
5446 struct bpf_reg_state *regs = cur_regs(env), *reg;
5447 struct bpf_map *map = meta->map_ptr;
5448 struct tnum range;
5449 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005450 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005451
5452 if (func_id != BPF_FUNC_tail_call)
5453 return 0;
5454 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
5455 verbose(env, "kernel subsystem misconfigured verifier\n");
5456 return -EINVAL;
5457 }
5458
5459 range = tnum_range(0, map->max_entries - 1);
5460 reg = &regs[BPF_REG_3];
5461
5462 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
5463 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5464 return 0;
5465 }
5466
Daniel Borkmanncc52d912019-12-19 22:19:50 +01005467 err = mark_chain_precision(env, BPF_REG_3);
5468 if (err)
5469 return err;
5470
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005471 val = reg->var_off.value;
5472 if (bpf_map_key_unseen(aux))
5473 bpf_map_key_store(aux, val);
5474 else if (!bpf_map_key_poisoned(aux) &&
5475 bpf_map_key_immediate(aux) != val)
5476 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
5477 return 0;
5478}
5479
Joe Stringerfd978bf72018-10-02 13:35:35 -07005480static int check_reference_leak(struct bpf_verifier_env *env)
5481{
5482 struct bpf_func_state *state = cur_func(env);
5483 int i;
5484
5485 for (i = 0; i < state->acquired_refs; i++) {
5486 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
5487 state->refs[i].id, state->refs[i].insn_idx);
5488 }
5489 return state->acquired_refs ? -EINVAL : 0;
5490}
5491
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005492static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005493{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005494 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005495 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005496 struct bpf_call_arg_meta meta;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005497 bool changes_data;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005498 int i, err;
5499
5500 /* find function prototype */
5501 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005502 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
5503 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005504 return -EINVAL;
5505 }
5506
Jakub Kicinski00176a32017-10-16 16:40:54 -07005507 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07005508 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005509 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005510 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
5511 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005512 return -EINVAL;
5513 }
5514
5515 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01005516 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02005517 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005518 return -EINVAL;
5519 }
5520
Jiri Olsaeae2e832020-08-25 21:21:19 +02005521 if (fn->allowed && !fn->allowed(env->prog)) {
5522 verbose(env, "helper call is not allowed in probe\n");
5523 return -EINVAL;
5524 }
5525
Daniel Borkmann04514d12017-12-14 21:07:25 +01005526 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08005527 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01005528 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
5529 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
5530 func_id_name(func_id), func_id);
5531 return -EINVAL;
5532 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005533
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005534 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02005535 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005536
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005537 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005538 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005539 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005540 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005541 return err;
5542 }
5543
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08005544 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005545 /* check args */
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005546 for (i = 0; i < 5; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005547 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005548 if (err)
5549 return err;
5550 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005551
Daniel Borkmannc93552c2018-05-24 02:32:53 +02005552 err = record_func_map(env, &meta, func_id, insn_idx);
5553 if (err)
5554 return err;
5555
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01005556 err = record_func_key(env, &meta, func_id, insn_idx);
5557 if (err)
5558 return err;
5559
Daniel Borkmann435faee12016-04-13 00:10:51 +02005560 /* Mark slots with STACK_MISC in case of raw mode, stack offset
5561 * is inferred from register state.
5562 */
5563 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01005564 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
5565 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02005566 if (err)
5567 return err;
5568 }
5569
Joe Stringerfd978bf72018-10-02 13:35:35 -07005570 if (func_id == BPF_FUNC_tail_call) {
5571 err = check_reference_leak(env);
5572 if (err) {
5573 verbose(env, "tail_call would lead to reference leak\n");
5574 return err;
5575 }
5576 } else if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005577 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005578 if (err) {
5579 verbose(env, "func %s#%d reference has not been acquired before\n",
5580 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005581 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08005582 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07005583 }
5584
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005585 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07005586
5587 /* check that flags argument in get_local_storage(map, flags) is 0,
5588 * this is required because get_local_storage() can't return an error.
5589 */
5590 if (func_id == BPF_FUNC_get_local_storage &&
5591 !register_is_null(&regs[BPF_REG_2])) {
5592 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
5593 return -EINVAL;
5594 }
5595
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005596 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01005597 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005598 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01005599 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5600 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005601
Jiong Wang5327ed32019-05-24 23:25:12 +01005602 /* helper call returns 64-bit value. */
5603 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
5604
Edward Creedc503a82017-08-15 20:34:35 +01005605 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005606 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01005607 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005608 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005609 } else if (fn->ret_type == RET_VOID) {
5610 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07005611 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
5612 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01005613 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005614 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005615 /* remember map_ptr, so that check_map_access()
5616 * can check 'value_size' boundary of memory access
5617 * to map element returned from bpf_map_lookup_elem()
5618 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005619 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005620 verbose(env,
5621 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005622 return -EINVAL;
5623 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005624 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005625 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
5626 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08005627 if (map_value_has_spin_lock(meta.map_ptr))
5628 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005629 } else {
5630 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01005631 }
Joe Stringerc64b7982018-10-02 13:35:33 -07005632 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
5633 mark_reg_known_zero(env, regs, BPF_REG_0);
5634 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08005635 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
5636 mark_reg_known_zero(env, regs, BPF_REG_0);
5637 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08005638 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
5639 mark_reg_known_zero(env, regs, BPF_REG_0);
5640 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005641 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
5642 mark_reg_known_zero(env, regs, BPF_REG_0);
5643 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005644 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07005645 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
5646 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005647 const struct btf_type *t;
5648
5649 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005650 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005651 if (!btf_type_is_struct(t)) {
5652 u32 tsize;
5653 const struct btf_type *ret;
5654 const char *tname;
5655
5656 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005657 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005658 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005659 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005660 verbose(env, "unable to resolve the size of type '%s': %ld\n",
5661 tname, PTR_ERR(ret));
5662 return -EINVAL;
5663 }
Hao Luo63d9b802020-09-29 16:50:48 -07005664 regs[BPF_REG_0].type =
5665 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5666 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005667 regs[BPF_REG_0].mem_size = tsize;
5668 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07005669 regs[BPF_REG_0].type =
5670 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
5671 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005672 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005673 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
5674 }
KP Singh3ca10322020-11-06 10:37:43 +00005675 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
5676 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07005677 int ret_btf_id;
5678
5679 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00005680 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
5681 PTR_TO_BTF_ID :
5682 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005683 ret_btf_id = *fn->ret_btf_id;
5684 if (ret_btf_id == 0) {
5685 verbose(env, "invalid return type %d of func %s#%d\n",
5686 fn->ret_type, func_id_name(func_id), func_id);
5687 return -EINVAL;
5688 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005689 /* current BPF helper definitions are only coming from
5690 * built-in code with type IDs from vmlinux BTF
5691 */
5692 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07005693 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005694 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005695 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005696 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005697 return -EINVAL;
5698 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005699
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07005700 if (reg_type_may_be_null(regs[BPF_REG_0].type))
5701 regs[BPF_REG_0].id = ++env->id_gen;
5702
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005703 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005704 /* For release_reference() */
5705 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005706 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08005707 int id = acquire_reference_state(env, insn_idx);
5708
5709 if (id < 0)
5710 return id;
5711 /* For mark_ptr_or_null_reg() */
5712 regs[BPF_REG_0].id = id;
5713 /* For release_reference() */
5714 regs[BPF_REG_0].ref_obj_id = id;
5715 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005716
Yonghong Song849fa502018-04-28 22:28:09 -07005717 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
5718
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005719 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00005720 if (err)
5721 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07005722
Song Liufa28dcb2020-06-29 23:28:44 -07005723 if ((func_id == BPF_FUNC_get_stack ||
5724 func_id == BPF_FUNC_get_task_stack) &&
5725 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07005726 const char *err_str;
5727
5728#ifdef CONFIG_PERF_EVENTS
5729 err = get_callchain_buffers(sysctl_perf_event_max_stack);
5730 err_str = "cannot get callchain buffer for func %s#%d\n";
5731#else
5732 err = -ENOTSUPP;
5733 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
5734#endif
5735 if (err) {
5736 verbose(env, err_str, func_id_name(func_id), func_id);
5737 return err;
5738 }
5739
5740 env->prog->has_callchain_buf = true;
5741 }
5742
Song Liu5d99cb2c2020-07-23 11:06:45 -07005743 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
5744 env->prog->call_get_stack = true;
5745
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005746 if (changes_data)
5747 clear_all_pkt_pointers(env);
5748 return 0;
5749}
5750
Edward Creeb03c9f92017-08-07 15:26:36 +01005751static bool signed_add_overflows(s64 a, s64 b)
5752{
5753 /* Do the add in u64, where overflow is well-defined */
5754 s64 res = (s64)((u64)a + (u64)b);
5755
5756 if (b < 0)
5757 return res > a;
5758 return res < a;
5759}
5760
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005761static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07005762{
5763 /* Do the add in u32, where overflow is well-defined */
5764 s32 res = (s32)((u32)a + (u32)b);
5765
5766 if (b < 0)
5767 return res > a;
5768 return res < a;
5769}
5770
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005771static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01005772{
5773 /* Do the sub in u64, where overflow is well-defined */
5774 s64 res = (s64)((u64)a - (u64)b);
5775
5776 if (b < 0)
5777 return res < a;
5778 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07005779}
5780
John Fastabend3f50f132020-03-30 14:36:39 -07005781static bool signed_sub32_overflows(s32 a, s32 b)
5782{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01005783 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07005784 s32 res = (s32)((u32)a - (u32)b);
5785
5786 if (b < 0)
5787 return res < a;
5788 return res > a;
5789}
5790
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08005791static bool check_reg_sane_offset(struct bpf_verifier_env *env,
5792 const struct bpf_reg_state *reg,
5793 enum bpf_reg_type type)
5794{
5795 bool known = tnum_is_const(reg->var_off);
5796 s64 val = reg->var_off.value;
5797 s64 smin = reg->smin_value;
5798
5799 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
5800 verbose(env, "math between %s pointer and %lld is not allowed\n",
5801 reg_type_str[type], val);
5802 return false;
5803 }
5804
5805 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
5806 verbose(env, "%s pointer offset %d is not allowed\n",
5807 reg_type_str[type], reg->off);
5808 return false;
5809 }
5810
5811 if (smin == S64_MIN) {
5812 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
5813 reg_type_str[type]);
5814 return false;
5815 }
5816
5817 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
5818 verbose(env, "value %lld makes %s pointer be out of bounds\n",
5819 smin, reg_type_str[type]);
5820 return false;
5821 }
5822
5823 return true;
5824}
5825
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005826static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
5827{
5828 return &env->insn_aux_data[env->insn_idx];
5829}
5830
5831static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
5832 u32 *ptr_limit, u8 opcode, bool off_is_neg)
5833{
5834 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
5835 (opcode == BPF_SUB && !off_is_neg);
5836 u32 off;
5837
5838 switch (ptr_reg->type) {
5839 case PTR_TO_STACK:
Andrey Ignatov088ec262019-04-03 23:22:39 -07005840 /* Indirect variable offset stack access is prohibited in
5841 * unprivileged mode so it's not handled here.
5842 */
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005843 off = ptr_reg->off + ptr_reg->var_off.value;
5844 if (mask_to_left)
5845 *ptr_limit = MAX_BPF_STACK + off;
5846 else
5847 *ptr_limit = -off;
5848 return 0;
5849 case PTR_TO_MAP_VALUE:
5850 if (mask_to_left) {
5851 *ptr_limit = ptr_reg->umax_value + ptr_reg->off;
5852 } else {
5853 off = ptr_reg->smin_value + ptr_reg->off;
5854 *ptr_limit = ptr_reg->map_ptr->value_size - off;
5855 }
5856 return 0;
5857 default:
5858 return -EINVAL;
5859 }
5860}
5861
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005862static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
5863 const struct bpf_insn *insn)
5864{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07005865 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005866}
5867
5868static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
5869 u32 alu_state, u32 alu_limit)
5870{
5871 /* If we arrived here from different branches with different
5872 * state or limits to sanitize, then this won't work.
5873 */
5874 if (aux->alu_state &&
5875 (aux->alu_state != alu_state ||
5876 aux->alu_limit != alu_limit))
5877 return -EACCES;
5878
5879 /* Corresponding fixup done in fixup_bpf_calls(). */
5880 aux->alu_state = alu_state;
5881 aux->alu_limit = alu_limit;
5882 return 0;
5883}
5884
5885static int sanitize_val_alu(struct bpf_verifier_env *env,
5886 struct bpf_insn *insn)
5887{
5888 struct bpf_insn_aux_data *aux = cur_aux(env);
5889
5890 if (can_skip_alu_sanitation(env, insn))
5891 return 0;
5892
5893 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
5894}
5895
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005896static int sanitize_ptr_alu(struct bpf_verifier_env *env,
5897 struct bpf_insn *insn,
5898 const struct bpf_reg_state *ptr_reg,
5899 struct bpf_reg_state *dst_reg,
5900 bool off_is_neg)
5901{
5902 struct bpf_verifier_state *vstate = env->cur_state;
5903 struct bpf_insn_aux_data *aux = cur_aux(env);
5904 bool ptr_is_dst_reg = ptr_reg == dst_reg;
5905 u8 opcode = BPF_OP(insn->code);
5906 u32 alu_state, alu_limit;
5907 struct bpf_reg_state tmp;
5908 bool ret;
5909
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005910 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005911 return 0;
5912
5913 /* We already marked aux for masking from non-speculative
5914 * paths, thus we got here in the first place. We only care
5915 * to explore bad access from here.
5916 */
5917 if (vstate->speculative)
5918 goto do_sim;
5919
5920 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
5921 alu_state |= ptr_is_dst_reg ?
5922 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
5923
5924 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg))
5925 return 0;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01005926 if (update_alu_sanitation_state(aux, alu_state, alu_limit))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005927 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005928do_sim:
5929 /* Simulate and find potential out-of-bounds access under
5930 * speculative execution from truncation as a result of
5931 * masking when off was not within expected range. If off
5932 * sits in dst, then we temporarily need to move ptr there
5933 * to simulate dst (== 0) +/-= ptr. Needed, for example,
5934 * for cases where we use K-based arithmetic in one direction
5935 * and truncated reg-based in the other in order to explore
5936 * bad access.
5937 */
5938 if (!ptr_is_dst_reg) {
5939 tmp = *dst_reg;
5940 *dst_reg = *ptr_reg;
5941 }
5942 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true);
Xu Yu08032782019-03-21 18:00:35 +08005943 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01005944 *dst_reg = tmp;
5945 return !ret ? -EFAULT : 0;
5946}
5947
Andrei Matei01f810a2021-02-06 20:10:24 -05005948/* check that stack access falls within stack limits and that 'reg' doesn't
5949 * have a variable offset.
5950 *
5951 * Variable offset is prohibited for unprivileged mode for simplicity since it
5952 * requires corresponding support in Spectre masking for stack ALU. See also
5953 * retrieve_ptr_limit().
5954 *
5955 *
5956 * 'off' includes 'reg->off'.
5957 */
5958static int check_stack_access_for_ptr_arithmetic(
5959 struct bpf_verifier_env *env,
5960 int regno,
5961 const struct bpf_reg_state *reg,
5962 int off)
5963{
5964 if (!tnum_is_const(reg->var_off)) {
5965 char tn_buf[48];
5966
5967 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5968 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
5969 regno, tn_buf, off);
5970 return -EACCES;
5971 }
5972
5973 if (off >= 0 || off < -MAX_BPF_STACK) {
5974 verbose(env, "R%d stack pointer arithmetic goes out of range, "
5975 "prohibited for !root; off=%d\n", regno, off);
5976 return -EACCES;
5977 }
5978
5979 return 0;
5980}
5981
5982
Edward Creef1174f72017-08-07 15:26:19 +01005983/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01005984 * Caller should also handle BPF_MOV case separately.
5985 * If we return -EACCES, caller may want to try again treating pointer as a
5986 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
5987 */
5988static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
5989 struct bpf_insn *insn,
5990 const struct bpf_reg_state *ptr_reg,
5991 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04005992{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005993 struct bpf_verifier_state *vstate = env->cur_state;
5994 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5995 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01005996 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01005997 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
5998 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
5999 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
6000 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006001 u32 dst = insn->dst_reg, src = insn->src_reg;
Josef Bacik48461132016-09-28 10:54:32 -04006002 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006003 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04006004
Edward Creef1174f72017-08-07 15:26:19 +01006005 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04006006
Daniel Borkmann6f161012018-01-18 01:15:21 +01006007 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
6008 smin_val > smax_val || umin_val > umax_val) {
6009 /* Taint dst register if offset had invalid bounds derived from
6010 * e.g. dead branches.
6011 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006012 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01006013 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04006014 }
6015
Edward Creef1174f72017-08-07 15:26:19 +01006016 if (BPF_CLASS(insn->code) != BPF_ALU64) {
6017 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07006018 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
6019 __mark_reg_unknown(env, dst_reg);
6020 return 0;
6021 }
6022
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006023 verbose(env,
6024 "R%d 32-bit pointer arithmetic prohibited\n",
6025 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006026 return -EACCES;
6027 }
David S. Millerd1174412017-05-10 11:22:52 -07006028
Joe Stringeraad2eea2018-10-02 13:35:30 -07006029 switch (ptr_reg->type) {
6030 case PTR_TO_MAP_VALUE_OR_NULL:
6031 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
6032 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006033 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006034 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07006035 /* smin_val represents the known value */
6036 if (known && smin_val == 0 && opcode == BPF_ADD)
6037 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05006038 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006039 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07006040 case PTR_TO_SOCKET:
6041 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006042 case PTR_TO_SOCK_COMMON:
6043 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006044 case PTR_TO_TCP_SOCK:
6045 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07006046 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07006047 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
6048 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01006049 return -EACCES;
Daniel Borkmann9d7ecee2019-01-03 00:58:32 +01006050 case PTR_TO_MAP_VALUE:
6051 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) {
6052 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n",
6053 off_reg == dst_reg ? dst : src);
6054 return -EACCES;
6055 }
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -05006056 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07006057 default:
6058 break;
Edward Creef1174f72017-08-07 15:26:19 +01006059 }
6060
6061 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
6062 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04006063 */
Edward Creef1174f72017-08-07 15:26:19 +01006064 dst_reg->type = ptr_reg->type;
6065 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05006066
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006067 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
6068 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
6069 return -EINVAL;
6070
John Fastabend3f50f132020-03-30 14:36:39 -07006071 /* pointer types do not carry 32-bit bounds at the moment. */
6072 __mark_reg32_unbounded(dst_reg);
6073
Josef Bacik48461132016-09-28 10:54:32 -04006074 switch (opcode) {
6075 case BPF_ADD:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006076 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6077 if (ret < 0) {
6078 verbose(env, "R%d tried to add from different maps or paths\n", dst);
6079 return ret;
6080 }
Edward Creef1174f72017-08-07 15:26:19 +01006081 /* We can take a fixed offset as long as it doesn't overflow
6082 * the s32 'off' field
6083 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006084 if (known && (ptr_reg->off + smin_val ==
6085 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006086 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006087 dst_reg->smin_value = smin_ptr;
6088 dst_reg->smax_value = smax_ptr;
6089 dst_reg->umin_value = umin_ptr;
6090 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006091 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01006092 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006093 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006094 break;
6095 }
Edward Creef1174f72017-08-07 15:26:19 +01006096 /* A new variable offset is created. Note that off_reg->off
6097 * == 0, since it's a scalar.
6098 * dst_reg gets the pointer type and since some positive
6099 * integer value was added to the pointer, give it a new 'id'
6100 * if it's a PTR_TO_PACKET.
6101 * this creates a new 'base' pointer, off_reg (variable) gets
6102 * added into the variable offset, and we copy the fixed offset
6103 * from ptr_reg.
6104 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006105 if (signed_add_overflows(smin_ptr, smin_val) ||
6106 signed_add_overflows(smax_ptr, smax_val)) {
6107 dst_reg->smin_value = S64_MIN;
6108 dst_reg->smax_value = S64_MAX;
6109 } else {
6110 dst_reg->smin_value = smin_ptr + smin_val;
6111 dst_reg->smax_value = smax_ptr + smax_val;
6112 }
6113 if (umin_ptr + umin_val < umin_ptr ||
6114 umax_ptr + umax_val < umax_ptr) {
6115 dst_reg->umin_value = 0;
6116 dst_reg->umax_value = U64_MAX;
6117 } else {
6118 dst_reg->umin_value = umin_ptr + umin_val;
6119 dst_reg->umax_value = umax_ptr + umax_val;
6120 }
Edward Creef1174f72017-08-07 15:26:19 +01006121 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
6122 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006123 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006124 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006125 dst_reg->id = ++env->id_gen;
6126 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006127 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006128 }
Josef Bacik48461132016-09-28 10:54:32 -04006129 break;
6130 case BPF_SUB:
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006131 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0);
6132 if (ret < 0) {
6133 verbose(env, "R%d tried to sub from different maps or paths\n", dst);
6134 return ret;
6135 }
Edward Creef1174f72017-08-07 15:26:19 +01006136 if (dst_reg == off_reg) {
6137 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006138 verbose(env, "R%d tried to subtract pointer from scalar\n",
6139 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006140 return -EACCES;
6141 }
6142 /* We don't allow subtraction from FP, because (according to
6143 * test_verifier.c test "invalid fp arithmetic", JITs might not
6144 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01006145 */
Edward Creef1174f72017-08-07 15:26:19 +01006146 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006147 verbose(env, "R%d subtraction from stack pointer prohibited\n",
6148 dst);
Edward Creef1174f72017-08-07 15:26:19 +01006149 return -EACCES;
6150 }
Edward Creeb03c9f92017-08-07 15:26:36 +01006151 if (known && (ptr_reg->off - smin_val ==
6152 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01006153 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01006154 dst_reg->smin_value = smin_ptr;
6155 dst_reg->smax_value = smax_ptr;
6156 dst_reg->umin_value = umin_ptr;
6157 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01006158 dst_reg->var_off = ptr_reg->var_off;
6159 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01006160 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01006161 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01006162 break;
6163 }
Edward Creef1174f72017-08-07 15:26:19 +01006164 /* A new variable offset is created. If the subtrahend is known
6165 * nonnegative, then any reg->range we had before is still good.
6166 */
Edward Creeb03c9f92017-08-07 15:26:36 +01006167 if (signed_sub_overflows(smin_ptr, smax_val) ||
6168 signed_sub_overflows(smax_ptr, smin_val)) {
6169 /* Overflow possible, we know nothing */
6170 dst_reg->smin_value = S64_MIN;
6171 dst_reg->smax_value = S64_MAX;
6172 } else {
6173 dst_reg->smin_value = smin_ptr - smax_val;
6174 dst_reg->smax_value = smax_ptr - smin_val;
6175 }
6176 if (umin_ptr < umax_val) {
6177 /* Overflow possible, we know nothing */
6178 dst_reg->umin_value = 0;
6179 dst_reg->umax_value = U64_MAX;
6180 } else {
6181 /* Cannot overflow (as long as bounds are consistent) */
6182 dst_reg->umin_value = umin_ptr - umax_val;
6183 dst_reg->umax_value = umax_ptr - umin_val;
6184 }
Edward Creef1174f72017-08-07 15:26:19 +01006185 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
6186 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01006187 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02006188 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01006189 dst_reg->id = ++env->id_gen;
6190 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01006191 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006192 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01006193 }
6194 break;
6195 case BPF_AND:
6196 case BPF_OR:
6197 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006198 /* bitwise ops on pointers are troublesome, prohibit. */
6199 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
6200 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006201 return -EACCES;
6202 default:
6203 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08006204 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
6205 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01006206 return -EACCES;
6207 }
6208
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006209 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
6210 return -EINVAL;
6211
Edward Creeb03c9f92017-08-07 15:26:36 +01006212 __update_reg_bounds(dst_reg);
6213 __reg_deduce_bounds(dst_reg);
6214 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006215
6216 /* For unprivileged we require that resulting offset must be in bounds
6217 * in order to be able to sanitize access later on.
6218 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006219 if (!env->bypass_spec_v1) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006220 if (dst_reg->type == PTR_TO_MAP_VALUE &&
6221 check_map_access(env, dst, dst_reg->off, 1, false)) {
6222 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
6223 "prohibited for !root\n", dst);
6224 return -EACCES;
6225 } else if (dst_reg->type == PTR_TO_STACK &&
Andrei Matei01f810a2021-02-06 20:10:24 -05006226 check_stack_access_for_ptr_arithmetic(
6227 env, dst, dst_reg, dst_reg->off +
6228 dst_reg->var_off.value)) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01006229 return -EACCES;
6230 }
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01006231 }
6232
Edward Creef1174f72017-08-07 15:26:19 +01006233 return 0;
6234}
6235
John Fastabend3f50f132020-03-30 14:36:39 -07006236static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
6237 struct bpf_reg_state *src_reg)
6238{
6239 s32 smin_val = src_reg->s32_min_value;
6240 s32 smax_val = src_reg->s32_max_value;
6241 u32 umin_val = src_reg->u32_min_value;
6242 u32 umax_val = src_reg->u32_max_value;
6243
6244 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
6245 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
6246 dst_reg->s32_min_value = S32_MIN;
6247 dst_reg->s32_max_value = S32_MAX;
6248 } else {
6249 dst_reg->s32_min_value += smin_val;
6250 dst_reg->s32_max_value += smax_val;
6251 }
6252 if (dst_reg->u32_min_value + umin_val < umin_val ||
6253 dst_reg->u32_max_value + umax_val < umax_val) {
6254 dst_reg->u32_min_value = 0;
6255 dst_reg->u32_max_value = U32_MAX;
6256 } else {
6257 dst_reg->u32_min_value += umin_val;
6258 dst_reg->u32_max_value += umax_val;
6259 }
6260}
6261
John Fastabend07cd2632020-03-24 10:38:15 -07006262static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
6263 struct bpf_reg_state *src_reg)
6264{
6265 s64 smin_val = src_reg->smin_value;
6266 s64 smax_val = src_reg->smax_value;
6267 u64 umin_val = src_reg->umin_value;
6268 u64 umax_val = src_reg->umax_value;
6269
6270 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
6271 signed_add_overflows(dst_reg->smax_value, smax_val)) {
6272 dst_reg->smin_value = S64_MIN;
6273 dst_reg->smax_value = S64_MAX;
6274 } else {
6275 dst_reg->smin_value += smin_val;
6276 dst_reg->smax_value += smax_val;
6277 }
6278 if (dst_reg->umin_value + umin_val < umin_val ||
6279 dst_reg->umax_value + umax_val < umax_val) {
6280 dst_reg->umin_value = 0;
6281 dst_reg->umax_value = U64_MAX;
6282 } else {
6283 dst_reg->umin_value += umin_val;
6284 dst_reg->umax_value += umax_val;
6285 }
John Fastabend3f50f132020-03-30 14:36:39 -07006286}
6287
6288static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
6289 struct bpf_reg_state *src_reg)
6290{
6291 s32 smin_val = src_reg->s32_min_value;
6292 s32 smax_val = src_reg->s32_max_value;
6293 u32 umin_val = src_reg->u32_min_value;
6294 u32 umax_val = src_reg->u32_max_value;
6295
6296 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
6297 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
6298 /* Overflow possible, we know nothing */
6299 dst_reg->s32_min_value = S32_MIN;
6300 dst_reg->s32_max_value = S32_MAX;
6301 } else {
6302 dst_reg->s32_min_value -= smax_val;
6303 dst_reg->s32_max_value -= smin_val;
6304 }
6305 if (dst_reg->u32_min_value < umax_val) {
6306 /* Overflow possible, we know nothing */
6307 dst_reg->u32_min_value = 0;
6308 dst_reg->u32_max_value = U32_MAX;
6309 } else {
6310 /* Cannot overflow (as long as bounds are consistent) */
6311 dst_reg->u32_min_value -= umax_val;
6312 dst_reg->u32_max_value -= umin_val;
6313 }
John Fastabend07cd2632020-03-24 10:38:15 -07006314}
6315
6316static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
6317 struct bpf_reg_state *src_reg)
6318{
6319 s64 smin_val = src_reg->smin_value;
6320 s64 smax_val = src_reg->smax_value;
6321 u64 umin_val = src_reg->umin_value;
6322 u64 umax_val = src_reg->umax_value;
6323
6324 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
6325 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
6326 /* Overflow possible, we know nothing */
6327 dst_reg->smin_value = S64_MIN;
6328 dst_reg->smax_value = S64_MAX;
6329 } else {
6330 dst_reg->smin_value -= smax_val;
6331 dst_reg->smax_value -= smin_val;
6332 }
6333 if (dst_reg->umin_value < umax_val) {
6334 /* Overflow possible, we know nothing */
6335 dst_reg->umin_value = 0;
6336 dst_reg->umax_value = U64_MAX;
6337 } else {
6338 /* Cannot overflow (as long as bounds are consistent) */
6339 dst_reg->umin_value -= umax_val;
6340 dst_reg->umax_value -= umin_val;
6341 }
John Fastabend3f50f132020-03-30 14:36:39 -07006342}
6343
6344static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
6345 struct bpf_reg_state *src_reg)
6346{
6347 s32 smin_val = src_reg->s32_min_value;
6348 u32 umin_val = src_reg->u32_min_value;
6349 u32 umax_val = src_reg->u32_max_value;
6350
6351 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
6352 /* Ain't nobody got time to multiply that sign */
6353 __mark_reg32_unbounded(dst_reg);
6354 return;
6355 }
6356 /* Both values are positive, so we can work with unsigned and
6357 * copy the result to signed (unless it exceeds S32_MAX).
6358 */
6359 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
6360 /* Potential overflow, we know nothing */
6361 __mark_reg32_unbounded(dst_reg);
6362 return;
6363 }
6364 dst_reg->u32_min_value *= umin_val;
6365 dst_reg->u32_max_value *= umax_val;
6366 if (dst_reg->u32_max_value > S32_MAX) {
6367 /* Overflow possible, we know nothing */
6368 dst_reg->s32_min_value = S32_MIN;
6369 dst_reg->s32_max_value = S32_MAX;
6370 } else {
6371 dst_reg->s32_min_value = dst_reg->u32_min_value;
6372 dst_reg->s32_max_value = dst_reg->u32_max_value;
6373 }
John Fastabend07cd2632020-03-24 10:38:15 -07006374}
6375
6376static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
6377 struct bpf_reg_state *src_reg)
6378{
6379 s64 smin_val = src_reg->smin_value;
6380 u64 umin_val = src_reg->umin_value;
6381 u64 umax_val = src_reg->umax_value;
6382
John Fastabend07cd2632020-03-24 10:38:15 -07006383 if (smin_val < 0 || dst_reg->smin_value < 0) {
6384 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07006385 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006386 return;
6387 }
6388 /* Both values are positive, so we can work with unsigned and
6389 * copy the result to signed (unless it exceeds S64_MAX).
6390 */
6391 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
6392 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07006393 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006394 return;
6395 }
6396 dst_reg->umin_value *= umin_val;
6397 dst_reg->umax_value *= umax_val;
6398 if (dst_reg->umax_value > S64_MAX) {
6399 /* Overflow possible, we know nothing */
6400 dst_reg->smin_value = S64_MIN;
6401 dst_reg->smax_value = S64_MAX;
6402 } else {
6403 dst_reg->smin_value = dst_reg->umin_value;
6404 dst_reg->smax_value = dst_reg->umax_value;
6405 }
6406}
6407
John Fastabend3f50f132020-03-30 14:36:39 -07006408static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
6409 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006410{
John Fastabend3f50f132020-03-30 14:36:39 -07006411 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6412 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6413 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6414 s32 smin_val = src_reg->s32_min_value;
6415 u32 umax_val = src_reg->u32_max_value;
6416
6417 /* Assuming scalar64_min_max_and will be called so its safe
6418 * to skip updating register for known 32-bit case.
6419 */
6420 if (src_known && dst_known)
6421 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006422
6423 /* We get our minimum from the var_off, since that's inherently
6424 * bitwise. Our maximum is the minimum of the operands' maxima.
6425 */
John Fastabend3f50f132020-03-30 14:36:39 -07006426 dst_reg->u32_min_value = var32_off.value;
6427 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
6428 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6429 /* Lose signed bounds when ANDing negative numbers,
6430 * ain't nobody got time for that.
6431 */
6432 dst_reg->s32_min_value = S32_MIN;
6433 dst_reg->s32_max_value = S32_MAX;
6434 } else {
6435 /* ANDing two positives gives a positive, so safe to
6436 * cast result into s64.
6437 */
6438 dst_reg->s32_min_value = dst_reg->u32_min_value;
6439 dst_reg->s32_max_value = dst_reg->u32_max_value;
6440 }
6441
6442}
6443
6444static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
6445 struct bpf_reg_state *src_reg)
6446{
6447 bool src_known = tnum_is_const(src_reg->var_off);
6448 bool dst_known = tnum_is_const(dst_reg->var_off);
6449 s64 smin_val = src_reg->smin_value;
6450 u64 umax_val = src_reg->umax_value;
6451
6452 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006453 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006454 return;
6455 }
6456
6457 /* We get our minimum from the var_off, since that's inherently
6458 * bitwise. Our maximum is the minimum of the operands' maxima.
6459 */
John Fastabend07cd2632020-03-24 10:38:15 -07006460 dst_reg->umin_value = dst_reg->var_off.value;
6461 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
6462 if (dst_reg->smin_value < 0 || smin_val < 0) {
6463 /* Lose signed bounds when ANDing negative numbers,
6464 * ain't nobody got time for that.
6465 */
6466 dst_reg->smin_value = S64_MIN;
6467 dst_reg->smax_value = S64_MAX;
6468 } else {
6469 /* ANDing two positives gives a positive, so safe to
6470 * cast result into s64.
6471 */
6472 dst_reg->smin_value = dst_reg->umin_value;
6473 dst_reg->smax_value = dst_reg->umax_value;
6474 }
6475 /* We may learn something more from the var_off */
6476 __update_reg_bounds(dst_reg);
6477}
6478
John Fastabend3f50f132020-03-30 14:36:39 -07006479static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
6480 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006481{
John Fastabend3f50f132020-03-30 14:36:39 -07006482 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6483 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6484 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006485 s32 smin_val = src_reg->s32_min_value;
6486 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006487
6488 /* Assuming scalar64_min_max_or will be called so it is safe
6489 * to skip updating register for known case.
6490 */
6491 if (src_known && dst_known)
6492 return;
John Fastabend07cd2632020-03-24 10:38:15 -07006493
6494 /* We get our maximum from the var_off, and our minimum is the
6495 * maximum of the operands' minima
6496 */
John Fastabend3f50f132020-03-30 14:36:39 -07006497 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
6498 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6499 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
6500 /* Lose signed bounds when ORing negative numbers,
6501 * ain't nobody got time for that.
6502 */
6503 dst_reg->s32_min_value = S32_MIN;
6504 dst_reg->s32_max_value = S32_MAX;
6505 } else {
6506 /* ORing two positives gives a positive, so safe to
6507 * cast result into s64.
6508 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02006509 dst_reg->s32_min_value = dst_reg->u32_min_value;
6510 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07006511 }
6512}
6513
6514static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
6515 struct bpf_reg_state *src_reg)
6516{
6517 bool src_known = tnum_is_const(src_reg->var_off);
6518 bool dst_known = tnum_is_const(dst_reg->var_off);
6519 s64 smin_val = src_reg->smin_value;
6520 u64 umin_val = src_reg->umin_value;
6521
6522 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07006523 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07006524 return;
6525 }
6526
6527 /* We get our maximum from the var_off, and our minimum is the
6528 * maximum of the operands' minima
6529 */
John Fastabend07cd2632020-03-24 10:38:15 -07006530 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
6531 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6532 if (dst_reg->smin_value < 0 || smin_val < 0) {
6533 /* Lose signed bounds when ORing negative numbers,
6534 * ain't nobody got time for that.
6535 */
6536 dst_reg->smin_value = S64_MIN;
6537 dst_reg->smax_value = S64_MAX;
6538 } else {
6539 /* ORing two positives gives a positive, so safe to
6540 * cast result into s64.
6541 */
6542 dst_reg->smin_value = dst_reg->umin_value;
6543 dst_reg->smax_value = dst_reg->umax_value;
6544 }
6545 /* We may learn something more from the var_off */
6546 __update_reg_bounds(dst_reg);
6547}
6548
Yonghong Song2921c902020-08-24 23:46:08 -07006549static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
6550 struct bpf_reg_state *src_reg)
6551{
6552 bool src_known = tnum_subreg_is_const(src_reg->var_off);
6553 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
6554 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
6555 s32 smin_val = src_reg->s32_min_value;
6556
6557 /* Assuming scalar64_min_max_xor will be called so it is safe
6558 * to skip updating register for known case.
6559 */
6560 if (src_known && dst_known)
6561 return;
6562
6563 /* We get both minimum and maximum from the var32_off. */
6564 dst_reg->u32_min_value = var32_off.value;
6565 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
6566
6567 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
6568 /* XORing two positive sign numbers gives a positive,
6569 * so safe to cast u32 result into s32.
6570 */
6571 dst_reg->s32_min_value = dst_reg->u32_min_value;
6572 dst_reg->s32_max_value = dst_reg->u32_max_value;
6573 } else {
6574 dst_reg->s32_min_value = S32_MIN;
6575 dst_reg->s32_max_value = S32_MAX;
6576 }
6577}
6578
6579static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
6580 struct bpf_reg_state *src_reg)
6581{
6582 bool src_known = tnum_is_const(src_reg->var_off);
6583 bool dst_known = tnum_is_const(dst_reg->var_off);
6584 s64 smin_val = src_reg->smin_value;
6585
6586 if (src_known && dst_known) {
6587 /* dst_reg->var_off.value has been updated earlier */
6588 __mark_reg_known(dst_reg, dst_reg->var_off.value);
6589 return;
6590 }
6591
6592 /* We get both minimum and maximum from the var_off. */
6593 dst_reg->umin_value = dst_reg->var_off.value;
6594 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
6595
6596 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
6597 /* XORing two positive sign numbers gives a positive,
6598 * so safe to cast u64 result into s64.
6599 */
6600 dst_reg->smin_value = dst_reg->umin_value;
6601 dst_reg->smax_value = dst_reg->umax_value;
6602 } else {
6603 dst_reg->smin_value = S64_MIN;
6604 dst_reg->smax_value = S64_MAX;
6605 }
6606
6607 __update_reg_bounds(dst_reg);
6608}
6609
John Fastabend3f50f132020-03-30 14:36:39 -07006610static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6611 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07006612{
John Fastabend07cd2632020-03-24 10:38:15 -07006613 /* We lose all sign bit information (except what we can pick
6614 * up from var_off)
6615 */
John Fastabend3f50f132020-03-30 14:36:39 -07006616 dst_reg->s32_min_value = S32_MIN;
6617 dst_reg->s32_max_value = S32_MAX;
6618 /* If we might shift our top bit out, then we know nothing */
6619 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
6620 dst_reg->u32_min_value = 0;
6621 dst_reg->u32_max_value = U32_MAX;
6622 } else {
6623 dst_reg->u32_min_value <<= umin_val;
6624 dst_reg->u32_max_value <<= umax_val;
6625 }
6626}
6627
6628static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
6629 struct bpf_reg_state *src_reg)
6630{
6631 u32 umax_val = src_reg->u32_max_value;
6632 u32 umin_val = src_reg->u32_min_value;
6633 /* u32 alu operation will zext upper bits */
6634 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6635
6636 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6637 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
6638 /* Not required but being careful mark reg64 bounds as unknown so
6639 * that we are forced to pick them up from tnum and zext later and
6640 * if some path skips this step we are still safe.
6641 */
6642 __mark_reg64_unbounded(dst_reg);
6643 __update_reg32_bounds(dst_reg);
6644}
6645
6646static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
6647 u64 umin_val, u64 umax_val)
6648{
6649 /* Special case <<32 because it is a common compiler pattern to sign
6650 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
6651 * positive we know this shift will also be positive so we can track
6652 * bounds correctly. Otherwise we lose all sign bit information except
6653 * what we can pick up from var_off. Perhaps we can generalize this
6654 * later to shifts of any length.
6655 */
6656 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
6657 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
6658 else
6659 dst_reg->smax_value = S64_MAX;
6660
6661 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
6662 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
6663 else
6664 dst_reg->smin_value = S64_MIN;
6665
John Fastabend07cd2632020-03-24 10:38:15 -07006666 /* If we might shift our top bit out, then we know nothing */
6667 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
6668 dst_reg->umin_value = 0;
6669 dst_reg->umax_value = U64_MAX;
6670 } else {
6671 dst_reg->umin_value <<= umin_val;
6672 dst_reg->umax_value <<= umax_val;
6673 }
John Fastabend3f50f132020-03-30 14:36:39 -07006674}
6675
6676static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
6677 struct bpf_reg_state *src_reg)
6678{
6679 u64 umax_val = src_reg->umax_value;
6680 u64 umin_val = src_reg->umin_value;
6681
6682 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
6683 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
6684 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
6685
John Fastabend07cd2632020-03-24 10:38:15 -07006686 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
6687 /* We may learn something more from the var_off */
6688 __update_reg_bounds(dst_reg);
6689}
6690
John Fastabend3f50f132020-03-30 14:36:39 -07006691static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
6692 struct bpf_reg_state *src_reg)
6693{
6694 struct tnum subreg = tnum_subreg(dst_reg->var_off);
6695 u32 umax_val = src_reg->u32_max_value;
6696 u32 umin_val = src_reg->u32_min_value;
6697
6698 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6699 * be negative, then either:
6700 * 1) src_reg might be zero, so the sign bit of the result is
6701 * unknown, so we lose our signed bounds
6702 * 2) it's known negative, thus the unsigned bounds capture the
6703 * signed bounds
6704 * 3) the signed bounds cross zero, so they tell us nothing
6705 * about the result
6706 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006707 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07006708 * Thus, in all cases it suffices to blow away our signed bounds
6709 * and rely on inferring new ones from the unsigned bounds and
6710 * var_off of the result.
6711 */
6712 dst_reg->s32_min_value = S32_MIN;
6713 dst_reg->s32_max_value = S32_MAX;
6714
6715 dst_reg->var_off = tnum_rshift(subreg, umin_val);
6716 dst_reg->u32_min_value >>= umax_val;
6717 dst_reg->u32_max_value >>= umin_val;
6718
6719 __mark_reg64_unbounded(dst_reg);
6720 __update_reg32_bounds(dst_reg);
6721}
6722
John Fastabend07cd2632020-03-24 10:38:15 -07006723static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
6724 struct bpf_reg_state *src_reg)
6725{
6726 u64 umax_val = src_reg->umax_value;
6727 u64 umin_val = src_reg->umin_value;
6728
6729 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
6730 * be negative, then either:
6731 * 1) src_reg might be zero, so the sign bit of the result is
6732 * unknown, so we lose our signed bounds
6733 * 2) it's known negative, thus the unsigned bounds capture the
6734 * signed bounds
6735 * 3) the signed bounds cross zero, so they tell us nothing
6736 * about the result
6737 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01006738 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07006739 * Thus, in all cases it suffices to blow away our signed bounds
6740 * and rely on inferring new ones from the unsigned bounds and
6741 * var_off of the result.
6742 */
6743 dst_reg->smin_value = S64_MIN;
6744 dst_reg->smax_value = S64_MAX;
6745 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
6746 dst_reg->umin_value >>= umax_val;
6747 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006748
6749 /* Its not easy to operate on alu32 bounds here because it depends
6750 * on bits being shifted in. Take easy way out and mark unbounded
6751 * so we can recalculate later from tnum.
6752 */
6753 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006754 __update_reg_bounds(dst_reg);
6755}
6756
John Fastabend3f50f132020-03-30 14:36:39 -07006757static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
6758 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07006759{
John Fastabend3f50f132020-03-30 14:36:39 -07006760 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07006761
6762 /* Upon reaching here, src_known is true and
6763 * umax_val is equal to umin_val.
6764 */
John Fastabend3f50f132020-03-30 14:36:39 -07006765 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
6766 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07006767
John Fastabend3f50f132020-03-30 14:36:39 -07006768 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
6769
6770 /* blow away the dst_reg umin_value/umax_value and rely on
6771 * dst_reg var_off to refine the result.
6772 */
6773 dst_reg->u32_min_value = 0;
6774 dst_reg->u32_max_value = U32_MAX;
6775
6776 __mark_reg64_unbounded(dst_reg);
6777 __update_reg32_bounds(dst_reg);
6778}
6779
6780static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
6781 struct bpf_reg_state *src_reg)
6782{
6783 u64 umin_val = src_reg->umin_value;
6784
6785 /* Upon reaching here, src_known is true and umax_val is equal
6786 * to umin_val.
6787 */
6788 dst_reg->smin_value >>= umin_val;
6789 dst_reg->smax_value >>= umin_val;
6790
6791 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07006792
6793 /* blow away the dst_reg umin_value/umax_value and rely on
6794 * dst_reg var_off to refine the result.
6795 */
6796 dst_reg->umin_value = 0;
6797 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07006798
6799 /* Its not easy to operate on alu32 bounds here because it depends
6800 * on bits being shifted in from upper 32-bits. Take easy way out
6801 * and mark unbounded so we can recalculate later from tnum.
6802 */
6803 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006804 __update_reg_bounds(dst_reg);
6805}
6806
Jann Horn468f6ea2017-12-18 20:11:56 -08006807/* WARNING: This function does calculations on 64-bit values, but the actual
6808 * execution may occur on 32-bit values. Therefore, things like bitshifts
6809 * need extra checks in the 32-bit case.
6810 */
Edward Creef1174f72017-08-07 15:26:19 +01006811static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
6812 struct bpf_insn *insn,
6813 struct bpf_reg_state *dst_reg,
6814 struct bpf_reg_state src_reg)
6815{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006816 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01006817 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08006818 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01006819 s64 smin_val, smax_val;
6820 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07006821 s32 s32_min_val, s32_max_val;
6822 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08006823 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006824 u32 dst = insn->dst_reg;
6825 int ret;
John Fastabend3f50f132020-03-30 14:36:39 -07006826 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Jann Hornb7992072018-10-05 18:17:59 +02006827
Edward Creeb03c9f92017-08-07 15:26:36 +01006828 smin_val = src_reg.smin_value;
6829 smax_val = src_reg.smax_value;
6830 umin_val = src_reg.umin_value;
6831 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01006832
John Fastabend3f50f132020-03-30 14:36:39 -07006833 s32_min_val = src_reg.s32_min_value;
6834 s32_max_val = src_reg.s32_max_value;
6835 u32_min_val = src_reg.u32_min_value;
6836 u32_max_val = src_reg.u32_max_value;
6837
6838 if (alu32) {
6839 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006840 if ((src_known &&
6841 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
6842 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
6843 /* Taint dst register if offset had invalid bounds
6844 * derived from e.g. dead branches.
6845 */
6846 __mark_reg_unknown(env, dst_reg);
6847 return 0;
6848 }
6849 } else {
6850 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07006851 if ((src_known &&
6852 (smin_val != smax_val || umin_val != umax_val)) ||
6853 smin_val > smax_val || umin_val > umax_val) {
6854 /* Taint dst register if offset had invalid bounds
6855 * derived from e.g. dead branches.
6856 */
6857 __mark_reg_unknown(env, dst_reg);
6858 return 0;
6859 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01006860 }
6861
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006862 if (!src_known &&
6863 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01006864 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006865 return 0;
6866 }
6867
John Fastabend3f50f132020-03-30 14:36:39 -07006868 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
6869 * There are two classes of instructions: The first class we track both
6870 * alu32 and alu64 sign/unsigned bounds independently this provides the
6871 * greatest amount of precision when alu operations are mixed with jmp32
6872 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
6873 * and BPF_OR. This is possible because these ops have fairly easy to
6874 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
6875 * See alu32 verifier tests for examples. The second class of
6876 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
6877 * with regards to tracking sign/unsigned bounds because the bits may
6878 * cross subreg boundaries in the alu64 case. When this happens we mark
6879 * the reg unbounded in the subreg bound space and use the resulting
6880 * tnum to calculate an approximation of the sign/unsigned bounds.
6881 */
Edward Creef1174f72017-08-07 15:26:19 +01006882 switch (opcode) {
6883 case BPF_ADD:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006884 ret = sanitize_val_alu(env, insn);
6885 if (ret < 0) {
6886 verbose(env, "R%d tried to add from different pointers or scalars\n", dst);
6887 return ret;
6888 }
John Fastabend3f50f132020-03-30 14:36:39 -07006889 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006890 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006891 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01006892 break;
6893 case BPF_SUB:
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006894 ret = sanitize_val_alu(env, insn);
6895 if (ret < 0) {
6896 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst);
6897 return ret;
6898 }
John Fastabend3f50f132020-03-30 14:36:39 -07006899 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006900 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07006901 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04006902 break;
6903 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07006904 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
6905 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006906 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006907 break;
6908 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07006909 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
6910 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006911 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006912 break;
6913 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07006914 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
6915 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07006916 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006917 break;
Yonghong Song2921c902020-08-24 23:46:08 -07006918 case BPF_XOR:
6919 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
6920 scalar32_min_max_xor(dst_reg, &src_reg);
6921 scalar_min_max_xor(dst_reg, &src_reg);
6922 break;
Josef Bacik48461132016-09-28 10:54:32 -04006923 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006924 if (umax_val >= insn_bitness) {
6925 /* Shifts greater than 31 or 63 are undefined.
6926 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006927 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006928 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006929 break;
6930 }
John Fastabend3f50f132020-03-30 14:36:39 -07006931 if (alu32)
6932 scalar32_min_max_lsh(dst_reg, &src_reg);
6933 else
6934 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006935 break;
6936 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08006937 if (umax_val >= insn_bitness) {
6938 /* Shifts greater than 31 or 63 are undefined.
6939 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01006940 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006941 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006942 break;
6943 }
John Fastabend3f50f132020-03-30 14:36:39 -07006944 if (alu32)
6945 scalar32_min_max_rsh(dst_reg, &src_reg);
6946 else
6947 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006948 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006949 case BPF_ARSH:
6950 if (umax_val >= insn_bitness) {
6951 /* Shifts greater than 31 or 63 are undefined.
6952 * This includes shifts by a negative number.
6953 */
6954 mark_reg_unknown(env, regs, insn->dst_reg);
6955 break;
6956 }
John Fastabend3f50f132020-03-30 14:36:39 -07006957 if (alu32)
6958 scalar32_min_max_arsh(dst_reg, &src_reg);
6959 else
6960 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07006961 break;
Josef Bacik48461132016-09-28 10:54:32 -04006962 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006963 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04006964 break;
6965 }
6966
John Fastabend3f50f132020-03-30 14:36:39 -07006967 /* ALU32 ops are zero extended into 64bit register */
6968 if (alu32)
6969 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08006970
John Fastabend294f2fc2020-03-24 10:38:37 -07006971 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01006972 __reg_deduce_bounds(dst_reg);
6973 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01006974 return 0;
6975}
6976
6977/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
6978 * and var_off.
6979 */
6980static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
6981 struct bpf_insn *insn)
6982{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006983 struct bpf_verifier_state *vstate = env->cur_state;
6984 struct bpf_func_state *state = vstate->frame[vstate->curframe];
6985 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01006986 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
6987 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07006988 int err;
Edward Creef1174f72017-08-07 15:26:19 +01006989
6990 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01006991 src_reg = NULL;
6992 if (dst_reg->type != SCALAR_VALUE)
6993 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07006994 else
6995 /* Make sure ID is cleared otherwise dst_reg min/max could be
6996 * incorrectly propagated into other registers by find_equal_scalars()
6997 */
6998 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01006999 if (BPF_SRC(insn->code) == BPF_X) {
7000 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01007001 if (src_reg->type != SCALAR_VALUE) {
7002 if (dst_reg->type != SCALAR_VALUE) {
7003 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007004 * an arbitrary scalar. Disallow all math except
7005 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01007006 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07007007 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007008 mark_reg_unknown(env, regs, insn->dst_reg);
7009 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01007010 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007011 verbose(env, "R%d pointer %s pointer prohibited\n",
7012 insn->dst_reg,
7013 bpf_alu_string[opcode >> 4]);
7014 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01007015 } else {
7016 /* scalar += pointer
7017 * This is legal, but we have to reverse our
7018 * src/dest handling in computing the range
7019 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007020 err = mark_chain_precision(env, insn->dst_reg);
7021 if (err)
7022 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007023 return adjust_ptr_min_max_vals(env, insn,
7024 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007025 }
7026 } else if (ptr_reg) {
7027 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07007028 err = mark_chain_precision(env, insn->src_reg);
7029 if (err)
7030 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007031 return adjust_ptr_min_max_vals(env, insn,
7032 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007033 }
7034 } else {
7035 /* Pretend the src is a reg with a known value, since we only
7036 * need to be able to read from this state.
7037 */
7038 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01007039 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01007040 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007041 if (ptr_reg) /* pointer += K */
7042 return adjust_ptr_min_max_vals(env, insn,
7043 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007044 }
7045
7046 /* Got here implies adding two SCALAR_VALUEs */
7047 if (WARN_ON_ONCE(ptr_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007048 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007049 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007050 return -EINVAL;
7051 }
7052 if (WARN_ON(!src_reg)) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007053 print_verifier_state(env, state);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007054 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01007055 return -EINVAL;
7056 }
7057 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04007058}
7059
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007060/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01007061static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007062{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07007063 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007064 u8 opcode = BPF_OP(insn->code);
7065 int err;
7066
7067 if (opcode == BPF_END || opcode == BPF_NEG) {
7068 if (opcode == BPF_NEG) {
7069 if (BPF_SRC(insn->code) != 0 ||
7070 insn->src_reg != BPF_REG_0 ||
7071 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007072 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007073 return -EINVAL;
7074 }
7075 } else {
7076 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01007077 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
7078 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007079 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007080 return -EINVAL;
7081 }
7082 }
7083
7084 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007085 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007086 if (err)
7087 return err;
7088
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007089 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007090 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007091 insn->dst_reg);
7092 return -EACCES;
7093 }
7094
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007095 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007096 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007097 if (err)
7098 return err;
7099
7100 } else if (opcode == BPF_MOV) {
7101
7102 if (BPF_SRC(insn->code) == BPF_X) {
7103 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007104 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007105 return -EINVAL;
7106 }
7107
7108 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01007109 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007110 if (err)
7111 return err;
7112 } else {
7113 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007114 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007115 return -EINVAL;
7116 }
7117 }
7118
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007119 /* check dest operand, mark as required later */
7120 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007121 if (err)
7122 return err;
7123
7124 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05007125 struct bpf_reg_state *src_reg = regs + insn->src_reg;
7126 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
7127
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007128 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7129 /* case: R1 = R2
7130 * copy register state to dest reg
7131 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07007132 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
7133 /* Assign src and dst registers the same ID
7134 * that will be used by find_equal_scalars()
7135 * to propagate min/max range.
7136 */
7137 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05007138 *dst_reg = *src_reg;
7139 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007140 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007141 } else {
Edward Creef1174f72017-08-07 15:26:19 +01007142 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007143 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007144 verbose(env,
7145 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007146 insn->src_reg);
7147 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05007148 } else if (src_reg->type == SCALAR_VALUE) {
7149 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07007150 /* Make sure ID is cleared otherwise
7151 * dst_reg min/max could be incorrectly
7152 * propagated into src_reg by find_equal_scalars()
7153 */
7154 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05007155 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01007156 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05007157 } else {
7158 mark_reg_unknown(env, regs,
7159 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07007160 }
John Fastabend3f50f132020-03-30 14:36:39 -07007161 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007162 }
7163 } else {
7164 /* case: R = imm
7165 * remember the value we stored into this reg
7166 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01007167 /* clear any state __mark_reg_known doesn't set */
7168 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007169 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08007170 if (BPF_CLASS(insn->code) == BPF_ALU64) {
7171 __mark_reg_known(regs + insn->dst_reg,
7172 insn->imm);
7173 } else {
7174 __mark_reg_known(regs + insn->dst_reg,
7175 (u32)insn->imm);
7176 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007177 }
7178
7179 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007180 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007181 return -EINVAL;
7182
7183 } else { /* all other ALU ops: and, sub, xor, add, ... */
7184
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007185 if (BPF_SRC(insn->code) == BPF_X) {
7186 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007187 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007188 return -EINVAL;
7189 }
7190 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007191 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007192 if (err)
7193 return err;
7194 } else {
7195 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007196 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007197 return -EINVAL;
7198 }
7199 }
7200
7201 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01007202 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007203 if (err)
7204 return err;
7205
7206 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
7207 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007208 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007209 return -EINVAL;
7210 }
7211
Rabin Vincent229394e82016-01-12 20:17:08 +01007212 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
7213 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
7214 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
7215
7216 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07007217 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01007218 return -EINVAL;
7219 }
7220 }
7221
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007222 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01007223 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07007224 if (err)
7225 return err;
7226
Edward Creef1174f72017-08-07 15:26:19 +01007227 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07007228 }
7229
7230 return 0;
7231}
7232
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007233static void __find_good_pkt_pointers(struct bpf_func_state *state,
7234 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007235 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007236{
7237 struct bpf_reg_state *reg;
7238 int i;
7239
7240 for (i = 0; i < MAX_BPF_REG; i++) {
7241 reg = &state->regs[i];
7242 if (reg->type == type && reg->id == dst_reg->id)
7243 /* keep the maximum range already checked */
7244 reg->range = max(reg->range, new_range);
7245 }
7246
7247 bpf_for_each_spilled_reg(i, state, reg) {
7248 if (!reg)
7249 continue;
7250 if (reg->type == type && reg->id == dst_reg->id)
7251 reg->range = max(reg->range, new_range);
7252 }
7253}
7254
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007255static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007256 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01007257 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007258 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007259{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007260 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007261
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007262 if (dst_reg->off < 0 ||
7263 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01007264 /* This doesn't give us any range */
7265 return;
7266
Edward Creeb03c9f92017-08-07 15:26:36 +01007267 if (dst_reg->umax_value > MAX_PACKET_OFF ||
7268 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01007269 /* Risk of overflow. For instance, ptr + (1<<63) may be less
7270 * than pkt_end, but that's because it's also less than pkt.
7271 */
7272 return;
7273
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007274 new_range = dst_reg->off;
7275 if (range_right_open)
7276 new_range--;
7277
7278 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007279 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007280 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007281 *
7282 * r2 = r3;
7283 * r2 += 8;
7284 * if (r2 > pkt_end) goto <handle exception>
7285 * <access okay>
7286 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007287 * r2 = r3;
7288 * r2 += 8;
7289 * if (r2 < pkt_end) goto <access okay>
7290 * <handle exception>
7291 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007292 * Where:
7293 * r2 == dst_reg, pkt_end == src_reg
7294 * r2=pkt(id=n,off=8,r=0)
7295 * r3=pkt(id=n,off=0,r=0)
7296 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007297 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007298 *
7299 * r2 = r3;
7300 * r2 += 8;
7301 * if (pkt_end >= r2) goto <access okay>
7302 * <handle exception>
7303 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007304 * r2 = r3;
7305 * r2 += 8;
7306 * if (pkt_end <= r2) goto <handle exception>
7307 * <access okay>
7308 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007309 * Where:
7310 * pkt_end == dst_reg, r2 == src_reg
7311 * r2=pkt(id=n,off=8,r=0)
7312 * r3=pkt(id=n,off=0,r=0)
7313 *
7314 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02007315 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
7316 * and [r3, r3 + 8-1) respectively is safe to access depending on
7317 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007318 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02007319
Edward Creef1174f72017-08-07 15:26:19 +01007320 /* If our ids match, then we must have the same max_value. And we
7321 * don't care about the other reg's fixed offset, since if it's too big
7322 * the range won't allow anything.
7323 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
7324 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007325 for (i = 0; i <= vstate->curframe; i++)
7326 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
7327 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07007328}
7329
John Fastabend3f50f132020-03-30 14:36:39 -07007330static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007331{
John Fastabend3f50f132020-03-30 14:36:39 -07007332 struct tnum subreg = tnum_subreg(reg->var_off);
7333 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007334
John Fastabend3f50f132020-03-30 14:36:39 -07007335 switch (opcode) {
7336 case BPF_JEQ:
7337 if (tnum_is_const(subreg))
7338 return !!tnum_equals_const(subreg, val);
7339 break;
7340 case BPF_JNE:
7341 if (tnum_is_const(subreg))
7342 return !tnum_equals_const(subreg, val);
7343 break;
7344 case BPF_JSET:
7345 if ((~subreg.mask & subreg.value) & val)
7346 return 1;
7347 if (!((subreg.mask | subreg.value) & val))
7348 return 0;
7349 break;
7350 case BPF_JGT:
7351 if (reg->u32_min_value > val)
7352 return 1;
7353 else if (reg->u32_max_value <= val)
7354 return 0;
7355 break;
7356 case BPF_JSGT:
7357 if (reg->s32_min_value > sval)
7358 return 1;
7359 else if (reg->s32_max_value < sval)
7360 return 0;
7361 break;
7362 case BPF_JLT:
7363 if (reg->u32_max_value < val)
7364 return 1;
7365 else if (reg->u32_min_value >= val)
7366 return 0;
7367 break;
7368 case BPF_JSLT:
7369 if (reg->s32_max_value < sval)
7370 return 1;
7371 else if (reg->s32_min_value >= sval)
7372 return 0;
7373 break;
7374 case BPF_JGE:
7375 if (reg->u32_min_value >= val)
7376 return 1;
7377 else if (reg->u32_max_value < val)
7378 return 0;
7379 break;
7380 case BPF_JSGE:
7381 if (reg->s32_min_value >= sval)
7382 return 1;
7383 else if (reg->s32_max_value < sval)
7384 return 0;
7385 break;
7386 case BPF_JLE:
7387 if (reg->u32_max_value <= val)
7388 return 1;
7389 else if (reg->u32_min_value > val)
7390 return 0;
7391 break;
7392 case BPF_JSLE:
7393 if (reg->s32_max_value <= sval)
7394 return 1;
7395 else if (reg->s32_min_value > sval)
7396 return 0;
7397 break;
Jiong Wang092ed092019-01-26 12:26:01 -05007398 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05007399
John Fastabend3f50f132020-03-30 14:36:39 -07007400 return -1;
7401}
7402
7403
7404static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
7405{
7406 s64 sval = (s64)val;
7407
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007408 switch (opcode) {
7409 case BPF_JEQ:
7410 if (tnum_is_const(reg->var_off))
7411 return !!tnum_equals_const(reg->var_off, val);
7412 break;
7413 case BPF_JNE:
7414 if (tnum_is_const(reg->var_off))
7415 return !tnum_equals_const(reg->var_off, val);
7416 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08007417 case BPF_JSET:
7418 if ((~reg->var_off.mask & reg->var_off.value) & val)
7419 return 1;
7420 if (!((reg->var_off.mask | reg->var_off.value) & val))
7421 return 0;
7422 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007423 case BPF_JGT:
7424 if (reg->umin_value > val)
7425 return 1;
7426 else if (reg->umax_value <= val)
7427 return 0;
7428 break;
7429 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007430 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007431 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007432 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007433 return 0;
7434 break;
7435 case BPF_JLT:
7436 if (reg->umax_value < val)
7437 return 1;
7438 else if (reg->umin_value >= val)
7439 return 0;
7440 break;
7441 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007442 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007443 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007444 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007445 return 0;
7446 break;
7447 case BPF_JGE:
7448 if (reg->umin_value >= val)
7449 return 1;
7450 else if (reg->umax_value < val)
7451 return 0;
7452 break;
7453 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007454 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007455 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007456 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007457 return 0;
7458 break;
7459 case BPF_JLE:
7460 if (reg->umax_value <= val)
7461 return 1;
7462 else if (reg->umin_value > val)
7463 return 0;
7464 break;
7465 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007466 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007467 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007468 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08007469 return 0;
7470 break;
7471 }
7472
7473 return -1;
7474}
7475
John Fastabend3f50f132020-03-30 14:36:39 -07007476/* compute branch direction of the expression "if (reg opcode val) goto target;"
7477 * and return:
7478 * 1 - branch will be taken and "goto target" will be executed
7479 * 0 - branch will not be taken and fall-through to next insn
7480 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
7481 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05007482 */
John Fastabend3f50f132020-03-30 14:36:39 -07007483static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
7484 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05007485{
John Fastabendcac616d2020-05-21 13:07:26 -07007486 if (__is_pointer_value(false, reg)) {
7487 if (!reg_type_not_null(reg->type))
7488 return -1;
7489
7490 /* If pointer is valid tests against zero will fail so we can
7491 * use this to direct branch taken.
7492 */
7493 if (val != 0)
7494 return -1;
7495
7496 switch (opcode) {
7497 case BPF_JEQ:
7498 return 0;
7499 case BPF_JNE:
7500 return 1;
7501 default:
7502 return -1;
7503 }
7504 }
Jiong Wang092ed092019-01-26 12:26:01 -05007505
John Fastabend3f50f132020-03-30 14:36:39 -07007506 if (is_jmp32)
7507 return is_branch32_taken(reg, val, opcode);
7508 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02007509}
7510
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007511static int flip_opcode(u32 opcode)
7512{
7513 /* How can we transform "a <op> b" into "b <op> a"? */
7514 static const u8 opcode_flip[16] = {
7515 /* these stay the same */
7516 [BPF_JEQ >> 4] = BPF_JEQ,
7517 [BPF_JNE >> 4] = BPF_JNE,
7518 [BPF_JSET >> 4] = BPF_JSET,
7519 /* these swap "lesser" and "greater" (L and G in the opcodes) */
7520 [BPF_JGE >> 4] = BPF_JLE,
7521 [BPF_JGT >> 4] = BPF_JLT,
7522 [BPF_JLE >> 4] = BPF_JGE,
7523 [BPF_JLT >> 4] = BPF_JGT,
7524 [BPF_JSGE >> 4] = BPF_JSLE,
7525 [BPF_JSGT >> 4] = BPF_JSLT,
7526 [BPF_JSLE >> 4] = BPF_JSGE,
7527 [BPF_JSLT >> 4] = BPF_JSGT
7528 };
7529 return opcode_flip[opcode >> 4];
7530}
7531
7532static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
7533 struct bpf_reg_state *src_reg,
7534 u8 opcode)
7535{
7536 struct bpf_reg_state *pkt;
7537
7538 if (src_reg->type == PTR_TO_PACKET_END) {
7539 pkt = dst_reg;
7540 } else if (dst_reg->type == PTR_TO_PACKET_END) {
7541 pkt = src_reg;
7542 opcode = flip_opcode(opcode);
7543 } else {
7544 return -1;
7545 }
7546
7547 if (pkt->range >= 0)
7548 return -1;
7549
7550 switch (opcode) {
7551 case BPF_JLE:
7552 /* pkt <= pkt_end */
7553 fallthrough;
7554 case BPF_JGT:
7555 /* pkt > pkt_end */
7556 if (pkt->range == BEYOND_PKT_END)
7557 /* pkt has at last one extra byte beyond pkt_end */
7558 return opcode == BPF_JGT;
7559 break;
7560 case BPF_JLT:
7561 /* pkt < pkt_end */
7562 fallthrough;
7563 case BPF_JGE:
7564 /* pkt >= pkt_end */
7565 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
7566 return opcode == BPF_JGE;
7567 break;
7568 }
7569 return -1;
7570}
7571
Josef Bacik48461132016-09-28 10:54:32 -04007572/* Adjusts the register min/max values in the case that the dst_reg is the
7573 * variable register that we are working on, and src_reg is a constant or we're
7574 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01007575 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04007576 */
7577static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007578 struct bpf_reg_state *false_reg,
7579 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007580 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007581{
John Fastabend3f50f132020-03-30 14:36:39 -07007582 struct tnum false_32off = tnum_subreg(false_reg->var_off);
7583 struct tnum false_64off = false_reg->var_off;
7584 struct tnum true_32off = tnum_subreg(true_reg->var_off);
7585 struct tnum true_64off = true_reg->var_off;
7586 s64 sval = (s64)val;
7587 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007588
Edward Creef1174f72017-08-07 15:26:19 +01007589 /* If the dst_reg is a pointer, we can't learn anything about its
7590 * variable offset from the compare (unless src_reg were a pointer into
7591 * the same object, but we don't bother with that.
7592 * Since false_reg and true_reg have the same type by construction, we
7593 * only need to check one of them for pointerness.
7594 */
7595 if (__is_pointer_value(false, false_reg))
7596 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007597
Josef Bacik48461132016-09-28 10:54:32 -04007598 switch (opcode) {
7599 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04007600 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007601 {
7602 struct bpf_reg_state *reg =
7603 opcode == BPF_JEQ ? true_reg : false_reg;
7604
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007605 /* JEQ/JNE comparison doesn't change the register equivalence.
7606 * r1 = r2;
7607 * if (r1 == 42) goto label;
7608 * ...
7609 * label: // here both r1 and r2 are known to be 42.
7610 *
7611 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04007612 */
John Fastabend3f50f132020-03-30 14:36:39 -07007613 if (is_jmp32)
7614 __mark_reg32_known(reg, val32);
7615 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07007616 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04007617 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007618 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007619 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07007620 if (is_jmp32) {
7621 false_32off = tnum_and(false_32off, tnum_const(~val32));
7622 if (is_power_of_2(val32))
7623 true_32off = tnum_or(true_32off,
7624 tnum_const(val32));
7625 } else {
7626 false_64off = tnum_and(false_64off, tnum_const(~val));
7627 if (is_power_of_2(val))
7628 true_64off = tnum_or(true_64off,
7629 tnum_const(val));
7630 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08007631 break;
Josef Bacik48461132016-09-28 10:54:32 -04007632 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007633 case BPF_JGT:
7634 {
John Fastabend3f50f132020-03-30 14:36:39 -07007635 if (is_jmp32) {
7636 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
7637 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
7638
7639 false_reg->u32_max_value = min(false_reg->u32_max_value,
7640 false_umax);
7641 true_reg->u32_min_value = max(true_reg->u32_min_value,
7642 true_umin);
7643 } else {
7644 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
7645 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
7646
7647 false_reg->umax_value = min(false_reg->umax_value, false_umax);
7648 true_reg->umin_value = max(true_reg->umin_value, true_umin);
7649 }
Edward Creeb03c9f92017-08-07 15:26:36 +01007650 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007651 }
Josef Bacik48461132016-09-28 10:54:32 -04007652 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007653 case BPF_JSGT:
7654 {
John Fastabend3f50f132020-03-30 14:36:39 -07007655 if (is_jmp32) {
7656 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
7657 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007658
John Fastabend3f50f132020-03-30 14:36:39 -07007659 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
7660 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
7661 } else {
7662 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
7663 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
7664
7665 false_reg->smax_value = min(false_reg->smax_value, false_smax);
7666 true_reg->smin_value = max(true_reg->smin_value, true_smin);
7667 }
Josef Bacik48461132016-09-28 10:54:32 -04007668 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007669 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007670 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007671 case BPF_JLT:
7672 {
John Fastabend3f50f132020-03-30 14:36:39 -07007673 if (is_jmp32) {
7674 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
7675 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
7676
7677 false_reg->u32_min_value = max(false_reg->u32_min_value,
7678 false_umin);
7679 true_reg->u32_max_value = min(true_reg->u32_max_value,
7680 true_umax);
7681 } else {
7682 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
7683 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
7684
7685 false_reg->umin_value = max(false_reg->umin_value, false_umin);
7686 true_reg->umax_value = min(true_reg->umax_value, true_umax);
7687 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007688 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007689 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007690 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05007691 case BPF_JSLT:
7692 {
John Fastabend3f50f132020-03-30 14:36:39 -07007693 if (is_jmp32) {
7694 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
7695 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007696
John Fastabend3f50f132020-03-30 14:36:39 -07007697 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
7698 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
7699 } else {
7700 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
7701 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
7702
7703 false_reg->smin_value = max(false_reg->smin_value, false_smin);
7704 true_reg->smax_value = min(true_reg->smax_value, true_smax);
7705 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02007706 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05007707 }
Josef Bacik48461132016-09-28 10:54:32 -04007708 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02007709 return;
Josef Bacik48461132016-09-28 10:54:32 -04007710 }
7711
John Fastabend3f50f132020-03-30 14:36:39 -07007712 if (is_jmp32) {
7713 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
7714 tnum_subreg(false_32off));
7715 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
7716 tnum_subreg(true_32off));
7717 __reg_combine_32_into_64(false_reg);
7718 __reg_combine_32_into_64(true_reg);
7719 } else {
7720 false_reg->var_off = false_64off;
7721 true_reg->var_off = true_64off;
7722 __reg_combine_64_into_32(false_reg);
7723 __reg_combine_64_into_32(true_reg);
7724 }
Josef Bacik48461132016-09-28 10:54:32 -04007725}
7726
Edward Creef1174f72017-08-07 15:26:19 +01007727/* Same as above, but for the case that dst_reg holds a constant and src_reg is
7728 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04007729 */
7730static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07007731 struct bpf_reg_state *false_reg,
7732 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05007733 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04007734{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007735 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02007736 /* This uses zero as "not present in table"; luckily the zero opcode,
7737 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01007738 */
Jann Horn0fc31b12020-03-30 18:03:24 +02007739 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07007740 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01007741}
7742
7743/* Regs are known to be equal, so intersect their min/max/var_off */
7744static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
7745 struct bpf_reg_state *dst_reg)
7746{
Edward Creeb03c9f92017-08-07 15:26:36 +01007747 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
7748 dst_reg->umin_value);
7749 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
7750 dst_reg->umax_value);
7751 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
7752 dst_reg->smin_value);
7753 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
7754 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01007755 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
7756 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007757 /* We might have learned new bounds from the var_off. */
7758 __update_reg_bounds(src_reg);
7759 __update_reg_bounds(dst_reg);
7760 /* We might have learned something about the sign bit. */
7761 __reg_deduce_bounds(src_reg);
7762 __reg_deduce_bounds(dst_reg);
7763 /* We might have learned some bits from the bounds. */
7764 __reg_bound_offset(src_reg);
7765 __reg_bound_offset(dst_reg);
7766 /* Intersecting with the old var_off might have improved our bounds
7767 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
7768 * then new var_off is (0; 0x7f...fc) which improves our umax.
7769 */
7770 __update_reg_bounds(src_reg);
7771 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01007772}
7773
7774static void reg_combine_min_max(struct bpf_reg_state *true_src,
7775 struct bpf_reg_state *true_dst,
7776 struct bpf_reg_state *false_src,
7777 struct bpf_reg_state *false_dst,
7778 u8 opcode)
7779{
7780 switch (opcode) {
7781 case BPF_JEQ:
7782 __reg_combine_min_max(true_src, true_dst);
7783 break;
7784 case BPF_JNE:
7785 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01007786 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02007787 }
Josef Bacik48461132016-09-28 10:54:32 -04007788}
7789
Joe Stringerfd978bf72018-10-02 13:35:35 -07007790static void mark_ptr_or_null_reg(struct bpf_func_state *state,
7791 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07007792 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007793{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07007794 if (reg_type_may_be_null(reg->type) && reg->id == id &&
7795 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01007796 /* Old offset (both fixed and variable parts) should
7797 * have been known-zero, because we don't allow pointer
7798 * arithmetic on pointers that might be NULL.
7799 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007800 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
7801 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01007802 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01007803 __mark_reg_known_zero(reg);
7804 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01007805 }
7806 if (is_null) {
7807 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007808 /* We don't need id and ref_obj_id from this point
7809 * onwards anymore, thus we should better reset it,
7810 * so that state pruning has chances to take effect.
7811 */
7812 reg->id = 0;
7813 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04007814
7815 return;
7816 }
7817
7818 mark_ptr_not_null_reg(reg);
7819
7820 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007821 /* For not-NULL ptr, reg->ref_obj_id will be reset
7822 * in release_reg_references().
7823 *
7824 * reg->id is still used by spin_lock ptr. Other
7825 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07007826 */
7827 reg->id = 0;
7828 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02007829 }
7830}
7831
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007832static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
7833 bool is_null)
7834{
7835 struct bpf_reg_state *reg;
7836 int i;
7837
7838 for (i = 0; i < MAX_BPF_REG; i++)
7839 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
7840
7841 bpf_for_each_spilled_reg(i, state, reg) {
7842 if (!reg)
7843 continue;
7844 mark_ptr_or_null_reg(state, reg, id, is_null);
7845 }
7846}
7847
Thomas Graf57a09bf2016-10-18 19:51:19 +02007848/* The logic is similar to find_good_pkt_pointers(), both could eventually
7849 * be folded together at some point.
7850 */
Joe Stringer840b9612018-10-02 13:35:32 -07007851static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
7852 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02007853{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007854 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007855 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007856 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01007857 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007858 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02007859
Martin KaFai Lau1b986582019-03-12 10:23:02 -07007860 if (ref_obj_id && ref_obj_id == id && is_null)
7861 /* regs[regno] is in the " == NULL" branch.
7862 * No one could have freed the reference state before
7863 * doing the NULL check.
7864 */
7865 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07007866
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02007867 for (i = 0; i <= vstate->curframe; i++)
7868 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02007869}
7870
Daniel Borkmann5beca082017-11-01 23:58:10 +01007871static bool try_match_pkt_pointers(const struct bpf_insn *insn,
7872 struct bpf_reg_state *dst_reg,
7873 struct bpf_reg_state *src_reg,
7874 struct bpf_verifier_state *this_branch,
7875 struct bpf_verifier_state *other_branch)
7876{
7877 if (BPF_SRC(insn->code) != BPF_X)
7878 return false;
7879
Jiong Wang092ed092019-01-26 12:26:01 -05007880 /* Pointers are always 64-bit. */
7881 if (BPF_CLASS(insn->code) == BPF_JMP32)
7882 return false;
7883
Daniel Borkmann5beca082017-11-01 23:58:10 +01007884 switch (BPF_OP(insn->code)) {
7885 case BPF_JGT:
7886 if ((dst_reg->type == PTR_TO_PACKET &&
7887 src_reg->type == PTR_TO_PACKET_END) ||
7888 (dst_reg->type == PTR_TO_PACKET_META &&
7889 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7890 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
7891 find_good_pkt_pointers(this_branch, dst_reg,
7892 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007893 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007894 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7895 src_reg->type == PTR_TO_PACKET) ||
7896 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7897 src_reg->type == PTR_TO_PACKET_META)) {
7898 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
7899 find_good_pkt_pointers(other_branch, src_reg,
7900 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007901 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007902 } else {
7903 return false;
7904 }
7905 break;
7906 case BPF_JLT:
7907 if ((dst_reg->type == PTR_TO_PACKET &&
7908 src_reg->type == PTR_TO_PACKET_END) ||
7909 (dst_reg->type == PTR_TO_PACKET_META &&
7910 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7911 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
7912 find_good_pkt_pointers(other_branch, dst_reg,
7913 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007914 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007915 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7916 src_reg->type == PTR_TO_PACKET) ||
7917 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7918 src_reg->type == PTR_TO_PACKET_META)) {
7919 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
7920 find_good_pkt_pointers(this_branch, src_reg,
7921 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007922 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007923 } else {
7924 return false;
7925 }
7926 break;
7927 case BPF_JGE:
7928 if ((dst_reg->type == PTR_TO_PACKET &&
7929 src_reg->type == PTR_TO_PACKET_END) ||
7930 (dst_reg->type == PTR_TO_PACKET_META &&
7931 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7932 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
7933 find_good_pkt_pointers(this_branch, dst_reg,
7934 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007935 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007936 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7937 src_reg->type == PTR_TO_PACKET) ||
7938 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7939 src_reg->type == PTR_TO_PACKET_META)) {
7940 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
7941 find_good_pkt_pointers(other_branch, src_reg,
7942 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007943 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007944 } else {
7945 return false;
7946 }
7947 break;
7948 case BPF_JLE:
7949 if ((dst_reg->type == PTR_TO_PACKET &&
7950 src_reg->type == PTR_TO_PACKET_END) ||
7951 (dst_reg->type == PTR_TO_PACKET_META &&
7952 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
7953 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
7954 find_good_pkt_pointers(other_branch, dst_reg,
7955 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007956 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007957 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
7958 src_reg->type == PTR_TO_PACKET) ||
7959 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
7960 src_reg->type == PTR_TO_PACKET_META)) {
7961 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
7962 find_good_pkt_pointers(this_branch, src_reg,
7963 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08007964 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01007965 } else {
7966 return false;
7967 }
7968 break;
7969 default:
7970 return false;
7971 }
7972
7973 return true;
7974}
7975
Alexei Starovoitov75748832020-10-08 18:12:37 -07007976static void find_equal_scalars(struct bpf_verifier_state *vstate,
7977 struct bpf_reg_state *known_reg)
7978{
7979 struct bpf_func_state *state;
7980 struct bpf_reg_state *reg;
7981 int i, j;
7982
7983 for (i = 0; i <= vstate->curframe; i++) {
7984 state = vstate->frame[i];
7985 for (j = 0; j < MAX_BPF_REG; j++) {
7986 reg = &state->regs[j];
7987 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7988 *reg = *known_reg;
7989 }
7990
7991 bpf_for_each_spilled_reg(j, state, reg) {
7992 if (!reg)
7993 continue;
7994 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
7995 *reg = *known_reg;
7996 }
7997 }
7998}
7999
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008000static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008001 struct bpf_insn *insn, int *insn_idx)
8002{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008003 struct bpf_verifier_state *this_branch = env->cur_state;
8004 struct bpf_verifier_state *other_branch;
8005 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008006 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008007 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05008008 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008009 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008010 int err;
8011
Jiong Wang092ed092019-01-26 12:26:01 -05008012 /* Only conditional jumps are expected to reach here. */
8013 if (opcode == BPF_JA || opcode > BPF_JSLE) {
8014 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008015 return -EINVAL;
8016 }
8017
8018 if (BPF_SRC(insn->code) == BPF_X) {
8019 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008020 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008021 return -EINVAL;
8022 }
8023
8024 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008025 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008026 if (err)
8027 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008028
8029 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008030 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008031 insn->src_reg);
8032 return -EACCES;
8033 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008034 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008035 } else {
8036 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05008037 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008038 return -EINVAL;
8039 }
8040 }
8041
8042 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008043 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008044 if (err)
8045 return err;
8046
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008047 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008048 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008049
John Fastabend3f50f132020-03-30 14:36:39 -07008050 if (BPF_SRC(insn->code) == BPF_K) {
8051 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
8052 } else if (src_reg->type == SCALAR_VALUE &&
8053 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
8054 pred = is_branch_taken(dst_reg,
8055 tnum_subreg(src_reg->var_off).value,
8056 opcode,
8057 is_jmp32);
8058 } else if (src_reg->type == SCALAR_VALUE &&
8059 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
8060 pred = is_branch_taken(dst_reg,
8061 src_reg->var_off.value,
8062 opcode,
8063 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008064 } else if (reg_is_pkt_pointer_any(dst_reg) &&
8065 reg_is_pkt_pointer_any(src_reg) &&
8066 !is_jmp32) {
8067 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07008068 }
8069
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008070 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07008071 /* If we get here with a dst_reg pointer type it is because
8072 * above is_branch_taken() special cased the 0 comparison.
8073 */
8074 if (!__is_pointer_value(false, dst_reg))
8075 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008076 if (BPF_SRC(insn->code) == BPF_X && !err &&
8077 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008078 err = mark_chain_precision(env, insn->src_reg);
8079 if (err)
8080 return err;
8081 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07008082 if (pred == 1) {
8083 /* only follow the goto, ignore fall-through */
8084 *insn_idx += insn->off;
8085 return 0;
8086 } else if (pred == 0) {
8087 /* only follow fall-through branch, since
8088 * that's where the program will go
8089 */
8090 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008091 }
8092
Daniel Borkmann979d63d2019-01-03 00:58:34 +01008093 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
8094 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008095 if (!other_branch)
8096 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008097 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008098
Josef Bacik48461132016-09-28 10:54:32 -04008099 /* detect if we are comparing against a constant value so we can adjust
8100 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01008101 * this is only legit if both are scalars (or pointers to the same
8102 * object, I suppose, but we don't support that right now), because
8103 * otherwise the different base pointers mean the offsets aren't
8104 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04008105 */
8106 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05008107 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05008108
Edward Creef1174f72017-08-07 15:26:19 +01008109 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05008110 src_reg->type == SCALAR_VALUE) {
8111 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008112 (is_jmp32 &&
8113 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008114 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008115 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008116 src_reg->var_off.value,
8117 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008118 opcode, is_jmp32);
8119 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07008120 (is_jmp32 &&
8121 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008122 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008123 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008124 dst_reg->var_off.value,
8125 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05008126 opcode, is_jmp32);
8127 else if (!is_jmp32 &&
8128 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01008129 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008130 reg_combine_min_max(&other_branch_regs[insn->src_reg],
8131 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05008132 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008133 if (src_reg->id &&
8134 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008135 find_equal_scalars(this_branch, src_reg);
8136 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
8137 }
8138
Edward Creef1174f72017-08-07 15:26:19 +01008139 }
8140 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008141 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07008142 dst_reg, insn->imm, (u32)insn->imm,
8143 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04008144 }
8145
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008146 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
8147 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07008148 find_equal_scalars(this_branch, dst_reg);
8149 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
8150 }
8151
Jiong Wang092ed092019-01-26 12:26:01 -05008152 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
8153 * NOTE: these optimizations below are related with pointer comparison
8154 * which will never be JMP32.
8155 */
8156 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008157 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07008158 reg_type_may_be_null(dst_reg->type)) {
8159 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02008160 * safe or unknown depending R == 0 or R != 0 conditional.
8161 */
Joe Stringer840b9612018-10-02 13:35:32 -07008162 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
8163 opcode == BPF_JNE);
8164 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
8165 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01008166 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
8167 this_branch, other_branch) &&
8168 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008169 verbose(env, "R%d pointer comparison prohibited\n",
8170 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008171 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008172 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07008173 if (env->log.level & BPF_LOG_LEVEL)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008174 print_verifier_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008175 return 0;
8176}
8177
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008178/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008179static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008180{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008181 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008182 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07008183 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008184 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008185 int err;
8186
8187 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008188 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008189 return -EINVAL;
8190 }
8191 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008192 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008193 return -EINVAL;
8194 }
8195
Edward Creedc503a82017-08-15 20:34:35 +01008196 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008197 if (err)
8198 return err;
8199
Hao Luo4976b712020-09-29 16:50:44 -07008200 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01008201 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01008202 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
8203
Hao Luo4976b712020-09-29 16:50:44 -07008204 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008205 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008206 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01008207 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008208
Hao Luo4976b712020-09-29 16:50:44 -07008209 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
8210 mark_reg_known_zero(env, regs, insn->dst_reg);
8211
8212 dst_reg->type = aux->btf_var.reg_type;
8213 switch (dst_reg->type) {
8214 case PTR_TO_MEM:
8215 dst_reg->mem_size = aux->btf_var.mem_size;
8216 break;
8217 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07008218 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08008219 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07008220 dst_reg->btf_id = aux->btf_var.btf_id;
8221 break;
8222 default:
8223 verbose(env, "bpf verifier is misconfigured\n");
8224 return -EFAULT;
8225 }
8226 return 0;
8227 }
8228
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008229 map = env->used_maps[aux->map_index];
8230 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07008231 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008232
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008233 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07008234 dst_reg->type = PTR_TO_MAP_VALUE;
8235 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008236 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07008237 dst_reg->id = ++env->id_gen;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008238 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
Hao Luo4976b712020-09-29 16:50:44 -07008239 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02008240 } else {
8241 verbose(env, "bpf verifier is misconfigured\n");
8242 return -EINVAL;
8243 }
8244
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008245 return 0;
8246}
8247
Daniel Borkmann96be4322015-03-01 12:31:46 +01008248static bool may_access_skb(enum bpf_prog_type type)
8249{
8250 switch (type) {
8251 case BPF_PROG_TYPE_SOCKET_FILTER:
8252 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01008253 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01008254 return true;
8255 default:
8256 return false;
8257 }
8258}
8259
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008260/* verify safety of LD_ABS|LD_IND instructions:
8261 * - they can only appear in the programs where ctx == skb
8262 * - since they are wrappers of function calls, they scratch R1-R5 registers,
8263 * preserve R6-R9, and store return value into R0
8264 *
8265 * Implicit input:
8266 * ctx == skb == R6 == CTX
8267 *
8268 * Explicit input:
8269 * SRC == any register
8270 * IMM == 32-bit immediate
8271 *
8272 * Output:
8273 * R0 - 8/16/32-bit skb data converted to cpu endianness
8274 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008275static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008276{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008277 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008278 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008279 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008280 int i, err;
8281
Udip Pant7e407812020-08-25 16:20:00 -07008282 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008283 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008284 return -EINVAL;
8285 }
8286
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02008287 if (!env->ops->gen_ld_abs) {
8288 verbose(env, "bpf verifier is misconfigured\n");
8289 return -EINVAL;
8290 }
8291
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008292 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07008293 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008294 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008295 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008296 return -EINVAL;
8297 }
8298
8299 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008300 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008301 if (err)
8302 return err;
8303
Joe Stringerfd978bf72018-10-02 13:35:35 -07008304 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
8305 * gen_ld_abs() may terminate the program at runtime, leading to
8306 * reference leak.
8307 */
8308 err = check_reference_leak(env);
8309 if (err) {
8310 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
8311 return err;
8312 }
8313
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08008314 if (env->cur_state->active_spin_lock) {
8315 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
8316 return -EINVAL;
8317 }
8318
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008319 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008320 verbose(env,
8321 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008322 return -EINVAL;
8323 }
8324
8325 if (mode == BPF_IND) {
8326 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01008327 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008328 if (err)
8329 return err;
8330 }
8331
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01008332 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
8333 if (err < 0)
8334 return err;
8335
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008336 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01008337 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008338 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01008339 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8340 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008341
8342 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01008343 * the value fetched from the packet.
8344 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008345 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008346 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01008347 /* ld_abs load up to 32-bit skb data. */
8348 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08008349 return 0;
8350}
8351
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008352static int check_return_code(struct bpf_verifier_env *env)
8353{
brakmo5cf1e912019-05-28 16:59:36 -07008354 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008355 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008356 struct bpf_reg_state *reg;
8357 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07008358 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008359 int err;
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008360 const bool is_subprog = env->cur_state->frame[0]->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008361
KP Singh9e4e01d2020-03-29 01:43:52 +01008362 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008363 if (!is_subprog &&
8364 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07008365 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08008366 !prog->aux->attach_func_proto->type)
8367 return 0;
8368
8369 /* eBPF calling convetion is such that R0 is used
8370 * to return the value from eBPF program.
8371 * Make sure that it's readable at this time
8372 * of bpf_exit, which means that program wrote
8373 * something into it earlier
8374 */
8375 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
8376 if (err)
8377 return err;
8378
8379 if (is_pointer_value(env, BPF_REG_0)) {
8380 verbose(env, "R0 leaks addr as return value\n");
8381 return -EACCES;
8382 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008383
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00008384 reg = cur_regs(env) + BPF_REG_0;
8385 if (is_subprog) {
8386 if (reg->type != SCALAR_VALUE) {
8387 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
8388 reg_type_str[reg->type]);
8389 return -EINVAL;
8390 }
8391 return 0;
8392 }
8393
Udip Pant7e407812020-08-25 16:20:00 -07008394 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02008395 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8396 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02008397 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
8398 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
8399 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
8400 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
8401 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02008402 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08008403 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
8404 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
8405 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008406 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008407 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07008408 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
8409 range = tnum_range(0, 3);
8410 enforce_attach_type_range = tnum_range(2, 3);
8411 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05008412 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008413 case BPF_PROG_TYPE_CGROUP_SOCK:
8414 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05008415 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08008416 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07008417 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008418 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07008419 case BPF_PROG_TYPE_RAW_TRACEPOINT:
8420 if (!env->prog->aux->attach_btf_id)
8421 return 0;
8422 range = tnum_const(0);
8423 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07008424 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07008425 switch (env->prog->expected_attach_type) {
8426 case BPF_TRACE_FENTRY:
8427 case BPF_TRACE_FEXIT:
8428 range = tnum_const(0);
8429 break;
8430 case BPF_TRACE_RAW_TP:
8431 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07008432 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02008433 case BPF_TRACE_ITER:
8434 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008435 default:
8436 return -ENOTSUPP;
8437 }
Yonghong Song15d83c42020-05-09 10:59:00 -07008438 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02008439 case BPF_PROG_TYPE_SK_LOOKUP:
8440 range = tnum_range(SK_DROP, SK_PASS);
8441 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07008442 case BPF_PROG_TYPE_EXT:
8443 /* freplace program can return anything as its return value
8444 * depends on the to-be-replaced kernel func or bpf program.
8445 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008446 default:
8447 return 0;
8448 }
8449
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008450 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008451 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008452 reg_type_str[reg->type]);
8453 return -EINVAL;
8454 }
8455
8456 if (!tnum_in(range, reg->var_off)) {
brakmo5cf1e912019-05-28 16:59:36 -07008457 char tn_buf[48];
8458
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008459 verbose(env, "At program exit the register R0 ");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008460 if (!tnum_is_unknown(reg->var_off)) {
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008461 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008462 verbose(env, "has value %s", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008463 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008464 verbose(env, "has unknown scalar value");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008465 }
brakmo5cf1e912019-05-28 16:59:36 -07008466 tnum_strn(tn_buf, sizeof(tn_buf), range);
Daniel Borkmann983695f2019-06-07 01:48:57 +02008467 verbose(env, " should have been in %s\n", tn_buf);
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008468 return -EINVAL;
8469 }
brakmo5cf1e912019-05-28 16:59:36 -07008470
8471 if (!tnum_is_unknown(enforce_attach_type_range) &&
8472 tnum_in(enforce_attach_type_range, reg->var_off))
8473 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07008474 return 0;
8475}
8476
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008477/* non-recursive DFS pseudo code
8478 * 1 procedure DFS-iterative(G,v):
8479 * 2 label v as discovered
8480 * 3 let S be a stack
8481 * 4 S.push(v)
8482 * 5 while S is not empty
8483 * 6 t <- S.pop()
8484 * 7 if t is what we're looking for:
8485 * 8 return t
8486 * 9 for all edges e in G.adjacentEdges(t) do
8487 * 10 if edge e is already labelled
8488 * 11 continue with the next edge
8489 * 12 w <- G.adjacentVertex(t,e)
8490 * 13 if vertex w is not discovered and not explored
8491 * 14 label e as tree-edge
8492 * 15 label w as discovered
8493 * 16 S.push(w)
8494 * 17 continue at 5
8495 * 18 else if vertex w is discovered
8496 * 19 label e as back-edge
8497 * 20 else
8498 * 21 // vertex w is explored
8499 * 22 label e as forward- or cross-edge
8500 * 23 label t as explored
8501 * 24 S.pop()
8502 *
8503 * convention:
8504 * 0x10 - discovered
8505 * 0x11 - discovered and fall-through edge labelled
8506 * 0x12 - discovered and fall-through and branch edges labelled
8507 * 0x20 - explored
8508 */
8509
8510enum {
8511 DISCOVERED = 0x10,
8512 EXPLORED = 0x20,
8513 FALLTHROUGH = 1,
8514 BRANCH = 2,
8515};
8516
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008517static u32 state_htab_size(struct bpf_verifier_env *env)
8518{
8519 return env->prog->len;
8520}
8521
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008522static struct bpf_verifier_state_list **explored_state(
8523 struct bpf_verifier_env *env,
8524 int idx)
8525{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07008526 struct bpf_verifier_state *cur = env->cur_state;
8527 struct bpf_func_state *state = cur->frame[cur->curframe];
8528
8529 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008530}
8531
8532static void init_explored_state(struct bpf_verifier_env *env, int idx)
8533{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07008534 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008535}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008536
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008537enum {
8538 DONE_EXPLORING = 0,
8539 KEEP_EXPLORING = 1,
8540};
8541
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008542/* t, w, e - match pseudo-code above:
8543 * t - index of current instruction
8544 * w - next instruction
8545 * e - edge
8546 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07008547static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
8548 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008549{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008550 int *insn_stack = env->cfg.insn_stack;
8551 int *insn_state = env->cfg.insn_state;
8552
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008553 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008554 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008555
8556 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008557 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008558
8559 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008560 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008561 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008562 return -EINVAL;
8563 }
8564
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008565 if (e == BRANCH)
8566 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07008567 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07008568
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008569 if (insn_state[w] == 0) {
8570 /* tree-edge */
8571 insn_state[t] = DISCOVERED | e;
8572 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008573 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008574 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008575 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008576 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008577 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07008578 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008579 return DONE_EXPLORING;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08008580 verbose_linfo(env, t, "%d: ", t);
8581 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008582 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008583 return -EINVAL;
8584 } else if (insn_state[w] == EXPLORED) {
8585 /* forward- or cross-edge */
8586 insn_state[t] = DISCOVERED | e;
8587 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008588 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008589 return -EFAULT;
8590 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008591 return DONE_EXPLORING;
8592}
8593
8594/* Visits the instruction at index t and returns one of the following:
8595 * < 0 - an error occurred
8596 * DONE_EXPLORING - the instruction was fully explored
8597 * KEEP_EXPLORING - there is still work to be done before it is fully explored
8598 */
8599static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
8600{
8601 struct bpf_insn *insns = env->prog->insnsi;
8602 int ret;
8603
8604 /* All non-branch instructions have a single fall-through edge. */
8605 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
8606 BPF_CLASS(insns[t].code) != BPF_JMP32)
8607 return push_insn(t, t + 1, FALLTHROUGH, env, false);
8608
8609 switch (BPF_OP(insns[t].code)) {
8610 case BPF_EXIT:
8611 return DONE_EXPLORING;
8612
8613 case BPF_CALL:
8614 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
8615 if (ret)
8616 return ret;
8617
8618 if (t + 1 < insn_cnt)
8619 init_explored_state(env, t + 1);
8620 if (insns[t].src_reg == BPF_PSEUDO_CALL) {
8621 init_explored_state(env, t);
8622 ret = push_insn(t, t + insns[t].imm + 1, BRANCH,
8623 env, false);
8624 }
8625 return ret;
8626
8627 case BPF_JA:
8628 if (BPF_SRC(insns[t].code) != BPF_K)
8629 return -EINVAL;
8630
8631 /* unconditional jump with single edge */
8632 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
8633 true);
8634 if (ret)
8635 return ret;
8636
8637 /* unconditional jmp is not a good pruning point,
8638 * but it's marked, since backtracking needs
8639 * to record jmp history in is_state_visited().
8640 */
8641 init_explored_state(env, t + insns[t].off + 1);
8642 /* tell verifier to check for equivalent states
8643 * after every call and jump
8644 */
8645 if (t + 1 < insn_cnt)
8646 init_explored_state(env, t + 1);
8647
8648 return ret;
8649
8650 default:
8651 /* conditional jump with two edges */
8652 init_explored_state(env, t);
8653 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
8654 if (ret)
8655 return ret;
8656
8657 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
8658 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008659}
8660
8661/* non-recursive depth-first-search to detect loops in BPF program
8662 * loop == back-edge in directed graph
8663 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008664static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008665{
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008666 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008667 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008668 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008669 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008670
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008671 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008672 if (!insn_state)
8673 return -ENOMEM;
8674
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008675 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008676 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008677 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008678 return -ENOMEM;
8679 }
8680
8681 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
8682 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008683 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008684
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008685 while (env->cfg.cur_stack > 0) {
8686 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008687
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008688 ret = visit_insn(t, insn_cnt, env);
8689 switch (ret) {
8690 case DONE_EXPLORING:
8691 insn_state[t] = EXPLORED;
8692 env->cfg.cur_stack--;
8693 break;
8694 case KEEP_EXPLORING:
8695 break;
8696 default:
8697 if (ret > 0) {
8698 verbose(env, "visit_insn internal bug\n");
8699 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08008700 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008701 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008702 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008703 }
8704
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00008705 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008706 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008707 ret = -EFAULT;
8708 goto err_free;
8709 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008710
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008711 for (i = 0; i < insn_cnt; i++) {
8712 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008713 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008714 ret = -EINVAL;
8715 goto err_free;
8716 }
8717 }
8718 ret = 0; /* cfg looks good */
8719
8720err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -07008721 kvfree(insn_state);
8722 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07008723 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07008724 return ret;
8725}
8726
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008727static int check_abnormal_return(struct bpf_verifier_env *env)
8728{
8729 int i;
8730
8731 for (i = 1; i < env->subprog_cnt; i++) {
8732 if (env->subprog_info[i].has_ld_abs) {
8733 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
8734 return -EINVAL;
8735 }
8736 if (env->subprog_info[i].has_tail_call) {
8737 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
8738 return -EINVAL;
8739 }
8740 }
8741 return 0;
8742}
8743
Yonghong Song838e9692018-11-19 15:29:11 -08008744/* The minimum supported BTF func info size */
8745#define MIN_BPF_FUNCINFO_SIZE 8
8746#define MAX_FUNCINFO_REC_SIZE 252
8747
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008748static int check_btf_func(struct bpf_verifier_env *env,
8749 const union bpf_attr *attr,
8750 union bpf_attr __user *uattr)
Yonghong Song838e9692018-11-19 15:29:11 -08008751{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008752 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008753 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -08008754 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008755 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008756 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008757 struct bpf_prog *prog;
8758 const struct btf *btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008759 void __user *urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -08008760 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008761 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +03008762 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -08008763
8764 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008765 if (!nfuncs) {
8766 if (check_abnormal_return(env))
8767 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008768 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008769 }
Yonghong Song838e9692018-11-19 15:29:11 -08008770
8771 if (nfuncs != env->subprog_cnt) {
8772 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
8773 return -EINVAL;
8774 }
8775
8776 urec_size = attr->func_info_rec_size;
8777 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
8778 urec_size > MAX_FUNCINFO_REC_SIZE ||
8779 urec_size % sizeof(u32)) {
8780 verbose(env, "invalid func info rec size %u\n", urec_size);
8781 return -EINVAL;
8782 }
8783
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008784 prog = env->prog;
8785 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -08008786
8787 urecord = u64_to_user_ptr(attr->func_info);
8788 min_size = min_t(u32, krec_size, urec_size);
8789
Yonghong Songba64e7d2018-11-24 23:20:44 -08008790 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008791 if (!krecord)
8792 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008793 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
8794 if (!info_aux)
8795 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008796
Yonghong Song838e9692018-11-19 15:29:11 -08008797 for (i = 0; i < nfuncs; i++) {
8798 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
8799 if (ret) {
8800 if (ret == -E2BIG) {
8801 verbose(env, "nonzero tailing record in func info");
8802 /* set the size kernel expects so loader can zero
8803 * out the rest of the record.
8804 */
8805 if (put_user(min_size, &uattr->func_info_rec_size))
8806 ret = -EFAULT;
8807 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008808 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008809 }
8810
Yonghong Songba64e7d2018-11-24 23:20:44 -08008811 if (copy_from_user(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008812 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008813 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008814 }
8815
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008816 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008817 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -08008818 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008819 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008820 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008821 "nonzero insn_off %u for the first func info record",
8822 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008823 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008824 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008825 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -08008826 verbose(env,
8827 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008828 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008829 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008830 }
8831
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008832 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -08008833 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008834 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008835 }
8836
8837 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -08008838 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008839 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -08008840 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -08008841 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008842 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -08008843 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08008844 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07008845
8846 func_proto = btf_type_by_id(btf, type->type);
8847 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
8848 /* btf_func_check() already verified it during BTF load */
8849 goto err_free;
8850 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
8851 scalar_return =
8852 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
8853 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
8854 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
8855 goto err_free;
8856 }
8857 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
8858 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
8859 goto err_free;
8860 }
8861
Martin KaFai Laud30d42e2018-12-05 17:35:44 -08008862 prev_offset = krecord[i].insn_off;
Yonghong Song838e9692018-11-19 15:29:11 -08008863 urecord += urec_size;
8864 }
8865
Yonghong Songba64e7d2018-11-24 23:20:44 -08008866 prog->aux->func_info = krecord;
8867 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008868 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -08008869 return 0;
8870
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008871err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -08008872 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008873 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -08008874 return ret;
8875}
8876
Yonghong Songba64e7d2018-11-24 23:20:44 -08008877static void adjust_btf_func(struct bpf_verifier_env *env)
8878{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008879 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008880 int i;
8881
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008882 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -08008883 return;
8884
8885 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -08008886 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -08008887}
8888
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008889#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
8890 sizeof(((struct bpf_line_info *)(0))->line_col))
8891#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
8892
8893static int check_btf_line(struct bpf_verifier_env *env,
8894 const union bpf_attr *attr,
8895 union bpf_attr __user *uattr)
8896{
8897 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
8898 struct bpf_subprog_info *sub;
8899 struct bpf_line_info *linfo;
8900 struct bpf_prog *prog;
8901 const struct btf *btf;
8902 void __user *ulinfo;
8903 int err;
8904
8905 nr_linfo = attr->line_info_cnt;
8906 if (!nr_linfo)
8907 return 0;
8908
8909 rec_size = attr->line_info_rec_size;
8910 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
8911 rec_size > MAX_LINEINFO_REC_SIZE ||
8912 rec_size & (sizeof(u32) - 1))
8913 return -EINVAL;
8914
8915 /* Need to zero it in case the userspace may
8916 * pass in a smaller bpf_line_info object.
8917 */
8918 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
8919 GFP_KERNEL | __GFP_NOWARN);
8920 if (!linfo)
8921 return -ENOMEM;
8922
8923 prog = env->prog;
8924 btf = prog->aux->btf;
8925
8926 s = 0;
8927 sub = env->subprog_info;
8928 ulinfo = u64_to_user_ptr(attr->line_info);
8929 expected_size = sizeof(struct bpf_line_info);
8930 ncopy = min_t(u32, expected_size, rec_size);
8931 for (i = 0; i < nr_linfo; i++) {
8932 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
8933 if (err) {
8934 if (err == -E2BIG) {
8935 verbose(env, "nonzero tailing record in line_info");
8936 if (put_user(expected_size,
8937 &uattr->line_info_rec_size))
8938 err = -EFAULT;
8939 }
8940 goto err_free;
8941 }
8942
8943 if (copy_from_user(&linfo[i], ulinfo, ncopy)) {
8944 err = -EFAULT;
8945 goto err_free;
8946 }
8947
8948 /*
8949 * Check insn_off to ensure
8950 * 1) strictly increasing AND
8951 * 2) bounded by prog->len
8952 *
8953 * The linfo[0].insn_off == 0 check logically falls into
8954 * the later "missing bpf_line_info for func..." case
8955 * because the first linfo[0].insn_off must be the
8956 * first sub also and the first sub must have
8957 * subprog_info[0].start == 0.
8958 */
8959 if ((i && linfo[i].insn_off <= prev_offset) ||
8960 linfo[i].insn_off >= prog->len) {
8961 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
8962 i, linfo[i].insn_off, prev_offset,
8963 prog->len);
8964 err = -EINVAL;
8965 goto err_free;
8966 }
8967
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -08008968 if (!prog->insnsi[linfo[i].insn_off].code) {
8969 verbose(env,
8970 "Invalid insn code at line_info[%u].insn_off\n",
8971 i);
8972 err = -EINVAL;
8973 goto err_free;
8974 }
8975
Martin KaFai Lau23127b32018-12-13 10:41:46 -08008976 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
8977 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -08008978 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
8979 err = -EINVAL;
8980 goto err_free;
8981 }
8982
8983 if (s != env->subprog_cnt) {
8984 if (linfo[i].insn_off == sub[s].start) {
8985 sub[s].linfo_idx = i;
8986 s++;
8987 } else if (sub[s].start < linfo[i].insn_off) {
8988 verbose(env, "missing bpf_line_info for func#%u\n", s);
8989 err = -EINVAL;
8990 goto err_free;
8991 }
8992 }
8993
8994 prev_offset = linfo[i].insn_off;
8995 ulinfo += rec_size;
8996 }
8997
8998 if (s != env->subprog_cnt) {
8999 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
9000 env->subprog_cnt - s, s);
9001 err = -EINVAL;
9002 goto err_free;
9003 }
9004
9005 prog->aux->linfo = linfo;
9006 prog->aux->nr_linfo = nr_linfo;
9007
9008 return 0;
9009
9010err_free:
9011 kvfree(linfo);
9012 return err;
9013}
9014
9015static int check_btf_info(struct bpf_verifier_env *env,
9016 const union bpf_attr *attr,
9017 union bpf_attr __user *uattr)
9018{
9019 struct btf *btf;
9020 int err;
9021
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009022 if (!attr->func_info_cnt && !attr->line_info_cnt) {
9023 if (check_abnormal_return(env))
9024 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009025 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07009026 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -08009027
9028 btf = btf_get_by_fd(attr->prog_btf_fd);
9029 if (IS_ERR(btf))
9030 return PTR_ERR(btf);
9031 env->prog->aux->btf = btf;
9032
9033 err = check_btf_func(env, attr, uattr);
9034 if (err)
9035 return err;
9036
9037 err = check_btf_line(env, attr, uattr);
9038 if (err)
9039 return err;
9040
9041 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -07009042}
9043
Edward Creef1174f72017-08-07 15:26:19 +01009044/* check %cur's range satisfies %old's */
9045static bool range_within(struct bpf_reg_state *old,
9046 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009047{
Edward Creeb03c9f92017-08-07 15:26:36 +01009048 return old->umin_value <= cur->umin_value &&
9049 old->umax_value >= cur->umax_value &&
9050 old->smin_value <= cur->smin_value &&
9051 old->smax_value >= cur->smax_value;
Edward Creef1174f72017-08-07 15:26:19 +01009052}
9053
9054/* Maximum number of register states that can exist at once */
9055#define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE)
9056struct idpair {
9057 u32 old;
9058 u32 cur;
9059};
9060
9061/* If in the old state two registers had the same id, then they need to have
9062 * the same id in the new state as well. But that id could be different from
9063 * the old state, so we need to track the mapping from old to new ids.
9064 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
9065 * regs with old id 5 must also have new id 9 for the new state to be safe. But
9066 * regs with a different old id could still have new id 9, we don't care about
9067 * that.
9068 * So we look through our idmap to see if this old id has been seen before. If
9069 * so, we require the new id to match; otherwise, we add the id pair to the map.
9070 */
9071static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap)
9072{
9073 unsigned int i;
9074
9075 for (i = 0; i < ID_MAP_SIZE; i++) {
9076 if (!idmap[i].old) {
9077 /* Reached an empty slot; haven't seen this id before */
9078 idmap[i].old = old_id;
9079 idmap[i].cur = cur_id;
9080 return true;
9081 }
9082 if (idmap[i].old == old_id)
9083 return idmap[i].cur == cur_id;
9084 }
9085 /* We ran out of idmap slots, which should be impossible */
9086 WARN_ON_ONCE(1);
9087 return false;
9088}
9089
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009090static void clean_func_state(struct bpf_verifier_env *env,
9091 struct bpf_func_state *st)
9092{
9093 enum bpf_reg_liveness live;
9094 int i, j;
9095
9096 for (i = 0; i < BPF_REG_FP; i++) {
9097 live = st->regs[i].live;
9098 /* liveness must not touch this register anymore */
9099 st->regs[i].live |= REG_LIVE_DONE;
9100 if (!(live & REG_LIVE_READ))
9101 /* since the register is unused, clear its state
9102 * to make further comparison simpler
9103 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009104 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009105 }
9106
9107 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
9108 live = st->stack[i].spilled_ptr.live;
9109 /* liveness must not touch this stack slot anymore */
9110 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
9111 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01009112 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009113 for (j = 0; j < BPF_REG_SIZE; j++)
9114 st->stack[i].slot_type[j] = STACK_INVALID;
9115 }
9116 }
9117}
9118
9119static void clean_verifier_state(struct bpf_verifier_env *env,
9120 struct bpf_verifier_state *st)
9121{
9122 int i;
9123
9124 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
9125 /* all regs in this state in all frames were already marked */
9126 return;
9127
9128 for (i = 0; i <= st->curframe; i++)
9129 clean_func_state(env, st->frame[i]);
9130}
9131
9132/* the parentage chains form a tree.
9133 * the verifier states are added to state lists at given insn and
9134 * pushed into state stack for future exploration.
9135 * when the verifier reaches bpf_exit insn some of the verifer states
9136 * stored in the state lists have their final liveness state already,
9137 * but a lot of states will get revised from liveness point of view when
9138 * the verifier explores other branches.
9139 * Example:
9140 * 1: r0 = 1
9141 * 2: if r1 == 100 goto pc+1
9142 * 3: r0 = 2
9143 * 4: exit
9144 * when the verifier reaches exit insn the register r0 in the state list of
9145 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
9146 * of insn 2 and goes exploring further. At the insn 4 it will walk the
9147 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
9148 *
9149 * Since the verifier pushes the branch states as it sees them while exploring
9150 * the program the condition of walking the branch instruction for the second
9151 * time means that all states below this branch were already explored and
9152 * their final liveness markes are already propagated.
9153 * Hence when the verifier completes the search of state list in is_state_visited()
9154 * we can call this clean_live_states() function to mark all liveness states
9155 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
9156 * will not be used.
9157 * This function also clears the registers and stack for states that !READ
9158 * to simplify state merging.
9159 *
9160 * Important note here that walking the same branch instruction in the callee
9161 * doesn't meant that the states are DONE. The verifier has to compare
9162 * the callsites
9163 */
9164static void clean_live_states(struct bpf_verifier_env *env, int insn,
9165 struct bpf_verifier_state *cur)
9166{
9167 struct bpf_verifier_state_list *sl;
9168 int i;
9169
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009170 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009171 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009172 if (sl->state.branches)
9173 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009174 if (sl->state.insn_idx != insn ||
9175 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009176 goto next;
9177 for (i = 0; i <= cur->curframe; i++)
9178 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
9179 goto next;
9180 clean_verifier_state(env, &sl->state);
9181next:
9182 sl = sl->next;
9183 }
9184}
9185
Edward Creef1174f72017-08-07 15:26:19 +01009186/* Returns true if (rold safe implies rcur safe) */
Edward Cree1b688a12017-08-23 15:10:50 +01009187static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
9188 struct idpair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +01009189{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009190 bool equal;
9191
Edward Creedc503a82017-08-15 20:34:35 +01009192 if (!(rold->live & REG_LIVE_READ))
9193 /* explored state didn't use this */
9194 return true;
9195
Edward Cree679c7822018-08-22 20:02:19 +01009196 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009197
9198 if (rold->type == PTR_TO_STACK)
9199 /* two stack pointers are equal only if they're pointing to
9200 * the same stack frame, since fp-8 in foo != fp-8 in bar
9201 */
9202 return equal && rold->frameno == rcur->frameno;
9203
9204 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +01009205 return true;
9206
9207 if (rold->type == NOT_INIT)
9208 /* explored state can't have used this */
9209 return true;
9210 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009211 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009212 switch (rold->type) {
9213 case SCALAR_VALUE:
9214 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009215 if (!rold->precise && !rcur->precise)
9216 return true;
Edward Creef1174f72017-08-07 15:26:19 +01009217 /* new val must satisfy old val knowledge */
9218 return range_within(rold, rcur) &&
9219 tnum_in(rold->var_off, rcur->var_off);
9220 } else {
Jann Horn179d1c52017-12-18 20:11:59 -08009221 /* We're trying to use a pointer in place of a scalar.
9222 * Even if the scalar was unbounded, this could lead to
9223 * pointer leaks because scalars are allowed to leak
9224 * while pointers are not. We could make this safe in
9225 * special cases if root is calling us, but it's
9226 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +01009227 */
Jann Horn179d1c52017-12-18 20:11:59 -08009228 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009229 }
9230 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +01009231 /* If the new min/max/var_off satisfy the old ones and
9232 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009233 * 'id' is not compared, since it's only used for maps with
9234 * bpf_spin_lock inside map element and in such cases if
9235 * the rest of the prog is valid for one map element then
9236 * it's valid for all map elements regardless of the key
9237 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +01009238 */
9239 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
9240 range_within(rold, rcur) &&
9241 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +01009242 case PTR_TO_MAP_VALUE_OR_NULL:
9243 /* a PTR_TO_MAP_VALUE could be safe to use as a
9244 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
9245 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
9246 * checked, doing so could have affected others with the same
9247 * id, and we can't check for that because we lost the id when
9248 * we converted to a PTR_TO_MAP_VALUE.
9249 */
9250 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
9251 return false;
9252 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
9253 return false;
9254 /* Check our ids match any regs they're supposed to */
9255 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009256 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +01009257 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02009258 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +01009259 return false;
9260 /* We must have at least as much range as the old ptr
9261 * did, so that any accesses which were safe before are
9262 * still safe. This is true even if old range < old off,
9263 * since someone could have accessed through (ptr - k), or
9264 * even done ptr -= k in a register, to get a safe access.
9265 */
9266 if (rold->range > rcur->range)
9267 return false;
9268 /* If the offsets don't match, we can't trust our alignment;
9269 * nor can we be sure that we won't fall out of range.
9270 */
9271 if (rold->off != rcur->off)
9272 return false;
9273 /* id relations must be preserved */
9274 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
9275 return false;
9276 /* new val must satisfy old val knowledge */
9277 return range_within(rold, rcur) &&
9278 tnum_in(rold->var_off, rcur->var_off);
9279 case PTR_TO_CTX:
9280 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +01009281 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07009282 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -07009283 case PTR_TO_SOCKET:
9284 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009285 case PTR_TO_SOCK_COMMON:
9286 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009287 case PTR_TO_TCP_SOCK:
9288 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009289 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +01009290 /* Only valid matches are exact, which memcmp() above
9291 * would have accepted
9292 */
9293 default:
9294 /* Don't know what's going on, just say it's not safe */
9295 return false;
9296 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009297
Edward Creef1174f72017-08-07 15:26:19 +01009298 /* Shouldn't get here; if we do, say it's not safe */
9299 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07009300 return false;
9301}
9302
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009303static bool stacksafe(struct bpf_func_state *old,
9304 struct bpf_func_state *cur,
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009305 struct idpair *idmap)
9306{
9307 int i, spi;
9308
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009309 /* walk slots of the explored stack and ignore any additional
9310 * slots in the current stack, since explored(safe) state
9311 * didn't use them
9312 */
9313 for (i = 0; i < old->allocated_stack; i++) {
9314 spi = i / BPF_REG_SIZE;
9315
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009316 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
9317 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009318 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +00009319 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -08009320 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009321
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009322 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
9323 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -08009324
9325 /* explored stack has more populated slots than current stack
9326 * and these slots were used
9327 */
9328 if (i >= cur->allocated_stack)
9329 return false;
9330
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009331 /* if old state was safe with misc data in the stack
9332 * it will be safe with zero-initialized stack.
9333 * The opposite is not true
9334 */
9335 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
9336 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
9337 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009338 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
9339 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
9340 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -07009341 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009342 * this verifier states are not equivalent,
9343 * return false to continue verification of this path
9344 */
9345 return false;
9346 if (i % BPF_REG_SIZE)
9347 continue;
9348 if (old->stack[spi].slot_type[0] != STACK_SPILL)
9349 continue;
9350 if (!regsafe(&old->stack[spi].spilled_ptr,
9351 &cur->stack[spi].spilled_ptr,
9352 idmap))
9353 /* when explored and current stack slot are both storing
9354 * spilled registers, check that stored pointers types
9355 * are the same as well.
9356 * Ex: explored safe path could have stored
9357 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
9358 * but current path has stored:
9359 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
9360 * such verifier states are not equivalent.
9361 * return false to continue verification of this path
9362 */
9363 return false;
9364 }
9365 return true;
9366}
9367
Joe Stringerfd978bf72018-10-02 13:35:35 -07009368static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
9369{
9370 if (old->acquired_refs != cur->acquired_refs)
9371 return false;
9372 return !memcmp(old->refs, cur->refs,
9373 sizeof(*old->refs) * old->acquired_refs);
9374}
9375
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009376/* compare two verifier states
9377 *
9378 * all states stored in state_list are known to be valid, since
9379 * verifier reached 'bpf_exit' instruction through them
9380 *
9381 * this function is called when verifier exploring different branches of
9382 * execution popped from the state stack. If it sees an old state that has
9383 * more strict register state and more strict stack state then this execution
9384 * branch doesn't need to be explored further, since verifier already
9385 * concluded that more strict state leads to valid finish.
9386 *
9387 * Therefore two states are equivalent if register state is more conservative
9388 * and explored stack state is more conservative than the current one.
9389 * Example:
9390 * explored current
9391 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
9392 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
9393 *
9394 * In other words if current stack state (one being explored) has more
9395 * valid slots than old one that already passed validation, it means
9396 * the verifier can stop exploring and conclude that current state is valid too
9397 *
9398 * Similarly with registers. If explored state has register type as invalid
9399 * whereas register type in current state is meaningful, it means that
9400 * the current state will reach 'bpf_exit' instruction safely
9401 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009402static bool func_states_equal(struct bpf_func_state *old,
9403 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009404{
Edward Creef1174f72017-08-07 15:26:19 +01009405 struct idpair *idmap;
9406 bool ret = false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009407 int i;
9408
Edward Creef1174f72017-08-07 15:26:19 +01009409 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL);
9410 /* If we failed to allocate the idmap, just say it's not safe */
9411 if (!idmap)
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009412 return false;
Edward Creef1174f72017-08-07 15:26:19 +01009413
9414 for (i = 0; i < MAX_BPF_REG; i++) {
Edward Cree1b688a12017-08-23 15:10:50 +01009415 if (!regsafe(&old->regs[i], &cur->regs[i], idmap))
Edward Creef1174f72017-08-07 15:26:19 +01009416 goto out_free;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009417 }
9418
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009419 if (!stacksafe(old, cur, idmap))
9420 goto out_free;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009421
9422 if (!refsafe(old, cur))
9423 goto out_free;
Edward Creef1174f72017-08-07 15:26:19 +01009424 ret = true;
9425out_free:
9426 kfree(idmap);
9427 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009428}
9429
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009430static bool states_equal(struct bpf_verifier_env *env,
9431 struct bpf_verifier_state *old,
9432 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +01009433{
Edward Creedc503a82017-08-15 20:34:35 +01009434 int i;
9435
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009436 if (old->curframe != cur->curframe)
9437 return false;
9438
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009439 /* Verification state from speculative execution simulation
9440 * must never prune a non-speculative execution one.
9441 */
9442 if (old->speculative && !cur->speculative)
9443 return false;
9444
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009445 if (old->active_spin_lock != cur->active_spin_lock)
9446 return false;
9447
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009448 /* for states to be equal callsites have to be the same
9449 * and all frame states need to be equivalent
9450 */
9451 for (i = 0; i <= old->curframe; i++) {
9452 if (old->frame[i]->callsite != cur->frame[i]->callsite)
9453 return false;
9454 if (!func_states_equal(old->frame[i], cur->frame[i]))
9455 return false;
9456 }
9457 return true;
9458}
9459
Jiong Wang5327ed32019-05-24 23:25:12 +01009460/* Return 0 if no propagation happened. Return negative error code if error
9461 * happened. Otherwise, return the propagated bit.
9462 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009463static int propagate_liveness_reg(struct bpf_verifier_env *env,
9464 struct bpf_reg_state *reg,
9465 struct bpf_reg_state *parent_reg)
9466{
Jiong Wang5327ed32019-05-24 23:25:12 +01009467 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
9468 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009469 int err;
9470
Jiong Wang5327ed32019-05-24 23:25:12 +01009471 /* When comes here, read flags of PARENT_REG or REG could be any of
9472 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
9473 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
9474 */
9475 if (parent_flag == REG_LIVE_READ64 ||
9476 /* Or if there is no read flag from REG. */
9477 !flag ||
9478 /* Or if the read flag from REG is the same as PARENT_REG. */
9479 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009480 return 0;
9481
Jiong Wang5327ed32019-05-24 23:25:12 +01009482 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009483 if (err)
9484 return err;
9485
Jiong Wang5327ed32019-05-24 23:25:12 +01009486 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009487}
9488
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009489/* A write screens off any subsequent reads; but write marks come from the
9490 * straight-line code between a state and its parent. When we arrive at an
9491 * equivalent state (jump target or such) we didn't arrive by the straight-line
9492 * code, so read marks in the state must propagate to the parent regardless
9493 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +01009494 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009495 */
9496static int propagate_liveness(struct bpf_verifier_env *env,
9497 const struct bpf_verifier_state *vstate,
9498 struct bpf_verifier_state *vparent)
9499{
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009500 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009501 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009502 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009503
9504 if (vparent->curframe != vstate->curframe) {
9505 WARN(1, "propagate_live: parent frame %d current frame %d\n",
9506 vparent->curframe, vstate->curframe);
9507 return -EFAULT;
9508 }
Edward Creedc503a82017-08-15 20:34:35 +01009509 /* Propagate read liveness of registers... */
9510 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -07009511 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009512 parent = vparent->frame[frame];
9513 state = vstate->frame[frame];
9514 parent_reg = parent->regs;
9515 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -07009516 /* We don't need to worry about FP liveness, it's read-only */
9517 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009518 err = propagate_liveness_reg(env, &state_reg[i],
9519 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +01009520 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009521 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +01009522 if (err == REG_LIVE_READ64)
9523 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009524 }
Edward Creedc503a82017-08-15 20:34:35 +01009525
Jiong Wang1b04aee2019-04-12 22:59:34 +01009526 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009527 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
9528 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009529 parent_reg = &parent->stack[i].spilled_ptr;
9530 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +01009531 err = propagate_liveness_reg(env, state_reg,
9532 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +01009533 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +01009534 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009535 }
Edward Creedc503a82017-08-15 20:34:35 +01009536 }
Jiong Wang5327ed32019-05-24 23:25:12 +01009537 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01009538}
9539
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009540/* find precise scalars in the previous equivalent state and
9541 * propagate them into the current state
9542 */
9543static int propagate_precision(struct bpf_verifier_env *env,
9544 const struct bpf_verifier_state *old)
9545{
9546 struct bpf_reg_state *state_reg;
9547 struct bpf_func_state *state;
9548 int i, err = 0;
9549
9550 state = old->frame[old->curframe];
9551 state_reg = state->regs;
9552 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
9553 if (state_reg->type != SCALAR_VALUE ||
9554 !state_reg->precise)
9555 continue;
9556 if (env->log.level & BPF_LOG_LEVEL2)
9557 verbose(env, "propagating r%d\n", i);
9558 err = mark_chain_precision(env, i);
9559 if (err < 0)
9560 return err;
9561 }
9562
9563 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
9564 if (state->stack[i].slot_type[0] != STACK_SPILL)
9565 continue;
9566 state_reg = &state->stack[i].spilled_ptr;
9567 if (state_reg->type != SCALAR_VALUE ||
9568 !state_reg->precise)
9569 continue;
9570 if (env->log.level & BPF_LOG_LEVEL2)
9571 verbose(env, "propagating fp%d\n",
9572 (-i - 1) * BPF_REG_SIZE);
9573 err = mark_chain_precision_stack(env, i);
9574 if (err < 0)
9575 return err;
9576 }
9577 return 0;
9578}
9579
Alexei Starovoitov25897262019-06-15 12:12:20 -07009580static bool states_maybe_looping(struct bpf_verifier_state *old,
9581 struct bpf_verifier_state *cur)
9582{
9583 struct bpf_func_state *fold, *fcur;
9584 int i, fr = cur->curframe;
9585
9586 if (old->curframe != fr)
9587 return false;
9588
9589 fold = old->frame[fr];
9590 fcur = cur->frame[fr];
9591 for (i = 0; i < MAX_BPF_REG; i++)
9592 if (memcmp(&fold->regs[i], &fcur->regs[i],
9593 offsetof(struct bpf_reg_state, parent)))
9594 return false;
9595 return true;
9596}
9597
9598
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009599static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009600{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009601 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009602 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +01009603 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009604 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -07009605 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009606
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009607 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009608 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009609 /* this 'insn_idx' instruction wasn't marked, so we will not
9610 * be doing state search here
9611 */
9612 return 0;
9613
Alexei Starovoitov25897262019-06-15 12:12:20 -07009614 /* bpf progs typically have pruning point every 4 instructions
9615 * http://vger.kernel.org/bpfconf2019.html#session-1
9616 * Do not add new state for future pruning if the verifier hasn't seen
9617 * at least 2 jumps and at least 8 instructions.
9618 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
9619 * In tests that amounts to up to 50% reduction into total verifier
9620 * memory consumption and 20% verifier time speedup.
9621 */
9622 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
9623 env->insn_processed - env->prev_insn_processed >= 8)
9624 add_new_state = true;
9625
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009626 pprev = explored_state(env, insn_idx);
9627 sl = *pprev;
9628
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08009629 clean_live_states(env, insn_idx, cur);
9630
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009631 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009632 states_cnt++;
9633 if (sl->state.insn_idx != insn_idx)
9634 goto next;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009635 if (sl->state.branches) {
9636 if (states_maybe_looping(&sl->state, cur) &&
9637 states_equal(env, &sl->state, cur)) {
9638 verbose_linfo(env, insn_idx, "; ");
9639 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
9640 return -EINVAL;
9641 }
9642 /* if the verifier is processing a loop, avoid adding new state
9643 * too often, since different loop iterations have distinct
9644 * states and may not help future pruning.
9645 * This threshold shouldn't be too low to make sure that
9646 * a loop with large bound will be rejected quickly.
9647 * The most abusive loop will be:
9648 * r1 += 1
9649 * if r1 < 1000000 goto pc-2
9650 * 1M insn_procssed limit / 100 == 10k peak states.
9651 * This threshold shouldn't be too high either, since states
9652 * at the end of the loop are likely to be useful in pruning.
9653 */
9654 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
9655 env->insn_processed - env->prev_insn_processed < 100)
9656 add_new_state = false;
9657 goto miss;
9658 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009659 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009660 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009661 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +01009662 * prune the search.
9663 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009664 * If we have any write marks in env->cur_state, they
9665 * will prevent corresponding reads in the continuation
9666 * from reaching our parent (an explored_state). Our
9667 * own state will get the read marks recorded, but
9668 * they'll be immediately forgotten as we're pruning
9669 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009670 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009671 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07009672
9673 /* if previous state reached the exit with precision and
9674 * current state is equivalent to it (except precsion marks)
9675 * the precision needs to be propagated back in
9676 * the current state.
9677 */
9678 err = err ? : push_jmp_history(env, cur);
9679 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009680 if (err)
9681 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009682 return 1;
Edward Creedc503a82017-08-15 20:34:35 +01009683 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07009684miss:
9685 /* when new state is not going to be added do not increase miss count.
9686 * Otherwise several loop iterations will remove the state
9687 * recorded earlier. The goal of these heuristics is to have
9688 * states from some iterations of the loop (some in the beginning
9689 * and some at the end) to help pruning.
9690 */
9691 if (add_new_state)
9692 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009693 /* heuristic to determine whether this state is beneficial
9694 * to keep checking from state equivalence point of view.
9695 * Higher numbers increase max_states_per_insn and verification time,
9696 * but do not meaningfully decrease insn_processed.
9697 */
9698 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
9699 /* the state is unlikely to be useful. Remove it to
9700 * speed up verification
9701 */
9702 *pprev = sl->next;
9703 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -07009704 u32 br = sl->state.branches;
9705
9706 WARN_ONCE(br,
9707 "BUG live_done but branches_to_explore %d\n",
9708 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009709 free_verifier_state(&sl->state, false);
9710 kfree(sl);
9711 env->peak_states--;
9712 } else {
9713 /* cannot free this state, since parentage chain may
9714 * walk it later. Add it for free_list instead to
9715 * be freed at the end of verification
9716 */
9717 sl->next = env->free_list;
9718 env->free_list = sl;
9719 }
9720 sl = *pprev;
9721 continue;
9722 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009723next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -07009724 pprev = &sl->next;
9725 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009726 }
9727
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009728 if (env->max_states_per_insn < states_cnt)
9729 env->max_states_per_insn = states_cnt;
9730
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009731 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009732 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -08009733
Alexei Starovoitov25897262019-06-15 12:12:20 -07009734 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009735 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -07009736
9737 /* There were no equivalent states, remember the current one.
9738 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009739 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009740 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009741 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -07009742 * again on the way to bpf_exit.
9743 * When looping the sl->state.branches will be > 0 and this state
9744 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009745 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009746 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009747 if (!new_sl)
9748 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009749 env->total_states++;
9750 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009751 env->prev_jmps_processed = env->jmps_processed;
9752 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009753
9754 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +01009755 new = &new_sl->state;
9756 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009757 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +01009758 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -07009759 kfree(new_sl);
9760 return err;
9761 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009762 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -07009763 WARN_ONCE(new->branches != 1,
9764 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009765
Alexei Starovoitov25897262019-06-15 12:12:20 -07009766 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009767 cur->first_insn_idx = insn_idx;
9768 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009769 new_sl->next = *explored_state(env, insn_idx);
9770 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -08009771 /* connect new state to parentage chain. Current frame needs all
9772 * registers connected. Only r6 - r9 of the callers are alive (pushed
9773 * to the stack implicitly by JITs) so in callers' frames connect just
9774 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
9775 * the state of the call instruction (with WRITTEN set), and r0 comes
9776 * from callee with its full parentage chain, anyway.
9777 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +01009778 /* clear write marks in current state: the writes we did are not writes
9779 * our child did, so they don't screen off its reads from us.
9780 * (There are no read marks in current state, because reads always mark
9781 * their parent and current state never has children yet. Only
9782 * explored_states can get read marks.)
9783 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -07009784 for (j = 0; j <= cur->curframe; j++) {
9785 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
9786 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
9787 for (i = 0; i < BPF_REG_FP; i++)
9788 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
9789 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009790
9791 /* all stack frames are accessible from callee, clear them all */
9792 for (j = 0; j <= cur->curframe; j++) {
9793 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +01009794 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009795
Edward Cree679c7822018-08-22 20:02:19 +01009796 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08009797 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01009798 frame->stack[i].spilled_ptr.parent =
9799 &newframe->stack[i].spilled_ptr;
9800 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009801 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009802 return 0;
9803}
9804
Joe Stringerc64b7982018-10-02 13:35:33 -07009805/* Return true if it's OK to have the same insn return a different type. */
9806static bool reg_type_mismatch_ok(enum bpf_reg_type type)
9807{
9808 switch (type) {
9809 case PTR_TO_CTX:
9810 case PTR_TO_SOCKET:
9811 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08009812 case PTR_TO_SOCK_COMMON:
9813 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08009814 case PTR_TO_TCP_SOCK:
9815 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07009816 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -07009817 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07009818 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -07009819 return false;
9820 default:
9821 return true;
9822 }
9823}
9824
9825/* If an instruction was previously used with particular pointer types, then we
9826 * need to be careful to avoid cases such as the below, where it may be ok
9827 * for one branch accessing the pointer, but not ok for the other branch:
9828 *
9829 * R1 = sock_ptr
9830 * goto X;
9831 * ...
9832 * R1 = some_other_valid_ptr;
9833 * goto X;
9834 * ...
9835 * R2 = *(u32 *)(R1 + 0);
9836 */
9837static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
9838{
9839 return src != prev && (!reg_type_mismatch_ok(src) ||
9840 !reg_type_mismatch_ok(prev));
9841}
9842
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009843static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009844{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07009845 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009846 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009847 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009848 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009849 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009850 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009851 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009852
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009853 for (;;) {
9854 struct bpf_insn *insn;
9855 u8 class;
9856 int err;
9857
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009858 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009859 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009860 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009861 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009862 return -EFAULT;
9863 }
9864
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009865 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009866 class = BPF_CLASS(insn->code);
9867
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009868 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009869 verbose(env,
9870 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009871 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009872 return -E2BIG;
9873 }
9874
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009875 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009876 if (err < 0)
9877 return err;
9878 if (err == 1) {
9879 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009880 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009881 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009882 verbose(env, "\nfrom %d to %d%s: safe\n",
9883 env->prev_insn_idx, env->insn_idx,
9884 env->cur_state->speculative ?
9885 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009886 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009887 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009888 }
9889 goto process_bpf_exit;
9890 }
9891
Alexei Starovoitovc3494802018-12-03 22:46:04 -08009892 if (signal_pending(current))
9893 return -EAGAIN;
9894
Daniel Borkmann3c2ce602017-05-18 03:00:06 +02009895 if (need_resched())
9896 cond_resched();
9897
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009898 if (env->log.level & BPF_LOG_LEVEL2 ||
9899 (env->log.level & BPF_LOG_LEVEL && do_print_state)) {
9900 if (env->log.level & BPF_LOG_LEVEL2)
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009901 verbose(env, "%d:", env->insn_idx);
David S. Millerc5fc9692017-05-10 11:25:17 -07009902 else
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009903 verbose(env, "\nfrom %d to %d%s:",
9904 env->prev_insn_idx, env->insn_idx,
9905 env->cur_state->speculative ?
9906 " (speculative execution)" : "");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009907 print_verifier_state(env, state->frame[state->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009908 do_print_state = false;
9909 }
9910
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009911 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +01009912 const struct bpf_insn_cbs cbs = {
9913 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +01009914 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +01009915 };
9916
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009917 verbose_linfo(env, env->insn_idx, "; ");
9918 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +01009919 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009920 }
9921
Jakub Kicinskicae19272017-12-27 18:39:05 -08009922 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009923 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
9924 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -08009925 if (err)
9926 return err;
9927 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +01009928
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009929 regs = cur_regs(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08009930 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009931 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -07009932
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009933 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009934 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009935 if (err)
9936 return err;
9937
9938 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009939 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009940
9941 /* check for reserved fields is already done */
9942
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009943 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01009944 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009945 if (err)
9946 return err;
9947
Edward Creedc503a82017-08-15 20:34:35 +01009948 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009949 if (err)
9950 return err;
9951
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -07009952 src_reg_type = regs[insn->src_reg].type;
9953
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009954 /* check that memory (src_reg + off) is readable,
9955 * the state of dst_reg will be updated by this func
9956 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009957 err = check_mem_access(env, env->insn_idx, insn->src_reg,
9958 insn->off, BPF_SIZE(insn->code),
9959 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009960 if (err)
9961 return err;
9962
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009963 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009964
9965 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009966 /* saw a valid insn
9967 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009968 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009969 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009970 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009971
Joe Stringerc64b7982018-10-02 13:35:33 -07009972 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009973 /* ABuser program is trying to use the same insn
9974 * dst_reg = *(u32*) (src_reg + off)
9975 * with different pointer types:
9976 * src_reg == ctx in one branch and
9977 * src_reg == stack|map in some other branch.
9978 * Reject it.
9979 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009980 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -07009981 return -EINVAL;
9982 }
9983
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009984 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +01009985 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -07009986
Brendan Jackman91c960b2021-01-14 18:17:44 +00009987 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
9988 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009989 if (err)
9990 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +01009991 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009992 continue;
9993 }
9994
Brendan Jackman5ca419f2021-01-14 18:17:46 +00009995 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
9996 verbose(env, "BPF_STX uses reserved fields\n");
9997 return -EINVAL;
9998 }
9999
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010000 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010001 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010002 if (err)
10003 return err;
10004 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +010010005 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010006 if (err)
10007 return err;
10008
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010009 dst_reg_type = regs[insn->dst_reg].type;
10010
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010011 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010012 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10013 insn->off, BPF_SIZE(insn->code),
10014 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010015 if (err)
10016 return err;
10017
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010018 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010010019
10020 if (*prev_dst_type == NOT_INIT) {
10021 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070010022 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010023 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010024 return -EINVAL;
10025 }
10026
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010027 } else if (class == BPF_ST) {
10028 if (BPF_MODE(insn->code) != BPF_MEM ||
10029 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010030 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010031 return -EINVAL;
10032 }
10033 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010010034 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010035 if (err)
10036 return err;
10037
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010038 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070010039 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020010040 insn->dst_reg,
10041 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010010042 return -EACCES;
10043 }
10044
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010045 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010046 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
10047 insn->off, BPF_SIZE(insn->code),
10048 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010049 if (err)
10050 return err;
10051
Jiong Wang092ed092019-01-26 12:26:01 -050010052 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010053 u8 opcode = BPF_OP(insn->code);
10054
Alexei Starovoitov25897262019-06-15 12:12:20 -070010055 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010056 if (opcode == BPF_CALL) {
10057 if (BPF_SRC(insn->code) != BPF_K ||
10058 insn->off != 0 ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010059 (insn->src_reg != BPF_REG_0 &&
10060 insn->src_reg != BPF_PSEUDO_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050010061 insn->dst_reg != BPF_REG_0 ||
10062 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010063 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010064 return -EINVAL;
10065 }
10066
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010067 if (env->cur_state->active_spin_lock &&
10068 (insn->src_reg == BPF_PSEUDO_CALL ||
10069 insn->imm != BPF_FUNC_spin_unlock)) {
10070 verbose(env, "function calls are not allowed while holding a lock\n");
10071 return -EINVAL;
10072 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010073 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010074 err = check_func_call(env, insn, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010075 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010076 err = check_helper_call(env, insn->imm, env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010077 if (err)
10078 return err;
10079
10080 } else if (opcode == BPF_JA) {
10081 if (BPF_SRC(insn->code) != BPF_K ||
10082 insn->imm != 0 ||
10083 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010084 insn->dst_reg != BPF_REG_0 ||
10085 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010086 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010087 return -EINVAL;
10088 }
10089
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010090 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010091 continue;
10092
10093 } else if (opcode == BPF_EXIT) {
10094 if (BPF_SRC(insn->code) != BPF_K ||
10095 insn->imm != 0 ||
10096 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050010097 insn->dst_reg != BPF_REG_0 ||
10098 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010099 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010100 return -EINVAL;
10101 }
10102
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010103 if (env->cur_state->active_spin_lock) {
10104 verbose(env, "bpf_spin_unlock is missing\n");
10105 return -EINVAL;
10106 }
10107
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010108 if (state->curframe) {
10109 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010110 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010111 if (err)
10112 return err;
10113 do_print_state = true;
10114 continue;
10115 }
10116
Joe Stringerfd978bf72018-10-02 13:35:35 -070010117 err = check_reference_leak(env);
10118 if (err)
10119 return err;
10120
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070010121 err = check_return_code(env);
10122 if (err)
10123 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010124process_bpf_exit:
Alexei Starovoitov25897262019-06-15 12:12:20 -070010125 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010126 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070010127 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010128 if (err < 0) {
10129 if (err != -ENOENT)
10130 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010131 break;
10132 } else {
10133 do_print_state = true;
10134 continue;
10135 }
10136 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010137 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010138 if (err)
10139 return err;
10140 }
10141 } else if (class == BPF_LD) {
10142 u8 mode = BPF_MODE(insn->code);
10143
10144 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080010145 err = check_ld_abs(env, insn);
10146 if (err)
10147 return err;
10148
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010149 } else if (mode == BPF_IMM) {
10150 err = check_ld_imm(env, insn);
10151 if (err)
10152 return err;
10153
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010154 env->insn_idx++;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010155 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010156 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010157 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010158 return -EINVAL;
10159 }
10160 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010161 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010162 return -EINVAL;
10163 }
10164
Daniel Borkmannc08435e2019-01-03 00:58:27 +010010165 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070010166 }
10167
10168 return 0;
10169}
10170
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010171static int find_btf_percpu_datasec(struct btf *btf)
10172{
10173 const struct btf_type *t;
10174 const char *tname;
10175 int i, n;
10176
10177 /*
10178 * Both vmlinux and module each have their own ".data..percpu"
10179 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
10180 * types to look at only module's own BTF types.
10181 */
10182 n = btf_nr_types(btf);
10183 if (btf_is_module(btf))
10184 i = btf_nr_types(btf_vmlinux);
10185 else
10186 i = 1;
10187
10188 for(; i < n; i++) {
10189 t = btf_type_by_id(btf, i);
10190 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
10191 continue;
10192
10193 tname = btf_name_by_offset(btf, t->name_off);
10194 if (!strcmp(tname, ".data..percpu"))
10195 return i;
10196 }
10197
10198 return -ENOENT;
10199}
10200
Hao Luo4976b712020-09-29 16:50:44 -070010201/* replace pseudo btf_id with kernel symbol address */
10202static int check_pseudo_btf_id(struct bpf_verifier_env *env,
10203 struct bpf_insn *insn,
10204 struct bpf_insn_aux_data *aux)
10205{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010206 const struct btf_var_secinfo *vsi;
10207 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010208 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070010209 const struct btf_type *t;
10210 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010211 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010212 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010213 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080010214 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070010215 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010216 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070010217
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010218 btf_fd = insn[1].imm;
10219 if (btf_fd) {
10220 btf = btf_get_by_fd(btf_fd);
10221 if (IS_ERR(btf)) {
10222 verbose(env, "invalid module BTF object FD specified.\n");
10223 return -EINVAL;
10224 }
10225 } else {
10226 if (!btf_vmlinux) {
10227 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
10228 return -EINVAL;
10229 }
10230 btf = btf_vmlinux;
10231 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070010232 }
10233
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010234 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070010235 if (!t) {
10236 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010237 err = -ENOENT;
10238 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010239 }
10240
10241 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010242 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
10243 err = -EINVAL;
10244 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010245 }
10246
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010247 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010248 addr = kallsyms_lookup_name(sym_name);
10249 if (!addr) {
10250 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
10251 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010252 err = -ENOENT;
10253 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010254 }
10255
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010256 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010257 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010258 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010259 for_each_vsi(i, datasec, vsi) {
10260 if (vsi->type == id) {
10261 percpu = true;
10262 break;
10263 }
10264 }
10265 }
10266
Hao Luo4976b712020-09-29 16:50:44 -070010267 insn[0].imm = (u32)addr;
10268 insn[1].imm = addr >> 32;
10269
10270 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010271 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010272 if (percpu) {
10273 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010274 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070010275 aux->btf_var.btf_id = type;
10276 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070010277 const struct btf_type *ret;
10278 const char *tname;
10279 u32 tsize;
10280
10281 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010282 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070010283 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010284 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070010285 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
10286 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010287 err = -EINVAL;
10288 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070010289 }
10290 aux->btf_var.reg_type = PTR_TO_MEM;
10291 aux->btf_var.mem_size = tsize;
10292 } else {
10293 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010294 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070010295 aux->btf_var.btf_id = type;
10296 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010297
10298 /* check whether we recorded this BTF (and maybe module) already */
10299 for (i = 0; i < env->used_btf_cnt; i++) {
10300 if (env->used_btfs[i].btf == btf) {
10301 btf_put(btf);
10302 return 0;
10303 }
10304 }
10305
10306 if (env->used_btf_cnt >= MAX_USED_BTFS) {
10307 err = -E2BIG;
10308 goto err_put;
10309 }
10310
10311 btf_mod = &env->used_btfs[env->used_btf_cnt];
10312 btf_mod->btf = btf;
10313 btf_mod->module = NULL;
10314
10315 /* if we reference variables from kernel module, bump its refcount */
10316 if (btf_is_module(btf)) {
10317 btf_mod->module = btf_try_get_module(btf);
10318 if (!btf_mod->module) {
10319 err = -ENXIO;
10320 goto err_put;
10321 }
10322 }
10323
10324 env->used_btf_cnt++;
10325
Hao Luo4976b712020-09-29 16:50:44 -070010326 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010327err_put:
10328 btf_put(btf);
10329 return err;
Hao Luo4976b712020-09-29 16:50:44 -070010330}
10331
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010332static int check_map_prealloc(struct bpf_map *map)
10333{
10334 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070010335 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
10336 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010337 !(map->map_flags & BPF_F_NO_PREALLOC);
10338}
10339
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010340static bool is_tracing_prog_type(enum bpf_prog_type type)
10341{
10342 switch (type) {
10343 case BPF_PROG_TYPE_KPROBE:
10344 case BPF_PROG_TYPE_TRACEPOINT:
10345 case BPF_PROG_TYPE_PERF_EVENT:
10346 case BPF_PROG_TYPE_RAW_TRACEPOINT:
10347 return true;
10348 default:
10349 return false;
10350 }
10351}
10352
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010353static bool is_preallocated_map(struct bpf_map *map)
10354{
10355 if (!check_map_prealloc(map))
10356 return false;
10357 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
10358 return false;
10359 return true;
10360}
10361
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010362static int check_map_prog_compatibility(struct bpf_verifier_env *env,
10363 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010364 struct bpf_prog *prog)
10365
10366{
Udip Pant7e407812020-08-25 16:20:00 -070010367 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010368 /*
10369 * Validate that trace type programs use preallocated hash maps.
10370 *
10371 * For programs attached to PERF events this is mandatory as the
10372 * perf NMI can hit any arbitrary code sequence.
10373 *
10374 * All other trace types using preallocated hash maps are unsafe as
10375 * well because tracepoint or kprobes can be inside locked regions
10376 * of the memory allocator or at a place where a recursion into the
10377 * memory allocator would see inconsistent state.
10378 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010379 * On RT enabled kernels run-time allocation of all trace type
10380 * programs is strictly prohibited due to lock type constraints. On
10381 * !RT kernels it is allowed for backwards compatibility reasons for
10382 * now, but warnings are emitted so developers are made aware of
10383 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010384 */
Udip Pant7e407812020-08-25 16:20:00 -070010385 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
10386 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010387 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070010388 return -EINVAL;
10389 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010010390 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
10391 verbose(env, "trace type programs can only use preallocated hash map\n");
10392 return -EINVAL;
10393 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010010394 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
10395 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 -070010396 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080010397
KP Singh9e7a4d92020-11-06 10:37:39 +000010398 if (map_value_has_spin_lock(map)) {
10399 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
10400 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
10401 return -EINVAL;
10402 }
10403
10404 if (is_tracing_prog_type(prog_type)) {
10405 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
10406 return -EINVAL;
10407 }
10408
10409 if (prog->aux->sleepable) {
10410 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
10411 return -EINVAL;
10412 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010413 }
10414
Jakub Kicinskia3884572018-01-11 20:29:09 -080010415 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070010416 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080010417 verbose(env, "offload device mismatch between prog and map\n");
10418 return -EINVAL;
10419 }
10420
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080010421 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
10422 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
10423 return -EINVAL;
10424 }
10425
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010426 if (prog->aux->sleepable)
10427 switch (map->map_type) {
10428 case BPF_MAP_TYPE_HASH:
10429 case BPF_MAP_TYPE_LRU_HASH:
10430 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010431 case BPF_MAP_TYPE_PERCPU_HASH:
10432 case BPF_MAP_TYPE_PERCPU_ARRAY:
10433 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
10434 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
10435 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010436 if (!is_preallocated_map(map)) {
10437 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080010438 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010439 return -EINVAL;
10440 }
10441 break;
KP Singhba90c2c2021-02-04 19:36:21 +000010442 case BPF_MAP_TYPE_RINGBUF:
10443 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010444 default:
10445 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000010446 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070010447 return -EINVAL;
10448 }
10449
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010450 return 0;
10451}
10452
Roman Gushchinb741f162018-09-28 14:45:43 +000010453static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
10454{
10455 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
10456 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
10457}
10458
Hao Luo4976b712020-09-29 16:50:44 -070010459/* find and rewrite pseudo imm in ld_imm64 instructions:
10460 *
10461 * 1. if it accesses map FD, replace it with actual map pointer.
10462 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
10463 *
10464 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010465 */
Hao Luo4976b712020-09-29 16:50:44 -070010466static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010467{
10468 struct bpf_insn *insn = env->prog->insnsi;
10469 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010470 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010471
Daniel Borkmannf1f77142017-01-13 23:38:15 +010010472 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010010473 if (err)
10474 return err;
10475
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010476 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010477 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070010478 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010479 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070010480 return -EINVAL;
10481 }
10482
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010483 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010484 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010485 struct bpf_map *map;
10486 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010487 u64 addr;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010488
10489 if (i == insn_cnt - 1 || insn[1].code != 0 ||
10490 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
10491 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010492 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010493 return -EINVAL;
10494 }
10495
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010496 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010497 /* valid generic load 64-bit imm */
10498 goto next_insn;
10499
Hao Luo4976b712020-09-29 16:50:44 -070010500 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
10501 aux = &env->insn_aux_data[i];
10502 err = check_pseudo_btf_id(env, insn, aux);
10503 if (err)
10504 return err;
10505 goto next_insn;
10506 }
10507
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010508 /* In final convert_pseudo_ld_imm64() step, this is
10509 * converted into regular 64-bit imm load insn.
10510 */
10511 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD &&
10512 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) ||
10513 (insn[0].src_reg == BPF_PSEUDO_MAP_FD &&
10514 insn[1].imm != 0)) {
10515 verbose(env,
10516 "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010517 return -EINVAL;
10518 }
10519
Daniel Borkmann20182392019-03-04 21:08:53 +010010520 f = fdget(insn[0].imm);
Daniel Borkmannc2101292015-10-29 14:58:07 +010010521 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010522 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010523 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010010524 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010525 return PTR_ERR(map);
10526 }
10527
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010528 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070010529 if (err) {
10530 fdput(f);
10531 return err;
10532 }
10533
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010534 aux = &env->insn_aux_data[i];
10535 if (insn->src_reg == BPF_PSEUDO_MAP_FD) {
10536 addr = (unsigned long)map;
10537 } else {
10538 u32 off = insn[1].imm;
10539
10540 if (off >= BPF_MAX_VAR_OFF) {
10541 verbose(env, "direct value offset of %u is not allowed\n", off);
10542 fdput(f);
10543 return -EINVAL;
10544 }
10545
10546 if (!map->ops->map_direct_value_addr) {
10547 verbose(env, "no direct value access support for this map type\n");
10548 fdput(f);
10549 return -EINVAL;
10550 }
10551
10552 err = map->ops->map_direct_value_addr(map, &addr, off);
10553 if (err) {
10554 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
10555 map->value_size, off);
10556 fdput(f);
10557 return err;
10558 }
10559
10560 aux->map_off = off;
10561 addr += off;
10562 }
10563
10564 insn[0].imm = (u32)addr;
10565 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010566
10567 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010568 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010569 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010570 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010571 fdput(f);
10572 goto next_insn;
10573 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010574 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010575
10576 if (env->used_map_cnt >= MAX_USED_MAPS) {
10577 fdput(f);
10578 return -E2BIG;
10579 }
10580
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010581 /* hold the map. If the program is rejected by verifier,
10582 * the map will be released by release_maps() or it
10583 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070010584 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010585 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080010586 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020010587
10588 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070010589 env->used_maps[env->used_map_cnt++] = map;
10590
Roman Gushchinb741f162018-09-28 14:45:43 +000010591 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010010592 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000010593 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070010594 fdput(f);
10595 return -EBUSY;
10596 }
10597
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010598 fdput(f);
10599next_insn:
10600 insn++;
10601 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010010602 continue;
10603 }
10604
10605 /* Basic sanity check before we invest more work here. */
10606 if (!bpf_opcode_in_insntable(insn->code)) {
10607 verbose(env, "unknown opcode %02x\n", insn->code);
10608 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010609 }
10610 }
10611
10612 /* now all pseudo BPF_LD_IMM64 instructions load valid
10613 * 'struct bpf_map *' into a register instead of user map_fd.
10614 * These pointers will be used later by verifier to validate map access.
10615 */
10616 return 0;
10617}
10618
10619/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010620static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010621{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010010622 __bpf_free_used_maps(env->prog->aux, env->used_maps,
10623 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010624}
10625
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080010626/* drop refcnt of maps used by the rejected program */
10627static void release_btfs(struct bpf_verifier_env *env)
10628{
10629 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
10630 env->used_btf_cnt);
10631}
10632
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010633/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010634static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010635{
10636 struct bpf_insn *insn = env->prog->insnsi;
10637 int insn_cnt = env->prog->len;
10638 int i;
10639
10640 for (i = 0; i < insn_cnt; i++, insn++)
10641 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW))
10642 insn->src_reg = 0;
10643}
10644
Alexei Starovoitov80419022017-03-15 18:26:41 -070010645/* single env->prog->insni[off] instruction was replaced with the range
10646 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
10647 * [0, off) and [off, end) to new locations, so the patched range stays zero
10648 */
Jiong Wangb325fbc2019-05-24 23:25:13 +010010649static int adjust_insn_aux_data(struct bpf_verifier_env *env,
10650 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070010651{
10652 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010653 struct bpf_insn *insn = new_prog->insnsi;
10654 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010655 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070010656
Jiong Wangb325fbc2019-05-24 23:25:13 +010010657 /* aux info at OFF always needs adjustment, no matter fast path
10658 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
10659 * original insn at old prog.
10660 */
10661 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
10662
Alexei Starovoitov80419022017-03-15 18:26:41 -070010663 if (cnt == 1)
10664 return 0;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010665 prog_len = new_prog->len;
Kees Cookfad953c2018-06-12 14:27:37 -070010666 new_data = vzalloc(array_size(prog_len,
10667 sizeof(struct bpf_insn_aux_data)));
Alexei Starovoitov80419022017-03-15 18:26:41 -070010668 if (!new_data)
10669 return -ENOMEM;
10670 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
10671 memcpy(new_data + off + cnt - 1, old_data + off,
10672 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010010673 for (i = off; i < off + cnt - 1; i++) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010674 new_data[i].seen = env->pass_cnt;
Jiong Wangb325fbc2019-05-24 23:25:13 +010010675 new_data[i].zext_dst = insn_has_def32(env, insn + i);
10676 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070010677 env->insn_aux_data = new_data;
10678 vfree(old_data);
10679 return 0;
10680}
10681
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010682static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
10683{
10684 int i;
10685
10686 if (len == 1)
10687 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040010688 /* NOTE: fake 'exit' subprog should be updated as well. */
10689 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000010690 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010691 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040010692 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010693 }
10694}
10695
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010696static void adjust_poke_descs(struct bpf_prog *prog, u32 len)
10697{
10698 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
10699 int i, sz = prog->aux->size_poke_tab;
10700 struct bpf_jit_poke_descriptor *desc;
10701
10702 for (i = 0; i < sz; i++) {
10703 desc = &tab[i];
10704 desc->insn_idx += len - 1;
10705 }
10706}
10707
Alexei Starovoitov80419022017-03-15 18:26:41 -070010708static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
10709 const struct bpf_insn *patch, u32 len)
10710{
10711 struct bpf_prog *new_prog;
10712
10713 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010714 if (IS_ERR(new_prog)) {
10715 if (PTR_ERR(new_prog) == -ERANGE)
10716 verbose(env,
10717 "insn %d cannot be patched due to 16-bit range\n",
10718 env->insn_aux_data[off].orig_idx);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010719 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070010720 }
Jiong Wangb325fbc2019-05-24 23:25:13 +010010721 if (adjust_insn_aux_data(env, new_prog, off, len))
Alexei Starovoitov80419022017-03-15 18:26:41 -070010722 return NULL;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010723 adjust_subprog_starts(env, off, len);
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020010724 adjust_poke_descs(new_prog, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070010725 return new_prog;
10726}
10727
Jakub Kicinski52875a02019-01-22 22:45:20 -080010728static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
10729 u32 off, u32 cnt)
10730{
10731 int i, j;
10732
10733 /* find first prog starting at or after off (first to remove) */
10734 for (i = 0; i < env->subprog_cnt; i++)
10735 if (env->subprog_info[i].start >= off)
10736 break;
10737 /* find first prog starting at or after off + cnt (first to stay) */
10738 for (j = i; j < env->subprog_cnt; j++)
10739 if (env->subprog_info[j].start >= off + cnt)
10740 break;
10741 /* if j doesn't start exactly at off + cnt, we are just removing
10742 * the front of previous prog
10743 */
10744 if (env->subprog_info[j].start != off + cnt)
10745 j--;
10746
10747 if (j > i) {
10748 struct bpf_prog_aux *aux = env->prog->aux;
10749 int move;
10750
10751 /* move fake 'exit' subprog as well */
10752 move = env->subprog_cnt + 1 - j;
10753
10754 memmove(env->subprog_info + i,
10755 env->subprog_info + j,
10756 sizeof(*env->subprog_info) * move);
10757 env->subprog_cnt -= j - i;
10758
10759 /* remove func_info */
10760 if (aux->func_info) {
10761 move = aux->func_info_cnt - j;
10762
10763 memmove(aux->func_info + i,
10764 aux->func_info + j,
10765 sizeof(*aux->func_info) * move);
10766 aux->func_info_cnt -= j - i;
10767 /* func_info->insn_off is set after all code rewrites,
10768 * in adjust_btf_func() - no need to adjust
10769 */
10770 }
10771 } else {
10772 /* convert i from "first prog to remove" to "first to adjust" */
10773 if (env->subprog_info[i].start == off)
10774 i++;
10775 }
10776
10777 /* update fake 'exit' subprog as well */
10778 for (; i <= env->subprog_cnt; i++)
10779 env->subprog_info[i].start -= cnt;
10780
10781 return 0;
10782}
10783
10784static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
10785 u32 cnt)
10786{
10787 struct bpf_prog *prog = env->prog;
10788 u32 i, l_off, l_cnt, nr_linfo;
10789 struct bpf_line_info *linfo;
10790
10791 nr_linfo = prog->aux->nr_linfo;
10792 if (!nr_linfo)
10793 return 0;
10794
10795 linfo = prog->aux->linfo;
10796
10797 /* find first line info to remove, count lines to be removed */
10798 for (i = 0; i < nr_linfo; i++)
10799 if (linfo[i].insn_off >= off)
10800 break;
10801
10802 l_off = i;
10803 l_cnt = 0;
10804 for (; i < nr_linfo; i++)
10805 if (linfo[i].insn_off < off + cnt)
10806 l_cnt++;
10807 else
10808 break;
10809
10810 /* First live insn doesn't match first live linfo, it needs to "inherit"
10811 * last removed linfo. prog is already modified, so prog->len == off
10812 * means no live instructions after (tail of the program was removed).
10813 */
10814 if (prog->len != off && l_cnt &&
10815 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
10816 l_cnt--;
10817 linfo[--i].insn_off = off + cnt;
10818 }
10819
10820 /* remove the line info which refer to the removed instructions */
10821 if (l_cnt) {
10822 memmove(linfo + l_off, linfo + i,
10823 sizeof(*linfo) * (nr_linfo - i));
10824
10825 prog->aux->nr_linfo -= l_cnt;
10826 nr_linfo = prog->aux->nr_linfo;
10827 }
10828
10829 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
10830 for (i = l_off; i < nr_linfo; i++)
10831 linfo[i].insn_off -= cnt;
10832
10833 /* fix up all subprogs (incl. 'exit') which start >= off */
10834 for (i = 0; i <= env->subprog_cnt; i++)
10835 if (env->subprog_info[i].linfo_idx > l_off) {
10836 /* program may have started in the removed region but
10837 * may not be fully removed
10838 */
10839 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
10840 env->subprog_info[i].linfo_idx -= l_cnt;
10841 else
10842 env->subprog_info[i].linfo_idx = l_off;
10843 }
10844
10845 return 0;
10846}
10847
10848static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
10849{
10850 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10851 unsigned int orig_prog_len = env->prog->len;
10852 int err;
10853
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010854 if (bpf_prog_is_dev_bound(env->prog->aux))
10855 bpf_prog_offload_remove_insns(env, off, cnt);
10856
Jakub Kicinski52875a02019-01-22 22:45:20 -080010857 err = bpf_remove_insns(env->prog, off, cnt);
10858 if (err)
10859 return err;
10860
10861 err = adjust_subprog_starts_after_remove(env, off, cnt);
10862 if (err)
10863 return err;
10864
10865 err = bpf_adj_linfo_after_remove(env, off, cnt);
10866 if (err)
10867 return err;
10868
10869 memmove(aux_data + off, aux_data + off + cnt,
10870 sizeof(*aux_data) * (orig_prog_len - off - cnt));
10871
10872 return 0;
10873}
10874
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010875/* The verifier does more data flow analysis than llvm and will not
10876 * explore branches that are dead at run time. Malicious programs can
10877 * have dead code too. Therefore replace all dead at-run-time code
10878 * with 'ja -1'.
10879 *
10880 * Just nops are not optimal, e.g. if they would sit at the end of the
10881 * program and through another bug we would manage to jump there, then
10882 * we'd execute beyond program memory otherwise. Returning exception
10883 * code also wouldn't work since we can have subprogs where the dead
10884 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010885 */
10886static void sanitize_dead_code(struct bpf_verifier_env *env)
10887{
10888 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010889 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010890 struct bpf_insn *insn = env->prog->insnsi;
10891 const int insn_cnt = env->prog->len;
10892 int i;
10893
10894 for (i = 0; i < insn_cnt; i++) {
10895 if (aux_data[i].seen)
10896 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010010897 memcpy(insn + i, &trap, sizeof(trap));
Alexei Starovoitovc1311872017-11-22 16:42:05 -080010898 }
10899}
10900
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010901static bool insn_is_cond_jump(u8 code)
10902{
10903 u8 op;
10904
Jiong Wang092ed092019-01-26 12:26:01 -050010905 if (BPF_CLASS(code) == BPF_JMP32)
10906 return true;
10907
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010908 if (BPF_CLASS(code) != BPF_JMP)
10909 return false;
10910
10911 op = BPF_OP(code);
10912 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
10913}
10914
10915static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
10916{
10917 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10918 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10919 struct bpf_insn *insn = env->prog->insnsi;
10920 const int insn_cnt = env->prog->len;
10921 int i;
10922
10923 for (i = 0; i < insn_cnt; i++, insn++) {
10924 if (!insn_is_cond_jump(insn->code))
10925 continue;
10926
10927 if (!aux_data[i + 1].seen)
10928 ja.off = insn->off;
10929 else if (!aux_data[i + 1 + insn->off].seen)
10930 ja.off = 0;
10931 else
10932 continue;
10933
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080010934 if (bpf_prog_is_dev_bound(env->prog->aux))
10935 bpf_prog_offload_replace_insn(env, i, &ja);
10936
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080010937 memcpy(insn, &ja, sizeof(ja));
10938 }
10939}
10940
Jakub Kicinski52875a02019-01-22 22:45:20 -080010941static int opt_remove_dead_code(struct bpf_verifier_env *env)
10942{
10943 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
10944 int insn_cnt = env->prog->len;
10945 int i, err;
10946
10947 for (i = 0; i < insn_cnt; i++) {
10948 int j;
10949
10950 j = 0;
10951 while (i + j < insn_cnt && !aux_data[i + j].seen)
10952 j++;
10953 if (!j)
10954 continue;
10955
10956 err = verifier_remove_insns(env, i, j);
10957 if (err)
10958 return err;
10959 insn_cnt = env->prog->len;
10960 }
10961
10962 return 0;
10963}
10964
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080010965static int opt_remove_nops(struct bpf_verifier_env *env)
10966{
10967 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
10968 struct bpf_insn *insn = env->prog->insnsi;
10969 int insn_cnt = env->prog->len;
10970 int i, err;
10971
10972 for (i = 0; i < insn_cnt; i++) {
10973 if (memcmp(&insn[i], &ja, sizeof(ja)))
10974 continue;
10975
10976 err = verifier_remove_insns(env, i, 1);
10977 if (err)
10978 return err;
10979 insn_cnt--;
10980 i--;
10981 }
10982
10983 return 0;
10984}
10985
Jiong Wangd6c23082019-05-24 23:25:18 +010010986static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
10987 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010988{
Jiong Wangd6c23082019-05-24 23:25:18 +010010989 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010990 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010010991 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010992 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010993 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010010994 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010995
Jiong Wangd6c23082019-05-24 23:25:18 +010010996 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010010997 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010010998 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
10999 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
11000 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011001 for (i = 0; i < len; i++) {
11002 int adj_idx = i + delta;
11003 struct bpf_insn insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011004 u8 load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011005
Jiong Wangd6c23082019-05-24 23:25:18 +010011006 insn = insns[adj_idx];
11007 if (!aux[adj_idx].zext_dst) {
11008 u8 code, class;
11009 u32 imm_rnd;
11010
11011 if (!rnd_hi32)
11012 continue;
11013
11014 code = insn.code;
11015 class = BPF_CLASS(code);
11016 if (insn_no_def(&insn))
11017 continue;
11018
11019 /* NOTE: arg "reg" (the fourth one) is only used for
11020 * BPF_STX which has been ruled out in above
11021 * check, it is safe to pass NULL here.
11022 */
11023 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) {
11024 if (class == BPF_LD &&
11025 BPF_MODE(code) == BPF_IMM)
11026 i++;
11027 continue;
11028 }
11029
11030 /* ctx load could be transformed into wider load. */
11031 if (class == BPF_LDX &&
11032 aux[adj_idx].ptr_type == PTR_TO_CTX)
11033 continue;
11034
11035 imm_rnd = get_random_int();
11036 rnd_hi32_patch[0] = insn;
11037 rnd_hi32_patch[1].imm = imm_rnd;
11038 rnd_hi32_patch[3].dst_reg = insn.dst_reg;
11039 patch = rnd_hi32_patch;
11040 patch_len = 4;
11041 goto apply_patch_buffer;
11042 }
11043
11044 if (!bpf_jit_needs_zext())
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011045 continue;
11046
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011047 /* zext_dst means that we want to zero-extend whatever register
11048 * the insn defines, which is dst_reg most of the time, with
11049 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH.
11050 */
11051 if (BPF_CLASS(insn.code) == BPF_STX &&
11052 BPF_MODE(insn.code) == BPF_ATOMIC) {
11053 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not
11054 * define any registers, therefore zext_dst cannot be
11055 * set.
11056 */
11057 if (WARN_ON(!(insn.imm & BPF_FETCH)))
11058 return -EINVAL;
11059 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0
11060 : insn.src_reg;
11061 } else {
11062 load_reg = insn.dst_reg;
11063 }
11064
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011065 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010011066 zext_patch[1].dst_reg = load_reg;
11067 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010011068 patch = zext_patch;
11069 patch_len = 2;
11070apply_patch_buffer:
11071 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011072 if (!new_prog)
11073 return -ENOMEM;
11074 env->prog = new_prog;
11075 insns = new_prog->insnsi;
11076 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010011077 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010011078 }
11079
11080 return 0;
11081}
11082
Joe Stringerc64b7982018-10-02 13:35:33 -070011083/* convert load instructions that access fields of a context type into a
11084 * sequence of instructions that access fields of the underlying structure:
11085 * struct __sk_buff -> struct sk_buff
11086 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011087 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011088static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011089{
Jakub Kicinski00176a32017-10-16 16:40:54 -070011090 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011091 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011092 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011093 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011094 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011095 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011096 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011097 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011098
Daniel Borkmannb09928b2018-10-24 22:05:49 +020011099 if (ops->gen_prologue || env->seen_direct_write) {
11100 if (!ops->gen_prologue) {
11101 verbose(env, "bpf verifier is misconfigured\n");
11102 return -EINVAL;
11103 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011104 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
11105 env->prog);
11106 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011107 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011108 return -EINVAL;
11109 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070011110 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011111 if (!new_prog)
11112 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070011113
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011114 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011115 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011116 }
11117 }
11118
Joe Stringerc64b7982018-10-02 13:35:33 -070011119 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011120 return 0;
11121
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011122 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020011123
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011124 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070011125 bpf_convert_ctx_access_t convert_ctx_access;
11126
Daniel Borkmann62c79892017-01-12 11:51:33 +010011127 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
11128 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
11129 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011130 insn->code == (BPF_LDX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011131 type = BPF_READ;
Daniel Borkmann62c79892017-01-12 11:51:33 +010011132 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
11133 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
11134 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
Alexei Starovoitovea2e7ce2016-09-01 18:37:21 -070011135 insn->code == (BPF_STX | BPF_MEM | BPF_DW))
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011136 type = BPF_WRITE;
11137 else
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011138 continue;
11139
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070011140 if (type == BPF_WRITE &&
11141 env->insn_aux_data[i + delta].sanitize_stack_off) {
11142 struct bpf_insn patch[] = {
11143 /* Sanitize suspicious stack slot with zero.
11144 * There are no memory dependencies for this store,
11145 * since it's only using frame pointer and immediate
11146 * constant of zero
11147 */
11148 BPF_ST_MEM(BPF_DW, BPF_REG_FP,
11149 env->insn_aux_data[i + delta].sanitize_stack_off,
11150 0),
11151 /* the original STX instruction will immediately
11152 * overwrite the same stack slot with appropriate value
11153 */
11154 *insn,
11155 };
11156
11157 cnt = ARRAY_SIZE(patch);
11158 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
11159 if (!new_prog)
11160 return -ENOMEM;
11161
11162 delta += cnt - 1;
11163 env->prog = new_prog;
11164 insn = new_prog->insnsi + i + delta;
11165 continue;
11166 }
11167
Joe Stringerc64b7982018-10-02 13:35:33 -070011168 switch (env->insn_aux_data[i + delta].ptr_type) {
11169 case PTR_TO_CTX:
11170 if (!ops->convert_ctx_access)
11171 continue;
11172 convert_ctx_access = ops->convert_ctx_access;
11173 break;
11174 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011175 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070011176 convert_ctx_access = bpf_sock_convert_ctx_access;
11177 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011178 case PTR_TO_TCP_SOCK:
11179 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
11180 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011181 case PTR_TO_XDP_SOCK:
11182 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
11183 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011184 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080011185 if (type == BPF_READ) {
11186 insn->code = BPF_LDX | BPF_PROBE_MEM |
11187 BPF_SIZE((insn)->code);
11188 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070011189 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011190 verbose(env, "Writes through BTF pointers are not allowed\n");
11191 return -EINVAL;
11192 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011193 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011194 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011195 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070011196 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011197
Yonghong Song31fd8582017-06-13 15:52:13 -070011198 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011199 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070011200
11201 /* If the read access is a narrower load of the field,
11202 * convert to a 4/8-byte load, to minimum program type specific
11203 * convert_ctx_access changes. If conversion is successful,
11204 * we will apply proper mask to the result.
11205 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020011206 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011207 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
11208 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070011209 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020011210 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070011211
Daniel Borkmannf96da092017-07-02 02:13:27 +020011212 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011213 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020011214 return -EINVAL;
11215 }
11216
11217 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070011218 if (ctx_field_size == 4)
11219 size_code = BPF_W;
11220 else if (ctx_field_size == 8)
11221 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020011222
Daniel Borkmannbc231052018-06-02 23:06:39 +020011223 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070011224 insn->code = BPF_LDX | BPF_MEM | size_code;
11225 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011226
11227 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070011228 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
11229 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020011230 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
11231 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011232 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011233 return -EINVAL;
11234 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020011235
11236 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020011237 u8 shift = bpf_ctx_narrow_access_offset(
11238 off, size, size_default) * 8;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011239 if (ctx_field_size <= 4) {
11240 if (shift)
11241 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
11242 insn->dst_reg,
11243 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011244 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020011245 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011246 } else {
11247 if (shift)
11248 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
11249 insn->dst_reg,
11250 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070011251 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020011252 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080011253 }
Yonghong Song31fd8582017-06-13 15:52:13 -070011254 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011255
Alexei Starovoitov80419022017-03-15 18:26:41 -070011256 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011257 if (!new_prog)
11258 return -ENOMEM;
11259
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011260 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011261
11262 /* keep walking new program and skip insns we just inserted */
11263 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011264 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011265 }
11266
11267 return 0;
11268}
11269
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011270static int jit_subprogs(struct bpf_verifier_env *env)
11271{
11272 struct bpf_prog *prog = env->prog, **func, *tmp;
11273 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011274 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011275 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011276 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011277 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011278
Jiong Wangf910cef2018-05-02 16:17:17 -040011279 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011280 return 0;
11281
Daniel Borkmann7105e822017-12-20 13:42:57 +010011282 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011283 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011284 continue;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011285 /* Upon error here we cannot fall back to interpreter but
11286 * need a hard reject of the program. Thus -EFAULT is
11287 * propagated in any case.
11288 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011289 subprog = find_subprog(env, i + insn->imm + 1);
11290 if (subprog < 0) {
11291 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
11292 i + insn->imm + 1);
11293 return -EFAULT;
11294 }
11295 /* temporarily remember subprog id inside insn instead of
11296 * aux_data, since next loop will split up all insns into funcs
11297 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011298 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011299 /* remember original imm in case JIT fails and fallback
11300 * to interpreter will be needed
11301 */
11302 env->insn_aux_data[i].call_imm = insn->imm;
11303 /* point imm to __bpf_call_base+1 from JITs point of view */
11304 insn->imm = 1;
11305 }
11306
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011307 err = bpf_prog_alloc_jited_linfo(prog);
11308 if (err)
11309 goto out_undo_insn;
11310
11311 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070011312 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011313 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011314 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011315
Jiong Wangf910cef2018-05-02 16:17:17 -040011316 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011317 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040011318 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011319
11320 len = subprog_end - subprog_start;
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011321 /* BPF_PROG_RUN doesn't call subprogs directly,
11322 * hence main prog stats include the runtime of subprogs.
11323 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080011324 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080011325 */
11326 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011327 if (!func[i])
11328 goto out_free;
11329 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
11330 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011331 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011332 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010011333 if (bpf_prog_calc_tag(func[i]))
11334 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011335 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080011336 func[i]->aux->func_idx = i;
11337 /* the btf and func_info will be freed only at prog->aux */
11338 func[i]->aux->btf = prog->aux->btf;
11339 func[i]->aux->func_info = prog->aux->func_info;
11340
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011341 for (j = 0; j < prog->aux->size_poke_tab; j++) {
11342 u32 insn_idx = prog->aux->poke_tab[j].insn_idx;
11343 int ret;
11344
11345 if (!(insn_idx >= subprog_start &&
11346 insn_idx <= subprog_end))
11347 continue;
11348
11349 ret = bpf_jit_add_poke_descriptor(func[i],
11350 &prog->aux->poke_tab[j]);
11351 if (ret < 0) {
11352 verbose(env, "adding tail call poke descriptor failed\n");
11353 goto out_free;
11354 }
11355
11356 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1;
11357
11358 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map;
11359 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux);
11360 if (ret < 0) {
11361 verbose(env, "tracking tail call prog failed\n");
11362 goto out_free;
11363 }
11364 }
11365
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011366 /* Use bpf_prog_F_tag to indicate functions in stack traces.
11367 * Long term would need debug info to populate names
11368 */
11369 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040011370 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011371 func[i]->jit_requested = 1;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011372 func[i]->aux->linfo = prog->aux->linfo;
11373 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
11374 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
11375 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070011376 num_exentries = 0;
11377 insn = func[i]->insnsi;
11378 for (j = 0; j < func[i]->len; j++, insn++) {
11379 if (BPF_CLASS(insn->code) == BPF_LDX &&
11380 BPF_MODE(insn->code) == BPF_PROBE_MEM)
11381 num_exentries++;
11382 }
11383 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020011384 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011385 func[i] = bpf_int_jit_compile(func[i]);
11386 if (!func[i]->jited) {
11387 err = -ENOTSUPP;
11388 goto out_free;
11389 }
11390 cond_resched();
11391 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011392
11393 /* Untrack main program's aux structs so that during map_poke_run()
11394 * we will not stumble upon the unfilled poke descriptors; each
11395 * of the main program's poke descs got distributed across subprogs
11396 * and got tracked onto map, so we are sure that none of them will
11397 * be missed after the operation below
11398 */
11399 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11400 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11401
11402 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
11403 }
11404
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011405 /* at this point all bpf functions were successfully JITed
11406 * now populate all bpf_calls with correct addresses and
11407 * run last pass of JIT
11408 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011409 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011410 insn = func[i]->insnsi;
11411 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011412 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011413 continue;
11414 subprog = insn->off;
Prashant Bhole0d306c32019-04-16 18:13:01 +090011415 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) -
11416 __bpf_call_base;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011417 }
Sandipan Das2162fed2018-05-24 12:26:45 +053011418
11419 /* we use the aux data to keep a list of the start addresses
11420 * of the JITed images for each function in the program
11421 *
11422 * for some architectures, such as powerpc64, the imm field
11423 * might not be large enough to hold the offset of the start
11424 * address of the callee's JITed image from __bpf_call_base
11425 *
11426 * in such cases, we can lookup the start address of a callee
11427 * by using its subprog id, available from the off field of
11428 * the call instruction, as an index for this list
11429 */
11430 func[i]->aux->func = func;
11431 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011432 }
Jiong Wangf910cef2018-05-02 16:17:17 -040011433 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011434 old_bpf_func = func[i]->bpf_func;
11435 tmp = bpf_int_jit_compile(func[i]);
11436 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
11437 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011438 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011439 goto out_free;
11440 }
11441 cond_resched();
11442 }
11443
11444 /* finally lock prog and jit images for all functions and
11445 * populate kallsysm
11446 */
Jiong Wangf910cef2018-05-02 16:17:17 -040011447 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011448 bpf_prog_lock_ro(func[i]);
11449 bpf_prog_kallsyms_add(func[i]);
11450 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010011451
11452 /* Last step: make now unused interpreter insns from main
11453 * prog consistent for later dump requests, so they can
11454 * later look the same as if they were interpreted only.
11455 */
11456 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011457 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010011458 continue;
11459 insn->off = env->insn_aux_data[i].call_imm;
11460 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053011461 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010011462 }
11463
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011464 prog->jited = 1;
11465 prog->bpf_func = func[0]->bpf_func;
11466 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040011467 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011468 bpf_prog_free_unused_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011469 return 0;
11470out_free:
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011471 for (i = 0; i < env->subprog_cnt; i++) {
11472 if (!func[i])
11473 continue;
11474
11475 for (j = 0; j < func[i]->aux->size_poke_tab; j++) {
11476 map_ptr = func[i]->aux->poke_tab[j].tail_call.map;
11477 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux);
11478 }
11479 bpf_jit_free(func[i]);
11480 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011481 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011482out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011483 /* cleanup main prog to be interpreted */
11484 prog->jit_requested = 0;
11485 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011486 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011487 continue;
11488 insn->off = 0;
11489 insn->imm = env->insn_aux_data[i].call_imm;
11490 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080011491 bpf_prog_free_jited_linfo(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011492 return err;
11493}
11494
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011495static int fixup_call_args(struct bpf_verifier_env *env)
11496{
David S. Miller19d28fb2018-01-11 21:27:54 -050011497#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011498 struct bpf_prog *prog = env->prog;
11499 struct bpf_insn *insn = prog->insnsi;
11500 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050011501#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010011502 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011503
Quentin Monnete4052d02018-10-07 12:56:58 +010011504 if (env->prog->jit_requested &&
11505 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050011506 err = jit_subprogs(env);
11507 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080011508 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020011509 if (err == -EFAULT)
11510 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050011511 }
11512#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011513 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
11514 /* When JIT fails the progs with bpf2bpf calls and tail_calls
11515 * have to be rejected, since interpreter doesn't support them yet.
11516 */
11517 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
11518 return -EINVAL;
11519 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011520 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080011521 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011522 continue;
11523 depth = get_callee_stack_depth(env, insn, i);
11524 if (depth < 0)
11525 return depth;
11526 bpf_patch_call_args(insn, depth);
11527 }
David S. Miller19d28fb2018-01-11 21:27:54 -050011528 err = 0;
11529#endif
11530 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080011531}
11532
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011533/* fixup insn->imm field of bpf_call instructions
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011534 * and inline eligible helpers as explicit sequence of BPF instructions
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011535 *
11536 * this function is called after eBPF program passed verification
11537 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011538static int fixup_bpf_calls(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011539{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011540 struct bpf_prog *prog = env->prog;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011541 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011542 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011543 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011544 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020011545 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011546 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011547 struct bpf_insn insn_buf[16];
11548 struct bpf_prog *new_prog;
11549 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011550 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011551
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011552 for (i = 0; i < insn_cnt; i++, insn++) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011553 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
11554 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11555 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011556 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010011557 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
11558 struct bpf_insn mask_and_div[] = {
11559 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
11560 /* Rx div 0 -> 0 */
11561 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2),
11562 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
11563 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
11564 *insn,
11565 };
11566 struct bpf_insn mask_and_mod[] = {
11567 BPF_MOV32_REG(insn->src_reg, insn->src_reg),
11568 /* Rx mod 0 -> Rx */
11569 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1),
11570 *insn,
11571 };
11572 struct bpf_insn *patchlet;
11573
11574 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
11575 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
11576 patchlet = mask_and_div + (is64 ? 1 : 0);
11577 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0);
11578 } else {
11579 patchlet = mask_and_mod + (is64 ? 1 : 0);
11580 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0);
11581 }
11582
11583 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080011584 if (!new_prog)
11585 return -ENOMEM;
11586
11587 delta += cnt - 1;
11588 env->prog = prog = new_prog;
11589 insn = new_prog->insnsi + i + delta;
11590 continue;
11591 }
11592
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020011593 if (BPF_CLASS(insn->code) == BPF_LD &&
11594 (BPF_MODE(insn->code) == BPF_ABS ||
11595 BPF_MODE(insn->code) == BPF_IND)) {
11596 cnt = env->ops->gen_ld_abs(insn, insn_buf);
11597 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
11598 verbose(env, "bpf verifier is misconfigured\n");
11599 return -EINVAL;
11600 }
11601
11602 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11603 if (!new_prog)
11604 return -ENOMEM;
11605
11606 delta += cnt - 1;
11607 env->prog = prog = new_prog;
11608 insn = new_prog->insnsi + i + delta;
11609 continue;
11610 }
11611
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011612 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
11613 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
11614 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
11615 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
11616 struct bpf_insn insn_buf[16];
11617 struct bpf_insn *patch = &insn_buf[0];
11618 bool issrc, isneg;
11619 u32 off_reg;
11620
11621 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010011622 if (!aux->alu_state ||
11623 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011624 continue;
11625
11626 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
11627 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
11628 BPF_ALU_SANITIZE_SRC;
11629
11630 off_reg = issrc ? insn->src_reg : insn->dst_reg;
11631 if (isneg)
11632 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11633 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1);
11634 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
11635 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
11636 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
11637 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
11638 if (issrc) {
11639 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX,
11640 off_reg);
11641 insn->src_reg = BPF_REG_AX;
11642 } else {
11643 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg,
11644 BPF_REG_AX);
11645 }
11646 if (isneg)
11647 insn->code = insn->code == code_add ?
11648 code_sub : code_add;
11649 *patch++ = *insn;
11650 if (issrc && isneg)
11651 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
11652 cnt = patch - insn_buf;
11653
11654 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11655 if (!new_prog)
11656 return -ENOMEM;
11657
11658 delta += cnt - 1;
11659 env->prog = prog = new_prog;
11660 insn = new_prog->insnsi + i + delta;
11661 continue;
11662 }
11663
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011664 if (insn->code != (BPF_JMP | BPF_CALL))
11665 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080011666 if (insn->src_reg == BPF_PSEUDO_CALL)
11667 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011668
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011669 if (insn->imm == BPF_FUNC_get_route_realm)
11670 prog->dst_needed = 1;
11671 if (insn->imm == BPF_FUNC_get_prandom_u32)
11672 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050011673 if (insn->imm == BPF_FUNC_override_return)
11674 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011675 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040011676 /* If we tail call into other programs, we
11677 * cannot make any assumptions since they can
11678 * be replaced dynamically during runtime in
11679 * the program array.
11680 */
11681 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020011682 if (!allow_tail_call_in_subprogs(env))
11683 prog->aux->stack_depth = MAX_BPF_STACK;
11684 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040011685
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011686 /* mark bpf_tail_call as different opcode to avoid
11687 * conditional branch in the interpeter for every normal
11688 * call and to prevent accidental JITing by JIT compiler
11689 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011690 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011691 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070011692 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011693
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011694 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011695 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010011696 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011697 !bpf_map_key_poisoned(aux) &&
11698 !bpf_map_ptr_poisoned(aux) &&
11699 !bpf_map_ptr_unpriv(aux)) {
11700 struct bpf_jit_poke_descriptor desc = {
11701 .reason = BPF_POKE_REASON_TAIL_CALL,
11702 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
11703 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020011704 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011705 };
11706
11707 ret = bpf_jit_add_poke_descriptor(prog, &desc);
11708 if (ret < 0) {
11709 verbose(env, "adding tail call poke descriptor failed\n");
11710 return ret;
11711 }
11712
11713 insn->imm = ret + 1;
11714 continue;
11715 }
11716
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011717 if (!bpf_map_ptr_unpriv(aux))
11718 continue;
11719
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011720 /* instead of changing every JIT dealing with tail_call
11721 * emit two extra insns:
11722 * if (index >= max_entries) goto out;
11723 * index &= array->index_mask;
11724 * to avoid out-of-bounds cpu speculation
11725 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011726 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000011727 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011728 return -EINVAL;
11729 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011730
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011731 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080011732 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
11733 map_ptr->max_entries, 2);
11734 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
11735 container_of(map_ptr,
11736 struct bpf_array,
11737 map)->index_mask);
11738 insn_buf[2] = *insn;
11739 cnt = 3;
11740 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
11741 if (!new_prog)
11742 return -ENOMEM;
11743
11744 delta += cnt - 1;
11745 env->prog = prog = new_prog;
11746 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011747 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011748 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011749
Daniel Borkmann89c63072017-08-19 03:12:45 +020011750 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020011751 * and other inlining handlers are currently limited to 64 bit
11752 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020011753 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080011754 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020011755 (insn->imm == BPF_FUNC_map_lookup_elem ||
11756 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020011757 insn->imm == BPF_FUNC_map_delete_elem ||
11758 insn->imm == BPF_FUNC_map_push_elem ||
11759 insn->imm == BPF_FUNC_map_pop_elem ||
11760 insn->imm == BPF_FUNC_map_peek_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020011761 aux = &env->insn_aux_data[i + delta];
11762 if (bpf_map_ptr_poisoned(aux))
11763 goto patch_call_imm;
11764
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011765 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020011766 ops = map_ptr->ops;
11767 if (insn->imm == BPF_FUNC_map_lookup_elem &&
11768 ops->map_gen_lookup) {
11769 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020011770 if (cnt == -EOPNOTSUPP)
11771 goto patch_map_ops_generic;
11772 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020011773 verbose(env, "bpf verifier is misconfigured\n");
11774 return -EINVAL;
11775 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011776
Daniel Borkmann09772d92018-06-02 23:06:35 +020011777 new_prog = bpf_patch_insn_data(env, i + delta,
11778 insn_buf, cnt);
11779 if (!new_prog)
11780 return -ENOMEM;
11781
11782 delta += cnt - 1;
11783 env->prog = prog = new_prog;
11784 insn = new_prog->insnsi + i + delta;
11785 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011786 }
11787
Daniel Borkmann09772d92018-06-02 23:06:35 +020011788 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
11789 (void *(*)(struct bpf_map *map, void *key))NULL));
11790 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
11791 (int (*)(struct bpf_map *map, void *key))NULL));
11792 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
11793 (int (*)(struct bpf_map *map, void *key, void *value,
11794 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020011795 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
11796 (int (*)(struct bpf_map *map, void *value,
11797 u64 flags))NULL));
11798 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
11799 (int (*)(struct bpf_map *map, void *value))NULL));
11800 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
11801 (int (*)(struct bpf_map *map, void *value))NULL));
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020011802patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020011803 switch (insn->imm) {
11804 case BPF_FUNC_map_lookup_elem:
11805 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) -
11806 __bpf_call_base;
11807 continue;
11808 case BPF_FUNC_map_update_elem:
11809 insn->imm = BPF_CAST_CALL(ops->map_update_elem) -
11810 __bpf_call_base;
11811 continue;
11812 case BPF_FUNC_map_delete_elem:
11813 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) -
11814 __bpf_call_base;
11815 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020011816 case BPF_FUNC_map_push_elem:
11817 insn->imm = BPF_CAST_CALL(ops->map_push_elem) -
11818 __bpf_call_base;
11819 continue;
11820 case BPF_FUNC_map_pop_elem:
11821 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) -
11822 __bpf_call_base;
11823 continue;
11824 case BPF_FUNC_map_peek_elem:
11825 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) -
11826 __bpf_call_base;
11827 continue;
Daniel Borkmann09772d92018-06-02 23:06:35 +020011828 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011829
Daniel Borkmann09772d92018-06-02 23:06:35 +020011830 goto patch_call_imm;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011831 }
11832
Martin KaFai Lau5576b992020-01-22 15:36:46 -080011833 if (prog->jit_requested && BITS_PER_LONG == 64 &&
11834 insn->imm == BPF_FUNC_jiffies64) {
11835 struct bpf_insn ld_jiffies_addr[2] = {
11836 BPF_LD_IMM64(BPF_REG_0,
11837 (unsigned long)&jiffies),
11838 };
11839
11840 insn_buf[0] = ld_jiffies_addr[0];
11841 insn_buf[1] = ld_jiffies_addr[1];
11842 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
11843 BPF_REG_0, 0);
11844 cnt = 3;
11845
11846 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
11847 cnt);
11848 if (!new_prog)
11849 return -ENOMEM;
11850
11851 delta += cnt - 1;
11852 env->prog = prog = new_prog;
11853 insn = new_prog->insnsi + i + delta;
11854 continue;
11855 }
11856
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070011857patch_call_imm:
Andrey Ignatov5e43f892018-03-30 15:08:00 -070011858 fn = env->ops->get_func_proto(insn->imm, env->prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011859 /* all functions that have prototype and verifier allowed
11860 * programs to call them, must be real in-kernel functions
11861 */
11862 if (!fn->func) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011863 verbose(env,
11864 "kernel subsystem misconfigured func %s#%d\n",
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011865 func_id_name(insn->imm), insn->imm);
11866 return -EFAULT;
11867 }
11868 insn->imm = fn->func - __bpf_call_base;
11869 }
11870
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010011871 /* Since poke tab is now finalized, publish aux to tracker. */
11872 for (i = 0; i < prog->aux->size_poke_tab; i++) {
11873 map_ptr = prog->aux->poke_tab[i].tail_call.map;
11874 if (!map_ptr->ops->map_poke_track ||
11875 !map_ptr->ops->map_poke_untrack ||
11876 !map_ptr->ops->map_poke_run) {
11877 verbose(env, "bpf verifier is misconfigured\n");
11878 return -EINVAL;
11879 }
11880
11881 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
11882 if (ret < 0) {
11883 verbose(env, "tracking tail call prog failed\n");
11884 return ret;
11885 }
11886 }
11887
Alexei Starovoitov79741b32017-03-15 18:26:40 -070011888 return 0;
11889}
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070011890
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011891static void free_states(struct bpf_verifier_env *env)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011892{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011893 struct bpf_verifier_state_list *sl, *sln;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011894 int i;
11895
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011896 sl = env->free_list;
11897 while (sl) {
11898 sln = sl->next;
11899 free_verifier_state(&sl->state, false);
11900 kfree(sl);
11901 sl = sln;
11902 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011903 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011904
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011905 if (!env->explored_states)
11906 return;
11907
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011908 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011909 sl = env->explored_states[i];
11910
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011911 while (sl) {
11912 sln = sl->next;
11913 free_verifier_state(&sl->state, false);
11914 kfree(sl);
11915 sl = sln;
11916 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011917 env->explored_states[i] = NULL;
11918 }
11919}
11920
11921/* The verifier is using insn_aux_data[] to store temporary data during
11922 * verification and to store information for passes that run after the
11923 * verification like dead code sanitization. do_check_common() for subprogram N
11924 * may analyze many other subprograms. sanitize_insn_aux_data() clears all
11925 * temporary data after do_check_common() finds that subprogram N cannot be
11926 * verified independently. pass_cnt counts the number of times
11927 * do_check_common() was run and insn->aux->seen tells the pass number
11928 * insn_aux_data was touched. These variables are compared to clear temporary
11929 * data from failed pass. For testing and experiments do_check_common() can be
11930 * run multiple times even when prior attempt to verify is unsuccessful.
11931 */
11932static void sanitize_insn_aux_data(struct bpf_verifier_env *env)
11933{
11934 struct bpf_insn *insn = env->prog->insnsi;
11935 struct bpf_insn_aux_data *aux;
11936 int i, class;
11937
11938 for (i = 0; i < env->prog->len; i++) {
11939 class = BPF_CLASS(insn[i].code);
11940 if (class != BPF_LDX && class != BPF_STX)
11941 continue;
11942 aux = &env->insn_aux_data[i];
11943 if (aux->seen != env->pass_cnt)
11944 continue;
11945 memset(aux, 0, offsetof(typeof(*aux), orig_idx));
11946 }
11947}
11948
11949static int do_check_common(struct bpf_verifier_env *env, int subprog)
11950{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011951 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011952 struct bpf_verifier_state *state;
11953 struct bpf_reg_state *regs;
11954 int ret, i;
11955
11956 env->prev_linfo = NULL;
11957 env->pass_cnt++;
11958
11959 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
11960 if (!state)
11961 return -ENOMEM;
11962 state->curframe = 0;
11963 state->speculative = false;
11964 state->branches = 1;
11965 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
11966 if (!state->frame[0]) {
11967 kfree(state);
11968 return -ENOMEM;
11969 }
11970 env->cur_state = state;
11971 init_func_state(env, state->frame[0],
11972 BPF_MAIN_FUNC /* callsite */,
11973 0 /* frameno */,
11974 subprog);
11975
11976 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080011977 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011978 ret = btf_prepare_func_args(env, subprog, regs);
11979 if (ret)
11980 goto out;
11981 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
11982 if (regs[i].type == PTR_TO_CTX)
11983 mark_reg_known_zero(env, regs, i);
11984 else if (regs[i].type == SCALAR_VALUE)
11985 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040011986 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
11987 const u32 mem_size = regs[i].mem_size;
11988
11989 mark_reg_known_zero(env, regs, i);
11990 regs[i].mem_size = mem_size;
11991 regs[i].id = ++env->id_gen;
11992 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011993 }
11994 } else {
11995 /* 1st arg to a function */
11996 regs[BPF_REG_1].type = PTR_TO_CTX;
11997 mark_reg_known_zero(env, regs, BPF_REG_1);
11998 ret = btf_check_func_arg_match(env, subprog, regs);
11999 if (ret == -EFAULT)
12000 /* unlikely verifier bug. abort.
12001 * ret == 0 and ret < 0 are sadly acceptable for
12002 * main() function due to backward compatibility.
12003 * Like socket filter program may be written as:
12004 * int bpf_prog(struct pt_regs *ctx)
12005 * and never dereference that ctx in the program.
12006 * 'struct pt_regs' is a type mismatch for socket
12007 * filter that should be using 'struct __sk_buff'.
12008 */
12009 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012010 }
12011
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012012 ret = do_check(env);
12013out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080012014 /* check for NULL is necessary, since cur_state can be freed inside
12015 * do_check() under memory pressure.
12016 */
12017 if (env->cur_state) {
12018 free_verifier_state(env->cur_state, true);
12019 env->cur_state = NULL;
12020 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070012021 while (!pop_stack(env, NULL, NULL, false));
12022 if (!ret && pop_log)
12023 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012024 free_states(env);
12025 if (ret)
12026 /* clean aux data in case subprog was rejected */
12027 sanitize_insn_aux_data(env);
12028 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012029}
12030
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012031/* Verify all global functions in a BPF program one by one based on their BTF.
12032 * All global functions must pass verification. Otherwise the whole program is rejected.
12033 * Consider:
12034 * int bar(int);
12035 * int foo(int f)
12036 * {
12037 * return bar(f);
12038 * }
12039 * int bar(int b)
12040 * {
12041 * ...
12042 * }
12043 * foo() will be verified first for R1=any_scalar_value. During verification it
12044 * will be assumed that bar() already verified successfully and call to bar()
12045 * from foo() will be checked for type match only. Later bar() will be verified
12046 * independently to check that it's safe for R1=any_scalar_value.
12047 */
12048static int do_check_subprogs(struct bpf_verifier_env *env)
12049{
12050 struct bpf_prog_aux *aux = env->prog->aux;
12051 int i, ret;
12052
12053 if (!aux->func_info)
12054 return 0;
12055
12056 for (i = 1; i < env->subprog_cnt; i++) {
12057 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
12058 continue;
12059 env->insn_idx = env->subprog_info[i].start;
12060 WARN_ON_ONCE(env->insn_idx == 0);
12061 ret = do_check_common(env, i);
12062 if (ret) {
12063 return ret;
12064 } else if (env->log.level & BPF_LOG_LEVEL) {
12065 verbose(env,
12066 "Func#%d is safe for any args that match its prototype\n",
12067 i);
12068 }
12069 }
12070 return 0;
12071}
12072
12073static int do_check_main(struct bpf_verifier_env *env)
12074{
12075 int ret;
12076
12077 env->insn_idx = 0;
12078 ret = do_check_common(env, 0);
12079 if (!ret)
12080 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
12081 return ret;
12082}
12083
12084
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012085static void print_verification_stats(struct bpf_verifier_env *env)
12086{
12087 int i;
12088
12089 if (env->log.level & BPF_LOG_STATS) {
12090 verbose(env, "verification time %lld usec\n",
12091 div_u64(env->verification_time, 1000));
12092 verbose(env, "stack depth ");
12093 for (i = 0; i < env->subprog_cnt; i++) {
12094 u32 depth = env->subprog_info[i].stack_depth;
12095
12096 verbose(env, "%d", depth);
12097 if (i + 1 < env->subprog_cnt)
12098 verbose(env, "+");
12099 }
12100 verbose(env, "\n");
12101 }
12102 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
12103 "total_states %d peak_states %d mark_read %d\n",
12104 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
12105 env->max_states_per_insn, env->total_states,
12106 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012107}
12108
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012109static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
12110{
12111 const struct btf_type *t, *func_proto;
12112 const struct bpf_struct_ops *st_ops;
12113 const struct btf_member *member;
12114 struct bpf_prog *prog = env->prog;
12115 u32 btf_id, member_idx;
12116 const char *mname;
12117
12118 btf_id = prog->aux->attach_btf_id;
12119 st_ops = bpf_struct_ops_find(btf_id);
12120 if (!st_ops) {
12121 verbose(env, "attach_btf_id %u is not a supported struct\n",
12122 btf_id);
12123 return -ENOTSUPP;
12124 }
12125
12126 t = st_ops->type;
12127 member_idx = prog->expected_attach_type;
12128 if (member_idx >= btf_type_vlen(t)) {
12129 verbose(env, "attach to invalid member idx %u of struct %s\n",
12130 member_idx, st_ops->name);
12131 return -EINVAL;
12132 }
12133
12134 member = &btf_type_member(t)[member_idx];
12135 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
12136 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
12137 NULL);
12138 if (!func_proto) {
12139 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
12140 mname, member_idx, st_ops->name);
12141 return -EINVAL;
12142 }
12143
12144 if (st_ops->check_member) {
12145 int err = st_ops->check_member(t, member);
12146
12147 if (err) {
12148 verbose(env, "attach to unsupported member %s of struct %s\n",
12149 mname, st_ops->name);
12150 return err;
12151 }
12152 }
12153
12154 prog->aux->attach_func_proto = func_proto;
12155 prog->aux->attach_func_name = mname;
12156 env->ops = st_ops->verifier_ops;
12157
12158 return 0;
12159}
KP Singh6ba43b72020-03-04 20:18:50 +010012160#define SECURITY_PREFIX "security_"
12161
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012162static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010012163{
KP Singh69191752020-03-05 21:49:55 +010012164 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012165 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010012166 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010012167
KP Singh6ba43b72020-03-04 20:18:50 +010012168 return -EINVAL;
12169}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012170
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012171/* list of non-sleepable functions that are otherwise on
12172 * ALLOW_ERROR_INJECTION list
12173 */
12174BTF_SET_START(btf_non_sleepable_error_inject)
12175/* Three functions below can be called from sleepable and non-sleepable context.
12176 * Assume non-sleepable from bpf safety point of view.
12177 */
12178BTF_ID(func, __add_to_page_cache_locked)
12179BTF_ID(func, should_fail_alloc_page)
12180BTF_ID(func, should_failslab)
12181BTF_SET_END(btf_non_sleepable_error_inject)
12182
12183static int check_non_sleepable_error_inject(u32 btf_id)
12184{
12185 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
12186}
12187
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012188int bpf_check_attach_target(struct bpf_verifier_log *log,
12189 const struct bpf_prog *prog,
12190 const struct bpf_prog *tgt_prog,
12191 u32 btf_id,
12192 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070012193{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012194 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012195 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012196 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012197 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012198 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012199 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012200 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012201 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012202
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012203 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012204 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012205 return -EINVAL;
12206 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012207 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012208 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012209 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012210 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
12211 return -EINVAL;
12212 }
12213 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012214 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012215 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012216 return -EINVAL;
12217 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012218 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012219 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012220 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012221 return -EINVAL;
12222 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012223 if (tgt_prog) {
12224 struct bpf_prog_aux *aux = tgt_prog->aux;
12225
12226 for (i = 0; i < aux->func_info_cnt; i++)
12227 if (aux->func_info[i].type_id == btf_id) {
12228 subprog = i;
12229 break;
12230 }
12231 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012232 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012233 return -EINVAL;
12234 }
12235 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012236 if (prog_extension) {
12237 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012238 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012239 "Cannot replace static functions\n");
12240 return -EINVAL;
12241 }
12242 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012243 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012244 "Extension programs should be JITed\n");
12245 return -EINVAL;
12246 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012247 }
12248 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012249 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012250 return -EINVAL;
12251 }
12252 if (tgt_prog->type == prog->type) {
12253 /* Cannot fentry/fexit another fentry/fexit program.
12254 * Cannot attach program extension to another extension.
12255 * It's ok to attach fentry/fexit to extension program.
12256 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012257 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012258 return -EINVAL;
12259 }
12260 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
12261 prog_extension &&
12262 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
12263 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
12264 /* Program extensions can extend all program types
12265 * except fentry/fexit. The reason is the following.
12266 * The fentry/fexit programs are used for performance
12267 * analysis, stats and can be attached to any program
12268 * type except themselves. When extension program is
12269 * replacing XDP function it is necessary to allow
12270 * performance analysis of all functions. Both original
12271 * XDP program and its program extension. Hence
12272 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
12273 * allowed. If extending of fentry/fexit was allowed it
12274 * would be possible to create long call chain
12275 * fentry->extension->fentry->extension beyond
12276 * reasonable stack size. Hence extending fentry is not
12277 * allowed.
12278 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012279 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012280 return -EINVAL;
12281 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012282 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012283 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012284 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012285 return -EINVAL;
12286 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012287 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012288
12289 switch (prog->expected_attach_type) {
12290 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012291 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012292 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012293 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
12294 return -EINVAL;
12295 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070012296 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012297 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012298 btf_id);
12299 return -EINVAL;
12300 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070012301 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012302 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070012303 btf_id, tname);
12304 return -EINVAL;
12305 }
12306 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012307 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012308 if (!btf_type_is_ptr(t))
12309 /* should never happen in valid vmlinux build */
12310 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012311 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012312 if (!btf_type_is_func_proto(t))
12313 /* should never happen in valid vmlinux build */
12314 return -EINVAL;
12315
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012316 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070012317 case BPF_TRACE_ITER:
12318 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012319 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070012320 btf_id);
12321 return -EINVAL;
12322 }
12323 t = btf_type_by_id(btf, t->type);
12324 if (!btf_type_is_func_proto(t))
12325 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012326 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
12327 if (ret)
12328 return ret;
12329 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012330 default:
12331 if (!prog_extension)
12332 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050012333 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010012334 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010012335 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012336 case BPF_TRACE_FENTRY:
12337 case BPF_TRACE_FEXIT:
12338 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012339 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012340 btf_id);
12341 return -EINVAL;
12342 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012343 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012344 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012345 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012346 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012347 if (!btf_type_is_func_proto(t))
12348 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012349
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012350 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
12351 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
12352 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
12353 return -EINVAL;
12354
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012355 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012356 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012357
12358 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012359 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012360 return ret;
12361
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012362 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080012363 if (subprog == 0)
12364 addr = (long) tgt_prog->bpf_func;
12365 else
12366 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012367 } else {
12368 addr = kallsyms_lookup_name(tname);
12369 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012370 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012371 "The address of function %s cannot be found\n",
12372 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012373 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080012374 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080012375 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012376
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012377 if (prog->aux->sleepable) {
12378 ret = -EINVAL;
12379 switch (prog->type) {
12380 case BPF_PROG_TYPE_TRACING:
12381 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
12382 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
12383 */
12384 if (!check_non_sleepable_error_inject(btf_id) &&
12385 within_error_injection_list(addr))
12386 ret = 0;
12387 break;
12388 case BPF_PROG_TYPE_LSM:
12389 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
12390 * Only some of them are sleepable.
12391 */
KP Singh423f1612020-11-13 00:59:29 +000012392 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012393 ret = 0;
12394 break;
12395 default:
12396 break;
12397 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012398 if (ret) {
12399 bpf_log(log, "%s is not sleepable\n", tname);
12400 return ret;
12401 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070012402 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012403 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020012404 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012405 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020012406 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012407 ret = check_attach_modify_return(addr, tname);
12408 if (ret) {
12409 bpf_log(log, "%s() is not modifiable\n", tname);
12410 return ret;
12411 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070012412 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012413
12414 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012415 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012416 tgt_info->tgt_addr = addr;
12417 tgt_info->tgt_name = tname;
12418 tgt_info->tgt_type = t;
12419 return 0;
12420}
12421
12422static int check_attach_btf_id(struct bpf_verifier_env *env)
12423{
12424 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012425 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012426 struct bpf_attach_target_info tgt_info = {};
12427 u32 btf_id = prog->aux->attach_btf_id;
12428 struct bpf_trampoline *tr;
12429 int ret;
12430 u64 key;
12431
12432 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
12433 prog->type != BPF_PROG_TYPE_LSM) {
12434 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
12435 return -EINVAL;
12436 }
12437
12438 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
12439 return check_struct_ops_btf_id(env);
12440
12441 if (prog->type != BPF_PROG_TYPE_TRACING &&
12442 prog->type != BPF_PROG_TYPE_LSM &&
12443 prog->type != BPF_PROG_TYPE_EXT)
12444 return 0;
12445
12446 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
12447 if (ret)
12448 return ret;
12449
12450 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012451 /* to make freplace equivalent to their targets, they need to
12452 * inherit env->ops and expected_attach_type for the rest of the
12453 * verification
12454 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012455 env->ops = bpf_verifier_ops[tgt_prog->type];
12456 prog->expected_attach_type = tgt_prog->expected_attach_type;
12457 }
12458
12459 /* store info about the attachment target that will be used later */
12460 prog->aux->attach_func_proto = tgt_info.tgt_type;
12461 prog->aux->attach_func_name = tgt_info.tgt_name;
12462
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020012463 if (tgt_prog) {
12464 prog->aux->saved_dst_prog_type = tgt_prog->type;
12465 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
12466 }
12467
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012468 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
12469 prog->aux->attach_btf_trace = true;
12470 return 0;
12471 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
12472 if (!bpf_iter_prog_supported(prog))
12473 return -EINVAL;
12474 return 0;
12475 }
12476
12477 if (prog->type == BPF_PROG_TYPE_LSM) {
12478 ret = bpf_lsm_verify_prog(&env->log, prog);
12479 if (ret < 0)
12480 return ret;
12481 }
12482
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080012483 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012484 tr = bpf_trampoline_get(key, &tgt_info);
12485 if (!tr)
12486 return -ENOMEM;
12487
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020012488 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020012489 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070012490}
12491
Alan Maguire76654e62020-09-28 12:31:03 +010012492struct btf *bpf_get_btf_vmlinux(void)
12493{
12494 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
12495 mutex_lock(&bpf_verifier_lock);
12496 if (!btf_vmlinux)
12497 btf_vmlinux = btf_parse_vmlinux();
12498 mutex_unlock(&bpf_verifier_lock);
12499 }
12500 return btf_vmlinux;
12501}
12502
Yonghong Song838e9692018-11-19 15:29:11 -080012503int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
12504 union bpf_attr __user *uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012505{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012506 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012507 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070012508 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012509 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012510 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012511
Arnd Bergmanneba0c922017-11-02 12:05:52 +010012512 /* no program is valid */
12513 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
12514 return -EINVAL;
12515
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012516 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012517 * allocate/free it every time bpf_check() is called
12518 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012519 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012520 if (!env)
12521 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012522 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012523
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012524 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070012525 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012526 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012527 ret = -ENOMEM;
12528 if (!env->insn_aux_data)
12529 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080012530 for (i = 0; i < len; i++)
12531 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012532 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070012533 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012534 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012535
Alan Maguire76654e62020-09-28 12:31:03 +010012536 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012537
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012538 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012539 if (!is_priv)
12540 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012541
12542 if (attr->log_level || attr->log_buf || attr->log_size) {
12543 /* user requested verbose verifier output
12544 * and supplied buffer to store the verification trace
12545 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012546 log->level = attr->log_level;
12547 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
12548 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012549
12550 ret = -EINVAL;
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070012551 /* log attributes have to be sane */
Alexei Starovoitov7a9f5c62019-04-01 21:27:46 -070012552 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 ||
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012553 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012554 goto err_unlock;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012555 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012556
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012557 if (IS_ERR(btf_vmlinux)) {
12558 /* Either gcc or pahole or kernel are broken. */
12559 verbose(env, "in-kernel BTF is malformed\n");
12560 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070012561 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070012562 }
12563
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020012564 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
12565 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070012566 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080012567 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
12568 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012569
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012570 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050012571 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070012572 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070012573 env->bypass_spec_v1 = bpf_bypass_spec_v1();
12574 env->bypass_spec_v4 = bpf_bypass_spec_v4();
12575 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012576
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070012577 if (is_priv)
12578 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
12579
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012580 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Quentin Monneta40a2632018-11-09 13:03:31 +000012581 ret = bpf_prog_offload_verifier_prep(env->prog);
Jakub Kicinskif4e3ec02018-05-03 18:37:11 -070012582 if (ret)
12583 goto skip_full_check;
12584 }
12585
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070012586 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012587 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070012588 GFP_USER);
12589 ret = -ENOMEM;
12590 if (!env->explored_states)
12591 goto skip_full_check;
12592
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012593 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070012594 if (ret < 0)
12595 goto skip_full_check;
12596
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012597 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080012598 if (ret < 0)
12599 goto skip_full_check;
12600
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080012601 ret = check_attach_btf_id(env);
12602 if (ret)
12603 goto skip_full_check;
12604
Hao Luo4976b712020-09-29 16:50:44 -070012605 ret = resolve_pseudo_ldimm64(env);
12606 if (ret < 0)
12607 goto skip_full_check;
12608
Martin KaFai Laud9762e82018-12-13 10:41:48 -080012609 ret = check_cfg(env);
12610 if (ret < 0)
12611 goto skip_full_check;
12612
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012613 ret = do_check_subprogs(env);
12614 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012615
Quentin Monnetc941ce92018-10-07 12:56:47 +010012616 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
12617 ret = bpf_prog_offload_finalize(env);
12618
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012619skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080012620 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012621
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012622 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080012623 ret = check_max_stack_depth(env);
12624
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012625 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012626 if (is_priv) {
12627 if (ret == 0)
12628 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012629 if (ret == 0)
12630 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080012631 if (ret == 0)
12632 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080012633 } else {
12634 if (ret == 0)
12635 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012636 }
12637
Jakub Kicinski9b38c402018-12-19 22:13:06 -080012638 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012639 /* program is valid, convert *(u32*)(ctx + off) accesses */
12640 ret = convert_ctx_accesses(env);
12641
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012642 if (ret == 0)
Alexei Starovoitov79741b32017-03-15 18:26:40 -070012643 ret = fixup_bpf_calls(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070012644
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012645 /* do 32-bit optimization after insn patching has done so those patched
12646 * insns could be handled correctly.
12647 */
Jiong Wangd6c23082019-05-24 23:25:18 +010012648 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
12649 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
12650 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
12651 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012652 }
12653
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012654 if (ret == 0)
12655 ret = fixup_call_args(env);
12656
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070012657 env->verification_time = ktime_get_ns() - start_time;
12658 print_verification_stats(env);
12659
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012660 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012661 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012662 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012663 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012664 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012665 }
12666
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012667 if (ret)
12668 goto err_release_maps;
12669
12670 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012671 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012672 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
12673 sizeof(env->used_maps[0]),
12674 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012675
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012676 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012677 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012678 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012679 }
12680
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012681 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012682 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012683 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012684 }
12685 if (env->used_btf_cnt) {
12686 /* if program passed verifier, update used_btfs in bpf_prog_aux */
12687 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
12688 sizeof(env->used_btfs[0]),
12689 GFP_KERNEL);
12690 if (!env->prog->aux->used_btfs) {
12691 ret = -ENOMEM;
12692 goto err_release_maps;
12693 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012694
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012695 memcpy(env->prog->aux->used_btfs, env->used_btfs,
12696 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
12697 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
12698 }
12699 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012700 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
12701 * bpf_ld_imm64 instructions
12702 */
12703 convert_pseudo_ld_imm64(env);
12704 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070012705
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012706 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080012707
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070012708err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012709 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012710 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070012711 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012712 */
12713 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012714 if (!env->prog->aux->used_btfs)
12715 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020012716
12717 /* extension progs temporarily inherit the attach_type of their targets
12718 for verification purposes, so set it back to zero before returning
12719 */
12720 if (env->prog->type == BPF_PROG_TYPE_EXT)
12721 env->prog->expected_attach_type = 0;
12722
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012723 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012724err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070012725 if (!is_priv)
12726 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012727 vfree(env->insn_aux_data);
12728err_free_env:
12729 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070012730 return ret;
12731}