blob: 72c4a6bbb5bce7fefa5fc36703ca3c2d989e04b4 [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>
Jakub Kicinskiaef2fed2021-12-15 18:55:37 -08007#include <linux/bpf-cgroup.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -07008#include <linux/kernel.h>
9#include <linux/types.h>
10#include <linux/slab.h>
11#include <linux/bpf.h>
Yonghong Song838e9692018-11-19 15:29:11 -080012#include <linux/btf.h>
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013#include <linux/bpf_verifier.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070014#include <linux/filter.h>
15#include <net/netlink.h>
16#include <linux/file.h>
17#include <linux/vmalloc.h>
Thomas Grafebb676d2016-10-27 11:23:51 +020018#include <linux/stringify.h>
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080019#include <linux/bsearch.h>
20#include <linux/sort.h>
Yonghong Songc195651e2018-04-28 22:28:08 -070021#include <linux/perf_event.h>
Martin KaFai Laud9762e82018-12-13 10:41:48 -080022#include <linux/ctype.h>
KP Singh6ba43b72020-03-04 20:18:50 +010023#include <linux/error-injection.h>
KP Singh9e4e01d2020-03-29 01:43:52 +010024#include <linux/bpf_lsm.h>
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070025#include <linux/btf_ids.h>
Alexei Starovoitov51580e72014-09-26 00:17:02 -070026
Jakub Kicinskif4ac7e02017-10-09 10:30:12 -070027#include "disasm.h"
28
Jakub Kicinski00176a32017-10-16 16:40:54 -070029static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
Alexei Starovoitov91cc1a92019-11-14 10:57:15 -080030#define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
Jakub Kicinski00176a32017-10-16 16:40:54 -070031 [_id] = & _name ## _verifier_ops,
32#define BPF_MAP_TYPE(_id, _ops)
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070033#define BPF_LINK_TYPE(_id, _name)
Jakub Kicinski00176a32017-10-16 16:40:54 -070034#include <linux/bpf_types.h>
35#undef BPF_PROG_TYPE
36#undef BPF_MAP_TYPE
Andrii Nakryikof2e10bf2020-04-28 17:16:08 -070037#undef BPF_LINK_TYPE
Jakub Kicinski00176a32017-10-16 16:40:54 -070038};
39
Alexei Starovoitov51580e72014-09-26 00:17:02 -070040/* bpf_check() is a static code analyzer that walks eBPF program
41 * instruction by instruction and updates register/stack state.
42 * All paths of conditional branches are analyzed until 'bpf_exit' insn.
43 *
44 * The first pass is depth-first-search to check that the program is a DAG.
45 * It rejects the following programs:
46 * - larger than BPF_MAXINSNS insns
47 * - if loop is present (detected via back-edge)
48 * - unreachable insns exist (shouldn't be a forest. program = one function)
49 * - out of bounds or malformed jumps
50 * The second pass is all possible path descent from the 1st insn.
Zhen Lei8fb33b62021-05-25 10:56:59 +080051 * Since it's analyzing all paths through the program, the length of the
Gary Lineba38a92017-03-01 16:25:51 +080052 * analysis is limited to 64k insn, which may be hit even if total number of
Alexei Starovoitov51580e72014-09-26 00:17:02 -070053 * insn is less then 4K, but there are too many branches that change stack/regs.
54 * Number of 'branches to be analyzed' is limited to 1k
55 *
56 * On entry to each instruction, each register has a type, and the instruction
57 * changes the types of the registers depending on instruction semantics.
58 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
59 * copied to R1.
60 *
61 * All registers are 64-bit.
62 * R0 - return register
63 * R1-R5 argument passing registers
64 * R6-R9 callee saved registers
65 * R10 - frame pointer read-only
66 *
67 * At the start of BPF program the register R1 contains a pointer to bpf_context
68 * and has type PTR_TO_CTX.
69 *
70 * Verifier tracks arithmetic operations on pointers in case:
71 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
72 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
73 * 1st insn copies R10 (which has FRAME_PTR) type into R1
74 * and 2nd arithmetic instruction is pattern matched to recognize
75 * that it wants to construct a pointer to some element within stack.
76 * So after 2nd insn, the register R1 has type PTR_TO_STACK
77 * (and -20 constant is saved for further stack bounds checking).
78 * Meaning that this reg is a pointer to stack plus known immediate constant.
79 *
Edward Creef1174f72017-08-07 15:26:19 +010080 * Most of the time the registers have SCALAR_VALUE type, which
Alexei Starovoitov51580e72014-09-26 00:17:02 -070081 * means the register has some value, but it's not a valid pointer.
Edward Creef1174f72017-08-07 15:26:19 +010082 * (like pointer plus pointer becomes SCALAR_VALUE type)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070083 *
84 * When verifier sees load or store instructions the type of base register
Joe Stringerc64b7982018-10-02 13:35:33 -070085 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
86 * four pointer types recognized by check_mem_access() function.
Alexei Starovoitov51580e72014-09-26 00:17:02 -070087 *
88 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
89 * and the range of [ptr, ptr + map's value_size) is accessible.
90 *
91 * registers used to pass values to function calls are checked against
92 * function argument constraints.
93 *
94 * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
95 * It means that the register type passed to this function must be
96 * PTR_TO_STACK and it will be used inside the function as
97 * 'pointer to map element key'
98 *
99 * For example the argument constraints for bpf_map_lookup_elem():
100 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
101 * .arg1_type = ARG_CONST_MAP_PTR,
102 * .arg2_type = ARG_PTR_TO_MAP_KEY,
103 *
104 * ret_type says that this function returns 'pointer to map elem value or null'
105 * function expects 1st argument to be a const pointer to 'struct bpf_map' and
106 * 2nd argument should be a pointer to stack, which will be used inside
107 * the helper function as a pointer to map element key.
108 *
109 * On the kernel side the helper function looks like:
110 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
111 * {
112 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
113 * void *key = (void *) (unsigned long) r2;
114 * void *value;
115 *
116 * here kernel can access 'key' and 'map' pointers safely, knowing that
117 * [key, key + map->key_size) bytes are valid and were initialized on
118 * the stack of eBPF program.
119 * }
120 *
121 * Corresponding eBPF program may look like:
122 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR
123 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
124 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP
125 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
126 * here verifier looks at prototype of map_lookup_elem() and sees:
127 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
128 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
129 *
130 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
131 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
132 * and were initialized prior to this call.
133 * If it's ok, then verifier allows this BPF_CALL insn and looks at
134 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
135 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
Zhen Lei8fb33b62021-05-25 10:56:59 +0800136 * returns either pointer to map value or NULL.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700137 *
138 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
139 * insn, the register holding that pointer in the true branch changes state to
140 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
141 * branch. See check_cond_jmp_op().
142 *
143 * After the call R0 is set to return type of the function and registers R1-R5
144 * are set to NOT_INIT to indicate that they are no longer readable.
Joe Stringerfd978bf72018-10-02 13:35:35 -0700145 *
146 * The following reference types represent a potential reference to a kernel
147 * resource which, after first being allocated, must be checked and freed by
148 * the BPF program:
149 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
150 *
151 * When the verifier sees a helper call return a reference type, it allocates a
152 * pointer id for the reference and stores it in the current function state.
153 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
154 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
155 * passes through a NULL-check conditional. For the branch wherein the state is
156 * changed to CONST_IMM, the verifier releases the reference.
Joe Stringer6acc9b42018-10-02 13:35:36 -0700157 *
158 * For each helper function that allocates a reference, such as
159 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
160 * bpf_sk_release(). When a reference type passes into the release function,
161 * the verifier also releases the reference. If any unchecked or unreleased
162 * reference remains at the end of the program, the verifier rejects it.
Alexei Starovoitov51580e72014-09-26 00:17:02 -0700163 */
164
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700165/* verifier_state + insn_idx are pushed to stack when branch is encountered */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100166struct bpf_verifier_stack_elem {
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700167 /* verifer state is 'st'
168 * before processing instruction 'insn_idx'
169 * and after processing instruction 'prev_insn_idx'
170 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100171 struct bpf_verifier_state st;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700172 int insn_idx;
173 int prev_insn_idx;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +0100174 struct bpf_verifier_stack_elem *next;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700175 /* length of verifier log at the time this state was pushed on stack */
176 u32 log_pos;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700177};
178
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -0700179#define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192
Alexei Starovoitovceefbc92018-12-03 22:46:06 -0800180#define BPF_COMPLEXITY_LIMIT_STATES 64
Daniel Borkmann07016152016-04-05 22:33:17 +0200181
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100182#define BPF_MAP_KEY_POISON (1ULL << 63)
183#define BPF_MAP_KEY_SEEN (1ULL << 62)
184
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200185#define BPF_MAP_PTR_UNPRIV 1UL
186#define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \
187 POISON_POINTER_DELTA))
188#define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
189
190static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
191{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100192 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200193}
194
195static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
196{
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100197 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200198}
199
200static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
201 const struct bpf_map *map, bool unpriv)
202{
203 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
204 unpriv |= bpf_map_ptr_unpriv(aux);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +0100205 aux->map_ptr_state = (unsigned long)map |
206 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
207}
208
209static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
210{
211 return aux->map_key_state & BPF_MAP_KEY_POISON;
212}
213
214static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
215{
216 return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
217}
218
219static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
220{
221 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
222}
223
224static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
225{
226 bool poisoned = bpf_map_key_poisoned(aux);
227
228 aux->map_key_state = state | BPF_MAP_KEY_SEEN |
229 (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
Daniel Borkmannc93552c2018-05-24 02:32:53 +0200230}
Martin KaFai Laufad73a12017-03-22 10:00:32 -0700231
Yonghong Song23a2d702021-02-04 15:48:27 -0800232static bool bpf_pseudo_call(const struct bpf_insn *insn)
233{
234 return insn->code == (BPF_JMP | BPF_CALL) &&
235 insn->src_reg == BPF_PSEUDO_CALL;
236}
237
Martin KaFai Laue6ac2452021-03-24 18:51:42 -0700238static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
239{
240 return insn->code == (BPF_JMP | BPF_CALL) &&
241 insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
242}
243
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200244struct bpf_call_arg_meta {
245 struct bpf_map *map_ptr;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200246 bool raw_mode;
Daniel Borkmann36bbef52016-09-20 00:26:13 +0200247 bool pkt_access;
Daniel Borkmann435faee12016-04-13 00:10:51 +0200248 int regno;
249 int access_size;
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700250 int mem_size;
John Fastabend10060502020-03-30 14:36:19 -0700251 u64 msize_max_value;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700252 int ref_obj_id;
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -0700253 int map_uid;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800254 int func_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800255 struct btf *btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700256 u32 btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800257 struct btf *ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700258 u32 ret_btf_id;
Yonghong Song69c087b2021-02-26 12:49:25 -0800259 u32 subprogno;
Daniel Borkmann33ff9822016-04-13 00:10:50 +0200260};
261
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700262struct btf *btf_vmlinux;
263
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700264static DEFINE_MUTEX(bpf_verifier_lock);
265
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800266static const struct bpf_line_info *
267find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
268{
269 const struct bpf_line_info *linfo;
270 const struct bpf_prog *prog;
271 u32 i, nr_linfo;
272
273 prog = env->prog;
274 nr_linfo = prog->aux->nr_linfo;
275
276 if (!nr_linfo || insn_off >= prog->len)
277 return NULL;
278
279 linfo = prog->aux->linfo;
280 for (i = 1; i < nr_linfo; i++)
281 if (insn_off < linfo[i].insn_off)
282 break;
283
284 return &linfo[i - 1];
285}
286
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700287void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt,
288 va_list args)
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700289{
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700290 unsigned int n;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700291
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700292 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args);
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700293
294 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1,
295 "verifier log line truncated - local buffer too short\n");
296
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700297 if (log->level == BPF_LOG_KERNEL) {
Hou Tao436d4042021-12-01 15:34:57 +0800298 bool newline = n > 0 && log->kbuf[n - 1] == '\n';
299
300 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n");
Alexei Starovoitov8580ac92019-10-15 20:24:57 -0700301 return;
302 }
Hou Tao436d4042021-12-01 15:34:57 +0800303
304 n = min(log->len_total - log->len_used - 1, n);
305 log->kbuf[n] = '\0';
Jakub Kicinskia2a7d572017-10-09 10:30:15 -0700306 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1))
307 log->len_used += n;
308 else
309 log->ubuf = NULL;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700310}
Jiri Olsaabe08842018-03-23 11:41:28 +0100311
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -0700312static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos)
313{
314 char zero = 0;
315
316 if (!bpf_verifier_log_needed(log))
317 return;
318
319 log->len_used = new_pos;
320 if (put_user(zero, log->ubuf + new_pos))
321 log->ubuf = NULL;
322}
323
Jiri Olsaabe08842018-03-23 11:41:28 +0100324/* log_level controls verbosity level of eBPF verifier.
325 * bpf_verifier_log_write() is used to dump the verification trace to the log,
326 * so the user can figure out what's wrong with the program
Quentin Monnet430e68d2018-01-10 12:26:06 +0000327 */
Jiri Olsaabe08842018-03-23 11:41:28 +0100328__printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env,
329 const char *fmt, ...)
330{
331 va_list args;
332
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700333 if (!bpf_verifier_log_needed(&env->log))
334 return;
335
Jiri Olsaabe08842018-03-23 11:41:28 +0100336 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700337 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100338 va_end(args);
339}
340EXPORT_SYMBOL_GPL(bpf_verifier_log_write);
341
342__printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
343{
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700344 struct bpf_verifier_env *env = private_data;
Jiri Olsaabe08842018-03-23 11:41:28 +0100345 va_list args;
346
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700347 if (!bpf_verifier_log_needed(&env->log))
348 return;
349
Jiri Olsaabe08842018-03-23 11:41:28 +0100350 va_start(args, fmt);
Martin KaFai Lau77d2e052018-03-24 11:44:23 -0700351 bpf_verifier_vlog(&env->log, fmt, args);
Jiri Olsaabe08842018-03-23 11:41:28 +0100352 va_end(args);
353}
Alexei Starovoitovcbd35702014-09-26 00:17:03 -0700354
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700355__printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
356 const char *fmt, ...)
357{
358 va_list args;
359
360 if (!bpf_verifier_log_needed(log))
361 return;
362
363 va_start(args, fmt);
364 bpf_verifier_vlog(log, fmt, args);
365 va_end(args);
366}
367
Martin KaFai Laud9762e82018-12-13 10:41:48 -0800368static const char *ltrim(const char *s)
369{
370 while (isspace(*s))
371 s++;
372
373 return s;
374}
375
376__printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
377 u32 insn_off,
378 const char *prefix_fmt, ...)
379{
380 const struct bpf_line_info *linfo;
381
382 if (!bpf_verifier_log_needed(&env->log))
383 return;
384
385 linfo = find_linfo(env, insn_off);
386 if (!linfo || linfo == env->prev_linfo)
387 return;
388
389 if (prefix_fmt) {
390 va_list args;
391
392 va_start(args, prefix_fmt);
393 bpf_verifier_vlog(&env->log, prefix_fmt, args);
394 va_end(args);
395 }
396
397 verbose(env, "%s\n",
398 ltrim(btf_name_by_offset(env->prog->aux->btf,
399 linfo->line_off)));
400
401 env->prev_linfo = linfo;
402}
403
Yonghong Songbc2591d2021-02-26 12:49:22 -0800404static void verbose_invalid_scalar(struct bpf_verifier_env *env,
405 struct bpf_reg_state *reg,
406 struct tnum *range, const char *ctx,
407 const char *reg_name)
408{
409 char tn_buf[48];
410
411 verbose(env, "At %s the register %s ", ctx, reg_name);
412 if (!tnum_is_unknown(reg->var_off)) {
413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
414 verbose(env, "has value %s", tn_buf);
415 } else {
416 verbose(env, "has unknown scalar value");
417 }
418 tnum_strn(tn_buf, sizeof(tn_buf), *range);
419 verbose(env, " should have been in %s\n", tn_buf);
420}
421
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200422static bool type_is_pkt_pointer(enum bpf_reg_type type)
423{
424 return type == PTR_TO_PACKET ||
425 type == PTR_TO_PACKET_META;
426}
427
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800428static bool type_is_sk_pointer(enum bpf_reg_type type)
429{
430 return type == PTR_TO_SOCKET ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800431 type == PTR_TO_SOCK_COMMON ||
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700432 type == PTR_TO_TCP_SOCK ||
433 type == PTR_TO_XDP_SOCK;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800434}
435
John Fastabendcac616d2020-05-21 13:07:26 -0700436static bool reg_type_not_null(enum bpf_reg_type type)
437{
438 return type == PTR_TO_SOCKET ||
439 type == PTR_TO_TCP_SOCK ||
440 type == PTR_TO_MAP_VALUE ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800441 type == PTR_TO_MAP_KEY ||
Yonghong Song01c66c42020-06-30 10:12:40 -0700442 type == PTR_TO_SOCK_COMMON;
John Fastabendcac616d2020-05-21 13:07:26 -0700443}
444
Joe Stringer840b9612018-10-02 13:35:32 -0700445static bool reg_type_may_be_null(enum bpf_reg_type type)
446{
Joe Stringerfd978bf72018-10-02 13:35:35 -0700447 return type == PTR_TO_MAP_VALUE_OR_NULL ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800448 type == PTR_TO_SOCKET_OR_NULL ||
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800449 type == PTR_TO_SOCK_COMMON_OR_NULL ||
Yonghong Songb121b342020-05-09 10:59:12 -0700450 type == PTR_TO_TCP_SOCK_OR_NULL ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700451 type == PTR_TO_BTF_ID_OR_NULL ||
Yonghong Songafbf21d2020-07-23 11:41:11 -0700452 type == PTR_TO_MEM_OR_NULL ||
453 type == PTR_TO_RDONLY_BUF_OR_NULL ||
454 type == PTR_TO_RDWR_BUF_OR_NULL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700455}
456
Alexei Starovoitovd83525c2019-01-31 15:40:04 -0800457static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
458{
459 return reg->type == PTR_TO_MAP_VALUE &&
460 map_value_has_spin_lock(reg->map_ptr);
461}
462
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700463static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type)
464{
465 return type == PTR_TO_SOCKET ||
466 type == PTR_TO_SOCKET_OR_NULL ||
467 type == PTR_TO_TCP_SOCK ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700468 type == PTR_TO_TCP_SOCK_OR_NULL ||
469 type == PTR_TO_MEM ||
470 type == PTR_TO_MEM_OR_NULL;
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700471}
472
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700473static bool arg_type_may_be_refcounted(enum bpf_arg_type type)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700474{
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700475 return type == ARG_PTR_TO_SOCK_COMMON;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700476}
477
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100478static bool arg_type_may_be_null(enum bpf_arg_type type)
479{
480 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL ||
481 type == ARG_PTR_TO_MEM_OR_NULL ||
482 type == ARG_PTR_TO_CTX_OR_NULL ||
483 type == ARG_PTR_TO_SOCKET_OR_NULL ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800484 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL ||
485 type == ARG_PTR_TO_STACK_OR_NULL;
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +0100486}
487
Joe Stringerfd978bf72018-10-02 13:35:35 -0700488/* Determine whether the function releases some resources allocated by another
489 * function call. The first reference type argument will be assumed to be
490 * released by release_reference().
491 */
492static bool is_release_function(enum bpf_func_id func_id)
493{
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700494 return func_id == BPF_FUNC_sk_release ||
495 func_id == BPF_FUNC_ringbuf_submit ||
496 func_id == BPF_FUNC_ringbuf_discard;
Joe Stringer840b9612018-10-02 13:35:32 -0700497}
498
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200499static bool may_be_acquire_function(enum bpf_func_id func_id)
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800500{
501 return func_id == BPF_FUNC_sk_lookup_tcp ||
Lorenz Baueredbf8c02019-03-22 09:54:01 +0800502 func_id == BPF_FUNC_sk_lookup_udp ||
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200503 func_id == BPF_FUNC_skc_lookup_tcp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700504 func_id == BPF_FUNC_map_lookup_elem ||
505 func_id == BPF_FUNC_ringbuf_reserve;
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200506}
507
508static bool is_acquire_function(enum bpf_func_id func_id,
509 const struct bpf_map *map)
510{
511 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512
513 if (func_id == BPF_FUNC_sk_lookup_tcp ||
514 func_id == BPF_FUNC_sk_lookup_udp ||
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700515 func_id == BPF_FUNC_skc_lookup_tcp ||
516 func_id == BPF_FUNC_ringbuf_reserve)
Jakub Sitnicki64d85292020-04-29 20:11:52 +0200517 return true;
518
519 if (func_id == BPF_FUNC_map_lookup_elem &&
520 (map_type == BPF_MAP_TYPE_SOCKMAP ||
521 map_type == BPF_MAP_TYPE_SOCKHASH))
522 return true;
523
524 return false;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800525}
526
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700527static bool is_ptr_cast_function(enum bpf_func_id func_id)
528{
529 return func_id == BPF_FUNC_tcp_sock ||
Martin KaFai Lau1df8f552020-09-24 17:03:50 -0700530 func_id == BPF_FUNC_sk_fullsock ||
531 func_id == BPF_FUNC_skc_to_tcp_sock ||
532 func_id == BPF_FUNC_skc_to_tcp6_sock ||
533 func_id == BPF_FUNC_skc_to_udp6_sock ||
534 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
535 func_id == BPF_FUNC_skc_to_tcp_request_sock;
Martin KaFai Lau1b986582019-03-12 10:23:02 -0700536}
537
Brendan Jackman39491862021-03-04 18:56:46 -0800538static bool is_cmpxchg_insn(const struct bpf_insn *insn)
539{
540 return BPF_CLASS(insn->code) == BPF_STX &&
541 BPF_MODE(insn->code) == BPF_ATOMIC &&
542 insn->imm == BPF_CMPXCHG;
543}
544
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700545/* string representation of 'enum bpf_reg_type' */
546static const char * const reg_type_str[] = {
547 [NOT_INIT] = "?",
Edward Creef1174f72017-08-07 15:26:19 +0100548 [SCALAR_VALUE] = "inv",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700549 [PTR_TO_CTX] = "ctx",
550 [CONST_PTR_TO_MAP] = "map_ptr",
551 [PTR_TO_MAP_VALUE] = "map_value",
552 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700553 [PTR_TO_STACK] = "fp",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700554 [PTR_TO_PACKET] = "pkt",
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200555 [PTR_TO_PACKET_META] = "pkt_meta",
Alexei Starovoitov969bf052016-05-05 19:49:10 -0700556 [PTR_TO_PACKET_END] = "pkt_end",
Petar Penkovd58e4682018-09-14 07:46:18 -0700557 [PTR_TO_FLOW_KEYS] = "flow_keys",
Joe Stringerc64b7982018-10-02 13:35:33 -0700558 [PTR_TO_SOCKET] = "sock",
559 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null",
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800560 [PTR_TO_SOCK_COMMON] = "sock_common",
561 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null",
Martin KaFai Lau655a51e2019-02-09 23:22:24 -0800562 [PTR_TO_TCP_SOCK] = "tcp_sock",
563 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null",
Matt Mullins9df1c282019-04-26 11:49:47 -0700564 [PTR_TO_TP_BUFFER] = "tp_buffer",
Jonathan Lemonfada7fd2019-06-06 13:59:40 -0700565 [PTR_TO_XDP_SOCK] = "xdp_sock",
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700566 [PTR_TO_BTF_ID] = "ptr_",
Yonghong Songb121b342020-05-09 10:59:12 -0700567 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_",
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700568 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_",
Andrii Nakryiko457f4432020-05-29 00:54:20 -0700569 [PTR_TO_MEM] = "mem",
570 [PTR_TO_MEM_OR_NULL] = "mem_or_null",
Yonghong Songafbf21d2020-07-23 11:41:11 -0700571 [PTR_TO_RDONLY_BUF] = "rdonly_buf",
572 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null",
573 [PTR_TO_RDWR_BUF] = "rdwr_buf",
574 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null",
Yonghong Song69c087b2021-02-26 12:49:25 -0800575 [PTR_TO_FUNC] = "func",
576 [PTR_TO_MAP_KEY] = "map_key",
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700577};
578
Edward Cree8efea212018-08-22 20:02:44 +0100579static char slot_type_char[] = {
580 [STACK_INVALID] = '?',
581 [STACK_SPILL] = 'r',
582 [STACK_MISC] = 'm',
583 [STACK_ZERO] = '0',
584};
585
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800586static void print_liveness(struct bpf_verifier_env *env,
587 enum bpf_reg_liveness live)
588{
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800589 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800590 verbose(env, "_");
591 if (live & REG_LIVE_READ)
592 verbose(env, "r");
593 if (live & REG_LIVE_WRITTEN)
594 verbose(env, "w");
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -0800595 if (live & REG_LIVE_DONE)
596 verbose(env, "D");
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800597}
598
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800599static struct bpf_func_state *func(struct bpf_verifier_env *env,
600 const struct bpf_reg_state *reg)
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700601{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800602 struct bpf_verifier_state *cur = env->cur_state;
603
604 return cur->frame[reg->frameno];
605}
606
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800607static const char *kernel_type_name(const struct btf* btf, u32 id)
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700608{
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800609 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -0700610}
611
Christy Lee0f55f9e2021-12-16 13:33:56 -0800612static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
613{
614 env->scratched_regs |= 1U << regno;
615}
616
617static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
618{
619 env->scratched_stack_slots |= 1UL << spi;
620}
621
622static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
623{
624 return (env->scratched_regs >> regno) & 1;
625}
626
627static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
628{
629 return (env->scratched_stack_slots >> regno) & 1;
630}
631
632static bool verifier_state_scratched(const struct bpf_verifier_env *env)
633{
634 return env->scratched_regs || env->scratched_stack_slots;
635}
636
637static void mark_verifier_state_clean(struct bpf_verifier_env *env)
638{
639 env->scratched_regs = 0U;
640 env->scratched_stack_slots = 0UL;
641}
642
643/* Used for printing the entire verifier state. */
644static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
645{
646 env->scratched_regs = ~0U;
647 env->scratched_stack_slots = ~0UL;
648}
649
Martin KaFai Lau27113c52021-09-21 17:49:34 -0700650/* The reg state of a pointer or a bounded scalar was saved when
651 * it was spilled to the stack.
652 */
653static bool is_spilled_reg(const struct bpf_stack_state *stack)
654{
655 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
656}
657
Martin KaFai Lau354e8f12021-09-21 17:49:41 -0700658static void scrub_spilled_slot(u8 *stype)
659{
660 if (*stype != STACK_INVALID)
661 *stype = STACK_MISC;
662}
663
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800664static void print_verifier_state(struct bpf_verifier_env *env,
Christy Lee0f55f9e2021-12-16 13:33:56 -0800665 const struct bpf_func_state *state,
666 bool print_all)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800667{
668 const struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700669 enum bpf_reg_type t;
670 int i;
671
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800672 if (state->frameno)
673 verbose(env, " frame%d:", state->frameno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700674 for (i = 0; i < MAX_BPF_REG; i++) {
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -0700675 reg = &state->regs[i];
676 t = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700677 if (t == NOT_INIT)
678 continue;
Christy Lee0f55f9e2021-12-16 13:33:56 -0800679 if (!print_all && !reg_scratched(env, i))
680 continue;
Alexei Starovoitov4e920242017-11-30 21:31:36 -0800681 verbose(env, " R%d", i);
682 print_liveness(env, reg->live);
683 verbose(env, "=%s", reg_type_str[t]);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700684 if (t == SCALAR_VALUE && reg->precise)
685 verbose(env, "P");
Edward Creef1174f72017-08-07 15:26:19 +0100686 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
687 tnum_is_const(reg->var_off)) {
688 /* reg->off should be 0 for SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700689 verbose(env, "%lld", reg->var_off.value + reg->off);
Edward Creef1174f72017-08-07 15:26:19 +0100690 } else {
Hao Luoeaa6bcb2020-09-29 16:50:47 -0700691 if (t == PTR_TO_BTF_ID ||
692 t == PTR_TO_BTF_ID_OR_NULL ||
693 t == PTR_TO_PERCPU_BTF_ID)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -0800694 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id));
Martin KaFai Laucba368c2019-03-18 10:37:13 -0700695 verbose(env, "(id=%d", reg->id);
696 if (reg_type_may_be_refcounted_or_null(t))
697 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id);
Edward Creef1174f72017-08-07 15:26:19 +0100698 if (t != SCALAR_VALUE)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700699 verbose(env, ",off=%d", reg->off);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +0200700 if (type_is_pkt_pointer(t))
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700701 verbose(env, ",r=%d", reg->range);
Edward Creef1174f72017-08-07 15:26:19 +0100702 else if (t == CONST_PTR_TO_MAP ||
Yonghong Song69c087b2021-02-26 12:49:25 -0800703 t == PTR_TO_MAP_KEY ||
Edward Creef1174f72017-08-07 15:26:19 +0100704 t == PTR_TO_MAP_VALUE ||
705 t == PTR_TO_MAP_VALUE_OR_NULL)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700706 verbose(env, ",ks=%d,vs=%d",
Edward Creef1174f72017-08-07 15:26:19 +0100707 reg->map_ptr->key_size,
708 reg->map_ptr->value_size);
Edward Cree7d1238f2017-08-07 15:26:56 +0100709 if (tnum_is_const(reg->var_off)) {
710 /* Typically an immediate SCALAR_VALUE, but
711 * could be a pointer whose offset is too big
712 * for reg->off
713 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700714 verbose(env, ",imm=%llx", reg->var_off.value);
Edward Cree7d1238f2017-08-07 15:26:56 +0100715 } else {
716 if (reg->smin_value != reg->umin_value &&
717 reg->smin_value != S64_MIN)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700718 verbose(env, ",smin_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100719 (long long)reg->smin_value);
720 if (reg->smax_value != reg->umax_value &&
721 reg->smax_value != S64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700722 verbose(env, ",smax_value=%lld",
Edward Cree7d1238f2017-08-07 15:26:56 +0100723 (long long)reg->smax_value);
724 if (reg->umin_value != 0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700725 verbose(env, ",umin_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100726 (unsigned long long)reg->umin_value);
727 if (reg->umax_value != U64_MAX)
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700728 verbose(env, ",umax_value=%llu",
Edward Cree7d1238f2017-08-07 15:26:56 +0100729 (unsigned long long)reg->umax_value);
730 if (!tnum_is_unknown(reg->var_off)) {
731 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +0100732
Edward Cree7d1238f2017-08-07 15:26:56 +0100733 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700734 verbose(env, ",var_off=%s", tn_buf);
Edward Cree7d1238f2017-08-07 15:26:56 +0100735 }
John Fastabend3f50f132020-03-30 14:36:39 -0700736 if (reg->s32_min_value != reg->smin_value &&
737 reg->s32_min_value != S32_MIN)
738 verbose(env, ",s32_min_value=%d",
739 (int)(reg->s32_min_value));
740 if (reg->s32_max_value != reg->smax_value &&
741 reg->s32_max_value != S32_MAX)
742 verbose(env, ",s32_max_value=%d",
743 (int)(reg->s32_max_value));
744 if (reg->u32_min_value != reg->umin_value &&
745 reg->u32_min_value != U32_MIN)
746 verbose(env, ",u32_min_value=%d",
747 (int)(reg->u32_min_value));
748 if (reg->u32_max_value != reg->umax_value &&
749 reg->u32_max_value != U32_MAX)
750 verbose(env, ",u32_max_value=%d",
751 (int)(reg->u32_max_value));
Edward Creef1174f72017-08-07 15:26:19 +0100752 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700753 verbose(env, ")");
Edward Creef1174f72017-08-07 15:26:19 +0100754 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700755 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700756 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Edward Cree8efea212018-08-22 20:02:44 +0100757 char types_buf[BPF_REG_SIZE + 1];
758 bool valid = false;
759 int j;
760
761 for (j = 0; j < BPF_REG_SIZE; j++) {
762 if (state->stack[i].slot_type[j] != STACK_INVALID)
763 valid = true;
764 types_buf[j] = slot_type_char[
765 state->stack[i].slot_type[j]];
766 }
767 types_buf[BPF_REG_SIZE] = 0;
768 if (!valid)
769 continue;
Christy Lee0f55f9e2021-12-16 13:33:56 -0800770 if (!print_all && !stack_slot_scratched(env, i))
771 continue;
Edward Cree8efea212018-08-22 20:02:44 +0100772 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
773 print_liveness(env, state->stack[i].spilled_ptr.live);
Martin KaFai Lau27113c52021-09-21 17:49:34 -0700774 if (is_spilled_reg(&state->stack[i])) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700775 reg = &state->stack[i].spilled_ptr;
776 t = reg->type;
777 verbose(env, "=%s", reg_type_str[t]);
778 if (t == SCALAR_VALUE && reg->precise)
779 verbose(env, "P");
780 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
781 verbose(env, "%lld", reg->var_off.value + reg->off);
782 } else {
Edward Cree8efea212018-08-22 20:02:44 +0100783 verbose(env, "=%s", types_buf);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700784 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700785 }
Joe Stringerfd978bf72018-10-02 13:35:35 -0700786 if (state->acquired_refs && state->refs[0].id) {
787 verbose(env, " refs=%d", state->refs[0].id);
788 for (i = 1; i < state->acquired_refs; i++)
789 if (state->refs[i].id)
790 verbose(env, ",%d", state->refs[i].id);
791 }
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -0700792 if (state->in_callback_fn)
793 verbose(env, " cb");
794 if (state->in_async_callback_fn)
795 verbose(env, " async_cb");
Jakub Kicinski61bd5212017-10-09 10:30:11 -0700796 verbose(env, "\n");
Christy Lee0f55f9e2021-12-16 13:33:56 -0800797 mark_verifier_state_clean(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -0700798}
799
Christy Lee2e576642021-12-16 19:42:45 -0800800static inline u32 vlog_alignment(u32 pos)
801{
802 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
803 BPF_LOG_MIN_ALIGNMENT) - pos - 1;
804}
805
806static void print_insn_state(struct bpf_verifier_env *env,
807 const struct bpf_func_state *state)
808{
809 if (env->prev_log_len && env->prev_log_len == env->log.len_used) {
810 /* remove new line character */
811 bpf_vlog_reset(&env->log, env->prev_log_len - 1);
812 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' ');
813 } else {
814 verbose(env, "%d:", env->insn_idx);
815 }
816 print_verifier_state(env, state, false);
817}
818
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100819/* copy array src of length n * size bytes to dst. dst is reallocated if it's too
820 * small to hold src. This is different from krealloc since we don't want to preserve
821 * the contents of dst.
822 *
823 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
824 * not be allocated.
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700825 */
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100826static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700827{
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100828 size_t bytes;
829
830 if (ZERO_OR_NULL_PTR(src))
831 goto out;
832
833 if (unlikely(check_mul_overflow(n, size, &bytes)))
834 return NULL;
835
836 if (ksize(dst) < bytes) {
837 kfree(dst);
838 dst = kmalloc_track_caller(bytes, flags);
839 if (!dst)
840 return NULL;
841 }
842
843 memcpy(dst, src, bytes);
844out:
845 return dst ? dst : ZERO_SIZE_PTR;
846}
847
848/* resize an array from old_n items to new_n items. the array is reallocated if it's too
849 * small to hold new_n items. new items are zeroed out if the array grows.
850 *
851 * Contrary to krealloc_array, does not free arr if new_n is zero.
852 */
853static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
854{
855 if (!new_n || old_n == new_n)
856 goto out;
857
858 arr = krealloc_array(arr, new_n, size, GFP_KERNEL);
859 if (!arr)
860 return NULL;
861
862 if (new_n > old_n)
863 memset(arr + old_n * size, 0, (new_n - old_n) * size);
864
865out:
866 return arr ? arr : ZERO_SIZE_PTR;
867}
868
869static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
870{
871 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
872 sizeof(struct bpf_reference_state), GFP_KERNEL);
873 if (!dst->refs)
874 return -ENOMEM;
875
876 dst->acquired_refs = src->acquired_refs;
877 return 0;
878}
879
880static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
881{
882 size_t n = src->allocated_stack / BPF_REG_SIZE;
883
884 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
885 GFP_KERNEL);
886 if (!dst->stack)
887 return -ENOMEM;
888
889 dst->allocated_stack = src->allocated_stack;
890 return 0;
891}
892
893static int resize_reference_state(struct bpf_func_state *state, size_t n)
894{
895 state->refs = realloc_array(state->refs, state->acquired_refs, n,
896 sizeof(struct bpf_reference_state));
897 if (!state->refs)
898 return -ENOMEM;
899
900 state->acquired_refs = n;
901 return 0;
902}
903
904static int grow_stack_state(struct bpf_func_state *state, int size)
905{
906 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
907
908 if (old_n >= n)
909 return 0;
910
911 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
912 if (!state->stack)
913 return -ENOMEM;
914
915 state->allocated_stack = size;
916 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700917}
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700918
Joe Stringerfd978bf72018-10-02 13:35:35 -0700919/* Acquire a pointer id from the env and update the state->refs to include
920 * this new pointer reference.
921 * On success, returns a valid pointer id to associate with the register
922 * On failure, returns a negative errno.
923 */
924static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
925{
926 struct bpf_func_state *state = cur_func(env);
927 int new_ofs = state->acquired_refs;
928 int id, err;
929
Lorenz Bauerc69431a2021-04-29 14:46:54 +0100930 err = resize_reference_state(state, state->acquired_refs + 1);
Joe Stringerfd978bf72018-10-02 13:35:35 -0700931 if (err)
932 return err;
933 id = ++env->id_gen;
934 state->refs[new_ofs].id = id;
935 state->refs[new_ofs].insn_idx = insn_idx;
936
937 return id;
938}
939
940/* release function corresponding to acquire_reference_state(). Idempotent. */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800941static int release_reference_state(struct bpf_func_state *state, int ptr_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -0700942{
943 int i, last_idx;
944
Joe Stringerfd978bf72018-10-02 13:35:35 -0700945 last_idx = state->acquired_refs - 1;
946 for (i = 0; i < state->acquired_refs; i++) {
947 if (state->refs[i].id == ptr_id) {
948 if (last_idx && i != last_idx)
949 memcpy(&state->refs[i], &state->refs[last_idx],
950 sizeof(*state->refs));
951 memset(&state->refs[last_idx], 0, sizeof(*state->refs));
952 state->acquired_refs--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700953 return 0;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700954 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700955 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -0800956 return -EINVAL;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700957}
958
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800959static void free_func_state(struct bpf_func_state *state)
960{
Alexei Starovoitov58963512018-01-08 07:51:17 -0800961 if (!state)
962 return;
Joe Stringerfd978bf72018-10-02 13:35:35 -0700963 kfree(state->refs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800964 kfree(state->stack);
965 kfree(state);
966}
967
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700968static void clear_jmp_history(struct bpf_verifier_state *state)
969{
970 kfree(state->jmp_history);
971 state->jmp_history = NULL;
972 state->jmp_history_cnt = 0;
973}
974
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700975static void free_verifier_state(struct bpf_verifier_state *state,
976 bool free_self)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700977{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800978 int i;
979
980 for (i = 0; i <= state->curframe; i++) {
981 free_func_state(state->frame[i]);
982 state->frame[i] = NULL;
983 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -0700984 clear_jmp_history(state);
Alexei Starovoitov1969db42017-11-01 00:08:04 -0700985 if (free_self)
986 kfree(state);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700987}
988
989/* copy verifier state from src to dst growing dst stack space
990 * when necessary to accommodate larger src stack
991 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -0800992static int copy_func_state(struct bpf_func_state *dst,
993 const struct bpf_func_state *src)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -0700994{
995 int err;
996
Joe Stringerfd978bf72018-10-02 13:35:35 -0700997 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
998 err = copy_reference_state(dst, src);
999 if (err)
1000 return err;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001001 return copy_stack_state(dst, src);
1002}
1003
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001004static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1005 const struct bpf_verifier_state *src)
1006{
1007 struct bpf_func_state *dst;
1008 int i, err;
1009
Lorenz Bauer06ab6a52021-04-29 14:46:55 +01001010 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1011 src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1012 GFP_USER);
1013 if (!dst_state->jmp_history)
1014 return -ENOMEM;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001015 dst_state->jmp_history_cnt = src->jmp_history_cnt;
1016
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001017 /* if dst has more stack frames then src frame, free them */
1018 for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1019 free_func_state(dst_state->frame[i]);
1020 dst_state->frame[i] = NULL;
1021 }
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001022 dst_state->speculative = src->speculative;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001023 dst_state->curframe = src->curframe;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08001024 dst_state->active_spin_lock = src->active_spin_lock;
Alexei Starovoitov25897262019-06-15 12:12:20 -07001025 dst_state->branches = src->branches;
1026 dst_state->parent = src->parent;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07001027 dst_state->first_insn_idx = src->first_insn_idx;
1028 dst_state->last_insn_idx = src->last_insn_idx;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001029 for (i = 0; i <= src->curframe; i++) {
1030 dst = dst_state->frame[i];
1031 if (!dst) {
1032 dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1033 if (!dst)
1034 return -ENOMEM;
1035 dst_state->frame[i] = dst;
1036 }
1037 err = copy_func_state(dst, src->frame[i]);
1038 if (err)
1039 return err;
1040 }
1041 return 0;
1042}
1043
Alexei Starovoitov25897262019-06-15 12:12:20 -07001044static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1045{
1046 while (st) {
1047 u32 br = --st->branches;
1048
1049 /* WARN_ON(br > 1) technically makes sense here,
1050 * but see comment in push_stack(), hence:
1051 */
1052 WARN_ONCE((int)br < 0,
1053 "BUG update_branch_counts:branches_to_explore=%d\n",
1054 br);
1055 if (br)
1056 break;
1057 st = st->parent;
1058 }
1059}
1060
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001061static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001062 int *insn_idx, bool pop_log)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001063{
1064 struct bpf_verifier_state *cur = env->cur_state;
1065 struct bpf_verifier_stack_elem *elem, *head = env->head;
1066 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001067
1068 if (env->head == NULL)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001069 return -ENOENT;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001070
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001071 if (cur) {
1072 err = copy_verifier_state(cur, &head->st);
1073 if (err)
1074 return err;
1075 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001076 if (pop_log)
1077 bpf_vlog_reset(&env->log, head->log_pos);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001078 if (insn_idx)
1079 *insn_idx = head->insn_idx;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001080 if (prev_insn_idx)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001081 *prev_insn_idx = head->prev_insn_idx;
1082 elem = head->next;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001083 free_verifier_state(&head->st, false);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001084 kfree(head);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001085 env->head = elem;
1086 env->stack_size--;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001087 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001088}
1089
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001090static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001091 int insn_idx, int prev_insn_idx,
1092 bool speculative)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001093{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001094 struct bpf_verifier_state *cur = env->cur_state;
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01001095 struct bpf_verifier_stack_elem *elem;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001096 int err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001097
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07001098 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001099 if (!elem)
1100 goto err;
1101
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001102 elem->insn_idx = insn_idx;
1103 elem->prev_insn_idx = prev_insn_idx;
1104 elem->next = env->head;
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001105 elem->log_pos = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001106 env->head = elem;
1107 env->stack_size++;
Alexei Starovoitov1969db42017-11-01 00:08:04 -07001108 err = copy_verifier_state(&elem->st, cur);
1109 if (err)
1110 goto err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01001111 elem->st.speculative |= speculative;
Alexei Starovoitovb285fcb2019-05-21 20:14:19 -07001112 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1113 verbose(env, "The sequence of %d jumps is too complex.\n",
1114 env->stack_size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001115 goto err;
1116 }
Alexei Starovoitov25897262019-06-15 12:12:20 -07001117 if (elem->st.parent) {
1118 ++elem->st.parent->branches;
1119 /* WARN_ON(branches > 2) technically makes sense here,
1120 * but
1121 * 1. speculative states will bump 'branches' for non-branch
1122 * instructions
1123 * 2. is_state_visited() heuristics may decide not to create
1124 * a new state for a sequence of branches and all such current
1125 * and cloned states will be pointing to a single parent state
1126 * which might have large 'branches' count.
1127 */
1128 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001129 return &elem->st;
1130err:
Alexei Starovoitov58963512018-01-08 07:51:17 -08001131 free_verifier_state(env->cur_state, true);
1132 env->cur_state = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001133 /* pop all elements and return */
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -07001134 while (!pop_stack(env, NULL, NULL, false));
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001135 return NULL;
1136}
1137
1138#define CALLER_SAVED_REGS 6
1139static const int caller_saved[CALLER_SAVED_REGS] = {
1140 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1141};
1142
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001143static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1144 struct bpf_reg_state *reg);
Edward Creef1174f72017-08-07 15:26:19 +01001145
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001146/* This helper doesn't clear reg->id */
1147static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
Edward Creeb03c9f92017-08-07 15:26:36 +01001148{
Edward Creeb03c9f92017-08-07 15:26:36 +01001149 reg->var_off = tnum_const(imm);
1150 reg->smin_value = (s64)imm;
1151 reg->smax_value = (s64)imm;
1152 reg->umin_value = imm;
1153 reg->umax_value = imm;
John Fastabend3f50f132020-03-30 14:36:39 -07001154
1155 reg->s32_min_value = (s32)imm;
1156 reg->s32_max_value = (s32)imm;
1157 reg->u32_min_value = (u32)imm;
1158 reg->u32_max_value = (u32)imm;
1159}
1160
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07001161/* Mark the unknown part of a register (variable offset or scalar value) as
1162 * known to have the value @imm.
1163 */
1164static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1165{
1166 /* Clear id, off, and union(map_ptr, range) */
1167 memset(((u8 *)reg) + sizeof(reg->type), 0,
1168 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1169 ___mark_reg_known(reg, imm);
1170}
1171
John Fastabend3f50f132020-03-30 14:36:39 -07001172static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1173{
1174 reg->var_off = tnum_const_subreg(reg->var_off, imm);
1175 reg->s32_min_value = (s32)imm;
1176 reg->s32_max_value = (s32)imm;
1177 reg->u32_min_value = (u32)imm;
1178 reg->u32_max_value = (u32)imm;
Edward Creeb03c9f92017-08-07 15:26:36 +01001179}
1180
Edward Creef1174f72017-08-07 15:26:19 +01001181/* Mark the 'variable offset' part of a register as zero. This should be
1182 * used only on registers holding a pointer type.
1183 */
1184static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1185{
Edward Creeb03c9f92017-08-07 15:26:36 +01001186 __mark_reg_known(reg, 0);
Edward Creef1174f72017-08-07 15:26:19 +01001187}
1188
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001189static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1190{
1191 __mark_reg_known(reg, 0);
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08001192 reg->type = SCALAR_VALUE;
1193}
1194
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001195static void mark_reg_known_zero(struct bpf_verifier_env *env,
1196 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001197{
1198 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001199 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01001200 /* Something bad happened, let's kill all regs */
1201 for (regno = 0; regno < MAX_BPF_REG; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001202 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001203 return;
1204 }
1205 __mark_reg_known_zero(regs + regno);
1206}
1207
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001208static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1209{
1210 switch (reg->type) {
1211 case PTR_TO_MAP_VALUE_OR_NULL: {
1212 const struct bpf_map *map = reg->map_ptr;
1213
1214 if (map->inner_map_meta) {
1215 reg->type = CONST_PTR_TO_MAP;
1216 reg->map_ptr = map->inner_map_meta;
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -07001217 /* transfer reg's id which is unique for every map_lookup_elem
1218 * as UID of the inner map.
1219 */
Alexei Starovoitov34d11a42021-11-10 09:25:56 -08001220 if (map_value_has_timer(map->inner_map_meta))
1221 reg->map_uid = reg->id;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001222 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1223 reg->type = PTR_TO_XDP_SOCK;
1224 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1225 map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1226 reg->type = PTR_TO_SOCKET;
1227 } else {
1228 reg->type = PTR_TO_MAP_VALUE;
1229 }
1230 break;
1231 }
1232 case PTR_TO_SOCKET_OR_NULL:
1233 reg->type = PTR_TO_SOCKET;
1234 break;
1235 case PTR_TO_SOCK_COMMON_OR_NULL:
1236 reg->type = PTR_TO_SOCK_COMMON;
1237 break;
1238 case PTR_TO_TCP_SOCK_OR_NULL:
1239 reg->type = PTR_TO_TCP_SOCK;
1240 break;
1241 case PTR_TO_BTF_ID_OR_NULL:
1242 reg->type = PTR_TO_BTF_ID;
1243 break;
1244 case PTR_TO_MEM_OR_NULL:
1245 reg->type = PTR_TO_MEM;
1246 break;
1247 case PTR_TO_RDONLY_BUF_OR_NULL:
1248 reg->type = PTR_TO_RDONLY_BUF;
1249 break;
1250 case PTR_TO_RDWR_BUF_OR_NULL:
1251 reg->type = PTR_TO_RDWR_BUF;
1252 break;
1253 default:
Dan Carpenter33ccec52021-02-17 10:45:25 +03001254 WARN_ONCE(1, "unknown nullable register type");
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04001255 }
1256}
1257
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02001258static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1259{
1260 return type_is_pkt_pointer(reg->type);
1261}
1262
1263static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
1264{
1265 return reg_is_pkt_pointer(reg) ||
1266 reg->type == PTR_TO_PACKET_END;
1267}
1268
1269/* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
1270static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
1271 enum bpf_reg_type which)
1272{
1273 /* The register can already have a range from prior markings.
1274 * This is fine as long as it hasn't been advanced from its
1275 * origin.
1276 */
1277 return reg->type == which &&
1278 reg->id == 0 &&
1279 reg->off == 0 &&
1280 tnum_equals_const(reg->var_off, 0);
1281}
1282
John Fastabend3f50f132020-03-30 14:36:39 -07001283/* Reset the min/max bounds of a register */
1284static void __mark_reg_unbounded(struct bpf_reg_state *reg)
1285{
1286 reg->smin_value = S64_MIN;
1287 reg->smax_value = S64_MAX;
1288 reg->umin_value = 0;
1289 reg->umax_value = U64_MAX;
1290
1291 reg->s32_min_value = S32_MIN;
1292 reg->s32_max_value = S32_MAX;
1293 reg->u32_min_value = 0;
1294 reg->u32_max_value = U32_MAX;
1295}
1296
1297static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
1298{
1299 reg->smin_value = S64_MIN;
1300 reg->smax_value = S64_MAX;
1301 reg->umin_value = 0;
1302 reg->umax_value = U64_MAX;
1303}
1304
1305static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
1306{
1307 reg->s32_min_value = S32_MIN;
1308 reg->s32_max_value = S32_MAX;
1309 reg->u32_min_value = 0;
1310 reg->u32_max_value = U32_MAX;
1311}
1312
1313static void __update_reg32_bounds(struct bpf_reg_state *reg)
1314{
1315 struct tnum var32_off = tnum_subreg(reg->var_off);
1316
1317 /* min signed is max(sign bit) | min(other bits) */
1318 reg->s32_min_value = max_t(s32, reg->s32_min_value,
1319 var32_off.value | (var32_off.mask & S32_MIN));
1320 /* max signed is min(sign bit) | max(other bits) */
1321 reg->s32_max_value = min_t(s32, reg->s32_max_value,
1322 var32_off.value | (var32_off.mask & S32_MAX));
1323 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
1324 reg->u32_max_value = min(reg->u32_max_value,
1325 (u32)(var32_off.value | var32_off.mask));
1326}
1327
1328static void __update_reg64_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001329{
1330 /* min signed is max(sign bit) | min(other bits) */
1331 reg->smin_value = max_t(s64, reg->smin_value,
1332 reg->var_off.value | (reg->var_off.mask & S64_MIN));
1333 /* max signed is min(sign bit) | max(other bits) */
1334 reg->smax_value = min_t(s64, reg->smax_value,
1335 reg->var_off.value | (reg->var_off.mask & S64_MAX));
1336 reg->umin_value = max(reg->umin_value, reg->var_off.value);
1337 reg->umax_value = min(reg->umax_value,
1338 reg->var_off.value | reg->var_off.mask);
1339}
1340
John Fastabend3f50f132020-03-30 14:36:39 -07001341static void __update_reg_bounds(struct bpf_reg_state *reg)
1342{
1343 __update_reg32_bounds(reg);
1344 __update_reg64_bounds(reg);
1345}
1346
Edward Creeb03c9f92017-08-07 15:26:36 +01001347/* Uses signed min/max values to inform unsigned, and vice-versa */
John Fastabend3f50f132020-03-30 14:36:39 -07001348static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
1349{
1350 /* Learn sign from signed bounds.
1351 * If we cannot cross the sign boundary, then signed and unsigned bounds
1352 * are the same, so combine. This works even in the negative case, e.g.
1353 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1354 */
1355 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
1356 reg->s32_min_value = reg->u32_min_value =
1357 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1358 reg->s32_max_value = reg->u32_max_value =
1359 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1360 return;
1361 }
1362 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1363 * boundary, so we must be careful.
1364 */
1365 if ((s32)reg->u32_max_value >= 0) {
1366 /* Positive. We can't learn anything from the smin, but smax
1367 * is positive, hence safe.
1368 */
1369 reg->s32_min_value = reg->u32_min_value;
1370 reg->s32_max_value = reg->u32_max_value =
1371 min_t(u32, reg->s32_max_value, reg->u32_max_value);
1372 } else if ((s32)reg->u32_min_value < 0) {
1373 /* Negative. We can't learn anything from the smax, but smin
1374 * is negative, hence safe.
1375 */
1376 reg->s32_min_value = reg->u32_min_value =
1377 max_t(u32, reg->s32_min_value, reg->u32_min_value);
1378 reg->s32_max_value = reg->u32_max_value;
1379 }
1380}
1381
1382static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001383{
1384 /* Learn sign from signed bounds.
1385 * If we cannot cross the sign boundary, then signed and unsigned bounds
1386 * are the same, so combine. This works even in the negative case, e.g.
1387 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
1388 */
1389 if (reg->smin_value >= 0 || reg->smax_value < 0) {
1390 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1391 reg->umin_value);
1392 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1393 reg->umax_value);
1394 return;
1395 }
1396 /* Learn sign from unsigned bounds. Signed bounds cross the sign
1397 * boundary, so we must be careful.
1398 */
1399 if ((s64)reg->umax_value >= 0) {
1400 /* Positive. We can't learn anything from the smin, but smax
1401 * is positive, hence safe.
1402 */
1403 reg->smin_value = reg->umin_value;
1404 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
1405 reg->umax_value);
1406 } else if ((s64)reg->umin_value < 0) {
1407 /* Negative. We can't learn anything from the smax, but smin
1408 * is negative, hence safe.
1409 */
1410 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
1411 reg->umin_value);
1412 reg->smax_value = reg->umax_value;
1413 }
1414}
1415
John Fastabend3f50f132020-03-30 14:36:39 -07001416static void __reg_deduce_bounds(struct bpf_reg_state *reg)
1417{
1418 __reg32_deduce_bounds(reg);
1419 __reg64_deduce_bounds(reg);
1420}
1421
Edward Creeb03c9f92017-08-07 15:26:36 +01001422/* Attempts to improve var_off based on unsigned min/max information */
1423static void __reg_bound_offset(struct bpf_reg_state *reg)
1424{
John Fastabend3f50f132020-03-30 14:36:39 -07001425 struct tnum var64_off = tnum_intersect(reg->var_off,
1426 tnum_range(reg->umin_value,
1427 reg->umax_value));
1428 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off),
1429 tnum_range(reg->u32_min_value,
1430 reg->u32_max_value));
1431
1432 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01001433}
1434
John Fastabend3f50f132020-03-30 14:36:39 -07001435static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
Edward Creeb03c9f92017-08-07 15:26:36 +01001436{
John Fastabend3f50f132020-03-30 14:36:39 -07001437 reg->umin_value = reg->u32_min_value;
1438 reg->umax_value = reg->u32_max_value;
1439 /* Attempt to pull 32-bit signed bounds into 64-bit bounds
1440 * but must be positive otherwise set to worse case bounds
1441 * and refine later from tnum.
1442 */
John Fastabend3a71dc32020-05-29 10:28:40 -07001443 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0)
John Fastabend3f50f132020-03-30 14:36:39 -07001444 reg->smax_value = reg->s32_max_value;
1445 else
1446 reg->smax_value = U32_MAX;
John Fastabend3a71dc32020-05-29 10:28:40 -07001447 if (reg->s32_min_value >= 0)
1448 reg->smin_value = reg->s32_min_value;
1449 else
1450 reg->smin_value = 0;
John Fastabend3f50f132020-03-30 14:36:39 -07001451}
1452
1453static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
1454{
1455 /* special case when 64-bit register has upper 32-bit register
1456 * zeroed. Typically happens after zext or <<32, >>32 sequence
1457 * allowing us to use 32-bit bounds directly,
1458 */
1459 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
1460 __reg_assign_32_into_64(reg);
1461 } else {
1462 /* Otherwise the best we can do is push lower 32bit known and
1463 * unknown bits into register (var_off set from jmp logic)
1464 * then learn as much as possible from the 64-bit tnum
1465 * known and unknown bits. The previous smin/smax bounds are
1466 * invalid here because of jmp32 compare so mark them unknown
1467 * so they do not impact tnum bounds calculation.
1468 */
1469 __mark_reg64_unbounded(reg);
1470 __update_reg_bounds(reg);
1471 }
1472
1473 /* Intersecting with the old var_off might have improved our bounds
1474 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1475 * then new var_off is (0; 0x7f...fc) which improves our umax.
1476 */
1477 __reg_deduce_bounds(reg);
1478 __reg_bound_offset(reg);
1479 __update_reg_bounds(reg);
1480}
1481
1482static bool __reg64_bound_s32(s64 a)
1483{
Alexei Starovoitov388e2c02021-11-01 15:21:52 -07001484 return a >= S32_MIN && a <= S32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001485}
1486
1487static bool __reg64_bound_u32(u64 a)
1488{
Alexei Starovoitovb9979db2021-11-01 15:21:51 -07001489 return a >= U32_MIN && a <= U32_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07001490}
1491
1492static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
1493{
1494 __mark_reg32_unbounded(reg);
1495
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001496 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001497 reg->s32_min_value = (s32)reg->smin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001498 reg->s32_max_value = (s32)reg->smax_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01001499 }
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001500 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
John Fastabend3f50f132020-03-30 14:36:39 -07001501 reg->u32_min_value = (u32)reg->umin_value;
John Fastabend3f50f132020-03-30 14:36:39 -07001502 reg->u32_max_value = (u32)reg->umax_value;
Daniel Borkmann10bf4e82021-04-23 13:59:55 +00001503 }
John Fastabend3f50f132020-03-30 14:36:39 -07001504
1505 /* Intersecting with the old var_off might have improved our bounds
1506 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
1507 * then new var_off is (0; 0x7f...fc) which improves our umax.
1508 */
1509 __reg_deduce_bounds(reg);
1510 __reg_bound_offset(reg);
1511 __update_reg_bounds(reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01001512}
1513
Edward Creef1174f72017-08-07 15:26:19 +01001514/* Mark a register as having a completely unknown (scalar) value. */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001515static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1516 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001517{
Alexei Starovoitova9c676b2018-09-04 19:13:44 -07001518 /*
1519 * Clear type, id, off, and union(map_ptr, range) and
1520 * padding between 'type' and union
1521 */
1522 memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
Edward Creef1174f72017-08-07 15:26:19 +01001523 reg->type = SCALAR_VALUE;
Edward Creef1174f72017-08-07 15:26:19 +01001524 reg->var_off = tnum_unknown;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001525 reg->frameno = 0;
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07001526 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable;
Edward Creeb03c9f92017-08-07 15:26:36 +01001527 __mark_reg_unbounded(reg);
Edward Creef1174f72017-08-07 15:26:19 +01001528}
1529
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001530static void mark_reg_unknown(struct bpf_verifier_env *env,
1531 struct bpf_reg_state *regs, u32 regno)
Edward Creef1174f72017-08-07 15:26:19 +01001532{
1533 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001534 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001535 /* Something bad happened, let's kill all regs except FP */
1536 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001537 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001538 return;
1539 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001540 __mark_reg_unknown(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001541}
1542
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001543static void __mark_reg_not_init(const struct bpf_verifier_env *env,
1544 struct bpf_reg_state *reg)
Edward Creef1174f72017-08-07 15:26:19 +01001545{
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001546 __mark_reg_unknown(env, reg);
Edward Creef1174f72017-08-07 15:26:19 +01001547 reg->type = NOT_INIT;
1548}
1549
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001550static void mark_reg_not_init(struct bpf_verifier_env *env,
1551 struct bpf_reg_state *regs, u32 regno)
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001552{
Edward Creef1174f72017-08-07 15:26:19 +01001553 if (WARN_ON(regno >= MAX_BPF_REG)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001554 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
Alexei Starovoitov19ceb412017-11-30 21:31:37 -08001555 /* Something bad happened, let's kill all regs except FP */
1556 for (regno = 0; regno < BPF_REG_FP; regno++)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001557 __mark_reg_not_init(env, regs + regno);
Edward Creef1174f72017-08-07 15:26:19 +01001558 return;
1559 }
Daniel Borkmannf54c7892019-12-22 23:37:40 +01001560 __mark_reg_not_init(env, regs + regno);
Daniel Borkmanna9789ef2017-05-25 01:05:06 +02001561}
1562
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001563static void mark_btf_ld_reg(struct bpf_verifier_env *env,
1564 struct bpf_reg_state *regs, u32 regno,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001565 enum bpf_reg_type reg_type,
1566 struct btf *btf, u32 btf_id)
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001567{
1568 if (reg_type == SCALAR_VALUE) {
1569 mark_reg_unknown(env, regs, regno);
1570 return;
1571 }
1572 mark_reg_known_zero(env, regs, regno);
1573 regs[regno].type = PTR_TO_BTF_ID;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08001574 regs[regno].btf = btf;
Andrey Ignatov41c48f32020-06-19 14:11:43 -07001575 regs[regno].btf_id = btf_id;
1576}
1577
Jiong Wang5327ed32019-05-24 23:25:12 +01001578#define DEF_NOT_SUBREG (0)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001579static void init_reg_state(struct bpf_verifier_env *env,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001580 struct bpf_func_state *state)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001581{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001582 struct bpf_reg_state *regs = state->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001583 int i;
1584
Edward Creedc503a82017-08-15 20:34:35 +01001585 for (i = 0; i < MAX_BPF_REG; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001586 mark_reg_not_init(env, regs, i);
Edward Creedc503a82017-08-15 20:34:35 +01001587 regs[i].live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +01001588 regs[i].parent = NULL;
Jiong Wang5327ed32019-05-24 23:25:12 +01001589 regs[i].subreg_def = DEF_NOT_SUBREG;
Edward Creedc503a82017-08-15 20:34:35 +01001590 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001591
1592 /* frame pointer */
Edward Creef1174f72017-08-07 15:26:19 +01001593 regs[BPF_REG_FP].type = PTR_TO_STACK;
Jakub Kicinski61bd5212017-10-09 10:30:11 -07001594 mark_reg_known_zero(env, regs, BPF_REG_FP);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001595 regs[BPF_REG_FP].frameno = state->frameno;
Daniel Borkmann6760bf22016-12-18 01:52:59 +01001596}
1597
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001598#define BPF_MAIN_FUNC (-1)
1599static void init_func_state(struct bpf_verifier_env *env,
1600 struct bpf_func_state *state,
1601 int callsite, int frameno, int subprogno)
1602{
1603 state->callsite = callsite;
1604 state->frameno = frameno;
1605 state->subprogno = subprogno;
1606 init_reg_state(env, state);
Christy Lee0f55f9e2021-12-16 13:33:56 -08001607 mark_verifier_state_scratched(env);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08001608}
1609
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07001610/* Similar to push_stack(), but for async callbacks */
1611static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
1612 int insn_idx, int prev_insn_idx,
1613 int subprog)
1614{
1615 struct bpf_verifier_stack_elem *elem;
1616 struct bpf_func_state *frame;
1617
1618 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1619 if (!elem)
1620 goto err;
1621
1622 elem->insn_idx = insn_idx;
1623 elem->prev_insn_idx = prev_insn_idx;
1624 elem->next = env->head;
1625 elem->log_pos = env->log.len_used;
1626 env->head = elem;
1627 env->stack_size++;
1628 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1629 verbose(env,
1630 "The sequence of %d jumps is too complex for async cb.\n",
1631 env->stack_size);
1632 goto err;
1633 }
1634 /* Unlike push_stack() do not copy_verifier_state().
1635 * The caller state doesn't matter.
1636 * This is async callback. It starts in a fresh stack.
1637 * Initialize it similar to do_check_common().
1638 */
1639 elem->st.branches = 1;
1640 frame = kzalloc(sizeof(*frame), GFP_KERNEL);
1641 if (!frame)
1642 goto err;
1643 init_func_state(env, frame,
1644 BPF_MAIN_FUNC /* callsite */,
1645 0 /* frameno within this callchain */,
1646 subprog /* subprog number within this prog */);
1647 elem->st.frame[0] = frame;
1648 return &elem->st;
1649err:
1650 free_verifier_state(env->cur_state, true);
1651 env->cur_state = NULL;
1652 /* pop all elements and return */
1653 while (!pop_stack(env, NULL, NULL, false));
1654 return NULL;
1655}
1656
1657
Alexei Starovoitov17a52672014-09-26 00:17:06 -07001658enum reg_arg_type {
1659 SRC_OP, /* register is used as source operand */
1660 DST_OP, /* register is used as destination operand */
1661 DST_OP_NO_MARK /* same as above, check only, don't mark */
1662};
1663
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001664static int cmp_subprogs(const void *a, const void *b)
1665{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001666 return ((struct bpf_subprog_info *)a)->start -
1667 ((struct bpf_subprog_info *)b)->start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001668}
1669
1670static int find_subprog(struct bpf_verifier_env *env, int off)
1671{
Jiong Wang9c8105b2018-05-02 16:17:18 -04001672 struct bpf_subprog_info *p;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001673
Jiong Wang9c8105b2018-05-02 16:17:18 -04001674 p = bsearch(&off, env->subprog_info, env->subprog_cnt,
1675 sizeof(env->subprog_info[0]), cmp_subprogs);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001676 if (!p)
1677 return -ENOENT;
Jiong Wang9c8105b2018-05-02 16:17:18 -04001678 return p - env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001679
1680}
1681
1682static int add_subprog(struct bpf_verifier_env *env, int off)
1683{
1684 int insn_cnt = env->prog->len;
1685 int ret;
1686
1687 if (off >= insn_cnt || off < 0) {
1688 verbose(env, "call to invalid destination\n");
1689 return -EINVAL;
1690 }
1691 ret = find_subprog(env, off);
1692 if (ret >= 0)
Yonghong Song282a0f42021-02-26 12:49:24 -08001693 return ret;
Jiong Wang4cb3d992018-05-02 16:17:19 -04001694 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001695 verbose(env, "too many subprograms\n");
1696 return -E2BIG;
1697 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001698 /* determine subprog starts. The end is one before the next starts */
Jiong Wang9c8105b2018-05-02 16:17:18 -04001699 env->subprog_info[env->subprog_cnt++].start = off;
1700 sort(env->subprog_info, env->subprog_cnt,
1701 sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
Yonghong Song282a0f42021-02-26 12:49:24 -08001702 return env->subprog_cnt - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001703}
1704
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301705#define MAX_KFUNC_DESCS 256
1706#define MAX_KFUNC_BTFS 256
1707
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001708struct bpf_kfunc_desc {
1709 struct btf_func_model func_model;
1710 u32 func_id;
1711 s32 imm;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301712 u16 offset;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001713};
1714
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301715struct bpf_kfunc_btf {
1716 struct btf *btf;
1717 struct module *module;
1718 u16 offset;
1719};
1720
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001721struct bpf_kfunc_desc_tab {
1722 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
1723 u32 nr_descs;
1724};
1725
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301726struct bpf_kfunc_btf_tab {
1727 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
1728 u32 nr_descs;
1729};
1730
1731static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08001732{
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001733 const struct bpf_kfunc_desc *d0 = a;
1734 const struct bpf_kfunc_desc *d1 = b;
1735
1736 /* func_id is not greater than BTF_MAX_TYPE */
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301737 return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
1738}
1739
1740static int kfunc_btf_cmp_by_off(const void *a, const void *b)
1741{
1742 const struct bpf_kfunc_btf *d0 = a;
1743 const struct bpf_kfunc_btf *d1 = b;
1744
1745 return d0->offset - d1->offset;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001746}
1747
1748static const struct bpf_kfunc_desc *
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301749find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001750{
1751 struct bpf_kfunc_desc desc = {
1752 .func_id = func_id,
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301753 .offset = offset,
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001754 };
1755 struct bpf_kfunc_desc_tab *tab;
1756
1757 tab = prog->aux->kfunc_tab;
1758 return bsearch(&desc, tab->descs, tab->nr_descs,
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301759 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001760}
1761
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301762static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
1763 s16 offset, struct module **btf_modp)
1764{
1765 struct bpf_kfunc_btf kf_btf = { .offset = offset };
1766 struct bpf_kfunc_btf_tab *tab;
1767 struct bpf_kfunc_btf *b;
1768 struct module *mod;
1769 struct btf *btf;
1770 int btf_fd;
1771
1772 tab = env->prog->aux->kfunc_btf_tab;
1773 b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
1774 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
1775 if (!b) {
1776 if (tab->nr_descs == MAX_KFUNC_BTFS) {
1777 verbose(env, "too many different module BTFs\n");
1778 return ERR_PTR(-E2BIG);
1779 }
1780
1781 if (bpfptr_is_null(env->fd_array)) {
1782 verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
1783 return ERR_PTR(-EPROTO);
1784 }
1785
1786 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
1787 offset * sizeof(btf_fd),
1788 sizeof(btf_fd)))
1789 return ERR_PTR(-EFAULT);
1790
1791 btf = btf_get_by_fd(btf_fd);
Kumar Kartikeya Dwivedi588cd7ef2021-10-09 09:39:00 +05301792 if (IS_ERR(btf)) {
1793 verbose(env, "invalid module BTF fd specified\n");
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301794 return btf;
Kumar Kartikeya Dwivedi588cd7ef2021-10-09 09:39:00 +05301795 }
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301796
1797 if (!btf_is_module(btf)) {
1798 verbose(env, "BTF fd for kfunc is not a module BTF\n");
1799 btf_put(btf);
1800 return ERR_PTR(-EINVAL);
1801 }
1802
1803 mod = btf_try_get_module(btf);
1804 if (!mod) {
1805 btf_put(btf);
1806 return ERR_PTR(-ENXIO);
1807 }
1808
1809 b = &tab->descs[tab->nr_descs++];
1810 b->btf = btf;
1811 b->module = mod;
1812 b->offset = offset;
1813
1814 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1815 kfunc_btf_cmp_by_off, NULL);
1816 }
1817 if (btf_modp)
1818 *btf_modp = b->module;
1819 return b->btf;
1820}
1821
1822void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
1823{
1824 if (!tab)
1825 return;
1826
1827 while (tab->nr_descs--) {
1828 module_put(tab->descs[tab->nr_descs].module);
1829 btf_put(tab->descs[tab->nr_descs].btf);
1830 }
1831 kfree(tab);
1832}
1833
1834static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env,
1835 u32 func_id, s16 offset,
1836 struct module **btf_modp)
1837{
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301838 if (offset) {
1839 if (offset < 0) {
1840 /* In the future, this can be allowed to increase limit
1841 * of fd index into fd_array, interpreted as u16.
1842 */
1843 verbose(env, "negative offset disallowed for kernel module function call\n");
1844 return ERR_PTR(-EINVAL);
1845 }
1846
Kumar Kartikeya Dwivedi588cd7ef2021-10-09 09:39:00 +05301847 return __find_kfunc_desc_btf(env, offset, btf_modp);
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301848 }
1849 return btf_vmlinux ?: ERR_PTR(-ENOENT);
1850}
1851
1852static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001853{
1854 const struct btf_type *func, *func_proto;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301855 struct bpf_kfunc_btf_tab *btf_tab;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001856 struct bpf_kfunc_desc_tab *tab;
1857 struct bpf_prog_aux *prog_aux;
1858 struct bpf_kfunc_desc *desc;
1859 const char *func_name;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301860 struct btf *desc_btf;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001861 unsigned long addr;
1862 int err;
1863
1864 prog_aux = env->prog->aux;
1865 tab = prog_aux->kfunc_tab;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301866 btf_tab = prog_aux->kfunc_btf_tab;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001867 if (!tab) {
1868 if (!btf_vmlinux) {
1869 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
1870 return -ENOTSUPP;
1871 }
1872
1873 if (!env->prog->jit_requested) {
1874 verbose(env, "JIT is required for calling kernel function\n");
1875 return -ENOTSUPP;
1876 }
1877
1878 if (!bpf_jit_supports_kfunc_call()) {
1879 verbose(env, "JIT does not support calling kernel function\n");
1880 return -ENOTSUPP;
1881 }
1882
1883 if (!env->prog->gpl_compatible) {
1884 verbose(env, "cannot call kernel function from non-GPL compatible program\n");
1885 return -EINVAL;
1886 }
1887
1888 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
1889 if (!tab)
1890 return -ENOMEM;
1891 prog_aux->kfunc_tab = tab;
1892 }
1893
Kumar Kartikeya Dwivedia5d82722021-10-02 06:47:50 +05301894 /* func_id == 0 is always invalid, but instead of returning an error, be
1895 * conservative and wait until the code elimination pass before returning
1896 * error, so that invalid calls that get pruned out can be in BPF programs
1897 * loaded from userspace. It is also required that offset be untouched
1898 * for such calls.
1899 */
1900 if (!func_id && !offset)
1901 return 0;
1902
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301903 if (!btf_tab && offset) {
1904 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
1905 if (!btf_tab)
1906 return -ENOMEM;
1907 prog_aux->kfunc_btf_tab = btf_tab;
1908 }
1909
1910 desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL);
1911 if (IS_ERR(desc_btf)) {
1912 verbose(env, "failed to find BTF for kernel function\n");
1913 return PTR_ERR(desc_btf);
1914 }
1915
1916 if (find_kfunc_desc(env->prog, func_id, offset))
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001917 return 0;
1918
1919 if (tab->nr_descs == MAX_KFUNC_DESCS) {
1920 verbose(env, "too many different kernel function calls\n");
1921 return -E2BIG;
1922 }
1923
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301924 func = btf_type_by_id(desc_btf, func_id);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001925 if (!func || !btf_type_is_func(func)) {
1926 verbose(env, "kernel btf_id %u is not a function\n",
1927 func_id);
1928 return -EINVAL;
1929 }
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301930 func_proto = btf_type_by_id(desc_btf, func->type);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001931 if (!func_proto || !btf_type_is_func_proto(func_proto)) {
1932 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
1933 func_id);
1934 return -EINVAL;
1935 }
1936
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301937 func_name = btf_name_by_offset(desc_btf, func->name_off);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001938 addr = kallsyms_lookup_name(func_name);
1939 if (!addr) {
1940 verbose(env, "cannot find address for kernel function %s\n",
1941 func_name);
1942 return -EINVAL;
1943 }
1944
1945 desc = &tab->descs[tab->nr_descs++];
1946 desc->func_id = func_id;
Kees Cook3d717fa2021-09-28 16:09:45 -07001947 desc->imm = BPF_CALL_IMM(addr);
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301948 desc->offset = offset;
1949 err = btf_distill_func_proto(&env->log, desc_btf,
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001950 func_proto, func_name,
1951 &desc->func_model);
1952 if (!err)
1953 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05301954 kfunc_desc_cmp_by_id_off, NULL);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07001955 return err;
1956}
1957
1958static int kfunc_desc_cmp_by_imm(const void *a, const void *b)
1959{
1960 const struct bpf_kfunc_desc *d0 = a;
1961 const struct bpf_kfunc_desc *d1 = b;
1962
1963 if (d0->imm > d1->imm)
1964 return 1;
1965 else if (d0->imm < d1->imm)
1966 return -1;
1967 return 0;
1968}
1969
1970static void sort_kfunc_descs_by_imm(struct bpf_prog *prog)
1971{
1972 struct bpf_kfunc_desc_tab *tab;
1973
1974 tab = prog->aux->kfunc_tab;
1975 if (!tab)
1976 return;
1977
1978 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
1979 kfunc_desc_cmp_by_imm, NULL);
1980}
1981
1982bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
1983{
1984 return !!prog->aux->kfunc_tab;
1985}
1986
1987const struct btf_func_model *
1988bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
1989 const struct bpf_insn *insn)
1990{
1991 const struct bpf_kfunc_desc desc = {
1992 .imm = insn->imm,
1993 };
1994 const struct bpf_kfunc_desc *res;
1995 struct bpf_kfunc_desc_tab *tab;
1996
1997 tab = prog->aux->kfunc_tab;
1998 res = bsearch(&desc, tab->descs, tab->nr_descs,
1999 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm);
2000
2001 return res ? &res->func_model : NULL;
2002}
2003
2004static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2005{
Jiong Wang9c8105b2018-05-02 16:17:18 -04002006 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002007 struct bpf_insn *insn = env->prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002008 int i, ret, insn_cnt = env->prog->len;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002009
Jiong Wangf910cef2018-05-02 16:17:17 -04002010 /* Add entry function. */
2011 ret = add_subprog(env, 0);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002012 if (ret)
Jiong Wangf910cef2018-05-02 16:17:17 -04002013 return ret;
2014
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002015 for (i = 0; i < insn_cnt; i++, insn++) {
2016 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2017 !bpf_pseudo_kfunc_call(insn))
Yonghong Song69c087b2021-02-26 12:49:25 -08002018 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002019
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002020 if (!env->bpf_capable) {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002021 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002022 return -EPERM;
2023 }
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002024
Martin KaFai Lau3990ed42021-11-05 18:40:14 -07002025 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002026 ret = add_subprog(env, i + insn->imm + 1);
Martin KaFai Lau3990ed42021-11-05 18:40:14 -07002027 else
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05302028 ret = add_kfunc_call(env, insn->imm, insn->off);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002029
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002030 if (ret < 0)
2031 return ret;
2032 }
2033
Jiong Wang4cb3d992018-05-02 16:17:19 -04002034 /* Add a fake 'exit' subprog which could simplify subprog iteration
2035 * logic. 'subprog_cnt' should not be increased.
2036 */
2037 subprog[env->subprog_cnt].start = insn_cnt;
2038
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002039 if (env->log.level & BPF_LOG_LEVEL2)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002040 for (i = 0; i < env->subprog_cnt; i++)
Jiong Wang9c8105b2018-05-02 16:17:18 -04002041 verbose(env, "func#%d @%d\n", i, subprog[i].start);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002042
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002043 return 0;
2044}
2045
2046static int check_subprogs(struct bpf_verifier_env *env)
2047{
2048 int i, subprog_start, subprog_end, off, cur_subprog = 0;
2049 struct bpf_subprog_info *subprog = env->subprog_info;
2050 struct bpf_insn *insn = env->prog->insnsi;
2051 int insn_cnt = env->prog->len;
2052
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002053 /* now check that all jumps are within the same subprog */
Jiong Wang4cb3d992018-05-02 16:17:19 -04002054 subprog_start = subprog[cur_subprog].start;
2055 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002056 for (i = 0; i < insn_cnt; i++) {
2057 u8 code = insn[i].code;
2058
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02002059 if (code == (BPF_JMP | BPF_CALL) &&
2060 insn[i].imm == BPF_FUNC_tail_call &&
2061 insn[i].src_reg != BPF_PSEUDO_CALL)
2062 subprog[cur_subprog].has_tail_call = true;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -07002063 if (BPF_CLASS(code) == BPF_LD &&
2064 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2065 subprog[cur_subprog].has_ld_abs = true;
Jiong Wang092ed092019-01-26 12:26:01 -05002066 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002067 goto next;
2068 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2069 goto next;
2070 off = i + insn[i].off + 1;
2071 if (off < subprog_start || off >= subprog_end) {
2072 verbose(env, "jump out of range from insn %d to %d\n", i, off);
2073 return -EINVAL;
2074 }
2075next:
2076 if (i == subprog_end - 1) {
2077 /* to avoid fall-through from one subprog into another
2078 * the last insn of the subprog should be either exit
2079 * or unconditional jump back
2080 */
2081 if (code != (BPF_JMP | BPF_EXIT) &&
2082 code != (BPF_JMP | BPF_JA)) {
2083 verbose(env, "last insn is not an exit or jmp\n");
2084 return -EINVAL;
2085 }
2086 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -04002087 cur_subprog++;
2088 if (cur_subprog < env->subprog_cnt)
Jiong Wang9c8105b2018-05-02 16:17:18 -04002089 subprog_end = subprog[cur_subprog + 1].start;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -08002090 }
2091 }
2092 return 0;
2093}
2094
Edward Cree679c7822018-08-22 20:02:19 +01002095/* Parentage chain of this register (or stack slot) should take care of all
2096 * issues like callee-saved registers, stack slot allocation time, etc.
2097 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002098static int mark_reg_read(struct bpf_verifier_env *env,
Edward Cree679c7822018-08-22 20:02:19 +01002099 const struct bpf_reg_state *state,
Jiong Wang5327ed32019-05-24 23:25:12 +01002100 struct bpf_reg_state *parent, u8 flag)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002101{
2102 bool writes = parent == state->parent; /* Observe write marks */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002103 int cnt = 0;
Edward Creedc503a82017-08-15 20:34:35 +01002104
2105 while (parent) {
2106 /* if read wasn't screened by an earlier write ... */
Edward Cree679c7822018-08-22 20:02:19 +01002107 if (writes && state->live & REG_LIVE_WRITTEN)
Edward Creedc503a82017-08-15 20:34:35 +01002108 break;
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -08002109 if (parent->live & REG_LIVE_DONE) {
2110 verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2111 reg_type_str[parent->type],
2112 parent->var_off.value, parent->off);
2113 return -EFAULT;
2114 }
Jiong Wang5327ed32019-05-24 23:25:12 +01002115 /* The first condition is more likely to be true than the
2116 * second, checked it first.
2117 */
2118 if ((parent->live & REG_LIVE_READ) == flag ||
2119 parent->live & REG_LIVE_READ64)
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07002120 /* The parentage chain never changes and
2121 * this parent was already marked as LIVE_READ.
2122 * There is no need to keep walking the chain again and
2123 * keep re-marking all parents as LIVE_READ.
2124 * This case happens when the same register is read
2125 * multiple times without writes into it in-between.
Jiong Wang5327ed32019-05-24 23:25:12 +01002126 * Also, if parent has the stronger REG_LIVE_READ64 set,
2127 * then no need to set the weak REG_LIVE_READ32.
Alexei Starovoitov25af32d2019-04-01 21:27:42 -07002128 */
2129 break;
Edward Creedc503a82017-08-15 20:34:35 +01002130 /* ... then we depend on parent's value */
Jiong Wang5327ed32019-05-24 23:25:12 +01002131 parent->live |= flag;
2132 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2133 if (flag == REG_LIVE_READ64)
2134 parent->live &= ~REG_LIVE_READ32;
Edward Creedc503a82017-08-15 20:34:35 +01002135 state = parent;
2136 parent = state->parent;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002137 writes = true;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002138 cnt++;
Edward Creedc503a82017-08-15 20:34:35 +01002139 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07002140
2141 if (env->longest_mark_read_walk < cnt)
2142 env->longest_mark_read_walk = cnt;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002143 return 0;
Edward Creedc503a82017-08-15 20:34:35 +01002144}
2145
Jiong Wang5327ed32019-05-24 23:25:12 +01002146/* This function is supposed to be used by the following 32-bit optimization
2147 * code only. It returns TRUE if the source or destination register operates
2148 * on 64-bit, otherwise return FALSE.
2149 */
2150static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2151 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2152{
2153 u8 code, class, op;
2154
2155 code = insn->code;
2156 class = BPF_CLASS(code);
2157 op = BPF_OP(code);
2158 if (class == BPF_JMP) {
2159 /* BPF_EXIT for "main" will reach here. Return TRUE
2160 * conservatively.
2161 */
2162 if (op == BPF_EXIT)
2163 return true;
2164 if (op == BPF_CALL) {
2165 /* BPF to BPF call will reach here because of marking
2166 * caller saved clobber with DST_OP_NO_MARK for which we
2167 * don't care the register def because they are anyway
2168 * marked as NOT_INIT already.
2169 */
2170 if (insn->src_reg == BPF_PSEUDO_CALL)
2171 return false;
2172 /* Helper call will reach here because of arg type
2173 * check, conservatively return TRUE.
2174 */
2175 if (t == SRC_OP)
2176 return true;
2177
2178 return false;
2179 }
2180 }
2181
2182 if (class == BPF_ALU64 || class == BPF_JMP ||
2183 /* BPF_END always use BPF_ALU class. */
2184 (class == BPF_ALU && op == BPF_END && insn->imm == 64))
2185 return true;
2186
2187 if (class == BPF_ALU || class == BPF_JMP32)
2188 return false;
2189
2190 if (class == BPF_LDX) {
2191 if (t != SRC_OP)
2192 return BPF_SIZE(code) == BPF_DW;
2193 /* LDX source must be ptr. */
2194 return true;
2195 }
2196
2197 if (class == BPF_STX) {
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01002198 /* BPF_STX (including atomic variants) has multiple source
2199 * operands, one of which is a ptr. Check whether the caller is
2200 * asking about it.
2201 */
2202 if (t == SRC_OP && reg->type != SCALAR_VALUE)
Jiong Wang5327ed32019-05-24 23:25:12 +01002203 return true;
2204 return BPF_SIZE(code) == BPF_DW;
2205 }
2206
2207 if (class == BPF_LD) {
2208 u8 mode = BPF_MODE(code);
2209
2210 /* LD_IMM64 */
2211 if (mode == BPF_IMM)
2212 return true;
2213
2214 /* Both LD_IND and LD_ABS return 32-bit data. */
2215 if (t != SRC_OP)
2216 return false;
2217
2218 /* Implicit ctx ptr. */
2219 if (regno == BPF_REG_6)
2220 return true;
2221
2222 /* Explicit source could be any width. */
2223 return true;
2224 }
2225
2226 if (class == BPF_ST)
2227 /* The only source register for BPF_ST is a ptr. */
2228 return true;
2229
2230 /* Conservatively return true at default. */
2231 return true;
2232}
2233
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01002234/* Return the regno defined by the insn, or -1. */
2235static int insn_def_regno(const struct bpf_insn *insn)
Jiong Wangb325fbc2019-05-24 23:25:13 +01002236{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01002237 switch (BPF_CLASS(insn->code)) {
2238 case BPF_JMP:
2239 case BPF_JMP32:
2240 case BPF_ST:
2241 return -1;
2242 case BPF_STX:
2243 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
2244 (insn->imm & BPF_FETCH)) {
2245 if (insn->imm == BPF_CMPXCHG)
2246 return BPF_REG_0;
2247 else
2248 return insn->src_reg;
2249 } else {
2250 return -1;
2251 }
2252 default:
2253 return insn->dst_reg;
2254 }
Jiong Wangb325fbc2019-05-24 23:25:13 +01002255}
2256
2257/* Return TRUE if INSN has defined any 32-bit value explicitly. */
2258static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
2259{
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01002260 int dst_reg = insn_def_regno(insn);
2261
2262 if (dst_reg == -1)
Jiong Wangb325fbc2019-05-24 23:25:13 +01002263 return false;
2264
Ilya Leoshkevich83a28812021-03-01 16:40:19 +01002265 return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
Jiong Wangb325fbc2019-05-24 23:25:13 +01002266}
2267
Jiong Wang5327ed32019-05-24 23:25:12 +01002268static void mark_insn_zext(struct bpf_verifier_env *env,
2269 struct bpf_reg_state *reg)
2270{
2271 s32 def_idx = reg->subreg_def;
2272
2273 if (def_idx == DEF_NOT_SUBREG)
2274 return;
2275
2276 env->insn_aux_data[def_idx - 1].zext_dst = true;
2277 /* The dst will be zero extended, so won't be sub-register anymore. */
2278 reg->subreg_def = DEF_NOT_SUBREG;
2279}
2280
Edward Creedc503a82017-08-15 20:34:35 +01002281static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002282 enum reg_arg_type t)
2283{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002284 struct bpf_verifier_state *vstate = env->cur_state;
2285 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Jiong Wang5327ed32019-05-24 23:25:12 +01002286 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
Jiong Wangc342dc12019-04-12 22:59:37 +01002287 struct bpf_reg_state *reg, *regs = state->regs;
Jiong Wang5327ed32019-05-24 23:25:12 +01002288 bool rw64;
Edward Creedc503a82017-08-15 20:34:35 +01002289
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002290 if (regno >= MAX_BPF_REG) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002291 verbose(env, "R%d is invalid\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002292 return -EINVAL;
2293 }
2294
Christy Lee0f55f9e2021-12-16 13:33:56 -08002295 mark_reg_scratched(env, regno);
2296
Jiong Wangc342dc12019-04-12 22:59:37 +01002297 reg = &regs[regno];
Jiong Wang5327ed32019-05-24 23:25:12 +01002298 rw64 = is_reg64(env, insn, regno, reg, t);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002299 if (t == SRC_OP) {
2300 /* check whether register used as source operand can be read */
Jiong Wangc342dc12019-04-12 22:59:37 +01002301 if (reg->type == NOT_INIT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002302 verbose(env, "R%d !read_ok\n", regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002303 return -EACCES;
2304 }
Edward Cree679c7822018-08-22 20:02:19 +01002305 /* We don't need to worry about FP liveness because it's read-only */
Jiong Wangc342dc12019-04-12 22:59:37 +01002306 if (regno == BPF_REG_FP)
2307 return 0;
2308
Jiong Wang5327ed32019-05-24 23:25:12 +01002309 if (rw64)
2310 mark_insn_zext(env, reg);
2311
2312 return mark_reg_read(env, reg, reg->parent,
2313 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002314 } else {
2315 /* check whether register used as dest operand can be written to */
2316 if (regno == BPF_REG_FP) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002317 verbose(env, "frame pointer is read only\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002318 return -EACCES;
2319 }
Jiong Wangc342dc12019-04-12 22:59:37 +01002320 reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01002321 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002322 if (t == DST_OP)
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002323 mark_reg_unknown(env, regs, regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002324 }
2325 return 0;
2326}
2327
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002328/* for any branch, call, exit record the history of jmps in the given state */
2329static int push_jmp_history(struct bpf_verifier_env *env,
2330 struct bpf_verifier_state *cur)
2331{
2332 u32 cnt = cur->jmp_history_cnt;
2333 struct bpf_idx_pair *p;
2334
2335 cnt++;
2336 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER);
2337 if (!p)
2338 return -ENOMEM;
2339 p[cnt - 1].idx = env->insn_idx;
2340 p[cnt - 1].prev_idx = env->prev_insn_idx;
2341 cur->jmp_history = p;
2342 cur->jmp_history_cnt = cnt;
2343 return 0;
2344}
2345
2346/* Backtrack one insn at a time. If idx is not at the top of recorded
2347 * history then previous instruction came from straight line execution.
2348 */
2349static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
2350 u32 *history)
2351{
2352 u32 cnt = *history;
2353
2354 if (cnt && st->jmp_history[cnt - 1].idx == i) {
2355 i = st->jmp_history[cnt - 1].prev_idx;
2356 (*history)--;
2357 } else {
2358 i--;
2359 }
2360 return i;
2361}
2362
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002363static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
2364{
2365 const struct btf_type *func;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05302366 struct btf *desc_btf;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002367
2368 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
2369 return NULL;
2370
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05302371 desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL);
2372 if (IS_ERR(desc_btf))
2373 return "<error>";
2374
2375 func = btf_type_by_id(desc_btf, insn->imm);
2376 return btf_name_by_offset(desc_btf, func->name_off);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002377}
2378
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002379/* For given verifier state backtrack_insn() is called from the last insn to
2380 * the first insn. Its purpose is to compute a bitmask of registers and
2381 * stack slots that needs precision in the parent verifier state.
2382 */
2383static int backtrack_insn(struct bpf_verifier_env *env, int idx,
2384 u32 *reg_mask, u64 *stack_mask)
2385{
2386 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07002387 .cb_call = disasm_kfunc_name,
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002388 .cb_print = verbose,
2389 .private_data = env,
2390 };
2391 struct bpf_insn *insn = env->prog->insnsi + idx;
2392 u8 class = BPF_CLASS(insn->code);
2393 u8 opcode = BPF_OP(insn->code);
2394 u8 mode = BPF_MODE(insn->code);
2395 u32 dreg = 1u << insn->dst_reg;
2396 u32 sreg = 1u << insn->src_reg;
2397 u32 spi;
2398
2399 if (insn->code == 0)
2400 return 0;
2401 if (env->log.level & BPF_LOG_LEVEL) {
2402 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask);
2403 verbose(env, "%d: ", idx);
2404 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
2405 }
2406
2407 if (class == BPF_ALU || class == BPF_ALU64) {
2408 if (!(*reg_mask & dreg))
2409 return 0;
2410 if (opcode == BPF_MOV) {
2411 if (BPF_SRC(insn->code) == BPF_X) {
2412 /* dreg = sreg
2413 * dreg needs precision after this insn
2414 * sreg needs precision before this insn
2415 */
2416 *reg_mask &= ~dreg;
2417 *reg_mask |= sreg;
2418 } else {
2419 /* dreg = K
2420 * dreg needs precision after this insn.
2421 * Corresponding register is already marked
2422 * as precise=true in this verifier state.
2423 * No further markings in parent are necessary
2424 */
2425 *reg_mask &= ~dreg;
2426 }
2427 } else {
2428 if (BPF_SRC(insn->code) == BPF_X) {
2429 /* dreg += sreg
2430 * both dreg and sreg need precision
2431 * before this insn
2432 */
2433 *reg_mask |= sreg;
2434 } /* else dreg += K
2435 * dreg still needs precision before this insn
2436 */
2437 }
2438 } else if (class == BPF_LDX) {
2439 if (!(*reg_mask & dreg))
2440 return 0;
2441 *reg_mask &= ~dreg;
2442
2443 /* scalars can only be spilled into stack w/o losing precision.
2444 * Load from any other memory can be zero extended.
2445 * The desire to keep that precision is already indicated
2446 * by 'precise' mark in corresponding register of this state.
2447 * No further tracking necessary.
2448 */
2449 if (insn->src_reg != BPF_REG_FP)
2450 return 0;
2451 if (BPF_SIZE(insn->code) != BPF_DW)
2452 return 0;
2453
2454 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
2455 * that [fp - off] slot contains scalar that needs to be
2456 * tracked with precision
2457 */
2458 spi = (-insn->off - 1) / BPF_REG_SIZE;
2459 if (spi >= 64) {
2460 verbose(env, "BUG spi %d\n", spi);
2461 WARN_ONCE(1, "verifier backtracking bug");
2462 return -EFAULT;
2463 }
2464 *stack_mask |= 1ull << spi;
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002465 } else if (class == BPF_STX || class == BPF_ST) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002466 if (*reg_mask & dreg)
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002467 /* stx & st shouldn't be using _scalar_ dst_reg
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002468 * to access memory. It means backtracking
2469 * encountered a case of pointer subtraction.
2470 */
2471 return -ENOTSUPP;
2472 /* scalars can only be spilled into stack */
2473 if (insn->dst_reg != BPF_REG_FP)
2474 return 0;
2475 if (BPF_SIZE(insn->code) != BPF_DW)
2476 return 0;
2477 spi = (-insn->off - 1) / BPF_REG_SIZE;
2478 if (spi >= 64) {
2479 verbose(env, "BUG spi %d\n", spi);
2480 WARN_ONCE(1, "verifier backtracking bug");
2481 return -EFAULT;
2482 }
2483 if (!(*stack_mask & (1ull << spi)))
2484 return 0;
2485 *stack_mask &= ~(1ull << spi);
Andrii Nakryikob3b50f02019-07-08 20:32:44 -07002486 if (class == BPF_STX)
2487 *reg_mask |= sreg;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002488 } else if (class == BPF_JMP || class == BPF_JMP32) {
2489 if (opcode == BPF_CALL) {
2490 if (insn->src_reg == BPF_PSEUDO_CALL)
2491 return -ENOTSUPP;
2492 /* regular helper call sets R0 */
2493 *reg_mask &= ~1;
2494 if (*reg_mask & 0x3f) {
2495 /* if backtracing was looking for registers R1-R5
2496 * they should have been found already.
2497 */
2498 verbose(env, "BUG regs %x\n", *reg_mask);
2499 WARN_ONCE(1, "verifier backtracking bug");
2500 return -EFAULT;
2501 }
2502 } else if (opcode == BPF_EXIT) {
2503 return -ENOTSUPP;
2504 }
2505 } else if (class == BPF_LD) {
2506 if (!(*reg_mask & dreg))
2507 return 0;
2508 *reg_mask &= ~dreg;
2509 /* It's ld_imm64 or ld_abs or ld_ind.
2510 * For ld_imm64 no further tracking of precision
2511 * into parent is necessary
2512 */
2513 if (mode == BPF_IND || mode == BPF_ABS)
2514 /* to be analyzed */
2515 return -ENOTSUPP;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002516 }
2517 return 0;
2518}
2519
2520/* the scalar precision tracking algorithm:
2521 * . at the start all registers have precise=false.
2522 * . scalar ranges are tracked as normal through alu and jmp insns.
2523 * . once precise value of the scalar register is used in:
2524 * . ptr + scalar alu
2525 * . if (scalar cond K|scalar)
2526 * . helper_call(.., scalar, ...) where ARG_CONST is expected
2527 * backtrack through the verifier states and mark all registers and
2528 * stack slots with spilled constants that these scalar regisers
2529 * should be precise.
2530 * . during state pruning two registers (or spilled stack slots)
2531 * are equivalent if both are not precise.
2532 *
2533 * Note the verifier cannot simply walk register parentage chain,
2534 * since many different registers and stack slots could have been
2535 * used to compute single precise scalar.
2536 *
2537 * The approach of starting with precise=true for all registers and then
2538 * backtrack to mark a register as not precise when the verifier detects
2539 * that program doesn't care about specific value (e.g., when helper
2540 * takes register as ARG_ANYTHING parameter) is not safe.
2541 *
2542 * It's ok to walk single parentage chain of the verifier states.
2543 * It's possible that this backtracking will go all the way till 1st insn.
2544 * All other branches will be explored for needing precision later.
2545 *
2546 * The backtracking needs to deal with cases like:
2547 * 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)
2548 * r9 -= r8
2549 * r5 = r9
2550 * if r5 > 0x79f goto pc+7
2551 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
2552 * r5 += 1
2553 * ...
2554 * call bpf_perf_event_output#25
2555 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO
2556 *
2557 * and this case:
2558 * r6 = 1
2559 * call foo // uses callee's r6 inside to compute r0
2560 * r0 += r6
2561 * if r0 == 0 goto
2562 *
2563 * to track above reg_mask/stack_mask needs to be independent for each frame.
2564 *
2565 * Also if parent's curframe > frame where backtracking started,
2566 * the verifier need to mark registers in both frames, otherwise callees
2567 * may incorrectly prune callers. This is similar to
2568 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
2569 *
2570 * For now backtracking falls back into conservative marking.
2571 */
2572static void mark_all_scalars_precise(struct bpf_verifier_env *env,
2573 struct bpf_verifier_state *st)
2574{
2575 struct bpf_func_state *func;
2576 struct bpf_reg_state *reg;
2577 int i, j;
2578
2579 /* big hammer: mark all scalars precise in this path.
2580 * pop_stack may still get !precise scalars.
2581 */
2582 for (; st; st = st->parent)
2583 for (i = 0; i <= st->curframe; i++) {
2584 func = st->frame[i];
2585 for (j = 0; j < BPF_REG_FP; j++) {
2586 reg = &func->regs[j];
2587 if (reg->type != SCALAR_VALUE)
2588 continue;
2589 reg->precise = true;
2590 }
2591 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
Martin KaFai Lau27113c52021-09-21 17:49:34 -07002592 if (!is_spilled_reg(&func->stack[j]))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002593 continue;
2594 reg = &func->stack[j].spilled_ptr;
2595 if (reg->type != SCALAR_VALUE)
2596 continue;
2597 reg->precise = true;
2598 }
2599 }
2600}
2601
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002602static int __mark_chain_precision(struct bpf_verifier_env *env, int regno,
2603 int spi)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002604{
2605 struct bpf_verifier_state *st = env->cur_state;
2606 int first_idx = st->first_insn_idx;
2607 int last_idx = env->insn_idx;
2608 struct bpf_func_state *func;
2609 struct bpf_reg_state *reg;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002610 u32 reg_mask = regno >= 0 ? 1u << regno : 0;
2611 u64 stack_mask = spi >= 0 ? 1ull << spi : 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002612 bool skip_first = true;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002613 bool new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002614 int i, err;
2615
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002616 if (!env->bpf_capable)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002617 return 0;
2618
2619 func = st->frame[st->curframe];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002620 if (regno >= 0) {
2621 reg = &func->regs[regno];
2622 if (reg->type != SCALAR_VALUE) {
2623 WARN_ONCE(1, "backtracing misuse");
2624 return -EFAULT;
2625 }
2626 if (!reg->precise)
2627 new_marks = true;
2628 else
2629 reg_mask = 0;
2630 reg->precise = true;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002631 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002632
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002633 while (spi >= 0) {
Martin KaFai Lau27113c52021-09-21 17:49:34 -07002634 if (!is_spilled_reg(&func->stack[spi])) {
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002635 stack_mask = 0;
2636 break;
2637 }
2638 reg = &func->stack[spi].spilled_ptr;
2639 if (reg->type != SCALAR_VALUE) {
2640 stack_mask = 0;
2641 break;
2642 }
2643 if (!reg->precise)
2644 new_marks = true;
2645 else
2646 stack_mask = 0;
2647 reg->precise = true;
2648 break;
2649 }
2650
2651 if (!new_marks)
2652 return 0;
2653 if (!reg_mask && !stack_mask)
2654 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002655 for (;;) {
2656 DECLARE_BITMAP(mask, 64);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002657 u32 history = st->jmp_history_cnt;
2658
2659 if (env->log.level & BPF_LOG_LEVEL)
2660 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx);
2661 for (i = last_idx;;) {
2662 if (skip_first) {
2663 err = 0;
2664 skip_first = false;
2665 } else {
2666 err = backtrack_insn(env, i, &reg_mask, &stack_mask);
2667 }
2668 if (err == -ENOTSUPP) {
2669 mark_all_scalars_precise(env, st);
2670 return 0;
2671 } else if (err) {
2672 return err;
2673 }
2674 if (!reg_mask && !stack_mask)
2675 /* Found assignment(s) into tracked register in this state.
2676 * Since this state is already marked, just return.
2677 * Nothing to be tracked further in the parent state.
2678 */
2679 return 0;
2680 if (i == first_idx)
2681 break;
2682 i = get_prev_insn_idx(st, i, &history);
2683 if (i >= env->prog->len) {
2684 /* This can happen if backtracking reached insn 0
2685 * and there are still reg_mask or stack_mask
2686 * to backtrack.
2687 * It means the backtracking missed the spot where
2688 * particular register was initialized with a constant.
2689 */
2690 verbose(env, "BUG backtracking idx %d\n", i);
2691 WARN_ONCE(1, "verifier backtracking bug");
2692 return -EFAULT;
2693 }
2694 }
2695 st = st->parent;
2696 if (!st)
2697 break;
2698
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002699 new_marks = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002700 func = st->frame[st->curframe];
2701 bitmap_from_u64(mask, reg_mask);
2702 for_each_set_bit(i, mask, 32) {
2703 reg = &func->regs[i];
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002704 if (reg->type != SCALAR_VALUE) {
2705 reg_mask &= ~(1u << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002706 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002707 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002708 if (!reg->precise)
2709 new_marks = true;
2710 reg->precise = true;
2711 }
2712
2713 bitmap_from_u64(mask, stack_mask);
2714 for_each_set_bit(i, mask, 64) {
2715 if (i >= func->allocated_stack / BPF_REG_SIZE) {
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002716 /* the sequence of instructions:
2717 * 2: (bf) r3 = r10
2718 * 3: (7b) *(u64 *)(r3 -8) = r0
2719 * 4: (79) r4 = *(u64 *)(r10 -8)
2720 * doesn't contain jmps. It's backtracked
2721 * as a single block.
2722 * During backtracking insn 3 is not recognized as
2723 * stack access, so at the end of backtracking
2724 * stack slot fp-8 is still marked in stack_mask.
2725 * However the parent state may not have accessed
2726 * fp-8 and it's "unallocated" stack space.
2727 * In such case fallback to conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002728 */
Alexei Starovoitov2339cd62019-09-03 15:16:17 -07002729 mark_all_scalars_precise(env, st);
2730 return 0;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002731 }
2732
Martin KaFai Lau27113c52021-09-21 17:49:34 -07002733 if (!is_spilled_reg(&func->stack[i])) {
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002734 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002735 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002736 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002737 reg = &func->stack[i].spilled_ptr;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002738 if (reg->type != SCALAR_VALUE) {
2739 stack_mask &= ~(1ull << i);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002740 continue;
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002741 }
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002742 if (!reg->precise)
2743 new_marks = true;
2744 reg->precise = true;
2745 }
2746 if (env->log.level & BPF_LOG_LEVEL) {
Christy Lee2e576642021-12-16 19:42:45 -08002747 verbose(env, "parent %s regs=%x stack=%llx marks:",
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002748 new_marks ? "didn't have" : "already had",
2749 reg_mask, stack_mask);
Christy Lee2e576642021-12-16 19:42:45 -08002750 print_verifier_state(env, func, true);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002751 }
2752
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002753 if (!reg_mask && !stack_mask)
2754 break;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002755 if (!new_marks)
2756 break;
2757
2758 last_idx = st->last_insn_idx;
2759 first_idx = st->first_insn_idx;
2760 }
2761 return 0;
2762}
2763
Alexei Starovoitova3ce6852019-06-28 09:24:09 -07002764static int mark_chain_precision(struct bpf_verifier_env *env, int regno)
2765{
2766 return __mark_chain_precision(env, regno, -1);
2767}
2768
2769static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi)
2770{
2771 return __mark_chain_precision(env, -1, spi);
2772}
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002773
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002774static bool is_spillable_regtype(enum bpf_reg_type type)
2775{
2776 switch (type) {
2777 case PTR_TO_MAP_VALUE:
2778 case PTR_TO_MAP_VALUE_OR_NULL:
2779 case PTR_TO_STACK:
2780 case PTR_TO_CTX:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002781 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02002782 case PTR_TO_PACKET_META:
Alexei Starovoitov969bf052016-05-05 19:49:10 -07002783 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -07002784 case PTR_TO_FLOW_KEYS:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002785 case CONST_PTR_TO_MAP:
Joe Stringerc64b7982018-10-02 13:35:33 -07002786 case PTR_TO_SOCKET:
2787 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08002788 case PTR_TO_SOCK_COMMON:
2789 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08002790 case PTR_TO_TCP_SOCK:
2791 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07002792 case PTR_TO_XDP_SOCK:
Martin KaFai Lau65726b52020-01-08 16:34:54 -08002793 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -07002794 case PTR_TO_BTF_ID_OR_NULL:
Yonghong Songafbf21d2020-07-23 11:41:11 -07002795 case PTR_TO_RDONLY_BUF:
2796 case PTR_TO_RDONLY_BUF_OR_NULL:
2797 case PTR_TO_RDWR_BUF:
2798 case PTR_TO_RDWR_BUF_OR_NULL:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07002799 case PTR_TO_PERCPU_BTF_ID:
Gilad Reti744ea4e2021-01-13 07:38:07 +02002800 case PTR_TO_MEM:
2801 case PTR_TO_MEM_OR_NULL:
Yonghong Song69c087b2021-02-26 12:49:25 -08002802 case PTR_TO_FUNC:
2803 case PTR_TO_MAP_KEY:
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07002804 return true;
2805 default:
2806 return false;
2807 }
2808}
2809
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002810/* Does this register contain a constant zero? */
2811static bool register_is_null(struct bpf_reg_state *reg)
2812{
2813 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
2814}
2815
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002816static bool register_is_const(struct bpf_reg_state *reg)
2817{
2818 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
2819}
2820
Yonghong Song5689d492020-10-08 18:12:38 -07002821static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
2822{
2823 return tnum_is_unknown(reg->var_off) &&
2824 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
2825 reg->umin_value == 0 && reg->umax_value == U64_MAX &&
2826 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
2827 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
2828}
2829
2830static bool register_is_bounded(struct bpf_reg_state *reg)
2831{
2832 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
2833}
2834
Jann Horn6e7e63c2020-04-17 02:00:06 +02002835static bool __is_pointer_value(bool allow_ptr_leaks,
2836 const struct bpf_reg_state *reg)
2837{
2838 if (allow_ptr_leaks)
2839 return false;
2840
2841 return reg->type != SCALAR_VALUE;
2842}
2843
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002844static void save_register_state(struct bpf_func_state *state,
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002845 int spi, struct bpf_reg_state *reg,
2846 int size)
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002847{
2848 int i;
2849
2850 state->stack[spi].spilled_ptr = *reg;
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002851 if (size == BPF_REG_SIZE)
2852 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002853
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002854 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
2855 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
2856
2857 /* size < 8 bytes spill */
2858 for (; i; i--)
2859 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002860}
2861
Andrei Matei01f810a2021-02-06 20:10:24 -05002862/* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002863 * stack boundary and alignment are checked in check_mem_access()
2864 */
Andrei Matei01f810a2021-02-06 20:10:24 -05002865static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
2866 /* stack frame we're writing to */
2867 struct bpf_func_state *state,
2868 int off, int size, int value_regno,
2869 int insn_idx)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002870{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002871 struct bpf_func_state *cur; /* state of the current function */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002872 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002873 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002874 struct bpf_reg_state *reg = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002875
Lorenz Bauerc69431a2021-04-29 14:46:54 +01002876 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002877 if (err)
2878 return err;
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002879 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
2880 * so it's aligned access and [off, off + size) are within stack limits
2881 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002882 if (!env->allow_ptr_leaks &&
2883 state->stack[spi].slot_type[0] == STACK_SPILL &&
2884 size != BPF_REG_SIZE) {
2885 verbose(env, "attempt to corrupt spilled pointer on stack\n");
2886 return -EACCES;
2887 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002888
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002889 cur = env->cur_state->frame[env->cur_state->curframe];
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002890 if (value_regno >= 0)
2891 reg = &cur->regs[value_regno];
Daniel Borkmann2039f262021-07-13 08:18:31 +00002892 if (!env->bypass_spec_v4) {
2893 bool sanitize = reg && is_spillable_regtype(reg->type);
2894
2895 for (i = 0; i < size; i++) {
2896 if (state->stack[spi].slot_type[i] == STACK_INVALID) {
2897 sanitize = true;
2898 break;
2899 }
2900 }
2901
2902 if (sanitize)
2903 env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
2904 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002905
Christy Lee0f55f9e2021-12-16 13:33:56 -08002906 mark_stack_slot_scratched(env, spi);
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002907 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07002908 !register_is_null(reg) && env->bpf_capable) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002909 if (dst_reg != BPF_REG_FP) {
2910 /* The backtracking logic can only recognize explicit
2911 * stack slot address like [fp - 8]. Other spill of
Zhen Lei8fb33b62021-05-25 10:56:59 +08002912 * scalar via different register has to be conservative.
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002913 * Backtrack from here and mark all registers as precise
2914 * that contributed into 'reg' being a constant.
2915 */
2916 err = mark_chain_precision(env, value_regno);
2917 if (err)
2918 return err;
2919 }
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002920 save_register_state(state, spi, reg, size);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002921 } else if (reg && is_spillable_regtype(reg->type)) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002922 /* register containing pointer is being spilled into stack */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002923 if (size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002924 verbose_linfo(env, insn_idx, "; ");
Jakub Kicinski61bd5212017-10-09 10:30:11 -07002925 verbose(env, "invalid size of register spill\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002926 return -EACCES;
2927 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07002928 if (state != cur && reg->type == PTR_TO_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08002929 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
2930 return -EINVAL;
2931 }
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002932 save_register_state(state, spi, reg, size);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002933 } else {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002934 u8 type = STACK_MISC;
2935
Edward Cree679c7822018-08-22 20:02:19 +01002936 /* regular write of data into stack destroys any spilled ptr */
2937 state->stack[spi].spilled_ptr.type = NOT_INIT;
Jiong Wang0bae2d42018-12-15 03:34:40 -05002938 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */
Martin KaFai Lau27113c52021-09-21 17:49:34 -07002939 if (is_spilled_reg(&state->stack[spi]))
Jiong Wang0bae2d42018-12-15 03:34:40 -05002940 for (i = 0; i < BPF_REG_SIZE; i++)
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07002941 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002942
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002943 /* only mark the slot as written if all 8 bytes were written
2944 * otherwise read propagation may incorrectly stop too soon
2945 * when stack slots are partially written.
2946 * This heuristic means that read propagation will be
2947 * conservative, since it will add reg_live_read marks
2948 * to stack slots all the way to first state when programs
2949 * writes+reads less than 8 bytes
2950 */
2951 if (size == BPF_REG_SIZE)
2952 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
2953
2954 /* when we zero initialize stack slots mark them as such */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002955 if (reg && register_is_null(reg)) {
2956 /* backtracking doesn't work for STACK_ZERO yet. */
2957 err = mark_chain_precision(env, value_regno);
2958 if (err)
2959 return err;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002960 type = STACK_ZERO;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07002961 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002962
Jiong Wang0bae2d42018-12-15 03:34:40 -05002963 /* Mark slots affected by this stack write. */
Alexei Starovoitov9c3997602014-10-28 15:11:41 -07002964 for (i = 0; i < size; i++)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07002965 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08002966 type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07002967 }
2968 return 0;
2969}
2970
Andrei Matei01f810a2021-02-06 20:10:24 -05002971/* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
2972 * known to contain a variable offset.
2973 * This function checks whether the write is permitted and conservatively
2974 * tracks the effects of the write, considering that each stack slot in the
2975 * dynamic range is potentially written to.
2976 *
2977 * 'off' includes 'regno->off'.
2978 * 'value_regno' can be -1, meaning that an unknown value is being written to
2979 * the stack.
2980 *
2981 * Spilled pointers in range are not marked as written because we don't know
2982 * what's going to be actually written. This means that read propagation for
2983 * future reads cannot be terminated by this write.
2984 *
2985 * For privileged programs, uninitialized stack slots are considered
2986 * initialized by this write (even though we don't know exactly what offsets
2987 * are going to be written to). The idea is that we don't want the verifier to
2988 * reject future reads that access slots written to through variable offsets.
2989 */
2990static int check_stack_write_var_off(struct bpf_verifier_env *env,
2991 /* func where register points to */
2992 struct bpf_func_state *state,
2993 int ptr_regno, int off, int size,
2994 int value_regno, int insn_idx)
2995{
2996 struct bpf_func_state *cur; /* state of the current function */
2997 int min_off, max_off;
2998 int i, err;
2999 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
3000 bool writing_zero = false;
3001 /* set if the fact that we're writing a zero is used to let any
3002 * stack slots remain STACK_ZERO
3003 */
3004 bool zero_used = false;
3005
3006 cur = env->cur_state->frame[env->cur_state->curframe];
3007 ptr_reg = &cur->regs[ptr_regno];
3008 min_off = ptr_reg->smin_value + off;
3009 max_off = ptr_reg->smax_value + off + size;
3010 if (value_regno >= 0)
3011 value_reg = &cur->regs[value_regno];
3012 if (value_reg && register_is_null(value_reg))
3013 writing_zero = true;
3014
Lorenz Bauerc69431a2021-04-29 14:46:54 +01003015 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
Andrei Matei01f810a2021-02-06 20:10:24 -05003016 if (err)
3017 return err;
3018
3019
3020 /* Variable offset writes destroy any spilled pointers in range. */
3021 for (i = min_off; i < max_off; i++) {
3022 u8 new_type, *stype;
3023 int slot, spi;
3024
3025 slot = -i - 1;
3026 spi = slot / BPF_REG_SIZE;
3027 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
Christy Lee0f55f9e2021-12-16 13:33:56 -08003028 mark_stack_slot_scratched(env, spi);
Andrei Matei01f810a2021-02-06 20:10:24 -05003029
3030 if (!env->allow_ptr_leaks
3031 && *stype != NOT_INIT
3032 && *stype != SCALAR_VALUE) {
3033 /* Reject the write if there's are spilled pointers in
3034 * range. If we didn't reject here, the ptr status
3035 * would be erased below (even though not all slots are
3036 * actually overwritten), possibly opening the door to
3037 * leaks.
3038 */
3039 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
3040 insn_idx, i);
3041 return -EINVAL;
3042 }
3043
3044 /* Erase all spilled pointers. */
3045 state->stack[spi].spilled_ptr.type = NOT_INIT;
3046
3047 /* Update the slot type. */
3048 new_type = STACK_MISC;
3049 if (writing_zero && *stype == STACK_ZERO) {
3050 new_type = STACK_ZERO;
3051 zero_used = true;
3052 }
3053 /* If the slot is STACK_INVALID, we check whether it's OK to
3054 * pretend that it will be initialized by this write. The slot
3055 * might not actually be written to, and so if we mark it as
3056 * initialized future reads might leak uninitialized memory.
3057 * For privileged programs, we will accept such reads to slots
3058 * that may or may not be written because, if we're reject
3059 * them, the error would be too confusing.
3060 */
3061 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
3062 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
3063 insn_idx, i);
3064 return -EINVAL;
3065 }
3066 *stype = new_type;
3067 }
3068 if (zero_used) {
3069 /* backtracking doesn't work for STACK_ZERO yet. */
3070 err = mark_chain_precision(env, value_regno);
3071 if (err)
3072 return err;
3073 }
3074 return 0;
3075}
3076
3077/* When register 'dst_regno' is assigned some values from stack[min_off,
3078 * max_off), we set the register's type according to the types of the
3079 * respective stack slots. If all the stack values are known to be zeros, then
3080 * so is the destination reg. Otherwise, the register is considered to be
3081 * SCALAR. This function does not deal with register filling; the caller must
3082 * ensure that all spilled registers in the stack range have been marked as
3083 * read.
3084 */
3085static void mark_reg_stack_read(struct bpf_verifier_env *env,
3086 /* func where src register points to */
3087 struct bpf_func_state *ptr_state,
3088 int min_off, int max_off, int dst_regno)
3089{
3090 struct bpf_verifier_state *vstate = env->cur_state;
3091 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3092 int i, slot, spi;
3093 u8 *stype;
3094 int zeros = 0;
3095
3096 for (i = min_off; i < max_off; i++) {
3097 slot = -i - 1;
3098 spi = slot / BPF_REG_SIZE;
3099 stype = ptr_state->stack[spi].slot_type;
3100 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
3101 break;
3102 zeros++;
3103 }
3104 if (zeros == max_off - min_off) {
3105 /* any access_size read into register is zero extended,
3106 * so the whole register == const_zero
3107 */
3108 __mark_reg_const_zero(&state->regs[dst_regno]);
3109 /* backtracking doesn't support STACK_ZERO yet,
3110 * so mark it precise here, so that later
3111 * backtracking can stop here.
3112 * Backtracking may not need this if this register
3113 * doesn't participate in pointer adjustment.
3114 * Forward propagation of precise flag is not
3115 * necessary either. This mark is only to stop
3116 * backtracking. Any register that contributed
3117 * to const 0 was marked precise before spill.
3118 */
3119 state->regs[dst_regno].precise = true;
3120 } else {
3121 /* have read misc data from the stack */
3122 mark_reg_unknown(env, state->regs, dst_regno);
3123 }
3124 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
3125}
3126
3127/* Read the stack at 'off' and put the results into the register indicated by
3128 * 'dst_regno'. It handles reg filling if the addressed stack slot is a
3129 * spilled reg.
3130 *
3131 * 'dst_regno' can be -1, meaning that the read value is not going to a
3132 * register.
3133 *
3134 * The access is assumed to be within the current stack bounds.
3135 */
3136static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
3137 /* func where src register points to */
3138 struct bpf_func_state *reg_state,
3139 int off, int size, int dst_regno)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003140{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003141 struct bpf_verifier_state *vstate = env->cur_state;
3142 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003143 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003144 struct bpf_reg_state *reg;
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07003145 u8 *stype, type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003146
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003147 stype = reg_state->stack[spi].slot_type;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003148 reg = &reg_state->stack[spi].spilled_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003149
Martin KaFai Lau27113c52021-09-21 17:49:34 -07003150 if (is_spilled_reg(&reg_state->stack[spi])) {
Martin KaFai Lauf30d49682021-11-01 23:45:35 -07003151 u8 spill_size = 1;
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07003152
Martin KaFai Lauf30d49682021-11-01 23:45:35 -07003153 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
3154 spill_size++;
3155
3156 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003157 if (reg->type != SCALAR_VALUE) {
3158 verbose_linfo(env, env->insn_idx, "; ");
3159 verbose(env, "invalid size of register fill\n");
3160 return -EACCES;
3161 }
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07003162
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003163 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07003164 if (dst_regno < 0)
3165 return 0;
3166
Martin KaFai Lauf30d49682021-11-01 23:45:35 -07003167 if (!(off % BPF_REG_SIZE) && size == spill_size) {
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07003168 /* The earlier check_reg_arg() has decided the
3169 * subreg_def for this insn. Save it first.
3170 */
3171 s32 subreg_def = state->regs[dst_regno].subreg_def;
3172
3173 state->regs[dst_regno] = *reg;
3174 state->regs[dst_regno].subreg_def = subreg_def;
3175 } else {
3176 for (i = 0; i < size; i++) {
3177 type = stype[(slot - i) % BPF_REG_SIZE];
3178 if (type == STACK_SPILL)
3179 continue;
3180 if (type == STACK_MISC)
3181 continue;
3182 verbose(env, "invalid read from stack off %d+%d size %d\n",
3183 off, i, size);
3184 return -EACCES;
3185 }
3186 mark_reg_unknown(env, state->regs, dst_regno);
3187 }
3188 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003189 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003190 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003191
Andrei Matei01f810a2021-02-06 20:10:24 -05003192 if (dst_regno >= 0) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003193 /* restore register state from stack */
Andrei Matei01f810a2021-02-06 20:10:24 -05003194 state->regs[dst_regno] = *reg;
Alexei Starovoitov2f18f622017-11-30 21:31:38 -08003195 /* mark reg as written since spilled pointer state likely
3196 * has its liveness marks cleared by is_state_visited()
3197 * which resets stack/reg liveness for state transitions
3198 */
Andrei Matei01f810a2021-02-06 20:10:24 -05003199 state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
Jann Horn6e7e63c2020-04-17 02:00:06 +02003200 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05003201 /* If dst_regno==-1, the caller is asking us whether
Jann Horn6e7e63c2020-04-17 02:00:06 +02003202 * it is acceptable to use this value as a SCALAR_VALUE
3203 * (e.g. for XADD).
3204 * We must not allow unprivileged callers to do that
3205 * with spilled pointers.
3206 */
3207 verbose(env, "leaking pointer from stack off %d\n",
3208 off);
3209 return -EACCES;
Edward Creedc503a82017-08-15 20:34:35 +01003210 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003211 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003212 } else {
3213 for (i = 0; i < size; i++) {
Andrei Matei01f810a2021-02-06 20:10:24 -05003214 type = stype[(slot - i) % BPF_REG_SIZE];
3215 if (type == STACK_MISC)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003216 continue;
Andrei Matei01f810a2021-02-06 20:10:24 -05003217 if (type == STACK_ZERO)
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003218 continue;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08003219 verbose(env, "invalid read from stack off %d+%d size %d\n",
3220 off, i, size);
3221 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003222 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003223 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
Andrei Matei01f810a2021-02-06 20:10:24 -05003224 if (dst_regno >= 0)
3225 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003226 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07003227 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003228}
3229
Andrei Matei01f810a2021-02-06 20:10:24 -05003230enum stack_access_src {
3231 ACCESS_DIRECT = 1, /* the access is performed by an instruction */
3232 ACCESS_HELPER = 2, /* the access is performed by a helper */
3233};
3234
3235static int check_stack_range_initialized(struct bpf_verifier_env *env,
3236 int regno, int off, int access_size,
3237 bool zero_size_allowed,
3238 enum stack_access_src type,
3239 struct bpf_call_arg_meta *meta);
3240
3241static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003242{
Andrei Matei01f810a2021-02-06 20:10:24 -05003243 return cur_regs(env) + regno;
3244}
3245
3246/* Read the stack at 'ptr_regno + off' and put the result into the register
3247 * 'dst_regno'.
3248 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
3249 * but not its variable offset.
3250 * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
3251 *
3252 * As opposed to check_stack_read_fixed_off, this function doesn't deal with
3253 * filling registers (i.e. reads of spilled register cannot be detected when
3254 * the offset is not fixed). We conservatively mark 'dst_regno' as containing
3255 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
3256 * offset; for a fixed offset check_stack_read_fixed_off should be used
3257 * instead.
3258 */
3259static int check_stack_read_var_off(struct bpf_verifier_env *env,
3260 int ptr_regno, int off, int size, int dst_regno)
3261{
3262 /* The state of the source register. */
3263 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3264 struct bpf_func_state *ptr_state = func(env, reg);
3265 int err;
3266 int min_off, max_off;
3267
3268 /* Note that we pass a NULL meta, so raw access will not be permitted.
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003269 */
Andrei Matei01f810a2021-02-06 20:10:24 -05003270 err = check_stack_range_initialized(env, ptr_regno, off, size,
3271 false, ACCESS_DIRECT, NULL);
3272 if (err)
3273 return err;
3274
3275 min_off = reg->smin_value + off;
3276 max_off = reg->smax_value + off;
3277 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
3278 return 0;
3279}
3280
3281/* check_stack_read dispatches to check_stack_read_fixed_off or
3282 * check_stack_read_var_off.
3283 *
3284 * The caller must ensure that the offset falls within the allocated stack
3285 * bounds.
3286 *
3287 * 'dst_regno' is a register which will receive the value from the stack. It
3288 * can be -1, meaning that the read value is not going to a register.
3289 */
3290static int check_stack_read(struct bpf_verifier_env *env,
3291 int ptr_regno, int off, int size,
3292 int dst_regno)
3293{
3294 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3295 struct bpf_func_state *state = func(env, reg);
3296 int err;
3297 /* Some accesses are only permitted with a static offset. */
3298 bool var_off = !tnum_is_const(reg->var_off);
3299
3300 /* The offset is required to be static when reads don't go to a
3301 * register, in order to not leak pointers (see
3302 * check_stack_read_fixed_off).
3303 */
3304 if (dst_regno < 0 && var_off) {
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003305 char tn_buf[48];
3306
3307 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05003308 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 +01003309 tn_buf, off, size);
3310 return -EACCES;
3311 }
Andrei Matei01f810a2021-02-06 20:10:24 -05003312 /* Variable offset is prohibited for unprivileged mode for simplicity
3313 * since it requires corresponding support in Spectre masking for stack
3314 * ALU. See also retrieve_ptr_limit().
3315 */
3316 if (!env->bypass_spec_v1 && var_off) {
3317 char tn_buf[48];
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003318
Andrei Matei01f810a2021-02-06 20:10:24 -05003319 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
3320 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n",
3321 ptr_regno, tn_buf);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003322 return -EACCES;
3323 }
3324
Andrei Matei01f810a2021-02-06 20:10:24 -05003325 if (!var_off) {
3326 off += reg->var_off.value;
3327 err = check_stack_read_fixed_off(env, state, off, size,
3328 dst_regno);
3329 } else {
3330 /* Variable offset stack reads need more conservative handling
3331 * than fixed offset ones. Note that dst_regno >= 0 on this
3332 * branch.
3333 */
3334 err = check_stack_read_var_off(env, ptr_regno, off, size,
3335 dst_regno);
3336 }
3337 return err;
3338}
3339
3340
3341/* check_stack_write dispatches to check_stack_write_fixed_off or
3342 * check_stack_write_var_off.
3343 *
3344 * 'ptr_regno' is the register used as a pointer into the stack.
3345 * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
3346 * 'value_regno' is the register whose value we're writing to the stack. It can
3347 * be -1, meaning that we're not writing from a register.
3348 *
3349 * The caller must ensure that the offset falls within the maximum stack size.
3350 */
3351static int check_stack_write(struct bpf_verifier_env *env,
3352 int ptr_regno, int off, int size,
3353 int value_regno, int insn_idx)
3354{
3355 struct bpf_reg_state *reg = reg_state(env, ptr_regno);
3356 struct bpf_func_state *state = func(env, reg);
3357 int err;
3358
3359 if (tnum_is_const(reg->var_off)) {
3360 off += reg->var_off.value;
3361 err = check_stack_write_fixed_off(env, state, off, size,
3362 value_regno, insn_idx);
3363 } else {
3364 /* Variable offset stack reads need more conservative handling
3365 * than fixed offset ones.
3366 */
3367 err = check_stack_write_var_off(env, state,
3368 ptr_regno, off, size,
3369 value_regno, insn_idx);
3370 }
3371 return err;
Daniel Borkmanne4298d22019-01-03 00:58:31 +01003372}
3373
Daniel Borkmann591fe982019-04-09 23:20:05 +02003374static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
3375 int off, int size, enum bpf_access_type type)
3376{
3377 struct bpf_reg_state *regs = cur_regs(env);
3378 struct bpf_map *map = regs[regno].map_ptr;
3379 u32 cap = bpf_map_flags_to_cap(map);
3380
3381 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
3382 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
3383 map->value_size, off, size);
3384 return -EACCES;
3385 }
3386
3387 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
3388 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
3389 map->value_size, off, size);
3390 return -EACCES;
3391 }
3392
3393 return 0;
3394}
3395
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003396/* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
3397static int __check_mem_access(struct bpf_verifier_env *env, int regno,
3398 int off, int size, u32 mem_size,
3399 bool zero_size_allowed)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003400{
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003401 bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
3402 struct bpf_reg_state *reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003403
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003404 if (off >= 0 && size_ok && (u64)off + size <= mem_size)
3405 return 0;
3406
3407 reg = &cur_regs(env)[regno];
3408 switch (reg->type) {
Yonghong Song69c087b2021-02-26 12:49:25 -08003409 case PTR_TO_MAP_KEY:
3410 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
3411 mem_size, off, size);
3412 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003413 case PTR_TO_MAP_VALUE:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003414 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003415 mem_size, off, size);
3416 break;
3417 case PTR_TO_PACKET:
3418 case PTR_TO_PACKET_META:
3419 case PTR_TO_PACKET_END:
3420 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
3421 off, size, regno, reg->id, off, mem_size);
3422 break;
3423 case PTR_TO_MEM:
3424 default:
3425 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
3426 mem_size, off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003427 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003428
3429 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003430}
3431
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003432/* check read/write into a memory region with possible variable offset */
3433static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
3434 int off, int size, u32 mem_size,
3435 bool zero_size_allowed)
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003436{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003437 struct bpf_verifier_state *vstate = env->cur_state;
3438 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003439 struct bpf_reg_state *reg = &state->regs[regno];
3440 int err;
3441
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003442 /* We may have adjusted the register pointing to memory region, so we
Edward Creef1174f72017-08-07 15:26:19 +01003443 * need to try adding each of min_value and max_value to off
3444 * to make sure our theoretical access will be safe.
Christy Lee2e576642021-12-16 19:42:45 -08003445 *
3446 * The minimum value is only important with signed
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003447 * comparisons where we can't assume the floor of a
3448 * value is 0. If we are using signed variables for our
3449 * index'es we need to make sure that whatever we use
3450 * will have a set floor within our range.
3451 */
Daniel Borkmannb7137c42019-01-03 00:58:33 +01003452 if (reg->smin_value < 0 &&
3453 (reg->smin_value == S64_MIN ||
3454 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
3455 reg->smin_value + off < 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003456 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 -08003457 regno);
3458 return -EACCES;
3459 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003460 err = __check_mem_access(env, regno, reg->smin_value + off, size,
3461 mem_size, zero_size_allowed);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003462 if (err) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003463 verbose(env, "R%d min value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003464 regno);
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003465 return err;
3466 }
3467
Edward Creeb03c9f92017-08-07 15:26:36 +01003468 /* If we haven't set a max value then we need to bail since we can't be
3469 * sure we won't do bad things.
3470 * If reg->umax_value + off could overflow, treat that as unbounded too.
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003471 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003472 if (reg->umax_value >= BPF_MAX_VAR_OFF) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003473 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003474 regno);
3475 return -EACCES;
3476 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003477 err = __check_mem_access(env, regno, reg->umax_value + off, size,
3478 mem_size, zero_size_allowed);
3479 if (err) {
3480 verbose(env, "R%d max value is outside of the allowed memory range\n",
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003481 regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003482 return err;
3483 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003484
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003485 return 0;
3486}
3487
3488/* check read/write into a map element with possible variable offset */
3489static int check_map_access(struct bpf_verifier_env *env, u32 regno,
3490 int off, int size, bool zero_size_allowed)
3491{
3492 struct bpf_verifier_state *vstate = env->cur_state;
3493 struct bpf_func_state *state = vstate->frame[vstate->curframe];
3494 struct bpf_reg_state *reg = &state->regs[regno];
3495 struct bpf_map *map = reg->map_ptr;
3496 int err;
3497
3498 err = check_mem_region_access(env, regno, off, size, map->value_size,
3499 zero_size_allowed);
3500 if (err)
3501 return err;
3502
3503 if (map_value_has_spin_lock(map)) {
3504 u32 lock = map->spin_lock_off;
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08003505
3506 /* if any part of struct bpf_spin_lock can be touched by
3507 * load/store reject this program.
3508 * To check that [x1, x2) overlaps with [y1, y2)
3509 * it is sufficient to check x1 < y2 && y1 < x2.
3510 */
3511 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) &&
3512 lock < reg->umax_value + off + size) {
3513 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n");
3514 return -EACCES;
3515 }
3516 }
Alexei Starovoitov68134662021-07-14 17:54:10 -07003517 if (map_value_has_timer(map)) {
3518 u32 t = map->timer_off;
3519
3520 if (reg->smin_value + off < t + sizeof(struct bpf_timer) &&
3521 t < reg->umax_value + off + size) {
3522 verbose(env, "bpf_timer cannot be accessed directly by load/store\n");
3523 return -EACCES;
3524 }
3525 }
Edward Creef1174f72017-08-07 15:26:19 +01003526 return err;
Gianluca Borellodbcfe5f2017-01-09 10:19:46 -08003527}
3528
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003529#define MAX_PACKET_OFF 0xffff
3530
Udip Pant7e407812020-08-25 16:20:00 -07003531static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog)
3532{
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +02003533 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type;
Udip Pant7e407812020-08-25 16:20:00 -07003534}
3535
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01003536static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003537 const struct bpf_call_arg_meta *meta,
3538 enum bpf_access_type t)
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003539{
Udip Pant7e407812020-08-25 16:20:00 -07003540 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
3541
3542 switch (prog_type) {
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003543 /* Program types only with direct read access go here! */
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003544 case BPF_PROG_TYPE_LWT_IN:
3545 case BPF_PROG_TYPE_LWT_OUT:
Mathieu Xhonneux004d4b22018-05-20 14:58:16 +01003546 case BPF_PROG_TYPE_LWT_SEG6LOCAL:
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07003547 case BPF_PROG_TYPE_SK_REUSEPORT:
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003548 case BPF_PROG_TYPE_FLOW_DISSECTOR:
Daniel Borkmannd5563d32018-10-24 22:05:46 +02003549 case BPF_PROG_TYPE_CGROUP_SKB:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003550 if (t == BPF_WRITE)
3551 return false;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05003552 fallthrough;
Daniel Borkmann5d66fa72018-10-24 22:05:45 +02003553
3554 /* Program types with direct read + write access go here! */
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003555 case BPF_PROG_TYPE_SCHED_CLS:
3556 case BPF_PROG_TYPE_SCHED_ACT:
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003557 case BPF_PROG_TYPE_XDP:
Thomas Graf3a0af8f2016-11-30 17:10:10 +01003558 case BPF_PROG_TYPE_LWT_XMIT:
John Fastabend8a31db52017-08-15 22:33:09 -07003559 case BPF_PROG_TYPE_SK_SKB:
John Fastabend4f738ad2018-03-18 12:57:10 -07003560 case BPF_PROG_TYPE_SK_MSG:
Daniel Borkmann36bbef52016-09-20 00:26:13 +02003561 if (meta)
3562 return meta->pkt_access;
3563
3564 env->seen_direct_write = true;
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003565 return true;
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07003566
3567 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3568 if (t == BPF_WRITE)
3569 env->seen_direct_write = true;
3570
3571 return true;
3572
Brenden Blanco4acf6c02016-07-19 12:16:56 -07003573 default:
3574 return false;
3575 }
3576}
3577
Edward Creef1174f72017-08-07 15:26:19 +01003578static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
Yonghong Song9fd29c02017-11-12 14:49:09 -08003579 int size, bool zero_size_allowed)
Edward Creef1174f72017-08-07 15:26:19 +01003580{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07003581 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01003582 struct bpf_reg_state *reg = &regs[regno];
3583 int err;
3584
3585 /* We may have added a variable offset to the packet pointer; but any
3586 * reg->range we have comes after that. We are only checking the fixed
3587 * offset.
3588 */
3589
3590 /* We don't allow negative numbers, because we aren't tracking enough
3591 * detail to prove they're safe.
3592 */
Edward Creeb03c9f92017-08-07 15:26:36 +01003593 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003594 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 +01003595 regno);
3596 return -EACCES;
3597 }
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08003598
3599 err = reg->range < 0 ? -EINVAL :
3600 __check_mem_access(env, regno, off, size, reg->range,
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003601 zero_size_allowed);
Edward Creef1174f72017-08-07 15:26:19 +01003602 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003603 verbose(env, "R%d offset is outside of the packet\n", regno);
Edward Creef1174f72017-08-07 15:26:19 +01003604 return err;
3605 }
Jiong Wange6478152018-11-08 04:08:42 -05003606
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003607 /* __check_mem_access has made sure "off + size - 1" is within u16.
Jiong Wange6478152018-11-08 04:08:42 -05003608 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
3609 * otherwise find_good_pkt_pointers would have refused to set range info
Andrii Nakryiko457f4432020-05-29 00:54:20 -07003610 * that __check_mem_access would have rejected this pkt access.
Jiong Wange6478152018-11-08 04:08:42 -05003611 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
3612 */
3613 env->prog->aux->max_pkt_offset =
3614 max_t(u32, env->prog->aux->max_pkt_offset,
3615 off + reg->umax_value + size - 1);
3616
Edward Creef1174f72017-08-07 15:26:19 +01003617 return err;
3618}
3619
3620/* check access to 'struct bpf_context' fields. Supports fixed offsets only */
Yonghong Song31fd8582017-06-13 15:52:13 -07003621static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003622 enum bpf_access_type t, enum bpf_reg_type *reg_type,
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003623 struct btf **btf, u32 *btf_id)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003624{
Daniel Borkmannf96da092017-07-02 02:13:27 +02003625 struct bpf_insn_access_aux info = {
3626 .reg_type = *reg_type,
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003627 .log = &env->log,
Daniel Borkmannf96da092017-07-02 02:13:27 +02003628 };
Yonghong Song31fd8582017-06-13 15:52:13 -07003629
Jakub Kicinski4f9218a2017-10-16 16:40:55 -07003630 if (env->ops->is_valid_access &&
Andrey Ignatov5e43f892018-03-30 15:08:00 -07003631 env->ops->is_valid_access(off, size, t, env->prog, &info)) {
Daniel Borkmannf96da092017-07-02 02:13:27 +02003632 /* A non zero info.ctx_field_size indicates that this field is a
3633 * candidate for later verifier transformation to load the whole
3634 * field and then apply a mask when accessed with a narrower
3635 * access than actual ctx access size. A zero info.ctx_field_size
3636 * will only allow for whole field access and rejects any other
3637 * type of narrower access.
Yonghong Song31fd8582017-06-13 15:52:13 -07003638 */
Yonghong Song23994632017-06-22 15:07:39 -07003639 *reg_type = info.reg_type;
Yonghong Song31fd8582017-06-13 15:52:13 -07003640
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003641 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) {
3642 *btf = info.btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003643 *btf_id = info.btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003644 } else {
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07003645 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08003646 }
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003647 /* remember the offset of last byte accessed in ctx */
3648 if (env->prog->aux->max_ctx_offset < off + size)
3649 env->prog->aux->max_ctx_offset = off + size;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003650 return 0;
Alexei Starovoitov32bbe002016-04-06 18:43:28 -07003651 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003652
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003653 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07003654 return -EACCES;
3655}
3656
Petar Penkovd58e4682018-09-14 07:46:18 -07003657static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
3658 int size)
3659{
3660 if (size < 0 || off < 0 ||
3661 (u64)off + size > sizeof(struct bpf_flow_keys)) {
3662 verbose(env, "invalid access to flow keys off=%d size=%d\n",
3663 off, size);
3664 return -EACCES;
3665 }
3666 return 0;
3667}
3668
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003669static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
3670 u32 regno, int off, int size,
3671 enum bpf_access_type t)
Joe Stringerc64b7982018-10-02 13:35:33 -07003672{
3673 struct bpf_reg_state *regs = cur_regs(env);
3674 struct bpf_reg_state *reg = &regs[regno];
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003675 struct bpf_insn_access_aux info = {};
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003676 bool valid;
Joe Stringerc64b7982018-10-02 13:35:33 -07003677
3678 if (reg->smin_value < 0) {
3679 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
3680 regno);
3681 return -EACCES;
3682 }
3683
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003684 switch (reg->type) {
3685 case PTR_TO_SOCK_COMMON:
3686 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
3687 break;
3688 case PTR_TO_SOCKET:
3689 valid = bpf_sock_is_valid_access(off, size, t, &info);
3690 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003691 case PTR_TO_TCP_SOCK:
3692 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
3693 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003694 case PTR_TO_XDP_SOCK:
3695 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
3696 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003697 default:
3698 valid = false;
Joe Stringerc64b7982018-10-02 13:35:33 -07003699 }
3700
Martin KaFai Lau5f456642019-02-08 22:25:54 -08003701
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003702 if (valid) {
3703 env->insn_aux_data[insn_idx].ctx_field_size =
3704 info.ctx_field_size;
3705 return 0;
3706 }
3707
3708 verbose(env, "R%d invalid %s access off=%d size=%d\n",
3709 regno, reg_type_str[reg->type], off, size);
3710
3711 return -EACCES;
Joe Stringerc64b7982018-10-02 13:35:33 -07003712}
3713
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003714static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
3715{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003716 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02003717}
3718
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003719static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
3720{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003721 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003722
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003723 return reg->type == PTR_TO_CTX;
3724}
3725
3726static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
3727{
3728 const struct bpf_reg_state *reg = reg_state(env, regno);
3729
3730 return type_is_sk_pointer(reg->type);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01003731}
3732
Daniel Borkmannca369602018-02-23 22:29:05 +01003733static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
3734{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02003735 const struct bpf_reg_state *reg = reg_state(env, regno);
Daniel Borkmannca369602018-02-23 22:29:05 +01003736
3737 return type_is_pkt_pointer(reg->type);
3738}
3739
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02003740static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
3741{
3742 const struct bpf_reg_state *reg = reg_state(env, regno);
3743
3744 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
3745 return reg->type == PTR_TO_FLOW_KEYS;
3746}
3747
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003748static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
3749 const struct bpf_reg_state *reg,
David S. Millerd1174412017-05-10 11:22:52 -07003750 int off, int size, bool strict)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003751{
Edward Creef1174f72017-08-07 15:26:19 +01003752 struct tnum reg_off;
David S. Millere07b98d2017-05-10 11:38:07 -07003753 int ip_align;
David S. Millerd1174412017-05-10 11:22:52 -07003754
3755 /* Byte size accesses are always allowed. */
3756 if (!strict || size == 1)
3757 return 0;
3758
David S. Millere4eda882017-05-22 12:27:07 -04003759 /* For platforms that do not have a Kconfig enabling
3760 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
3761 * NET_IP_ALIGN is universally set to '2'. And on platforms
3762 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
3763 * to this code only in strict mode where we want to emulate
3764 * the NET_IP_ALIGN==2 checking. Therefore use an
3765 * unconditional IP align value of '2'.
David S. Millere07b98d2017-05-10 11:38:07 -07003766 */
David S. Millere4eda882017-05-22 12:27:07 -04003767 ip_align = 2;
Edward Creef1174f72017-08-07 15:26:19 +01003768
3769 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
3770 if (!tnum_is_aligned(reg_off, size)) {
3771 char tn_buf[48];
3772
3773 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003774 verbose(env,
3775 "misaligned packet access off %d+%s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003776 ip_align, tn_buf, reg->off, off, size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003777 return -EACCES;
3778 }
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003779
Alexei Starovoitov969bf052016-05-05 19:49:10 -07003780 return 0;
3781}
3782
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003783static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
3784 const struct bpf_reg_state *reg,
Edward Creef1174f72017-08-07 15:26:19 +01003785 const char *pointer_desc,
3786 int off, int size, bool strict)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003787{
Edward Creef1174f72017-08-07 15:26:19 +01003788 struct tnum reg_off;
3789
3790 /* Byte size accesses are always allowed. */
3791 if (!strict || size == 1)
3792 return 0;
3793
3794 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
3795 if (!tnum_is_aligned(reg_off, size)) {
3796 char tn_buf[48];
3797
3798 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003799 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
Edward Creef1174f72017-08-07 15:26:19 +01003800 pointer_desc, tn_buf, reg->off, off, size);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003801 return -EACCES;
3802 }
3803
3804 return 0;
3805}
3806
David S. Millere07b98d2017-05-10 11:38:07 -07003807static int check_ptr_alignment(struct bpf_verifier_env *env,
Daniel Borkmannca369602018-02-23 22:29:05 +01003808 const struct bpf_reg_state *reg, int off,
3809 int size, bool strict_alignment_once)
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003810{
Daniel Borkmannca369602018-02-23 22:29:05 +01003811 bool strict = env->strict_alignment || strict_alignment_once;
Edward Creef1174f72017-08-07 15:26:19 +01003812 const char *pointer_desc = "";
David S. Millerd1174412017-05-10 11:22:52 -07003813
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003814 switch (reg->type) {
3815 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02003816 case PTR_TO_PACKET_META:
3817 /* Special case, because of NET_IP_ALIGN. Given metadata sits
3818 * right in front, treat it the very same way.
3819 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003820 return check_pkt_ptr_alignment(env, reg, off, size, strict);
Petar Penkovd58e4682018-09-14 07:46:18 -07003821 case PTR_TO_FLOW_KEYS:
3822 pointer_desc = "flow keys ";
3823 break;
Yonghong Song69c087b2021-02-26 12:49:25 -08003824 case PTR_TO_MAP_KEY:
3825 pointer_desc = "key ";
3826 break;
Edward Creef1174f72017-08-07 15:26:19 +01003827 case PTR_TO_MAP_VALUE:
3828 pointer_desc = "value ";
3829 break;
3830 case PTR_TO_CTX:
3831 pointer_desc = "context ";
3832 break;
3833 case PTR_TO_STACK:
3834 pointer_desc = "stack ";
Andrei Matei01f810a2021-02-06 20:10:24 -05003835 /* The stack spill tracking logic in check_stack_write_fixed_off()
3836 * and check_stack_read_fixed_off() relies on stack accesses being
Jann Horna5ec6ae2017-12-18 20:11:58 -08003837 * aligned.
3838 */
3839 strict = true;
Edward Creef1174f72017-08-07 15:26:19 +01003840 break;
Joe Stringerc64b7982018-10-02 13:35:33 -07003841 case PTR_TO_SOCKET:
3842 pointer_desc = "sock ";
3843 break;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08003844 case PTR_TO_SOCK_COMMON:
3845 pointer_desc = "sock_common ";
3846 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08003847 case PTR_TO_TCP_SOCK:
3848 pointer_desc = "tcp_sock ";
3849 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07003850 case PTR_TO_XDP_SOCK:
3851 pointer_desc = "xdp_sock ";
3852 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003853 default:
Edward Creef1174f72017-08-07 15:26:19 +01003854 break;
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003855 }
Jakub Kicinski61bd5212017-10-09 10:30:11 -07003856 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
3857 strict);
Daniel Borkmann79adffc2017-03-31 02:24:03 +02003858}
3859
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003860static int update_stack_depth(struct bpf_verifier_env *env,
3861 const struct bpf_func_state *func,
3862 int off)
3863{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003864 u16 stack = env->subprog_info[func->subprogno].stack_depth;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003865
3866 if (stack >= -off)
3867 return 0;
3868
3869 /* update known max for given subprogram */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003870 env->subprog_info[func->subprogno].stack_depth = -off;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003871 return 0;
3872}
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003873
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003874/* starting from main bpf function walk all instructions of the function
3875 * and recursively walk all callees that given function can call.
3876 * Ignore jump and exit insns.
3877 * Since recursion is prevented by check_cfg() this algorithm
3878 * only needs a local stack of MAX_CALL_FRAMES to remember callsites
3879 */
3880static int check_max_stack_depth(struct bpf_verifier_env *env)
3881{
Jiong Wang9c8105b2018-05-02 16:17:18 -04003882 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end;
3883 struct bpf_subprog_info *subprog = env->subprog_info;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003884 struct bpf_insn *insn = env->prog->insnsi;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003885 bool tail_call_reachable = false;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003886 int ret_insn[MAX_CALL_FRAMES];
3887 int ret_prog[MAX_CALL_FRAMES];
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003888 int j;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003889
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003890process_func:
Maciej Fijalkowski7f6e4312020-09-16 23:10:07 +02003891 /* protect against potential stack overflow that might happen when
3892 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
3893 * depth for such case down to 256 so that the worst case scenario
3894 * would result in 8k stack size (32 which is tailcall limit * 256 =
3895 * 8k).
3896 *
3897 * To get the idea what might happen, see an example:
3898 * func1 -> sub rsp, 128
3899 * subfunc1 -> sub rsp, 256
3900 * tailcall1 -> add rsp, 256
3901 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
3902 * subfunc2 -> sub rsp, 64
3903 * subfunc22 -> sub rsp, 128
3904 * tailcall2 -> add rsp, 128
3905 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
3906 *
3907 * tailcall will unwind the current stack frame but it will not get rid
3908 * of caller's stack as shown on the example above.
3909 */
3910 if (idx && subprog[idx].has_tail_call && depth >= 256) {
3911 verbose(env,
3912 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
3913 depth);
3914 return -EACCES;
3915 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003916 /* round up to 32-bytes, since this is granularity
3917 * of interpreter stack size
3918 */
Jiong Wang9c8105b2018-05-02 16:17:18 -04003919 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003920 if (depth > MAX_BPF_STACK) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003921 verbose(env, "combined stack size of %d calls is %d. Too large\n",
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003922 frame + 1, depth);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003923 return -EACCES;
3924 }
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003925continue_func:
Jiong Wang4cb3d992018-05-02 16:17:19 -04003926 subprog_end = subprog[idx + 1].start;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003927 for (; i < subprog_end; i++) {
Alexei Starovoitov7ddc80a2021-07-14 17:54:15 -07003928 int next_insn;
3929
Yonghong Song69c087b2021-02-26 12:49:25 -08003930 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003931 continue;
3932 /* remember insn and function to return to */
3933 ret_insn[frame] = i + 1;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003934 ret_prog[frame] = idx;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003935
3936 /* find the callee */
Alexei Starovoitov7ddc80a2021-07-14 17:54:15 -07003937 next_insn = i + insn[i].imm + 1;
3938 idx = find_subprog(env, next_insn);
Jiong Wang9c8105b2018-05-02 16:17:18 -04003939 if (idx < 0) {
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003940 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
Alexei Starovoitov7ddc80a2021-07-14 17:54:15 -07003941 next_insn);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003942 return -EFAULT;
3943 }
Alexei Starovoitov7ddc80a2021-07-14 17:54:15 -07003944 if (subprog[idx].is_async_cb) {
3945 if (subprog[idx].has_tail_call) {
3946 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
3947 return -EFAULT;
3948 }
3949 /* async callbacks don't increase bpf prog stack size */
3950 continue;
3951 }
3952 i = next_insn;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003953
3954 if (subprog[idx].has_tail_call)
3955 tail_call_reachable = true;
3956
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003957 frame++;
3958 if (frame >= MAX_CALL_FRAMES) {
Paul Chaignon927cb782019-03-20 13:58:27 +01003959 verbose(env, "the call stack of %d frames is too deep !\n",
3960 frame);
3961 return -E2BIG;
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003962 }
3963 goto process_func;
3964 }
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003965 /* if tail call got detected across bpf2bpf calls then mark each of the
3966 * currently present subprog frames as tail call reachable subprogs;
3967 * this info will be utilized by JIT so that we will be preserving the
3968 * tail call counter throughout bpf2bpf calls combined with tailcalls
3969 */
3970 if (tail_call_reachable)
3971 for (j = 0; j < frame; j++)
3972 subprog[ret_prog[j]].tail_call_reachable = true;
Daniel Borkmann5dd0a6b2021-07-12 22:57:35 +02003973 if (subprog[0].tail_call_reachable)
3974 env->prog->aux->tail_call_reachable = true;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +02003975
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003976 /* end of for() loop means the last insn of the 'subprog'
3977 * was reached. Doesn't matter whether it was JA or EXIT
3978 */
3979 if (frame == 0)
3980 return 0;
Jiong Wang9c8105b2018-05-02 16:17:18 -04003981 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003982 frame--;
3983 i = ret_insn[frame];
Jiong Wang9c8105b2018-05-02 16:17:18 -04003984 idx = ret_prog[frame];
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -08003985 goto continue_func;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08003986}
3987
David S. Miller19d28fb2018-01-11 21:27:54 -05003988#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08003989static int get_callee_stack_depth(struct bpf_verifier_env *env,
3990 const struct bpf_insn *insn, int idx)
3991{
3992 int start = idx + insn->imm + 1, subprog;
3993
3994 subprog = find_subprog(env, start);
3995 if (subprog < 0) {
3996 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
3997 start);
3998 return -EFAULT;
3999 }
Jiong Wang9c8105b2018-05-02 16:17:18 -04004000 return env->subprog_info[subprog].stack_depth;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08004001}
David S. Miller19d28fb2018-01-11 21:27:54 -05004002#endif
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -08004003
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08004004int check_ctx_reg(struct bpf_verifier_env *env,
4005 const struct bpf_reg_state *reg, int regno)
Daniel Borkmann58990d12018-06-07 17:40:03 +02004006{
4007 /* Access to ctx or passing it to a helper is only allowed in
4008 * its original, unmodified form.
4009 */
4010
4011 if (reg->off) {
4012 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n",
4013 regno, reg->off);
4014 return -EACCES;
4015 }
4016
4017 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4018 char tn_buf[48];
4019
4020 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4021 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf);
4022 return -EACCES;
4023 }
4024
4025 return 0;
4026}
4027
Yonghong Songafbf21d2020-07-23 11:41:11 -07004028static int __check_buffer_access(struct bpf_verifier_env *env,
4029 const char *buf_info,
4030 const struct bpf_reg_state *reg,
4031 int regno, int off, int size)
Matt Mullins9df1c282019-04-26 11:49:47 -07004032{
4033 if (off < 0) {
4034 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07004035 "R%d invalid %s buffer access: off=%d, size=%d\n",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004036 regno, buf_info, off, size);
Matt Mullins9df1c282019-04-26 11:49:47 -07004037 return -EACCES;
4038 }
4039 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4040 char tn_buf[48];
4041
4042 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4043 verbose(env,
Yonghong Song4fc00b72020-07-28 15:18:01 -07004044 "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
Matt Mullins9df1c282019-04-26 11:49:47 -07004045 regno, off, tn_buf);
4046 return -EACCES;
4047 }
Yonghong Songafbf21d2020-07-23 11:41:11 -07004048
4049 return 0;
4050}
4051
4052static int check_tp_buffer_access(struct bpf_verifier_env *env,
4053 const struct bpf_reg_state *reg,
4054 int regno, int off, int size)
4055{
4056 int err;
4057
4058 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
4059 if (err)
4060 return err;
4061
Matt Mullins9df1c282019-04-26 11:49:47 -07004062 if (off + size > env->prog->aux->max_tp_access)
4063 env->prog->aux->max_tp_access = off + size;
4064
4065 return 0;
4066}
4067
Yonghong Songafbf21d2020-07-23 11:41:11 -07004068static int check_buffer_access(struct bpf_verifier_env *env,
4069 const struct bpf_reg_state *reg,
4070 int regno, int off, int size,
4071 bool zero_size_allowed,
4072 const char *buf_info,
4073 u32 *max_access)
4074{
4075 int err;
4076
4077 err = __check_buffer_access(env, buf_info, reg, regno, off, size);
4078 if (err)
4079 return err;
4080
4081 if (off + size > *max_access)
4082 *max_access = off + size;
4083
4084 return 0;
4085}
4086
John Fastabend3f50f132020-03-30 14:36:39 -07004087/* BPF architecture zero extends alu32 ops into 64-bit registesr */
4088static void zext_32_to_64(struct bpf_reg_state *reg)
4089{
4090 reg->var_off = tnum_subreg(reg->var_off);
4091 __reg_assign_32_into_64(reg);
4092}
Matt Mullins9df1c282019-04-26 11:49:47 -07004093
Jann Horn0c17d1d2017-12-18 20:11:55 -08004094/* truncate register to smaller size (in bytes)
4095 * must be called with size < BPF_REG_SIZE
4096 */
4097static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
4098{
4099 u64 mask;
4100
4101 /* clear high bits in bit representation */
4102 reg->var_off = tnum_cast(reg->var_off, size);
4103
4104 /* fix arithmetic bounds */
4105 mask = ((u64)1 << (size * 8)) - 1;
4106 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
4107 reg->umin_value &= mask;
4108 reg->umax_value &= mask;
4109 } else {
4110 reg->umin_value = 0;
4111 reg->umax_value = mask;
4112 }
4113 reg->smin_value = reg->umin_value;
4114 reg->smax_value = reg->umax_value;
John Fastabend3f50f132020-03-30 14:36:39 -07004115
4116 /* If size is smaller than 32bit register the 32bit register
4117 * values are also truncated so we push 64-bit bounds into
4118 * 32-bit bounds. Above were truncated < 32-bits already.
4119 */
4120 if (size >= 4)
4121 return;
4122 __reg_combine_64_into_32(reg);
Jann Horn0c17d1d2017-12-18 20:11:55 -08004123}
4124
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004125static bool bpf_map_is_rdonly(const struct bpf_map *map)
4126{
Daniel Borkmann353050b2021-11-09 18:48:08 +00004127 /* A map is considered read-only if the following condition are true:
4128 *
4129 * 1) BPF program side cannot change any of the map content. The
4130 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
4131 * and was set at map creation time.
4132 * 2) The map value(s) have been initialized from user space by a
4133 * loader and then "frozen", such that no new map update/delete
4134 * operations from syscall side are possible for the rest of
4135 * the map's lifetime from that point onwards.
4136 * 3) Any parallel/pending map update/delete operations from syscall
4137 * side have been completed. Only after that point, it's safe to
4138 * assume that map value(s) are immutable.
4139 */
4140 return (map->map_flags & BPF_F_RDONLY_PROG) &&
4141 READ_ONCE(map->frozen) &&
4142 !bpf_map_write_active(map);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004143}
4144
4145static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val)
4146{
4147 void *ptr;
4148 u64 addr;
4149 int err;
4150
4151 err = map->ops->map_direct_value_addr(map, &addr, off);
4152 if (err)
4153 return err;
Andrii Nakryiko2dedd7d2019-10-11 10:20:53 -07004154 ptr = (void *)(long)addr + off;
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004155
4156 switch (size) {
4157 case sizeof(u8):
4158 *val = (u64)*(u8 *)ptr;
4159 break;
4160 case sizeof(u16):
4161 *val = (u64)*(u16 *)ptr;
4162 break;
4163 case sizeof(u32):
4164 *val = (u64)*(u32 *)ptr;
4165 break;
4166 case sizeof(u64):
4167 *val = *(u64 *)ptr;
4168 break;
4169 default:
4170 return -EINVAL;
4171 }
4172 return 0;
4173}
4174
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004175static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
4176 struct bpf_reg_state *regs,
4177 int regno, int off, int size,
4178 enum bpf_access_type atype,
4179 int value_regno)
4180{
4181 struct bpf_reg_state *reg = regs + regno;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004182 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
4183 const char *tname = btf_name_by_offset(reg->btf, t->name_off);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004184 u32 btf_id;
4185 int ret;
4186
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004187 if (off < 0) {
4188 verbose(env,
4189 "R%d is ptr_%s invalid negative access: off=%d\n",
4190 regno, tname, off);
4191 return -EACCES;
4192 }
4193 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4194 char tn_buf[48];
4195
4196 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4197 verbose(env,
4198 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
4199 regno, tname, off, tn_buf);
4200 return -EACCES;
4201 }
4202
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08004203 if (env->ops->btf_struct_access) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004204 ret = env->ops->btf_struct_access(&env->log, reg->btf, t,
4205 off, size, atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08004206 } else {
4207 if (atype != BPF_READ) {
4208 verbose(env, "only read is supported\n");
4209 return -EACCES;
4210 }
4211
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004212 ret = btf_struct_access(&env->log, reg->btf, t, off, size,
4213 atype, &btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08004214 }
4215
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004216 if (ret < 0)
4217 return ret;
4218
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004219 if (atype == BPF_READ && value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004220 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08004221
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004222 return 0;
4223}
4224
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004225static int check_ptr_to_map_access(struct bpf_verifier_env *env,
4226 struct bpf_reg_state *regs,
4227 int regno, int off, int size,
4228 enum bpf_access_type atype,
4229 int value_regno)
4230{
4231 struct bpf_reg_state *reg = regs + regno;
4232 struct bpf_map *map = reg->map_ptr;
4233 const struct btf_type *t;
4234 const char *tname;
4235 u32 btf_id;
4236 int ret;
4237
4238 if (!btf_vmlinux) {
4239 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
4240 return -ENOTSUPP;
4241 }
4242
4243 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
4244 verbose(env, "map_ptr access not supported for map type %d\n",
4245 map->map_type);
4246 return -ENOTSUPP;
4247 }
4248
4249 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
4250 tname = btf_name_by_offset(btf_vmlinux, t->name_off);
4251
4252 if (!env->allow_ptr_to_map_access) {
4253 verbose(env,
4254 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
4255 tname);
4256 return -EPERM;
4257 }
4258
4259 if (off < 0) {
4260 verbose(env, "R%d is %s invalid negative access: off=%d\n",
4261 regno, tname, off);
4262 return -EACCES;
4263 }
4264
4265 if (atype != BPF_READ) {
4266 verbose(env, "only read from %s is supported\n", tname);
4267 return -EACCES;
4268 }
4269
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004270 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004271 if (ret < 0)
4272 return ret;
4273
4274 if (value_regno >= 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004275 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004276
4277 return 0;
4278}
4279
Andrei Matei01f810a2021-02-06 20:10:24 -05004280/* Check that the stack access at the given offset is within bounds. The
4281 * maximum valid offset is -1.
4282 *
4283 * The minimum valid offset is -MAX_BPF_STACK for writes, and
4284 * -state->allocated_stack for reads.
4285 */
4286static int check_stack_slot_within_bounds(int off,
4287 struct bpf_func_state *state,
4288 enum bpf_access_type t)
4289{
4290 int min_valid_off;
4291
4292 if (t == BPF_WRITE)
4293 min_valid_off = -MAX_BPF_STACK;
4294 else
4295 min_valid_off = -state->allocated_stack;
4296
4297 if (off < min_valid_off || off > -1)
4298 return -EACCES;
4299 return 0;
4300}
4301
4302/* Check that the stack access at 'regno + off' falls within the maximum stack
4303 * bounds.
4304 *
4305 * 'off' includes `regno->offset`, but not its dynamic part (if any).
4306 */
4307static int check_stack_access_within_bounds(
4308 struct bpf_verifier_env *env,
4309 int regno, int off, int access_size,
4310 enum stack_access_src src, enum bpf_access_type type)
4311{
4312 struct bpf_reg_state *regs = cur_regs(env);
4313 struct bpf_reg_state *reg = regs + regno;
4314 struct bpf_func_state *state = func(env, reg);
4315 int min_off, max_off;
4316 int err;
4317 char *err_extra;
4318
4319 if (src == ACCESS_HELPER)
4320 /* We don't know if helpers are reading or writing (or both). */
4321 err_extra = " indirect access to";
4322 else if (type == BPF_READ)
4323 err_extra = " read from";
4324 else
4325 err_extra = " write to";
4326
4327 if (tnum_is_const(reg->var_off)) {
4328 min_off = reg->var_off.value + off;
4329 if (access_size > 0)
4330 max_off = min_off + access_size - 1;
4331 else
4332 max_off = min_off;
4333 } else {
4334 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
4335 reg->smin_value <= -BPF_MAX_VAR_OFF) {
4336 verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
4337 err_extra, regno);
4338 return -EACCES;
4339 }
4340 min_off = reg->smin_value + off;
4341 if (access_size > 0)
4342 max_off = reg->smax_value + off + access_size - 1;
4343 else
4344 max_off = min_off;
4345 }
4346
4347 err = check_stack_slot_within_bounds(min_off, state, type);
4348 if (!err)
4349 err = check_stack_slot_within_bounds(max_off, state, type);
4350
4351 if (err) {
4352 if (tnum_is_const(reg->var_off)) {
4353 verbose(env, "invalid%s stack R%d off=%d size=%d\n",
4354 err_extra, regno, off, access_size);
4355 } else {
4356 char tn_buf[48];
4357
4358 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4359 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
4360 err_extra, regno, tn_buf, access_size);
4361 }
4362 }
4363 return err;
4364}
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004365
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004366/* check whether memory at (regno + off) is accessible for t = (read | write)
4367 * if t==write, value_regno is a register which value is stored into memory
4368 * if t==read, value_regno is a register which will receive the value from memory
4369 * if t==write && value_regno==-1, some unknown value is stored into memory
4370 * if t==read && value_regno==-1, don't care what we read from memory
4371 */
Daniel Borkmannca369602018-02-23 22:29:05 +01004372static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
4373 int off, int bpf_size, enum bpf_access_type t,
4374 int value_regno, bool strict_alignment_once)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004375{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004376 struct bpf_reg_state *regs = cur_regs(env);
4377 struct bpf_reg_state *reg = regs + regno;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004378 struct bpf_func_state *state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004379 int size, err = 0;
4380
4381 size = bpf_size_to_bytes(bpf_size);
4382 if (size < 0)
4383 return size;
4384
Edward Creef1174f72017-08-07 15:26:19 +01004385 /* alignment checks will add in reg->off themselves */
Daniel Borkmannca369602018-02-23 22:29:05 +01004386 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004387 if (err)
4388 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004389
Edward Creef1174f72017-08-07 15:26:19 +01004390 /* for access checks, reg->off is just part of off */
4391 off += reg->off;
4392
Yonghong Song69c087b2021-02-26 12:49:25 -08004393 if (reg->type == PTR_TO_MAP_KEY) {
4394 if (t == BPF_WRITE) {
4395 verbose(env, "write to change key R%d not allowed\n", regno);
4396 return -EACCES;
4397 }
4398
4399 err = check_mem_region_access(env, regno, off, size,
4400 reg->map_ptr->key_size, false);
4401 if (err)
4402 return err;
4403 if (value_regno >= 0)
4404 mark_reg_unknown(env, regs, value_regno);
4405 } else if (reg->type == PTR_TO_MAP_VALUE) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004406 if (t == BPF_WRITE && value_regno >= 0 &&
4407 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004408 verbose(env, "R%d leaks addr into map\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004409 return -EACCES;
4410 }
Daniel Borkmann591fe982019-04-09 23:20:05 +02004411 err = check_map_access_type(env, regno, off, size, t);
4412 if (err)
4413 return err;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004414 err = check_map_access(env, regno, off, size, false);
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004415 if (!err && t == BPF_READ && value_regno >= 0) {
4416 struct bpf_map *map = reg->map_ptr;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004417
Andrii Nakryikoa23740e2019-10-09 13:14:57 -07004418 /* if map is read-only, track its contents as scalars */
4419 if (tnum_is_const(reg->var_off) &&
4420 bpf_map_is_rdonly(map) &&
4421 map->ops->map_direct_value_addr) {
4422 int map_off = off + reg->var_off.value;
4423 u64 val = 0;
4424
4425 err = bpf_map_direct_read(map, map_off, size,
4426 &val);
4427 if (err)
4428 return err;
4429
4430 regs[value_regno].type = SCALAR_VALUE;
4431 __mark_reg_known(&regs[value_regno], val);
4432 } else {
4433 mark_reg_unknown(env, regs, value_regno);
4434 }
4435 }
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004436 } else if (reg->type == PTR_TO_MEM) {
4437 if (t == BPF_WRITE && value_regno >= 0 &&
4438 is_pointer_value(env, value_regno)) {
4439 verbose(env, "R%d leaks addr into mem\n", value_regno);
4440 return -EACCES;
4441 }
4442 err = check_mem_region_access(env, regno, off, size,
4443 reg->mem_size, false);
4444 if (!err && t == BPF_READ && value_regno >= 0)
4445 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07004446 } else if (reg->type == PTR_TO_CTX) {
Edward Creef1174f72017-08-07 15:26:19 +01004447 enum bpf_reg_type reg_type = SCALAR_VALUE;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004448 struct btf *btf = NULL;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004449 u32 btf_id = 0;
Alexei Starovoitov19de99f2016-06-15 18:25:38 -07004450
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004451 if (t == BPF_WRITE && value_regno >= 0 &&
4452 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004453 verbose(env, "R%d leaks addr into ctx\n", value_regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07004454 return -EACCES;
4455 }
Edward Creef1174f72017-08-07 15:26:19 +01004456
Daniel Borkmann58990d12018-06-07 17:40:03 +02004457 err = check_ctx_reg(env, reg, regno);
4458 if (err < 0)
4459 return err;
4460
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004461 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf, &btf_id);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004462 if (err)
4463 verbose_linfo(env, insn_idx, "; ");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004464 if (!err && t == BPF_READ && value_regno >= 0) {
Edward Creef1174f72017-08-07 15:26:19 +01004465 /* ctx access returns either a scalar, or a
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004466 * PTR_TO_PACKET[_META,_END]. In the latter
4467 * case, we know the offset is zero.
Edward Creef1174f72017-08-07 15:26:19 +01004468 */
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004469 if (reg_type == SCALAR_VALUE) {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004470 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004471 } else {
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004472 mark_reg_known_zero(env, regs,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004473 value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004474 if (reg_type_may_be_null(reg_type))
4475 regs[value_regno].id = ++env->id_gen;
Jiong Wang5327ed32019-05-24 23:25:12 +01004476 /* A load of ctx field could have different
4477 * actual load size with the one encoded in the
4478 * insn. When the dst is PTR, it is for sure not
4479 * a sub-register.
4480 */
4481 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
Yonghong Songb121b342020-05-09 10:59:12 -07004482 if (reg_type == PTR_TO_BTF_ID ||
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004483 reg_type == PTR_TO_BTF_ID_OR_NULL) {
4484 regs[value_regno].btf = btf;
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004485 regs[value_regno].btf_id = btf_id;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08004486 }
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004487 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004488 regs[value_regno].type = reg_type;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004489 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004490
Edward Creef1174f72017-08-07 15:26:19 +01004491 } else if (reg->type == PTR_TO_STACK) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004492 /* Basic bounds checks. */
4493 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
Daniel Borkmanne4298d22019-01-03 00:58:31 +01004494 if (err)
4495 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004496
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004497 state = func(env, reg);
4498 err = update_stack_depth(env, state, off);
4499 if (err)
4500 return err;
Alexei Starovoitov87266792017-05-30 13:31:29 -07004501
Andrei Matei01f810a2021-02-06 20:10:24 -05004502 if (t == BPF_READ)
4503 err = check_stack_read(env, regno, off, size,
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004504 value_regno);
Andrei Matei01f810a2021-02-06 20:10:24 -05004505 else
4506 err = check_stack_write(env, regno, off, size,
4507 value_regno, insn_idx);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004508 } else if (reg_is_pkt_pointer(reg)) {
Thomas Graf3a0af8f2016-11-30 17:10:10 +01004509 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004510 verbose(env, "cannot write into packet\n");
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004511 return -EACCES;
4512 }
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004513 if (t == BPF_WRITE && value_regno >= 0 &&
4514 is_pointer_value(env, value_regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004515 verbose(env, "R%d leaks addr into packet\n",
4516 value_regno);
Brenden Blanco4acf6c02016-07-19 12:16:56 -07004517 return -EACCES;
4518 }
Yonghong Song9fd29c02017-11-12 14:49:09 -08004519 err = check_packet_access(env, regno, off, size, false);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004520 if (!err && t == BPF_READ && value_regno >= 0)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004521 mark_reg_unknown(env, regs, value_regno);
Petar Penkovd58e4682018-09-14 07:46:18 -07004522 } else if (reg->type == PTR_TO_FLOW_KEYS) {
4523 if (t == BPF_WRITE && value_regno >= 0 &&
4524 is_pointer_value(env, value_regno)) {
4525 verbose(env, "R%d leaks addr into flow keys\n",
4526 value_regno);
4527 return -EACCES;
4528 }
4529
4530 err = check_flow_keys_access(env, off, size);
4531 if (!err && t == BPF_READ && value_regno >= 0)
4532 mark_reg_unknown(env, regs, value_regno);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004533 } else if (type_is_sk_pointer(reg->type)) {
Joe Stringerc64b7982018-10-02 13:35:33 -07004534 if (t == BPF_WRITE) {
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004535 verbose(env, "R%d cannot write into %s\n",
4536 regno, reg_type_str[reg->type]);
Joe Stringerc64b7982018-10-02 13:35:33 -07004537 return -EACCES;
4538 }
Martin KaFai Lau5f456642019-02-08 22:25:54 -08004539 err = check_sock_access(env, insn_idx, regno, off, size, t);
Joe Stringerc64b7982018-10-02 13:35:33 -07004540 if (!err && value_regno >= 0)
4541 mark_reg_unknown(env, regs, value_regno);
Matt Mullins9df1c282019-04-26 11:49:47 -07004542 } else if (reg->type == PTR_TO_TP_BUFFER) {
4543 err = check_tp_buffer_access(env, reg, regno, off, size);
4544 if (!err && t == BPF_READ && value_regno >= 0)
4545 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov9e15db62019-10-15 20:25:00 -07004546 } else if (reg->type == PTR_TO_BTF_ID) {
4547 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
4548 value_regno);
Andrey Ignatov41c48f32020-06-19 14:11:43 -07004549 } else if (reg->type == CONST_PTR_TO_MAP) {
4550 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
4551 value_regno);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004552 } else if (reg->type == PTR_TO_RDONLY_BUF) {
4553 if (t == BPF_WRITE) {
4554 verbose(env, "R%d cannot write into %s\n",
4555 regno, reg_type_str[reg->type]);
4556 return -EACCES;
4557 }
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004558 err = check_buffer_access(env, reg, regno, off, size, false,
4559 "rdonly",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004560 &env->prog->aux->max_rdonly_access);
4561 if (!err && value_regno >= 0)
4562 mark_reg_unknown(env, regs, value_regno);
4563 } else if (reg->type == PTR_TO_RDWR_BUF) {
Colin Ian Kingf6dfbe312020-07-27 18:54:11 +01004564 err = check_buffer_access(env, reg, regno, off, size, false,
4565 "rdwr",
Yonghong Songafbf21d2020-07-23 11:41:11 -07004566 &env->prog->aux->max_rdwr_access);
4567 if (!err && t == BPF_READ && value_regno >= 0)
4568 mark_reg_unknown(env, regs, value_regno);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004569 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004570 verbose(env, "R%d invalid mem access '%s'\n", regno,
4571 reg_type_str[reg->type]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004572 return -EACCES;
4573 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004574
Edward Creef1174f72017-08-07 15:26:19 +01004575 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004576 regs[value_regno].type == SCALAR_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01004577 /* b/h/w load zero-extends, mark upper bits as known 0 */
Jann Horn0c17d1d2017-12-18 20:11:55 -08004578 coerce_reg_to_size(&regs[value_regno], size);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07004579 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004580 return err;
4581}
4582
Brendan Jackman91c960b2021-01-14 18:17:44 +00004583static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004584{
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004585 int load_reg;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004586 int err;
4587
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004588 switch (insn->imm) {
4589 case BPF_ADD:
4590 case BPF_ADD | BPF_FETCH:
Brendan Jackman981f94c2021-01-14 18:17:49 +00004591 case BPF_AND:
4592 case BPF_AND | BPF_FETCH:
4593 case BPF_OR:
4594 case BPF_OR | BPF_FETCH:
4595 case BPF_XOR:
4596 case BPF_XOR | BPF_FETCH:
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004597 case BPF_XCHG:
4598 case BPF_CMPXCHG:
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004599 break;
4600 default:
Brendan Jackman91c960b2021-01-14 18:17:44 +00004601 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
4602 return -EINVAL;
4603 }
4604
4605 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
4606 verbose(env, "invalid atomic operand size\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004607 return -EINVAL;
4608 }
4609
4610 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004611 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004612 if (err)
4613 return err;
4614
4615 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01004616 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004617 if (err)
4618 return err;
4619
Brendan Jackman5ffa2552021-01-14 18:17:47 +00004620 if (insn->imm == BPF_CMPXCHG) {
4621 /* Check comparison of R0 with memory location */
4622 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
4623 if (err)
4624 return err;
4625 }
4626
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004627 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07004628 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
Daniel Borkmann6bdf6ab2017-06-29 03:04:59 +02004629 return -EACCES;
4630 }
4631
Daniel Borkmannca369602018-02-23 22:29:05 +01004632 if (is_ctx_reg(env, insn->dst_reg) ||
Daniel Borkmann4b5defd2018-10-21 02:09:25 +02004633 is_pkt_reg(env, insn->dst_reg) ||
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08004634 is_flow_key_reg(env, insn->dst_reg) ||
4635 is_sk_reg(env, insn->dst_reg)) {
Brendan Jackman91c960b2021-01-14 18:17:44 +00004636 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004637 insn->dst_reg,
4638 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +01004639 return -EACCES;
4640 }
4641
Brendan Jackman37086bf2021-02-02 13:50:02 +00004642 if (insn->imm & BPF_FETCH) {
4643 if (insn->imm == BPF_CMPXCHG)
4644 load_reg = BPF_REG_0;
4645 else
4646 load_reg = insn->src_reg;
4647
4648 /* check and record load of old value */
4649 err = check_reg_arg(env, load_reg, DST_OP);
4650 if (err)
4651 return err;
4652 } else {
4653 /* This instruction accesses a memory location but doesn't
4654 * actually load it into a register.
4655 */
4656 load_reg = -1;
4657 }
4658
Brendan Jackman91c960b2021-01-14 18:17:44 +00004659 /* check whether we can read the memory */
Yonghong Song31fd8582017-06-13 15:52:13 -07004660 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
Brendan Jackman37086bf2021-02-02 13:50:02 +00004661 BPF_SIZE(insn->code), BPF_READ, load_reg, true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004662 if (err)
4663 return err;
4664
Brendan Jackman91c960b2021-01-14 18:17:44 +00004665 /* check whether we can write into the same memory */
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004666 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
4667 BPF_SIZE(insn->code), BPF_WRITE, -1, true);
4668 if (err)
4669 return err;
4670
Brendan Jackman5ca419f2021-01-14 18:17:46 +00004671 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004672}
4673
Andrei Matei01f810a2021-02-06 20:10:24 -05004674/* When register 'regno' is used to read the stack (either directly or through
4675 * a helper function) make sure that it's within stack boundary and, depending
4676 * on the access type, that all elements of the stack are initialized.
4677 *
4678 * 'off' includes 'regno->off', but not its dynamic part (if any).
4679 *
4680 * All registers that have been spilled on the stack in the slots within the
4681 * read offsets are marked as read.
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004682 */
Andrei Matei01f810a2021-02-06 20:10:24 -05004683static int check_stack_range_initialized(
4684 struct bpf_verifier_env *env, int regno, int off,
4685 int access_size, bool zero_size_allowed,
4686 enum stack_access_src type, struct bpf_call_arg_meta *meta)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004687{
Daniel Borkmann2a159c62018-10-21 02:09:24 +02004688 struct bpf_reg_state *reg = reg_state(env, regno);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08004689 struct bpf_func_state *state = func(env, reg);
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004690 int err, min_off, max_off, i, j, slot, spi;
Andrei Matei01f810a2021-02-06 20:10:24 -05004691 char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
4692 enum bpf_access_type bounds_check_type;
4693 /* Some accesses can write anything into the stack, others are
4694 * read-only.
4695 */
4696 bool clobber = false;
4697
4698 if (access_size == 0 && !zero_size_allowed) {
4699 verbose(env, "invalid zero-sized read\n");
4700 return -EACCES;
4701 }
4702
4703 if (type == ACCESS_HELPER) {
4704 /* The bounds checks for writes are more permissive than for
4705 * reads. However, if raw_mode is not set, we'll do extra
4706 * checks below.
4707 */
4708 bounds_check_type = BPF_WRITE;
4709 clobber = true;
4710 } else {
4711 bounds_check_type = BPF_READ;
4712 }
4713 err = check_stack_access_within_bounds(env, regno, off, access_size,
4714 type, bounds_check_type);
4715 if (err)
4716 return err;
4717
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004718
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004719 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004720 min_off = max_off = reg->var_off.value + off;
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004721 } else {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004722 /* Variable offset is prohibited for unprivileged mode for
4723 * simplicity since it requires corresponding support in
4724 * Spectre masking for stack ALU.
4725 * See also retrieve_ptr_limit().
4726 */
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07004727 if (!env->bypass_spec_v1) {
Andrey Ignatov088ec262019-04-03 23:22:39 -07004728 char tn_buf[48];
Edward Creef1174f72017-08-07 15:26:19 +01004729
Andrey Ignatov088ec262019-04-03 23:22:39 -07004730 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004731 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
4732 regno, err_extra, tn_buf);
Andrey Ignatov088ec262019-04-03 23:22:39 -07004733 return -EACCES;
4734 }
Andrey Ignatovf2bcd052019-04-03 23:22:37 -07004735 /* Only initialized buffer on stack is allowed to be accessed
4736 * with variable offset. With uninitialized buffer it's hard to
4737 * guarantee that whole memory is marked as initialized on
4738 * helper return since specific bounds are unknown what may
4739 * cause uninitialized stack leaking.
4740 */
4741 if (meta && meta->raw_mode)
4742 meta = NULL;
4743
Andrei Matei01f810a2021-02-06 20:10:24 -05004744 min_off = reg->smin_value + off;
4745 max_off = reg->smax_value + off;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004746 }
4747
Daniel Borkmann435faee12016-04-13 00:10:51 +02004748 if (meta && meta->raw_mode) {
4749 meta->access_size = access_size;
4750 meta->regno = regno;
4751 return 0;
4752 }
4753
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004754 for (i = min_off; i < max_off + access_size; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004755 u8 *stype;
4756
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004757 slot = -i - 1;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004758 spi = slot / BPF_REG_SIZE;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004759 if (state->allocated_stack <= slot)
4760 goto err;
4761 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4762 if (*stype == STACK_MISC)
4763 goto mark;
4764 if (*stype == STACK_ZERO) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004765 if (clobber) {
4766 /* helper can write anything into the stack */
4767 *stype = STACK_MISC;
4768 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004769 goto mark;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004770 }
Yonghong Song1d68f222020-05-09 10:59:15 -07004771
Martin KaFai Lau27113c52021-09-21 17:49:34 -07004772 if (is_spilled_reg(&state->stack[spi]) &&
Yonghong Song1d68f222020-05-09 10:59:15 -07004773 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID)
4774 goto mark;
4775
Martin KaFai Lau27113c52021-09-21 17:49:34 -07004776 if (is_spilled_reg(&state->stack[spi]) &&
Yonghong Songcd17d382020-12-09 17:33:49 -08004777 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
4778 env->allow_ptr_leaks)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004779 if (clobber) {
4780 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
4781 for (j = 0; j < BPF_REG_SIZE; j++)
Martin KaFai Lau354e8f12021-09-21 17:49:41 -07004782 scrub_spilled_slot(&state->stack[spi].slot_type[j]);
Andrei Matei01f810a2021-02-06 20:10:24 -05004783 }
Alexei Starovoitovf7cf25b2019-06-15 12:12:17 -07004784 goto mark;
4785 }
4786
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004787err:
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004788 if (tnum_is_const(reg->var_off)) {
Andrei Matei01f810a2021-02-06 20:10:24 -05004789 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
4790 err_extra, regno, min_off, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004791 } else {
4792 char tn_buf[48];
4793
4794 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
Andrei Matei01f810a2021-02-06 20:10:24 -05004795 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
4796 err_extra, regno, tn_buf, i - min_off, access_size);
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004797 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -08004798 return -EACCES;
4799mark:
4800 /* reading any byte out of 8-byte 'spill_slot' will cause
4801 * the whole slot to be marked as 'read'
4802 */
Edward Cree679c7822018-08-22 20:02:19 +01004803 mark_reg_read(env, &state->stack[spi].spilled_ptr,
Jiong Wang5327ed32019-05-24 23:25:12 +01004804 state->stack[spi].spilled_ptr.parent,
4805 REG_LIVE_READ64);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004806 }
Andrey Ignatov2011fcc2019-03-28 18:01:57 -07004807 return update_stack_depth(env, state, min_off);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07004808}
4809
Gianluca Borello06c1c042017-01-09 10:19:49 -08004810static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
4811 int access_size, bool zero_size_allowed,
4812 struct bpf_call_arg_meta *meta)
4813{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07004814 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Gianluca Borello06c1c042017-01-09 10:19:49 -08004815
Edward Creef1174f72017-08-07 15:26:19 +01004816 switch (reg->type) {
Gianluca Borello06c1c042017-01-09 10:19:49 -08004817 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02004818 case PTR_TO_PACKET_META:
Yonghong Song9fd29c02017-11-12 14:49:09 -08004819 return check_packet_access(env, regno, reg->off, access_size,
4820 zero_size_allowed);
Yonghong Song69c087b2021-02-26 12:49:25 -08004821 case PTR_TO_MAP_KEY:
4822 return check_mem_region_access(env, regno, reg->off, access_size,
4823 reg->map_ptr->key_size, false);
Gianluca Borello06c1c042017-01-09 10:19:49 -08004824 case PTR_TO_MAP_VALUE:
Daniel Borkmann591fe982019-04-09 23:20:05 +02004825 if (check_map_access_type(env, regno, reg->off, access_size,
4826 meta && meta->raw_mode ? BPF_WRITE :
4827 BPF_READ))
4828 return -EACCES;
Yonghong Song9fd29c02017-11-12 14:49:09 -08004829 return check_map_access(env, regno, reg->off, access_size,
4830 zero_size_allowed);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07004831 case PTR_TO_MEM:
4832 return check_mem_region_access(env, regno, reg->off,
4833 access_size, reg->mem_size,
4834 zero_size_allowed);
Yonghong Songafbf21d2020-07-23 11:41:11 -07004835 case PTR_TO_RDONLY_BUF:
4836 if (meta && meta->raw_mode)
4837 return -EACCES;
4838 return check_buffer_access(env, reg, regno, reg->off,
4839 access_size, zero_size_allowed,
4840 "rdonly",
4841 &env->prog->aux->max_rdonly_access);
4842 case PTR_TO_RDWR_BUF:
4843 return check_buffer_access(env, reg, regno, reg->off,
4844 access_size, zero_size_allowed,
4845 "rdwr",
4846 &env->prog->aux->max_rdwr_access);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004847 case PTR_TO_STACK:
Andrei Matei01f810a2021-02-06 20:10:24 -05004848 return check_stack_range_initialized(
4849 env,
4850 regno, reg->off, access_size,
4851 zero_size_allowed, ACCESS_HELPER, meta);
Lorenz Bauer0d004c022020-09-21 13:12:18 +01004852 default: /* scalar_value or invalid ptr */
4853 /* Allow zero-byte read from NULL, regardless of pointer type */
4854 if (zero_size_allowed && access_size == 0 &&
4855 register_is_null(reg))
4856 return 0;
4857
4858 verbose(env, "R%d type=%s expected=%s\n", regno,
4859 reg_type_str[reg->type],
4860 reg_type_str[PTR_TO_STACK]);
4861 return -EACCES;
Gianluca Borello06c1c042017-01-09 10:19:49 -08004862 }
4863}
4864
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +04004865int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
4866 u32 regno, u32 mem_size)
4867{
4868 if (register_is_null(reg))
4869 return 0;
4870
4871 if (reg_type_may_be_null(reg->type)) {
4872 /* Assuming that the register contains a value check if the memory
4873 * access is safe. Temporarily save and restore the register's state as
4874 * the conversion shouldn't be visible to a caller.
4875 */
4876 const struct bpf_reg_state saved_reg = *reg;
4877 int rv;
4878
4879 mark_ptr_not_null_reg(reg);
4880 rv = check_helper_mem_access(env, regno, mem_size, true, NULL);
4881 *reg = saved_reg;
4882 return rv;
4883 }
4884
4885 return check_helper_mem_access(env, regno, mem_size, true, NULL);
4886}
4887
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004888/* Implementation details:
4889 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL
4890 * Two bpf_map_lookups (even with the same key) will have different reg->id.
4891 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after
4892 * value_or_null->value transition, since the verifier only cares about
4893 * the range of access to valid map value pointer and doesn't care about actual
4894 * address of the map element.
4895 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
4896 * reg->id > 0 after value_or_null->value transition. By doing so
4897 * two bpf_map_lookups will be considered two different pointers that
4898 * point to different bpf_spin_locks.
4899 * The verifier allows taking only one bpf_spin_lock at a time to avoid
4900 * dead-locks.
4901 * Since only one bpf_spin_lock is allowed the checks are simpler than
4902 * reg_is_refcounted() logic. The verifier needs to remember only
4903 * one spin_lock instead of array of acquired_refs.
4904 * cur_state->active_spin_lock remembers which map value element got locked
4905 * and clears it after bpf_spin_unlock.
4906 */
4907static int process_spin_lock(struct bpf_verifier_env *env, int regno,
4908 bool is_lock)
4909{
4910 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4911 struct bpf_verifier_state *cur = env->cur_state;
4912 bool is_const = tnum_is_const(reg->var_off);
4913 struct bpf_map *map = reg->map_ptr;
4914 u64 val = reg->var_off.value;
4915
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08004916 if (!is_const) {
4917 verbose(env,
4918 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
4919 regno);
4920 return -EINVAL;
4921 }
4922 if (!map->btf) {
4923 verbose(env,
4924 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
4925 map->name);
4926 return -EINVAL;
4927 }
4928 if (!map_value_has_spin_lock(map)) {
4929 if (map->spin_lock_off == -E2BIG)
4930 verbose(env,
4931 "map '%s' has more than one 'struct bpf_spin_lock'\n",
4932 map->name);
4933 else if (map->spin_lock_off == -ENOENT)
4934 verbose(env,
4935 "map '%s' doesn't have 'struct bpf_spin_lock'\n",
4936 map->name);
4937 else
4938 verbose(env,
4939 "map '%s' is not a struct type or bpf_spin_lock is mangled\n",
4940 map->name);
4941 return -EINVAL;
4942 }
4943 if (map->spin_lock_off != val + reg->off) {
4944 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n",
4945 val + reg->off);
4946 return -EINVAL;
4947 }
4948 if (is_lock) {
4949 if (cur->active_spin_lock) {
4950 verbose(env,
4951 "Locking two bpf_spin_locks are not allowed\n");
4952 return -EINVAL;
4953 }
4954 cur->active_spin_lock = reg->id;
4955 } else {
4956 if (!cur->active_spin_lock) {
4957 verbose(env, "bpf_spin_unlock without taking a lock\n");
4958 return -EINVAL;
4959 }
4960 if (cur->active_spin_lock != reg->id) {
4961 verbose(env, "bpf_spin_unlock of different lock\n");
4962 return -EINVAL;
4963 }
4964 cur->active_spin_lock = 0;
4965 }
4966 return 0;
4967}
4968
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07004969static int process_timer_func(struct bpf_verifier_env *env, int regno,
4970 struct bpf_call_arg_meta *meta)
4971{
4972 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
4973 bool is_const = tnum_is_const(reg->var_off);
4974 struct bpf_map *map = reg->map_ptr;
4975 u64 val = reg->var_off.value;
4976
4977 if (!is_const) {
4978 verbose(env,
4979 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
4980 regno);
4981 return -EINVAL;
4982 }
4983 if (!map->btf) {
4984 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
4985 map->name);
4986 return -EINVAL;
4987 }
Alexei Starovoitov68134662021-07-14 17:54:10 -07004988 if (!map_value_has_timer(map)) {
4989 if (map->timer_off == -E2BIG)
4990 verbose(env,
4991 "map '%s' has more than one 'struct bpf_timer'\n",
4992 map->name);
4993 else if (map->timer_off == -ENOENT)
4994 verbose(env,
4995 "map '%s' doesn't have 'struct bpf_timer'\n",
4996 map->name);
4997 else
4998 verbose(env,
4999 "map '%s' is not a struct type or bpf_timer is mangled\n",
5000 map->name);
5001 return -EINVAL;
5002 }
5003 if (map->timer_off != val + reg->off) {
5004 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
5005 val + reg->off, map->timer_off);
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005006 return -EINVAL;
5007 }
5008 if (meta->map_ptr) {
5009 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
5010 return -EFAULT;
5011 }
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -07005012 meta->map_uid = reg->map_uid;
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005013 meta->map_ptr = map;
5014 return 0;
5015}
5016
Daniel Borkmann90133412018-01-20 01:24:29 +01005017static bool arg_type_is_mem_ptr(enum bpf_arg_type type)
5018{
5019 return type == ARG_PTR_TO_MEM ||
5020 type == ARG_PTR_TO_MEM_OR_NULL ||
5021 type == ARG_PTR_TO_UNINIT_MEM;
5022}
5023
5024static bool arg_type_is_mem_size(enum bpf_arg_type type)
5025{
5026 return type == ARG_CONST_SIZE ||
5027 type == ARG_CONST_SIZE_OR_ZERO;
5028}
5029
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005030static bool arg_type_is_alloc_size(enum bpf_arg_type type)
5031{
5032 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO;
5033}
5034
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07005035static bool arg_type_is_int_ptr(enum bpf_arg_type type)
5036{
5037 return type == ARG_PTR_TO_INT ||
5038 type == ARG_PTR_TO_LONG;
5039}
5040
5041static int int_ptr_type_to_size(enum bpf_arg_type type)
5042{
5043 if (type == ARG_PTR_TO_INT)
5044 return sizeof(u32);
5045 else if (type == ARG_PTR_TO_LONG)
5046 return sizeof(u64);
5047
5048 return -EINVAL;
5049}
5050
Lorenz Bauer912f4422020-08-21 11:29:46 +01005051static int resolve_map_arg_type(struct bpf_verifier_env *env,
5052 const struct bpf_call_arg_meta *meta,
5053 enum bpf_arg_type *arg_type)
5054{
5055 if (!meta->map_ptr) {
5056 /* kernel subsystem misconfigured verifier */
5057 verbose(env, "invalid map_ptr to access map->type\n");
5058 return -EACCES;
5059 }
5060
5061 switch (meta->map_ptr->map_type) {
5062 case BPF_MAP_TYPE_SOCKMAP:
5063 case BPF_MAP_TYPE_SOCKHASH:
5064 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
Lorenz Bauer6550f2d2020-09-28 10:08:02 +01005065 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
Lorenz Bauer912f4422020-08-21 11:29:46 +01005066 } else {
5067 verbose(env, "invalid arg_type for sockmap/sockhash\n");
5068 return -EINVAL;
5069 }
5070 break;
Joanne Koong93309862021-10-27 16:45:00 -07005071 case BPF_MAP_TYPE_BLOOM_FILTER:
5072 if (meta->func_id == BPF_FUNC_map_peek_elem)
5073 *arg_type = ARG_PTR_TO_MAP_VALUE;
5074 break;
Lorenz Bauer912f4422020-08-21 11:29:46 +01005075 default:
5076 break;
5077 }
5078 return 0;
5079}
5080
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005081struct bpf_reg_types {
5082 const enum bpf_reg_type types[10];
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005083 u32 *btf_id;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005084};
5085
5086static const struct bpf_reg_types map_key_value_types = {
5087 .types = {
5088 PTR_TO_STACK,
5089 PTR_TO_PACKET,
5090 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08005091 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005092 PTR_TO_MAP_VALUE,
5093 },
5094};
5095
5096static const struct bpf_reg_types sock_types = {
5097 .types = {
5098 PTR_TO_SOCK_COMMON,
5099 PTR_TO_SOCKET,
5100 PTR_TO_TCP_SOCK,
5101 PTR_TO_XDP_SOCK,
5102 },
5103};
5104
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07005105#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005106static const struct bpf_reg_types btf_id_sock_common_types = {
5107 .types = {
5108 PTR_TO_SOCK_COMMON,
5109 PTR_TO_SOCKET,
5110 PTR_TO_TCP_SOCK,
5111 PTR_TO_XDP_SOCK,
5112 PTR_TO_BTF_ID,
5113 },
5114 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5115};
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07005116#endif
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005117
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005118static const struct bpf_reg_types mem_types = {
5119 .types = {
5120 PTR_TO_STACK,
5121 PTR_TO_PACKET,
5122 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08005123 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005124 PTR_TO_MAP_VALUE,
5125 PTR_TO_MEM,
5126 PTR_TO_RDONLY_BUF,
5127 PTR_TO_RDWR_BUF,
5128 },
5129};
5130
5131static const struct bpf_reg_types int_ptr_types = {
5132 .types = {
5133 PTR_TO_STACK,
5134 PTR_TO_PACKET,
5135 PTR_TO_PACKET_META,
Yonghong Song69c087b2021-02-26 12:49:25 -08005136 PTR_TO_MAP_KEY,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005137 PTR_TO_MAP_VALUE,
5138 },
5139};
5140
5141static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
5142static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
5143static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
5144static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } };
5145static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
5146static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } };
5147static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } };
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005148static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
Yonghong Song69c087b2021-02-26 12:49:25 -08005149static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
5150static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
Florent Revestfff13c42021-04-19 17:52:39 +02005151static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005152static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005153
Lorenz Bauer0789e13b2020-09-23 17:01:55 +01005154static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005155 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types,
5156 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types,
5157 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types,
5158 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types,
5159 [ARG_CONST_SIZE] = &scalar_types,
5160 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types,
5161 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types,
5162 [ARG_CONST_MAP_PTR] = &const_map_ptr_types,
5163 [ARG_PTR_TO_CTX] = &context_types,
5164 [ARG_PTR_TO_CTX_OR_NULL] = &context_types,
5165 [ARG_PTR_TO_SOCK_COMMON] = &sock_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07005166#ifdef CONFIG_NET
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005167 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
Randy Dunlap49a2a4d2020-10-06 19:16:13 -07005168#endif
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005169 [ARG_PTR_TO_SOCKET] = &fullsock_types,
5170 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types,
5171 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types,
5172 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types,
5173 [ARG_PTR_TO_MEM] = &mem_types,
5174 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types,
5175 [ARG_PTR_TO_UNINIT_MEM] = &mem_types,
5176 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types,
5177 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types,
5178 [ARG_PTR_TO_INT] = &int_ptr_types,
5179 [ARG_PTR_TO_LONG] = &int_ptr_types,
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005180 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types,
Yonghong Song69c087b2021-02-26 12:49:25 -08005181 [ARG_PTR_TO_FUNC] = &func_ptr_types,
5182 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types,
Florent Revestfff13c42021-04-19 17:52:39 +02005183 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types,
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005184 [ARG_PTR_TO_TIMER] = &timer_types,
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005185};
5186
5187static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005188 enum bpf_arg_type arg_type,
5189 const u32 *arg_btf_id)
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005190{
5191 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
5192 enum bpf_reg_type expected, type = reg->type;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005193 const struct bpf_reg_types *compatible;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005194 int i, j;
5195
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005196 compatible = compatible_reg_types[arg_type];
5197 if (!compatible) {
5198 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
5199 return -EFAULT;
5200 }
5201
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005202 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
5203 expected = compatible->types[i];
5204 if (expected == NOT_INIT)
5205 break;
5206
5207 if (type == expected)
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005208 goto found;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005209 }
5210
5211 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]);
5212 for (j = 0; j + 1 < i; j++)
5213 verbose(env, "%s, ", reg_type_str[compatible->types[j]]);
5214 verbose(env, "%s\n", reg_type_str[compatible->types[j]]);
5215 return -EACCES;
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005216
5217found:
5218 if (type == PTR_TO_BTF_ID) {
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005219 if (!arg_btf_id) {
5220 if (!compatible->btf_id) {
5221 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
5222 return -EFAULT;
5223 }
5224 arg_btf_id = compatible->btf_id;
5225 }
5226
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005227 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5228 btf_vmlinux, *arg_btf_id)) {
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005229 verbose(env, "R%d is of type %s but %s is expected\n",
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005230 regno, kernel_type_name(reg->btf, reg->btf_id),
5231 kernel_type_name(btf_vmlinux, *arg_btf_id));
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005232 return -EACCES;
5233 }
5234
5235 if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5236 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n",
5237 regno);
5238 return -EACCES;
5239 }
5240 }
5241
5242 return 0;
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005243}
5244
Yonghong Songaf7ec132020-06-23 16:08:09 -07005245static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
5246 struct bpf_call_arg_meta *meta,
5247 const struct bpf_func_proto *fn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005248{
Yonghong Songaf7ec132020-06-23 16:08:09 -07005249 u32 regno = BPF_REG_1 + arg;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07005250 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
Yonghong Songaf7ec132020-06-23 16:08:09 -07005251 enum bpf_arg_type arg_type = fn->arg_type[arg];
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005252 enum bpf_reg_type type = reg->type;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005253 int err = 0;
5254
Daniel Borkmann80f1d682015-03-12 17:21:42 +01005255 if (arg_type == ARG_DONTCARE)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005256 return 0;
5257
Edward Creedc503a82017-08-15 20:34:35 +01005258 err = check_reg_arg(env, regno, SRC_OP);
5259 if (err)
5260 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005261
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005262 if (arg_type == ARG_ANYTHING) {
5263 if (is_pointer_value(env, regno)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005264 verbose(env, "R%d leaks addr into helper function\n",
5265 regno);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005266 return -EACCES;
5267 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01005268 return 0;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07005269 }
Daniel Borkmann80f1d682015-03-12 17:21:42 +01005270
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005271 if (type_is_pkt_pointer(type) &&
Thomas Graf3a0af8f2016-11-30 17:10:10 +01005272 !may_access_direct_pkt_data(env, meta, BPF_READ)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005273 verbose(env, "helper access to the packet is not allowed\n");
Alexei Starovoitov6841de82016-08-11 18:17:16 -07005274 return -EACCES;
5275 }
5276
Lorenz Bauer912f4422020-08-21 11:29:46 +01005277 if (arg_type == ARG_PTR_TO_MAP_VALUE ||
5278 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE ||
5279 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) {
5280 err = resolve_map_arg_type(env, meta, &arg_type);
5281 if (err)
5282 return err;
5283 }
5284
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01005285 if (register_is_null(reg) && arg_type_may_be_null(arg_type))
5286 /* A NULL register has a SCALAR_VALUE type, so skip
5287 * type checking.
5288 */
5289 goto skip_type_check;
Jiri Olsafaaf4a72020-08-25 21:21:18 +02005290
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005291 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]);
Lorenz Bauerf79e7ea2020-09-21 13:12:27 +01005292 if (err)
5293 return err;
5294
Martin KaFai Laua968d5e2020-09-24 17:03:44 -07005295 if (type == PTR_TO_CTX) {
Lorenz Bauerfeec7042020-09-21 13:12:23 +01005296 err = check_ctx_reg(env, reg, regno);
5297 if (err < 0)
5298 return err;
Lorenz Bauerd7b94542020-09-21 13:12:21 +01005299 }
5300
Lorenz Bauerfd1b0d62020-09-21 13:12:26 +01005301skip_type_check:
Lorenz Bauer02f7c952020-09-21 13:12:22 +01005302 if (reg->ref_obj_id) {
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005303 if (meta->ref_obj_id) {
5304 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
5305 regno, reg->ref_obj_id,
5306 meta->ref_obj_id);
5307 return -EFAULT;
5308 }
5309 meta->ref_obj_id = reg->ref_obj_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005310 }
5311
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005312 if (arg_type == ARG_CONST_MAP_PTR) {
5313 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -07005314 if (meta->map_ptr) {
5315 /* Use map_uid (which is unique id of inner map) to reject:
5316 * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
5317 * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
5318 * if (inner_map1 && inner_map2) {
5319 * timer = bpf_map_lookup_elem(inner_map1);
5320 * if (timer)
5321 * // mismatch would have been allowed
5322 * bpf_timer_init(timer, inner_map2);
5323 * }
5324 *
5325 * Comparing map_ptr is enough to distinguish normal and outer maps.
5326 */
5327 if (meta->map_ptr != reg->map_ptr ||
5328 meta->map_uid != reg->map_uid) {
5329 verbose(env,
5330 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
5331 meta->map_uid, reg->map_uid);
5332 return -EINVAL;
5333 }
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005334 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005335 meta->map_ptr = reg->map_ptr;
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -07005336 meta->map_uid = reg->map_uid;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005337 } else if (arg_type == ARG_PTR_TO_MAP_KEY) {
5338 /* bpf_map_xxx(..., map_ptr, ..., key) call:
5339 * check that [key, key + map->key_size) are within
5340 * stack limits and initialized
5341 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005342 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005343 /* in function declaration map_ptr must come before
5344 * map_key, so that it's verified and known before
5345 * we have to check map_key here. Otherwise it means
5346 * that kernel subsystem misconfigured verifier
5347 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005348 verbose(env, "invalid map_ptr to access map->key\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005349 return -EACCES;
5350 }
Paul Chaignond71962f2018-04-24 15:07:54 +02005351 err = check_helper_mem_access(env, regno,
5352 meta->map_ptr->key_size, false,
5353 NULL);
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02005354 } else if (arg_type == ARG_PTR_TO_MAP_VALUE ||
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005355 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL &&
5356 !register_is_null(reg)) ||
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02005357 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005358 /* bpf_map_xxx(..., map_ptr, ..., value) call:
5359 * check [value, value + map->value_size) validity
5360 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02005361 if (!meta->map_ptr) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005362 /* kernel subsystem misconfigured verifier */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005363 verbose(env, "invalid map_ptr to access map->value\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005364 return -EACCES;
5365 }
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02005366 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE);
Paul Chaignond71962f2018-04-24 15:07:54 +02005367 err = check_helper_mem_access(env, regno,
5368 meta->map_ptr->value_size, false,
Mauricio Vasquez B2ea864c2018-10-18 15:16:20 +02005369 meta);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005370 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) {
5371 if (!reg->btf_id) {
5372 verbose(env, "Helper has invalid btf_id in R%d\n", regno);
5373 return -EACCES;
5374 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08005375 meta->ret_btf = reg->btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07005376 meta->ret_btf_id = reg->btf_id;
Lorenz Bauerc18f0b62020-09-21 13:12:25 +01005377 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) {
5378 if (meta->func_id == BPF_FUNC_spin_lock) {
5379 if (process_spin_lock(env, regno, true))
5380 return -EACCES;
5381 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
5382 if (process_spin_lock(env, regno, false))
5383 return -EACCES;
5384 } else {
5385 verbose(env, "verifier internal error\n");
5386 return -EFAULT;
5387 }
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07005388 } else if (arg_type == ARG_PTR_TO_TIMER) {
5389 if (process_timer_func(env, regno, meta))
5390 return -EACCES;
Yonghong Song69c087b2021-02-26 12:49:25 -08005391 } else if (arg_type == ARG_PTR_TO_FUNC) {
5392 meta->subprogno = reg->subprogno;
Lorenz Bauera2bbe7c2020-09-21 13:12:24 +01005393 } else if (arg_type_is_mem_ptr(arg_type)) {
5394 /* The access to this pointer is only checked when we hit the
5395 * next is_mem_size argument below.
5396 */
5397 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM);
Daniel Borkmann90133412018-01-20 01:24:29 +01005398 } else if (arg_type_is_mem_size(arg_type)) {
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005399 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005400
John Fastabend10060502020-03-30 14:36:19 -07005401 /* This is used to refine r0 return value bounds for helpers
5402 * that enforce this value as an upper bound on return values.
5403 * See do_refine_retval_range() for helpers that can refine
5404 * the return value. C type of helper is u32 so we pull register
5405 * bound from umax_value however, if negative verifier errors
5406 * out. Only upper bounds can be learned because retval is an
5407 * int type and negative retvals are allowed.
Yonghong Song849fa502018-04-28 22:28:09 -07005408 */
John Fastabend10060502020-03-30 14:36:19 -07005409 meta->msize_max_value = reg->umax_value;
Yonghong Song849fa502018-04-28 22:28:09 -07005410
Edward Creef1174f72017-08-07 15:26:19 +01005411 /* The register is SCALAR_VALUE; the access check
5412 * happens using its boundaries.
Gianluca Borello06c1c042017-01-09 10:19:49 -08005413 */
Edward Creef1174f72017-08-07 15:26:19 +01005414 if (!tnum_is_const(reg->var_off))
Gianluca Borello06c1c042017-01-09 10:19:49 -08005415 /* For unprivileged variable accesses, disable raw
5416 * mode so that the program is required to
5417 * initialize all the memory that the helper could
5418 * just partially fill up.
5419 */
5420 meta = NULL;
5421
Edward Creeb03c9f92017-08-07 15:26:36 +01005422 if (reg->smin_value < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005423 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005424 regno);
5425 return -EACCES;
5426 }
Gianluca Borello06c1c042017-01-09 10:19:49 -08005427
Edward Creeb03c9f92017-08-07 15:26:36 +01005428 if (reg->umin_value == 0) {
Edward Creef1174f72017-08-07 15:26:19 +01005429 err = check_helper_mem_access(env, regno - 1, 0,
5430 zero_size_allowed,
5431 meta);
Gianluca Borello06c1c042017-01-09 10:19:49 -08005432 if (err)
5433 return err;
Gianluca Borello06c1c042017-01-09 10:19:49 -08005434 }
Edward Creef1174f72017-08-07 15:26:19 +01005435
Edward Creeb03c9f92017-08-07 15:26:36 +01005436 if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005437 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
Edward Creef1174f72017-08-07 15:26:19 +01005438 regno);
5439 return -EACCES;
5440 }
5441 err = check_helper_mem_access(env, regno - 1,
Edward Creeb03c9f92017-08-07 15:26:36 +01005442 reg->umax_value,
Edward Creef1174f72017-08-07 15:26:19 +01005443 zero_size_allowed, meta);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07005444 if (!err)
5445 err = mark_chain_precision(env, regno);
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005446 } else if (arg_type_is_alloc_size(arg_type)) {
5447 if (!tnum_is_const(reg->var_off)) {
Brendan Jackman28a8add2021-01-12 12:39:13 +00005448 verbose(env, "R%d is not a known constant'\n",
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005449 regno);
5450 return -EACCES;
5451 }
5452 meta->mem_size = reg->var_off.value;
Andrey Ignatov57c3bb72019-03-18 16:57:10 -07005453 } else if (arg_type_is_int_ptr(arg_type)) {
5454 int size = int_ptr_type_to_size(arg_type);
5455
5456 err = check_helper_mem_access(env, regno, size, false, meta);
5457 if (err)
5458 return err;
5459 err = check_ptr_alignment(env, reg, 0, size, true);
Florent Revestfff13c42021-04-19 17:52:39 +02005460 } else if (arg_type == ARG_PTR_TO_CONST_STR) {
5461 struct bpf_map *map = reg->map_ptr;
5462 int map_off;
5463 u64 map_addr;
5464 char *str_ptr;
5465
Florent Revesta8fad732021-04-23 01:55:43 +02005466 if (!bpf_map_is_rdonly(map)) {
Florent Revestfff13c42021-04-19 17:52:39 +02005467 verbose(env, "R%d does not point to a readonly map'\n", regno);
5468 return -EACCES;
5469 }
5470
5471 if (!tnum_is_const(reg->var_off)) {
5472 verbose(env, "R%d is not a constant address'\n", regno);
5473 return -EACCES;
5474 }
5475
5476 if (!map->ops->map_direct_value_addr) {
5477 verbose(env, "no direct value access support for this map type\n");
5478 return -EACCES;
5479 }
5480
5481 err = check_map_access(env, regno, reg->off,
5482 map->value_size - reg->off, false);
5483 if (err)
5484 return err;
5485
5486 map_off = reg->off + reg->var_off.value;
5487 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
5488 if (err) {
5489 verbose(env, "direct value access on string failed\n");
5490 return err;
5491 }
5492
5493 str_ptr = (char *)(long)(map_addr);
5494 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
5495 verbose(env, "string is not zero-terminated\n");
5496 return -EINVAL;
5497 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07005498 }
5499
5500 return err;
5501}
5502
Lorenz Bauer01262402020-08-21 11:29:47 +01005503static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
5504{
5505 enum bpf_attach_type eatype = env->prog->expected_attach_type;
Udip Pant7e407812020-08-25 16:20:00 -07005506 enum bpf_prog_type type = resolve_prog_type(env->prog);
Lorenz Bauer01262402020-08-21 11:29:47 +01005507
5508 if (func_id != BPF_FUNC_map_update_elem)
5509 return false;
5510
5511 /* It's not possible to get access to a locked struct sock in these
5512 * contexts, so updating is safe.
5513 */
5514 switch (type) {
5515 case BPF_PROG_TYPE_TRACING:
5516 if (eatype == BPF_TRACE_ITER)
5517 return true;
5518 break;
5519 case BPF_PROG_TYPE_SOCKET_FILTER:
5520 case BPF_PROG_TYPE_SCHED_CLS:
5521 case BPF_PROG_TYPE_SCHED_ACT:
5522 case BPF_PROG_TYPE_XDP:
5523 case BPF_PROG_TYPE_SK_REUSEPORT:
5524 case BPF_PROG_TYPE_FLOW_DISSECTOR:
5525 case BPF_PROG_TYPE_SK_LOOKUP:
5526 return true;
5527 default:
5528 break;
5529 }
5530
5531 verbose(env, "cannot update sockmap in this context\n");
5532 return false;
5533}
5534
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005535static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
5536{
5537 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64);
5538}
5539
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005540static int check_map_func_compatibility(struct bpf_verifier_env *env,
5541 struct bpf_map *map, int func_id)
Kaixu Xia35578d72015-08-06 07:02:35 +00005542{
Kaixu Xia35578d72015-08-06 07:02:35 +00005543 if (!map)
5544 return 0;
5545
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005546 /* We need a two way check, first is from map perspective ... */
5547 switch (map->map_type) {
5548 case BPF_MAP_TYPE_PROG_ARRAY:
5549 if (func_id != BPF_FUNC_tail_call)
5550 goto error;
5551 break;
5552 case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
5553 if (func_id != BPF_FUNC_perf_event_read &&
Yonghong Song908432c2017-10-05 09:19:20 -07005554 func_id != BPF_FUNC_perf_event_output &&
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005555 func_id != BPF_FUNC_skb_output &&
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005556 func_id != BPF_FUNC_perf_event_read_value &&
5557 func_id != BPF_FUNC_xdp_output)
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005558 goto error;
5559 break;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005560 case BPF_MAP_TYPE_RINGBUF:
5561 if (func_id != BPF_FUNC_ringbuf_output &&
5562 func_id != BPF_FUNC_ringbuf_reserve &&
Andrii Nakryiko457f4432020-05-29 00:54:20 -07005563 func_id != BPF_FUNC_ringbuf_query)
5564 goto error;
5565 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005566 case BPF_MAP_TYPE_STACK_TRACE:
5567 if (func_id != BPF_FUNC_get_stackid)
5568 goto error;
5569 break;
Martin KaFai Lau4ed8ec52016-06-30 10:28:43 -07005570 case BPF_MAP_TYPE_CGROUP_ARRAY:
David S. Miller60747ef2016-08-18 01:17:32 -04005571 if (func_id != BPF_FUNC_skb_under_cgroup &&
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005572 func_id != BPF_FUNC_current_task_under_cgroup)
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005573 goto error;
5574 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005575 case BPF_MAP_TYPE_CGROUP_STORAGE:
Roman Gushchinb741f162018-09-28 14:45:43 +00005576 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
Roman Gushchincd339432018-08-02 14:27:24 -07005577 if (func_id != BPF_FUNC_get_local_storage)
5578 goto error;
5579 break;
John Fastabend546ac1f2017-07-17 09:28:56 -07005580 case BPF_MAP_TYPE_DEVMAP:
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005581 case BPF_MAP_TYPE_DEVMAP_HASH:
Toke Høiland-Jørgensen0cdbb4b2019-06-28 11:12:35 +02005582 if (func_id != BPF_FUNC_redirect_map &&
5583 func_id != BPF_FUNC_map_lookup_elem)
John Fastabend546ac1f2017-07-17 09:28:56 -07005584 goto error;
5585 break;
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005586 /* Restrict bpf side of cpumap and xskmap, open when use-cases
5587 * appear.
5588 */
Jesper Dangaard Brouer6710e112017-10-16 12:19:28 +02005589 case BPF_MAP_TYPE_CPUMAP:
5590 if (func_id != BPF_FUNC_redirect_map)
5591 goto error;
5592 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07005593 case BPF_MAP_TYPE_XSKMAP:
5594 if (func_id != BPF_FUNC_redirect_map &&
5595 func_id != BPF_FUNC_map_lookup_elem)
5596 goto error;
5597 break;
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005598 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -07005599 case BPF_MAP_TYPE_HASH_OF_MAPS:
Martin KaFai Lau56f668d2017-03-22 10:00:33 -07005600 if (func_id != BPF_FUNC_map_lookup_elem)
5601 goto error;
Martin KaFai Lau16a43622017-08-17 18:14:43 -07005602 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005603 case BPF_MAP_TYPE_SOCKMAP:
5604 if (func_id != BPF_FUNC_sk_redirect_map &&
5605 func_id != BPF_FUNC_sock_map_update &&
John Fastabend4f738ad2018-03-18 12:57:10 -07005606 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005607 func_id != BPF_FUNC_msg_redirect_map &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005608 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005609 func_id != BPF_FUNC_map_lookup_elem &&
5610 !may_update_sockmap(env, func_id))
John Fastabend174a79f2017-08-15 22:32:47 -07005611 goto error;
5612 break;
John Fastabend81110382018-05-14 10:00:17 -07005613 case BPF_MAP_TYPE_SOCKHASH:
5614 if (func_id != BPF_FUNC_sk_redirect_hash &&
5615 func_id != BPF_FUNC_sock_hash_update &&
5616 func_id != BPF_FUNC_map_delete_elem &&
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005617 func_id != BPF_FUNC_msg_redirect_hash &&
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005618 func_id != BPF_FUNC_sk_select_reuseport &&
Lorenz Bauer01262402020-08-21 11:29:47 +01005619 func_id != BPF_FUNC_map_lookup_elem &&
5620 !may_update_sockmap(env, func_id))
John Fastabend81110382018-05-14 10:00:17 -07005621 goto error;
5622 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005623 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
5624 if (func_id != BPF_FUNC_sk_select_reuseport)
5625 goto error;
5626 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005627 case BPF_MAP_TYPE_QUEUE:
5628 case BPF_MAP_TYPE_STACK:
5629 if (func_id != BPF_FUNC_map_peek_elem &&
5630 func_id != BPF_FUNC_map_pop_elem &&
5631 func_id != BPF_FUNC_map_push_elem)
5632 goto error;
5633 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005634 case BPF_MAP_TYPE_SK_STORAGE:
5635 if (func_id != BPF_FUNC_sk_storage_get &&
5636 func_id != BPF_FUNC_sk_storage_delete)
5637 goto error;
5638 break;
KP Singh8ea63682020-08-25 20:29:17 +02005639 case BPF_MAP_TYPE_INODE_STORAGE:
5640 if (func_id != BPF_FUNC_inode_storage_get &&
5641 func_id != BPF_FUNC_inode_storage_delete)
5642 goto error;
5643 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005644 case BPF_MAP_TYPE_TASK_STORAGE:
5645 if (func_id != BPF_FUNC_task_storage_get &&
5646 func_id != BPF_FUNC_task_storage_delete)
5647 goto error;
5648 break;
Joanne Koong93309862021-10-27 16:45:00 -07005649 case BPF_MAP_TYPE_BLOOM_FILTER:
5650 if (func_id != BPF_FUNC_map_peek_elem &&
5651 func_id != BPF_FUNC_map_push_elem)
5652 goto error;
5653 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005654 default:
5655 break;
5656 }
5657
5658 /* ... and second from the function itself. */
5659 switch (func_id) {
5660 case BPF_FUNC_tail_call:
5661 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
5662 goto error;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +02005663 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
5664 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005665 return -EINVAL;
5666 }
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005667 break;
5668 case BPF_FUNC_perf_event_read:
5669 case BPF_FUNC_perf_event_output:
Yonghong Song908432c2017-10-05 09:19:20 -07005670 case BPF_FUNC_perf_event_read_value:
Alexei Starovoitova7658e12019-10-15 20:25:04 -07005671 case BPF_FUNC_skb_output:
Eelco Chaudrond831ee82020-03-06 08:59:23 +00005672 case BPF_FUNC_xdp_output:
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005673 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
5674 goto error;
5675 break;
Daniel Borkmann5b029a32021-08-23 21:02:09 +02005676 case BPF_FUNC_ringbuf_output:
5677 case BPF_FUNC_ringbuf_reserve:
5678 case BPF_FUNC_ringbuf_query:
5679 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
5680 goto error;
5681 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005682 case BPF_FUNC_get_stackid:
5683 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
5684 goto error;
5685 break;
Sargun Dhillon60d20f92016-08-12 08:56:52 -07005686 case BPF_FUNC_current_task_under_cgroup:
Daniel Borkmann747ea552016-08-12 22:17:17 +02005687 case BPF_FUNC_skb_under_cgroup:
Martin KaFai Lau4a482f32016-06-30 10:28:44 -07005688 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
5689 goto error;
5690 break;
John Fastabend97f91a72017-07-17 09:29:18 -07005691 case BPF_FUNC_redirect_map:
Jesper Dangaard Brouer9c270af2017-10-16 12:19:34 +02005692 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
Toke Høiland-Jørgensen6f9d4512019-07-26 18:06:55 +02005693 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
Björn Töpelfbfc504a2018-05-02 13:01:28 +02005694 map->map_type != BPF_MAP_TYPE_CPUMAP &&
5695 map->map_type != BPF_MAP_TYPE_XSKMAP)
John Fastabend97f91a72017-07-17 09:29:18 -07005696 goto error;
5697 break;
John Fastabend174a79f2017-08-15 22:32:47 -07005698 case BPF_FUNC_sk_redirect_map:
John Fastabend4f738ad2018-03-18 12:57:10 -07005699 case BPF_FUNC_msg_redirect_map:
John Fastabend81110382018-05-14 10:00:17 -07005700 case BPF_FUNC_sock_map_update:
John Fastabend174a79f2017-08-15 22:32:47 -07005701 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
5702 goto error;
5703 break;
John Fastabend81110382018-05-14 10:00:17 -07005704 case BPF_FUNC_sk_redirect_hash:
5705 case BPF_FUNC_msg_redirect_hash:
5706 case BPF_FUNC_sock_hash_update:
5707 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
John Fastabend174a79f2017-08-15 22:32:47 -07005708 goto error;
5709 break;
Roman Gushchincd339432018-08-02 14:27:24 -07005710 case BPF_FUNC_get_local_storage:
Roman Gushchinb741f162018-09-28 14:45:43 +00005711 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
5712 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
Roman Gushchincd339432018-08-02 14:27:24 -07005713 goto error;
5714 break;
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005715 case BPF_FUNC_sk_select_reuseport:
Jakub Sitnicki9fed9002020-02-18 17:10:20 +00005716 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
5717 map->map_type != BPF_MAP_TYPE_SOCKMAP &&
5718 map->map_type != BPF_MAP_TYPE_SOCKHASH)
Martin KaFai Lau2dbb9b92018-08-08 01:01:25 -07005719 goto error;
5720 break;
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005721 case BPF_FUNC_map_pop_elem:
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02005722 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5723 map->map_type != BPF_MAP_TYPE_STACK)
5724 goto error;
5725 break;
Joanne Koong93309862021-10-27 16:45:00 -07005726 case BPF_FUNC_map_peek_elem:
5727 case BPF_FUNC_map_push_elem:
5728 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
5729 map->map_type != BPF_MAP_TYPE_STACK &&
5730 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
5731 goto error;
5732 break;
Martin KaFai Lau6ac99e82019-04-26 16:39:39 -07005733 case BPF_FUNC_sk_storage_get:
5734 case BPF_FUNC_sk_storage_delete:
5735 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
5736 goto error;
5737 break;
KP Singh8ea63682020-08-25 20:29:17 +02005738 case BPF_FUNC_inode_storage_get:
5739 case BPF_FUNC_inode_storage_delete:
5740 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
5741 goto error;
5742 break;
KP Singh4cf1bc12020-11-06 10:37:40 +00005743 case BPF_FUNC_task_storage_get:
5744 case BPF_FUNC_task_storage_delete:
5745 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
5746 goto error;
5747 break;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005748 default:
5749 break;
Kaixu Xia35578d72015-08-06 07:02:35 +00005750 }
5751
5752 return 0;
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005753error:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005754 verbose(env, "cannot pass map_type %d into func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02005755 map->map_type, func_id_name(func_id), func_id);
Alexei Starovoitov6aff67c2016-04-27 18:56:21 -07005756 return -EINVAL;
Kaixu Xia35578d72015-08-06 07:02:35 +00005757}
5758
Daniel Borkmann90133412018-01-20 01:24:29 +01005759static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005760{
5761 int count = 0;
5762
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005763 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005764 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005765 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005766 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005767 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005768 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005769 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005770 count++;
Alexei Starovoitov39f19ebb2017-01-09 10:19:50 -08005771 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
Daniel Borkmann435faee12016-04-13 00:10:51 +02005772 count++;
5773
Daniel Borkmann90133412018-01-20 01:24:29 +01005774 /* We only support one arg being in raw mode at the moment,
5775 * which is sufficient for the helper functions we have
5776 * right now.
5777 */
5778 return count <= 1;
5779}
5780
5781static bool check_args_pair_invalid(enum bpf_arg_type arg_curr,
5782 enum bpf_arg_type arg_next)
5783{
5784 return (arg_type_is_mem_ptr(arg_curr) &&
5785 !arg_type_is_mem_size(arg_next)) ||
5786 (!arg_type_is_mem_ptr(arg_curr) &&
5787 arg_type_is_mem_size(arg_next));
5788}
5789
5790static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
5791{
5792 /* bpf_xxx(..., buf, len) call will access 'len'
5793 * bytes from memory 'buf'. Both arg types need
5794 * to be paired, so make sure there's no buggy
5795 * helper function specification.
5796 */
5797 if (arg_type_is_mem_size(fn->arg1_type) ||
5798 arg_type_is_mem_ptr(fn->arg5_type) ||
5799 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) ||
5800 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) ||
5801 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) ||
5802 check_args_pair_invalid(fn->arg4_type, fn->arg5_type))
5803 return false;
5804
5805 return true;
5806}
5807
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005808static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005809{
5810 int count = 0;
5811
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005812 if (arg_type_may_be_refcounted(fn->arg1_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005813 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005814 if (arg_type_may_be_refcounted(fn->arg2_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005815 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005816 if (arg_type_may_be_refcounted(fn->arg3_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005817 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005818 if (arg_type_may_be_refcounted(fn->arg4_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005819 count++;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005820 if (arg_type_may_be_refcounted(fn->arg5_type))
Joe Stringerfd978bf72018-10-02 13:35:35 -07005821 count++;
5822
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005823 /* A reference acquiring function cannot acquire
5824 * another refcounted ptr.
5825 */
Jakub Sitnicki64d85292020-04-29 20:11:52 +02005826 if (may_be_acquire_function(func_id) && count)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005827 return false;
5828
Joe Stringerfd978bf72018-10-02 13:35:35 -07005829 /* We only support one arg being unreferenced at the moment,
5830 * which is sufficient for the helper functions we have right now.
5831 */
5832 return count <= 1;
5833}
5834
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005835static bool check_btf_id_ok(const struct bpf_func_proto *fn)
5836{
5837 int i;
5838
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005839 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005840 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i])
5841 return false;
5842
Martin KaFai Lau1df8f552020-09-24 17:03:50 -07005843 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i])
5844 return false;
5845 }
5846
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005847 return true;
5848}
5849
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005850static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
Daniel Borkmann90133412018-01-20 01:24:29 +01005851{
5852 return check_raw_mode_ok(fn) &&
Joe Stringerfd978bf72018-10-02 13:35:35 -07005853 check_arg_pair_ok(fn) &&
Lorenz Bauer9436ef62020-09-21 13:12:20 +01005854 check_btf_id_ok(fn) &&
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005855 check_refcount_ok(fn, func_id) ? 0 : -EINVAL;
Daniel Borkmann435faee12016-04-13 00:10:51 +02005856}
5857
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005858/* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
5859 * are now invalid, so turn them into unknown SCALAR_VALUE.
Edward Creef1174f72017-08-07 15:26:19 +01005860 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005861static void __clear_all_pkt_pointers(struct bpf_verifier_env *env,
5862 struct bpf_func_state *state)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005863{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01005864 struct bpf_reg_state *regs = state->regs, *reg;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005865 int i;
5866
5867 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005868 if (reg_is_pkt_pointer_any(&regs[i]))
Jakub Kicinski61bd5212017-10-09 10:30:11 -07005869 mark_reg_unknown(env, regs, i);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005870
Joe Stringerf3709f62018-10-02 13:35:29 -07005871 bpf_for_each_spilled_reg(i, state, reg) {
5872 if (!reg)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005873 continue;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02005874 if (reg_is_pkt_pointer_any(reg))
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005875 __mark_reg_unknown(env, reg);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07005876 }
5877}
5878
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005879static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
5880{
5881 struct bpf_verifier_state *vstate = env->cur_state;
5882 int i;
5883
5884 for (i = 0; i <= vstate->curframe; i++)
5885 __clear_all_pkt_pointers(env, vstate->frame[i]);
5886}
5887
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08005888enum {
5889 AT_PKT_END = -1,
5890 BEYOND_PKT_END = -2,
5891};
5892
5893static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
5894{
5895 struct bpf_func_state *state = vstate->frame[vstate->curframe];
5896 struct bpf_reg_state *reg = &state->regs[regn];
5897
5898 if (reg->type != PTR_TO_PACKET)
5899 /* PTR_TO_PACKET_META is not supported yet */
5900 return;
5901
5902 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
5903 * How far beyond pkt_end it goes is unknown.
5904 * if (!range_open) it's the case of pkt >= pkt_end
5905 * if (range_open) it's the case of pkt > pkt_end
5906 * hence this pointer is at least 1 byte bigger than pkt_end
5907 */
5908 if (range_open)
5909 reg->range = BEYOND_PKT_END;
5910 else
5911 reg->range = AT_PKT_END;
5912}
5913
Joe Stringerfd978bf72018-10-02 13:35:35 -07005914static void release_reg_references(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005915 struct bpf_func_state *state,
5916 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005917{
5918 struct bpf_reg_state *regs = state->regs, *reg;
5919 int i;
5920
5921 for (i = 0; i < MAX_BPF_REG; i++)
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005922 if (regs[i].ref_obj_id == ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005923 mark_reg_unknown(env, regs, i);
5924
5925 bpf_for_each_spilled_reg(i, state, reg) {
5926 if (!reg)
5927 continue;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005928 if (reg->ref_obj_id == ref_obj_id)
Daniel Borkmannf54c7892019-12-22 23:37:40 +01005929 __mark_reg_unknown(env, reg);
Joe Stringerfd978bf72018-10-02 13:35:35 -07005930 }
5931}
5932
5933/* The pointer with the specified id has released its reference to kernel
5934 * resources. Identify all copies of the same pointer and clear the reference.
5935 */
5936static int release_reference(struct bpf_verifier_env *env,
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005937 int ref_obj_id)
Joe Stringerfd978bf72018-10-02 13:35:35 -07005938{
5939 struct bpf_verifier_state *vstate = env->cur_state;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005940 int err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005941 int i;
5942
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005943 err = release_reference_state(cur_func(env), ref_obj_id);
5944 if (err)
5945 return err;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005946
Martin KaFai Lau1b986582019-03-12 10:23:02 -07005947 for (i = 0; i <= vstate->curframe; i++)
5948 release_reg_references(env, vstate->frame[i], ref_obj_id);
5949
5950 return 0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07005951}
5952
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005953static void clear_caller_saved_regs(struct bpf_verifier_env *env,
5954 struct bpf_reg_state *regs)
5955{
5956 int i;
5957
5958 /* after the call registers r0 - r5 were scratched */
5959 for (i = 0; i < CALLER_SAVED_REGS; i++) {
5960 mark_reg_not_init(env, regs, caller_saved[i]);
5961 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
5962 }
5963}
5964
Yonghong Song14351372021-02-26 12:49:23 -08005965typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
5966 struct bpf_func_state *caller,
5967 struct bpf_func_state *callee,
5968 int insn_idx);
5969
5970static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
5971 int *insn_idx, int subprog,
5972 set_callee_state_fn set_callee_state_cb)
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005973{
5974 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005975 struct bpf_func_info_aux *func_info_aux;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005976 struct bpf_func_state *caller, *callee;
Yonghong Song14351372021-02-26 12:49:23 -08005977 int err;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005978 bool is_global = false;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005979
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005980 if (state->curframe + 1 >= MAX_CALL_FRAMES) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005981 verbose(env, "the call stack of %d frames is too deep\n",
Alexei Starovoitovaada9ce2017-12-25 13:15:42 -08005982 state->curframe + 2);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005983 return -E2BIG;
5984 }
5985
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08005986 caller = state->frame[state->curframe];
5987 if (state->frame[state->curframe + 1]) {
5988 verbose(env, "verifier bug. Frame %d already allocated\n",
5989 state->curframe + 1);
5990 return -EFAULT;
5991 }
5992
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005993 func_info_aux = env->prog->aux->func_info_aux;
5994 if (func_info_aux)
5995 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
Martin KaFai Lau34747c42021-03-24 18:51:36 -07005996 err = btf_check_subprog_arg_match(env, subprog, caller->regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08005997 if (err == -EFAULT)
5998 return err;
5999 if (is_global) {
6000 if (err) {
6001 verbose(env, "Caller passes invalid args into func#%d\n",
6002 subprog);
6003 return err;
6004 } else {
6005 if (env->log.level & BPF_LOG_LEVEL)
6006 verbose(env,
6007 "Func#%d is global and valid. Skipping.\n",
6008 subprog);
6009 clear_caller_saved_regs(env, caller->regs);
6010
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01006011 /* All global functions return a 64-bit SCALAR_VALUE */
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006012 mark_reg_unknown(env, caller->regs, BPF_REG_0);
Ilya Leoshkevich45159b22021-02-12 05:04:08 +01006013 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006014
6015 /* continue with next insn after call */
6016 return 0;
6017 }
6018 }
6019
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07006020 if (insn->code == (BPF_JMP | BPF_CALL) &&
6021 insn->imm == BPF_FUNC_timer_set_callback) {
6022 struct bpf_verifier_state *async_cb;
6023
6024 /* there is no real recursion here. timer callbacks are async */
Alexei Starovoitov7ddc80a2021-07-14 17:54:15 -07006025 env->subprog_info[subprog].is_async_cb = true;
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07006026 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
6027 *insn_idx, subprog);
6028 if (!async_cb)
6029 return -EFAULT;
6030 callee = async_cb->frame[0];
6031 callee->async_entry_cnt = caller->async_entry_cnt + 1;
6032
6033 /* Convert bpf_timer_set_callback() args into timer callback args */
6034 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6035 if (err)
6036 return err;
6037
6038 clear_caller_saved_regs(env, caller->regs);
6039 mark_reg_unknown(env, caller->regs, BPF_REG_0);
6040 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6041 /* continue with next insn after call */
6042 return 0;
6043 }
6044
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006045 callee = kzalloc(sizeof(*callee), GFP_KERNEL);
6046 if (!callee)
6047 return -ENOMEM;
6048 state->frame[state->curframe + 1] = callee;
6049
6050 /* callee cannot access r0, r6 - r9 for reading and has to write
6051 * into its own stack before reading from it.
6052 * callee can read/write into caller's stack
6053 */
6054 init_func_state(env, callee,
6055 /* remember the callsite, it will be used by bpf_exit */
6056 *insn_idx /* callsite */,
6057 state->curframe + 1 /* frameno within this callchain */,
Jiong Wangf910cef2018-05-02 16:17:17 -04006058 subprog /* subprog number within this prog */);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006059
Joe Stringerfd978bf72018-10-02 13:35:35 -07006060 /* Transfer references to the callee */
Lorenz Bauerc69431a2021-04-29 14:46:54 +01006061 err = copy_reference_state(callee, caller);
Joe Stringerfd978bf72018-10-02 13:35:35 -07006062 if (err)
6063 return err;
6064
Yonghong Song14351372021-02-26 12:49:23 -08006065 err = set_callee_state_cb(env, caller, callee, *insn_idx);
6066 if (err)
6067 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006068
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -08006069 clear_caller_saved_regs(env, caller->regs);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006070
6071 /* only increment it after check_reg_arg() finished */
6072 state->curframe++;
6073
6074 /* and go analyze first insn of the callee */
Yonghong Song14351372021-02-26 12:49:23 -08006075 *insn_idx = env->subprog_info[subprog].start - 1;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006076
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07006077 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006078 verbose(env, "caller:\n");
Christy Lee0f55f9e2021-12-16 13:33:56 -08006079 print_verifier_state(env, caller, true);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006080 verbose(env, "callee:\n");
Christy Lee0f55f9e2021-12-16 13:33:56 -08006081 print_verifier_state(env, callee, true);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006082 }
6083 return 0;
6084}
6085
Yonghong Song314ee052021-02-26 12:49:27 -08006086int map_set_for_each_callback_args(struct bpf_verifier_env *env,
6087 struct bpf_func_state *caller,
6088 struct bpf_func_state *callee)
6089{
6090 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
6091 * void *callback_ctx, u64 flags);
6092 * callback_fn(struct bpf_map *map, void *key, void *value,
6093 * void *callback_ctx);
6094 */
6095 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6096
6097 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6098 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6099 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6100
6101 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6102 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6103 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
6104
6105 /* pointer to stack or null */
6106 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
6107
6108 /* unused */
6109 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6110 return 0;
6111}
6112
Yonghong Song14351372021-02-26 12:49:23 -08006113static int set_callee_state(struct bpf_verifier_env *env,
6114 struct bpf_func_state *caller,
6115 struct bpf_func_state *callee, int insn_idx)
6116{
6117 int i;
6118
6119 /* copy r1 - r5 args that callee can access. The copy includes parent
6120 * pointers, which connects us up to the liveness chain
6121 */
6122 for (i = BPF_REG_1; i <= BPF_REG_5; i++)
6123 callee->regs[i] = caller->regs[i];
6124 return 0;
6125}
6126
6127static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6128 int *insn_idx)
6129{
6130 int subprog, target_insn;
6131
6132 target_insn = *insn_idx + insn->imm + 1;
6133 subprog = find_subprog(env, target_insn);
6134 if (subprog < 0) {
6135 verbose(env, "verifier bug. No program starts at insn %d\n",
6136 target_insn);
6137 return -EFAULT;
6138 }
6139
6140 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
6141}
6142
Yonghong Song69c087b2021-02-26 12:49:25 -08006143static int set_map_elem_callback_state(struct bpf_verifier_env *env,
6144 struct bpf_func_state *caller,
6145 struct bpf_func_state *callee,
6146 int insn_idx)
6147{
6148 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
6149 struct bpf_map *map;
6150 int err;
6151
6152 if (bpf_map_ptr_poisoned(insn_aux)) {
6153 verbose(env, "tail_call abusing map_ptr\n");
6154 return -EINVAL;
6155 }
6156
6157 map = BPF_MAP_PTR(insn_aux->map_ptr_state);
6158 if (!map->ops->map_set_for_each_callback_args ||
6159 !map->ops->map_for_each_callback) {
6160 verbose(env, "callback function not allowed for map\n");
6161 return -ENOTSUPP;
6162 }
6163
6164 err = map->ops->map_set_for_each_callback_args(env, caller, callee);
6165 if (err)
6166 return err;
6167
6168 callee->in_callback_fn = true;
6169 return 0;
6170}
6171
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006172static int set_loop_callback_state(struct bpf_verifier_env *env,
6173 struct bpf_func_state *caller,
6174 struct bpf_func_state *callee,
6175 int insn_idx)
6176{
6177 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
6178 * u64 flags);
6179 * callback_fn(u32 index, void *callback_ctx);
6180 */
6181 callee->regs[BPF_REG_1].type = SCALAR_VALUE;
6182 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
6183
6184 /* unused */
6185 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
6186 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6187 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6188
6189 callee->in_callback_fn = true;
6190 return 0;
6191}
6192
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07006193static int set_timer_callback_state(struct bpf_verifier_env *env,
6194 struct bpf_func_state *caller,
6195 struct bpf_func_state *callee,
6196 int insn_idx)
6197{
6198 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
6199
6200 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
6201 * callback_fn(struct bpf_map *map, void *key, void *value);
6202 */
6203 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
6204 __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
6205 callee->regs[BPF_REG_1].map_ptr = map_ptr;
6206
6207 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
6208 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6209 callee->regs[BPF_REG_2].map_ptr = map_ptr;
6210
6211 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
6212 __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
6213 callee->regs[BPF_REG_3].map_ptr = map_ptr;
6214
6215 /* unused */
6216 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6217 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07006218 callee->in_async_callback_fn = true;
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07006219 return 0;
6220}
6221
Song Liu7c7e3d32021-11-05 16:23:29 -07006222static int set_find_vma_callback_state(struct bpf_verifier_env *env,
6223 struct bpf_func_state *caller,
6224 struct bpf_func_state *callee,
6225 int insn_idx)
6226{
6227 /* bpf_find_vma(struct task_struct *task, u64 addr,
6228 * void *callback_fn, void *callback_ctx, u64 flags)
6229 * (callback_fn)(struct task_struct *task,
6230 * struct vm_area_struct *vma, void *callback_ctx);
6231 */
6232 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
6233
6234 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
6235 __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
6236 callee->regs[BPF_REG_2].btf = btf_vmlinux;
Song Liud19ddb42021-11-12 07:02:43 -08006237 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
Song Liu7c7e3d32021-11-05 16:23:29 -07006238
6239 /* pointer to stack or null */
6240 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
6241
6242 /* unused */
6243 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
6244 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
6245 callee->in_callback_fn = true;
6246 return 0;
6247}
6248
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006249static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
6250{
6251 struct bpf_verifier_state *state = env->cur_state;
6252 struct bpf_func_state *caller, *callee;
6253 struct bpf_reg_state *r0;
Joe Stringerfd978bf72018-10-02 13:35:35 -07006254 int err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006255
6256 callee = state->frame[state->curframe];
6257 r0 = &callee->regs[BPF_REG_0];
6258 if (r0->type == PTR_TO_STACK) {
6259 /* technically it's ok to return caller's stack pointer
6260 * (or caller's caller's pointer) back to the caller,
6261 * since these pointers are valid. Only current stack
6262 * pointer will be invalid as soon as function exits,
6263 * but let's be conservative
6264 */
6265 verbose(env, "cannot return stack pointer to the caller\n");
6266 return -EINVAL;
6267 }
6268
6269 state->curframe--;
6270 caller = state->frame[state->curframe];
Yonghong Song69c087b2021-02-26 12:49:25 -08006271 if (callee->in_callback_fn) {
6272 /* enforce R0 return value range [0, 1]. */
6273 struct tnum range = tnum_range(0, 1);
6274
6275 if (r0->type != SCALAR_VALUE) {
6276 verbose(env, "R0 not a scalar value\n");
6277 return -EACCES;
6278 }
6279 if (!tnum_in(range, r0->var_off)) {
6280 verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
6281 return -EINVAL;
6282 }
6283 } else {
6284 /* return to the caller whatever r0 had in the callee */
6285 caller->regs[BPF_REG_0] = *r0;
6286 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006287
Joe Stringerfd978bf72018-10-02 13:35:35 -07006288 /* Transfer references to the caller */
Lorenz Bauerc69431a2021-04-29 14:46:54 +01006289 err = copy_reference_state(caller, callee);
Joe Stringerfd978bf72018-10-02 13:35:35 -07006290 if (err)
6291 return err;
6292
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006293 *insn_idx = callee->callsite + 1;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07006294 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006295 verbose(env, "returning from callee:\n");
Christy Lee0f55f9e2021-12-16 13:33:56 -08006296 print_verifier_state(env, callee, true);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006297 verbose(env, "to caller at %d:\n", *insn_idx);
Christy Lee0f55f9e2021-12-16 13:33:56 -08006298 print_verifier_state(env, caller, true);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08006299 }
6300 /* clear everything in the callee */
6301 free_func_state(callee);
6302 state->frame[state->curframe + 1] = NULL;
6303 return 0;
6304}
6305
Yonghong Song849fa502018-04-28 22:28:09 -07006306static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
6307 int func_id,
6308 struct bpf_call_arg_meta *meta)
6309{
6310 struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
6311
6312 if (ret_type != RET_INTEGER ||
6313 (func_id != BPF_FUNC_get_stack &&
Dave Marchevskyfd0b88f2021-04-16 13:47:02 -07006314 func_id != BPF_FUNC_get_task_stack &&
Daniel Borkmann47cc0ed2020-05-15 12:11:17 +02006315 func_id != BPF_FUNC_probe_read_str &&
6316 func_id != BPF_FUNC_probe_read_kernel_str &&
6317 func_id != BPF_FUNC_probe_read_user_str))
Yonghong Song849fa502018-04-28 22:28:09 -07006318 return;
6319
John Fastabend10060502020-03-30 14:36:19 -07006320 ret_reg->smax_value = meta->msize_max_value;
John Fastabendfa123ac2020-03-30 14:36:59 -07006321 ret_reg->s32_max_value = meta->msize_max_value;
Alexei Starovoitovb02709582020-12-08 19:01:51 +01006322 ret_reg->smin_value = -MAX_ERRNO;
6323 ret_reg->s32_min_value = -MAX_ERRNO;
Yonghong Song849fa502018-04-28 22:28:09 -07006324 __reg_deduce_bounds(ret_reg);
6325 __reg_bound_offset(ret_reg);
John Fastabend10060502020-03-30 14:36:19 -07006326 __update_reg_bounds(ret_reg);
Yonghong Song849fa502018-04-28 22:28:09 -07006327}
6328
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006329static int
6330record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6331 int func_id, int insn_idx)
6332{
6333 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
Daniel Borkmann591fe982019-04-09 23:20:05 +02006334 struct bpf_map *map = meta->map_ptr;
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006335
6336 if (func_id != BPF_FUNC_tail_call &&
Daniel Borkmann09772d92018-06-02 23:06:35 +02006337 func_id != BPF_FUNC_map_lookup_elem &&
6338 func_id != BPF_FUNC_map_update_elem &&
Mauricio Vasquez Bf1a2e442018-10-18 15:16:25 +02006339 func_id != BPF_FUNC_map_delete_elem &&
6340 func_id != BPF_FUNC_map_push_elem &&
6341 func_id != BPF_FUNC_map_pop_elem &&
Yonghong Song69c087b2021-02-26 12:49:25 -08006342 func_id != BPF_FUNC_map_peek_elem &&
Björn Töpele6a47502021-03-08 12:29:06 +01006343 func_id != BPF_FUNC_for_each_map_elem &&
6344 func_id != BPF_FUNC_redirect_map)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006345 return 0;
Daniel Borkmann09772d92018-06-02 23:06:35 +02006346
Daniel Borkmann591fe982019-04-09 23:20:05 +02006347 if (map == NULL) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006348 verbose(env, "kernel subsystem misconfigured verifier\n");
6349 return -EINVAL;
6350 }
6351
Daniel Borkmann591fe982019-04-09 23:20:05 +02006352 /* In case of read-only, some additional restrictions
6353 * need to be applied in order to prevent altering the
6354 * state of the map from program side.
6355 */
6356 if ((map->map_flags & BPF_F_RDONLY_PROG) &&
6357 (func_id == BPF_FUNC_map_delete_elem ||
6358 func_id == BPF_FUNC_map_update_elem ||
6359 func_id == BPF_FUNC_map_push_elem ||
6360 func_id == BPF_FUNC_map_pop_elem)) {
6361 verbose(env, "write into map forbidden\n");
6362 return -EACCES;
6363 }
6364
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006365 if (!BPF_MAP_PTR(aux->map_ptr_state))
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006366 bpf_map_ptr_store(aux, meta->map_ptr,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006367 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006368 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006369 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07006370 !meta->map_ptr->bypass_spec_v1);
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006371 return 0;
6372}
6373
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006374static int
6375record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
6376 int func_id, int insn_idx)
6377{
6378 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
6379 struct bpf_reg_state *regs = cur_regs(env), *reg;
6380 struct bpf_map *map = meta->map_ptr;
6381 struct tnum range;
6382 u64 val;
Daniel Borkmanncc52d912019-12-19 22:19:50 +01006383 int err;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006384
6385 if (func_id != BPF_FUNC_tail_call)
6386 return 0;
6387 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
6388 verbose(env, "kernel subsystem misconfigured verifier\n");
6389 return -EINVAL;
6390 }
6391
6392 range = tnum_range(0, map->max_entries - 1);
6393 reg = &regs[BPF_REG_3];
6394
6395 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) {
6396 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6397 return 0;
6398 }
6399
Daniel Borkmanncc52d912019-12-19 22:19:50 +01006400 err = mark_chain_precision(env, BPF_REG_3);
6401 if (err)
6402 return err;
6403
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006404 val = reg->var_off.value;
6405 if (bpf_map_key_unseen(aux))
6406 bpf_map_key_store(aux, val);
6407 else if (!bpf_map_key_poisoned(aux) &&
6408 bpf_map_key_immediate(aux) != val)
6409 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
6410 return 0;
6411}
6412
Joe Stringerfd978bf72018-10-02 13:35:35 -07006413static int check_reference_leak(struct bpf_verifier_env *env)
6414{
6415 struct bpf_func_state *state = cur_func(env);
6416 int i;
6417
6418 for (i = 0; i < state->acquired_refs; i++) {
6419 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
6420 state->refs[i].id, state->refs[i].insn_idx);
6421 }
6422 return state->acquired_refs ? -EINVAL : 0;
6423}
6424
Florent Revest7b155232021-04-19 17:52:40 +02006425static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
6426 struct bpf_reg_state *regs)
6427{
6428 struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
6429 struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
6430 struct bpf_map *fmt_map = fmt_reg->map_ptr;
6431 int err, fmt_map_off, num_args;
6432 u64 fmt_addr;
6433 char *fmt;
6434
6435 /* data must be an array of u64 */
6436 if (data_len_reg->var_off.value % 8)
6437 return -EINVAL;
6438 num_args = data_len_reg->var_off.value / 8;
6439
6440 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
6441 * and map_direct_value_addr is set.
6442 */
6443 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
6444 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
6445 fmt_map_off);
Florent Revest8e8ee102021-04-23 01:55:42 +02006446 if (err) {
6447 verbose(env, "verifier bug\n");
6448 return -EFAULT;
6449 }
Florent Revest7b155232021-04-19 17:52:40 +02006450 fmt = (char *)(long)fmt_addr + fmt_map_off;
6451
6452 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
6453 * can focus on validating the format specifiers.
6454 */
Florent Revest48cac3f2021-04-27 19:43:13 +02006455 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args);
Florent Revest7b155232021-04-19 17:52:40 +02006456 if (err < 0)
6457 verbose(env, "Invalid format string\n");
6458
6459 return err;
6460}
6461
Jiri Olsa9b99edc2021-07-14 11:43:55 +02006462static int check_get_func_ip(struct bpf_verifier_env *env)
6463{
Jiri Olsa9b99edc2021-07-14 11:43:55 +02006464 enum bpf_prog_type type = resolve_prog_type(env->prog);
6465 int func_id = BPF_FUNC_get_func_ip;
6466
6467 if (type == BPF_PROG_TYPE_TRACING) {
Jiri Olsaf92c1e12021-12-08 20:32:44 +01006468 if (!bpf_prog_has_trampoline(env->prog)) {
Jiri Olsa9b99edc2021-07-14 11:43:55 +02006469 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
6470 func_id_name(func_id), func_id);
6471 return -ENOTSUPP;
6472 }
6473 return 0;
Jiri Olsa9ffd9f32021-07-14 11:43:56 +02006474 } else if (type == BPF_PROG_TYPE_KPROBE) {
6475 return 0;
Jiri Olsa9b99edc2021-07-14 11:43:55 +02006476 }
6477
6478 verbose(env, "func %s#%d not supported for program type %d\n",
6479 func_id_name(func_id), func_id, type);
6480 return -ENOTSUPP;
6481}
6482
Yonghong Song69c087b2021-02-26 12:49:25 -08006483static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
6484 int *insn_idx_p)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006485{
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006486 const struct bpf_func_proto *fn = NULL;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006487 struct bpf_reg_state *regs;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006488 struct bpf_call_arg_meta meta;
Yonghong Song69c087b2021-02-26 12:49:25 -08006489 int insn_idx = *insn_idx_p;
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006490 bool changes_data;
Yonghong Song69c087b2021-02-26 12:49:25 -08006491 int i, err, func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006492
6493 /* find function prototype */
Yonghong Song69c087b2021-02-26 12:49:25 -08006494 func_id = insn->imm;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006495 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006496 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
6497 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006498 return -EINVAL;
6499 }
6500
Jakub Kicinski00176a32017-10-16 16:40:54 -07006501 if (env->ops->get_func_proto)
Andrey Ignatov5e43f892018-03-30 15:08:00 -07006502 fn = env->ops->get_func_proto(func_id, env->prog);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006503 if (!fn) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006504 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
6505 func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006506 return -EINVAL;
6507 }
6508
6509 /* eBPF programs must be GPL compatible to use GPL-ed functions */
Daniel Borkmann24701ec2015-03-01 12:31:47 +01006510 if (!env->prog->gpl_compatible && fn->gpl_only) {
Daniel Borkmann3fe28672018-06-02 23:06:33 +02006511 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006512 return -EINVAL;
6513 }
6514
Jiri Olsaeae2e832020-08-25 21:21:19 +02006515 if (fn->allowed && !fn->allowed(env->prog)) {
6516 verbose(env, "helper call is not allowed in probe\n");
6517 return -EINVAL;
6518 }
6519
Daniel Borkmann04514d12017-12-14 21:07:25 +01006520 /* With LD_ABS/IND some JITs save/restore skb from r1. */
Martin KaFai Lau17bedab2016-12-07 15:53:11 -08006521 changes_data = bpf_helper_changes_pkt_data(fn->func);
Daniel Borkmann04514d12017-12-14 21:07:25 +01006522 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
6523 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
6524 func_id_name(func_id), func_id);
6525 return -EINVAL;
6526 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006527
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006528 memset(&meta, 0, sizeof(meta));
Daniel Borkmann36bbef52016-09-20 00:26:13 +02006529 meta.pkt_access = fn->pkt_access;
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006530
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006531 err = check_func_proto(fn, func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006532 if (err) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006533 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02006534 func_id_name(func_id), func_id);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006535 return err;
6536 }
6537
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08006538 meta.func_id = func_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006539 /* check args */
Dmitrii Banshchikov523a4cf2021-02-26 00:26:29 +04006540 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07006541 err = check_func_arg(env, i, &meta, fn);
Alexei Starovoitova7658e12019-10-15 20:25:04 -07006542 if (err)
6543 return err;
6544 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006545
Daniel Borkmannc93552c2018-05-24 02:32:53 +02006546 err = record_func_map(env, &meta, func_id, insn_idx);
6547 if (err)
6548 return err;
6549
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +01006550 err = record_func_key(env, &meta, func_id, insn_idx);
6551 if (err)
6552 return err;
6553
Daniel Borkmann435faee12016-04-13 00:10:51 +02006554 /* Mark slots with STACK_MISC in case of raw mode, stack offset
6555 * is inferred from register state.
6556 */
6557 for (i = 0; i < meta.access_size; i++) {
Daniel Borkmannca369602018-02-23 22:29:05 +01006558 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
6559 BPF_WRITE, -1, false);
Daniel Borkmann435faee12016-04-13 00:10:51 +02006560 if (err)
6561 return err;
6562 }
6563
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006564 if (is_release_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006565 err = release_reference(env, meta.ref_obj_id);
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006566 if (err) {
6567 verbose(env, "func %s#%d reference has not been acquired before\n",
6568 func_id_name(func_id), func_id);
Joe Stringerfd978bf72018-10-02 13:35:35 -07006569 return err;
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08006570 }
Joe Stringerfd978bf72018-10-02 13:35:35 -07006571 }
6572
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07006573 regs = cur_regs(env);
Roman Gushchincd339432018-08-02 14:27:24 -07006574
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006575 switch (func_id) {
6576 case BPF_FUNC_tail_call:
6577 err = check_reference_leak(env);
6578 if (err) {
6579 verbose(env, "tail_call would lead to reference leak\n");
6580 return err;
6581 }
6582 break;
6583 case BPF_FUNC_get_local_storage:
6584 /* check that flags argument in get_local_storage(map, flags) is 0,
6585 * this is required because get_local_storage() can't return an error.
6586 */
6587 if (!register_is_null(&regs[BPF_REG_2])) {
6588 verbose(env, "get_local_storage() doesn't support non-zero flags\n");
6589 return -EINVAL;
6590 }
6591 break;
6592 case BPF_FUNC_for_each_map_elem:
Yonghong Song69c087b2021-02-26 12:49:25 -08006593 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6594 set_map_elem_callback_state);
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006595 break;
6596 case BPF_FUNC_timer_set_callback:
Alexei Starovoitovb00628b2021-07-14 17:54:09 -07006597 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6598 set_timer_callback_state);
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006599 break;
6600 case BPF_FUNC_find_vma:
Song Liu7c7e3d32021-11-05 16:23:29 -07006601 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6602 set_find_vma_callback_state);
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006603 break;
6604 case BPF_FUNC_snprintf:
6605 err = check_bpf_snprintf_call(env, regs);
6606 break;
6607 case BPF_FUNC_loop:
6608 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
6609 set_loop_callback_state);
6610 break;
Song Liu7c7e3d32021-11-05 16:23:29 -07006611 }
6612
Joanne Koonge6f2dd02021-11-29 19:06:19 -08006613 if (err)
6614 return err;
Florent Revest7b155232021-04-19 17:52:40 +02006615
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006616 /* reset caller saved regs */
Edward Creedc503a82017-08-15 20:34:35 +01006617 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006618 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01006619 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
6620 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006621
Jiong Wang5327ed32019-05-24 23:25:12 +01006622 /* helper call returns 64-bit value. */
6623 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
6624
Edward Creedc503a82017-08-15 20:34:35 +01006625 /* update return register (already marked as written above) */
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006626 if (fn->ret_type == RET_INTEGER) {
Edward Creef1174f72017-08-07 15:26:19 +01006627 /* sets type to SCALAR_VALUE */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006628 mark_reg_unknown(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006629 } else if (fn->ret_type == RET_VOID) {
6630 regs[BPF_REG_0].type = NOT_INIT;
Roman Gushchin3e6a4b32018-08-02 14:27:22 -07006631 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL ||
6632 fn->ret_type == RET_PTR_TO_MAP_VALUE) {
Edward Creef1174f72017-08-07 15:26:19 +01006633 /* There is no offset yet applied, variable or fixed */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006634 mark_reg_known_zero(env, regs, BPF_REG_0);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006635 /* remember map_ptr, so that check_map_access()
6636 * can check 'value_size' boundary of memory access
6637 * to map element returned from bpf_map_lookup_elem()
6638 */
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006639 if (meta.map_ptr == NULL) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006640 verbose(env,
6641 "kernel subsystem misconfigured verifier\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006642 return -EINVAL;
6643 }
Daniel Borkmann33ff9822016-04-13 00:10:50 +02006644 regs[BPF_REG_0].map_ptr = meta.map_ptr;
Alexei Starovoitov3e8ce292021-07-14 17:54:11 -07006645 regs[BPF_REG_0].map_uid = meta.map_uid;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006646 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) {
6647 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE;
Alexei Starovoitove16d2f12019-01-31 15:40:05 -08006648 if (map_value_has_spin_lock(meta.map_ptr))
6649 regs[BPF_REG_0].id = ++env->id_gen;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006650 } else {
6651 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL;
Daniel Borkmann4d31f302018-11-01 00:05:53 +01006652 }
Joe Stringerc64b7982018-10-02 13:35:33 -07006653 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) {
6654 mark_reg_known_zero(env, regs, BPF_REG_0);
6655 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL;
Lorenz Bauer85a51f82019-03-22 09:54:00 +08006656 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) {
6657 mark_reg_known_zero(env, regs, BPF_REG_0);
6658 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08006659 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) {
6660 mark_reg_known_zero(env, regs, BPF_REG_0);
6661 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07006662 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) {
6663 mark_reg_known_zero(env, regs, BPF_REG_0);
6664 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL;
Andrii Nakryiko457f4432020-05-29 00:54:20 -07006665 regs[BPF_REG_0].mem_size = meta.mem_size;
Hao Luo63d9b802020-09-29 16:50:48 -07006666 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL ||
6667 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) {
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006668 const struct btf_type *t;
6669
6670 mark_reg_known_zero(env, regs, BPF_REG_0);
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006671 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006672 if (!btf_type_is_struct(t)) {
6673 u32 tsize;
6674 const struct btf_type *ret;
6675 const char *tname;
6676
6677 /* resolve the type size of ksym. */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006678 ret = btf_resolve_size(meta.ret_btf, t, &tsize);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006679 if (IS_ERR(ret)) {
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006680 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006681 verbose(env, "unable to resolve the size of type '%s': %ld\n",
6682 tname, PTR_ERR(ret));
6683 return -EINVAL;
6684 }
Hao Luo63d9b802020-09-29 16:50:48 -07006685 regs[BPF_REG_0].type =
6686 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6687 PTR_TO_MEM : PTR_TO_MEM_OR_NULL;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006688 regs[BPF_REG_0].mem_size = tsize;
6689 } else {
Hao Luo63d9b802020-09-29 16:50:48 -07006690 regs[BPF_REG_0].type =
6691 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ?
6692 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL;
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006693 regs[BPF_REG_0].btf = meta.ret_btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -07006694 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
6695 }
KP Singh3ca10322020-11-06 10:37:43 +00006696 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL ||
6697 fn->ret_type == RET_PTR_TO_BTF_ID) {
Yonghong Songaf7ec132020-06-23 16:08:09 -07006698 int ret_btf_id;
6699
6700 mark_reg_known_zero(env, regs, BPF_REG_0);
KP Singh3ca10322020-11-06 10:37:43 +00006701 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ?
6702 PTR_TO_BTF_ID :
6703 PTR_TO_BTF_ID_OR_NULL;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006704 ret_btf_id = *fn->ret_btf_id;
6705 if (ret_btf_id == 0) {
6706 verbose(env, "invalid return type %d of func %s#%d\n",
6707 fn->ret_type, func_id_name(func_id), func_id);
6708 return -EINVAL;
6709 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08006710 /* current BPF helper definitions are only coming from
6711 * built-in code with type IDs from vmlinux BTF
6712 */
6713 regs[BPF_REG_0].btf = btf_vmlinux;
Yonghong Songaf7ec132020-06-23 16:08:09 -07006714 regs[BPF_REG_0].btf_id = ret_btf_id;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006715 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006716 verbose(env, "unknown return type %d of func %s#%d\n",
Thomas Grafebb676d2016-10-27 11:23:51 +02006717 fn->ret_type, func_id_name(func_id), func_id);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07006718 return -EINVAL;
6719 }
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006720
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07006721 if (reg_type_may_be_null(regs[BPF_REG_0].type))
6722 regs[BPF_REG_0].id = ++env->id_gen;
6723
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006724 if (is_ptr_cast_function(func_id)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006725 /* For release_reference() */
6726 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
Jakub Sitnicki64d85292020-04-29 20:11:52 +02006727 } else if (is_acquire_function(func_id, meta.map_ptr)) {
Lorenz Bauer0f3adc22019-03-22 09:53:59 +08006728 int id = acquire_reference_state(env, insn_idx);
6729
6730 if (id < 0)
6731 return id;
6732 /* For mark_ptr_or_null_reg() */
6733 regs[BPF_REG_0].id = id;
6734 /* For release_reference() */
6735 regs[BPF_REG_0].ref_obj_id = id;
6736 }
Martin KaFai Lau1b986582019-03-12 10:23:02 -07006737
Yonghong Song849fa502018-04-28 22:28:09 -07006738 do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
6739
Jakub Kicinski61bd5212017-10-09 10:30:11 -07006740 err = check_map_func_compatibility(env, meta.map_ptr, func_id);
Kaixu Xia35578d72015-08-06 07:02:35 +00006741 if (err)
6742 return err;
Alexei Starovoitov04fd61ab2015-05-19 16:59:03 -07006743
Song Liufa28dcb2020-06-29 23:28:44 -07006744 if ((func_id == BPF_FUNC_get_stack ||
6745 func_id == BPF_FUNC_get_task_stack) &&
6746 !env->prog->has_callchain_buf) {
Yonghong Songc195651e2018-04-28 22:28:08 -07006747 const char *err_str;
6748
6749#ifdef CONFIG_PERF_EVENTS
6750 err = get_callchain_buffers(sysctl_perf_event_max_stack);
6751 err_str = "cannot get callchain buffer for func %s#%d\n";
6752#else
6753 err = -ENOTSUPP;
6754 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
6755#endif
6756 if (err) {
6757 verbose(env, err_str, func_id_name(func_id), func_id);
6758 return err;
6759 }
6760
6761 env->prog->has_callchain_buf = true;
6762 }
6763
Song Liu5d99cb2c2020-07-23 11:06:45 -07006764 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
6765 env->prog->call_get_stack = true;
6766
Jiri Olsa9b99edc2021-07-14 11:43:55 +02006767 if (func_id == BPF_FUNC_get_func_ip) {
6768 if (check_get_func_ip(env))
6769 return -ENOTSUPP;
6770 env->prog->call_get_func_ip = true;
6771 }
6772
Alexei Starovoitov969bf052016-05-05 19:49:10 -07006773 if (changes_data)
6774 clear_all_pkt_pointers(env);
6775 return 0;
6776}
6777
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006778/* mark_btf_func_reg_size() is used when the reg size is determined by
6779 * the BTF func_proto's return value size and argument.
6780 */
6781static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
6782 size_t reg_size)
6783{
6784 struct bpf_reg_state *reg = &cur_regs(env)[regno];
6785
6786 if (regno == BPF_REG_0) {
6787 /* Function return value */
6788 reg->live |= REG_LIVE_WRITTEN;
6789 reg->subreg_def = reg_size == sizeof(u64) ?
6790 DEF_NOT_SUBREG : env->insn_idx + 1;
6791 } else {
6792 /* Function argument */
6793 if (reg_size == sizeof(u64)) {
6794 mark_insn_zext(env, reg);
6795 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
6796 } else {
6797 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
6798 }
6799 }
6800}
6801
6802static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn)
6803{
6804 const struct btf_type *t, *func, *func_proto, *ptr_type;
6805 struct bpf_reg_state *regs = cur_regs(env);
6806 const char *func_name, *ptr_type_name;
6807 u32 i, nargs, func_id, ptr_type_id;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306808 struct module *btf_mod = NULL;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006809 const struct btf_param *args;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306810 struct btf *desc_btf;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006811 int err;
6812
Kumar Kartikeya Dwivedia5d82722021-10-02 06:47:50 +05306813 /* skip for now, but return error when we find this in fixup_kfunc_call */
6814 if (!insn->imm)
6815 return 0;
6816
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306817 desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod);
6818 if (IS_ERR(desc_btf))
6819 return PTR_ERR(desc_btf);
6820
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006821 func_id = insn->imm;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306822 func = btf_type_by_id(desc_btf, func_id);
6823 func_name = btf_name_by_offset(desc_btf, func->name_off);
6824 func_proto = btf_type_by_id(desc_btf, func->type);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006825
6826 if (!env->ops->check_kfunc_call ||
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306827 !env->ops->check_kfunc_call(func_id, btf_mod)) {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006828 verbose(env, "calling kernel function %s is not allowed\n",
6829 func_name);
6830 return -EACCES;
6831 }
6832
6833 /* Check the arguments */
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306834 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006835 if (err)
6836 return err;
6837
6838 for (i = 0; i < CALLER_SAVED_REGS; i++)
6839 mark_reg_not_init(env, regs, caller_saved[i]);
6840
6841 /* Check return type */
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306842 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006843 if (btf_type_is_scalar(t)) {
6844 mark_reg_unknown(env, regs, BPF_REG_0);
6845 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
6846 } else if (btf_type_is_ptr(t)) {
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306847 ptr_type = btf_type_skip_modifiers(desc_btf, t->type,
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006848 &ptr_type_id);
6849 if (!btf_type_is_struct(ptr_type)) {
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306850 ptr_type_name = btf_name_by_offset(desc_btf,
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006851 ptr_type->name_off);
6852 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n",
6853 func_name, btf_type_str(ptr_type),
6854 ptr_type_name);
6855 return -EINVAL;
6856 }
6857 mark_reg_known_zero(env, regs, BPF_REG_0);
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306858 regs[BPF_REG_0].btf = desc_btf;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006859 regs[BPF_REG_0].type = PTR_TO_BTF_ID;
6860 regs[BPF_REG_0].btf_id = ptr_type_id;
6861 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
6862 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */
6863
6864 nargs = btf_type_vlen(func_proto);
6865 args = (const struct btf_param *)(func_proto + 1);
6866 for (i = 0; i < nargs; i++) {
6867 u32 regno = i + 1;
6868
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +05306869 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -07006870 if (btf_type_is_ptr(t))
6871 mark_btf_func_reg_size(env, regno, sizeof(void *));
6872 else
6873 /* scalar. ensured by btf_check_kfunc_arg_match() */
6874 mark_btf_func_reg_size(env, regno, t->size);
6875 }
6876
6877 return 0;
6878}
6879
Edward Creeb03c9f92017-08-07 15:26:36 +01006880static bool signed_add_overflows(s64 a, s64 b)
6881{
6882 /* Do the add in u64, where overflow is well-defined */
6883 s64 res = (s64)((u64)a + (u64)b);
6884
6885 if (b < 0)
6886 return res > a;
6887 return res < a;
6888}
6889
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006890static bool signed_add32_overflows(s32 a, s32 b)
John Fastabend3f50f132020-03-30 14:36:39 -07006891{
6892 /* Do the add in u32, where overflow is well-defined */
6893 s32 res = (s32)((u32)a + (u32)b);
6894
6895 if (b < 0)
6896 return res > a;
6897 return res < a;
6898}
6899
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006900static bool signed_sub_overflows(s64 a, s64 b)
Edward Creeb03c9f92017-08-07 15:26:36 +01006901{
6902 /* Do the sub in u64, where overflow is well-defined */
6903 s64 res = (s64)((u64)a - (u64)b);
6904
6905 if (b < 0)
6906 return res < a;
6907 return res > a;
David S. Millerd1174412017-05-10 11:22:52 -07006908}
6909
John Fastabend3f50f132020-03-30 14:36:39 -07006910static bool signed_sub32_overflows(s32 a, s32 b)
6911{
Daniel Borkmannbc895e82021-01-20 00:24:24 +01006912 /* Do the sub in u32, where overflow is well-defined */
John Fastabend3f50f132020-03-30 14:36:39 -07006913 s32 res = (s32)((u32)a - (u32)b);
6914
6915 if (b < 0)
6916 return res < a;
6917 return res > a;
6918}
6919
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08006920static bool check_reg_sane_offset(struct bpf_verifier_env *env,
6921 const struct bpf_reg_state *reg,
6922 enum bpf_reg_type type)
6923{
6924 bool known = tnum_is_const(reg->var_off);
6925 s64 val = reg->var_off.value;
6926 s64 smin = reg->smin_value;
6927
6928 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
6929 verbose(env, "math between %s pointer and %lld is not allowed\n",
6930 reg_type_str[type], val);
6931 return false;
6932 }
6933
6934 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
6935 verbose(env, "%s pointer offset %d is not allowed\n",
6936 reg_type_str[type], reg->off);
6937 return false;
6938 }
6939
6940 if (smin == S64_MIN) {
6941 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
6942 reg_type_str[type]);
6943 return false;
6944 }
6945
6946 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
6947 verbose(env, "value %lld makes %s pointer be out of bounds\n",
6948 smin, reg_type_str[type]);
6949 return false;
6950 }
6951
6952 return true;
6953}
6954
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006955static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
6956{
6957 return &env->insn_aux_data[env->insn_idx];
6958}
6959
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006960enum {
6961 REASON_BOUNDS = -1,
6962 REASON_TYPE = -2,
6963 REASON_PATHS = -3,
6964 REASON_LIMIT = -4,
6965 REASON_STACK = -5,
6966};
6967
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006968static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00006969 u32 *alu_limit, bool mask_to_left)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006970{
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006971 u32 max = 0, ptr_limit = 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006972
6973 switch (ptr_reg->type) {
6974 case PTR_TO_STACK:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006975 /* Offset 0 is out-of-bounds, but acceptable start for the
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006976 * left direction, see BPF_REG_FP. Also, unknown scalar
6977 * offset where we would need to deal with min/max bounds is
6978 * currently prohibited for unprivileged.
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006979 */
6980 max = MAX_BPF_STACK + mask_to_left;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006981 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006982 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006983 case PTR_TO_MAP_VALUE:
Piotr Krysiuk1b1597e2021-03-16 09:47:02 +01006984 max = ptr_reg->map_ptr->value_size;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01006985 ptr_limit = (mask_to_left ?
6986 ptr_reg->smin_value :
6987 ptr_reg->umax_value) + ptr_reg->off;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006988 break;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006989 default:
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006990 return REASON_TYPE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006991 }
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006992
6993 if (ptr_limit >= max)
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01006994 return REASON_LIMIT;
Daniel Borkmannb658bbb2021-03-23 09:04:10 +01006995 *alu_limit = ptr_limit;
6996 return 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01006997}
6998
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01006999static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
7000 const struct bpf_insn *insn)
7001{
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07007002 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007003}
7004
7005static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
7006 u32 alu_state, u32 alu_limit)
7007{
7008 /* If we arrived here from different branches with different
7009 * state or limits to sanitize, then this won't work.
7010 */
7011 if (aux->alu_state &&
7012 (aux->alu_state != alu_state ||
7013 aux->alu_limit != alu_limit))
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007014 return REASON_PATHS;
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007015
Brendan Jackmane6ac5932021-02-17 10:45:09 +00007016 /* Corresponding fixup done in do_misc_fixups(). */
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007017 aux->alu_state = alu_state;
7018 aux->alu_limit = alu_limit;
7019 return 0;
7020}
7021
7022static int sanitize_val_alu(struct bpf_verifier_env *env,
7023 struct bpf_insn *insn)
7024{
7025 struct bpf_insn_aux_data *aux = cur_aux(env);
7026
7027 if (can_skip_alu_sanitation(env, insn))
7028 return 0;
7029
7030 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
7031}
7032
Daniel Borkmannf5288192021-03-24 11:25:39 +01007033static bool sanitize_needed(u8 opcode)
7034{
7035 return opcode == BPF_ADD || opcode == BPF_SUB;
7036}
7037
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007038struct bpf_sanitize_info {
7039 struct bpf_insn_aux_data aux;
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00007040 bool mask_to_left;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007041};
7042
Daniel Borkmann9183671a2021-05-28 15:47:32 +00007043static struct bpf_verifier_state *
7044sanitize_speculative_path(struct bpf_verifier_env *env,
7045 const struct bpf_insn *insn,
7046 u32 next_idx, u32 curr_idx)
7047{
7048 struct bpf_verifier_state *branch;
7049 struct bpf_reg_state *regs;
7050
7051 branch = push_stack(env, next_idx, curr_idx, true);
7052 if (branch && insn) {
7053 regs = branch->frame[branch->curframe]->regs;
7054 if (BPF_SRC(insn->code) == BPF_K) {
7055 mark_reg_unknown(env, regs, insn->dst_reg);
7056 } else if (BPF_SRC(insn->code) == BPF_X) {
7057 mark_reg_unknown(env, regs, insn->dst_reg);
7058 mark_reg_unknown(env, regs, insn->src_reg);
7059 }
7060 }
7061 return branch;
7062}
7063
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007064static int sanitize_ptr_alu(struct bpf_verifier_env *env,
7065 struct bpf_insn *insn,
7066 const struct bpf_reg_state *ptr_reg,
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01007067 const struct bpf_reg_state *off_reg,
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007068 struct bpf_reg_state *dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007069 struct bpf_sanitize_info *info,
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007070 const bool commit_window)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007071{
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007072 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007073 struct bpf_verifier_state *vstate = env->cur_state;
Daniel Borkmann801c6052021-04-29 15:19:37 +00007074 bool off_is_imm = tnum_is_const(off_reg->var_off);
Daniel Borkmann6f55b2f2021-03-22 15:45:52 +01007075 bool off_is_neg = off_reg->smin_value < 0;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007076 bool ptr_is_dst_reg = ptr_reg == dst_reg;
7077 u8 opcode = BPF_OP(insn->code);
7078 u32 alu_state, alu_limit;
7079 struct bpf_reg_state tmp;
7080 bool ret;
Piotr Krysiukf2323262021-03-16 09:47:02 +01007081 int err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007082
Daniel Borkmannd3bd7412019-01-06 00:54:37 +01007083 if (can_skip_alu_sanitation(env, insn))
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007084 return 0;
7085
7086 /* We already marked aux for masking from non-speculative
7087 * paths, thus we got here in the first place. We only care
7088 * to explore bad access from here.
7089 */
7090 if (vstate->speculative)
7091 goto do_sim;
7092
Daniel Borkmannbb01a1b2021-05-21 10:19:22 +00007093 if (!commit_window) {
7094 if (!tnum_is_const(off_reg->var_off) &&
7095 (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
7096 return REASON_BOUNDS;
7097
7098 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) ||
7099 (opcode == BPF_SUB && !off_is_neg);
7100 }
7101
7102 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
Piotr Krysiukf2323262021-03-16 09:47:02 +01007103 if (err < 0)
7104 return err;
7105
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007106 if (commit_window) {
7107 /* In commit phase we narrow the masking window based on
7108 * the observed pointer move after the simulated operation.
7109 */
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007110 alu_state = info->aux.alu_state;
7111 alu_limit = abs(info->aux.alu_limit - alu_limit);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007112 } else {
7113 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
Daniel Borkmann801c6052021-04-29 15:19:37 +00007114 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007115 alu_state |= ptr_is_dst_reg ?
7116 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
Daniel Borkmanne042aa52021-07-16 09:18:21 +00007117
7118 /* Limit pruning on unknown scalars to enable deep search for
7119 * potential masking differences from other program paths.
7120 */
7121 if (!off_is_imm)
7122 env->explore_alu_limits = true;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007123 }
7124
Piotr Krysiukf2323262021-03-16 09:47:02 +01007125 err = update_alu_sanitation_state(aux, alu_state, alu_limit);
7126 if (err < 0)
7127 return err;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007128do_sim:
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007129 /* If we're in commit phase, we're done here given we already
7130 * pushed the truncated dst_reg into the speculative verification
7131 * stack.
Daniel Borkmanna7036192021-05-04 08:58:25 +00007132 *
7133 * Also, when register is a known constant, we rewrite register-based
7134 * operation to immediate-based, and thus do not need masking (and as
7135 * a consequence, do not need to simulate the zero-truncation either).
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007136 */
Daniel Borkmanna7036192021-05-04 08:58:25 +00007137 if (commit_window || off_is_imm)
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007138 return 0;
7139
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007140 /* Simulate and find potential out-of-bounds access under
7141 * speculative execution from truncation as a result of
7142 * masking when off was not within expected range. If off
7143 * sits in dst, then we temporarily need to move ptr there
7144 * to simulate dst (== 0) +/-= ptr. Needed, for example,
7145 * for cases where we use K-based arithmetic in one direction
7146 * and truncated reg-based in the other in order to explore
7147 * bad access.
7148 */
7149 if (!ptr_is_dst_reg) {
7150 tmp = *dst_reg;
7151 *dst_reg = *ptr_reg;
7152 }
Daniel Borkmann9183671a2021-05-28 15:47:32 +00007153 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
7154 env->insn_idx);
Xu Yu08032782019-03-21 18:00:35 +08007155 if (!ptr_is_dst_reg && ret)
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007156 *dst_reg = tmp;
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007157 return !ret ? REASON_STACK : 0;
7158}
7159
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +00007160static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
7161{
7162 struct bpf_verifier_state *vstate = env->cur_state;
7163
7164 /* If we simulate paths under speculation, we don't update the
7165 * insn as 'seen' such that when we verify unreachable paths in
7166 * the non-speculative domain, sanitize_dead_code() can still
7167 * rewrite/sanitize them.
7168 */
7169 if (!vstate->speculative)
7170 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
7171}
7172
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007173static int sanitize_err(struct bpf_verifier_env *env,
7174 const struct bpf_insn *insn, int reason,
7175 const struct bpf_reg_state *off_reg,
7176 const struct bpf_reg_state *dst_reg)
7177{
7178 static const char *err = "pointer arithmetic with it prohibited for !root";
7179 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
7180 u32 dst = insn->dst_reg, src = insn->src_reg;
7181
7182 switch (reason) {
7183 case REASON_BOUNDS:
7184 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
7185 off_reg == dst_reg ? dst : src, err);
7186 break;
7187 case REASON_TYPE:
7188 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
7189 off_reg == dst_reg ? src : dst, err);
7190 break;
7191 case REASON_PATHS:
7192 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
7193 dst, op, err);
7194 break;
7195 case REASON_LIMIT:
7196 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
7197 dst, op, err);
7198 break;
7199 case REASON_STACK:
7200 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
7201 dst, err);
7202 break;
7203 default:
7204 verbose(env, "verifier internal error: unknown reason (%d)\n",
7205 reason);
7206 break;
7207 }
7208
7209 return -EACCES;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007210}
7211
Andrei Matei01f810a2021-02-06 20:10:24 -05007212/* check that stack access falls within stack limits and that 'reg' doesn't
7213 * have a variable offset.
7214 *
7215 * Variable offset is prohibited for unprivileged mode for simplicity since it
7216 * requires corresponding support in Spectre masking for stack ALU. See also
7217 * retrieve_ptr_limit().
7218 *
7219 *
7220 * 'off' includes 'reg->off'.
7221 */
7222static int check_stack_access_for_ptr_arithmetic(
7223 struct bpf_verifier_env *env,
7224 int regno,
7225 const struct bpf_reg_state *reg,
7226 int off)
7227{
7228 if (!tnum_is_const(reg->var_off)) {
7229 char tn_buf[48];
7230
7231 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7232 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
7233 regno, tn_buf, off);
7234 return -EACCES;
7235 }
7236
7237 if (off >= 0 || off < -MAX_BPF_STACK) {
7238 verbose(env, "R%d stack pointer arithmetic goes out of range, "
7239 "prohibited for !root; off=%d\n", regno, off);
7240 return -EACCES;
7241 }
7242
7243 return 0;
7244}
7245
Daniel Borkmann073815b2021-03-23 15:05:48 +01007246static int sanitize_check_bounds(struct bpf_verifier_env *env,
7247 const struct bpf_insn *insn,
7248 const struct bpf_reg_state *dst_reg)
7249{
7250 u32 dst = insn->dst_reg;
7251
7252 /* For unprivileged we require that resulting offset must be in bounds
7253 * in order to be able to sanitize access later on.
7254 */
7255 if (env->bypass_spec_v1)
7256 return 0;
7257
7258 switch (dst_reg->type) {
7259 case PTR_TO_STACK:
7260 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
7261 dst_reg->off + dst_reg->var_off.value))
7262 return -EACCES;
7263 break;
7264 case PTR_TO_MAP_VALUE:
7265 if (check_map_access(env, dst, dst_reg->off, 1, false)) {
7266 verbose(env, "R%d pointer arithmetic of map value goes out of range, "
7267 "prohibited for !root\n", dst);
7268 return -EACCES;
7269 }
7270 break;
7271 default:
7272 break;
7273 }
7274
7275 return 0;
7276}
Andrei Matei01f810a2021-02-06 20:10:24 -05007277
Edward Creef1174f72017-08-07 15:26:19 +01007278/* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
Edward Creef1174f72017-08-07 15:26:19 +01007279 * Caller should also handle BPF_MOV case separately.
7280 * If we return -EACCES, caller may want to try again treating pointer as a
7281 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks.
7282 */
7283static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
7284 struct bpf_insn *insn,
7285 const struct bpf_reg_state *ptr_reg,
7286 const struct bpf_reg_state *off_reg)
Josef Bacik48461132016-09-28 10:54:32 -04007287{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08007288 struct bpf_verifier_state *vstate = env->cur_state;
7289 struct bpf_func_state *state = vstate->frame[vstate->curframe];
7290 struct bpf_reg_state *regs = state->regs, *dst_reg;
Edward Creef1174f72017-08-07 15:26:19 +01007291 bool known = tnum_is_const(off_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01007292 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
7293 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
7294 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
7295 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007296 struct bpf_sanitize_info info = {};
Josef Bacik48461132016-09-28 10:54:32 -04007297 u8 opcode = BPF_OP(insn->code);
Daniel Borkmann24c109b2021-03-23 08:51:02 +01007298 u32 dst = insn->dst_reg;
Daniel Borkmann979d63d2019-01-03 00:58:34 +01007299 int ret;
Josef Bacik48461132016-09-28 10:54:32 -04007300
Edward Creef1174f72017-08-07 15:26:19 +01007301 dst_reg = &regs[dst];
Josef Bacik48461132016-09-28 10:54:32 -04007302
Daniel Borkmann6f161012018-01-18 01:15:21 +01007303 if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
7304 smin_val > smax_val || umin_val > umax_val) {
7305 /* Taint dst register if offset had invalid bounds derived from
7306 * e.g. dead branches.
7307 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +01007308 __mark_reg_unknown(env, dst_reg);
Daniel Borkmann6f161012018-01-18 01:15:21 +01007309 return 0;
Josef Bacik48461132016-09-28 10:54:32 -04007310 }
7311
Edward Creef1174f72017-08-07 15:26:19 +01007312 if (BPF_CLASS(insn->code) != BPF_ALU64) {
7313 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
Yonghong Song6c693542020-06-18 16:46:31 -07007314 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
7315 __mark_reg_unknown(env, dst_reg);
7316 return 0;
7317 }
7318
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007319 verbose(env,
7320 "R%d 32-bit pointer arithmetic prohibited\n",
7321 dst);
Edward Creef1174f72017-08-07 15:26:19 +01007322 return -EACCES;
7323 }
David S. Millerd1174412017-05-10 11:22:52 -07007324
Joe Stringeraad2eea2018-10-02 13:35:30 -07007325 switch (ptr_reg->type) {
7326 case PTR_TO_MAP_VALUE_OR_NULL:
7327 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
7328 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01007329 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07007330 case CONST_PTR_TO_MAP:
Yonghong Song7c696732020-09-08 10:57:02 -07007331 /* smin_val represents the known value */
7332 if (known && smin_val == 0 && opcode == BPF_ADD)
7333 break;
Gustavo A. R. Silva87317452020-10-02 18:42:17 -05007334 fallthrough;
Joe Stringeraad2eea2018-10-02 13:35:30 -07007335 case PTR_TO_PACKET_END:
Joe Stringerc64b7982018-10-02 13:35:33 -07007336 case PTR_TO_SOCKET:
7337 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -08007338 case PTR_TO_SOCK_COMMON:
7339 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -08007340 case PTR_TO_TCP_SOCK:
7341 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -07007342 case PTR_TO_XDP_SOCK:
Joe Stringeraad2eea2018-10-02 13:35:30 -07007343 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
7344 dst, reg_type_str[ptr_reg->type]);
Edward Creef1174f72017-08-07 15:26:19 +01007345 return -EACCES;
Joe Stringeraad2eea2018-10-02 13:35:30 -07007346 default:
7347 break;
Edward Creef1174f72017-08-07 15:26:19 +01007348 }
7349
7350 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
7351 * The id may be overwritten later if we create a new variable offset.
Josef Bacik48461132016-09-28 10:54:32 -04007352 */
Edward Creef1174f72017-08-07 15:26:19 +01007353 dst_reg->type = ptr_reg->type;
7354 dst_reg->id = ptr_reg->id;
Josef Bacikf23cc642016-11-14 15:45:36 -05007355
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007356 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
7357 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
7358 return -EINVAL;
7359
John Fastabend3f50f132020-03-30 14:36:39 -07007360 /* pointer types do not carry 32-bit bounds at the moment. */
7361 __mark_reg32_unbounded(dst_reg);
7362
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007363 if (sanitize_needed(opcode)) {
7364 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007365 &info, false);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007366 if (ret < 0)
7367 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007368 }
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01007369
Josef Bacik48461132016-09-28 10:54:32 -04007370 switch (opcode) {
7371 case BPF_ADD:
Edward Creef1174f72017-08-07 15:26:19 +01007372 /* We can take a fixed offset as long as it doesn't overflow
7373 * the s32 'off' field
7374 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007375 if (known && (ptr_reg->off + smin_val ==
7376 (s64)(s32)(ptr_reg->off + smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01007377 /* pointer += K. Accumulate it into fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01007378 dst_reg->smin_value = smin_ptr;
7379 dst_reg->smax_value = smax_ptr;
7380 dst_reg->umin_value = umin_ptr;
7381 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01007382 dst_reg->var_off = ptr_reg->var_off;
Edward Creeb03c9f92017-08-07 15:26:36 +01007383 dst_reg->off = ptr_reg->off + smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01007384 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01007385 break;
7386 }
Edward Creef1174f72017-08-07 15:26:19 +01007387 /* A new variable offset is created. Note that off_reg->off
7388 * == 0, since it's a scalar.
7389 * dst_reg gets the pointer type and since some positive
7390 * integer value was added to the pointer, give it a new 'id'
7391 * if it's a PTR_TO_PACKET.
7392 * this creates a new 'base' pointer, off_reg (variable) gets
7393 * added into the variable offset, and we copy the fixed offset
7394 * from ptr_reg.
7395 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007396 if (signed_add_overflows(smin_ptr, smin_val) ||
7397 signed_add_overflows(smax_ptr, smax_val)) {
7398 dst_reg->smin_value = S64_MIN;
7399 dst_reg->smax_value = S64_MAX;
7400 } else {
7401 dst_reg->smin_value = smin_ptr + smin_val;
7402 dst_reg->smax_value = smax_ptr + smax_val;
7403 }
7404 if (umin_ptr + umin_val < umin_ptr ||
7405 umax_ptr + umax_val < umax_ptr) {
7406 dst_reg->umin_value = 0;
7407 dst_reg->umax_value = U64_MAX;
7408 } else {
7409 dst_reg->umin_value = umin_ptr + umin_val;
7410 dst_reg->umax_value = umax_ptr + umax_val;
7411 }
Edward Creef1174f72017-08-07 15:26:19 +01007412 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
7413 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01007414 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007415 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01007416 dst_reg->id = ++env->id_gen;
7417 /* something was added to pkt_ptr, set range to zero */
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08007418 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01007419 }
Josef Bacik48461132016-09-28 10:54:32 -04007420 break;
7421 case BPF_SUB:
Edward Creef1174f72017-08-07 15:26:19 +01007422 if (dst_reg == off_reg) {
7423 /* scalar -= pointer. Creates an unknown scalar */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007424 verbose(env, "R%d tried to subtract pointer from scalar\n",
7425 dst);
Edward Creef1174f72017-08-07 15:26:19 +01007426 return -EACCES;
7427 }
7428 /* We don't allow subtraction from FP, because (according to
7429 * test_verifier.c test "invalid fp arithmetic", JITs might not
7430 * be able to deal with it.
Edward Cree93057062017-07-21 14:37:34 +01007431 */
Edward Creef1174f72017-08-07 15:26:19 +01007432 if (ptr_reg->type == PTR_TO_STACK) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007433 verbose(env, "R%d subtraction from stack pointer prohibited\n",
7434 dst);
Edward Creef1174f72017-08-07 15:26:19 +01007435 return -EACCES;
7436 }
Edward Creeb03c9f92017-08-07 15:26:36 +01007437 if (known && (ptr_reg->off - smin_val ==
7438 (s64)(s32)(ptr_reg->off - smin_val))) {
Edward Creef1174f72017-08-07 15:26:19 +01007439 /* pointer -= K. Subtract it from fixed offset */
Edward Creeb03c9f92017-08-07 15:26:36 +01007440 dst_reg->smin_value = smin_ptr;
7441 dst_reg->smax_value = smax_ptr;
7442 dst_reg->umin_value = umin_ptr;
7443 dst_reg->umax_value = umax_ptr;
Edward Creef1174f72017-08-07 15:26:19 +01007444 dst_reg->var_off = ptr_reg->var_off;
7445 dst_reg->id = ptr_reg->id;
Edward Creeb03c9f92017-08-07 15:26:36 +01007446 dst_reg->off = ptr_reg->off - smin_val;
Daniel Borkmann09625902018-11-01 00:05:52 +01007447 dst_reg->raw = ptr_reg->raw;
Edward Creef1174f72017-08-07 15:26:19 +01007448 break;
7449 }
Edward Creef1174f72017-08-07 15:26:19 +01007450 /* A new variable offset is created. If the subtrahend is known
7451 * nonnegative, then any reg->range we had before is still good.
7452 */
Edward Creeb03c9f92017-08-07 15:26:36 +01007453 if (signed_sub_overflows(smin_ptr, smax_val) ||
7454 signed_sub_overflows(smax_ptr, smin_val)) {
7455 /* Overflow possible, we know nothing */
7456 dst_reg->smin_value = S64_MIN;
7457 dst_reg->smax_value = S64_MAX;
7458 } else {
7459 dst_reg->smin_value = smin_ptr - smax_val;
7460 dst_reg->smax_value = smax_ptr - smin_val;
7461 }
7462 if (umin_ptr < umax_val) {
7463 /* Overflow possible, we know nothing */
7464 dst_reg->umin_value = 0;
7465 dst_reg->umax_value = U64_MAX;
7466 } else {
7467 /* Cannot overflow (as long as bounds are consistent) */
7468 dst_reg->umin_value = umin_ptr - umax_val;
7469 dst_reg->umax_value = umax_ptr - umin_val;
7470 }
Edward Creef1174f72017-08-07 15:26:19 +01007471 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
7472 dst_reg->off = ptr_reg->off;
Daniel Borkmann09625902018-11-01 00:05:52 +01007473 dst_reg->raw = ptr_reg->raw;
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02007474 if (reg_is_pkt_pointer(ptr_reg)) {
Edward Creef1174f72017-08-07 15:26:19 +01007475 dst_reg->id = ++env->id_gen;
7476 /* something was added to pkt_ptr, set range to zero */
Edward Creeb03c9f92017-08-07 15:26:36 +01007477 if (smin_val < 0)
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08007478 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
Edward Creef1174f72017-08-07 15:26:19 +01007479 }
7480 break;
7481 case BPF_AND:
7482 case BPF_OR:
7483 case BPF_XOR:
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007484 /* bitwise ops on pointers are troublesome, prohibit. */
7485 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
7486 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01007487 return -EACCES;
7488 default:
7489 /* other operators (e.g. MUL,LSH) produce non-pointer results */
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08007490 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
7491 dst, bpf_alu_string[opcode >> 4]);
Edward Creef1174f72017-08-07 15:26:19 +01007492 return -EACCES;
7493 }
7494
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08007495 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
7496 return -EINVAL;
7497
Edward Creeb03c9f92017-08-07 15:26:36 +01007498 __update_reg_bounds(dst_reg);
7499 __reg_deduce_bounds(dst_reg);
7500 __reg_bound_offset(dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01007501
Daniel Borkmann073815b2021-03-23 15:05:48 +01007502 if (sanitize_check_bounds(env, insn, dst_reg) < 0)
7503 return -EACCES;
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007504 if (sanitize_needed(opcode)) {
7505 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
Daniel Borkmann3d0220f2021-05-21 10:17:36 +00007506 &info, true);
Daniel Borkmann7fedb632021-03-24 10:38:26 +01007507 if (ret < 0)
7508 return sanitize_err(env, insn, ret, off_reg, dst_reg);
Daniel Borkmann0d6303d2019-01-03 00:58:30 +01007509 }
7510
Edward Creef1174f72017-08-07 15:26:19 +01007511 return 0;
7512}
7513
John Fastabend3f50f132020-03-30 14:36:39 -07007514static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
7515 struct bpf_reg_state *src_reg)
7516{
7517 s32 smin_val = src_reg->s32_min_value;
7518 s32 smax_val = src_reg->s32_max_value;
7519 u32 umin_val = src_reg->u32_min_value;
7520 u32 umax_val = src_reg->u32_max_value;
7521
7522 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
7523 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
7524 dst_reg->s32_min_value = S32_MIN;
7525 dst_reg->s32_max_value = S32_MAX;
7526 } else {
7527 dst_reg->s32_min_value += smin_val;
7528 dst_reg->s32_max_value += smax_val;
7529 }
7530 if (dst_reg->u32_min_value + umin_val < umin_val ||
7531 dst_reg->u32_max_value + umax_val < umax_val) {
7532 dst_reg->u32_min_value = 0;
7533 dst_reg->u32_max_value = U32_MAX;
7534 } else {
7535 dst_reg->u32_min_value += umin_val;
7536 dst_reg->u32_max_value += umax_val;
7537 }
7538}
7539
John Fastabend07cd2632020-03-24 10:38:15 -07007540static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
7541 struct bpf_reg_state *src_reg)
7542{
7543 s64 smin_val = src_reg->smin_value;
7544 s64 smax_val = src_reg->smax_value;
7545 u64 umin_val = src_reg->umin_value;
7546 u64 umax_val = src_reg->umax_value;
7547
7548 if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
7549 signed_add_overflows(dst_reg->smax_value, smax_val)) {
7550 dst_reg->smin_value = S64_MIN;
7551 dst_reg->smax_value = S64_MAX;
7552 } else {
7553 dst_reg->smin_value += smin_val;
7554 dst_reg->smax_value += smax_val;
7555 }
7556 if (dst_reg->umin_value + umin_val < umin_val ||
7557 dst_reg->umax_value + umax_val < umax_val) {
7558 dst_reg->umin_value = 0;
7559 dst_reg->umax_value = U64_MAX;
7560 } else {
7561 dst_reg->umin_value += umin_val;
7562 dst_reg->umax_value += umax_val;
7563 }
John Fastabend3f50f132020-03-30 14:36:39 -07007564}
7565
7566static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
7567 struct bpf_reg_state *src_reg)
7568{
7569 s32 smin_val = src_reg->s32_min_value;
7570 s32 smax_val = src_reg->s32_max_value;
7571 u32 umin_val = src_reg->u32_min_value;
7572 u32 umax_val = src_reg->u32_max_value;
7573
7574 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
7575 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
7576 /* Overflow possible, we know nothing */
7577 dst_reg->s32_min_value = S32_MIN;
7578 dst_reg->s32_max_value = S32_MAX;
7579 } else {
7580 dst_reg->s32_min_value -= smax_val;
7581 dst_reg->s32_max_value -= smin_val;
7582 }
7583 if (dst_reg->u32_min_value < umax_val) {
7584 /* Overflow possible, we know nothing */
7585 dst_reg->u32_min_value = 0;
7586 dst_reg->u32_max_value = U32_MAX;
7587 } else {
7588 /* Cannot overflow (as long as bounds are consistent) */
7589 dst_reg->u32_min_value -= umax_val;
7590 dst_reg->u32_max_value -= umin_val;
7591 }
John Fastabend07cd2632020-03-24 10:38:15 -07007592}
7593
7594static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
7595 struct bpf_reg_state *src_reg)
7596{
7597 s64 smin_val = src_reg->smin_value;
7598 s64 smax_val = src_reg->smax_value;
7599 u64 umin_val = src_reg->umin_value;
7600 u64 umax_val = src_reg->umax_value;
7601
7602 if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
7603 signed_sub_overflows(dst_reg->smax_value, smin_val)) {
7604 /* Overflow possible, we know nothing */
7605 dst_reg->smin_value = S64_MIN;
7606 dst_reg->smax_value = S64_MAX;
7607 } else {
7608 dst_reg->smin_value -= smax_val;
7609 dst_reg->smax_value -= smin_val;
7610 }
7611 if (dst_reg->umin_value < umax_val) {
7612 /* Overflow possible, we know nothing */
7613 dst_reg->umin_value = 0;
7614 dst_reg->umax_value = U64_MAX;
7615 } else {
7616 /* Cannot overflow (as long as bounds are consistent) */
7617 dst_reg->umin_value -= umax_val;
7618 dst_reg->umax_value -= umin_val;
7619 }
John Fastabend3f50f132020-03-30 14:36:39 -07007620}
7621
7622static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
7623 struct bpf_reg_state *src_reg)
7624{
7625 s32 smin_val = src_reg->s32_min_value;
7626 u32 umin_val = src_reg->u32_min_value;
7627 u32 umax_val = src_reg->u32_max_value;
7628
7629 if (smin_val < 0 || dst_reg->s32_min_value < 0) {
7630 /* Ain't nobody got time to multiply that sign */
7631 __mark_reg32_unbounded(dst_reg);
7632 return;
7633 }
7634 /* Both values are positive, so we can work with unsigned and
7635 * copy the result to signed (unless it exceeds S32_MAX).
7636 */
7637 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
7638 /* Potential overflow, we know nothing */
7639 __mark_reg32_unbounded(dst_reg);
7640 return;
7641 }
7642 dst_reg->u32_min_value *= umin_val;
7643 dst_reg->u32_max_value *= umax_val;
7644 if (dst_reg->u32_max_value > S32_MAX) {
7645 /* Overflow possible, we know nothing */
7646 dst_reg->s32_min_value = S32_MIN;
7647 dst_reg->s32_max_value = S32_MAX;
7648 } else {
7649 dst_reg->s32_min_value = dst_reg->u32_min_value;
7650 dst_reg->s32_max_value = dst_reg->u32_max_value;
7651 }
John Fastabend07cd2632020-03-24 10:38:15 -07007652}
7653
7654static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
7655 struct bpf_reg_state *src_reg)
7656{
7657 s64 smin_val = src_reg->smin_value;
7658 u64 umin_val = src_reg->umin_value;
7659 u64 umax_val = src_reg->umax_value;
7660
John Fastabend07cd2632020-03-24 10:38:15 -07007661 if (smin_val < 0 || dst_reg->smin_value < 0) {
7662 /* Ain't nobody got time to multiply that sign */
John Fastabend3f50f132020-03-30 14:36:39 -07007663 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007664 return;
7665 }
7666 /* Both values are positive, so we can work with unsigned and
7667 * copy the result to signed (unless it exceeds S64_MAX).
7668 */
7669 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
7670 /* Potential overflow, we know nothing */
John Fastabend3f50f132020-03-30 14:36:39 -07007671 __mark_reg64_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07007672 return;
7673 }
7674 dst_reg->umin_value *= umin_val;
7675 dst_reg->umax_value *= umax_val;
7676 if (dst_reg->umax_value > S64_MAX) {
7677 /* Overflow possible, we know nothing */
7678 dst_reg->smin_value = S64_MIN;
7679 dst_reg->smax_value = S64_MAX;
7680 } else {
7681 dst_reg->smin_value = dst_reg->umin_value;
7682 dst_reg->smax_value = dst_reg->umax_value;
7683 }
7684}
7685
John Fastabend3f50f132020-03-30 14:36:39 -07007686static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
7687 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007688{
John Fastabend3f50f132020-03-30 14:36:39 -07007689 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7690 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7691 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7692 s32 smin_val = src_reg->s32_min_value;
7693 u32 umax_val = src_reg->u32_max_value;
7694
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007695 if (src_known && dst_known) {
7696 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007697 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007698 }
John Fastabend07cd2632020-03-24 10:38:15 -07007699
7700 /* We get our minimum from the var_off, since that's inherently
7701 * bitwise. Our maximum is the minimum of the operands' maxima.
7702 */
John Fastabend3f50f132020-03-30 14:36:39 -07007703 dst_reg->u32_min_value = var32_off.value;
7704 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
7705 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7706 /* Lose signed bounds when ANDing negative numbers,
7707 * ain't nobody got time for that.
7708 */
7709 dst_reg->s32_min_value = S32_MIN;
7710 dst_reg->s32_max_value = S32_MAX;
7711 } else {
7712 /* ANDing two positives gives a positive, so safe to
7713 * cast result into s64.
7714 */
7715 dst_reg->s32_min_value = dst_reg->u32_min_value;
7716 dst_reg->s32_max_value = dst_reg->u32_max_value;
7717 }
John Fastabend3f50f132020-03-30 14:36:39 -07007718}
7719
7720static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
7721 struct bpf_reg_state *src_reg)
7722{
7723 bool src_known = tnum_is_const(src_reg->var_off);
7724 bool dst_known = tnum_is_const(dst_reg->var_off);
7725 s64 smin_val = src_reg->smin_value;
7726 u64 umax_val = src_reg->umax_value;
7727
7728 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007729 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007730 return;
7731 }
7732
7733 /* We get our minimum from the var_off, since that's inherently
7734 * bitwise. Our maximum is the minimum of the operands' maxima.
7735 */
John Fastabend07cd2632020-03-24 10:38:15 -07007736 dst_reg->umin_value = dst_reg->var_off.value;
7737 dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
7738 if (dst_reg->smin_value < 0 || smin_val < 0) {
7739 /* Lose signed bounds when ANDing negative numbers,
7740 * ain't nobody got time for that.
7741 */
7742 dst_reg->smin_value = S64_MIN;
7743 dst_reg->smax_value = S64_MAX;
7744 } else {
7745 /* ANDing two positives gives a positive, so safe to
7746 * cast result into s64.
7747 */
7748 dst_reg->smin_value = dst_reg->umin_value;
7749 dst_reg->smax_value = dst_reg->umax_value;
7750 }
7751 /* We may learn something more from the var_off */
7752 __update_reg_bounds(dst_reg);
7753}
7754
John Fastabend3f50f132020-03-30 14:36:39 -07007755static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
7756 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07007757{
John Fastabend3f50f132020-03-30 14:36:39 -07007758 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7759 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7760 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007761 s32 smin_val = src_reg->s32_min_value;
7762 u32 umin_val = src_reg->u32_min_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007763
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007764 if (src_known && dst_known) {
7765 __mark_reg32_known(dst_reg, var32_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007766 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007767 }
John Fastabend07cd2632020-03-24 10:38:15 -07007768
7769 /* We get our maximum from the var_off, and our minimum is the
7770 * maximum of the operands' minima
7771 */
John Fastabend3f50f132020-03-30 14:36:39 -07007772 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
7773 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7774 if (dst_reg->s32_min_value < 0 || smin_val < 0) {
7775 /* Lose signed bounds when ORing negative numbers,
7776 * ain't nobody got time for that.
7777 */
7778 dst_reg->s32_min_value = S32_MIN;
7779 dst_reg->s32_max_value = S32_MAX;
7780 } else {
7781 /* ORing two positives gives a positive, so safe to
7782 * cast result into s64.
7783 */
Daniel Borkmann5b9fbeb2020-10-07 15:48:58 +02007784 dst_reg->s32_min_value = dst_reg->u32_min_value;
7785 dst_reg->s32_max_value = dst_reg->u32_max_value;
John Fastabend3f50f132020-03-30 14:36:39 -07007786 }
7787}
7788
7789static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
7790 struct bpf_reg_state *src_reg)
7791{
7792 bool src_known = tnum_is_const(src_reg->var_off);
7793 bool dst_known = tnum_is_const(dst_reg->var_off);
7794 s64 smin_val = src_reg->smin_value;
7795 u64 umin_val = src_reg->umin_value;
7796
7797 if (src_known && dst_known) {
John Fastabend4fbb38a2020-09-24 11:45:06 -07007798 __mark_reg_known(dst_reg, dst_reg->var_off.value);
John Fastabend3f50f132020-03-30 14:36:39 -07007799 return;
7800 }
7801
7802 /* We get our maximum from the var_off, and our minimum is the
7803 * maximum of the operands' minima
7804 */
John Fastabend07cd2632020-03-24 10:38:15 -07007805 dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
7806 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7807 if (dst_reg->smin_value < 0 || smin_val < 0) {
7808 /* Lose signed bounds when ORing negative numbers,
7809 * ain't nobody got time for that.
7810 */
7811 dst_reg->smin_value = S64_MIN;
7812 dst_reg->smax_value = S64_MAX;
7813 } else {
7814 /* ORing two positives gives a positive, so safe to
7815 * cast result into s64.
7816 */
7817 dst_reg->smin_value = dst_reg->umin_value;
7818 dst_reg->smax_value = dst_reg->umax_value;
7819 }
7820 /* We may learn something more from the var_off */
7821 __update_reg_bounds(dst_reg);
7822}
7823
Yonghong Song2921c902020-08-24 23:46:08 -07007824static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
7825 struct bpf_reg_state *src_reg)
7826{
7827 bool src_known = tnum_subreg_is_const(src_reg->var_off);
7828 bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
7829 struct tnum var32_off = tnum_subreg(dst_reg->var_off);
7830 s32 smin_val = src_reg->s32_min_value;
7831
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007832 if (src_known && dst_known) {
7833 __mark_reg32_known(dst_reg, var32_off.value);
Yonghong Song2921c902020-08-24 23:46:08 -07007834 return;
Daniel Borkmann049c4e12021-05-10 13:10:44 +00007835 }
Yonghong Song2921c902020-08-24 23:46:08 -07007836
7837 /* We get both minimum and maximum from the var32_off. */
7838 dst_reg->u32_min_value = var32_off.value;
7839 dst_reg->u32_max_value = var32_off.value | var32_off.mask;
7840
7841 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
7842 /* XORing two positive sign numbers gives a positive,
7843 * so safe to cast u32 result into s32.
7844 */
7845 dst_reg->s32_min_value = dst_reg->u32_min_value;
7846 dst_reg->s32_max_value = dst_reg->u32_max_value;
7847 } else {
7848 dst_reg->s32_min_value = S32_MIN;
7849 dst_reg->s32_max_value = S32_MAX;
7850 }
7851}
7852
7853static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
7854 struct bpf_reg_state *src_reg)
7855{
7856 bool src_known = tnum_is_const(src_reg->var_off);
7857 bool dst_known = tnum_is_const(dst_reg->var_off);
7858 s64 smin_val = src_reg->smin_value;
7859
7860 if (src_known && dst_known) {
7861 /* dst_reg->var_off.value has been updated earlier */
7862 __mark_reg_known(dst_reg, dst_reg->var_off.value);
7863 return;
7864 }
7865
7866 /* We get both minimum and maximum from the var_off. */
7867 dst_reg->umin_value = dst_reg->var_off.value;
7868 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
7869
7870 if (dst_reg->smin_value >= 0 && smin_val >= 0) {
7871 /* XORing two positive sign numbers gives a positive,
7872 * so safe to cast u64 result into s64.
7873 */
7874 dst_reg->smin_value = dst_reg->umin_value;
7875 dst_reg->smax_value = dst_reg->umax_value;
7876 } else {
7877 dst_reg->smin_value = S64_MIN;
7878 dst_reg->smax_value = S64_MAX;
7879 }
7880
7881 __update_reg_bounds(dst_reg);
7882}
7883
John Fastabend3f50f132020-03-30 14:36:39 -07007884static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7885 u64 umin_val, u64 umax_val)
John Fastabend07cd2632020-03-24 10:38:15 -07007886{
John Fastabend07cd2632020-03-24 10:38:15 -07007887 /* We lose all sign bit information (except what we can pick
7888 * up from var_off)
7889 */
John Fastabend3f50f132020-03-30 14:36:39 -07007890 dst_reg->s32_min_value = S32_MIN;
7891 dst_reg->s32_max_value = S32_MAX;
7892 /* If we might shift our top bit out, then we know nothing */
7893 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
7894 dst_reg->u32_min_value = 0;
7895 dst_reg->u32_max_value = U32_MAX;
7896 } else {
7897 dst_reg->u32_min_value <<= umin_val;
7898 dst_reg->u32_max_value <<= umax_val;
7899 }
7900}
7901
7902static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
7903 struct bpf_reg_state *src_reg)
7904{
7905 u32 umax_val = src_reg->u32_max_value;
7906 u32 umin_val = src_reg->u32_min_value;
7907 /* u32 alu operation will zext upper bits */
7908 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7909
7910 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7911 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
7912 /* Not required but being careful mark reg64 bounds as unknown so
7913 * that we are forced to pick them up from tnum and zext later and
7914 * if some path skips this step we are still safe.
7915 */
7916 __mark_reg64_unbounded(dst_reg);
7917 __update_reg32_bounds(dst_reg);
7918}
7919
7920static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
7921 u64 umin_val, u64 umax_val)
7922{
7923 /* Special case <<32 because it is a common compiler pattern to sign
7924 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
7925 * positive we know this shift will also be positive so we can track
7926 * bounds correctly. Otherwise we lose all sign bit information except
7927 * what we can pick up from var_off. Perhaps we can generalize this
7928 * later to shifts of any length.
7929 */
7930 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
7931 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
7932 else
7933 dst_reg->smax_value = S64_MAX;
7934
7935 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
7936 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
7937 else
7938 dst_reg->smin_value = S64_MIN;
7939
John Fastabend07cd2632020-03-24 10:38:15 -07007940 /* If we might shift our top bit out, then we know nothing */
7941 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
7942 dst_reg->umin_value = 0;
7943 dst_reg->umax_value = U64_MAX;
7944 } else {
7945 dst_reg->umin_value <<= umin_val;
7946 dst_reg->umax_value <<= umax_val;
7947 }
John Fastabend3f50f132020-03-30 14:36:39 -07007948}
7949
7950static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
7951 struct bpf_reg_state *src_reg)
7952{
7953 u64 umax_val = src_reg->umax_value;
7954 u64 umin_val = src_reg->umin_value;
7955
7956 /* scalar64 calc uses 32bit unshifted bounds so must be called first */
7957 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
7958 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
7959
John Fastabend07cd2632020-03-24 10:38:15 -07007960 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
7961 /* We may learn something more from the var_off */
7962 __update_reg_bounds(dst_reg);
7963}
7964
John Fastabend3f50f132020-03-30 14:36:39 -07007965static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
7966 struct bpf_reg_state *src_reg)
7967{
7968 struct tnum subreg = tnum_subreg(dst_reg->var_off);
7969 u32 umax_val = src_reg->u32_max_value;
7970 u32 umin_val = src_reg->u32_min_value;
7971
7972 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
7973 * be negative, then either:
7974 * 1) src_reg might be zero, so the sign bit of the result is
7975 * unknown, so we lose our signed bounds
7976 * 2) it's known negative, thus the unsigned bounds capture the
7977 * signed bounds
7978 * 3) the signed bounds cross zero, so they tell us nothing
7979 * about the result
7980 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01007981 * unsigned bounds capture the signed bounds.
John Fastabend3f50f132020-03-30 14:36:39 -07007982 * Thus, in all cases it suffices to blow away our signed bounds
7983 * and rely on inferring new ones from the unsigned bounds and
7984 * var_off of the result.
7985 */
7986 dst_reg->s32_min_value = S32_MIN;
7987 dst_reg->s32_max_value = S32_MAX;
7988
7989 dst_reg->var_off = tnum_rshift(subreg, umin_val);
7990 dst_reg->u32_min_value >>= umax_val;
7991 dst_reg->u32_max_value >>= umin_val;
7992
7993 __mark_reg64_unbounded(dst_reg);
7994 __update_reg32_bounds(dst_reg);
7995}
7996
John Fastabend07cd2632020-03-24 10:38:15 -07007997static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
7998 struct bpf_reg_state *src_reg)
7999{
8000 u64 umax_val = src_reg->umax_value;
8001 u64 umin_val = src_reg->umin_value;
8002
8003 /* BPF_RSH is an unsigned shift. If the value in dst_reg might
8004 * be negative, then either:
8005 * 1) src_reg might be zero, so the sign bit of the result is
8006 * unknown, so we lose our signed bounds
8007 * 2) it's known negative, thus the unsigned bounds capture the
8008 * signed bounds
8009 * 3) the signed bounds cross zero, so they tell us nothing
8010 * about the result
8011 * If the value in dst_reg is known nonnegative, then again the
Tobias Klauser18b24d72021-01-21 18:43:24 +01008012 * unsigned bounds capture the signed bounds.
John Fastabend07cd2632020-03-24 10:38:15 -07008013 * Thus, in all cases it suffices to blow away our signed bounds
8014 * and rely on inferring new ones from the unsigned bounds and
8015 * var_off of the result.
8016 */
8017 dst_reg->smin_value = S64_MIN;
8018 dst_reg->smax_value = S64_MAX;
8019 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
8020 dst_reg->umin_value >>= umax_val;
8021 dst_reg->umax_value >>= umin_val;
John Fastabend3f50f132020-03-30 14:36:39 -07008022
8023 /* Its not easy to operate on alu32 bounds here because it depends
8024 * on bits being shifted in. Take easy way out and mark unbounded
8025 * so we can recalculate later from tnum.
8026 */
8027 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008028 __update_reg_bounds(dst_reg);
8029}
8030
John Fastabend3f50f132020-03-30 14:36:39 -07008031static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
8032 struct bpf_reg_state *src_reg)
John Fastabend07cd2632020-03-24 10:38:15 -07008033{
John Fastabend3f50f132020-03-30 14:36:39 -07008034 u64 umin_val = src_reg->u32_min_value;
John Fastabend07cd2632020-03-24 10:38:15 -07008035
8036 /* Upon reaching here, src_known is true and
8037 * umax_val is equal to umin_val.
8038 */
John Fastabend3f50f132020-03-30 14:36:39 -07008039 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
8040 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
John Fastabend07cd2632020-03-24 10:38:15 -07008041
John Fastabend3f50f132020-03-30 14:36:39 -07008042 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
8043
8044 /* blow away the dst_reg umin_value/umax_value and rely on
8045 * dst_reg var_off to refine the result.
8046 */
8047 dst_reg->u32_min_value = 0;
8048 dst_reg->u32_max_value = U32_MAX;
8049
8050 __mark_reg64_unbounded(dst_reg);
8051 __update_reg32_bounds(dst_reg);
8052}
8053
8054static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
8055 struct bpf_reg_state *src_reg)
8056{
8057 u64 umin_val = src_reg->umin_value;
8058
8059 /* Upon reaching here, src_known is true and umax_val is equal
8060 * to umin_val.
8061 */
8062 dst_reg->smin_value >>= umin_val;
8063 dst_reg->smax_value >>= umin_val;
8064
8065 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
John Fastabend07cd2632020-03-24 10:38:15 -07008066
8067 /* blow away the dst_reg umin_value/umax_value and rely on
8068 * dst_reg var_off to refine the result.
8069 */
8070 dst_reg->umin_value = 0;
8071 dst_reg->umax_value = U64_MAX;
John Fastabend3f50f132020-03-30 14:36:39 -07008072
8073 /* Its not easy to operate on alu32 bounds here because it depends
8074 * on bits being shifted in from upper 32-bits. Take easy way out
8075 * and mark unbounded so we can recalculate later from tnum.
8076 */
8077 __mark_reg32_unbounded(dst_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008078 __update_reg_bounds(dst_reg);
8079}
8080
Jann Horn468f6ea2017-12-18 20:11:56 -08008081/* WARNING: This function does calculations on 64-bit values, but the actual
8082 * execution may occur on 32-bit values. Therefore, things like bitshifts
8083 * need extra checks in the 32-bit case.
8084 */
Edward Creef1174f72017-08-07 15:26:19 +01008085static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
8086 struct bpf_insn *insn,
8087 struct bpf_reg_state *dst_reg,
8088 struct bpf_reg_state src_reg)
8089{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008090 struct bpf_reg_state *regs = cur_regs(env);
Edward Creef1174f72017-08-07 15:26:19 +01008091 u8 opcode = BPF_OP(insn->code);
Mao Wenanb0b3fb62020-04-18 09:37:35 +08008092 bool src_known;
Edward Creeb03c9f92017-08-07 15:26:36 +01008093 s64 smin_val, smax_val;
8094 u64 umin_val, umax_val;
John Fastabend3f50f132020-03-30 14:36:39 -07008095 s32 s32_min_val, s32_max_val;
8096 u32 u32_min_val, u32_max_val;
Jann Horn468f6ea2017-12-18 20:11:56 -08008097 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
John Fastabend3f50f132020-03-30 14:36:39 -07008098 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
Daniel Borkmanna6aaece2021-03-23 09:30:01 +01008099 int ret;
Jann Hornb7992072018-10-05 18:17:59 +02008100
Edward Creeb03c9f92017-08-07 15:26:36 +01008101 smin_val = src_reg.smin_value;
8102 smax_val = src_reg.smax_value;
8103 umin_val = src_reg.umin_value;
8104 umax_val = src_reg.umax_value;
Edward Creef1174f72017-08-07 15:26:19 +01008105
John Fastabend3f50f132020-03-30 14:36:39 -07008106 s32_min_val = src_reg.s32_min_value;
8107 s32_max_val = src_reg.s32_max_value;
8108 u32_min_val = src_reg.u32_min_value;
8109 u32_max_val = src_reg.u32_max_value;
8110
8111 if (alu32) {
8112 src_known = tnum_subreg_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07008113 if ((src_known &&
8114 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
8115 s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
8116 /* Taint dst register if offset had invalid bounds
8117 * derived from e.g. dead branches.
8118 */
8119 __mark_reg_unknown(env, dst_reg);
8120 return 0;
8121 }
8122 } else {
8123 src_known = tnum_is_const(src_reg.var_off);
John Fastabend3f50f132020-03-30 14:36:39 -07008124 if ((src_known &&
8125 (smin_val != smax_val || umin_val != umax_val)) ||
8126 smin_val > smax_val || umin_val > umax_val) {
8127 /* Taint dst register if offset had invalid bounds
8128 * derived from e.g. dead branches.
8129 */
8130 __mark_reg_unknown(env, dst_reg);
8131 return 0;
8132 }
Daniel Borkmann6f161012018-01-18 01:15:21 +01008133 }
8134
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08008135 if (!src_known &&
8136 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +01008137 __mark_reg_unknown(env, dst_reg);
Alexei Starovoitovbb7f0f92017-12-18 20:12:00 -08008138 return 0;
8139 }
8140
Daniel Borkmannf5288192021-03-24 11:25:39 +01008141 if (sanitize_needed(opcode)) {
8142 ret = sanitize_val_alu(env, insn);
8143 if (ret < 0)
8144 return sanitize_err(env, insn, ret, NULL, NULL);
8145 }
8146
John Fastabend3f50f132020-03-30 14:36:39 -07008147 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
8148 * There are two classes of instructions: The first class we track both
8149 * alu32 and alu64 sign/unsigned bounds independently this provides the
8150 * greatest amount of precision when alu operations are mixed with jmp32
8151 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
8152 * and BPF_OR. This is possible because these ops have fairly easy to
8153 * understand and calculate behavior in both 32-bit and 64-bit alu ops.
8154 * See alu32 verifier tests for examples. The second class of
8155 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
8156 * with regards to tracking sign/unsigned bounds because the bits may
8157 * cross subreg boundaries in the alu64 case. When this happens we mark
8158 * the reg unbounded in the subreg bound space and use the resulting
8159 * tnum to calculate an approximation of the sign/unsigned bounds.
8160 */
Edward Creef1174f72017-08-07 15:26:19 +01008161 switch (opcode) {
8162 case BPF_ADD:
John Fastabend3f50f132020-03-30 14:36:39 -07008163 scalar32_min_max_add(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008164 scalar_min_max_add(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07008165 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
Edward Creef1174f72017-08-07 15:26:19 +01008166 break;
8167 case BPF_SUB:
John Fastabend3f50f132020-03-30 14:36:39 -07008168 scalar32_min_max_sub(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008169 scalar_min_max_sub(dst_reg, &src_reg);
John Fastabend3f50f132020-03-30 14:36:39 -07008170 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
Josef Bacik48461132016-09-28 10:54:32 -04008171 break;
8172 case BPF_MUL:
John Fastabend3f50f132020-03-30 14:36:39 -07008173 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
8174 scalar32_min_max_mul(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008175 scalar_min_max_mul(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008176 break;
8177 case BPF_AND:
John Fastabend3f50f132020-03-30 14:36:39 -07008178 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
8179 scalar32_min_max_and(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008180 scalar_min_max_and(dst_reg, &src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008181 break;
8182 case BPF_OR:
John Fastabend3f50f132020-03-30 14:36:39 -07008183 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
8184 scalar32_min_max_or(dst_reg, &src_reg);
John Fastabend07cd2632020-03-24 10:38:15 -07008185 scalar_min_max_or(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008186 break;
Yonghong Song2921c902020-08-24 23:46:08 -07008187 case BPF_XOR:
8188 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
8189 scalar32_min_max_xor(dst_reg, &src_reg);
8190 scalar_min_max_xor(dst_reg, &src_reg);
8191 break;
Josef Bacik48461132016-09-28 10:54:32 -04008192 case BPF_LSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08008193 if (umax_val >= insn_bitness) {
8194 /* Shifts greater than 31 or 63 are undefined.
8195 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01008196 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008197 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008198 break;
8199 }
John Fastabend3f50f132020-03-30 14:36:39 -07008200 if (alu32)
8201 scalar32_min_max_lsh(dst_reg, &src_reg);
8202 else
8203 scalar_min_max_lsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008204 break;
8205 case BPF_RSH:
Jann Horn468f6ea2017-12-18 20:11:56 -08008206 if (umax_val >= insn_bitness) {
8207 /* Shifts greater than 31 or 63 are undefined.
8208 * This includes shifts by a negative number.
Edward Creeb03c9f92017-08-07 15:26:36 +01008209 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008210 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008211 break;
8212 }
John Fastabend3f50f132020-03-30 14:36:39 -07008213 if (alu32)
8214 scalar32_min_max_rsh(dst_reg, &src_reg);
8215 else
8216 scalar_min_max_rsh(dst_reg, &src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008217 break;
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07008218 case BPF_ARSH:
8219 if (umax_val >= insn_bitness) {
8220 /* Shifts greater than 31 or 63 are undefined.
8221 * This includes shifts by a negative number.
8222 */
8223 mark_reg_unknown(env, regs, insn->dst_reg);
8224 break;
8225 }
John Fastabend3f50f132020-03-30 14:36:39 -07008226 if (alu32)
8227 scalar32_min_max_arsh(dst_reg, &src_reg);
8228 else
8229 scalar_min_max_arsh(dst_reg, &src_reg);
Yonghong Song9cbe1f5a2018-04-28 22:28:11 -07008230 break;
Josef Bacik48461132016-09-28 10:54:32 -04008231 default:
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008232 mark_reg_unknown(env, regs, insn->dst_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008233 break;
8234 }
8235
John Fastabend3f50f132020-03-30 14:36:39 -07008236 /* ALU32 ops are zero extended into 64bit register */
8237 if (alu32)
8238 zext_32_to_64(dst_reg);
Jann Horn468f6ea2017-12-18 20:11:56 -08008239
John Fastabend294f2fc2020-03-24 10:38:37 -07008240 __update_reg_bounds(dst_reg);
Edward Creeb03c9f92017-08-07 15:26:36 +01008241 __reg_deduce_bounds(dst_reg);
8242 __reg_bound_offset(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008243 return 0;
8244}
8245
8246/* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
8247 * and var_off.
8248 */
8249static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
8250 struct bpf_insn *insn)
8251{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008252 struct bpf_verifier_state *vstate = env->cur_state;
8253 struct bpf_func_state *state = vstate->frame[vstate->curframe];
8254 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
Edward Creef1174f72017-08-07 15:26:19 +01008255 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
8256 u8 opcode = BPF_OP(insn->code);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008257 int err;
Edward Creef1174f72017-08-07 15:26:19 +01008258
8259 dst_reg = &regs[insn->dst_reg];
Edward Creef1174f72017-08-07 15:26:19 +01008260 src_reg = NULL;
8261 if (dst_reg->type != SCALAR_VALUE)
8262 ptr_reg = dst_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07008263 else
8264 /* Make sure ID is cleared otherwise dst_reg min/max could be
8265 * incorrectly propagated into other registers by find_equal_scalars()
8266 */
8267 dst_reg->id = 0;
Edward Creef1174f72017-08-07 15:26:19 +01008268 if (BPF_SRC(insn->code) == BPF_X) {
8269 src_reg = &regs[insn->src_reg];
Edward Creef1174f72017-08-07 15:26:19 +01008270 if (src_reg->type != SCALAR_VALUE) {
8271 if (dst_reg->type != SCALAR_VALUE) {
8272 /* Combining two pointers by any ALU op yields
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008273 * an arbitrary scalar. Disallow all math except
8274 * pointer subtraction
Edward Creef1174f72017-08-07 15:26:19 +01008275 */
Alexei Starovoitovdd066822018-09-12 14:06:10 -07008276 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008277 mark_reg_unknown(env, regs, insn->dst_reg);
8278 return 0;
Edward Creef1174f72017-08-07 15:26:19 +01008279 }
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008280 verbose(env, "R%d pointer %s pointer prohibited\n",
8281 insn->dst_reg,
8282 bpf_alu_string[opcode >> 4]);
8283 return -EACCES;
Edward Creef1174f72017-08-07 15:26:19 +01008284 } else {
8285 /* scalar += pointer
8286 * This is legal, but we have to reverse our
8287 * src/dest handling in computing the range
8288 */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008289 err = mark_chain_precision(env, insn->dst_reg);
8290 if (err)
8291 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008292 return adjust_ptr_min_max_vals(env, insn,
8293 src_reg, dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008294 }
8295 } else if (ptr_reg) {
8296 /* pointer += scalar */
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07008297 err = mark_chain_precision(env, insn->src_reg);
8298 if (err)
8299 return err;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008300 return adjust_ptr_min_max_vals(env, insn,
8301 dst_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008302 }
8303 } else {
8304 /* Pretend the src is a reg with a known value, since we only
8305 * need to be able to read from this state.
8306 */
8307 off_reg.type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01008308 __mark_reg_known(&off_reg, insn->imm);
Edward Creef1174f72017-08-07 15:26:19 +01008309 src_reg = &off_reg;
Alexei Starovoitov82abbf82017-12-18 20:15:20 -08008310 if (ptr_reg) /* pointer += K */
8311 return adjust_ptr_min_max_vals(env, insn,
8312 ptr_reg, src_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008313 }
8314
8315 /* Got here implies adding two SCALAR_VALUEs */
8316 if (WARN_ON_ONCE(ptr_reg)) {
Christy Lee0f55f9e2021-12-16 13:33:56 -08008317 print_verifier_state(env, state, true);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008318 verbose(env, "verifier internal error: unexpected ptr_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01008319 return -EINVAL;
8320 }
8321 if (WARN_ON(!src_reg)) {
Christy Lee0f55f9e2021-12-16 13:33:56 -08008322 print_verifier_state(env, state, true);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008323 verbose(env, "verifier internal error: no src_reg\n");
Edward Creef1174f72017-08-07 15:26:19 +01008324 return -EINVAL;
8325 }
8326 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
Josef Bacik48461132016-09-28 10:54:32 -04008327}
8328
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008329/* check validity of 32-bit and 64-bit arithmetic operations */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01008330static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008331{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07008332 struct bpf_reg_state *regs = cur_regs(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008333 u8 opcode = BPF_OP(insn->code);
8334 int err;
8335
8336 if (opcode == BPF_END || opcode == BPF_NEG) {
8337 if (opcode == BPF_NEG) {
8338 if (BPF_SRC(insn->code) != 0 ||
8339 insn->src_reg != BPF_REG_0 ||
8340 insn->off != 0 || insn->imm != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008341 verbose(env, "BPF_NEG uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008342 return -EINVAL;
8343 }
8344 } else {
8345 if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
Edward Creee67b8a62017-09-15 14:37:38 +01008346 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
8347 BPF_CLASS(insn->code) == BPF_ALU64) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008348 verbose(env, "BPF_END uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008349 return -EINVAL;
8350 }
8351 }
8352
8353 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01008354 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008355 if (err)
8356 return err;
8357
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008358 if (is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008359 verbose(env, "R%d pointer arithmetic prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008360 insn->dst_reg);
8361 return -EACCES;
8362 }
8363
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008364 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01008365 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008366 if (err)
8367 return err;
8368
8369 } else if (opcode == BPF_MOV) {
8370
8371 if (BPF_SRC(insn->code) == BPF_X) {
8372 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008373 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008374 return -EINVAL;
8375 }
8376
8377 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +01008378 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008379 if (err)
8380 return err;
8381 } else {
8382 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008383 verbose(env, "BPF_MOV uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008384 return -EINVAL;
8385 }
8386 }
8387
Arthur Fabrefbeb1602018-07-31 18:17:22 +01008388 /* check dest operand, mark as required later */
8389 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008390 if (err)
8391 return err;
8392
8393 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wange434b8c2018-12-07 12:16:18 -05008394 struct bpf_reg_state *src_reg = regs + insn->src_reg;
8395 struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
8396
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008397 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8398 /* case: R1 = R2
8399 * copy register state to dest reg
8400 */
Alexei Starovoitov75748832020-10-08 18:12:37 -07008401 if (src_reg->type == SCALAR_VALUE && !src_reg->id)
8402 /* Assign src and dst registers the same ID
8403 * that will be used by find_equal_scalars()
8404 * to propagate min/max range.
8405 */
8406 src_reg->id = ++env->id_gen;
Jiong Wange434b8c2018-12-07 12:16:18 -05008407 *dst_reg = *src_reg;
8408 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01008409 dst_reg->subreg_def = DEF_NOT_SUBREG;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008410 } else {
Edward Creef1174f72017-08-07 15:26:19 +01008411 /* R1 = (u32) R2 */
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008412 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008413 verbose(env,
8414 "R%d partial copy of pointer\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008415 insn->src_reg);
8416 return -EACCES;
Jiong Wange434b8c2018-12-07 12:16:18 -05008417 } else if (src_reg->type == SCALAR_VALUE) {
8418 *dst_reg = *src_reg;
Alexei Starovoitov75748832020-10-08 18:12:37 -07008419 /* Make sure ID is cleared otherwise
8420 * dst_reg min/max could be incorrectly
8421 * propagated into src_reg by find_equal_scalars()
8422 */
8423 dst_reg->id = 0;
Jiong Wange434b8c2018-12-07 12:16:18 -05008424 dst_reg->live |= REG_LIVE_WRITTEN;
Jiong Wang5327ed32019-05-24 23:25:12 +01008425 dst_reg->subreg_def = env->insn_idx + 1;
Jiong Wange434b8c2018-12-07 12:16:18 -05008426 } else {
8427 mark_reg_unknown(env, regs,
8428 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07008429 }
John Fastabend3f50f132020-03-30 14:36:39 -07008430 zext_32_to_64(dst_reg);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008431 }
8432 } else {
8433 /* case: R = imm
8434 * remember the value we stored into this reg
8435 */
Arthur Fabrefbeb1602018-07-31 18:17:22 +01008436 /* clear any state __mark_reg_known doesn't set */
8437 mark_reg_unknown(env, regs, insn->dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01008438 regs[insn->dst_reg].type = SCALAR_VALUE;
Jann Horn95a762e2017-12-18 20:11:54 -08008439 if (BPF_CLASS(insn->code) == BPF_ALU64) {
8440 __mark_reg_known(regs + insn->dst_reg,
8441 insn->imm);
8442 } else {
8443 __mark_reg_known(regs + insn->dst_reg,
8444 (u32)insn->imm);
8445 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008446 }
8447
8448 } else if (opcode > BPF_END) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008449 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008450 return -EINVAL;
8451
8452 } else { /* all other ALU ops: and, sub, xor, add, ... */
8453
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008454 if (BPF_SRC(insn->code) == BPF_X) {
8455 if (insn->imm != 0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008456 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008457 return -EINVAL;
8458 }
8459 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008460 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008461 if (err)
8462 return err;
8463 } else {
8464 if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008465 verbose(env, "BPF_ALU uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008466 return -EINVAL;
8467 }
8468 }
8469
8470 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01008471 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008472 if (err)
8473 return err;
8474
8475 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
8476 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008477 verbose(env, "div by zero\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008478 return -EINVAL;
8479 }
8480
Rabin Vincent229394e82016-01-12 20:17:08 +01008481 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
8482 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
8483 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
8484
8485 if (insn->imm < 0 || insn->imm >= size) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07008486 verbose(env, "invalid shift %d\n", insn->imm);
Rabin Vincent229394e82016-01-12 20:17:08 +01008487 return -EINVAL;
8488 }
8489 }
8490
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008491 /* check dest operand */
Edward Creedc503a82017-08-15 20:34:35 +01008492 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07008493 if (err)
8494 return err;
8495
Edward Creef1174f72017-08-07 15:26:19 +01008496 return adjust_reg_min_max_vals(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07008497 }
8498
8499 return 0;
8500}
8501
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008502static void __find_good_pkt_pointers(struct bpf_func_state *state,
8503 struct bpf_reg_state *dst_reg,
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008504 enum bpf_reg_type type, int new_range)
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008505{
8506 struct bpf_reg_state *reg;
8507 int i;
8508
8509 for (i = 0; i < MAX_BPF_REG; i++) {
8510 reg = &state->regs[i];
8511 if (reg->type == type && reg->id == dst_reg->id)
8512 /* keep the maximum range already checked */
8513 reg->range = max(reg->range, new_range);
8514 }
8515
8516 bpf_for_each_spilled_reg(i, state, reg) {
8517 if (!reg)
8518 continue;
8519 if (reg->type == type && reg->id == dst_reg->id)
8520 reg->range = max(reg->range, new_range);
8521 }
8522}
8523
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08008524static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
Daniel Borkmannde8f3a82017-09-25 02:25:51 +02008525 struct bpf_reg_state *dst_reg,
David S. Millerf8ddadc2017-10-22 13:36:53 +01008526 enum bpf_reg_type type,
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008527 bool range_right_open)
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008528{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008529 int new_range, i;
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008530
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008531 if (dst_reg->off < 0 ||
8532 (dst_reg->off == 0 && range_right_open))
Edward Creef1174f72017-08-07 15:26:19 +01008533 /* This doesn't give us any range */
8534 return;
8535
Edward Creeb03c9f92017-08-07 15:26:36 +01008536 if (dst_reg->umax_value > MAX_PACKET_OFF ||
8537 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
Edward Creef1174f72017-08-07 15:26:19 +01008538 /* Risk of overflow. For instance, ptr + (1<<63) may be less
8539 * than pkt_end, but that's because it's also less than pkt.
8540 */
8541 return;
8542
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008543 new_range = dst_reg->off;
8544 if (range_right_open)
Maxim Mikityanskiy2fa7d942021-11-30 20:16:07 +02008545 new_range++;
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008546
8547 /* Examples for register markings:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008548 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008549 * pkt_data in dst register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008550 *
8551 * r2 = r3;
8552 * r2 += 8;
8553 * if (r2 > pkt_end) goto <handle exception>
8554 * <access okay>
8555 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008556 * r2 = r3;
8557 * r2 += 8;
8558 * if (r2 < pkt_end) goto <access okay>
8559 * <handle exception>
8560 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008561 * Where:
8562 * r2 == dst_reg, pkt_end == src_reg
8563 * r2=pkt(id=n,off=8,r=0)
8564 * r3=pkt(id=n,off=0,r=0)
8565 *
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008566 * pkt_data in src register:
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008567 *
8568 * r2 = r3;
8569 * r2 += 8;
8570 * if (pkt_end >= r2) goto <access okay>
8571 * <handle exception>
8572 *
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008573 * r2 = r3;
8574 * r2 += 8;
8575 * if (pkt_end <= r2) goto <handle exception>
8576 * <access okay>
8577 *
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008578 * Where:
8579 * pkt_end == dst_reg, r2 == src_reg
8580 * r2=pkt(id=n,off=8,r=0)
8581 * r3=pkt(id=n,off=0,r=0)
8582 *
8583 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
Daniel Borkmannfb2a3112017-10-21 02:34:21 +02008584 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
8585 * and [r3, r3 + 8-1) respectively is safe to access depending on
8586 * the check.
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008587 */
Daniel Borkmann2d2be8c2016-09-08 01:03:42 +02008588
Edward Creef1174f72017-08-07 15:26:19 +01008589 /* If our ids match, then we must have the same max_value. And we
8590 * don't care about the other reg's fixed offset, since if it's too big
8591 * the range won't allow anything.
8592 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
8593 */
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02008594 for (i = 0; i <= vstate->curframe; i++)
8595 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type,
8596 new_range);
Alexei Starovoitov969bf052016-05-05 19:49:10 -07008597}
8598
John Fastabend3f50f132020-03-30 14:36:39 -07008599static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008600{
John Fastabend3f50f132020-03-30 14:36:39 -07008601 struct tnum subreg = tnum_subreg(reg->var_off);
8602 s32 sval = (s32)val;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008603
John Fastabend3f50f132020-03-30 14:36:39 -07008604 switch (opcode) {
8605 case BPF_JEQ:
8606 if (tnum_is_const(subreg))
8607 return !!tnum_equals_const(subreg, val);
8608 break;
8609 case BPF_JNE:
8610 if (tnum_is_const(subreg))
8611 return !tnum_equals_const(subreg, val);
8612 break;
8613 case BPF_JSET:
8614 if ((~subreg.mask & subreg.value) & val)
8615 return 1;
8616 if (!((subreg.mask | subreg.value) & val))
8617 return 0;
8618 break;
8619 case BPF_JGT:
8620 if (reg->u32_min_value > val)
8621 return 1;
8622 else if (reg->u32_max_value <= val)
8623 return 0;
8624 break;
8625 case BPF_JSGT:
8626 if (reg->s32_min_value > sval)
8627 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008628 else if (reg->s32_max_value <= sval)
John Fastabend3f50f132020-03-30 14:36:39 -07008629 return 0;
8630 break;
8631 case BPF_JLT:
8632 if (reg->u32_max_value < val)
8633 return 1;
8634 else if (reg->u32_min_value >= val)
8635 return 0;
8636 break;
8637 case BPF_JSLT:
8638 if (reg->s32_max_value < sval)
8639 return 1;
8640 else if (reg->s32_min_value >= sval)
8641 return 0;
8642 break;
8643 case BPF_JGE:
8644 if (reg->u32_min_value >= val)
8645 return 1;
8646 else if (reg->u32_max_value < val)
8647 return 0;
8648 break;
8649 case BPF_JSGE:
8650 if (reg->s32_min_value >= sval)
8651 return 1;
8652 else if (reg->s32_max_value < sval)
8653 return 0;
8654 break;
8655 case BPF_JLE:
8656 if (reg->u32_max_value <= val)
8657 return 1;
8658 else if (reg->u32_min_value > val)
8659 return 0;
8660 break;
8661 case BPF_JSLE:
8662 if (reg->s32_max_value <= sval)
8663 return 1;
8664 else if (reg->s32_min_value > sval)
8665 return 0;
8666 break;
Jiong Wang092ed092019-01-26 12:26:01 -05008667 }
Jiong Wanga72dafa2019-01-26 12:26:00 -05008668
John Fastabend3f50f132020-03-30 14:36:39 -07008669 return -1;
8670}
8671
8672
8673static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
8674{
8675 s64 sval = (s64)val;
8676
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008677 switch (opcode) {
8678 case BPF_JEQ:
8679 if (tnum_is_const(reg->var_off))
8680 return !!tnum_equals_const(reg->var_off, val);
8681 break;
8682 case BPF_JNE:
8683 if (tnum_is_const(reg->var_off))
8684 return !tnum_equals_const(reg->var_off, val);
8685 break;
Jakub Kicinski960ea052018-12-19 22:13:04 -08008686 case BPF_JSET:
8687 if ((~reg->var_off.mask & reg->var_off.value) & val)
8688 return 1;
8689 if (!((reg->var_off.mask | reg->var_off.value) & val))
8690 return 0;
8691 break;
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008692 case BPF_JGT:
8693 if (reg->umin_value > val)
8694 return 1;
8695 else if (reg->umax_value <= val)
8696 return 0;
8697 break;
8698 case BPF_JSGT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008699 if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008700 return 1;
Daniel Borkmannee114dd2021-02-05 17:20:14 +01008701 else if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008702 return 0;
8703 break;
8704 case BPF_JLT:
8705 if (reg->umax_value < val)
8706 return 1;
8707 else if (reg->umin_value >= val)
8708 return 0;
8709 break;
8710 case BPF_JSLT:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008711 if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008712 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008713 else if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008714 return 0;
8715 break;
8716 case BPF_JGE:
8717 if (reg->umin_value >= val)
8718 return 1;
8719 else if (reg->umax_value < val)
8720 return 0;
8721 break;
8722 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008723 if (reg->smin_value >= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008724 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008725 else if (reg->smax_value < sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008726 return 0;
8727 break;
8728 case BPF_JLE:
8729 if (reg->umax_value <= val)
8730 return 1;
8731 else if (reg->umin_value > val)
8732 return 0;
8733 break;
8734 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008735 if (reg->smax_value <= sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008736 return 1;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008737 else if (reg->smin_value > sval)
Alexei Starovoitov4f7b3e82018-12-03 22:46:05 -08008738 return 0;
8739 break;
8740 }
8741
8742 return -1;
8743}
8744
John Fastabend3f50f132020-03-30 14:36:39 -07008745/* compute branch direction of the expression "if (reg opcode val) goto target;"
8746 * and return:
8747 * 1 - branch will be taken and "goto target" will be executed
8748 * 0 - branch will not be taken and fall-through to next insn
8749 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
8750 * range [0,10]
Jiong Wang092ed092019-01-26 12:26:01 -05008751 */
John Fastabend3f50f132020-03-30 14:36:39 -07008752static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
8753 bool is_jmp32)
Jiong Wang092ed092019-01-26 12:26:01 -05008754{
John Fastabendcac616d2020-05-21 13:07:26 -07008755 if (__is_pointer_value(false, reg)) {
8756 if (!reg_type_not_null(reg->type))
8757 return -1;
8758
8759 /* If pointer is valid tests against zero will fail so we can
8760 * use this to direct branch taken.
8761 */
8762 if (val != 0)
8763 return -1;
8764
8765 switch (opcode) {
8766 case BPF_JEQ:
8767 return 0;
8768 case BPF_JNE:
8769 return 1;
8770 default:
8771 return -1;
8772 }
8773 }
Jiong Wang092ed092019-01-26 12:26:01 -05008774
John Fastabend3f50f132020-03-30 14:36:39 -07008775 if (is_jmp32)
8776 return is_branch32_taken(reg, val, opcode);
8777 return is_branch64_taken(reg, val, opcode);
Jann Horn604dca52020-03-30 18:03:23 +02008778}
8779
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08008780static int flip_opcode(u32 opcode)
8781{
8782 /* How can we transform "a <op> b" into "b <op> a"? */
8783 static const u8 opcode_flip[16] = {
8784 /* these stay the same */
8785 [BPF_JEQ >> 4] = BPF_JEQ,
8786 [BPF_JNE >> 4] = BPF_JNE,
8787 [BPF_JSET >> 4] = BPF_JSET,
8788 /* these swap "lesser" and "greater" (L and G in the opcodes) */
8789 [BPF_JGE >> 4] = BPF_JLE,
8790 [BPF_JGT >> 4] = BPF_JLT,
8791 [BPF_JLE >> 4] = BPF_JGE,
8792 [BPF_JLT >> 4] = BPF_JGT,
8793 [BPF_JSGE >> 4] = BPF_JSLE,
8794 [BPF_JSGT >> 4] = BPF_JSLT,
8795 [BPF_JSLE >> 4] = BPF_JSGE,
8796 [BPF_JSLT >> 4] = BPF_JSGT
8797 };
8798 return opcode_flip[opcode >> 4];
8799}
8800
8801static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
8802 struct bpf_reg_state *src_reg,
8803 u8 opcode)
8804{
8805 struct bpf_reg_state *pkt;
8806
8807 if (src_reg->type == PTR_TO_PACKET_END) {
8808 pkt = dst_reg;
8809 } else if (dst_reg->type == PTR_TO_PACKET_END) {
8810 pkt = src_reg;
8811 opcode = flip_opcode(opcode);
8812 } else {
8813 return -1;
8814 }
8815
8816 if (pkt->range >= 0)
8817 return -1;
8818
8819 switch (opcode) {
8820 case BPF_JLE:
8821 /* pkt <= pkt_end */
8822 fallthrough;
8823 case BPF_JGT:
8824 /* pkt > pkt_end */
8825 if (pkt->range == BEYOND_PKT_END)
8826 /* pkt has at last one extra byte beyond pkt_end */
8827 return opcode == BPF_JGT;
8828 break;
8829 case BPF_JLT:
8830 /* pkt < pkt_end */
8831 fallthrough;
8832 case BPF_JGE:
8833 /* pkt >= pkt_end */
8834 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
8835 return opcode == BPF_JGE;
8836 break;
8837 }
8838 return -1;
8839}
8840
Josef Bacik48461132016-09-28 10:54:32 -04008841/* Adjusts the register min/max values in the case that the dst_reg is the
8842 * variable register that we are working on, and src_reg is a constant or we're
8843 * simply doing a BPF_K check.
Edward Creef1174f72017-08-07 15:26:19 +01008844 * In JEQ/JNE cases we also adjust the var_off values.
Josef Bacik48461132016-09-28 10:54:32 -04008845 */
8846static void reg_set_min_max(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07008847 struct bpf_reg_state *false_reg,
8848 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05008849 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04008850{
John Fastabend3f50f132020-03-30 14:36:39 -07008851 struct tnum false_32off = tnum_subreg(false_reg->var_off);
8852 struct tnum false_64off = false_reg->var_off;
8853 struct tnum true_32off = tnum_subreg(true_reg->var_off);
8854 struct tnum true_64off = true_reg->var_off;
8855 s64 sval = (s64)val;
8856 s32 sval32 = (s32)val32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008857
Edward Creef1174f72017-08-07 15:26:19 +01008858 /* If the dst_reg is a pointer, we can't learn anything about its
8859 * variable offset from the compare (unless src_reg were a pointer into
8860 * the same object, but we don't bother with that.
8861 * Since false_reg and true_reg have the same type by construction, we
8862 * only need to check one of them for pointerness.
8863 */
8864 if (__is_pointer_value(false, false_reg))
8865 return;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02008866
Josef Bacik48461132016-09-28 10:54:32 -04008867 switch (opcode) {
8868 case BPF_JEQ:
Josef Bacik48461132016-09-28 10:54:32 -04008869 case BPF_JNE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008870 {
8871 struct bpf_reg_state *reg =
8872 opcode == BPF_JEQ ? true_reg : false_reg;
8873
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008874 /* JEQ/JNE comparison doesn't change the register equivalence.
8875 * r1 = r2;
8876 * if (r1 == 42) goto label;
8877 * ...
8878 * label: // here both r1 and r2 are known to be 42.
8879 *
8880 * Hence when marking register as known preserve it's ID.
Josef Bacik48461132016-09-28 10:54:32 -04008881 */
John Fastabend3f50f132020-03-30 14:36:39 -07008882 if (is_jmp32)
8883 __mark_reg32_known(reg, val32);
8884 else
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07008885 ___mark_reg_known(reg, val);
Josef Bacik48461132016-09-28 10:54:32 -04008886 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008887 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008888 case BPF_JSET:
John Fastabend3f50f132020-03-30 14:36:39 -07008889 if (is_jmp32) {
8890 false_32off = tnum_and(false_32off, tnum_const(~val32));
8891 if (is_power_of_2(val32))
8892 true_32off = tnum_or(true_32off,
8893 tnum_const(val32));
8894 } else {
8895 false_64off = tnum_and(false_64off, tnum_const(~val));
8896 if (is_power_of_2(val))
8897 true_64off = tnum_or(true_64off,
8898 tnum_const(val));
8899 }
Jakub Kicinski960ea052018-12-19 22:13:04 -08008900 break;
Josef Bacik48461132016-09-28 10:54:32 -04008901 case BPF_JGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008902 case BPF_JGT:
8903 {
John Fastabend3f50f132020-03-30 14:36:39 -07008904 if (is_jmp32) {
8905 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1;
8906 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
8907
8908 false_reg->u32_max_value = min(false_reg->u32_max_value,
8909 false_umax);
8910 true_reg->u32_min_value = max(true_reg->u32_min_value,
8911 true_umin);
8912 } else {
8913 u64 false_umax = opcode == BPF_JGT ? val : val - 1;
8914 u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
8915
8916 false_reg->umax_value = min(false_reg->umax_value, false_umax);
8917 true_reg->umin_value = max(true_reg->umin_value, true_umin);
8918 }
Edward Creeb03c9f92017-08-07 15:26:36 +01008919 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008920 }
Josef Bacik48461132016-09-28 10:54:32 -04008921 case BPF_JSGE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008922 case BPF_JSGT:
8923 {
John Fastabend3f50f132020-03-30 14:36:39 -07008924 if (is_jmp32) {
8925 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1;
8926 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008927
John Fastabend3f50f132020-03-30 14:36:39 -07008928 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
8929 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
8930 } else {
8931 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1;
8932 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
8933
8934 false_reg->smax_value = min(false_reg->smax_value, false_smax);
8935 true_reg->smin_value = max(true_reg->smin_value, true_smin);
8936 }
Josef Bacik48461132016-09-28 10:54:32 -04008937 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008938 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008939 case BPF_JLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008940 case BPF_JLT:
8941 {
John Fastabend3f50f132020-03-30 14:36:39 -07008942 if (is_jmp32) {
8943 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1;
8944 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
8945
8946 false_reg->u32_min_value = max(false_reg->u32_min_value,
8947 false_umin);
8948 true_reg->u32_max_value = min(true_reg->u32_max_value,
8949 true_umax);
8950 } else {
8951 u64 false_umin = opcode == BPF_JLT ? val : val + 1;
8952 u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
8953
8954 false_reg->umin_value = max(false_reg->umin_value, false_umin);
8955 true_reg->umax_value = min(true_reg->umax_value, true_umax);
8956 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008957 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008958 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008959 case BPF_JSLE:
Jiong Wanga72dafa2019-01-26 12:26:00 -05008960 case BPF_JSLT:
8961 {
John Fastabend3f50f132020-03-30 14:36:39 -07008962 if (is_jmp32) {
8963 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1;
8964 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008965
John Fastabend3f50f132020-03-30 14:36:39 -07008966 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
8967 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
8968 } else {
8969 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1;
8970 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
8971
8972 false_reg->smin_value = max(false_reg->smin_value, false_smin);
8973 true_reg->smax_value = min(true_reg->smax_value, true_smax);
8974 }
Daniel Borkmannb4e432f2017-08-10 01:40:02 +02008975 break;
Jiong Wanga72dafa2019-01-26 12:26:00 -05008976 }
Josef Bacik48461132016-09-28 10:54:32 -04008977 default:
Jann Horn0fc31b12020-03-30 18:03:24 +02008978 return;
Josef Bacik48461132016-09-28 10:54:32 -04008979 }
8980
John Fastabend3f50f132020-03-30 14:36:39 -07008981 if (is_jmp32) {
8982 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
8983 tnum_subreg(false_32off));
8984 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
8985 tnum_subreg(true_32off));
8986 __reg_combine_32_into_64(false_reg);
8987 __reg_combine_32_into_64(true_reg);
8988 } else {
8989 false_reg->var_off = false_64off;
8990 true_reg->var_off = true_64off;
8991 __reg_combine_64_into_32(false_reg);
8992 __reg_combine_64_into_32(true_reg);
8993 }
Josef Bacik48461132016-09-28 10:54:32 -04008994}
8995
Edward Creef1174f72017-08-07 15:26:19 +01008996/* Same as above, but for the case that dst_reg holds a constant and src_reg is
8997 * the variable reg.
Josef Bacik48461132016-09-28 10:54:32 -04008998 */
8999static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07009000 struct bpf_reg_state *false_reg,
9001 u64 val, u32 val32,
Jiong Wang092ed092019-01-26 12:26:01 -05009002 u8 opcode, bool is_jmp32)
Josef Bacik48461132016-09-28 10:54:32 -04009003{
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009004 opcode = flip_opcode(opcode);
Jann Horn0fc31b12020-03-30 18:03:24 +02009005 /* This uses zero as "not present in table"; luckily the zero opcode,
9006 * BPF_JA, can't get here.
Edward Creeb03c9f92017-08-07 15:26:36 +01009007 */
Jann Horn0fc31b12020-03-30 18:03:24 +02009008 if (opcode)
John Fastabend3f50f132020-03-30 14:36:39 -07009009 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
Edward Creef1174f72017-08-07 15:26:19 +01009010}
9011
9012/* Regs are known to be equal, so intersect their min/max/var_off */
9013static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
9014 struct bpf_reg_state *dst_reg)
9015{
Edward Creeb03c9f92017-08-07 15:26:36 +01009016 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
9017 dst_reg->umin_value);
9018 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
9019 dst_reg->umax_value);
9020 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
9021 dst_reg->smin_value);
9022 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
9023 dst_reg->smax_value);
Edward Creef1174f72017-08-07 15:26:19 +01009024 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
9025 dst_reg->var_off);
Edward Creeb03c9f92017-08-07 15:26:36 +01009026 /* We might have learned new bounds from the var_off. */
9027 __update_reg_bounds(src_reg);
9028 __update_reg_bounds(dst_reg);
9029 /* We might have learned something about the sign bit. */
9030 __reg_deduce_bounds(src_reg);
9031 __reg_deduce_bounds(dst_reg);
9032 /* We might have learned some bits from the bounds. */
9033 __reg_bound_offset(src_reg);
9034 __reg_bound_offset(dst_reg);
9035 /* Intersecting with the old var_off might have improved our bounds
9036 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
9037 * then new var_off is (0; 0x7f...fc) which improves our umax.
9038 */
9039 __update_reg_bounds(src_reg);
9040 __update_reg_bounds(dst_reg);
Edward Creef1174f72017-08-07 15:26:19 +01009041}
9042
9043static void reg_combine_min_max(struct bpf_reg_state *true_src,
9044 struct bpf_reg_state *true_dst,
9045 struct bpf_reg_state *false_src,
9046 struct bpf_reg_state *false_dst,
9047 u8 opcode)
9048{
9049 switch (opcode) {
9050 case BPF_JEQ:
9051 __reg_combine_min_max(true_src, true_dst);
9052 break;
9053 case BPF_JNE:
9054 __reg_combine_min_max(false_src, false_dst);
Edward Creeb03c9f92017-08-07 15:26:36 +01009055 break;
Daniel Borkmann4cabc5b2017-07-21 00:00:21 +02009056 }
Josef Bacik48461132016-09-28 10:54:32 -04009057}
9058
Joe Stringerfd978bf72018-10-02 13:35:35 -07009059static void mark_ptr_or_null_reg(struct bpf_func_state *state,
9060 struct bpf_reg_state *reg, u32 id,
Joe Stringer840b9612018-10-02 13:35:32 -07009061 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02009062{
Martin KaFai Lau93c230e2020-10-19 12:42:12 -07009063 if (reg_type_may_be_null(reg->type) && reg->id == id &&
9064 !WARN_ON_ONCE(!reg->id)) {
Edward Creef1174f72017-08-07 15:26:19 +01009065 /* Old offset (both fixed and variable parts) should
9066 * have been known-zero, because we don't allow pointer
9067 * arithmetic on pointers that might be NULL.
9068 */
Edward Creeb03c9f92017-08-07 15:26:36 +01009069 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value ||
9070 !tnum_equals_const(reg->var_off, 0) ||
Edward Creef1174f72017-08-07 15:26:19 +01009071 reg->off)) {
Edward Creeb03c9f92017-08-07 15:26:36 +01009072 __mark_reg_known_zero(reg);
9073 reg->off = 0;
Edward Creef1174f72017-08-07 15:26:19 +01009074 }
9075 if (is_null) {
9076 reg->type = SCALAR_VALUE;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07009077 /* We don't need id and ref_obj_id from this point
9078 * onwards anymore, thus we should better reset it,
9079 * so that state pruning has chances to take effect.
9080 */
9081 reg->id = 0;
9082 reg->ref_obj_id = 0;
Dmitrii Banshchikov4ddb7412021-02-13 00:56:40 +04009083
9084 return;
9085 }
9086
9087 mark_ptr_not_null_reg(reg);
9088
9089 if (!reg_may_point_to_spin_lock(reg)) {
Martin KaFai Lau1b986582019-03-12 10:23:02 -07009090 /* For not-NULL ptr, reg->ref_obj_id will be reset
9091 * in release_reg_references().
9092 *
9093 * reg->id is still used by spin_lock ptr. Other
9094 * than spin_lock ptr type, reg->id can be reset.
Joe Stringerfd978bf72018-10-02 13:35:35 -07009095 */
9096 reg->id = 0;
9097 }
Thomas Graf57a09bf2016-10-18 19:51:19 +02009098 }
9099}
9100
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02009101static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id,
9102 bool is_null)
9103{
9104 struct bpf_reg_state *reg;
9105 int i;
9106
9107 for (i = 0; i < MAX_BPF_REG; i++)
9108 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null);
9109
9110 bpf_for_each_spilled_reg(i, state, reg) {
9111 if (!reg)
9112 continue;
9113 mark_ptr_or_null_reg(state, reg, id, is_null);
9114 }
9115}
9116
Thomas Graf57a09bf2016-10-18 19:51:19 +02009117/* The logic is similar to find_good_pkt_pointers(), both could eventually
9118 * be folded together at some point.
9119 */
Joe Stringer840b9612018-10-02 13:35:32 -07009120static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
9121 bool is_null)
Thomas Graf57a09bf2016-10-18 19:51:19 +02009122{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009123 struct bpf_func_state *state = vstate->frame[vstate->curframe];
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02009124 struct bpf_reg_state *regs = state->regs;
Martin KaFai Lau1b986582019-03-12 10:23:02 -07009125 u32 ref_obj_id = regs[regno].ref_obj_id;
Daniel Borkmanna08dd0d2016-12-15 01:30:06 +01009126 u32 id = regs[regno].id;
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02009127 int i;
Thomas Graf57a09bf2016-10-18 19:51:19 +02009128
Martin KaFai Lau1b986582019-03-12 10:23:02 -07009129 if (ref_obj_id && ref_obj_id == id && is_null)
9130 /* regs[regno] is in the " == NULL" branch.
9131 * No one could have freed the reference state before
9132 * doing the NULL check.
9133 */
9134 WARN_ON_ONCE(release_reference_state(state, id));
Joe Stringerfd978bf72018-10-02 13:35:35 -07009135
Paul Chaignonc6a9efa2019-04-24 21:50:42 +02009136 for (i = 0; i <= vstate->curframe; i++)
9137 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null);
Thomas Graf57a09bf2016-10-18 19:51:19 +02009138}
9139
Daniel Borkmann5beca082017-11-01 23:58:10 +01009140static bool try_match_pkt_pointers(const struct bpf_insn *insn,
9141 struct bpf_reg_state *dst_reg,
9142 struct bpf_reg_state *src_reg,
9143 struct bpf_verifier_state *this_branch,
9144 struct bpf_verifier_state *other_branch)
9145{
9146 if (BPF_SRC(insn->code) != BPF_X)
9147 return false;
9148
Jiong Wang092ed092019-01-26 12:26:01 -05009149 /* Pointers are always 64-bit. */
9150 if (BPF_CLASS(insn->code) == BPF_JMP32)
9151 return false;
9152
Daniel Borkmann5beca082017-11-01 23:58:10 +01009153 switch (BPF_OP(insn->code)) {
9154 case BPF_JGT:
9155 if ((dst_reg->type == PTR_TO_PACKET &&
9156 src_reg->type == PTR_TO_PACKET_END) ||
9157 (dst_reg->type == PTR_TO_PACKET_META &&
9158 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9159 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
9160 find_good_pkt_pointers(this_branch, dst_reg,
9161 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009162 mark_pkt_end(other_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009163 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9164 src_reg->type == PTR_TO_PACKET) ||
9165 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9166 src_reg->type == PTR_TO_PACKET_META)) {
9167 /* pkt_end > pkt_data', pkt_data > pkt_meta' */
9168 find_good_pkt_pointers(other_branch, src_reg,
9169 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009170 mark_pkt_end(this_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009171 } else {
9172 return false;
9173 }
9174 break;
9175 case BPF_JLT:
9176 if ((dst_reg->type == PTR_TO_PACKET &&
9177 src_reg->type == PTR_TO_PACKET_END) ||
9178 (dst_reg->type == PTR_TO_PACKET_META &&
9179 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9180 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
9181 find_good_pkt_pointers(other_branch, dst_reg,
9182 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009183 mark_pkt_end(this_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009184 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9185 src_reg->type == PTR_TO_PACKET) ||
9186 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9187 src_reg->type == PTR_TO_PACKET_META)) {
9188 /* pkt_end < pkt_data', pkt_data > pkt_meta' */
9189 find_good_pkt_pointers(this_branch, src_reg,
9190 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009191 mark_pkt_end(other_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009192 } else {
9193 return false;
9194 }
9195 break;
9196 case BPF_JGE:
9197 if ((dst_reg->type == PTR_TO_PACKET &&
9198 src_reg->type == PTR_TO_PACKET_END) ||
9199 (dst_reg->type == PTR_TO_PACKET_META &&
9200 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9201 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
9202 find_good_pkt_pointers(this_branch, dst_reg,
9203 dst_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009204 mark_pkt_end(other_branch, insn->dst_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009205 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9206 src_reg->type == PTR_TO_PACKET) ||
9207 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9208 src_reg->type == PTR_TO_PACKET_META)) {
9209 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
9210 find_good_pkt_pointers(other_branch, src_reg,
9211 src_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009212 mark_pkt_end(this_branch, insn->src_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009213 } else {
9214 return false;
9215 }
9216 break;
9217 case BPF_JLE:
9218 if ((dst_reg->type == PTR_TO_PACKET &&
9219 src_reg->type == PTR_TO_PACKET_END) ||
9220 (dst_reg->type == PTR_TO_PACKET_META &&
9221 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
9222 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
9223 find_good_pkt_pointers(other_branch, dst_reg,
9224 dst_reg->type, false);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009225 mark_pkt_end(this_branch, insn->dst_reg, true);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009226 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
9227 src_reg->type == PTR_TO_PACKET) ||
9228 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
9229 src_reg->type == PTR_TO_PACKET_META)) {
9230 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
9231 find_good_pkt_pointers(this_branch, src_reg,
9232 src_reg->type, true);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009233 mark_pkt_end(other_branch, insn->src_reg, false);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009234 } else {
9235 return false;
9236 }
9237 break;
9238 default:
9239 return false;
9240 }
9241
9242 return true;
9243}
9244
Alexei Starovoitov75748832020-10-08 18:12:37 -07009245static void find_equal_scalars(struct bpf_verifier_state *vstate,
9246 struct bpf_reg_state *known_reg)
9247{
9248 struct bpf_func_state *state;
9249 struct bpf_reg_state *reg;
9250 int i, j;
9251
9252 for (i = 0; i <= vstate->curframe; i++) {
9253 state = vstate->frame[i];
9254 for (j = 0; j < MAX_BPF_REG; j++) {
9255 reg = &state->regs[j];
9256 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9257 *reg = *known_reg;
9258 }
9259
9260 bpf_for_each_spilled_reg(j, state, reg) {
9261 if (!reg)
9262 continue;
9263 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
9264 *reg = *known_reg;
9265 }
9266 }
9267}
9268
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009269static int check_cond_jmp_op(struct bpf_verifier_env *env,
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009270 struct bpf_insn *insn, int *insn_idx)
9271{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009272 struct bpf_verifier_state *this_branch = env->cur_state;
9273 struct bpf_verifier_state *other_branch;
9274 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009275 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009276 u8 opcode = BPF_OP(insn->code);
Jiong Wang092ed092019-01-26 12:26:01 -05009277 bool is_jmp32;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009278 int pred = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009279 int err;
9280
Jiong Wang092ed092019-01-26 12:26:01 -05009281 /* Only conditional jumps are expected to reach here. */
9282 if (opcode == BPF_JA || opcode > BPF_JSLE) {
9283 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009284 return -EINVAL;
9285 }
9286
9287 if (BPF_SRC(insn->code) == BPF_X) {
9288 if (insn->imm != 0) {
Jiong Wang092ed092019-01-26 12:26:01 -05009289 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009290 return -EINVAL;
9291 }
9292
9293 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009294 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009295 if (err)
9296 return err;
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009297
9298 if (is_pointer_value(env, insn->src_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009299 verbose(env, "R%d pointer comparison prohibited\n",
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009300 insn->src_reg);
9301 return -EACCES;
9302 }
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009303 src_reg = &regs[insn->src_reg];
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009304 } else {
9305 if (insn->src_reg != BPF_REG_0) {
Jiong Wang092ed092019-01-26 12:26:01 -05009306 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009307 return -EINVAL;
9308 }
9309 }
9310
9311 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +01009312 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009313 if (err)
9314 return err;
9315
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009316 dst_reg = &regs[insn->dst_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05009317 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009318
John Fastabend3f50f132020-03-30 14:36:39 -07009319 if (BPF_SRC(insn->code) == BPF_K) {
9320 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
9321 } else if (src_reg->type == SCALAR_VALUE &&
9322 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
9323 pred = is_branch_taken(dst_reg,
9324 tnum_subreg(src_reg->var_off).value,
9325 opcode,
9326 is_jmp32);
9327 } else if (src_reg->type == SCALAR_VALUE &&
9328 !is_jmp32 && tnum_is_const(src_reg->var_off)) {
9329 pred = is_branch_taken(dst_reg,
9330 src_reg->var_off.value,
9331 opcode,
9332 is_jmp32);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009333 } else if (reg_is_pkt_pointer_any(dst_reg) &&
9334 reg_is_pkt_pointer_any(src_reg) &&
9335 !is_jmp32) {
9336 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
John Fastabend3f50f132020-03-30 14:36:39 -07009337 }
9338
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009339 if (pred >= 0) {
John Fastabendcac616d2020-05-21 13:07:26 -07009340 /* If we get here with a dst_reg pointer type it is because
9341 * above is_branch_taken() special cased the 0 comparison.
9342 */
9343 if (!__is_pointer_value(false, dst_reg))
9344 err = mark_chain_precision(env, insn->dst_reg);
Alexei Starovoitov6d94e742020-11-10 19:12:11 -08009345 if (BPF_SRC(insn->code) == BPF_X && !err &&
9346 !__is_pointer_value(false, src_reg))
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -07009347 err = mark_chain_precision(env, insn->src_reg);
9348 if (err)
9349 return err;
9350 }
Daniel Borkmann9183671a2021-05-28 15:47:32 +00009351
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009352 if (pred == 1) {
Daniel Borkmann9183671a2021-05-28 15:47:32 +00009353 /* Only follow the goto, ignore fall-through. If needed, push
9354 * the fall-through branch for simulation under speculative
9355 * execution.
9356 */
9357 if (!env->bypass_spec_v1 &&
9358 !sanitize_speculative_path(env, insn, *insn_idx + 1,
9359 *insn_idx))
9360 return -EFAULT;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009361 *insn_idx += insn->off;
9362 return 0;
9363 } else if (pred == 0) {
Daniel Borkmann9183671a2021-05-28 15:47:32 +00009364 /* Only follow the fall-through branch, since that's where the
9365 * program will go. If needed, push the goto branch for
9366 * simulation under speculative execution.
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009367 */
Daniel Borkmann9183671a2021-05-28 15:47:32 +00009368 if (!env->bypass_spec_v1 &&
9369 !sanitize_speculative_path(env, insn,
9370 *insn_idx + insn->off + 1,
9371 *insn_idx))
9372 return -EFAULT;
Alexei Starovoitovfb8d2512019-06-15 12:12:19 -07009373 return 0;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009374 }
9375
Daniel Borkmann979d63d2019-01-03 00:58:34 +01009376 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
9377 false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009378 if (!other_branch)
9379 return -EFAULT;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009380 other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009381
Josef Bacik48461132016-09-28 10:54:32 -04009382 /* detect if we are comparing against a constant value so we can adjust
9383 * our min/max values for our dst register.
Edward Creef1174f72017-08-07 15:26:19 +01009384 * this is only legit if both are scalars (or pointers to the same
9385 * object, I suppose, but we don't support that right now), because
9386 * otherwise the different base pointers mean the offsets aren't
9387 * comparable.
Josef Bacik48461132016-09-28 10:54:32 -04009388 */
9389 if (BPF_SRC(insn->code) == BPF_X) {
Jiong Wang092ed092019-01-26 12:26:01 -05009390 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
Jiong Wang092ed092019-01-26 12:26:01 -05009391
Edward Creef1174f72017-08-07 15:26:19 +01009392 if (dst_reg->type == SCALAR_VALUE &&
Jiong Wang092ed092019-01-26 12:26:01 -05009393 src_reg->type == SCALAR_VALUE) {
9394 if (tnum_is_const(src_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07009395 (is_jmp32 &&
9396 tnum_is_const(tnum_subreg(src_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009397 reg_set_min_max(&other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05009398 dst_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07009399 src_reg->var_off.value,
9400 tnum_subreg(src_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05009401 opcode, is_jmp32);
9402 else if (tnum_is_const(dst_reg->var_off) ||
John Fastabend3f50f132020-03-30 14:36:39 -07009403 (is_jmp32 &&
9404 tnum_is_const(tnum_subreg(dst_reg->var_off))))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009405 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05009406 src_reg,
John Fastabend3f50f132020-03-30 14:36:39 -07009407 dst_reg->var_off.value,
9408 tnum_subreg(dst_reg->var_off).value,
Jiong Wang092ed092019-01-26 12:26:01 -05009409 opcode, is_jmp32);
9410 else if (!is_jmp32 &&
9411 (opcode == BPF_JEQ || opcode == BPF_JNE))
Edward Creef1174f72017-08-07 15:26:19 +01009412 /* Comparing for equality, we can combine knowledge */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009413 reg_combine_min_max(&other_branch_regs[insn->src_reg],
9414 &other_branch_regs[insn->dst_reg],
Jiong Wang092ed092019-01-26 12:26:01 -05009415 src_reg, dst_reg, opcode);
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07009416 if (src_reg->id &&
9417 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07009418 find_equal_scalars(this_branch, src_reg);
9419 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
9420 }
9421
Edward Creef1174f72017-08-07 15:26:19 +01009422 }
9423 } else if (dst_reg->type == SCALAR_VALUE) {
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -08009424 reg_set_min_max(&other_branch_regs[insn->dst_reg],
John Fastabend3f50f132020-03-30 14:36:39 -07009425 dst_reg, insn->imm, (u32)insn->imm,
9426 opcode, is_jmp32);
Josef Bacik48461132016-09-28 10:54:32 -04009427 }
9428
Alexei Starovoitove688c3d2020-10-14 10:56:08 -07009429 if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
9430 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
Alexei Starovoitov75748832020-10-08 18:12:37 -07009431 find_equal_scalars(this_branch, dst_reg);
9432 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
9433 }
9434
Jiong Wang092ed092019-01-26 12:26:01 -05009435 /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
9436 * NOTE: these optimizations below are related with pointer comparison
9437 * which will never be JMP32.
9438 */
9439 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -07009440 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
Joe Stringer840b9612018-10-02 13:35:32 -07009441 reg_type_may_be_null(dst_reg->type)) {
9442 /* Mark all identical registers in each branch as either
Thomas Graf57a09bf2016-10-18 19:51:19 +02009443 * safe or unknown depending R == 0 or R != 0 conditional.
9444 */
Joe Stringer840b9612018-10-02 13:35:32 -07009445 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
9446 opcode == BPF_JNE);
9447 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
9448 opcode == BPF_JEQ);
Daniel Borkmann5beca082017-11-01 23:58:10 +01009449 } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
9450 this_branch, other_branch) &&
9451 is_pointer_value(env, insn->dst_reg)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009452 verbose(env, "R%d pointer comparison prohibited\n",
9453 insn->dst_reg);
Alexei Starovoitov1be7f752015-10-07 22:23:21 -07009454 return -EACCES;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009455 }
Alexei Starovoitov06ee7112019-04-01 21:27:40 -07009456 if (env->log.level & BPF_LOG_LEVEL)
Christy Lee2e576642021-12-16 19:42:45 -08009457 print_insn_state(env, this_branch->frame[this_branch->curframe]);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009458 return 0;
9459}
9460
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009461/* verify BPF_LD_IMM64 instruction */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009462static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009463{
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009464 struct bpf_insn_aux_data *aux = cur_aux(env);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009465 struct bpf_reg_state *regs = cur_regs(env);
Hao Luo4976b712020-09-29 16:50:44 -07009466 struct bpf_reg_state *dst_reg;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009467 struct bpf_map *map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009468 int err;
9469
9470 if (BPF_SIZE(insn->code) != BPF_DW) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009471 verbose(env, "invalid BPF_LD_IMM insn\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009472 return -EINVAL;
9473 }
9474 if (insn->off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009475 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009476 return -EINVAL;
9477 }
9478
Edward Creedc503a82017-08-15 20:34:35 +01009479 err = check_reg_arg(env, insn->dst_reg, DST_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009480 if (err)
9481 return err;
9482
Hao Luo4976b712020-09-29 16:50:44 -07009483 dst_reg = &regs[insn->dst_reg];
Jakub Kicinski6b173872016-09-21 11:43:59 +01009484 if (insn->src_reg == 0) {
Jakub Kicinski6b173872016-09-21 11:43:59 +01009485 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
9486
Hao Luo4976b712020-09-29 16:50:44 -07009487 dst_reg->type = SCALAR_VALUE;
Edward Creeb03c9f92017-08-07 15:26:36 +01009488 __mark_reg_known(&regs[insn->dst_reg], imm);
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009489 return 0;
Jakub Kicinski6b173872016-09-21 11:43:59 +01009490 }
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009491
Hao Luo4976b712020-09-29 16:50:44 -07009492 if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
9493 mark_reg_known_zero(env, regs, insn->dst_reg);
9494
9495 dst_reg->type = aux->btf_var.reg_type;
9496 switch (dst_reg->type) {
9497 case PTR_TO_MEM:
9498 dst_reg->mem_size = aux->btf_var.mem_size;
9499 break;
9500 case PTR_TO_BTF_ID:
Hao Luoeaa6bcb2020-09-29 16:50:47 -07009501 case PTR_TO_PERCPU_BTF_ID:
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -08009502 dst_reg->btf = aux->btf_var.btf;
Hao Luo4976b712020-09-29 16:50:44 -07009503 dst_reg->btf_id = aux->btf_var.btf_id;
9504 break;
9505 default:
9506 verbose(env, "bpf verifier is misconfigured\n");
9507 return -EFAULT;
9508 }
9509 return 0;
9510 }
9511
Yonghong Song69c087b2021-02-26 12:49:25 -08009512 if (insn->src_reg == BPF_PSEUDO_FUNC) {
9513 struct bpf_prog_aux *aux = env->prog->aux;
Martin KaFai Lau3990ed42021-11-05 18:40:14 -07009514 u32 subprogno = find_subprog(env,
9515 env->insn_idx + insn->imm + 1);
Yonghong Song69c087b2021-02-26 12:49:25 -08009516
9517 if (!aux->func_info) {
9518 verbose(env, "missing btf func_info\n");
9519 return -EINVAL;
9520 }
9521 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
9522 verbose(env, "callback function not static\n");
9523 return -EINVAL;
9524 }
9525
9526 dst_reg->type = PTR_TO_FUNC;
9527 dst_reg->subprogno = subprogno;
9528 return 0;
9529 }
9530
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009531 map = env->used_maps[aux->map_index];
9532 mark_reg_known_zero(env, regs, insn->dst_reg);
Hao Luo4976b712020-09-29 16:50:44 -07009533 dst_reg->map_ptr = map;
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009534
Alexei Starovoitov387544b2021-05-13 17:36:10 -07009535 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
9536 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
Hao Luo4976b712020-09-29 16:50:44 -07009537 dst_reg->type = PTR_TO_MAP_VALUE;
9538 dst_reg->off = aux->map_off;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009539 if (map_value_has_spin_lock(map))
Hao Luo4976b712020-09-29 16:50:44 -07009540 dst_reg->id = ++env->id_gen;
Alexei Starovoitov387544b2021-05-13 17:36:10 -07009541 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
9542 insn->src_reg == BPF_PSEUDO_MAP_IDX) {
Hao Luo4976b712020-09-29 16:50:44 -07009543 dst_reg->type = CONST_PTR_TO_MAP;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +02009544 } else {
9545 verbose(env, "bpf verifier is misconfigured\n");
9546 return -EINVAL;
9547 }
9548
Alexei Starovoitov17a52672014-09-26 00:17:06 -07009549 return 0;
9550}
9551
Daniel Borkmann96be4322015-03-01 12:31:46 +01009552static bool may_access_skb(enum bpf_prog_type type)
9553{
9554 switch (type) {
9555 case BPF_PROG_TYPE_SOCKET_FILTER:
9556 case BPF_PROG_TYPE_SCHED_CLS:
Daniel Borkmann94caee8c2015-03-20 15:11:11 +01009557 case BPF_PROG_TYPE_SCHED_ACT:
Daniel Borkmann96be4322015-03-01 12:31:46 +01009558 return true;
9559 default:
9560 return false;
9561 }
9562}
9563
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009564/* verify safety of LD_ABS|LD_IND instructions:
9565 * - they can only appear in the programs where ctx == skb
9566 * - since they are wrappers of function calls, they scratch R1-R5 registers,
9567 * preserve R6-R9, and store return value into R0
9568 *
9569 * Implicit input:
9570 * ctx == skb == R6 == CTX
9571 *
9572 * Explicit input:
9573 * SRC == any register
9574 * IMM == 32-bit immediate
9575 *
9576 * Output:
9577 * R0 - 8/16/32-bit skb data converted to cpu endianness
9578 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +01009579static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009580{
Alexei Starovoitov638f5b92017-10-31 18:16:05 -07009581 struct bpf_reg_state *regs = cur_regs(env);
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009582 static const int ctx_reg = BPF_REG_6;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009583 u8 mode = BPF_MODE(insn->code);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009584 int i, err;
9585
Udip Pant7e407812020-08-25 16:20:00 -07009586 if (!may_access_skb(resolve_prog_type(env->prog))) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009587 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009588 return -EINVAL;
9589 }
9590
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +02009591 if (!env->ops->gen_ld_abs) {
9592 verbose(env, "bpf verifier is misconfigured\n");
9593 return -EINVAL;
9594 }
9595
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009596 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
Alexei Starovoitovd82bccc2016-04-12 10:26:19 -07009597 BPF_SIZE(insn->code) == BPF_DW ||
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009598 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009599 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009600 return -EINVAL;
9601 }
9602
9603 /* check whether implicit source operand (register R6) is readable */
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009604 err = check_reg_arg(env, ctx_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009605 if (err)
9606 return err;
9607
Joe Stringerfd978bf72018-10-02 13:35:35 -07009608 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
9609 * gen_ld_abs() may terminate the program at runtime, leading to
9610 * reference leak.
9611 */
9612 err = check_reference_leak(env);
9613 if (err) {
9614 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
9615 return err;
9616 }
9617
Alexei Starovoitovd83525c2019-01-31 15:40:04 -08009618 if (env->cur_state->active_spin_lock) {
9619 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
9620 return -EINVAL;
9621 }
9622
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009623 if (regs[ctx_reg].type != PTR_TO_CTX) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009624 verbose(env,
9625 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009626 return -EINVAL;
9627 }
9628
9629 if (mode == BPF_IND) {
9630 /* check explicit source operand */
Edward Creedc503a82017-08-15 20:34:35 +01009631 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009632 if (err)
9633 return err;
9634 }
9635
Daniel Borkmann6d4f1512020-01-06 22:51:57 +01009636 err = check_ctx_reg(env, &regs[ctx_reg], ctx_reg);
9637 if (err < 0)
9638 return err;
9639
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009640 /* reset caller saved regs to unreadable */
Edward Creedc503a82017-08-15 20:34:35 +01009641 for (i = 0; i < CALLER_SAVED_REGS; i++) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009642 mark_reg_not_init(env, regs, caller_saved[i]);
Edward Creedc503a82017-08-15 20:34:35 +01009643 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9644 }
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009645
9646 /* mark destination R0 register as readable, since it contains
Edward Creedc503a82017-08-15 20:34:35 +01009647 * the value fetched from the packet.
9648 * Already marked as written above.
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009649 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009650 mark_reg_unknown(env, regs, BPF_REG_0);
Jiong Wang5327ed32019-05-24 23:25:12 +01009651 /* ld_abs load up to 32-bit skb data. */
9652 regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
Alexei Starovoitovddd872b2014-12-01 15:06:34 -08009653 return 0;
9654}
9655
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009656static int check_return_code(struct bpf_verifier_env *env)
9657{
brakmo5cf1e912019-05-28 16:59:36 -07009658 struct tnum enforce_attach_type_range = tnum_unknown;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009659 const struct bpf_prog *prog = env->prog;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009660 struct bpf_reg_state *reg;
9661 struct tnum range = tnum_range(0, 1);
Udip Pant7e407812020-08-25 16:20:00 -07009662 enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009663 int err;
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07009664 struct bpf_func_state *frame = env->cur_state->frame[0];
9665 const bool is_subprog = frame->subprogno;
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009666
KP Singh9e4e01d2020-03-29 01:43:52 +01009667 /* LSM and struct_ops func-ptr's return type could be "void" */
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009668 if (!is_subprog &&
9669 (prog_type == BPF_PROG_TYPE_STRUCT_OPS ||
Udip Pant7e407812020-08-25 16:20:00 -07009670 prog_type == BPF_PROG_TYPE_LSM) &&
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009671 !prog->aux->attach_func_proto->type)
9672 return 0;
9673
Zhen Lei8fb33b62021-05-25 10:56:59 +08009674 /* eBPF calling convention is such that R0 is used
Martin KaFai Lau27ae79972020-01-08 16:35:03 -08009675 * to return the value from eBPF program.
9676 * Make sure that it's readable at this time
9677 * of bpf_exit, which means that program wrote
9678 * something into it earlier
9679 */
9680 err = check_reg_arg(env, BPF_REG_0, SRC_OP);
9681 if (err)
9682 return err;
9683
9684 if (is_pointer_value(env, BPF_REG_0)) {
9685 verbose(env, "R0 leaks addr as return value\n");
9686 return -EACCES;
9687 }
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009688
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009689 reg = cur_regs(env) + BPF_REG_0;
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07009690
9691 if (frame->in_async_callback_fn) {
9692 /* enforce return zero from async callbacks like timer */
9693 if (reg->type != SCALAR_VALUE) {
9694 verbose(env, "In async callback the register R0 is not a known value (%s)\n",
9695 reg_type_str[reg->type]);
9696 return -EINVAL;
9697 }
9698
9699 if (!tnum_in(tnum_const(0), reg->var_off)) {
9700 verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
9701 return -EINVAL;
9702 }
9703 return 0;
9704 }
9705
Dmitrii Banshchikovf782e2c2020-11-13 17:17:56 +00009706 if (is_subprog) {
9707 if (reg->type != SCALAR_VALUE) {
9708 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
9709 reg_type_str[reg->type]);
9710 return -EINVAL;
9711 }
9712 return 0;
9713 }
9714
Udip Pant7e407812020-08-25 16:20:00 -07009715 switch (prog_type) {
Daniel Borkmann983695f2019-06-07 01:48:57 +02009716 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9717 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
Daniel Borkmann1b66d252020-05-19 00:45:45 +02009718 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
9719 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
9720 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
9721 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
9722 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
Daniel Borkmann983695f2019-06-07 01:48:57 +02009723 range = tnum_range(1, 1);
Stanislav Fomichev77241212021-01-27 11:31:39 -08009724 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
9725 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
9726 range = tnum_range(0, 3);
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009727 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009728 case BPF_PROG_TYPE_CGROUP_SKB:
brakmo5cf1e912019-05-28 16:59:36 -07009729 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
9730 range = tnum_range(0, 3);
9731 enforce_attach_type_range = tnum_range(2, 3);
9732 }
Gustavo A. R. Silvaed4ed402019-07-11 11:22:33 -05009733 break;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009734 case BPF_PROG_TYPE_CGROUP_SOCK:
9735 case BPF_PROG_TYPE_SOCK_OPS:
Roman Gushchinebc614f2017-11-05 08:15:32 -05009736 case BPF_PROG_TYPE_CGROUP_DEVICE:
Andrey Ignatov7b146ce2019-02-27 12:59:24 -08009737 case BPF_PROG_TYPE_CGROUP_SYSCTL:
Stanislav Fomichev0d01da62019-06-27 13:38:47 -07009738 case BPF_PROG_TYPE_CGROUP_SOCKOPT:
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009739 break;
Alexei Starovoitov15ab09b2019-10-28 20:24:26 -07009740 case BPF_PROG_TYPE_RAW_TRACEPOINT:
9741 if (!env->prog->aux->attach_btf_id)
9742 return 0;
9743 range = tnum_const(0);
9744 break;
Yonghong Song15d83c42020-05-09 10:59:00 -07009745 case BPF_PROG_TYPE_TRACING:
Yonghong Songe92888c72020-05-13 22:32:05 -07009746 switch (env->prog->expected_attach_type) {
9747 case BPF_TRACE_FENTRY:
9748 case BPF_TRACE_FEXIT:
9749 range = tnum_const(0);
9750 break;
9751 case BPF_TRACE_RAW_TP:
9752 case BPF_MODIFY_RETURN:
Yonghong Song15d83c42020-05-09 10:59:00 -07009753 return 0;
Daniel Borkmann2ec06162020-05-16 00:39:18 +02009754 case BPF_TRACE_ITER:
9755 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009756 default:
9757 return -ENOTSUPP;
9758 }
Yonghong Song15d83c42020-05-09 10:59:00 -07009759 break;
Jakub Sitnickie9ddbb72020-07-17 12:35:23 +02009760 case BPF_PROG_TYPE_SK_LOOKUP:
9761 range = tnum_range(SK_DROP, SK_PASS);
9762 break;
Yonghong Songe92888c72020-05-13 22:32:05 -07009763 case BPF_PROG_TYPE_EXT:
9764 /* freplace program can return anything as its return value
9765 * depends on the to-be-replaced kernel func or bpf program.
9766 */
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009767 default:
9768 return 0;
9769 }
9770
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009771 if (reg->type != SCALAR_VALUE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009772 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009773 reg_type_str[reg->type]);
9774 return -EINVAL;
9775 }
9776
9777 if (!tnum_in(range, reg->var_off)) {
Yonghong Songbc2591d2021-02-26 12:49:22 -08009778 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009779 return -EINVAL;
9780 }
brakmo5cf1e912019-05-28 16:59:36 -07009781
9782 if (!tnum_is_unknown(enforce_attach_type_range) &&
9783 tnum_in(enforce_attach_type_range, reg->var_off))
9784 env->prog->enforce_expected_attach_type = 1;
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -07009785 return 0;
9786}
9787
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009788/* non-recursive DFS pseudo code
9789 * 1 procedure DFS-iterative(G,v):
9790 * 2 label v as discovered
9791 * 3 let S be a stack
9792 * 4 S.push(v)
9793 * 5 while S is not empty
9794 * 6 t <- S.pop()
9795 * 7 if t is what we're looking for:
9796 * 8 return t
9797 * 9 for all edges e in G.adjacentEdges(t) do
9798 * 10 if edge e is already labelled
9799 * 11 continue with the next edge
9800 * 12 w <- G.adjacentVertex(t,e)
9801 * 13 if vertex w is not discovered and not explored
9802 * 14 label e as tree-edge
9803 * 15 label w as discovered
9804 * 16 S.push(w)
9805 * 17 continue at 5
9806 * 18 else if vertex w is discovered
9807 * 19 label e as back-edge
9808 * 20 else
9809 * 21 // vertex w is explored
9810 * 22 label e as forward- or cross-edge
9811 * 23 label t as explored
9812 * 24 S.pop()
9813 *
9814 * convention:
9815 * 0x10 - discovered
9816 * 0x11 - discovered and fall-through edge labelled
9817 * 0x12 - discovered and fall-through and branch edges labelled
9818 * 0x20 - explored
9819 */
9820
9821enum {
9822 DISCOVERED = 0x10,
9823 EXPLORED = 0x20,
9824 FALLTHROUGH = 1,
9825 BRANCH = 2,
9826};
9827
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009828static u32 state_htab_size(struct bpf_verifier_env *env)
9829{
9830 return env->prog->len;
9831}
9832
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009833static struct bpf_verifier_state_list **explored_state(
9834 struct bpf_verifier_env *env,
9835 int idx)
9836{
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -07009837 struct bpf_verifier_state *cur = env->cur_state;
9838 struct bpf_func_state *state = cur->frame[cur->curframe];
9839
9840 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009841}
9842
9843static void init_explored_state(struct bpf_verifier_env *env, int idx)
9844{
Alexei Starovoitova8f500a2019-05-21 20:17:06 -07009845 env->insn_aux_data[idx].prune_point = true;
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009846}
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009847
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009848enum {
9849 DONE_EXPLORING = 0,
9850 KEEP_EXPLORING = 1,
9851};
9852
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009853/* t, w, e - match pseudo-code above:
9854 * t - index of current instruction
9855 * w - next instruction
9856 * e - edge
9857 */
Alexei Starovoitov25897262019-06-15 12:12:20 -07009858static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
9859 bool loop_ok)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009860{
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009861 int *insn_stack = env->cfg.insn_stack;
9862 int *insn_state = env->cfg.insn_state;
9863
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009864 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009865 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009866
9867 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009868 return DONE_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009869
9870 if (w < 0 || w >= env->prog->len) {
Martin KaFai Laud9762e82018-12-13 10:41:48 -08009871 verbose_linfo(env, t, "%d: ", t);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009872 verbose(env, "jump out of range from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009873 return -EINVAL;
9874 }
9875
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009876 if (e == BRANCH)
9877 /* mark branch target for state pruning */
Alexei Starovoitov5d839022019-05-21 20:17:05 -07009878 init_explored_state(env, w);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -07009879
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009880 if (insn_state[w] == 0) {
9881 /* tree-edge */
9882 insn_state[t] = DISCOVERED | e;
9883 insn_state[w] = DISCOVERED;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009884 if (env->cfg.cur_stack >= env->prog->len)
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009885 return -E2BIG;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -07009886 insn_stack[env->cfg.cur_stack++] = w;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009887 return KEEP_EXPLORING;
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009888 } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -07009889 if (loop_ok && env->bpf_capable)
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009890 return DONE_EXPLORING;
Martin KaFai Laud9762e82018-12-13 10:41:48 -08009891 verbose_linfo(env, t, "%d: ", t);
9892 verbose_linfo(env, w, "%d: ", w);
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009893 verbose(env, "back-edge from insn %d to %d\n", t, w);
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009894 return -EINVAL;
9895 } else if (insn_state[w] == EXPLORED) {
9896 /* forward- or cross-edge */
9897 insn_state[t] = DISCOVERED | e;
9898 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -07009899 verbose(env, "insn state internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009900 return -EFAULT;
9901 }
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009902 return DONE_EXPLORING;
9903}
9904
Yonghong Songefdb22d2021-02-26 12:49:20 -08009905static int visit_func_call_insn(int t, int insn_cnt,
9906 struct bpf_insn *insns,
9907 struct bpf_verifier_env *env,
9908 bool visit_callee)
9909{
9910 int ret;
9911
9912 ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
9913 if (ret)
9914 return ret;
9915
9916 if (t + 1 < insn_cnt)
9917 init_explored_state(env, t + 1);
9918 if (visit_callee) {
9919 init_explored_state(env, t);
Alexei Starovoitov86fc6ee2021-07-14 17:54:13 -07009920 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
9921 /* It's ok to allow recursion from CFG point of
9922 * view. __check_func_call() will do the actual
9923 * check.
9924 */
9925 bpf_pseudo_func(insns + t));
Yonghong Songefdb22d2021-02-26 12:49:20 -08009926 }
9927 return ret;
9928}
9929
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009930/* Visits the instruction at index t and returns one of the following:
9931 * < 0 - an error occurred
9932 * DONE_EXPLORING - the instruction was fully explored
9933 * KEEP_EXPLORING - there is still work to be done before it is fully explored
9934 */
9935static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env)
9936{
9937 struct bpf_insn *insns = env->prog->insnsi;
9938 int ret;
9939
Yonghong Song69c087b2021-02-26 12:49:25 -08009940 if (bpf_pseudo_func(insns + t))
9941 return visit_func_call_insn(t, insn_cnt, insns, env, true);
9942
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009943 /* All non-branch instructions have a single fall-through edge. */
9944 if (BPF_CLASS(insns[t].code) != BPF_JMP &&
9945 BPF_CLASS(insns[t].code) != BPF_JMP32)
9946 return push_insn(t, t + 1, FALLTHROUGH, env, false);
9947
9948 switch (BPF_OP(insns[t].code)) {
9949 case BPF_EXIT:
9950 return DONE_EXPLORING;
9951
9952 case BPF_CALL:
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -07009953 if (insns[t].imm == BPF_FUNC_timer_set_callback)
9954 /* Mark this call insn to trigger is_state_visited() check
9955 * before call itself is processed by __check_func_call().
9956 * Otherwise new async state will be pushed for further
9957 * exploration.
9958 */
9959 init_explored_state(env, t);
Yonghong Songefdb22d2021-02-26 12:49:20 -08009960 return visit_func_call_insn(t, insn_cnt, insns, env,
9961 insns[t].src_reg == BPF_PSEUDO_CALL);
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +00009962
9963 case BPF_JA:
9964 if (BPF_SRC(insns[t].code) != BPF_K)
9965 return -EINVAL;
9966
9967 /* unconditional jump with single edge */
9968 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env,
9969 true);
9970 if (ret)
9971 return ret;
9972
9973 /* unconditional jmp is not a good pruning point,
9974 * but it's marked, since backtracking needs
9975 * to record jmp history in is_state_visited().
9976 */
9977 init_explored_state(env, t + insns[t].off + 1);
9978 /* tell verifier to check for equivalent states
9979 * after every call and jump
9980 */
9981 if (t + 1 < insn_cnt)
9982 init_explored_state(env, t + 1);
9983
9984 return ret;
9985
9986 default:
9987 /* conditional jump with two edges */
9988 init_explored_state(env, t);
9989 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
9990 if (ret)
9991 return ret;
9992
9993 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true);
9994 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -07009995}
9996
9997/* non-recursive depth-first-search to detect loops in BPF program
9998 * loop == back-edge in directed graph
9999 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010010000static int check_cfg(struct bpf_verifier_env *env)
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010001{
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010002 int insn_cnt = env->prog->len;
Alexei Starovoitov7df737e2019-04-19 07:44:54 -070010003 int *insn_stack, *insn_state;
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010004 int ret = 0;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +000010005 int i;
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010006
Alexei Starovoitov7df737e2019-04-19 07:44:54 -070010007 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010008 if (!insn_state)
10009 return -ENOMEM;
10010
Alexei Starovoitov7df737e2019-04-19 07:44:54 -070010011 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010012 if (!insn_stack) {
Alexei Starovoitov71dde682019-04-01 21:27:43 -070010013 kvfree(insn_state);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010014 return -ENOMEM;
10015 }
10016
10017 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
10018 insn_stack[0] = 0; /* 0 is the first instruction */
Alexei Starovoitov7df737e2019-04-19 07:44:54 -070010019 env->cfg.cur_stack = 1;
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010020
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +000010021 while (env->cfg.cur_stack > 0) {
10022 int t = insn_stack[env->cfg.cur_stack - 1];
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010023
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +000010024 ret = visit_insn(t, insn_cnt, env);
10025 switch (ret) {
10026 case DONE_EXPLORING:
10027 insn_state[t] = EXPLORED;
10028 env->cfg.cur_stack--;
10029 break;
10030 case KEEP_EXPLORING:
10031 break;
10032 default:
10033 if (ret > 0) {
10034 verbose(env, "visit_insn internal bug\n");
10035 ret = -EFAULT;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080010036 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010037 goto err_free;
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +000010038 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010039 }
10040
Wedson Almeida Filho59e2e272020-11-21 01:55:09 +000010041 if (env->cfg.cur_stack < 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010042 verbose(env, "pop stack internal bug\n");
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010043 ret = -EFAULT;
10044 goto err_free;
10045 }
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010046
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010047 for (i = 0; i < insn_cnt; i++) {
10048 if (insn_state[i] != EXPLORED) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070010049 verbose(env, "unreachable insn %d\n", i);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010050 ret = -EINVAL;
10051 goto err_free;
10052 }
10053 }
10054 ret = 0; /* cfg looks good */
10055
10056err_free:
Alexei Starovoitov71dde682019-04-01 21:27:43 -070010057 kvfree(insn_state);
10058 kvfree(insn_stack);
Alexei Starovoitov7df737e2019-04-19 07:44:54 -070010059 env->cfg.insn_state = env->cfg.insn_stack = NULL;
Alexei Starovoitov475fb782014-09-26 00:17:05 -070010060 return ret;
10061}
10062
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010063static int check_abnormal_return(struct bpf_verifier_env *env)
10064{
10065 int i;
10066
10067 for (i = 1; i < env->subprog_cnt; i++) {
10068 if (env->subprog_info[i].has_ld_abs) {
10069 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
10070 return -EINVAL;
10071 }
10072 if (env->subprog_info[i].has_tail_call) {
10073 verbose(env, "tail_call is not allowed in subprogs without BTF\n");
10074 return -EINVAL;
10075 }
10076 }
10077 return 0;
10078}
10079
Yonghong Song838e9692018-11-19 15:29:11 -080010080/* The minimum supported BTF func info size */
10081#define MIN_BPF_FUNCINFO_SIZE 8
10082#define MAX_FUNCINFO_REC_SIZE 252
10083
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010084static int check_btf_func(struct bpf_verifier_env *env,
10085 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010086 bpfptr_t uattr)
Yonghong Song838e9692018-11-19 15:29:11 -080010087{
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010088 const struct btf_type *type, *func_proto, *ret_type;
Peter Oskolkovd0b28182019-01-16 10:43:01 -080010089 u32 i, nfuncs, urec_size, min_size;
Yonghong Song838e9692018-11-19 15:29:11 -080010090 u32 krec_size = sizeof(struct bpf_func_info);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010091 struct bpf_func_info *krecord;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010092 struct bpf_func_info_aux *info_aux = NULL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010093 struct bpf_prog *prog;
10094 const struct btf *btf;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010095 bpfptr_t urecord;
Peter Oskolkovd0b28182019-01-16 10:43:01 -080010096 u32 prev_offset = 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010097 bool scalar_return;
Dan Carpentere7ed83d2020-06-04 11:54:36 +030010098 int ret = -ENOMEM;
Yonghong Song838e9692018-11-19 15:29:11 -080010099
10100 nfuncs = attr->func_info_cnt;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010101 if (!nfuncs) {
10102 if (check_abnormal_return(env))
10103 return -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -080010104 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010105 }
Yonghong Song838e9692018-11-19 15:29:11 -080010106
10107 if (nfuncs != env->subprog_cnt) {
10108 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
10109 return -EINVAL;
10110 }
10111
10112 urec_size = attr->func_info_rec_size;
10113 if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
10114 urec_size > MAX_FUNCINFO_REC_SIZE ||
10115 urec_size % sizeof(u32)) {
10116 verbose(env, "invalid func info rec size %u\n", urec_size);
10117 return -EINVAL;
10118 }
10119
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010120 prog = env->prog;
10121 btf = prog->aux->btf;
Yonghong Song838e9692018-11-19 15:29:11 -080010122
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010123 urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
Yonghong Song838e9692018-11-19 15:29:11 -080010124 min_size = min_t(u32, krec_size, urec_size);
10125
Yonghong Songba64e7d2018-11-24 23:20:44 -080010126 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010127 if (!krecord)
10128 return -ENOMEM;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010129 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
10130 if (!info_aux)
10131 goto err_free;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010132
Yonghong Song838e9692018-11-19 15:29:11 -080010133 for (i = 0; i < nfuncs; i++) {
10134 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
10135 if (ret) {
10136 if (ret == -E2BIG) {
10137 verbose(env, "nonzero tailing record in func info");
10138 /* set the size kernel expects so loader can zero
10139 * out the rest of the record.
10140 */
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010141 if (copy_to_bpfptr_offset(uattr,
10142 offsetof(union bpf_attr, func_info_rec_size),
10143 &min_size, sizeof(min_size)))
Yonghong Song838e9692018-11-19 15:29:11 -080010144 ret = -EFAULT;
10145 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010146 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010147 }
10148
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010149 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
Yonghong Song838e9692018-11-19 15:29:11 -080010150 ret = -EFAULT;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010151 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010152 }
10153
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010154 /* check insn_off */
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010155 ret = -EINVAL;
Yonghong Song838e9692018-11-19 15:29:11 -080010156 if (i == 0) {
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010157 if (krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -080010158 verbose(env,
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010159 "nonzero insn_off %u for the first func info record",
10160 krecord[i].insn_off);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010161 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010162 }
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010163 } else if (krecord[i].insn_off <= prev_offset) {
Yonghong Song838e9692018-11-19 15:29:11 -080010164 verbose(env,
10165 "same or smaller insn offset (%u) than previous func info record (%u)",
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010166 krecord[i].insn_off, prev_offset);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010167 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010168 }
10169
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010170 if (env->subprog_info[i].start != krecord[i].insn_off) {
Yonghong Song838e9692018-11-19 15:29:11 -080010171 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010172 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010173 }
10174
10175 /* check type_id */
Yonghong Songba64e7d2018-11-24 23:20:44 -080010176 type = btf_type_by_id(btf, krecord[i].type_id);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010177 if (!type || !btf_type_is_func(type)) {
Yonghong Song838e9692018-11-19 15:29:11 -080010178 verbose(env, "invalid type id %d in func info",
Yonghong Songba64e7d2018-11-24 23:20:44 -080010179 krecord[i].type_id);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010180 goto err_free;
Yonghong Song838e9692018-11-19 15:29:11 -080010181 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080010182 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010183
10184 func_proto = btf_type_by_id(btf, type->type);
10185 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
10186 /* btf_func_check() already verified it during BTF load */
10187 goto err_free;
10188 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
10189 scalar_return =
10190 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type);
10191 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
10192 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
10193 goto err_free;
10194 }
10195 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
10196 verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
10197 goto err_free;
10198 }
10199
Martin KaFai Laud30d42e2018-12-05 17:35:44 -080010200 prev_offset = krecord[i].insn_off;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010201 bpfptr_add(&urecord, urec_size);
Yonghong Song838e9692018-11-19 15:29:11 -080010202 }
10203
Yonghong Songba64e7d2018-11-24 23:20:44 -080010204 prog->aux->func_info = krecord;
10205 prog->aux->func_info_cnt = nfuncs;
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010206 prog->aux->func_info_aux = info_aux;
Yonghong Song838e9692018-11-19 15:29:11 -080010207 return 0;
10208
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010209err_free:
Yonghong Songba64e7d2018-11-24 23:20:44 -080010210 kvfree(krecord);
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010211 kfree(info_aux);
Yonghong Song838e9692018-11-19 15:29:11 -080010212 return ret;
10213}
10214
Yonghong Songba64e7d2018-11-24 23:20:44 -080010215static void adjust_btf_func(struct bpf_verifier_env *env)
10216{
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010217 struct bpf_prog_aux *aux = env->prog->aux;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010218 int i;
10219
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010220 if (!aux->func_info)
Yonghong Songba64e7d2018-11-24 23:20:44 -080010221 return;
10222
10223 for (i = 0; i < env->subprog_cnt; i++)
Alexei Starovoitov8c1b6e62019-11-14 10:57:16 -080010224 aux->func_info[i].insn_off = env->subprog_info[i].start;
Yonghong Songba64e7d2018-11-24 23:20:44 -080010225}
10226
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010227#define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \
10228 sizeof(((struct bpf_line_info *)(0))->line_col))
10229#define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE
10230
10231static int check_btf_line(struct bpf_verifier_env *env,
10232 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010233 bpfptr_t uattr)
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010234{
10235 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
10236 struct bpf_subprog_info *sub;
10237 struct bpf_line_info *linfo;
10238 struct bpf_prog *prog;
10239 const struct btf *btf;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010240 bpfptr_t ulinfo;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010241 int err;
10242
10243 nr_linfo = attr->line_info_cnt;
10244 if (!nr_linfo)
10245 return 0;
Bixuan Cui0e6491b2021-09-11 08:55:57 +080010246 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
10247 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010248
10249 rec_size = attr->line_info_rec_size;
10250 if (rec_size < MIN_BPF_LINEINFO_SIZE ||
10251 rec_size > MAX_LINEINFO_REC_SIZE ||
10252 rec_size & (sizeof(u32) - 1))
10253 return -EINVAL;
10254
10255 /* Need to zero it in case the userspace may
10256 * pass in a smaller bpf_line_info object.
10257 */
10258 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
10259 GFP_KERNEL | __GFP_NOWARN);
10260 if (!linfo)
10261 return -ENOMEM;
10262
10263 prog = env->prog;
10264 btf = prog->aux->btf;
10265
10266 s = 0;
10267 sub = env->subprog_info;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010268 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010269 expected_size = sizeof(struct bpf_line_info);
10270 ncopy = min_t(u32, expected_size, rec_size);
10271 for (i = 0; i < nr_linfo; i++) {
10272 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
10273 if (err) {
10274 if (err == -E2BIG) {
10275 verbose(env, "nonzero tailing record in line_info");
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010276 if (copy_to_bpfptr_offset(uattr,
10277 offsetof(union bpf_attr, line_info_rec_size),
10278 &expected_size, sizeof(expected_size)))
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010279 err = -EFAULT;
10280 }
10281 goto err_free;
10282 }
10283
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010284 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010285 err = -EFAULT;
10286 goto err_free;
10287 }
10288
10289 /*
10290 * Check insn_off to ensure
10291 * 1) strictly increasing AND
10292 * 2) bounded by prog->len
10293 *
10294 * The linfo[0].insn_off == 0 check logically falls into
10295 * the later "missing bpf_line_info for func..." case
10296 * because the first linfo[0].insn_off must be the
10297 * first sub also and the first sub must have
10298 * subprog_info[0].start == 0.
10299 */
10300 if ((i && linfo[i].insn_off <= prev_offset) ||
10301 linfo[i].insn_off >= prog->len) {
10302 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
10303 i, linfo[i].insn_off, prev_offset,
10304 prog->len);
10305 err = -EINVAL;
10306 goto err_free;
10307 }
10308
Martin KaFai Laufdbaa0b2018-12-19 13:01:01 -080010309 if (!prog->insnsi[linfo[i].insn_off].code) {
10310 verbose(env,
10311 "Invalid insn code at line_info[%u].insn_off\n",
10312 i);
10313 err = -EINVAL;
10314 goto err_free;
10315 }
10316
Martin KaFai Lau23127b32018-12-13 10:41:46 -080010317 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
10318 !btf_name_by_offset(btf, linfo[i].file_name_off)) {
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010319 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
10320 err = -EINVAL;
10321 goto err_free;
10322 }
10323
10324 if (s != env->subprog_cnt) {
10325 if (linfo[i].insn_off == sub[s].start) {
10326 sub[s].linfo_idx = i;
10327 s++;
10328 } else if (sub[s].start < linfo[i].insn_off) {
10329 verbose(env, "missing bpf_line_info for func#%u\n", s);
10330 err = -EINVAL;
10331 goto err_free;
10332 }
10333 }
10334
10335 prev_offset = linfo[i].insn_off;
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010336 bpfptr_add(&ulinfo, rec_size);
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010337 }
10338
10339 if (s != env->subprog_cnt) {
10340 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
10341 env->subprog_cnt - s, s);
10342 err = -EINVAL;
10343 goto err_free;
10344 }
10345
10346 prog->aux->linfo = linfo;
10347 prog->aux->nr_linfo = nr_linfo;
10348
10349 return 0;
10350
10351err_free:
10352 kvfree(linfo);
10353 return err;
10354}
10355
Alexei Starovoitovfbd94c72021-12-01 10:10:28 -080010356#define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo)
10357#define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE
10358
10359static int check_core_relo(struct bpf_verifier_env *env,
10360 const union bpf_attr *attr,
10361 bpfptr_t uattr)
10362{
10363 u32 i, nr_core_relo, ncopy, expected_size, rec_size;
10364 struct bpf_core_relo core_relo = {};
10365 struct bpf_prog *prog = env->prog;
10366 const struct btf *btf = prog->aux->btf;
10367 struct bpf_core_ctx ctx = {
10368 .log = &env->log,
10369 .btf = btf,
10370 };
10371 bpfptr_t u_core_relo;
10372 int err;
10373
10374 nr_core_relo = attr->core_relo_cnt;
10375 if (!nr_core_relo)
10376 return 0;
10377 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
10378 return -EINVAL;
10379
10380 rec_size = attr->core_relo_rec_size;
10381 if (rec_size < MIN_CORE_RELO_SIZE ||
10382 rec_size > MAX_CORE_RELO_SIZE ||
10383 rec_size % sizeof(u32))
10384 return -EINVAL;
10385
10386 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
10387 expected_size = sizeof(struct bpf_core_relo);
10388 ncopy = min_t(u32, expected_size, rec_size);
10389
10390 /* Unlike func_info and line_info, copy and apply each CO-RE
10391 * relocation record one at a time.
10392 */
10393 for (i = 0; i < nr_core_relo; i++) {
10394 /* future proofing when sizeof(bpf_core_relo) changes */
10395 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
10396 if (err) {
10397 if (err == -E2BIG) {
10398 verbose(env, "nonzero tailing record in core_relo");
10399 if (copy_to_bpfptr_offset(uattr,
10400 offsetof(union bpf_attr, core_relo_rec_size),
10401 &expected_size, sizeof(expected_size)))
10402 err = -EFAULT;
10403 }
10404 break;
10405 }
10406
10407 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
10408 err = -EFAULT;
10409 break;
10410 }
10411
10412 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
10413 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
10414 i, core_relo.insn_off, prog->len);
10415 err = -EINVAL;
10416 break;
10417 }
10418
10419 err = bpf_core_apply(&ctx, &core_relo, i,
10420 &prog->insnsi[core_relo.insn_off / 8]);
10421 if (err)
10422 break;
10423 bpfptr_add(&u_core_relo, rec_size);
10424 }
10425 return err;
10426}
10427
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010428static int check_btf_info(struct bpf_verifier_env *env,
10429 const union bpf_attr *attr,
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070010430 bpfptr_t uattr)
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010431{
10432 struct btf *btf;
10433 int err;
10434
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010435 if (!attr->func_info_cnt && !attr->line_info_cnt) {
10436 if (check_abnormal_return(env))
10437 return -EINVAL;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010438 return 0;
Alexei Starovoitov09b28d72020-09-17 19:09:18 -070010439 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010440
10441 btf = btf_get_by_fd(attr->prog_btf_fd);
10442 if (IS_ERR(btf))
10443 return PTR_ERR(btf);
Alexei Starovoitov350a5c42021-03-07 14:52:48 -080010444 if (btf_is_kernel(btf)) {
10445 btf_put(btf);
10446 return -EACCES;
10447 }
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010448 env->prog->aux->btf = btf;
10449
10450 err = check_btf_func(env, attr, uattr);
10451 if (err)
10452 return err;
10453
10454 err = check_btf_line(env, attr, uattr);
10455 if (err)
10456 return err;
10457
Alexei Starovoitovfbd94c72021-12-01 10:10:28 -080010458 err = check_core_relo(env, attr, uattr);
10459 if (err)
10460 return err;
10461
Martin KaFai Lauc454a462018-12-07 16:42:25 -080010462 return 0;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070010463}
10464
Edward Creef1174f72017-08-07 15:26:19 +010010465/* check %cur's range satisfies %old's */
10466static bool range_within(struct bpf_reg_state *old,
10467 struct bpf_reg_state *cur)
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010468{
Edward Creeb03c9f92017-08-07 15:26:36 +010010469 return old->umin_value <= cur->umin_value &&
10470 old->umax_value >= cur->umax_value &&
10471 old->smin_value <= cur->smin_value &&
Daniel Borkmannfd675182021-02-05 20:48:21 +010010472 old->smax_value >= cur->smax_value &&
10473 old->u32_min_value <= cur->u32_min_value &&
10474 old->u32_max_value >= cur->u32_max_value &&
10475 old->s32_min_value <= cur->s32_min_value &&
10476 old->s32_max_value >= cur->s32_max_value;
Edward Creef1174f72017-08-07 15:26:19 +010010477}
10478
Edward Creef1174f72017-08-07 15:26:19 +010010479/* If in the old state two registers had the same id, then they need to have
10480 * the same id in the new state as well. But that id could be different from
10481 * the old state, so we need to track the mapping from old to new ids.
10482 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
10483 * regs with old id 5 must also have new id 9 for the new state to be safe. But
10484 * regs with a different old id could still have new id 9, we don't care about
10485 * that.
10486 * So we look through our idmap to see if this old id has been seen before. If
10487 * so, we require the new id to match; otherwise, we add the id pair to the map.
10488 */
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010489static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +010010490{
10491 unsigned int i;
10492
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010493 for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
Edward Creef1174f72017-08-07 15:26:19 +010010494 if (!idmap[i].old) {
10495 /* Reached an empty slot; haven't seen this id before */
10496 idmap[i].old = old_id;
10497 idmap[i].cur = cur_id;
10498 return true;
10499 }
10500 if (idmap[i].old == old_id)
10501 return idmap[i].cur == cur_id;
10502 }
10503 /* We ran out of idmap slots, which should be impossible */
10504 WARN_ON_ONCE(1);
10505 return false;
10506}
10507
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010508static void clean_func_state(struct bpf_verifier_env *env,
10509 struct bpf_func_state *st)
10510{
10511 enum bpf_reg_liveness live;
10512 int i, j;
10513
10514 for (i = 0; i < BPF_REG_FP; i++) {
10515 live = st->regs[i].live;
10516 /* liveness must not touch this register anymore */
10517 st->regs[i].live |= REG_LIVE_DONE;
10518 if (!(live & REG_LIVE_READ))
10519 /* since the register is unused, clear its state
10520 * to make further comparison simpler
10521 */
Daniel Borkmannf54c7892019-12-22 23:37:40 +010010522 __mark_reg_not_init(env, &st->regs[i]);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010523 }
10524
10525 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
10526 live = st->stack[i].spilled_ptr.live;
10527 /* liveness must not touch this stack slot anymore */
10528 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
10529 if (!(live & REG_LIVE_READ)) {
Daniel Borkmannf54c7892019-12-22 23:37:40 +010010530 __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010531 for (j = 0; j < BPF_REG_SIZE; j++)
10532 st->stack[i].slot_type[j] = STACK_INVALID;
10533 }
10534 }
10535}
10536
10537static void clean_verifier_state(struct bpf_verifier_env *env,
10538 struct bpf_verifier_state *st)
10539{
10540 int i;
10541
10542 if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
10543 /* all regs in this state in all frames were already marked */
10544 return;
10545
10546 for (i = 0; i <= st->curframe; i++)
10547 clean_func_state(env, st->frame[i]);
10548}
10549
10550/* the parentage chains form a tree.
10551 * the verifier states are added to state lists at given insn and
10552 * pushed into state stack for future exploration.
10553 * when the verifier reaches bpf_exit insn some of the verifer states
10554 * stored in the state lists have their final liveness state already,
10555 * but a lot of states will get revised from liveness point of view when
10556 * the verifier explores other branches.
10557 * Example:
10558 * 1: r0 = 1
10559 * 2: if r1 == 100 goto pc+1
10560 * 3: r0 = 2
10561 * 4: exit
10562 * when the verifier reaches exit insn the register r0 in the state list of
10563 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
10564 * of insn 2 and goes exploring further. At the insn 4 it will walk the
10565 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
10566 *
10567 * Since the verifier pushes the branch states as it sees them while exploring
10568 * the program the condition of walking the branch instruction for the second
10569 * time means that all states below this branch were already explored and
Zhen Lei8fb33b62021-05-25 10:56:59 +080010570 * their final liveness marks are already propagated.
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010571 * Hence when the verifier completes the search of state list in is_state_visited()
10572 * we can call this clean_live_states() function to mark all liveness states
10573 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
10574 * will not be used.
10575 * This function also clears the registers and stack for states that !READ
10576 * to simplify state merging.
10577 *
10578 * Important note here that walking the same branch instruction in the callee
10579 * doesn't meant that the states are DONE. The verifier has to compare
10580 * the callsites
10581 */
10582static void clean_live_states(struct bpf_verifier_env *env, int insn,
10583 struct bpf_verifier_state *cur)
10584{
10585 struct bpf_verifier_state_list *sl;
10586 int i;
10587
Alexei Starovoitov5d839022019-05-21 20:17:05 -070010588 sl = *explored_state(env, insn);
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070010589 while (sl) {
Alexei Starovoitov25897262019-06-15 12:12:20 -070010590 if (sl->state.branches)
10591 goto next;
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070010592 if (sl->state.insn_idx != insn ||
10593 sl->state.curframe != cur->curframe)
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080010594 goto next;
10595 for (i = 0; i <= cur->curframe; i++)
10596 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
10597 goto next;
10598 clean_verifier_state(env, &sl->state);
10599next:
10600 sl = sl->next;
10601 }
10602}
10603
Edward Creef1174f72017-08-07 15:26:19 +010010604/* Returns true if (rold safe implies rcur safe) */
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010605static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
10606 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap)
Edward Creef1174f72017-08-07 15:26:19 +010010607{
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010608 bool equal;
10609
Edward Creedc503a82017-08-15 20:34:35 +010010610 if (!(rold->live & REG_LIVE_READ))
10611 /* explored state didn't use this */
10612 return true;
10613
Edward Cree679c7822018-08-22 20:02:19 +010010614 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010615
10616 if (rold->type == PTR_TO_STACK)
10617 /* two stack pointers are equal only if they're pointing to
10618 * the same stack frame, since fp-8 in foo != fp-8 in bar
10619 */
10620 return equal && rold->frameno == rcur->frameno;
10621
10622 if (equal)
Edward Creef1174f72017-08-07 15:26:19 +010010623 return true;
10624
10625 if (rold->type == NOT_INIT)
10626 /* explored state can't have used this */
10627 return true;
10628 if (rcur->type == NOT_INIT)
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010629 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010630 switch (rold->type) {
10631 case SCALAR_VALUE:
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010632 if (env->explore_alu_limits)
10633 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010634 if (rcur->type == SCALAR_VALUE) {
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070010635 if (!rold->precise && !rcur->precise)
10636 return true;
Edward Creef1174f72017-08-07 15:26:19 +010010637 /* new val must satisfy old val knowledge */
10638 return range_within(rold, rcur) &&
10639 tnum_in(rold->var_off, rcur->var_off);
10640 } else {
Jann Horn179d1c52017-12-18 20:11:59 -080010641 /* We're trying to use a pointer in place of a scalar.
10642 * Even if the scalar was unbounded, this could lead to
10643 * pointer leaks because scalars are allowed to leak
10644 * while pointers are not. We could make this safe in
10645 * special cases if root is calling us, but it's
10646 * probably not worth the hassle.
Edward Creef1174f72017-08-07 15:26:19 +010010647 */
Jann Horn179d1c52017-12-18 20:11:59 -080010648 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010649 }
Yonghong Song69c087b2021-02-26 12:49:25 -080010650 case PTR_TO_MAP_KEY:
Edward Creef1174f72017-08-07 15:26:19 +010010651 case PTR_TO_MAP_VALUE:
Edward Cree1b688a12017-08-23 15:10:50 +010010652 /* If the new min/max/var_off satisfy the old ones and
10653 * everything else matches, we are OK.
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010654 * 'id' is not compared, since it's only used for maps with
10655 * bpf_spin_lock inside map element and in such cases if
10656 * the rest of the prog is valid for one map element then
10657 * it's valid for all map elements regardless of the key
10658 * used in bpf_map_lookup()
Edward Cree1b688a12017-08-23 15:10:50 +010010659 */
10660 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
10661 range_within(rold, rcur) &&
10662 tnum_in(rold->var_off, rcur->var_off);
Edward Creef1174f72017-08-07 15:26:19 +010010663 case PTR_TO_MAP_VALUE_OR_NULL:
10664 /* a PTR_TO_MAP_VALUE could be safe to use as a
10665 * PTR_TO_MAP_VALUE_OR_NULL into the same map.
10666 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL-
10667 * checked, doing so could have affected others with the same
10668 * id, and we can't check for that because we lost the id when
10669 * we converted to a PTR_TO_MAP_VALUE.
10670 */
10671 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL)
10672 return false;
10673 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)))
10674 return false;
10675 /* Check our ids match any regs they're supposed to */
10676 return check_ids(rold->id, rcur->id, idmap);
Daniel Borkmannde8f3a82017-09-25 02:25:51 +020010677 case PTR_TO_PACKET_META:
Edward Creef1174f72017-08-07 15:26:19 +010010678 case PTR_TO_PACKET:
Daniel Borkmannde8f3a82017-09-25 02:25:51 +020010679 if (rcur->type != rold->type)
Edward Creef1174f72017-08-07 15:26:19 +010010680 return false;
10681 /* We must have at least as much range as the old ptr
10682 * did, so that any accesses which were safe before are
10683 * still safe. This is true even if old range < old off,
10684 * since someone could have accessed through (ptr - k), or
10685 * even done ptr -= k in a register, to get a safe access.
10686 */
10687 if (rold->range > rcur->range)
10688 return false;
10689 /* If the offsets don't match, we can't trust our alignment;
10690 * nor can we be sure that we won't fall out of range.
10691 */
10692 if (rold->off != rcur->off)
10693 return false;
10694 /* id relations must be preserved */
10695 if (rold->id && !check_ids(rold->id, rcur->id, idmap))
10696 return false;
10697 /* new val must satisfy old val knowledge */
10698 return range_within(rold, rcur) &&
10699 tnum_in(rold->var_off, rcur->var_off);
10700 case PTR_TO_CTX:
10701 case CONST_PTR_TO_MAP:
Edward Creef1174f72017-08-07 15:26:19 +010010702 case PTR_TO_PACKET_END:
Petar Penkovd58e4682018-09-14 07:46:18 -070010703 case PTR_TO_FLOW_KEYS:
Joe Stringerc64b7982018-10-02 13:35:33 -070010704 case PTR_TO_SOCKET:
10705 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080010706 case PTR_TO_SOCK_COMMON:
10707 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080010708 case PTR_TO_TCP_SOCK:
10709 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070010710 case PTR_TO_XDP_SOCK:
Edward Creef1174f72017-08-07 15:26:19 +010010711 /* Only valid matches are exact, which memcmp() above
10712 * would have accepted
10713 */
10714 default:
10715 /* Don't know what's going on, just say it's not safe */
10716 return false;
10717 }
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010718
Edward Creef1174f72017-08-07 15:26:19 +010010719 /* Shouldn't get here; if we do, say it's not safe */
10720 WARN_ON_ONCE(1);
Alexei Starovoitov969bf052016-05-05 19:49:10 -070010721 return false;
10722}
10723
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010724static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
10725 struct bpf_func_state *cur, struct bpf_id_pair *idmap)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010726{
10727 int i, spi;
10728
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010729 /* walk slots of the explored stack and ignore any additional
10730 * slots in the current stack, since explored(safe) state
10731 * didn't use them
10732 */
10733 for (i = 0; i < old->allocated_stack; i++) {
10734 spi = i / BPF_REG_SIZE;
10735
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010736 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
10737 i += BPF_REG_SIZE - 1;
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010738 /* explored state didn't use this */
Gianluca Borellofd05e572017-12-23 10:09:55 +000010739 continue;
Alexei Starovoitovb2339202018-12-13 11:42:31 -080010740 }
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010741
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010742 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
10743 continue;
Alexei Starovoitov19e2dbb2018-12-13 11:42:33 -080010744
10745 /* explored stack has more populated slots than current stack
10746 * and these slots were used
10747 */
10748 if (i >= cur->allocated_stack)
10749 return false;
10750
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080010751 /* if old state was safe with misc data in the stack
10752 * it will be safe with zero-initialized stack.
10753 * The opposite is not true
10754 */
10755 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
10756 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
10757 continue;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010758 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
10759 cur->stack[spi].slot_type[i % BPF_REG_SIZE])
10760 /* Ex: old explored (safe) state has STACK_SPILL in
Randy Dunlapb8c1a302020-08-06 20:31:41 -070010761 * this stack slot, but current has STACK_MISC ->
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010762 * this verifier states are not equivalent,
10763 * return false to continue verification of this path
10764 */
10765 return false;
Martin KaFai Lau27113c52021-09-21 17:49:34 -070010766 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010767 continue;
Martin KaFai Lau27113c52021-09-21 17:49:34 -070010768 if (!is_spilled_reg(&old->stack[spi]))
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010769 continue;
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010770 if (!regsafe(env, &old->stack[spi].spilled_ptr,
10771 &cur->stack[spi].spilled_ptr, idmap))
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070010772 /* when explored and current stack slot are both storing
10773 * spilled registers, check that stored pointers types
10774 * are the same as well.
10775 * Ex: explored safe path could have stored
10776 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
10777 * but current path has stored:
10778 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
10779 * such verifier states are not equivalent.
10780 * return false to continue verification of this path
10781 */
10782 return false;
10783 }
10784 return true;
10785}
10786
Joe Stringerfd978bf72018-10-02 13:35:35 -070010787static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur)
10788{
10789 if (old->acquired_refs != cur->acquired_refs)
10790 return false;
10791 return !memcmp(old->refs, cur->refs,
10792 sizeof(*old->refs) * old->acquired_refs);
10793}
10794
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010795/* compare two verifier states
10796 *
10797 * all states stored in state_list are known to be valid, since
10798 * verifier reached 'bpf_exit' instruction through them
10799 *
10800 * this function is called when verifier exploring different branches of
10801 * execution popped from the state stack. If it sees an old state that has
10802 * more strict register state and more strict stack state then this execution
10803 * branch doesn't need to be explored further, since verifier already
10804 * concluded that more strict state leads to valid finish.
10805 *
10806 * Therefore two states are equivalent if register state is more conservative
10807 * and explored stack state is more conservative than the current one.
10808 * Example:
10809 * explored current
10810 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
10811 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
10812 *
10813 * In other words if current stack state (one being explored) has more
10814 * valid slots than old one that already passed validation, it means
10815 * the verifier can stop exploring and conclude that current state is valid too
10816 *
10817 * Similarly with registers. If explored state has register type as invalid
10818 * whereas register type in current state is meaningful, it means that
10819 * the current state will reach 'bpf_exit' instruction safely
10820 */
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010821static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010822 struct bpf_func_state *cur)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010823{
10824 int i;
10825
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010826 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch));
10827 for (i = 0; i < MAX_BPF_REG; i++)
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010828 if (!regsafe(env, &old->regs[i], &cur->regs[i],
10829 env->idmap_scratch))
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010830 return false;
10831
Daniel Borkmanne042aa52021-07-16 09:18:21 +000010832 if (!stacksafe(env, old, cur, env->idmap_scratch))
Alexei Starovoitov1a0dc1a2016-05-05 19:49:09 -070010833 return false;
Edward Creef1174f72017-08-07 15:26:19 +010010834
Joe Stringerfd978bf72018-10-02 13:35:35 -070010835 if (!refsafe(old, cur))
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010836 return false;
10837
10838 return true;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070010839}
10840
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010841static bool states_equal(struct bpf_verifier_env *env,
10842 struct bpf_verifier_state *old,
10843 struct bpf_verifier_state *cur)
Edward Creedc503a82017-08-15 20:34:35 +010010844{
Edward Creedc503a82017-08-15 20:34:35 +010010845 int i;
10846
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010847 if (old->curframe != cur->curframe)
10848 return false;
10849
Daniel Borkmann979d63d2019-01-03 00:58:34 +010010850 /* Verification state from speculative execution simulation
10851 * must never prune a non-speculative execution one.
10852 */
10853 if (old->speculative && !cur->speculative)
10854 return false;
10855
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080010856 if (old->active_spin_lock != cur->active_spin_lock)
10857 return false;
10858
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010859 /* for states to be equal callsites have to be the same
10860 * and all frame states need to be equivalent
10861 */
10862 for (i = 0; i <= old->curframe; i++) {
10863 if (old->frame[i]->callsite != cur->frame[i]->callsite)
10864 return false;
Lorenz Bauerc9e73e32021-04-29 14:46:56 +010010865 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010866 return false;
10867 }
10868 return true;
10869}
10870
Jiong Wang5327ed32019-05-24 23:25:12 +010010871/* Return 0 if no propagation happened. Return negative error code if error
10872 * happened. Otherwise, return the propagated bit.
10873 */
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010874static int propagate_liveness_reg(struct bpf_verifier_env *env,
10875 struct bpf_reg_state *reg,
10876 struct bpf_reg_state *parent_reg)
10877{
Jiong Wang5327ed32019-05-24 23:25:12 +010010878 u8 parent_flag = parent_reg->live & REG_LIVE_READ;
10879 u8 flag = reg->live & REG_LIVE_READ;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010880 int err;
10881
Jiong Wang5327ed32019-05-24 23:25:12 +010010882 /* When comes here, read flags of PARENT_REG or REG could be any of
10883 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
10884 * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
10885 */
10886 if (parent_flag == REG_LIVE_READ64 ||
10887 /* Or if there is no read flag from REG. */
10888 !flag ||
10889 /* Or if the read flag from REG is the same as PARENT_REG. */
10890 parent_flag == flag)
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010891 return 0;
10892
Jiong Wang5327ed32019-05-24 23:25:12 +010010893 err = mark_reg_read(env, reg, parent_reg, flag);
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010894 if (err)
10895 return err;
10896
Jiong Wang5327ed32019-05-24 23:25:12 +010010897 return flag;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010898}
10899
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010900/* A write screens off any subsequent reads; but write marks come from the
10901 * straight-line code between a state and its parent. When we arrive at an
10902 * equivalent state (jump target or such) we didn't arrive by the straight-line
10903 * code, so read marks in the state must propagate to the parent regardless
10904 * of the state's write marks. That's what 'parent == state->parent' comparison
Edward Cree679c7822018-08-22 20:02:19 +010010905 * in mark_reg_read() is for.
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010906 */
10907static int propagate_liveness(struct bpf_verifier_env *env,
10908 const struct bpf_verifier_state *vstate,
10909 struct bpf_verifier_state *vparent)
10910{
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010911 struct bpf_reg_state *state_reg, *parent_reg;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010912 struct bpf_func_state *state, *parent;
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010913 int i, frame, err = 0;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010914
10915 if (vparent->curframe != vstate->curframe) {
10916 WARN(1, "propagate_live: parent frame %d current frame %d\n",
10917 vparent->curframe, vstate->curframe);
10918 return -EFAULT;
10919 }
Edward Creedc503a82017-08-15 20:34:35 +010010920 /* Propagate read liveness of registers... */
10921 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
Jakub Kicinski83d16312019-03-21 14:34:36 -070010922 for (frame = 0; frame <= vstate->curframe; frame++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010923 parent = vparent->frame[frame];
10924 state = vstate->frame[frame];
10925 parent_reg = parent->regs;
10926 state_reg = state->regs;
Jakub Kicinski83d16312019-03-21 14:34:36 -070010927 /* We don't need to worry about FP liveness, it's read-only */
10928 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010929 err = propagate_liveness_reg(env, &state_reg[i],
10930 &parent_reg[i]);
Jiong Wang5327ed32019-05-24 23:25:12 +010010931 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010932 return err;
Jiong Wang5327ed32019-05-24 23:25:12 +010010933 if (err == REG_LIVE_READ64)
10934 mark_insn_zext(env, &parent_reg[i]);
Edward Creedc503a82017-08-15 20:34:35 +010010935 }
Edward Creedc503a82017-08-15 20:34:35 +010010936
Jiong Wang1b04aee2019-04-12 22:59:34 +010010937 /* Propagate stack slots. */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010938 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
10939 i < parent->allocated_stack / BPF_REG_SIZE; i++) {
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010940 parent_reg = &parent->stack[i].spilled_ptr;
10941 state_reg = &state->stack[i].spilled_ptr;
Jiong Wang55e7f3b2019-04-12 22:59:36 +010010942 err = propagate_liveness_reg(env, state_reg,
10943 parent_reg);
Jiong Wang5327ed32019-05-24 23:25:12 +010010944 if (err < 0)
Jiong Wang3f8cafa2019-04-12 22:59:35 +010010945 return err;
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080010946 }
Edward Creedc503a82017-08-15 20:34:35 +010010947 }
Jiong Wang5327ed32019-05-24 23:25:12 +010010948 return 0;
Edward Creedc503a82017-08-15 20:34:35 +010010949}
10950
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010951/* find precise scalars in the previous equivalent state and
10952 * propagate them into the current state
10953 */
10954static int propagate_precision(struct bpf_verifier_env *env,
10955 const struct bpf_verifier_state *old)
10956{
10957 struct bpf_reg_state *state_reg;
10958 struct bpf_func_state *state;
10959 int i, err = 0;
10960
10961 state = old->frame[old->curframe];
10962 state_reg = state->regs;
10963 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
10964 if (state_reg->type != SCALAR_VALUE ||
10965 !state_reg->precise)
10966 continue;
10967 if (env->log.level & BPF_LOG_LEVEL2)
10968 verbose(env, "propagating r%d\n", i);
10969 err = mark_chain_precision(env, i);
10970 if (err < 0)
10971 return err;
10972 }
10973
10974 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
Martin KaFai Lau27113c52021-09-21 17:49:34 -070010975 if (!is_spilled_reg(&state->stack[i]))
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070010976 continue;
10977 state_reg = &state->stack[i].spilled_ptr;
10978 if (state_reg->type != SCALAR_VALUE ||
10979 !state_reg->precise)
10980 continue;
10981 if (env->log.level & BPF_LOG_LEVEL2)
10982 verbose(env, "propagating fp%d\n",
10983 (-i - 1) * BPF_REG_SIZE);
10984 err = mark_chain_precision_stack(env, i);
10985 if (err < 0)
10986 return err;
10987 }
10988 return 0;
10989}
10990
Alexei Starovoitov25897262019-06-15 12:12:20 -070010991static bool states_maybe_looping(struct bpf_verifier_state *old,
10992 struct bpf_verifier_state *cur)
10993{
10994 struct bpf_func_state *fold, *fcur;
10995 int i, fr = cur->curframe;
10996
10997 if (old->curframe != fr)
10998 return false;
10999
11000 fold = old->frame[fr];
11001 fcur = cur->frame[fr];
11002 for (i = 0; i < MAX_BPF_REG; i++)
11003 if (memcmp(&fold->regs[i], &fcur->regs[i],
11004 offsetof(struct bpf_reg_state, parent)))
11005 return false;
11006 return true;
11007}
11008
11009
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011010static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011011{
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011012 struct bpf_verifier_state_list *new_sl;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011013 struct bpf_verifier_state_list *sl, **pprev;
Edward Cree679c7822018-08-22 20:02:19 +010011014 struct bpf_verifier_state *cur = env->cur_state, *new;
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080011015 int i, j, err, states_cnt = 0;
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070011016 bool add_new_state = env->test_state_freq ? true : false;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011017
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011018 cur->last_insn_idx = env->prev_insn_idx;
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011019 if (!env->insn_aux_data[insn_idx].prune_point)
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011020 /* this 'insn_idx' instruction wasn't marked, so we will not
11021 * be doing state search here
11022 */
11023 return 0;
11024
Alexei Starovoitov25897262019-06-15 12:12:20 -070011025 /* bpf progs typically have pruning point every 4 instructions
11026 * http://vger.kernel.org/bpfconf2019.html#session-1
11027 * Do not add new state for future pruning if the verifier hasn't seen
11028 * at least 2 jumps and at least 8 instructions.
11029 * This heuristics helps decrease 'total_states' and 'peak_states' metric.
11030 * In tests that amounts to up to 50% reduction into total verifier
11031 * memory consumption and 20% verifier time speedup.
11032 */
11033 if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
11034 env->insn_processed - env->prev_insn_processed >= 8)
11035 add_new_state = true;
11036
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011037 pprev = explored_state(env, insn_idx);
11038 sl = *pprev;
11039
Alexei Starovoitov9242b5f2018-12-13 11:42:34 -080011040 clean_live_states(env, insn_idx, cur);
11041
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070011042 while (sl) {
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011043 states_cnt++;
11044 if (sl->state.insn_idx != insn_idx)
11045 goto next;
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -070011046
Alexei Starovoitov25897262019-06-15 12:12:20 -070011047 if (sl->state.branches) {
Alexei Starovoitovbfc6bb72021-07-14 17:54:14 -070011048 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
11049
11050 if (frame->in_async_callback_fn &&
11051 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
11052 /* Different async_entry_cnt means that the verifier is
11053 * processing another entry into async callback.
11054 * Seeing the same state is not an indication of infinite
11055 * loop or infinite recursion.
11056 * But finding the same state doesn't mean that it's safe
11057 * to stop processing the current state. The previous state
11058 * hasn't yet reached bpf_exit, since state.branches > 0.
11059 * Checking in_async_callback_fn alone is not enough either.
11060 * Since the verifier still needs to catch infinite loops
11061 * inside async callbacks.
11062 */
11063 } else if (states_maybe_looping(&sl->state, cur) &&
11064 states_equal(env, &sl->state, cur)) {
Alexei Starovoitov25897262019-06-15 12:12:20 -070011065 verbose_linfo(env, insn_idx, "; ");
11066 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
11067 return -EINVAL;
11068 }
11069 /* if the verifier is processing a loop, avoid adding new state
11070 * too often, since different loop iterations have distinct
11071 * states and may not help future pruning.
11072 * This threshold shouldn't be too low to make sure that
11073 * a loop with large bound will be rejected quickly.
11074 * The most abusive loop will be:
11075 * r1 += 1
11076 * if r1 < 1000000 goto pc-2
11077 * 1M insn_procssed limit / 100 == 10k peak states.
11078 * This threshold shouldn't be too high either, since states
11079 * at the end of the loop are likely to be useful in pruning.
11080 */
11081 if (env->jmps_processed - env->prev_jmps_processed < 20 &&
11082 env->insn_processed - env->prev_insn_processed < 100)
11083 add_new_state = false;
11084 goto miss;
11085 }
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070011086 if (states_equal(env, &sl->state, cur)) {
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011087 sl->hit_cnt++;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011088 /* reached equivalent register/stack state,
Edward Creedc503a82017-08-15 20:34:35 +010011089 * prune the search.
11090 * Registers read by the continuation are read by us.
Edward Cree8e9cd9c2017-08-23 15:11:21 +010011091 * If we have any write marks in env->cur_state, they
11092 * will prevent corresponding reads in the continuation
11093 * from reaching our parent (an explored_state). Our
11094 * own state will get the read marks recorded, but
11095 * they'll be immediately forgotten as we're pruning
11096 * this state and will pop a new one.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011097 */
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011098 err = propagate_liveness(env, &sl->state, cur);
Alexei Starovoitova3ce6852019-06-28 09:24:09 -070011099
11100 /* if previous state reached the exit with precision and
11101 * current state is equivalent to it (except precsion marks)
11102 * the precision needs to be propagated back in
11103 * the current state.
11104 */
11105 err = err ? : push_jmp_history(env, cur);
11106 err = err ? : propagate_precision(env, &sl->state);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011107 if (err)
11108 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011109 return 1;
Edward Creedc503a82017-08-15 20:34:35 +010011110 }
Alexei Starovoitov25897262019-06-15 12:12:20 -070011111miss:
11112 /* when new state is not going to be added do not increase miss count.
11113 * Otherwise several loop iterations will remove the state
11114 * recorded earlier. The goal of these heuristics is to have
11115 * states from some iterations of the loop (some in the beginning
11116 * and some at the end) to help pruning.
11117 */
11118 if (add_new_state)
11119 sl->miss_cnt++;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011120 /* heuristic to determine whether this state is beneficial
11121 * to keep checking from state equivalence point of view.
11122 * Higher numbers increase max_states_per_insn and verification time,
11123 * but do not meaningfully decrease insn_processed.
11124 */
11125 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
11126 /* the state is unlikely to be useful. Remove it to
11127 * speed up verification
11128 */
11129 *pprev = sl->next;
11130 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
Alexei Starovoitov25897262019-06-15 12:12:20 -070011131 u32 br = sl->state.branches;
11132
11133 WARN_ONCE(br,
11134 "BUG live_done but branches_to_explore %d\n",
11135 br);
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011136 free_verifier_state(&sl->state, false);
11137 kfree(sl);
11138 env->peak_states--;
11139 } else {
11140 /* cannot free this state, since parentage chain may
11141 * walk it later. Add it for free_list instead to
11142 * be freed at the end of verification
11143 */
11144 sl->next = env->free_list;
11145 env->free_list = sl;
11146 }
11147 sl = *pprev;
11148 continue;
11149 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011150next:
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070011151 pprev = &sl->next;
11152 sl = *pprev;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011153 }
11154
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011155 if (env->max_states_per_insn < states_cnt)
11156 env->max_states_per_insn = states_cnt;
11157
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070011158 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011159 return push_jmp_history(env, cur);
Alexei Starovoitovceefbc92018-12-03 22:46:06 -080011160
Alexei Starovoitov25897262019-06-15 12:12:20 -070011161 if (!add_new_state)
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011162 return push_jmp_history(env, cur);
Alexei Starovoitov25897262019-06-15 12:12:20 -070011163
11164 /* There were no equivalent states, remember the current one.
11165 * Technically the current state is not proven to be safe yet,
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011166 * but it will either reach outer most bpf_exit (which means it's safe)
Alexei Starovoitov25897262019-06-15 12:12:20 -070011167 * or it will be rejected. When there are no loops the verifier won't be
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011168 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
Alexei Starovoitov25897262019-06-15 12:12:20 -070011169 * again on the way to bpf_exit.
11170 * When looping the sl->state.branches will be > 0 and this state
11171 * will not be considered for equivalence until branches == 0.
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011172 */
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070011173 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011174 if (!new_sl)
11175 return -ENOMEM;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011176 env->total_states++;
11177 env->peak_states++;
Alexei Starovoitov25897262019-06-15 12:12:20 -070011178 env->prev_jmps_processed = env->jmps_processed;
11179 env->prev_insn_processed = env->insn_processed;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011180
11181 /* add new state to the head of linked list */
Edward Cree679c7822018-08-22 20:02:19 +010011182 new = &new_sl->state;
11183 err = copy_verifier_state(new, cur);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070011184 if (err) {
Edward Cree679c7822018-08-22 20:02:19 +010011185 free_verifier_state(new, false);
Alexei Starovoitov1969db42017-11-01 00:08:04 -070011186 kfree(new_sl);
11187 return err;
11188 }
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070011189 new->insn_idx = insn_idx;
Alexei Starovoitov25897262019-06-15 12:12:20 -070011190 WARN_ONCE(new->branches != 1,
11191 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011192
Alexei Starovoitov25897262019-06-15 12:12:20 -070011193 cur->parent = new;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011194 cur->first_insn_idx = insn_idx;
11195 clear_jmp_history(cur);
Alexei Starovoitov5d839022019-05-21 20:17:05 -070011196 new_sl->next = *explored_state(env, insn_idx);
11197 *explored_state(env, insn_idx) = new_sl;
Jakub Kicinski7640ead2018-12-12 16:29:07 -080011198 /* connect new state to parentage chain. Current frame needs all
11199 * registers connected. Only r6 - r9 of the callers are alive (pushed
11200 * to the stack implicitly by JITs) so in callers' frames connect just
11201 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
11202 * the state of the call instruction (with WRITTEN set), and r0 comes
11203 * from callee with its full parentage chain, anyway.
11204 */
Edward Cree8e9cd9c2017-08-23 15:11:21 +010011205 /* clear write marks in current state: the writes we did are not writes
11206 * our child did, so they don't screen off its reads from us.
11207 * (There are no read marks in current state, because reads always mark
11208 * their parent and current state never has children yet. Only
11209 * explored_states can get read marks.)
11210 */
Alexei Starovoitoveea1c222019-06-15 12:12:21 -070011211 for (j = 0; j <= cur->curframe; j++) {
11212 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
11213 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
11214 for (i = 0; i < BPF_REG_FP; i++)
11215 cur->frame[j]->regs[i].live = REG_LIVE_NONE;
11216 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011217
11218 /* all stack frames are accessible from callee, clear them all */
11219 for (j = 0; j <= cur->curframe; j++) {
11220 struct bpf_func_state *frame = cur->frame[j];
Edward Cree679c7822018-08-22 20:02:19 +010011221 struct bpf_func_state *newframe = new->frame[j];
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011222
Edward Cree679c7822018-08-22 20:02:19 +010011223 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
Alexei Starovoitovcc2b14d2017-12-14 17:55:08 -080011224 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
Edward Cree679c7822018-08-22 20:02:19 +010011225 frame->stack[i].spilled_ptr.parent =
11226 &newframe->stack[i].spilled_ptr;
11227 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011228 }
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011229 return 0;
11230}
11231
Joe Stringerc64b7982018-10-02 13:35:33 -070011232/* Return true if it's OK to have the same insn return a different type. */
11233static bool reg_type_mismatch_ok(enum bpf_reg_type type)
11234{
11235 switch (type) {
11236 case PTR_TO_CTX:
11237 case PTR_TO_SOCKET:
11238 case PTR_TO_SOCKET_OR_NULL:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080011239 case PTR_TO_SOCK_COMMON:
11240 case PTR_TO_SOCK_COMMON_OR_NULL:
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080011241 case PTR_TO_TCP_SOCK:
11242 case PTR_TO_TCP_SOCK_OR_NULL:
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070011243 case PTR_TO_XDP_SOCK:
Alexei Starovoitov2a027592019-10-15 20:25:02 -070011244 case PTR_TO_BTF_ID:
Yonghong Songb121b342020-05-09 10:59:12 -070011245 case PTR_TO_BTF_ID_OR_NULL:
Joe Stringerc64b7982018-10-02 13:35:33 -070011246 return false;
11247 default:
11248 return true;
11249 }
11250}
11251
11252/* If an instruction was previously used with particular pointer types, then we
11253 * need to be careful to avoid cases such as the below, where it may be ok
11254 * for one branch accessing the pointer, but not ok for the other branch:
11255 *
11256 * R1 = sock_ptr
11257 * goto X;
11258 * ...
11259 * R1 = some_other_valid_ptr;
11260 * goto X;
11261 * ...
11262 * R2 = *(u32 *)(R1 + 0);
11263 */
11264static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
11265{
11266 return src != prev && (!reg_type_mismatch_ok(src) ||
11267 !reg_type_mismatch_ok(prev));
11268}
11269
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010011270static int do_check(struct bpf_verifier_env *env)
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011271{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011272 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080011273 struct bpf_verifier_state *state = env->cur_state;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011274 struct bpf_insn *insns = env->prog->insnsi;
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070011275 struct bpf_reg_state *regs;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011276 int insn_cnt = env->prog->len;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011277 bool do_print_state = false;
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011278 int prev_insn_idx = -1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011279
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011280 for (;;) {
11281 struct bpf_insn *insn;
11282 u8 class;
11283 int err;
11284
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011285 env->prev_insn_idx = prev_insn_idx;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011286 if (env->insn_idx >= insn_cnt) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011287 verbose(env, "invalid insn idx %d insn_cnt %d\n",
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011288 env->insn_idx, insn_cnt);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011289 return -EFAULT;
11290 }
11291
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011292 insn = &insns[env->insn_idx];
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011293 class = BPF_CLASS(insn->code);
11294
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011295 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011296 verbose(env,
11297 "BPF program is too large. Processed %d insn\n",
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011298 env->insn_processed);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011299 return -E2BIG;
11300 }
11301
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011302 err = is_state_visited(env, env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011303 if (err < 0)
11304 return err;
11305 if (err == 1) {
11306 /* found equivalent state, can prune the search */
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011307 if (env->log.level & BPF_LOG_LEVEL) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011308 if (do_print_state)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010011309 verbose(env, "\nfrom %d to %d%s: safe\n",
11310 env->prev_insn_idx, env->insn_idx,
11311 env->cur_state->speculative ?
11312 " (speculative execution)" : "");
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011313 else
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011314 verbose(env, "%d: safe\n", env->insn_idx);
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011315 }
11316 goto process_bpf_exit;
11317 }
11318
Alexei Starovoitovc3494802018-12-03 22:46:04 -080011319 if (signal_pending(current))
11320 return -EAGAIN;
11321
Daniel Borkmann3c2ce602017-05-18 03:00:06 +020011322 if (need_resched())
11323 cond_resched();
11324
Christy Lee2e576642021-12-16 19:42:45 -080011325 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
11326 verbose(env, "\nfrom %d to %d%s:",
11327 env->prev_insn_idx, env->insn_idx,
11328 env->cur_state->speculative ?
11329 " (speculative execution)" : "");
11330 print_verifier_state(env, state->frame[state->curframe], true);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011331 do_print_state = false;
11332 }
11333
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070011334 if (env->log.level & BPF_LOG_LEVEL) {
Daniel Borkmann7105e822017-12-20 13:42:57 +010011335 const struct bpf_insn_cbs cbs = {
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070011336 .cb_call = disasm_kfunc_name,
Daniel Borkmann7105e822017-12-20 13:42:57 +010011337 .cb_print = verbose,
Jiri Olsaabe08842018-03-23 11:41:28 +010011338 .private_data = env,
Daniel Borkmann7105e822017-12-20 13:42:57 +010011339 };
11340
Christy Lee2e576642021-12-16 19:42:45 -080011341 if (verifier_state_scratched(env))
11342 print_insn_state(env, state->frame[state->curframe]);
11343
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011344 verbose_linfo(env, env->insn_idx, "; ");
Christy Lee2e576642021-12-16 19:42:45 -080011345 env->prev_log_len = env->log.len_used;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011346 verbose(env, "%d: ", env->insn_idx);
Jiri Olsaabe08842018-03-23 11:41:28 +010011347 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
Christy Lee2e576642021-12-16 19:42:45 -080011348 env->prev_insn_print_len = env->log.len_used - env->prev_log_len;
11349 env->prev_log_len = env->log.len_used;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011350 }
11351
Jakub Kicinskicae19272017-12-27 18:39:05 -080011352 if (bpf_prog_is_dev_bound(env->prog->aux)) {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011353 err = bpf_prog_offload_verify_insn(env, env->insn_idx,
11354 env->prev_insn_idx);
Jakub Kicinskicae19272017-12-27 18:39:05 -080011355 if (err)
11356 return err;
11357 }
Jakub Kicinski13a27df2016-09-21 11:43:58 +010011358
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070011359 regs = cur_regs(env);
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +000011360 sanitize_mark_insn_seen(env);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011361 prev_insn_idx = env->insn_idx;
Joe Stringerfd978bf72018-10-02 13:35:35 -070011362
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011363 if (class == BPF_ALU || class == BPF_ALU64) {
Alexei Starovoitov1be7f752015-10-07 22:23:21 -070011364 err = check_alu_op(env, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011365 if (err)
11366 return err;
11367
11368 } else if (class == BPF_LDX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011369 enum bpf_reg_type *prev_src_type, src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011370
11371 /* check for reserved fields is already done */
11372
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011373 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010011374 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011375 if (err)
11376 return err;
11377
Edward Creedc503a82017-08-15 20:34:35 +010011378 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011379 if (err)
11380 return err;
11381
Alexei Starovoitov725f9dc2015-04-15 16:19:33 -070011382 src_reg_type = regs[insn->src_reg].type;
11383
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011384 /* check that memory (src_reg + off) is readable,
11385 * the state of dst_reg will be updated by this func
11386 */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011387 err = check_mem_access(env, env->insn_idx, insn->src_reg,
11388 insn->off, BPF_SIZE(insn->code),
11389 BPF_READ, insn->dst_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011390 if (err)
11391 return err;
11392
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011393 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011394
11395 if (*prev_src_type == NOT_INIT) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011396 /* saw a valid insn
11397 * dst_reg = *(u32 *)(src_reg + off)
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011398 * save type to validate intersecting paths
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011399 */
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011400 *prev_src_type = src_reg_type;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011401
Joe Stringerc64b7982018-10-02 13:35:33 -070011402 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011403 /* ABuser program is trying to use the same insn
11404 * dst_reg = *(u32*) (src_reg + off)
11405 * with different pointer types:
11406 * src_reg == ctx in one branch and
11407 * src_reg == stack|map in some other branch.
11408 * Reject it.
11409 */
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011410 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011411 return -EINVAL;
11412 }
11413
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011414 } else if (class == BPF_STX) {
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011415 enum bpf_reg_type *prev_dst_type, dst_reg_type;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011416
Brendan Jackman91c960b2021-01-14 18:17:44 +000011417 if (BPF_MODE(insn->code) == BPF_ATOMIC) {
11418 err = check_atomic(env, env->insn_idx, insn);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011419 if (err)
11420 return err;
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011421 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011422 continue;
11423 }
11424
Brendan Jackman5ca419f2021-01-14 18:17:46 +000011425 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
11426 verbose(env, "BPF_STX uses reserved fields\n");
11427 return -EINVAL;
11428 }
11429
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011430 /* check src1 operand */
Edward Creedc503a82017-08-15 20:34:35 +010011431 err = check_reg_arg(env, insn->src_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011432 if (err)
11433 return err;
11434 /* check src2 operand */
Edward Creedc503a82017-08-15 20:34:35 +010011435 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011436 if (err)
11437 return err;
11438
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011439 dst_reg_type = regs[insn->dst_reg].type;
11440
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011441 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011442 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11443 insn->off, BPF_SIZE(insn->code),
11444 BPF_WRITE, insn->src_reg, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011445 if (err)
11446 return err;
11447
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011448 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010011449
11450 if (*prev_dst_type == NOT_INIT) {
11451 *prev_dst_type = dst_reg_type;
Joe Stringerc64b7982018-10-02 13:35:33 -070011452 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011453 verbose(env, "same insn cannot be used with different pointers\n");
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011454 return -EINVAL;
11455 }
11456
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011457 } else if (class == BPF_ST) {
11458 if (BPF_MODE(insn->code) != BPF_MEM ||
11459 insn->src_reg != BPF_REG_0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011460 verbose(env, "BPF_ST uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011461 return -EINVAL;
11462 }
11463 /* check src operand */
Edward Creedc503a82017-08-15 20:34:35 +010011464 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011465 if (err)
11466 return err;
11467
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010011468 if (is_ctx_reg(env, insn->dst_reg)) {
Joe Stringer9d2be442018-10-02 13:35:31 -070011469 verbose(env, "BPF_ST stores into R%d %s is not allowed\n",
Daniel Borkmann2a159c62018-10-21 02:09:24 +020011470 insn->dst_reg,
11471 reg_type_str[reg_state(env, insn->dst_reg)->type]);
Daniel Borkmannf37a8cb2018-01-16 23:30:10 +010011472 return -EACCES;
11473 }
11474
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011475 /* check that memory (dst_reg + off) is writeable */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011476 err = check_mem_access(env, env->insn_idx, insn->dst_reg,
11477 insn->off, BPF_SIZE(insn->code),
11478 BPF_WRITE, -1, false);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011479 if (err)
11480 return err;
11481
Jiong Wang092ed092019-01-26 12:26:01 -050011482 } else if (class == BPF_JMP || class == BPF_JMP32) {
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011483 u8 opcode = BPF_OP(insn->code);
11484
Alexei Starovoitov25897262019-06-15 12:12:20 -070011485 env->jmps_processed++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011486 if (opcode == BPF_CALL) {
11487 if (BPF_SRC(insn->code) != BPF_K ||
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +053011488 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
11489 && insn->off != 0) ||
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011490 (insn->src_reg != BPF_REG_0 &&
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070011491 insn->src_reg != BPF_PSEUDO_CALL &&
11492 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
Jiong Wang092ed092019-01-26 12:26:01 -050011493 insn->dst_reg != BPF_REG_0 ||
11494 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011495 verbose(env, "BPF_CALL uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011496 return -EINVAL;
11497 }
11498
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011499 if (env->cur_state->active_spin_lock &&
11500 (insn->src_reg == BPF_PSEUDO_CALL ||
11501 insn->imm != BPF_FUNC_spin_unlock)) {
11502 verbose(env, "function calls are not allowed while holding a lock\n");
11503 return -EINVAL;
11504 }
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011505 if (insn->src_reg == BPF_PSEUDO_CALL)
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011506 err = check_func_call(env, insn, &env->insn_idx);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070011507 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
11508 err = check_kfunc_call(env, insn);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011509 else
Yonghong Song69c087b2021-02-26 12:49:25 -080011510 err = check_helper_call(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011511 if (err)
11512 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011513 } else if (opcode == BPF_JA) {
11514 if (BPF_SRC(insn->code) != BPF_K ||
11515 insn->imm != 0 ||
11516 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050011517 insn->dst_reg != BPF_REG_0 ||
11518 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011519 verbose(env, "BPF_JA uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011520 return -EINVAL;
11521 }
11522
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011523 env->insn_idx += insn->off + 1;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011524 continue;
11525
11526 } else if (opcode == BPF_EXIT) {
11527 if (BPF_SRC(insn->code) != BPF_K ||
11528 insn->imm != 0 ||
11529 insn->src_reg != BPF_REG_0 ||
Jiong Wang092ed092019-01-26 12:26:01 -050011530 insn->dst_reg != BPF_REG_0 ||
11531 class == BPF_JMP32) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011532 verbose(env, "BPF_EXIT uses reserved fields\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011533 return -EINVAL;
11534 }
11535
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011536 if (env->cur_state->active_spin_lock) {
11537 verbose(env, "bpf_spin_unlock is missing\n");
11538 return -EINVAL;
11539 }
11540
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011541 if (state->curframe) {
11542 /* exit from nested function */
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011543 err = prepare_func_exit(env, &env->insn_idx);
Alexei Starovoitovf4d7e402017-12-14 17:55:06 -080011544 if (err)
11545 return err;
11546 do_print_state = true;
11547 continue;
11548 }
11549
Joe Stringerfd978bf72018-10-02 13:35:35 -070011550 err = check_reference_leak(env);
11551 if (err)
11552 return err;
11553
Alexei Starovoitov390ee7e2017-10-02 22:50:23 -070011554 err = check_return_code(env);
11555 if (err)
11556 return err;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070011557process_bpf_exit:
Christy Lee0f55f9e2021-12-16 13:33:56 -080011558 mark_verifier_state_scratched(env);
Alexei Starovoitov25897262019-06-15 12:12:20 -070011559 update_branch_counts(env, env->cur_state);
Alexei Starovoitovb5dc0162019-06-15 12:12:25 -070011560 err = pop_stack(env, &prev_insn_idx,
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070011561 &env->insn_idx, pop_log);
Alexei Starovoitov638f5b92017-10-31 18:16:05 -070011562 if (err < 0) {
11563 if (err != -ENOENT)
11564 return err;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011565 break;
11566 } else {
11567 do_print_state = true;
11568 continue;
11569 }
11570 } else {
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011571 err = check_cond_jmp_op(env, insn, &env->insn_idx);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011572 if (err)
11573 return err;
11574 }
11575 } else if (class == BPF_LD) {
11576 u8 mode = BPF_MODE(insn->code);
11577
11578 if (mode == BPF_ABS || mode == BPF_IND) {
Alexei Starovoitovddd872b2014-12-01 15:06:34 -080011579 err = check_ld_abs(env, insn);
11580 if (err)
11581 return err;
11582
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011583 } else if (mode == BPF_IMM) {
11584 err = check_ld_imm(env, insn);
11585 if (err)
11586 return err;
11587
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011588 env->insn_idx++;
Daniel Borkmannfe9a5ca2021-05-28 13:47:27 +000011589 sanitize_mark_insn_seen(env);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011590 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011591 verbose(env, "invalid BPF_LD mode\n");
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011592 return -EINVAL;
11593 }
11594 } else {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011595 verbose(env, "unknown insn class %d\n", class);
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011596 return -EINVAL;
11597 }
11598
Daniel Borkmannc08435e2019-01-03 00:58:27 +010011599 env->insn_idx++;
Alexei Starovoitov17a52672014-09-26 00:17:06 -070011600 }
11601
11602 return 0;
11603}
11604
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011605static int find_btf_percpu_datasec(struct btf *btf)
11606{
11607 const struct btf_type *t;
11608 const char *tname;
11609 int i, n;
11610
11611 /*
11612 * Both vmlinux and module each have their own ".data..percpu"
11613 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
11614 * types to look at only module's own BTF types.
11615 */
11616 n = btf_nr_types(btf);
11617 if (btf_is_module(btf))
11618 i = btf_nr_types(btf_vmlinux);
11619 else
11620 i = 1;
11621
11622 for(; i < n; i++) {
11623 t = btf_type_by_id(btf, i);
11624 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
11625 continue;
11626
11627 tname = btf_name_by_offset(btf, t->name_off);
11628 if (!strcmp(tname, ".data..percpu"))
11629 return i;
11630 }
11631
11632 return -ENOENT;
11633}
11634
Hao Luo4976b712020-09-29 16:50:44 -070011635/* replace pseudo btf_id with kernel symbol address */
11636static int check_pseudo_btf_id(struct bpf_verifier_env *env,
11637 struct bpf_insn *insn,
11638 struct bpf_insn_aux_data *aux)
11639{
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011640 const struct btf_var_secinfo *vsi;
11641 const struct btf_type *datasec;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011642 struct btf_mod_pair *btf_mod;
Hao Luo4976b712020-09-29 16:50:44 -070011643 const struct btf_type *t;
11644 const char *sym_name;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011645 bool percpu = false;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080011646 u32 type, id = insn->imm;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011647 struct btf *btf;
Kaixu Xiaf16e6312020-11-11 13:03:46 +080011648 s32 datasec_id;
Hao Luo4976b712020-09-29 16:50:44 -070011649 u64 addr;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011650 int i, btf_fd, err;
Hao Luo4976b712020-09-29 16:50:44 -070011651
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011652 btf_fd = insn[1].imm;
11653 if (btf_fd) {
11654 btf = btf_get_by_fd(btf_fd);
11655 if (IS_ERR(btf)) {
11656 verbose(env, "invalid module BTF object FD specified.\n");
11657 return -EINVAL;
11658 }
11659 } else {
11660 if (!btf_vmlinux) {
11661 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
11662 return -EINVAL;
11663 }
11664 btf = btf_vmlinux;
11665 btf_get(btf);
Hao Luo4976b712020-09-29 16:50:44 -070011666 }
11667
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011668 t = btf_type_by_id(btf, id);
Hao Luo4976b712020-09-29 16:50:44 -070011669 if (!t) {
11670 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011671 err = -ENOENT;
11672 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070011673 }
11674
11675 if (!btf_type_is_var(t)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011676 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
11677 err = -EINVAL;
11678 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070011679 }
11680
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011681 sym_name = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070011682 addr = kallsyms_lookup_name(sym_name);
11683 if (!addr) {
11684 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
11685 sym_name);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011686 err = -ENOENT;
11687 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070011688 }
11689
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011690 datasec_id = find_btf_percpu_datasec(btf);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011691 if (datasec_id > 0) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011692 datasec = btf_type_by_id(btf, datasec_id);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011693 for_each_vsi(i, datasec, vsi) {
11694 if (vsi->type == id) {
11695 percpu = true;
11696 break;
11697 }
11698 }
11699 }
11700
Hao Luo4976b712020-09-29 16:50:44 -070011701 insn[0].imm = (u32)addr;
11702 insn[1].imm = addr >> 32;
11703
11704 type = t->type;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011705 t = btf_type_skip_modifiers(btf, type, NULL);
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011706 if (percpu) {
11707 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011708 aux->btf_var.btf = btf;
Hao Luoeaa6bcb2020-09-29 16:50:47 -070011709 aux->btf_var.btf_id = type;
11710 } else if (!btf_type_is_struct(t)) {
Hao Luo4976b712020-09-29 16:50:44 -070011711 const struct btf_type *ret;
11712 const char *tname;
11713 u32 tsize;
11714
11715 /* resolve the type size of ksym. */
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011716 ret = btf_resolve_size(btf, t, &tsize);
Hao Luo4976b712020-09-29 16:50:44 -070011717 if (IS_ERR(ret)) {
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011718 tname = btf_name_by_offset(btf, t->name_off);
Hao Luo4976b712020-09-29 16:50:44 -070011719 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
11720 tname, PTR_ERR(ret));
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011721 err = -EINVAL;
11722 goto err_put;
Hao Luo4976b712020-09-29 16:50:44 -070011723 }
11724 aux->btf_var.reg_type = PTR_TO_MEM;
11725 aux->btf_var.mem_size = tsize;
11726 } else {
11727 aux->btf_var.reg_type = PTR_TO_BTF_ID;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011728 aux->btf_var.btf = btf;
Hao Luo4976b712020-09-29 16:50:44 -070011729 aux->btf_var.btf_id = type;
11730 }
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011731
11732 /* check whether we recorded this BTF (and maybe module) already */
11733 for (i = 0; i < env->used_btf_cnt; i++) {
11734 if (env->used_btfs[i].btf == btf) {
11735 btf_put(btf);
11736 return 0;
11737 }
11738 }
11739
11740 if (env->used_btf_cnt >= MAX_USED_BTFS) {
11741 err = -E2BIG;
11742 goto err_put;
11743 }
11744
11745 btf_mod = &env->used_btfs[env->used_btf_cnt];
11746 btf_mod->btf = btf;
11747 btf_mod->module = NULL;
11748
11749 /* if we reference variables from kernel module, bump its refcount */
11750 if (btf_is_module(btf)) {
11751 btf_mod->module = btf_try_get_module(btf);
11752 if (!btf_mod->module) {
11753 err = -ENXIO;
11754 goto err_put;
11755 }
11756 }
11757
11758 env->used_btf_cnt++;
11759
Hao Luo4976b712020-09-29 16:50:44 -070011760 return 0;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080011761err_put:
11762 btf_put(btf);
11763 return err;
Hao Luo4976b712020-09-29 16:50:44 -070011764}
11765
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011766static int check_map_prealloc(struct bpf_map *map)
11767{
11768 return (map->map_type != BPF_MAP_TYPE_HASH &&
Martin KaFai Laubcc6b1b2017-03-22 10:00:34 -070011769 map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
11770 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) ||
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011771 !(map->map_flags & BPF_F_NO_PREALLOC);
11772}
11773
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011774static bool is_tracing_prog_type(enum bpf_prog_type type)
11775{
11776 switch (type) {
11777 case BPF_PROG_TYPE_KPROBE:
11778 case BPF_PROG_TYPE_TRACEPOINT:
11779 case BPF_PROG_TYPE_PERF_EVENT:
11780 case BPF_PROG_TYPE_RAW_TRACEPOINT:
11781 return true;
11782 default:
11783 return false;
11784 }
11785}
11786
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011787static bool is_preallocated_map(struct bpf_map *map)
11788{
11789 if (!check_map_prealloc(map))
11790 return false;
11791 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta))
11792 return false;
11793 return true;
11794}
11795
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011796static int check_map_prog_compatibility(struct bpf_verifier_env *env,
11797 struct bpf_map *map,
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011798 struct bpf_prog *prog)
11799
11800{
Udip Pant7e407812020-08-25 16:20:00 -070011801 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011802 /*
11803 * Validate that trace type programs use preallocated hash maps.
11804 *
11805 * For programs attached to PERF events this is mandatory as the
11806 * perf NMI can hit any arbitrary code sequence.
11807 *
11808 * All other trace types using preallocated hash maps are unsafe as
11809 * well because tracepoint or kprobes can be inside locked regions
11810 * of the memory allocator or at a place where a recursion into the
11811 * memory allocator would see inconsistent state.
11812 *
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011813 * On RT enabled kernels run-time allocation of all trace type
11814 * programs is strictly prohibited due to lock type constraints. On
11815 * !RT kernels it is allowed for backwards compatibility reasons for
11816 * now, but warnings are emitted so developers are made aware of
11817 * the unsafety and can fix their programs before this is enforced.
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011818 */
Udip Pant7e407812020-08-25 16:20:00 -070011819 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) {
11820 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011821 verbose(env, "perf_event programs can only use preallocated hash map\n");
Martin KaFai Lau56f668d2017-03-22 10:00:33 -070011822 return -EINVAL;
11823 }
Thomas Gleixner2ed905c2020-02-24 15:01:33 +010011824 if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
11825 verbose(env, "trace type programs can only use preallocated hash map\n");
11826 return -EINVAL;
11827 }
Thomas Gleixner94dacdb2020-02-24 15:01:32 +010011828 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n");
11829 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 -070011830 }
Jakub Kicinskia3884572018-01-11 20:29:09 -080011831
KP Singh9e7a4d92020-11-06 10:37:39 +000011832 if (map_value_has_spin_lock(map)) {
11833 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
11834 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
11835 return -EINVAL;
11836 }
11837
11838 if (is_tracing_prog_type(prog_type)) {
11839 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
11840 return -EINVAL;
11841 }
11842
11843 if (prog->aux->sleepable) {
11844 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
11845 return -EINVAL;
11846 }
Alexei Starovoitovd83525c2019-01-31 15:40:04 -080011847 }
11848
Dmitrii Banshchikov5e0bc302021-11-13 18:22:26 +040011849 if (map_value_has_timer(map)) {
11850 if (is_tracing_prog_type(prog_type)) {
11851 verbose(env, "tracing progs cannot use bpf_timer yet\n");
11852 return -EINVAL;
11853 }
11854 }
11855
Jakub Kicinskia3884572018-01-11 20:29:09 -080011856 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) &&
Jakub Kicinski09728262018-07-17 10:53:23 -070011857 !bpf_offload_prog_map_match(prog, map)) {
Jakub Kicinskia3884572018-01-11 20:29:09 -080011858 verbose(env, "offload device mismatch between prog and map\n");
11859 return -EINVAL;
11860 }
11861
Martin KaFai Lau85d33df2020-01-08 16:35:05 -080011862 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
11863 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
11864 return -EINVAL;
11865 }
11866
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011867 if (prog->aux->sleepable)
11868 switch (map->map_type) {
11869 case BPF_MAP_TYPE_HASH:
11870 case BPF_MAP_TYPE_LRU_HASH:
11871 case BPF_MAP_TYPE_ARRAY:
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011872 case BPF_MAP_TYPE_PERCPU_HASH:
11873 case BPF_MAP_TYPE_PERCPU_ARRAY:
11874 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
11875 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
11876 case BPF_MAP_TYPE_HASH_OF_MAPS:
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011877 if (!is_preallocated_map(map)) {
11878 verbose(env,
Alexei Starovoitov638e4b82021-02-09 19:36:33 -080011879 "Sleepable programs can only use preallocated maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011880 return -EINVAL;
11881 }
11882 break;
KP Singhba90c2c2021-02-04 19:36:21 +000011883 case BPF_MAP_TYPE_RINGBUF:
11884 break;
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011885 default:
11886 verbose(env,
KP Singhba90c2c2021-02-04 19:36:21 +000011887 "Sleepable programs can only use array, hash, and ringbuf maps\n");
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070011888 return -EINVAL;
11889 }
11890
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011891 return 0;
11892}
11893
Roman Gushchinb741f162018-09-28 14:45:43 +000011894static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
11895{
11896 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
11897 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
11898}
11899
Hao Luo4976b712020-09-29 16:50:44 -070011900/* find and rewrite pseudo imm in ld_imm64 instructions:
11901 *
11902 * 1. if it accesses map FD, replace it with actual map pointer.
11903 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
11904 *
11905 * NOTE: btf_vmlinux is required for converting pseudo btf_id.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011906 */
Hao Luo4976b712020-09-29 16:50:44 -070011907static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011908{
11909 struct bpf_insn *insn = env->prog->insnsi;
11910 int insn_cnt = env->prog->len;
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011911 int i, j, err;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011912
Daniel Borkmannf1f77142017-01-13 23:38:15 +010011913 err = bpf_prog_calc_tag(env->prog);
Daniel Borkmannaafe6ae2016-12-18 01:52:57 +010011914 if (err)
11915 return err;
11916
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011917 for (i = 0; i < insn_cnt; i++, insn++) {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011918 if (BPF_CLASS(insn->code) == BPF_LDX &&
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070011919 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011920 verbose(env, "BPF_LDX uses reserved fields\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070011921 return -EINVAL;
11922 }
11923
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011924 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011925 struct bpf_insn_aux_data *aux;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011926 struct bpf_map *map;
11927 struct fd f;
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011928 u64 addr;
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011929 u32 fd;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011930
11931 if (i == insn_cnt - 1 || insn[1].code != 0 ||
11932 insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
11933 insn[1].off != 0) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011934 verbose(env, "invalid bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011935 return -EINVAL;
11936 }
11937
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011938 if (insn[0].src_reg == 0)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011939 /* valid generic load 64-bit imm */
11940 goto next_insn;
11941
Hao Luo4976b712020-09-29 16:50:44 -070011942 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
11943 aux = &env->insn_aux_data[i];
11944 err = check_pseudo_btf_id(env, insn, aux);
11945 if (err)
11946 return err;
11947 goto next_insn;
11948 }
11949
Yonghong Song69c087b2021-02-26 12:49:25 -080011950 if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
11951 aux = &env->insn_aux_data[i];
11952 aux->ptr_type = PTR_TO_FUNC;
11953 goto next_insn;
11954 }
11955
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020011956 /* In final convert_pseudo_ld_imm64() step, this is
11957 * converted into regular 64-bit imm load insn.
11958 */
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011959 switch (insn[0].src_reg) {
11960 case BPF_PSEUDO_MAP_VALUE:
11961 case BPF_PSEUDO_MAP_IDX_VALUE:
11962 break;
11963 case BPF_PSEUDO_MAP_FD:
11964 case BPF_PSEUDO_MAP_IDX:
11965 if (insn[1].imm == 0)
11966 break;
11967 fallthrough;
11968 default:
11969 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011970 return -EINVAL;
11971 }
11972
Alexei Starovoitov387544b2021-05-13 17:36:10 -070011973 switch (insn[0].src_reg) {
11974 case BPF_PSEUDO_MAP_IDX_VALUE:
11975 case BPF_PSEUDO_MAP_IDX:
11976 if (bpfptr_is_null(env->fd_array)) {
11977 verbose(env, "fd_idx without fd_array is invalid\n");
11978 return -EPROTO;
11979 }
11980 if (copy_from_bpfptr_offset(&fd, env->fd_array,
11981 insn[0].imm * sizeof(fd),
11982 sizeof(fd)))
11983 return -EFAULT;
11984 break;
11985 default:
11986 fd = insn[0].imm;
11987 break;
11988 }
11989
11990 f = fdget(fd);
Daniel Borkmannc2101292015-10-29 14:58:07 +010011991 map = __bpf_map_get(f);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011992 if (IS_ERR(map)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011993 verbose(env, "fd %d is not pointing to valid bpf_map\n",
Daniel Borkmann20182392019-03-04 21:08:53 +010011994 insn[0].imm);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070011995 return PTR_ERR(map);
11996 }
11997
Jakub Kicinski61bd5212017-10-09 10:30:11 -070011998 err = check_map_prog_compatibility(env, map, env->prog);
Alexei Starovoitovfdc15d32016-09-01 18:37:23 -070011999 if (err) {
12000 fdput(f);
12001 return err;
12002 }
12003
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012004 aux = &env->insn_aux_data[i];
Alexei Starovoitov387544b2021-05-13 17:36:10 -070012005 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
12006 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012007 addr = (unsigned long)map;
12008 } else {
12009 u32 off = insn[1].imm;
12010
12011 if (off >= BPF_MAX_VAR_OFF) {
12012 verbose(env, "direct value offset of %u is not allowed\n", off);
12013 fdput(f);
12014 return -EINVAL;
12015 }
12016
12017 if (!map->ops->map_direct_value_addr) {
12018 verbose(env, "no direct value access support for this map type\n");
12019 fdput(f);
12020 return -EINVAL;
12021 }
12022
12023 err = map->ops->map_direct_value_addr(map, &addr, off);
12024 if (err) {
12025 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
12026 map->value_size, off);
12027 fdput(f);
12028 return err;
12029 }
12030
12031 aux->map_off = off;
12032 addr += off;
12033 }
12034
12035 insn[0].imm = (u32)addr;
12036 insn[1].imm = addr >> 32;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012037
12038 /* check whether we recorded this map already */
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012039 for (j = 0; j < env->used_map_cnt; j++) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012040 if (env->used_maps[j] == map) {
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012041 aux->map_index = j;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012042 fdput(f);
12043 goto next_insn;
12044 }
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012045 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012046
12047 if (env->used_map_cnt >= MAX_USED_MAPS) {
12048 fdput(f);
12049 return -E2BIG;
12050 }
12051
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012052 /* hold the map. If the program is rejected by verifier,
12053 * the map will be released by release_maps() or it
12054 * will be used by the valid program until it's unloaded
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070012055 * and all maps are released in free_used_maps()
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012056 */
Andrii Nakryiko1e0bd5a2019-11-17 09:28:02 -080012057 bpf_map_inc(map);
Daniel Borkmannd8eca5b2019-04-09 23:20:03 +020012058
12059 aux->map_index = env->used_map_cnt;
Alexei Starovoitov92117d82016-04-27 18:56:20 -070012060 env->used_maps[env->used_map_cnt++] = map;
12061
Roman Gushchinb741f162018-09-28 14:45:43 +000012062 if (bpf_map_is_cgroup_storage(map) &&
Daniel Borkmanne4730422019-12-17 13:28:16 +010012063 bpf_cgroup_storage_assign(env->prog->aux, map)) {
Roman Gushchinb741f162018-09-28 14:45:43 +000012064 verbose(env, "only one cgroup storage of each type is allowed\n");
Roman Gushchinde9cbba2018-08-02 14:27:18 -070012065 fdput(f);
12066 return -EBUSY;
12067 }
12068
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012069 fdput(f);
12070next_insn:
12071 insn++;
12072 i++;
Daniel Borkmann5e581da2018-01-26 23:33:38 +010012073 continue;
12074 }
12075
12076 /* Basic sanity check before we invest more work here. */
12077 if (!bpf_opcode_in_insntable(insn->code)) {
12078 verbose(env, "unknown opcode %02x\n", insn->code);
12079 return -EINVAL;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012080 }
12081 }
12082
12083 /* now all pseudo BPF_LD_IMM64 instructions load valid
12084 * 'struct bpf_map *' into a register instead of user map_fd.
12085 * These pointers will be used later by verifier to validate map access.
12086 */
12087 return 0;
12088}
12089
12090/* drop refcnt of maps used by the rejected program */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012091static void release_maps(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012092{
Daniel Borkmanna2ea0742019-12-16 17:49:00 +010012093 __bpf_free_used_maps(env->prog->aux, env->used_maps,
12094 env->used_map_cnt);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012095}
12096
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080012097/* drop refcnt of maps used by the rejected program */
12098static void release_btfs(struct bpf_verifier_env *env)
12099{
12100 __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
12101 env->used_btf_cnt);
12102}
12103
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012104/* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012105static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012106{
12107 struct bpf_insn *insn = env->prog->insnsi;
12108 int insn_cnt = env->prog->len;
12109 int i;
12110
Yonghong Song69c087b2021-02-26 12:49:25 -080012111 for (i = 0; i < insn_cnt; i++, insn++) {
12112 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
12113 continue;
12114 if (insn->src_reg == BPF_PSEUDO_FUNC)
12115 continue;
12116 insn->src_reg = 0;
12117 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070012118}
12119
Alexei Starovoitov80419022017-03-15 18:26:41 -070012120/* single env->prog->insni[off] instruction was replaced with the range
12121 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying
12122 * [0, off) and [off, end) to new locations, so the patched range stays zero
12123 */
He Fengqing75f0fc72021-07-14 10:18:15 +000012124static void adjust_insn_aux_data(struct bpf_verifier_env *env,
12125 struct bpf_insn_aux_data *new_data,
12126 struct bpf_prog *new_prog, u32 off, u32 cnt)
Alexei Starovoitov80419022017-03-15 18:26:41 -070012127{
He Fengqing75f0fc72021-07-14 10:18:15 +000012128 struct bpf_insn_aux_data *old_data = env->insn_aux_data;
Jiong Wangb325fbc2019-05-24 23:25:13 +010012129 struct bpf_insn *insn = new_prog->insnsi;
Daniel Borkmannd203b0f2021-05-28 13:03:30 +000012130 u32 old_seen = old_data[off].seen;
Jiong Wangb325fbc2019-05-24 23:25:13 +010012131 u32 prog_len;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080012132 int i;
Alexei Starovoitov80419022017-03-15 18:26:41 -070012133
Jiong Wangb325fbc2019-05-24 23:25:13 +010012134 /* aux info at OFF always needs adjustment, no matter fast path
12135 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
12136 * original insn at old prog.
12137 */
12138 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
12139
Alexei Starovoitov80419022017-03-15 18:26:41 -070012140 if (cnt == 1)
He Fengqing75f0fc72021-07-14 10:18:15 +000012141 return;
Jiong Wangb325fbc2019-05-24 23:25:13 +010012142 prog_len = new_prog->len;
He Fengqing75f0fc72021-07-14 10:18:15 +000012143
Alexei Starovoitov80419022017-03-15 18:26:41 -070012144 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
12145 memcpy(new_data + off + cnt - 1, old_data + off,
12146 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
Jiong Wangb325fbc2019-05-24 23:25:13 +010012147 for (i = off; i < off + cnt - 1; i++) {
Daniel Borkmannd203b0f2021-05-28 13:03:30 +000012148 /* Expand insni[off]'s seen count to the patched range. */
12149 new_data[i].seen = old_seen;
Jiong Wangb325fbc2019-05-24 23:25:13 +010012150 new_data[i].zext_dst = insn_has_def32(env, insn + i);
12151 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070012152 env->insn_aux_data = new_data;
12153 vfree(old_data);
Alexei Starovoitov80419022017-03-15 18:26:41 -070012154}
12155
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012156static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
12157{
12158 int i;
12159
12160 if (len == 1)
12161 return;
Jiong Wang4cb3d992018-05-02 16:17:19 -040012162 /* NOTE: fake 'exit' subprog should be updated as well. */
12163 for (i = 0; i <= env->subprog_cnt; i++) {
Edward Creeafd59422018-11-16 12:00:07 +000012164 if (env->subprog_info[i].start <= off)
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012165 continue;
Jiong Wang9c8105b2018-05-02 16:17:18 -040012166 env->subprog_info[i].start += len - 1;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012167 }
12168}
12169
John Fastabend7506d212021-06-16 15:55:00 -070012170static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012171{
12172 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
12173 int i, sz = prog->aux->size_poke_tab;
12174 struct bpf_jit_poke_descriptor *desc;
12175
12176 for (i = 0; i < sz; i++) {
12177 desc = &tab[i];
John Fastabend7506d212021-06-16 15:55:00 -070012178 if (desc->insn_idx <= off)
12179 continue;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012180 desc->insn_idx += len - 1;
12181 }
12182}
12183
Alexei Starovoitov80419022017-03-15 18:26:41 -070012184static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
12185 const struct bpf_insn *patch, u32 len)
12186{
12187 struct bpf_prog *new_prog;
He Fengqing75f0fc72021-07-14 10:18:15 +000012188 struct bpf_insn_aux_data *new_data = NULL;
12189
12190 if (len > 1) {
12191 new_data = vzalloc(array_size(env->prog->len + len - 1,
12192 sizeof(struct bpf_insn_aux_data)));
12193 if (!new_data)
12194 return NULL;
12195 }
Alexei Starovoitov80419022017-03-15 18:26:41 -070012196
12197 new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
Alexei Starovoitov4f733792019-04-01 21:27:44 -070012198 if (IS_ERR(new_prog)) {
12199 if (PTR_ERR(new_prog) == -ERANGE)
12200 verbose(env,
12201 "insn %d cannot be patched due to 16-bit range\n",
12202 env->insn_aux_data[off].orig_idx);
He Fengqing75f0fc72021-07-14 10:18:15 +000012203 vfree(new_data);
Alexei Starovoitov80419022017-03-15 18:26:41 -070012204 return NULL;
Alexei Starovoitov4f733792019-04-01 21:27:44 -070012205 }
He Fengqing75f0fc72021-07-14 10:18:15 +000012206 adjust_insn_aux_data(env, new_data, new_prog, off, len);
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080012207 adjust_subprog_starts(env, off, len);
John Fastabend7506d212021-06-16 15:55:00 -070012208 adjust_poke_descs(new_prog, off, len);
Alexei Starovoitov80419022017-03-15 18:26:41 -070012209 return new_prog;
12210}
12211
Jakub Kicinski52875a02019-01-22 22:45:20 -080012212static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
12213 u32 off, u32 cnt)
12214{
12215 int i, j;
12216
12217 /* find first prog starting at or after off (first to remove) */
12218 for (i = 0; i < env->subprog_cnt; i++)
12219 if (env->subprog_info[i].start >= off)
12220 break;
12221 /* find first prog starting at or after off + cnt (first to stay) */
12222 for (j = i; j < env->subprog_cnt; j++)
12223 if (env->subprog_info[j].start >= off + cnt)
12224 break;
12225 /* if j doesn't start exactly at off + cnt, we are just removing
12226 * the front of previous prog
12227 */
12228 if (env->subprog_info[j].start != off + cnt)
12229 j--;
12230
12231 if (j > i) {
12232 struct bpf_prog_aux *aux = env->prog->aux;
12233 int move;
12234
12235 /* move fake 'exit' subprog as well */
12236 move = env->subprog_cnt + 1 - j;
12237
12238 memmove(env->subprog_info + i,
12239 env->subprog_info + j,
12240 sizeof(*env->subprog_info) * move);
12241 env->subprog_cnt -= j - i;
12242
12243 /* remove func_info */
12244 if (aux->func_info) {
12245 move = aux->func_info_cnt - j;
12246
12247 memmove(aux->func_info + i,
12248 aux->func_info + j,
12249 sizeof(*aux->func_info) * move);
12250 aux->func_info_cnt -= j - i;
12251 /* func_info->insn_off is set after all code rewrites,
12252 * in adjust_btf_func() - no need to adjust
12253 */
12254 }
12255 } else {
12256 /* convert i from "first prog to remove" to "first to adjust" */
12257 if (env->subprog_info[i].start == off)
12258 i++;
12259 }
12260
12261 /* update fake 'exit' subprog as well */
12262 for (; i <= env->subprog_cnt; i++)
12263 env->subprog_info[i].start -= cnt;
12264
12265 return 0;
12266}
12267
12268static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
12269 u32 cnt)
12270{
12271 struct bpf_prog *prog = env->prog;
12272 u32 i, l_off, l_cnt, nr_linfo;
12273 struct bpf_line_info *linfo;
12274
12275 nr_linfo = prog->aux->nr_linfo;
12276 if (!nr_linfo)
12277 return 0;
12278
12279 linfo = prog->aux->linfo;
12280
12281 /* find first line info to remove, count lines to be removed */
12282 for (i = 0; i < nr_linfo; i++)
12283 if (linfo[i].insn_off >= off)
12284 break;
12285
12286 l_off = i;
12287 l_cnt = 0;
12288 for (; i < nr_linfo; i++)
12289 if (linfo[i].insn_off < off + cnt)
12290 l_cnt++;
12291 else
12292 break;
12293
12294 /* First live insn doesn't match first live linfo, it needs to "inherit"
12295 * last removed linfo. prog is already modified, so prog->len == off
12296 * means no live instructions after (tail of the program was removed).
12297 */
12298 if (prog->len != off && l_cnt &&
12299 (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
12300 l_cnt--;
12301 linfo[--i].insn_off = off + cnt;
12302 }
12303
12304 /* remove the line info which refer to the removed instructions */
12305 if (l_cnt) {
12306 memmove(linfo + l_off, linfo + i,
12307 sizeof(*linfo) * (nr_linfo - i));
12308
12309 prog->aux->nr_linfo -= l_cnt;
12310 nr_linfo = prog->aux->nr_linfo;
12311 }
12312
12313 /* pull all linfo[i].insn_off >= off + cnt in by cnt */
12314 for (i = l_off; i < nr_linfo; i++)
12315 linfo[i].insn_off -= cnt;
12316
12317 /* fix up all subprogs (incl. 'exit') which start >= off */
12318 for (i = 0; i <= env->subprog_cnt; i++)
12319 if (env->subprog_info[i].linfo_idx > l_off) {
12320 /* program may have started in the removed region but
12321 * may not be fully removed
12322 */
12323 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
12324 env->subprog_info[i].linfo_idx -= l_cnt;
12325 else
12326 env->subprog_info[i].linfo_idx = l_off;
12327 }
12328
12329 return 0;
12330}
12331
12332static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
12333{
12334 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12335 unsigned int orig_prog_len = env->prog->len;
12336 int err;
12337
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080012338 if (bpf_prog_is_dev_bound(env->prog->aux))
12339 bpf_prog_offload_remove_insns(env, off, cnt);
12340
Jakub Kicinski52875a02019-01-22 22:45:20 -080012341 err = bpf_remove_insns(env->prog, off, cnt);
12342 if (err)
12343 return err;
12344
12345 err = adjust_subprog_starts_after_remove(env, off, cnt);
12346 if (err)
12347 return err;
12348
12349 err = bpf_adj_linfo_after_remove(env, off, cnt);
12350 if (err)
12351 return err;
12352
12353 memmove(aux_data + off, aux_data + off + cnt,
12354 sizeof(*aux_data) * (orig_prog_len - off - cnt));
12355
12356 return 0;
12357}
12358
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010012359/* The verifier does more data flow analysis than llvm and will not
12360 * explore branches that are dead at run time. Malicious programs can
12361 * have dead code too. Therefore replace all dead at-run-time code
12362 * with 'ja -1'.
12363 *
12364 * Just nops are not optimal, e.g. if they would sit at the end of the
12365 * program and through another bug we would manage to jump there, then
12366 * we'd execute beyond program memory otherwise. Returning exception
12367 * code also wouldn't work since we can have subprogs where the dead
12368 * code could be located.
Alexei Starovoitovc1311872017-11-22 16:42:05 -080012369 */
12370static void sanitize_dead_code(struct bpf_verifier_env *env)
12371{
12372 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010012373 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
Alexei Starovoitovc1311872017-11-22 16:42:05 -080012374 struct bpf_insn *insn = env->prog->insnsi;
12375 const int insn_cnt = env->prog->len;
12376 int i;
12377
12378 for (i = 0; i < insn_cnt; i++) {
12379 if (aux_data[i].seen)
12380 continue;
Daniel Borkmann2a5418a2018-01-26 23:33:37 +010012381 memcpy(insn + i, &trap, sizeof(trap));
Ilya Leoshkevich45c709f2021-08-12 17:18:10 +020012382 aux_data[i].zext_dst = false;
Alexei Starovoitovc1311872017-11-22 16:42:05 -080012383 }
12384}
12385
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012386static bool insn_is_cond_jump(u8 code)
12387{
12388 u8 op;
12389
Jiong Wang092ed092019-01-26 12:26:01 -050012390 if (BPF_CLASS(code) == BPF_JMP32)
12391 return true;
12392
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012393 if (BPF_CLASS(code) != BPF_JMP)
12394 return false;
12395
12396 op = BPF_OP(code);
12397 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
12398}
12399
12400static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
12401{
12402 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12403 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12404 struct bpf_insn *insn = env->prog->insnsi;
12405 const int insn_cnt = env->prog->len;
12406 int i;
12407
12408 for (i = 0; i < insn_cnt; i++, insn++) {
12409 if (!insn_is_cond_jump(insn->code))
12410 continue;
12411
12412 if (!aux_data[i + 1].seen)
12413 ja.off = insn->off;
12414 else if (!aux_data[i + 1 + insn->off].seen)
12415 ja.off = 0;
12416 else
12417 continue;
12418
Jakub Kicinski08ca90a2019-01-22 22:45:24 -080012419 if (bpf_prog_is_dev_bound(env->prog->aux))
12420 bpf_prog_offload_replace_insn(env, i, &ja);
12421
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080012422 memcpy(insn, &ja, sizeof(ja));
12423 }
12424}
12425
Jakub Kicinski52875a02019-01-22 22:45:20 -080012426static int opt_remove_dead_code(struct bpf_verifier_env *env)
12427{
12428 struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
12429 int insn_cnt = env->prog->len;
12430 int i, err;
12431
12432 for (i = 0; i < insn_cnt; i++) {
12433 int j;
12434
12435 j = 0;
12436 while (i + j < insn_cnt && !aux_data[i + j].seen)
12437 j++;
12438 if (!j)
12439 continue;
12440
12441 err = verifier_remove_insns(env, i, j);
12442 if (err)
12443 return err;
12444 insn_cnt = env->prog->len;
12445 }
12446
12447 return 0;
12448}
12449
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080012450static int opt_remove_nops(struct bpf_verifier_env *env)
12451{
12452 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
12453 struct bpf_insn *insn = env->prog->insnsi;
12454 int insn_cnt = env->prog->len;
12455 int i, err;
12456
12457 for (i = 0; i < insn_cnt; i++) {
12458 if (memcmp(&insn[i], &ja, sizeof(ja)))
12459 continue;
12460
12461 err = verifier_remove_insns(env, i, 1);
12462 if (err)
12463 return err;
12464 insn_cnt--;
12465 i--;
12466 }
12467
12468 return 0;
12469}
12470
Jiong Wangd6c23082019-05-24 23:25:18 +010012471static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
12472 const union bpf_attr *attr)
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012473{
Jiong Wangd6c23082019-05-24 23:25:18 +010012474 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012475 struct bpf_insn_aux_data *aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010012476 int i, patch_len, delta = 0, len = env->prog->len;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012477 struct bpf_insn *insns = env->prog->insnsi;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012478 struct bpf_prog *new_prog;
Jiong Wangd6c23082019-05-24 23:25:18 +010012479 bool rnd_hi32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012480
Jiong Wangd6c23082019-05-24 23:25:18 +010012481 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012482 zext_patch[1] = BPF_ZEXT_REG(0);
Jiong Wangd6c23082019-05-24 23:25:18 +010012483 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
12484 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
12485 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012486 for (i = 0; i < len; i++) {
12487 int adj_idx = i + delta;
12488 struct bpf_insn insn;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012489 int load_reg;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012490
Jiong Wangd6c23082019-05-24 23:25:18 +010012491 insn = insns[adj_idx];
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012492 load_reg = insn_def_regno(&insn);
Jiong Wangd6c23082019-05-24 23:25:18 +010012493 if (!aux[adj_idx].zext_dst) {
12494 u8 code, class;
12495 u32 imm_rnd;
12496
12497 if (!rnd_hi32)
12498 continue;
12499
12500 code = insn.code;
12501 class = BPF_CLASS(code);
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012502 if (load_reg == -1)
Jiong Wangd6c23082019-05-24 23:25:18 +010012503 continue;
12504
12505 /* NOTE: arg "reg" (the fourth one) is only used for
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012506 * BPF_STX + SRC_OP, so it is safe to pass NULL
12507 * here.
Jiong Wangd6c23082019-05-24 23:25:18 +010012508 */
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012509 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
Jiong Wangd6c23082019-05-24 23:25:18 +010012510 if (class == BPF_LD &&
12511 BPF_MODE(code) == BPF_IMM)
12512 i++;
12513 continue;
12514 }
12515
12516 /* ctx load could be transformed into wider load. */
12517 if (class == BPF_LDX &&
12518 aux[adj_idx].ptr_type == PTR_TO_CTX)
12519 continue;
12520
12521 imm_rnd = get_random_int();
12522 rnd_hi32_patch[0] = insn;
12523 rnd_hi32_patch[1].imm = imm_rnd;
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012524 rnd_hi32_patch[3].dst_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010012525 patch = rnd_hi32_patch;
12526 patch_len = 4;
12527 goto apply_patch_buffer;
12528 }
12529
Brendan Jackman39491862021-03-04 18:56:46 -080012530 /* Add in an zero-extend instruction if a) the JIT has requested
12531 * it or b) it's a CMPXCHG.
12532 *
12533 * The latter is because: BPF_CMPXCHG always loads a value into
12534 * R0, therefore always zero-extends. However some archs'
12535 * equivalent instruction only does this load when the
12536 * comparison is successful. This detail of CMPXCHG is
12537 * orthogonal to the general zero-extension behaviour of the
12538 * CPU, so it's treated independently of bpf_jit_needs_zext.
12539 */
12540 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012541 continue;
12542
Ilya Leoshkevich83a28812021-03-01 16:40:19 +010012543 if (WARN_ON(load_reg == -1)) {
12544 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
12545 return -EFAULT;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010012546 }
12547
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012548 zext_patch[0] = insn;
Ilya Leoshkevichb2e37a72021-02-10 21:45:02 +010012549 zext_patch[1].dst_reg = load_reg;
12550 zext_patch[1].src_reg = load_reg;
Jiong Wangd6c23082019-05-24 23:25:18 +010012551 patch = zext_patch;
12552 patch_len = 2;
12553apply_patch_buffer:
12554 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012555 if (!new_prog)
12556 return -ENOMEM;
12557 env->prog = new_prog;
12558 insns = new_prog->insnsi;
12559 aux = env->insn_aux_data;
Jiong Wangd6c23082019-05-24 23:25:18 +010012560 delta += patch_len - 1;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010012561 }
12562
12563 return 0;
12564}
12565
Joe Stringerc64b7982018-10-02 13:35:33 -070012566/* convert load instructions that access fields of a context type into a
12567 * sequence of instructions that access fields of the underlying structure:
12568 * struct __sk_buff -> struct sk_buff
12569 * struct bpf_sock_ops -> struct sock
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012570 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010012571static int convert_ctx_accesses(struct bpf_verifier_env *env)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012572{
Jakub Kicinski00176a32017-10-16 16:40:54 -070012573 const struct bpf_verifier_ops *ops = env->ops;
Daniel Borkmannf96da092017-07-02 02:13:27 +020012574 int i, cnt, size, ctx_field_size, delta = 0;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012575 const int insn_cnt = env->prog->len;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012576 struct bpf_insn insn_buf[16], *insn;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012577 u32 target_size, size_default, off;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012578 struct bpf_prog *new_prog;
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070012579 enum bpf_access_type type;
Daniel Borkmannf96da092017-07-02 02:13:27 +020012580 bool is_narrower_load;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012581
Daniel Borkmannb09928b2018-10-24 22:05:49 +020012582 if (ops->gen_prologue || env->seen_direct_write) {
12583 if (!ops->gen_prologue) {
12584 verbose(env, "bpf verifier is misconfigured\n");
12585 return -EINVAL;
12586 }
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012587 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
12588 env->prog);
12589 if (cnt >= ARRAY_SIZE(insn_buf)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012590 verbose(env, "bpf verifier is misconfigured\n");
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012591 return -EINVAL;
12592 } else if (cnt) {
Alexei Starovoitov80419022017-03-15 18:26:41 -070012593 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012594 if (!new_prog)
12595 return -ENOMEM;
Alexei Starovoitov80419022017-03-15 18:26:41 -070012596
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012597 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012598 delta += cnt - 1;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012599 }
12600 }
12601
Joe Stringerc64b7982018-10-02 13:35:33 -070012602 if (bpf_prog_is_dev_bound(env->prog->aux))
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012603 return 0;
12604
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012605 insn = env->prog->insnsi + delta;
Daniel Borkmann36bbef52016-09-20 00:26:13 +020012606
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012607 for (i = 0; i < insn_cnt; i++, insn++) {
Joe Stringerc64b7982018-10-02 13:35:33 -070012608 bpf_convert_ctx_access_t convert_ctx_access;
Daniel Borkmann2039f262021-07-13 08:18:31 +000012609 bool ctx_access;
Joe Stringerc64b7982018-10-02 13:35:33 -070012610
Daniel Borkmann62c79892017-01-12 11:51:33 +010012611 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
12612 insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
12613 insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
Daniel Borkmann2039f262021-07-13 08:18:31 +000012614 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) {
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070012615 type = BPF_READ;
Daniel Borkmann2039f262021-07-13 08:18:31 +000012616 ctx_access = true;
12617 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
12618 insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
12619 insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
12620 insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
12621 insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
12622 insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
12623 insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
12624 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
Alexei Starovoitovd691f9e2015-06-04 10:11:54 -070012625 type = BPF_WRITE;
Daniel Borkmann2039f262021-07-13 08:18:31 +000012626 ctx_access = BPF_CLASS(insn->code) == BPF_STX;
12627 } else {
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012628 continue;
Daniel Borkmann2039f262021-07-13 08:18:31 +000012629 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012630
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070012631 if (type == BPF_WRITE &&
Daniel Borkmann2039f262021-07-13 08:18:31 +000012632 env->insn_aux_data[i + delta].sanitize_stack_spill) {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070012633 struct bpf_insn patch[] = {
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070012634 *insn,
Daniel Borkmann2039f262021-07-13 08:18:31 +000012635 BPF_ST_NOSPEC(),
Alexei Starovoitovaf86ca42018-05-15 09:27:05 -070012636 };
12637
12638 cnt = ARRAY_SIZE(patch);
12639 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
12640 if (!new_prog)
12641 return -ENOMEM;
12642
12643 delta += cnt - 1;
12644 env->prog = new_prog;
12645 insn = new_prog->insnsi + i + delta;
12646 continue;
12647 }
12648
Daniel Borkmann2039f262021-07-13 08:18:31 +000012649 if (!ctx_access)
12650 continue;
12651
Joe Stringerc64b7982018-10-02 13:35:33 -070012652 switch (env->insn_aux_data[i + delta].ptr_type) {
12653 case PTR_TO_CTX:
12654 if (!ops->convert_ctx_access)
12655 continue;
12656 convert_ctx_access = ops->convert_ctx_access;
12657 break;
12658 case PTR_TO_SOCKET:
Martin KaFai Lau46f8bc92019-02-09 23:22:20 -080012659 case PTR_TO_SOCK_COMMON:
Joe Stringerc64b7982018-10-02 13:35:33 -070012660 convert_ctx_access = bpf_sock_convert_ctx_access;
12661 break;
Martin KaFai Lau655a51e2019-02-09 23:22:24 -080012662 case PTR_TO_TCP_SOCK:
12663 convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
12664 break;
Jonathan Lemonfada7fd2019-06-06 13:59:40 -070012665 case PTR_TO_XDP_SOCK:
12666 convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
12667 break;
Alexei Starovoitov2a027592019-10-15 20:25:02 -070012668 case PTR_TO_BTF_ID:
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080012669 if (type == BPF_READ) {
12670 insn->code = BPF_LDX | BPF_PROBE_MEM |
12671 BPF_SIZE((insn)->code);
12672 env->prog->aux->num_exentries++;
Udip Pant7e407812020-08-25 16:20:00 -070012673 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) {
Alexei Starovoitov2a027592019-10-15 20:25:02 -070012674 verbose(env, "Writes through BTF pointers are not allowed\n");
12675 return -EINVAL;
12676 }
Alexei Starovoitov2a027592019-10-15 20:25:02 -070012677 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070012678 default:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012679 continue;
Joe Stringerc64b7982018-10-02 13:35:33 -070012680 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012681
Yonghong Song31fd8582017-06-13 15:52:13 -070012682 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
Daniel Borkmannf96da092017-07-02 02:13:27 +020012683 size = BPF_LDST_BYTES(insn);
Yonghong Song31fd8582017-06-13 15:52:13 -070012684
12685 /* If the read access is a narrower load of the field,
12686 * convert to a 4/8-byte load, to minimum program type specific
12687 * convert_ctx_access changes. If conversion is successful,
12688 * we will apply proper mask to the result.
12689 */
Daniel Borkmannf96da092017-07-02 02:13:27 +020012690 is_narrower_load = size < ctx_field_size;
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012691 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
12692 off = insn->off;
Yonghong Song31fd8582017-06-13 15:52:13 -070012693 if (is_narrower_load) {
Daniel Borkmannf96da092017-07-02 02:13:27 +020012694 u8 size_code;
Yonghong Song31fd8582017-06-13 15:52:13 -070012695
Daniel Borkmannf96da092017-07-02 02:13:27 +020012696 if (type == BPF_WRITE) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012697 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
Daniel Borkmannf96da092017-07-02 02:13:27 +020012698 return -EINVAL;
12699 }
12700
12701 size_code = BPF_H;
Yonghong Song31fd8582017-06-13 15:52:13 -070012702 if (ctx_field_size == 4)
12703 size_code = BPF_W;
12704 else if (ctx_field_size == 8)
12705 size_code = BPF_DW;
Daniel Borkmannf96da092017-07-02 02:13:27 +020012706
Daniel Borkmannbc231052018-06-02 23:06:39 +020012707 insn->off = off & ~(size_default - 1);
Yonghong Song31fd8582017-06-13 15:52:13 -070012708 insn->code = BPF_LDX | BPF_MEM | size_code;
12709 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020012710
12711 target_size = 0;
Joe Stringerc64b7982018-10-02 13:35:33 -070012712 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
12713 &target_size);
Daniel Borkmannf96da092017-07-02 02:13:27 +020012714 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
12715 (ctx_field_size && !target_size)) {
Jakub Kicinski61bd5212017-10-09 10:30:11 -070012716 verbose(env, "bpf verifier is misconfigured\n");
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012717 return -EINVAL;
12718 }
Daniel Borkmannf96da092017-07-02 02:13:27 +020012719
12720 if (is_narrower_load && size < target_size) {
Ilya Leoshkevichd895a0f2019-08-16 12:53:00 +020012721 u8 shift = bpf_ctx_narrow_access_offset(
12722 off, size, size_default) * 8;
Andrey Ignatovd7af7e42021-08-20 09:39:35 -070012723 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
12724 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
12725 return -EINVAL;
12726 }
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012727 if (ctx_field_size <= 4) {
12728 if (shift)
12729 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
12730 insn->dst_reg,
12731 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070012732 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
Daniel Borkmannf96da092017-07-02 02:13:27 +020012733 (1 << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012734 } else {
12735 if (shift)
12736 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
12737 insn->dst_reg,
12738 shift);
Yonghong Song31fd8582017-06-13 15:52:13 -070012739 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg,
Krzesimir Nowake2f7fc02019-05-08 18:08:58 +020012740 (1ULL << size * 8) - 1);
Andrey Ignatov46f53a62018-11-10 22:15:13 -080012741 }
Yonghong Song31fd8582017-06-13 15:52:13 -070012742 }
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012743
Alexei Starovoitov80419022017-03-15 18:26:41 -070012744 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012745 if (!new_prog)
12746 return -ENOMEM;
12747
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012748 delta += cnt - 1;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012749
12750 /* keep walking new program and skip insns we just inserted */
12751 env->prog = new_prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010012752 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070012753 }
12754
12755 return 0;
12756}
12757
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012758static int jit_subprogs(struct bpf_verifier_env *env)
12759{
12760 struct bpf_prog *prog = env->prog, **func, *tmp;
12761 int i, j, subprog_start, subprog_end = 0, len, subprog;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012762 struct bpf_map *map_ptr;
Daniel Borkmann7105e822017-12-20 13:42:57 +010012763 struct bpf_insn *insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012764 void *old_bpf_func;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070012765 int err, num_exentries;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012766
Jiong Wangf910cef2018-05-02 16:17:17 -040012767 if (env->subprog_cnt <= 1)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012768 return 0;
12769
Daniel Borkmann7105e822017-12-20 13:42:57 +010012770 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Martin KaFai Lau3990ed42021-11-05 18:40:14 -070012771 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
Yonghong Song69c087b2021-02-26 12:49:25 -080012772 continue;
Yonghong Song69c087b2021-02-26 12:49:25 -080012773
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012774 /* Upon error here we cannot fall back to interpreter but
12775 * need a hard reject of the program. Thus -EFAULT is
12776 * propagated in any case.
12777 */
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012778 subprog = find_subprog(env, i + insn->imm + 1);
12779 if (subprog < 0) {
12780 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
12781 i + insn->imm + 1);
12782 return -EFAULT;
12783 }
12784 /* temporarily remember subprog id inside insn instead of
12785 * aux_data, since next loop will split up all insns into funcs
12786 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012787 insn->off = subprog;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012788 /* remember original imm in case JIT fails and fallback
12789 * to interpreter will be needed
12790 */
12791 env->insn_aux_data[i].call_imm = insn->imm;
12792 /* point imm to __bpf_call_base+1 from JITs point of view */
12793 insn->imm = 1;
Martin KaFai Lau3990ed42021-11-05 18:40:14 -070012794 if (bpf_pseudo_func(insn))
12795 /* jit (e.g. x86_64) may emit fewer instructions
12796 * if it learns a u32 imm is the same as a u64 imm.
12797 * Force a non zero here.
12798 */
12799 insn[1].imm = 1;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012800 }
12801
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012802 err = bpf_prog_alloc_jited_linfo(prog);
12803 if (err)
12804 goto out_undo_insn;
12805
12806 err = -ENOMEM;
Kees Cook6396bb22018-06-12 14:03:40 -070012807 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012808 if (!func)
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012809 goto out_undo_insn;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012810
Jiong Wangf910cef2018-05-02 16:17:17 -040012811 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012812 subprog_start = subprog_end;
Jiong Wang4cb3d992018-05-02 16:17:19 -040012813 subprog_end = env->subprog_info[i + 1].start;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012814
12815 len = subprog_end - subprog_start;
Andrii Nakryikofb7dd8b2021-08-15 00:05:54 -070012816 /* bpf_prog_run() doesn't call subprogs directly,
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012817 * hence main prog stats include the runtime of subprogs.
12818 * subprogs don't have IDs and not reachable via prog_get_next_id
Alexei Starovoitov700d4792021-02-09 19:36:26 -080012819 * func[i]->stats will never be accessed and stays NULL
Alexei Starovoitov492ecee2019-02-25 14:28:39 -080012820 */
12821 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012822 if (!func[i])
12823 goto out_free;
12824 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
12825 len * sizeof(struct bpf_insn));
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012826 func[i]->type = prog->type;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012827 func[i]->len = len;
Daniel Borkmann4f74d802017-12-20 13:42:56 +010012828 if (bpf_prog_calc_tag(func[i]))
12829 goto out_free;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012830 func[i]->is_func = 1;
Yonghong Songba64e7d2018-11-24 23:20:44 -080012831 func[i]->aux->func_idx = i;
John Fastabendf263a812021-07-07 15:38:47 -070012832 /* Below members will be freed only at prog->aux */
Yonghong Songba64e7d2018-11-24 23:20:44 -080012833 func[i]->aux->btf = prog->aux->btf;
12834 func[i]->aux->func_info = prog->aux->func_info;
John Fastabendf263a812021-07-07 15:38:47 -070012835 func[i]->aux->poke_tab = prog->aux->poke_tab;
12836 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
Yonghong Songba64e7d2018-11-24 23:20:44 -080012837
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012838 for (j = 0; j < prog->aux->size_poke_tab; j++) {
John Fastabendf263a812021-07-07 15:38:47 -070012839 struct bpf_jit_poke_descriptor *poke;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012840
John Fastabendf263a812021-07-07 15:38:47 -070012841 poke = &prog->aux->poke_tab[j];
12842 if (poke->insn_idx < subprog_end &&
12843 poke->insn_idx >= subprog_start)
12844 poke->aux = func[i]->aux;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012845 }
12846
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012847 /* Use bpf_prog_F_tag to indicate functions in stack traces.
12848 * Long term would need debug info to populate names
12849 */
12850 func[i]->aux->name[0] = 'F';
Jiong Wang9c8105b2018-05-02 16:17:18 -040012851 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012852 func[i]->jit_requested = 1;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012853 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +053012854 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
Martin KaFai Lauc454a462018-12-07 16:42:25 -080012855 func[i]->aux->linfo = prog->aux->linfo;
12856 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
12857 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
12858 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
Yonghong Songc4c0bdc2020-06-23 17:10:54 -070012859 num_exentries = 0;
12860 insn = func[i]->insnsi;
12861 for (j = 0; j < func[i]->len; j++, insn++) {
12862 if (BPF_CLASS(insn->code) == BPF_LDX &&
12863 BPF_MODE(insn->code) == BPF_PROBE_MEM)
12864 num_exentries++;
12865 }
12866 func[i]->aux->num_exentries = num_exentries;
Maciej Fijalkowskiebf7d1f2020-09-16 23:10:08 +020012867 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012868 func[i] = bpf_int_jit_compile(func[i]);
12869 if (!func[i]->jited) {
12870 err = -ENOTSUPP;
12871 goto out_free;
12872 }
12873 cond_resched();
12874 }
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012875
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012876 /* at this point all bpf functions were successfully JITed
12877 * now populate all bpf_calls with correct addresses and
12878 * run last pass of JIT
12879 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012880 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012881 insn = func[i]->insnsi;
12882 for (j = 0; j < func[i]->len; j++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012883 if (bpf_pseudo_func(insn)) {
Martin KaFai Lau3990ed42021-11-05 18:40:14 -070012884 subprog = insn->off;
Yonghong Song69c087b2021-02-26 12:49:25 -080012885 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
12886 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
12887 continue;
12888 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012889 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012890 continue;
12891 subprog = insn->off;
Kees Cook3d717fa2021-09-28 16:09:45 -070012892 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012893 }
Sandipan Das2162fed2018-05-24 12:26:45 +053012894
12895 /* we use the aux data to keep a list of the start addresses
12896 * of the JITed images for each function in the program
12897 *
12898 * for some architectures, such as powerpc64, the imm field
12899 * might not be large enough to hold the offset of the start
12900 * address of the callee's JITed image from __bpf_call_base
12901 *
12902 * in such cases, we can lookup the start address of a callee
12903 * by using its subprog id, available from the off field of
12904 * the call instruction, as an index for this list
12905 */
12906 func[i]->aux->func = func;
12907 func[i]->aux->func_cnt = env->subprog_cnt;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012908 }
Jiong Wangf910cef2018-05-02 16:17:17 -040012909 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012910 old_bpf_func = func[i]->bpf_func;
12911 tmp = bpf_int_jit_compile(func[i]);
12912 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
12913 verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012914 err = -ENOTSUPP;
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012915 goto out_free;
12916 }
12917 cond_resched();
12918 }
12919
12920 /* finally lock prog and jit images for all functions and
12921 * populate kallsysm
12922 */
Jiong Wangf910cef2018-05-02 16:17:17 -040012923 for (i = 0; i < env->subprog_cnt; i++) {
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012924 bpf_prog_lock_ro(func[i]);
12925 bpf_prog_kallsyms_add(func[i]);
12926 }
Daniel Borkmann7105e822017-12-20 13:42:57 +010012927
12928 /* Last step: make now unused interpreter insns from main
12929 * prog consistent for later dump requests, so they can
12930 * later look the same as if they were interpreted only.
12931 */
12932 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080012933 if (bpf_pseudo_func(insn)) {
12934 insn[0].imm = env->insn_aux_data[i].call_imm;
Martin KaFai Lau3990ed42021-11-05 18:40:14 -070012935 insn[1].imm = insn->off;
12936 insn->off = 0;
Yonghong Song69c087b2021-02-26 12:49:25 -080012937 continue;
12938 }
Yonghong Song23a2d702021-02-04 15:48:27 -080012939 if (!bpf_pseudo_call(insn))
Daniel Borkmann7105e822017-12-20 13:42:57 +010012940 continue;
12941 insn->off = env->insn_aux_data[i].call_imm;
12942 subprog = find_subprog(env, i + insn->off + 1);
Sandipan Dasdbecd732018-05-24 12:26:48 +053012943 insn->imm = subprog;
Daniel Borkmann7105e822017-12-20 13:42:57 +010012944 }
12945
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012946 prog->jited = 1;
12947 prog->bpf_func = func[0]->bpf_func;
12948 prog->aux->func = func;
Jiong Wangf910cef2018-05-02 16:17:17 -040012949 prog->aux->func_cnt = env->subprog_cnt;
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012950 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012951 return 0;
12952out_free:
John Fastabendf263a812021-07-07 15:38:47 -070012953 /* We failed JIT'ing, so at this point we need to unregister poke
12954 * descriptors from subprogs, so that kernel is not attempting to
12955 * patch it anymore as we're freeing the subprog JIT memory.
12956 */
12957 for (i = 0; i < prog->aux->size_poke_tab; i++) {
12958 map_ptr = prog->aux->poke_tab[i].tail_call.map;
12959 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
12960 }
12961 /* At this point we're guaranteed that poke descriptors are not
12962 * live anymore. We can just unlink its descriptor table as it's
12963 * released with the main prog.
12964 */
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012965 for (i = 0; i < env->subprog_cnt; i++) {
12966 if (!func[i])
12967 continue;
John Fastabendf263a812021-07-07 15:38:47 -070012968 func[i]->aux->poke_tab = NULL;
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020012969 bpf_jit_free(func[i]);
12970 }
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012971 kfree(func);
Daniel Borkmannc7a89782018-07-12 21:44:28 +020012972out_undo_insn:
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012973 /* cleanup main prog to be interpreted */
12974 prog->jit_requested = 0;
12975 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
Yonghong Song23a2d702021-02-04 15:48:27 -080012976 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012977 continue;
12978 insn->off = 0;
12979 insn->imm = env->insn_aux_data[i].call_imm;
12980 }
Martin KaFai Laue16301f2021-03-24 18:51:30 -070012981 bpf_prog_jit_attempt_done(prog);
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012982 return err;
12983}
12984
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012985static int fixup_call_args(struct bpf_verifier_env *env)
12986{
David S. Miller19d28fb2018-01-11 21:27:54 -050012987#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012988 struct bpf_prog *prog = env->prog;
12989 struct bpf_insn *insn = prog->insnsi;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070012990 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012991 int i, depth;
David S. Miller19d28fb2018-01-11 21:27:54 -050012992#endif
Quentin Monnete4052d02018-10-07 12:56:58 +010012993 int err = 0;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080012994
Quentin Monnete4052d02018-10-07 12:56:58 +010012995 if (env->prog->jit_requested &&
12996 !bpf_prog_is_dev_bound(env->prog->aux)) {
David S. Miller19d28fb2018-01-11 21:27:54 -050012997 err = jit_subprogs(env);
12998 if (err == 0)
Alexei Starovoitov1c2a0882017-12-14 17:55:15 -080012999 return 0;
Daniel Borkmannc7a89782018-07-12 21:44:28 +020013000 if (err == -EFAULT)
13001 return err;
David S. Miller19d28fb2018-01-11 21:27:54 -050013002 }
13003#ifndef CONFIG_BPF_JIT_ALWAYS_ON
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013004 if (has_kfunc_call) {
13005 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
13006 return -EINVAL;
13007 }
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020013008 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
13009 /* When JIT fails the progs with bpf2bpf calls and tail_calls
13010 * have to be rejected, since interpreter doesn't support them yet.
13011 */
13012 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
13013 return -EINVAL;
13014 }
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080013015 for (i = 0; i < prog->len; i++, insn++) {
Yonghong Song69c087b2021-02-26 12:49:25 -080013016 if (bpf_pseudo_func(insn)) {
13017 /* When JIT fails the progs with callback calls
13018 * have to be rejected, since interpreter doesn't support them yet.
13019 */
13020 verbose(env, "callbacks are not allowed in non-JITed programs\n");
13021 return -EINVAL;
13022 }
13023
Yonghong Song23a2d702021-02-04 15:48:27 -080013024 if (!bpf_pseudo_call(insn))
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080013025 continue;
13026 depth = get_callee_stack_depth(env, insn, i);
13027 if (depth < 0)
13028 return depth;
13029 bpf_patch_call_args(insn, depth);
13030 }
David S. Miller19d28fb2018-01-11 21:27:54 -050013031 err = 0;
13032#endif
13033 return err;
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080013034}
13035
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013036static int fixup_kfunc_call(struct bpf_verifier_env *env,
13037 struct bpf_insn *insn)
13038{
13039 const struct bpf_kfunc_desc *desc;
13040
Kumar Kartikeya Dwivedia5d82722021-10-02 06:47:50 +053013041 if (!insn->imm) {
13042 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
13043 return -EINVAL;
13044 }
13045
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013046 /* insn->imm has the btf func_id. Replace it with
13047 * an address (relative to __bpf_base_call).
13048 */
Kumar Kartikeya Dwivedi23576722021-10-02 06:47:49 +053013049 desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013050 if (!desc) {
13051 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
13052 insn->imm);
13053 return -EFAULT;
13054 }
13055
13056 insn->imm = desc->imm;
13057
13058 return 0;
13059}
13060
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013061/* Do various post-verification rewrites in a single program pass.
13062 * These rewrites simplify JIT and interpreter implementations.
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013063 */
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013064static int do_misc_fixups(struct bpf_verifier_env *env)
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013065{
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013066 struct bpf_prog *prog = env->prog;
Jiri Olsaf92c1e12021-12-08 20:32:44 +010013067 enum bpf_attach_type eatype = prog->expected_attach_type;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013068 bool expect_blinding = bpf_jit_blinding_enabled(prog);
Jiri Olsa9b99edc2021-07-14 11:43:55 +020013069 enum bpf_prog_type prog_type = resolve_prog_type(prog);
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013070 struct bpf_insn *insn = prog->insnsi;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013071 const struct bpf_func_proto *fn;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013072 const int insn_cnt = prog->len;
Daniel Borkmann09772d92018-06-02 23:06:35 +020013073 const struct bpf_map_ops *ops;
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013074 struct bpf_insn_aux_data *aux;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070013075 struct bpf_insn insn_buf[16];
13076 struct bpf_prog *new_prog;
13077 struct bpf_map *map_ptr;
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013078 int i, ret, cnt, delta = 0;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013079
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013080 for (i = 0; i < insn_cnt; i++, insn++) {
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013081 /* Make divide-by-zero exceptions impossible. */
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013082 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
13083 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
13084 insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
Alexei Starovoitov68fda452018-01-12 18:59:52 -080013085 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013086 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000013087 bool isdiv = BPF_OP(insn->code) == BPF_DIV;
13088 struct bpf_insn *patchlet;
13089 struct bpf_insn chk_and_div[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010013090 /* [R,W]x div 0 -> 0 */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000013091 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13092 BPF_JNE | BPF_K, insn->src_reg,
13093 0, 2, 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013094 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
13095 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13096 *insn,
13097 };
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000013098 struct bpf_insn chk_and_mod[] = {
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010013099 /* [R,W]x mod 0 -> [R,W]x */
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000013100 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
13101 BPF_JEQ | BPF_K, insn->src_reg,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010013102 0, 1 + (is64 ? 0 : 1), 0),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013103 *insn,
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010013104 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
13105 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013106 };
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013107
Daniel Borkmanne88b2c62021-02-09 18:46:10 +000013108 patchlet = isdiv ? chk_and_div : chk_and_mod;
13109 cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
Daniel Borkmann9b00f1b2021-02-10 14:14:42 +010013110 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
Daniel Borkmannf6b1b3b2018-01-26 23:33:39 +010013111
13112 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
Alexei Starovoitov68fda452018-01-12 18:59:52 -080013113 if (!new_prog)
13114 return -ENOMEM;
13115
13116 delta += cnt - 1;
13117 env->prog = prog = new_prog;
13118 insn = new_prog->insnsi + i + delta;
13119 continue;
13120 }
13121
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013122 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
Daniel Borkmanne0cea7c2018-05-04 01:08:14 +020013123 if (BPF_CLASS(insn->code) == BPF_LD &&
13124 (BPF_MODE(insn->code) == BPF_ABS ||
13125 BPF_MODE(insn->code) == BPF_IND)) {
13126 cnt = env->ops->gen_ld_abs(insn, insn_buf);
13127 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
13128 verbose(env, "bpf verifier is misconfigured\n");
13129 return -EINVAL;
13130 }
13131
13132 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13133 if (!new_prog)
13134 return -ENOMEM;
13135
13136 delta += cnt - 1;
13137 env->prog = prog = new_prog;
13138 insn = new_prog->insnsi + i + delta;
13139 continue;
13140 }
13141
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013142 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013143 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
13144 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
13145 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
13146 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013147 struct bpf_insn *patch = &insn_buf[0];
Daniel Borkmann801c6052021-04-29 15:19:37 +000013148 bool issrc, isneg, isimm;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013149 u32 off_reg;
13150
13151 aux = &env->insn_aux_data[i + delta];
Daniel Borkmann3612af72019-03-01 22:05:29 +010013152 if (!aux->alu_state ||
13153 aux->alu_state == BPF_ALU_NON_POINTER)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013154 continue;
13155
13156 isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
13157 issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
13158 BPF_ALU_SANITIZE_SRC;
Daniel Borkmann801c6052021-04-29 15:19:37 +000013159 isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013160
13161 off_reg = issrc ? insn->src_reg : insn->dst_reg;
Daniel Borkmann801c6052021-04-29 15:19:37 +000013162 if (isimm) {
13163 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13164 } else {
13165 if (isneg)
13166 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13167 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
13168 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
13169 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
13170 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
13171 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
13172 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
13173 }
Daniel Borkmannb9b34dd2021-04-30 16:21:46 +020013174 if (!issrc)
13175 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
13176 insn->src_reg = BPF_REG_AX;
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013177 if (isneg)
13178 insn->code = insn->code == code_add ?
13179 code_sub : code_add;
13180 *patch++ = *insn;
Daniel Borkmann801c6052021-04-29 15:19:37 +000013181 if (issrc && isneg && !isimm)
Daniel Borkmann979d63d2019-01-03 00:58:34 +010013182 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
13183 cnt = patch - insn_buf;
13184
13185 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13186 if (!new_prog)
13187 return -ENOMEM;
13188
13189 delta += cnt - 1;
13190 env->prog = prog = new_prog;
13191 insn = new_prog->insnsi + i + delta;
13192 continue;
13193 }
13194
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013195 if (insn->code != (BPF_JMP | BPF_CALL))
13196 continue;
Alexei Starovoitovcc8b0b92017-12-14 17:55:05 -080013197 if (insn->src_reg == BPF_PSEUDO_CALL)
13198 continue;
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013199 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
13200 ret = fixup_kfunc_call(env, insn);
13201 if (ret)
13202 return ret;
13203 continue;
13204 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013205
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013206 if (insn->imm == BPF_FUNC_get_route_realm)
13207 prog->dst_needed = 1;
13208 if (insn->imm == BPF_FUNC_get_prandom_u32)
13209 bpf_user_rnd_init_once();
Josef Bacik9802d862017-12-11 11:36:48 -050013210 if (insn->imm == BPF_FUNC_override_return)
13211 prog->kprobe_override = 1;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013212 if (insn->imm == BPF_FUNC_tail_call) {
David S. Miller7b9f6da2017-04-20 10:35:33 -040013213 /* If we tail call into other programs, we
13214 * cannot make any assumptions since they can
13215 * be replaced dynamically during runtime in
13216 * the program array.
13217 */
13218 prog->cb_access = 1;
Maciej Fijalkowskie4119012020-09-16 23:10:09 +020013219 if (!allow_tail_call_in_subprogs(env))
13220 prog->aux->stack_depth = MAX_BPF_STACK;
13221 prog->aux->max_pkt_offset = MAX_PACKET_OFF;
David S. Miller7b9f6da2017-04-20 10:35:33 -040013222
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013223 /* mark bpf_tail_call as different opcode to avoid
Zhen Lei8fb33b62021-05-25 10:56:59 +080013224 * conditional branch in the interpreter for every normal
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013225 * call and to prevent accidental JITing by JIT compiler
13226 * that doesn't support bpf_tail_call yet
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013227 */
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013228 insn->imm = 0;
Alexei Starovoitov71189fa2017-05-30 13:31:27 -070013229 insn->code = BPF_JMP | BPF_TAIL_CALL;
Alexei Starovoitovb2157392018-01-07 17:33:02 -080013230
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013231 aux = &env->insn_aux_data[i + delta];
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070013232 if (env->bpf_capable && !expect_blinding &&
Daniel Borkmanncc52d912019-12-19 22:19:50 +010013233 prog->jit_requested &&
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013234 !bpf_map_key_poisoned(aux) &&
13235 !bpf_map_ptr_poisoned(aux) &&
13236 !bpf_map_ptr_unpriv(aux)) {
13237 struct bpf_jit_poke_descriptor desc = {
13238 .reason = BPF_POKE_REASON_TAIL_CALL,
13239 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
13240 .tail_call.key = bpf_map_key_immediate(aux),
Maciej Fijalkowskia748c692020-09-16 23:10:05 +020013241 .insn_idx = i + delta,
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013242 };
13243
13244 ret = bpf_jit_add_poke_descriptor(prog, &desc);
13245 if (ret < 0) {
13246 verbose(env, "adding tail call poke descriptor failed\n");
13247 return ret;
13248 }
13249
13250 insn->imm = ret + 1;
13251 continue;
13252 }
13253
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013254 if (!bpf_map_ptr_unpriv(aux))
13255 continue;
13256
Alexei Starovoitovb2157392018-01-07 17:33:02 -080013257 /* instead of changing every JIT dealing with tail_call
13258 * emit two extra insns:
13259 * if (index >= max_entries) goto out;
13260 * index &= array->index_mask;
13261 * to avoid out-of-bounds cpu speculation
13262 */
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013263 if (bpf_map_ptr_poisoned(aux)) {
Colin Ian King40950342018-01-10 09:20:54 +000013264 verbose(env, "tail_call abusing map_ptr\n");
Alexei Starovoitovb2157392018-01-07 17:33:02 -080013265 return -EINVAL;
13266 }
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013267
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013268 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Alexei Starovoitovb2157392018-01-07 17:33:02 -080013269 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
13270 map_ptr->max_entries, 2);
13271 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
13272 container_of(map_ptr,
13273 struct bpf_array,
13274 map)->index_mask);
13275 insn_buf[2] = *insn;
13276 cnt = 3;
13277 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13278 if (!new_prog)
13279 return -ENOMEM;
13280
13281 delta += cnt - 1;
13282 env->prog = prog = new_prog;
13283 insn = new_prog->insnsi + i + delta;
Alexei Starovoitov79741b32017-03-15 18:26:40 -070013284 continue;
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013285 }
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070013286
Alexei Starovoitovb00628b2021-07-14 17:54:09 -070013287 if (insn->imm == BPF_FUNC_timer_set_callback) {
13288 /* The verifier will process callback_fn as many times as necessary
13289 * with different maps and the register states prepared by
13290 * set_timer_callback_state will be accurate.
13291 *
13292 * The following use case is valid:
13293 * map1 is shared by prog1, prog2, prog3.
13294 * prog1 calls bpf_timer_init for some map1 elements
13295 * prog2 calls bpf_timer_set_callback for some map1 elements.
13296 * Those that were not bpf_timer_init-ed will return -EINVAL.
13297 * prog3 calls bpf_timer_start for some map1 elements.
13298 * Those that were not both bpf_timer_init-ed and
13299 * bpf_timer_set_callback-ed will return -EINVAL.
13300 */
13301 struct bpf_insn ld_addrs[2] = {
13302 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
13303 };
13304
13305 insn_buf[0] = ld_addrs[0];
13306 insn_buf[1] = ld_addrs[1];
13307 insn_buf[2] = *insn;
13308 cnt = 3;
13309
13310 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13311 if (!new_prog)
13312 return -ENOMEM;
13313
13314 delta += cnt - 1;
13315 env->prog = prog = new_prog;
13316 insn = new_prog->insnsi + i + delta;
13317 goto patch_call_imm;
13318 }
13319
Daniel Borkmann89c63072017-08-19 03:12:45 +020013320 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
Daniel Borkmann09772d92018-06-02 23:06:35 +020013321 * and other inlining handlers are currently limited to 64 bit
13322 * only.
Daniel Borkmann89c63072017-08-19 03:12:45 +020013323 */
Alexei Starovoitov60b58afc2017-12-14 17:55:14 -080013324 if (prog->jit_requested && BITS_PER_LONG == 64 &&
Daniel Borkmann09772d92018-06-02 23:06:35 +020013325 (insn->imm == BPF_FUNC_map_lookup_elem ||
13326 insn->imm == BPF_FUNC_map_update_elem ||
Daniel Borkmann84430d42018-10-21 02:09:27 +020013327 insn->imm == BPF_FUNC_map_delete_elem ||
13328 insn->imm == BPF_FUNC_map_push_elem ||
13329 insn->imm == BPF_FUNC_map_pop_elem ||
Björn Töpele6a47502021-03-08 12:29:06 +010013330 insn->imm == BPF_FUNC_map_peek_elem ||
Andrey Ignatov0640c772021-10-05 17:18:38 -070013331 insn->imm == BPF_FUNC_redirect_map ||
13332 insn->imm == BPF_FUNC_for_each_map_elem)) {
Daniel Borkmannc93552c2018-05-24 02:32:53 +020013333 aux = &env->insn_aux_data[i + delta];
13334 if (bpf_map_ptr_poisoned(aux))
13335 goto patch_call_imm;
13336
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013337 map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
Daniel Borkmann09772d92018-06-02 23:06:35 +020013338 ops = map_ptr->ops;
13339 if (insn->imm == BPF_FUNC_map_lookup_elem &&
13340 ops->map_gen_lookup) {
13341 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020013342 if (cnt == -EOPNOTSUPP)
13343 goto patch_map_ops_generic;
13344 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
Daniel Borkmann09772d92018-06-02 23:06:35 +020013345 verbose(env, "bpf verifier is misconfigured\n");
13346 return -EINVAL;
13347 }
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070013348
Daniel Borkmann09772d92018-06-02 23:06:35 +020013349 new_prog = bpf_patch_insn_data(env, i + delta,
13350 insn_buf, cnt);
13351 if (!new_prog)
13352 return -ENOMEM;
13353
13354 delta += cnt - 1;
13355 env->prog = prog = new_prog;
13356 insn = new_prog->insnsi + i + delta;
13357 continue;
Alexei Starovoitov81ed18a2017-03-15 18:26:42 -070013358 }
13359
Daniel Borkmann09772d92018-06-02 23:06:35 +020013360 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
13361 (void *(*)(struct bpf_map *map, void *key))NULL));
13362 BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
13363 (int (*)(struct bpf_map *map, void *key))NULL));
13364 BUILD_BUG_ON(!__same_type(ops->map_update_elem,
13365 (int (*)(struct bpf_map *map, void *key, void *value,
13366 u64 flags))NULL));
Daniel Borkmann84430d42018-10-21 02:09:27 +020013367 BUILD_BUG_ON(!__same_type(ops->map_push_elem,
13368 (int (*)(struct bpf_map *map, void *value,
13369 u64 flags))NULL));
13370 BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
13371 (int (*)(struct bpf_map *map, void *value))NULL));
13372 BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
13373 (int (*)(struct bpf_map *map, void *value))NULL));
Björn Töpele6a47502021-03-08 12:29:06 +010013374 BUILD_BUG_ON(!__same_type(ops->map_redirect,
13375 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL));
Andrey Ignatov0640c772021-10-05 17:18:38 -070013376 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
13377 (int (*)(struct bpf_map *map,
13378 bpf_callback_t callback_fn,
13379 void *callback_ctx,
13380 u64 flags))NULL));
Björn Töpele6a47502021-03-08 12:29:06 +010013381
Daniel Borkmann4a8f87e2020-10-11 01:40:03 +020013382patch_map_ops_generic:
Daniel Borkmann09772d92018-06-02 23:06:35 +020013383 switch (insn->imm) {
13384 case BPF_FUNC_map_lookup_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013385 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
Daniel Borkmann09772d92018-06-02 23:06:35 +020013386 continue;
13387 case BPF_FUNC_map_update_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013388 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
Daniel Borkmann09772d92018-06-02 23:06:35 +020013389 continue;
13390 case BPF_FUNC_map_delete_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013391 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
Daniel Borkmann09772d92018-06-02 23:06:35 +020013392 continue;
Daniel Borkmann84430d42018-10-21 02:09:27 +020013393 case BPF_FUNC_map_push_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013394 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
Daniel Borkmann84430d42018-10-21 02:09:27 +020013395 continue;
13396 case BPF_FUNC_map_pop_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013397 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
Daniel Borkmann84430d42018-10-21 02:09:27 +020013398 continue;
13399 case BPF_FUNC_map_peek_elem:
Kees Cook3d717fa2021-09-28 16:09:45 -070013400 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
Daniel Borkmann84430d42018-10-21 02:09:27 +020013401 continue;
Björn Töpele6a47502021-03-08 12:29:06 +010013402 case BPF_FUNC_redirect_map:
Kees Cook3d717fa2021-09-28 16:09:45 -070013403 insn->imm = BPF_CALL_IMM(ops->map_redirect);
Björn Töpele6a47502021-03-08 12:29:06 +010013404 continue;
Andrey Ignatov0640c772021-10-05 17:18:38 -070013405 case BPF_FUNC_for_each_map_elem:
13406 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013407 continue;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013408 }
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010013409
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013410 goto patch_call_imm;
13411 }
13412
Brendan Jackmane6ac5932021-02-17 10:45:09 +000013413 /* Implement bpf_jiffies64 inline. */
Martin KaFai Lau5576b992020-01-22 15:36:46 -080013414 if (prog->jit_requested && BITS_PER_LONG == 64 &&
13415 insn->imm == BPF_FUNC_jiffies64) {
13416 struct bpf_insn ld_jiffies_addr[2] = {
13417 BPF_LD_IMM64(BPF_REG_0,
13418 (unsigned long)&jiffies),
13419 };
13420
13421 insn_buf[0] = ld_jiffies_addr[0];
13422 insn_buf[1] = ld_jiffies_addr[1];
13423 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
13424 BPF_REG_0, 0);
13425 cnt = 3;
13426
13427 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
13428 cnt);
13429 if (!new_prog)
13430 return -ENOMEM;
13431
13432 delta += cnt - 1;
13433 env->prog = prog = new_prog;
13434 insn = new_prog->insnsi + i + delta;
13435 continue;
13436 }
13437
Jiri Olsaf92c1e12021-12-08 20:32:44 +010013438 /* Implement bpf_get_func_arg inline. */
13439 if (prog_type == BPF_PROG_TYPE_TRACING &&
13440 insn->imm == BPF_FUNC_get_func_arg) {
13441 /* Load nr_args from ctx - 8 */
13442 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13443 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
13444 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
13445 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
13446 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
13447 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13448 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
13449 insn_buf[7] = BPF_JMP_A(1);
13450 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
13451 cnt = 9;
13452
13453 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13454 if (!new_prog)
13455 return -ENOMEM;
13456
13457 delta += cnt - 1;
13458 env->prog = prog = new_prog;
13459 insn = new_prog->insnsi + i + delta;
13460 continue;
13461 }
13462
13463 /* Implement bpf_get_func_ret inline. */
13464 if (prog_type == BPF_PROG_TYPE_TRACING &&
13465 insn->imm == BPF_FUNC_get_func_ret) {
13466 if (eatype == BPF_TRACE_FEXIT ||
13467 eatype == BPF_MODIFY_RETURN) {
13468 /* Load nr_args from ctx - 8 */
13469 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13470 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
13471 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
13472 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
13473 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
13474 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
13475 cnt = 6;
13476 } else {
13477 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
13478 cnt = 1;
13479 }
13480
13481 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
13482 if (!new_prog)
13483 return -ENOMEM;
13484
13485 delta += cnt - 1;
13486 env->prog = prog = new_prog;
13487 insn = new_prog->insnsi + i + delta;
13488 continue;
13489 }
13490
13491 /* Implement get_func_arg_cnt inline. */
13492 if (prog_type == BPF_PROG_TYPE_TRACING &&
13493 insn->imm == BPF_FUNC_get_func_arg_cnt) {
13494 /* Load nr_args from ctx - 8 */
13495 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
13496
13497 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13498 if (!new_prog)
13499 return -ENOMEM;
13500
13501 env->prog = prog = new_prog;
13502 insn = new_prog->insnsi + i + delta;
13503 continue;
13504 }
13505
Jiri Olsa9b99edc2021-07-14 11:43:55 +020013506 /* Implement bpf_get_func_ip inline. */
13507 if (prog_type == BPF_PROG_TYPE_TRACING &&
13508 insn->imm == BPF_FUNC_get_func_ip) {
Jiri Olsaf92c1e12021-12-08 20:32:44 +010013509 /* Load IP address from ctx - 16 */
13510 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
Jiri Olsa9b99edc2021-07-14 11:43:55 +020013511
13512 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
13513 if (!new_prog)
13514 return -ENOMEM;
13515
13516 env->prog = prog = new_prog;
13517 insn = new_prog->insnsi + i + delta;
13518 continue;
13519 }
13520
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070013521patch_call_imm:
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013522 fn = env->ops->get_func_proto(insn->imm, env->prog);
13523 /* all functions that have prototype and verifier allowed
13524 * programs to call them, must be real in-kernel functions
13525 */
13526 if (!fn->func) {
13527 verbose(env,
13528 "kernel subsystem misconfigured func %s#%d\n",
13529 func_id_name(insn->imm), insn->imm);
13530 return -EFAULT;
13531 }
13532 insn->imm = fn->func - __bpf_call_base;
13533 }
13534
Daniel Borkmannd2e4c1e2019-11-22 21:07:59 +010013535 /* Since poke tab is now finalized, publish aux to tracker. */
13536 for (i = 0; i < prog->aux->size_poke_tab; i++) {
13537 map_ptr = prog->aux->poke_tab[i].tail_call.map;
13538 if (!map_ptr->ops->map_poke_track ||
13539 !map_ptr->ops->map_poke_untrack ||
13540 !map_ptr->ops->map_poke_run) {
13541 verbose(env, "bpf verifier is misconfigured\n");
13542 return -EINVAL;
13543 }
13544
13545 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
13546 if (ret < 0) {
13547 verbose(env, "tracking tail call prog failed\n");
13548 return ret;
13549 }
13550 }
13551
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070013552 sort_kfunc_descs_by_imm(env->prog);
13553
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013554 return 0;
13555}
13556
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013557static void free_states(struct bpf_verifier_env *env)
13558{
13559 struct bpf_verifier_state_list *sl, *sln;
13560 int i;
13561
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070013562 sl = env->free_list;
13563 while (sl) {
13564 sln = sl->next;
13565 free_verifier_state(&sl->state, false);
13566 kfree(sl);
13567 sl = sln;
13568 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013569 env->free_list = NULL;
Alexei Starovoitov9f4686c2019-04-01 21:27:41 -070013570
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013571 if (!env->explored_states)
13572 return;
13573
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070013574 for (i = 0; i < state_htab_size(env); i++) {
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013575 sl = env->explored_states[i];
13576
Alexei Starovoitova8f500a2019-05-21 20:17:06 -070013577 while (sl) {
13578 sln = sl->next;
13579 free_verifier_state(&sl->state, false);
13580 kfree(sl);
13581 sl = sln;
13582 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013583 env->explored_states[i] = NULL;
13584 }
13585}
13586
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013587static int do_check_common(struct bpf_verifier_env *env, int subprog)
13588{
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070013589 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013590 struct bpf_verifier_state *state;
13591 struct bpf_reg_state *regs;
13592 int ret, i;
13593
13594 env->prev_linfo = NULL;
13595 env->pass_cnt++;
13596
13597 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
13598 if (!state)
13599 return -ENOMEM;
13600 state->curframe = 0;
13601 state->speculative = false;
13602 state->branches = 1;
13603 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
13604 if (!state->frame[0]) {
13605 kfree(state);
13606 return -ENOMEM;
13607 }
13608 env->cur_state = state;
13609 init_func_state(env, state->frame[0],
13610 BPF_MAIN_FUNC /* callsite */,
13611 0 /* frameno */,
13612 subprog);
13613
13614 regs = state->frame[state->curframe]->regs;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013615 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013616 ret = btf_prepare_func_args(env, subprog, regs);
13617 if (ret)
13618 goto out;
13619 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
13620 if (regs[i].type == PTR_TO_CTX)
13621 mark_reg_known_zero(env, regs, i);
13622 else if (regs[i].type == SCALAR_VALUE)
13623 mark_reg_unknown(env, regs, i);
Dmitrii Banshchikove5069b9c2021-02-13 00:56:41 +040013624 else if (regs[i].type == PTR_TO_MEM_OR_NULL) {
13625 const u32 mem_size = regs[i].mem_size;
13626
13627 mark_reg_known_zero(env, regs, i);
13628 regs[i].mem_size = mem_size;
13629 regs[i].id = ++env->id_gen;
13630 }
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013631 }
13632 } else {
13633 /* 1st arg to a function */
13634 regs[BPF_REG_1].type = PTR_TO_CTX;
13635 mark_reg_known_zero(env, regs, BPF_REG_1);
Martin KaFai Lau34747c42021-03-24 18:51:36 -070013636 ret = btf_check_subprog_arg_match(env, subprog, regs);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013637 if (ret == -EFAULT)
13638 /* unlikely verifier bug. abort.
13639 * ret == 0 and ret < 0 are sadly acceptable for
13640 * main() function due to backward compatibility.
13641 * Like socket filter program may be written as:
13642 * int bpf_prog(struct pt_regs *ctx)
13643 * and never dereference that ctx in the program.
13644 * 'struct pt_regs' is a type mismatch for socket
13645 * filter that should be using 'struct __sk_buff'.
13646 */
13647 goto out;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013648 }
13649
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013650 ret = do_check(env);
13651out:
Alexei Starovoitovf59bbfc2020-01-21 18:41:38 -080013652 /* check for NULL is necessary, since cur_state can be freed inside
13653 * do_check() under memory pressure.
13654 */
13655 if (env->cur_state) {
13656 free_verifier_state(env->cur_state, true);
13657 env->cur_state = NULL;
13658 }
Andrii Nakryiko6f8a57c2020-04-23 12:58:50 -070013659 while (!pop_stack(env, NULL, NULL, false));
13660 if (!ret && pop_log)
13661 bpf_vlog_reset(&env->log, 0);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013662 free_states(env);
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013663 return ret;
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070013664}
13665
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080013666/* Verify all global functions in a BPF program one by one based on their BTF.
13667 * All global functions must pass verification. Otherwise the whole program is rejected.
13668 * Consider:
13669 * int bar(int);
13670 * int foo(int f)
13671 * {
13672 * return bar(f);
13673 * }
13674 * int bar(int b)
13675 * {
13676 * ...
13677 * }
13678 * foo() will be verified first for R1=any_scalar_value. During verification it
13679 * will be assumed that bar() already verified successfully and call to bar()
13680 * from foo() will be checked for type match only. Later bar() will be verified
13681 * independently to check that it's safe for R1=any_scalar_value.
13682 */
13683static int do_check_subprogs(struct bpf_verifier_env *env)
13684{
13685 struct bpf_prog_aux *aux = env->prog->aux;
13686 int i, ret;
13687
13688 if (!aux->func_info)
13689 return 0;
13690
13691 for (i = 1; i < env->subprog_cnt; i++) {
13692 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
13693 continue;
13694 env->insn_idx = env->subprog_info[i].start;
13695 WARN_ON_ONCE(env->insn_idx == 0);
13696 ret = do_check_common(env, i);
13697 if (ret) {
13698 return ret;
13699 } else if (env->log.level & BPF_LOG_LEVEL) {
13700 verbose(env,
13701 "Func#%d is safe for any args that match its prototype\n",
13702 i);
13703 }
13704 }
13705 return 0;
13706}
13707
13708static int do_check_main(struct bpf_verifier_env *env)
13709{
13710 int ret;
13711
13712 env->insn_idx = 0;
13713 ret = do_check_common(env, 0);
13714 if (!ret)
13715 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
13716 return ret;
13717}
13718
13719
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070013720static void print_verification_stats(struct bpf_verifier_env *env)
13721{
13722 int i;
13723
13724 if (env->log.level & BPF_LOG_STATS) {
13725 verbose(env, "verification time %lld usec\n",
13726 div_u64(env->verification_time, 1000));
13727 verbose(env, "stack depth ");
13728 for (i = 0; i < env->subprog_cnt; i++) {
13729 u32 depth = env->subprog_info[i].stack_depth;
13730
13731 verbose(env, "%d", depth);
13732 if (i + 1 < env->subprog_cnt)
13733 verbose(env, "+");
13734 }
13735 verbose(env, "\n");
13736 }
13737 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
13738 "total_states %d peak_states %d mark_read %d\n",
13739 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
13740 env->max_states_per_insn, env->total_states,
13741 env->peak_states, env->longest_mark_read_walk);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070013742}
13743
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080013744static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
13745{
13746 const struct btf_type *t, *func_proto;
13747 const struct bpf_struct_ops *st_ops;
13748 const struct btf_member *member;
13749 struct bpf_prog *prog = env->prog;
13750 u32 btf_id, member_idx;
13751 const char *mname;
13752
Toke Høiland-Jørgensen12aa8a92021-03-26 11:03:13 +010013753 if (!prog->gpl_compatible) {
13754 verbose(env, "struct ops programs must have a GPL compatible license\n");
13755 return -EINVAL;
13756 }
13757
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080013758 btf_id = prog->aux->attach_btf_id;
13759 st_ops = bpf_struct_ops_find(btf_id);
13760 if (!st_ops) {
13761 verbose(env, "attach_btf_id %u is not a supported struct\n",
13762 btf_id);
13763 return -ENOTSUPP;
13764 }
13765
13766 t = st_ops->type;
13767 member_idx = prog->expected_attach_type;
13768 if (member_idx >= btf_type_vlen(t)) {
13769 verbose(env, "attach to invalid member idx %u of struct %s\n",
13770 member_idx, st_ops->name);
13771 return -EINVAL;
13772 }
13773
13774 member = &btf_type_member(t)[member_idx];
13775 mname = btf_name_by_offset(btf_vmlinux, member->name_off);
13776 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
13777 NULL);
13778 if (!func_proto) {
13779 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
13780 mname, member_idx, st_ops->name);
13781 return -EINVAL;
13782 }
13783
13784 if (st_ops->check_member) {
13785 int err = st_ops->check_member(t, member);
13786
13787 if (err) {
13788 verbose(env, "attach to unsupported member %s of struct %s\n",
13789 mname, st_ops->name);
13790 return err;
13791 }
13792 }
13793
13794 prog->aux->attach_func_proto = func_proto;
13795 prog->aux->attach_func_name = mname;
13796 env->ops = st_ops->verifier_ops;
13797
13798 return 0;
13799}
KP Singh6ba43b72020-03-04 20:18:50 +010013800#define SECURITY_PREFIX "security_"
13801
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013802static int check_attach_modify_return(unsigned long addr, const char *func_name)
KP Singh6ba43b72020-03-04 20:18:50 +010013803{
KP Singh69191752020-03-05 21:49:55 +010013804 if (within_error_injection_list(addr) ||
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013805 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
KP Singh6ba43b72020-03-04 20:18:50 +010013806 return 0;
KP Singh6ba43b72020-03-04 20:18:50 +010013807
KP Singh6ba43b72020-03-04 20:18:50 +010013808 return -EINVAL;
13809}
Martin KaFai Lau27ae79972020-01-08 16:35:03 -080013810
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013811/* list of non-sleepable functions that are otherwise on
13812 * ALLOW_ERROR_INJECTION list
13813 */
13814BTF_SET_START(btf_non_sleepable_error_inject)
13815/* Three functions below can be called from sleepable and non-sleepable context.
13816 * Assume non-sleepable from bpf safety point of view.
13817 */
Matthew Wilcox (Oracle)9dd3d062020-12-08 08:56:28 -050013818BTF_ID(func, __filemap_add_folio)
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070013819BTF_ID(func, should_fail_alloc_page)
13820BTF_ID(func, should_failslab)
13821BTF_SET_END(btf_non_sleepable_error_inject)
13822
13823static int check_non_sleepable_error_inject(u32 btf_id)
13824{
13825 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
13826}
13827
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013828int bpf_check_attach_target(struct bpf_verifier_log *log,
13829 const struct bpf_prog *prog,
13830 const struct bpf_prog *tgt_prog,
13831 u32 btf_id,
13832 struct bpf_attach_target_info *tgt_info)
Martin KaFai Lau38207292019-10-24 17:18:11 -070013833{
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013834 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013835 const char prefix[] = "btf_trace_";
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013836 int ret = 0, subprog = -1, i;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013837 const struct btf_type *t;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013838 bool conservative = true;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013839 const char *tname;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013840 struct btf *btf;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013841 long addr = 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070013842
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013843 if (!btf_id) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013844 bpf_log(log, "Tracing programs must provide btf_id\n");
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013845 return -EINVAL;
13846 }
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080013847 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013848 if (!btf) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013849 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013850 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
13851 return -EINVAL;
13852 }
13853 t = btf_type_by_id(btf, btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013854 if (!t) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013855 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013856 return -EINVAL;
13857 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013858 tname = btf_name_by_offset(btf, t->name_off);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013859 if (!tname) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013860 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013861 return -EINVAL;
13862 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013863 if (tgt_prog) {
13864 struct bpf_prog_aux *aux = tgt_prog->aux;
13865
13866 for (i = 0; i < aux->func_info_cnt; i++)
13867 if (aux->func_info[i].type_id == btf_id) {
13868 subprog = i;
13869 break;
13870 }
13871 if (subprog == -1) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013872 bpf_log(log, "Subprog %s doesn't exist\n", tname);
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013873 return -EINVAL;
13874 }
13875 conservative = aux->func_info_aux[subprog].unreliable;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013876 if (prog_extension) {
13877 if (conservative) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013878 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013879 "Cannot replace static functions\n");
13880 return -EINVAL;
13881 }
13882 if (!prog->jit_requested) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013883 bpf_log(log,
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013884 "Extension programs should be JITed\n");
13885 return -EINVAL;
13886 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013887 }
13888 if (!tgt_prog->jited) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013889 bpf_log(log, "Can attach to only JITed progs\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013890 return -EINVAL;
13891 }
13892 if (tgt_prog->type == prog->type) {
13893 /* Cannot fentry/fexit another fentry/fexit program.
13894 * Cannot attach program extension to another extension.
13895 * It's ok to attach fentry/fexit to extension program.
13896 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013897 bpf_log(log, "Cannot recursively attach\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013898 return -EINVAL;
13899 }
13900 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
13901 prog_extension &&
13902 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
13903 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
13904 /* Program extensions can extend all program types
13905 * except fentry/fexit. The reason is the following.
13906 * The fentry/fexit programs are used for performance
13907 * analysis, stats and can be attached to any program
13908 * type except themselves. When extension program is
13909 * replacing XDP function it is necessary to allow
13910 * performance analysis of all functions. Both original
13911 * XDP program and its program extension. Hence
13912 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
13913 * allowed. If extending of fentry/fexit was allowed it
13914 * would be possible to create long call chain
13915 * fentry->extension->fentry->extension beyond
13916 * reasonable stack size. Hence extending fentry is not
13917 * allowed.
13918 */
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013919 bpf_log(log, "Cannot extend fentry/fexit\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013920 return -EINVAL;
13921 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013922 } else {
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013923 if (prog_extension) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013924 bpf_log(log, "Cannot replace kernel functions\n");
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013925 return -EINVAL;
13926 }
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013927 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013928
13929 switch (prog->expected_attach_type) {
13930 case BPF_TRACE_RAW_TP:
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013931 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013932 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013933 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
13934 return -EINVAL;
13935 }
Martin KaFai Lau38207292019-10-24 17:18:11 -070013936 if (!btf_type_is_typedef(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013937 bpf_log(log, "attach_btf_id %u is not a typedef\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013938 btf_id);
13939 return -EINVAL;
13940 }
Alexei Starovoitovf1b95092019-10-30 15:32:11 -070013941 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013942 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
Martin KaFai Lau38207292019-10-24 17:18:11 -070013943 btf_id, tname);
13944 return -EINVAL;
13945 }
13946 tname += sizeof(prefix) - 1;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013947 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013948 if (!btf_type_is_ptr(t))
13949 /* should never happen in valid vmlinux build */
13950 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013951 t = btf_type_by_id(btf, t->type);
Martin KaFai Lau38207292019-10-24 17:18:11 -070013952 if (!btf_type_is_func_proto(t))
13953 /* should never happen in valid vmlinux build */
13954 return -EINVAL;
13955
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013956 break;
Yonghong Song15d83c42020-05-09 10:59:00 -070013957 case BPF_TRACE_ITER:
13958 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013959 bpf_log(log, "attach_btf_id %u is not a function\n",
Yonghong Song15d83c42020-05-09 10:59:00 -070013960 btf_id);
13961 return -EINVAL;
13962 }
13963 t = btf_type_by_id(btf, t->type);
13964 if (!btf_type_is_func_proto(t))
13965 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013966 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
13967 if (ret)
13968 return ret;
13969 break;
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013970 default:
13971 if (!prog_extension)
13972 return -EINVAL;
Gustavo A. R. Silvadf561f662020-08-23 17:36:59 -050013973 fallthrough;
KP Singhae240822020-03-04 20:18:49 +010013974 case BPF_MODIFY_RETURN:
KP Singh9e4e01d2020-03-29 01:43:52 +010013975 case BPF_LSM_MAC:
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013976 case BPF_TRACE_FENTRY:
13977 case BPF_TRACE_FEXIT:
13978 if (!btf_type_is_func(t)) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013979 bpf_log(log, "attach_btf_id %u is not a function\n",
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013980 btf_id);
13981 return -EINVAL;
13982 }
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013983 if (prog_extension &&
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020013984 btf_check_type_match(log, prog, btf, t))
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080013985 return -EINVAL;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013986 t = btf_type_by_id(btf, t->type);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013987 if (!btf_type_is_func_proto(t))
13988 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013989
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020013990 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
13991 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
13992 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
13993 return -EINVAL;
13994
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013995 if (tgt_prog && conservative)
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080013996 t = NULL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020013997
13998 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080013999 if (ret < 0)
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014000 return ret;
14001
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080014002 if (tgt_prog) {
Yonghong Songe9eeec52019-12-04 17:06:06 -080014003 if (subprog == 0)
14004 addr = (long) tgt_prog->bpf_func;
14005 else
14006 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080014007 } else {
14008 addr = kallsyms_lookup_name(tname);
14009 if (!addr) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020014010 bpf_log(log,
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080014011 "The address of function %s cannot be found\n",
14012 tname);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014013 return -ENOENT;
Alexei Starovoitov5b92a282019-11-14 10:57:17 -080014014 }
Alexei Starovoitovfec56f52019-11-14 10:57:04 -080014015 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070014016
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070014017 if (prog->aux->sleepable) {
14018 ret = -EINVAL;
14019 switch (prog->type) {
14020 case BPF_PROG_TYPE_TRACING:
14021 /* fentry/fexit/fmod_ret progs can be sleepable only if they are
14022 * attached to ALLOW_ERROR_INJECTION and are not in denylist.
14023 */
14024 if (!check_non_sleepable_error_inject(btf_id) &&
14025 within_error_injection_list(addr))
14026 ret = 0;
14027 break;
14028 case BPF_PROG_TYPE_LSM:
14029 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
14030 * Only some of them are sleepable.
14031 */
KP Singh423f1612020-11-13 00:59:29 +000014032 if (bpf_lsm_is_sleepable_hook(btf_id))
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070014033 ret = 0;
14034 break;
14035 default:
14036 break;
14037 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014038 if (ret) {
14039 bpf_log(log, "%s is not sleepable\n", tname);
14040 return ret;
14041 }
Alexei Starovoitov1e6c62a2020-08-27 15:01:11 -070014042 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020014043 if (tgt_prog) {
Toke Høiland-Jørgensenefc68152020-09-25 23:25:01 +020014044 bpf_log(log, "can't modify return codes of BPF programs\n");
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014045 return -EINVAL;
Toke Høiland-Jørgensen1af92702020-09-25 23:25:00 +020014046 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014047 ret = check_attach_modify_return(addr, tname);
14048 if (ret) {
14049 bpf_log(log, "%s() is not modifiable\n", tname);
14050 return ret;
14051 }
Alexei Starovoitov18644ce2020-05-28 21:38:36 -070014052 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014053
14054 break;
Martin KaFai Lau38207292019-10-24 17:18:11 -070014055 }
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014056 tgt_info->tgt_addr = addr;
14057 tgt_info->tgt_name = tname;
14058 tgt_info->tgt_type = t;
14059 return 0;
14060}
14061
Jiri Olsa35e38152021-04-29 13:47:12 +020014062BTF_SET_START(btf_id_deny)
14063BTF_ID_UNUSED
14064#ifdef CONFIG_SMP
14065BTF_ID(func, migrate_disable)
14066BTF_ID(func, migrate_enable)
14067#endif
14068#if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
14069BTF_ID(func, rcu_read_unlock_strict)
14070#endif
14071BTF_SET_END(btf_id_deny)
14072
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014073static int check_attach_btf_id(struct bpf_verifier_env *env)
14074{
14075 struct bpf_prog *prog = env->prog;
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020014076 struct bpf_prog *tgt_prog = prog->aux->dst_prog;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014077 struct bpf_attach_target_info tgt_info = {};
14078 u32 btf_id = prog->aux->attach_btf_id;
14079 struct bpf_trampoline *tr;
14080 int ret;
14081 u64 key;
14082
Alexei Starovoitov79a7f8b2021-05-13 17:36:03 -070014083 if (prog->type == BPF_PROG_TYPE_SYSCALL) {
14084 if (prog->aux->sleepable)
14085 /* attach_btf_id checked to be zero already */
14086 return 0;
14087 verbose(env, "Syscall programs can only be sleepable\n");
14088 return -EINVAL;
14089 }
14090
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014091 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING &&
14092 prog->type != BPF_PROG_TYPE_LSM) {
14093 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n");
14094 return -EINVAL;
14095 }
14096
14097 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
14098 return check_struct_ops_btf_id(env);
14099
14100 if (prog->type != BPF_PROG_TYPE_TRACING &&
14101 prog->type != BPF_PROG_TYPE_LSM &&
14102 prog->type != BPF_PROG_TYPE_EXT)
14103 return 0;
14104
14105 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
14106 if (ret)
14107 return ret;
14108
14109 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020014110 /* to make freplace equivalent to their targets, they need to
14111 * inherit env->ops and expected_attach_type for the rest of the
14112 * verification
14113 */
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014114 env->ops = bpf_verifier_ops[tgt_prog->type];
14115 prog->expected_attach_type = tgt_prog->expected_attach_type;
14116 }
14117
14118 /* store info about the attachment target that will be used later */
14119 prog->aux->attach_func_proto = tgt_info.tgt_type;
14120 prog->aux->attach_func_name = tgt_info.tgt_name;
14121
Toke Høiland-Jørgensen4a1e7c02020-09-29 14:45:51 +020014122 if (tgt_prog) {
14123 prog->aux->saved_dst_prog_type = tgt_prog->type;
14124 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
14125 }
14126
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014127 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
14128 prog->aux->attach_btf_trace = true;
14129 return 0;
14130 } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
14131 if (!bpf_iter_prog_supported(prog))
14132 return -EINVAL;
14133 return 0;
14134 }
14135
14136 if (prog->type == BPF_PROG_TYPE_LSM) {
14137 ret = bpf_lsm_verify_prog(&env->log, prog);
14138 if (ret < 0)
14139 return ret;
Jiri Olsa35e38152021-04-29 13:47:12 +020014140 } else if (prog->type == BPF_PROG_TYPE_TRACING &&
14141 btf_id_set_contains(&btf_id_deny, btf_id)) {
14142 return -EINVAL;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014143 }
14144
Andrii Nakryiko22dc4a02020-12-03 12:46:29 -080014145 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014146 tr = bpf_trampoline_get(key, &tgt_info);
14147 if (!tr)
14148 return -ENOMEM;
14149
Toke Høiland-Jørgensen3aac1ea2020-09-29 14:45:50 +020014150 prog->aux->dst_trampoline = tr;
Toke Høiland-Jørgensenf7b12b62020-09-25 23:25:02 +020014151 return 0;
Martin KaFai Lau38207292019-10-24 17:18:11 -070014152}
14153
Alan Maguire76654e62020-09-28 12:31:03 +010014154struct btf *bpf_get_btf_vmlinux(void)
14155{
14156 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
14157 mutex_lock(&bpf_verifier_lock);
14158 if (!btf_vmlinux)
14159 btf_vmlinux = btf_parse_vmlinux();
14160 mutex_unlock(&bpf_verifier_lock);
14161 }
14162 return btf_vmlinux;
14163}
14164
Alexei Starovoitovaf2ac3e2021-05-13 17:36:05 -070014165int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr)
Alexei Starovoitov51580e72014-09-26 00:17:02 -070014166{
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070014167 u64 start_time = ktime_get_ns();
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010014168 struct bpf_verifier_env *env;
Martin KaFai Laub9193c12018-03-24 11:44:22 -070014169 struct bpf_verifier_log *log;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080014170 int i, len, ret = -EINVAL;
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080014171 bool is_priv;
Alexei Starovoitov51580e72014-09-26 00:17:02 -070014172
Arnd Bergmanneba0c922017-11-02 12:05:52 +010014173 /* no program is valid */
14174 if (ARRAY_SIZE(bpf_verifier_ops) == 0)
14175 return -EINVAL;
14176
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010014177 /* 'struct bpf_verifier_env' can be global, but since it's not small,
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014178 * allocate/free it every time bpf_check() is called
14179 */
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010014180 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014181 if (!env)
14182 return -ENOMEM;
Jakub Kicinski61bd5212017-10-09 10:30:11 -070014183 log = &env->log;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014184
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080014185 len = (*prog)->len;
Kees Cookfad953c2018-06-12 14:27:37 -070014186 env->insn_aux_data =
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080014187 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
Jakub Kicinski3df126f2016-09-21 11:43:56 +010014188 ret = -ENOMEM;
14189 if (!env->insn_aux_data)
14190 goto err_free_env;
Jakub Kicinski9e4c24e2019-01-22 22:45:23 -080014191 for (i = 0; i < len; i++)
14192 env->insn_aux_data[i].orig_idx = i;
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014193 env->prog = *prog;
Jakub Kicinski00176a32017-10-16 16:40:54 -070014194 env->ops = bpf_verifier_ops[env->prog->type];
Alexei Starovoitov387544b2021-05-13 17:36:10 -070014195 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070014196 is_priv = bpf_capable();
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014197
Alan Maguire76654e62020-09-28 12:31:03 +010014198 bpf_get_btf_vmlinux();
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070014199
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014200 /* grab the mutex to protect few globals used by verifier */
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070014201 if (!is_priv)
14202 mutex_lock(&bpf_verifier_lock);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014203
14204 if (attr->log_level || attr->log_buf || attr->log_size) {
14205 /* user requested verbose verifier output
14206 * and supplied buffer to store the verification trace
14207 */
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070014208 log->level = attr->log_level;
14209 log->ubuf = (char __user *) (unsigned long) attr->log_buf;
14210 log->len_total = attr->log_size;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014211
Jakub Kicinskie7bf8242017-10-09 10:30:10 -070014212 /* log attributes have to be sane */
Hou Tao866de402021-12-03 13:30:01 +080014213 if (!bpf_verifier_log_attr_valid(log)) {
14214 ret = -EINVAL;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010014215 goto err_unlock;
Hou Tao866de402021-12-03 13:30:01 +080014216 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014217 }
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020014218
Christy Lee0f55f9e2021-12-16 13:33:56 -080014219 mark_verifier_state_clean(env);
14220
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070014221 if (IS_ERR(btf_vmlinux)) {
14222 /* Either gcc or pahole or kernel are broken. */
14223 verbose(env, "in-kernel BTF is malformed\n");
14224 ret = PTR_ERR(btf_vmlinux);
Martin KaFai Lau38207292019-10-24 17:18:11 -070014225 goto skip_full_check;
Alexei Starovoitov8580ac92019-10-15 20:24:57 -070014226 }
14227
Daniel Borkmann1ad2f582017-05-25 01:05:05 +020014228 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
14229 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
David S. Millere07b98d2017-05-10 11:38:07 -070014230 env->strict_alignment = true;
David Millere9ee9ef2018-11-30 21:08:14 -080014231 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
14232 env->strict_alignment = false;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014233
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070014234 env->allow_ptr_leaks = bpf_allow_ptr_leaks();
Andrei Matei01f810a2021-02-06 20:10:24 -050014235 env->allow_uninit_stack = bpf_allow_uninit_stack();
Andrey Ignatov41c48f32020-06-19 14:11:43 -070014236 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access();
Alexei Starovoitov2c78ee82020-05-13 16:03:54 -070014237 env->bypass_spec_v1 = bpf_bypass_spec_v1();
14238 env->bypass_spec_v4 = bpf_bypass_spec_v4();
14239 env->bpf_capable = bpf_capable();
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080014240
Alexei Starovoitov10d274e2019-08-22 22:52:12 -070014241 if (is_priv)
14242 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
14243
Alexei Starovoitovdc2a4eb2019-05-21 20:17:07 -070014244 env->explored_states = kvcalloc(state_htab_size(env),
Jakub Kicinski58e2af8b2016-09-21 11:43:57 +010014245 sizeof(struct bpf_verifier_state_list *),
Alexei Starovoitovf1bca822014-09-29 18:50:01 -070014246 GFP_USER);
14247 ret = -ENOMEM;
14248 if (!env->explored_states)
14249 goto skip_full_check;
14250
Martin KaFai Laue6ac2452021-03-24 18:51:42 -070014251 ret = add_subprog_and_kfunc(env);
14252 if (ret < 0)
14253 goto skip_full_check;
14254
Martin KaFai Laud9762e82018-12-13 10:41:48 -080014255 ret = check_subprogs(env);
Alexei Starovoitov475fb782014-09-26 00:17:05 -070014256 if (ret < 0)
14257 goto skip_full_check;
14258
Martin KaFai Lauc454a462018-12-07 16:42:25 -080014259 ret = check_btf_info(env, attr, uattr);
Yonghong Song838e9692018-11-19 15:29:11 -080014260 if (ret < 0)
14261 goto skip_full_check;
14262
Alexei Starovoitovbe8704f2020-01-20 16:53:46 -080014263 ret = check_attach_btf_id(env);
14264 if (ret)
14265 goto skip_full_check;
14266
Hao Luo4976b712020-09-29 16:50:44 -070014267 ret = resolve_pseudo_ldimm64(env);
14268 if (ret < 0)
14269 goto skip_full_check;
14270
Yinjun Zhangceb11672021-05-20 10:58:34 +020014271 if (bpf_prog_is_dev_bound(env->prog->aux)) {
14272 ret = bpf_prog_offload_verifier_prep(env->prog);
14273 if (ret)
14274 goto skip_full_check;
14275 }
14276
Martin KaFai Laud9762e82018-12-13 10:41:48 -080014277 ret = check_cfg(env);
14278 if (ret < 0)
14279 goto skip_full_check;
14280
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080014281 ret = do_check_subprogs(env);
14282 ret = ret ?: do_check_main(env);
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014283
Quentin Monnetc941ce92018-10-07 12:56:47 +010014284 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux))
14285 ret = bpf_prog_offload_finalize(env);
14286
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014287skip_full_check:
Alexei Starovoitov51c39bb2020-01-09 22:41:20 -080014288 kvfree(env->explored_states);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014289
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014290 if (ret == 0)
Alexei Starovoitov70a87ff2017-12-25 13:15:40 -080014291 ret = check_max_stack_depth(env);
14292
Jakub Kicinski9b38c402018-12-19 22:13:06 -080014293 /* instruction rewrites happen after this point */
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080014294 if (is_priv) {
14295 if (ret == 0)
14296 opt_hard_wire_dead_code_branches(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080014297 if (ret == 0)
14298 ret = opt_remove_dead_code(env);
Jakub Kicinskia1b14ab2019-01-22 22:45:21 -080014299 if (ret == 0)
14300 ret = opt_remove_nops(env);
Jakub Kicinski52875a02019-01-22 22:45:20 -080014301 } else {
14302 if (ret == 0)
14303 sanitize_dead_code(env);
Jakub Kicinskie2ae4ca2019-01-22 22:45:19 -080014304 }
14305
Jakub Kicinski9b38c402018-12-19 22:13:06 -080014306 if (ret == 0)
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014307 /* program is valid, convert *(u32*)(ctx + off) accesses */
14308 ret = convert_ctx_accesses(env);
14309
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070014310 if (ret == 0)
Brendan Jackmane6ac5932021-02-17 10:45:09 +000014311 ret = do_misc_fixups(env);
Alexei Starovoitove245c5c62017-03-15 18:26:39 -070014312
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010014313 /* do 32-bit optimization after insn patching has done so those patched
14314 * insns could be handled correctly.
14315 */
Jiong Wangd6c23082019-05-24 23:25:18 +010014316 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) {
14317 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
14318 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
14319 : false;
Jiong Wanga4b1d3c2019-05-24 23:25:15 +010014320 }
14321
Alexei Starovoitov1ea47e02017-12-14 17:55:13 -080014322 if (ret == 0)
14323 ret = fixup_call_args(env);
14324
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070014325 env->verification_time = ktime_get_ns() - start_time;
14326 print_verification_stats(env);
Dave Marchevskyaba64c72021-10-20 00:48:17 -070014327 env->prog->aux->verified_insns = env->insn_processed;
Alexei Starovoitov06ee7112019-04-01 21:27:40 -070014328
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070014329 if (log->level && bpf_verifier_log_full(log))
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014330 ret = -ENOSPC;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070014331 if (log->level && !log->ubuf) {
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014332 ret = -EFAULT;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070014333 goto err_release_maps;
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014334 }
14335
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080014336 if (ret)
14337 goto err_release_maps;
14338
14339 if (env->used_map_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014340 /* if program passed verifier, update used_maps in bpf_prog_info */
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014341 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
14342 sizeof(env->used_maps[0]),
14343 GFP_KERNEL);
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014344
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014345 if (!env->prog->aux->used_maps) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014346 ret = -ENOMEM;
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070014347 goto err_release_maps;
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014348 }
14349
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014350 memcpy(env->prog->aux->used_maps, env->used_maps,
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014351 sizeof(env->used_maps[0]) * env->used_map_cnt);
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014352 env->prog->aux->used_map_cnt = env->used_map_cnt;
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080014353 }
14354 if (env->used_btf_cnt) {
14355 /* if program passed verifier, update used_btfs in bpf_prog_aux */
14356 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
14357 sizeof(env->used_btfs[0]),
14358 GFP_KERNEL);
14359 if (!env->prog->aux->used_btfs) {
14360 ret = -ENOMEM;
14361 goto err_release_maps;
14362 }
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014363
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080014364 memcpy(env->prog->aux->used_btfs, env->used_btfs,
14365 sizeof(env->used_btfs[0]) * env->used_btf_cnt);
14366 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
14367 }
14368 if (env->used_map_cnt || env->used_btf_cnt) {
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014369 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
14370 * bpf_ld_imm64 instructions
14371 */
14372 convert_pseudo_ld_imm64(env);
14373 }
Alexei Starovoitovcbd35702014-09-26 00:17:03 -070014374
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080014375 adjust_btf_func(env);
Yonghong Songba64e7d2018-11-24 23:20:44 -080014376
Jakub Kicinskia2a7d572017-10-09 10:30:15 -070014377err_release_maps:
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014378 if (!env->prog->aux->used_maps)
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014379 /* if we didn't copy map pointers into bpf_prog_info, release
Jakub Kicinskiab7f5bf2018-05-03 18:37:17 -070014380 * them now. Otherwise free_used_maps() will release them.
Alexei Starovoitov0246e642014-09-26 00:17:04 -070014381 */
14382 release_maps(env);
Andrii Nakryiko541c3ba2021-01-11 23:55:18 -080014383 if (!env->prog->aux->used_btfs)
14384 release_btfs(env);
Toke Høiland-Jørgensen03f87c02020-04-24 15:34:27 +020014385
14386 /* extension progs temporarily inherit the attach_type of their targets
14387 for verification purposes, so set it back to zero before returning
14388 */
14389 if (env->prog->type == BPF_PROG_TYPE_EXT)
14390 env->prog->expected_attach_type = 0;
14391
Alexei Starovoitov9bac3d62015-03-13 11:57:42 -070014392 *prog = env->prog;
Jakub Kicinski3df126f2016-09-21 11:43:56 +010014393err_unlock:
Alexei Starovoitov45a73c12019-04-19 07:44:55 -070014394 if (!is_priv)
14395 mutex_unlock(&bpf_verifier_lock);
Jakub Kicinski3df126f2016-09-21 11:43:56 +010014396 vfree(env->insn_aux_data);
14397err_free_env:
14398 kfree(env);
Alexei Starovoitov51580e72014-09-26 00:17:02 -070014399 return ret;
14400}